Esempio n. 1
0
  /**
   * Rates a board by the position advantage
   *
   * @param b
   * @param color
   * @return
   */
  private int h2(Board b, char color) {
    int kingVal = 2;
    int result = 0;
    int[][] posVals = {
      {2, 1, 1, 1, 1, 1, 1, 2},
      {2, 1, 1, 1, 1, 1, 1, 2},
      {2, 1, 1, 1, 1, 1, 1, 2},
      {2, 1, 1, 1, 1, 1, 1, 2},
      {2, 1, 1, 1, 1, 1, 1, 2},
      {2, 1, 1, 1, 1, 1, 1, 2},
      {2, 1, 1, 1, 1, 1, 1, 2},
      {2, 1, 1, 1, 1, 1, 1, 2}
    };

    for (int i = 0; i < 8; i++) {
      for (int j = 0; j < 8; j++) {
        Piece p = b.getPiece(i, j);
        int pVal = 0;
        if (p.getColor() == color) pVal = posVals[i][j];
        else if (p.getColor() != '-') pVal = -posVals[i][j];
        if (p.isKing()) pVal = pVal * kingVal;
        result += pVal;
      }
    }
    return result;
  }
  public void undoLastMove() {
    // Check that we have a move to undo
    if (moves.isEmpty()) {
      throw new InternalError("No move available to undo");
    }

    final Move lastMove = getLastMove();
    final Point from = lastMove.getFrom();
    final Point to = lastMove.getTo();
    final Piece piece = lastMove.getPiece();

    squares[from.getX()][from.getY()].setPiece(piece);

    if (lastMove.isLeftCastling()) {
      squares[to.getX()][to.getY()].setPiece(null);
      if (piece.getColor() == Color.W) {
        setPiece(Piece.WHITE_ROOK, King.W_LEFT_ROOK);
        setPiece(null, to.incrementX(1));
      } else {
        setPiece(Piece.BLACK_ROOK, King.B_LEFT_ROOK);
        setPiece(null, to.incrementX(1));
      }
    } else if (lastMove.isRightCastling()) {
      squares[to.getX()][to.getY()].setPiece(null);
      if (piece.getColor() == Color.W) {
        setPiece(Piece.WHITE_ROOK, King.W_RIGHT_ROOK);
        setPiece(null, to.decrementX(1));
      } else {
        setPiece(Piece.BLACK_ROOK, King.B_RIGHT_ROOK);
        setPiece(null, to.decrementX(1));
      }
    } else {
      final Piece captured = lastMove.getCaptured();

      // Undoing an en passant move?
      if (lastMove.isEnPassant()) {
        if (captured.getColor() == Color.B) {
          squares[to.getX()][to.getY() - 1].setPiece(captured);
        } else {
          squares[to.getX()][to.getY() + 1].setPiece(captured);
        }
        squares[to.getX()][to.getY()].setPiece(null);
      } else {
        squares[to.getX()][to.getY()].setPiece(captured);
      }

      // Keep track of the kings
      if (piece == WHITE_KING) {
        whiteKing = squares[from.getX()][from.getY()];
      } else if (piece == BLACK_KING) {
        blackKing = squares[from.getX()][from.getY()];
      }
    }

    // Remove move from history
    moves.remove(moves.size() - 1);
  }
Esempio n. 3
0
 public boolean validTake(Point start, Point end) {
   Piece piece = b.get(start);
   Piece ending = b.get(end);
   if (ending != null
       && piece.validCapture(start, end)
       && checkIfPathIsClear(start, end)
       && piece.getColor() != ending.getColor()) {
     return true;
   }
   return false;
 }
  public void doMove(Move move) {
    final Point from = move.getFrom();
    final Point to = move.getTo();
    final Piece piece = move.getPiece();

    // Carry out the move on the board
    squares[from.getX()][from.getY()].setPiece(null);
    move.setCaptured(squares[to.getX()][to.getY()].getPiece());
    squares[to.getX()][to.getY()].setPiece(piece);

    // Keep track of the kings
    if (piece == WHITE_KING) {
      whiteKing = squares[to.getX()][to.getY()];
    } else if (piece == BLACK_KING) {
      blackKing = squares[to.getX()][to.getY()];
    }

    // Check for castling first
    if (move.isLeftCastling()) {
      if (piece.getColor() == Color.W) {
        setPiece(null, King.W_LEFT_ROOK);
        setPiece(Piece.WHITE_ROOK, to.incrementX(1));
      } else {
        setPiece(null, King.B_LEFT_ROOK);
        setPiece(Piece.BLACK_ROOK, to.incrementX(1));
      }
    } else if (move.isRightCastling()) {
      if (piece.getColor() == Color.W) {
        setPiece(null, King.W_RIGHT_ROOK);
        setPiece(Piece.WHITE_ROOK, to.decrementX(1));
      } else {
        setPiece(null, King.B_RIGHT_ROOK);
        setPiece(Piece.BLACK_ROOK, to.decrementX(1));
      }
    } else {
      // Check for pawn promotions
      if (piece.isPromoted(to)) {
        setPiece(piece.getColor().getQueen(), to);
        move.setPromoted(true);
      }

      // En passant?
      final Move lastMove = getLastMove();
      if (move.isEnPassantAllowed(lastMove)) {
        final Point lastTo = lastMove.getTo();
        move.setEnPassant(true);
        move.setCaptured(squares[lastTo.getX()][lastTo.getY()].getPiece());
        squares[lastTo.getX()][lastTo.getY()].setPiece(null);
      }
    }

    // Record last move
    moves.add(move);
  }
Esempio n. 5
0
 public boolean takePiece(Point startLocation, Point endLocation) {
   Piece piece = b.get(startLocation);
   Piece ending = b.get(endLocation);
   if (piece.validCapture(startLocation, endLocation)
       && checkIfPathIsClear(startLocation, endLocation)
       && piece.getColor() != ending.getColor()) {
     b.remove(endLocation);
     b.put(endLocation, b.get(startLocation));
     b.remove(startLocation);
     piece.setHasNotMoved(false);
     return true;
   }
   return false;
 }
Esempio n. 6
0
 /**
  * Rates a board by the number of kings.
  *
  * @param b
  * @return
  */
 private int h1(Board b, char color) {
   int result = 0;
   for (int i = 0; i < 8; i++) {
     for (int j = 0; j < 8; j++) {
       Piece p = b.getPiece(i, j);
       if (p.getColor() == color) {
         result++;
         if (p.isKing()) result++;
       } else if (p.getColor() != '-') {
         result--;
         if (p.isKing()) result--;
       }
     }
   }
   return result;
 }
  /**
   * Do the Jump, removing the piece from x1, y1 and setting the piece in x2, y2. Remove the piece
   * from captureX, captureY as well. If the piece is now on their "King's Row", then promote the
   * piece should be promoted to a King
   */
  public void execute(final Jump jump) {
    // CHECK IF ALL OF THEM ON BOARD
    if (isOnBoard(jump.getX1(), jump.getX2())
        && isOnBoard(jump.getY1(), jump.getY2())
        && isOnBoard(jump.getCaptureX(), jump.getCaptureY())) {
      // check if landing square is empty
      if (isEmptySquare(jump.getY1(), jump.getY2())) {
        Piece piece = getPiece(jump.getY1(), jump.getX1());
        // check if capture piece is enemy color
        if (getPiece(jump.getCaptureY(), jump.getCaptureX()).isEnemyColor(piece.getColor())) {

          if (Piece.WHITE_MAN.equals(piece)) {
            if (jump.getY2() == 7) {
              piece = Piece.WHITE_KING;
            }
          } else if (Piece.RED_MAN.equals(piece)) {
            if (jump.getY2() == 0) {
              piece = Piece.RED_KING;
            }
          }

          setPiece(jump.getY2(), jump.getX2(), piece);
          removePiece(jump.getCaptureY(), jump.getCaptureX());
          removePiece(jump.getY1(), jump.getX1());
        }
      }
    }
  }
Esempio n. 8
0
  /** Determines whether the king can be captured by the player with the move. */
  public boolean isKingLeftInCheck() {
    MoveLogic attacksKingLogic = new MoveAttacksKingLogic();

    HashSet<Move> attackingMoves;
    PieceColor colorToMove = this.getColorToMove();
    int kx = -1; // If search succeeds, these should be set to "real" values
    int ky = -1;

    squareloop:
    for (int j = 0; j < Chess.BOARD_SIZE; j++) {
      for (int i = 0; i < Chess.BOARD_SIZE; i++) {
        Piece pieceHere = this.getPieceAt(new Square(i, j));
        if (pieceHere.getType() == PieceType.KING && pieceHere.getColor() == colorToMove.invert()) {
          kx = i;
          ky = j;
          break squareloop;
        }
      }
    }

    assert ((kx != -1) || (ky != -1))
        : "Unexpected search failure, inconsistent state.  King not found.";
    Square kingSquare = new Square(kx, ky);

    attackingMoves = possibleMovesWhichEndAt(kingSquare);

    for (Move move : attackingMoves) {
      if (attacksKingLogic.isLegal(this, move)) {
        return true;
      }
    }
    return false;
  }
Esempio n. 9
0
 public ArrayList<Piece> getPiecesOfType(PieceTypes.Color color) {
   ArrayList<Piece> ret = new ArrayList<Piece>();
   for (Piece p : pieces) {
     if (p.getColor() == color) {
       ret.add(p);
     }
   }
   return ret;
 }
Esempio n. 10
0
 /**
  * Checks whether there is a piece at the specified location that is not marked as 'captured' and
  * has the specified color.
  *
  * @param color one of Piece.COLOR_..
  * @param row one of Piece.ROW_..
  * @param column on of Piece.COLUMN_..
  * @return true, if the location contains a not-captured piece of the specified color
  */
 private boolean isNonCapturedPieceAtLocation(int color, int row, int column) {
   for (Piece piece : this.pieces) {
     if (piece.getRow() == row
         && piece.getColumn() == column
         && piece.isCaptured() == false
         && piece.getColor() == color) {
       return true;
     }
   }
   return false;
 }
Esempio n. 11
0
  /**
   * Determines whether the piece at the given square can be moved, i.e. that there is actually a
   * piece there and that its color matches the color to move.
   */
  public boolean isMovablePieceAtSquare(Square startSquare) {
    final Piece pieceToMove = getPieceAt(startSquare);

    // There should be a piece on the starting square
    if (pieceToMove.equals(Piece.NONE)) {
      return false;
    }
    // The color of the piece being moved must be the color
    // of the player to move
    return (pieceToMove.getColor() == getColorToMove());
  }
Esempio n. 12
0
 private int h4(Board b, char color) {
   int result = 0;
   for (int i = 0; i < 8; i++) {
     for (int j = 0; j < 8; j++) {
       Piece p = b.getPiece(i, j);
       if (p.getColor() == color && p.isKing() == true) {
         result++;
       }
     }
   }
   return result;
 }
Esempio n. 13
0
 private void sendBoardToDisplay(MITrisBoard board, Display2D display, double brightness) {
   int width = display.getWidth();
   int height = display.getHeight();
   for (int x = 0; x < width; x++) {
     for (int y = 0; y < height; y++) {
       Piece p = board.getPosition(x, y);
       Color c = p == null ? Color.BLACK : p.getColor(board.getLevel(), gameDisplayTime);
       float[] hsb = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), new float[3]);
       hsb[2] *= brightness;
       display.setPixelHSB(x, height - 1 - y, hsb[0], hsb[1], hsb[2]);
     }
   }
 }
Esempio n. 14
0
  /**
   * Move piece to the specified location. If the target location is occupied by an opponent piece,
   * that piece is marked as 'captured'
   *
   * @param sourceRow the source row (Piece.ROW_..) of the piece to move
   * @param sourceColumn the source column (Piece.COLUMN_..) of the piece to move
   * @param targetRow the target row (Piece.ROW_..)
   * @param targetColumn the target column (Piece.COLUMN_..)
   */
  public void movePiece(int sourceRow, int sourceColumn, int targetRow, int targetColumn) {
    Piece piece = getNonCapturedPieceAtLocation(sourceRow, sourceColumn);

    if (piece == null) {
      throw new IllegalArgumentException("No piece at source location");
    }

    if (piece.getColor() == Piece.COLOR_WHITE && this.gameState != ChessGame.GAME_STATE_WHITE
        || piece.getColor() == Piece.COLOR_BLACK && this.gameState != ChessGame.GAME_STATE_BLACK) {
      throw new IllegalArgumentException("It's not your turn");
    }

    // check if the move is capturing an opponent piece
    int opponentColor =
        (piece.getColor() == Piece.COLOR_BLACK ? Piece.COLOR_WHITE : Piece.COLOR_BLACK);
    if (isNonCapturedPieceAtLocation(opponentColor, targetRow, targetColumn)) {
      Piece opponentPiece = getNonCapturedPieceAtLocation(targetRow, targetColumn);
      opponentPiece.isCaptured(true);
    }

    piece.setRow(targetRow);
    piece.setColumn(targetColumn);
  }
Esempio n. 15
0
  /**
   * Draw a piece.
   *
   * @param obj the piece to draw
   * @param comp not used
   * @param g2 the graphics 2D object to draw with
   */
  public void draw(Object obj, Component comp, Graphics2D g2) {
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    Piece piece = (Piece) obj;
    Color pieceColor = piece.getColor();
    g2.setPaint(pieceColor);
    g2.draw(body);

    g2.scale(1.0 / GRADIENT_SIZE, 1.0 / GRADIENT_SIZE);
    g2.setPaint(
        new GradientPaint(
            -GRADIENT_SIZE / 4,
            -GRADIENT_SIZE / 2,
            Color.white,
            GRADIENT_SIZE / 4,
            GRADIENT_SIZE / 4,
            pieceColor));
    g2.fill(ATX.createTransformedShape(body));
    g2.scale(GRADIENT_SIZE, GRADIENT_SIZE);
  }
Esempio n. 16
0
  /**
   * Performs the move, and modifies the actual board
   *
   * @throws IOException
   */
  public void performMove(String move, String color, boolean actuallyMove) throws IOException {
    int[] moveArray = parseInput(move);
    // System.out.println(board[moveArray[0]][moveArray[1]]);

    if (board[moveArray[0]][moveArray[1]] == null) {
      throw new IOException();
    }

    if (!board[moveArray[0]][moveArray[1]].getColor().equals(color)) {
      throw new IOException();
    }

    if (board[moveArray[2]][moveArray[3]] != null) {
      if (board[moveArray[2]][moveArray[3]].getColor().equals(color)) {
        throw new IOException();
      }
    }

    if (board[moveArray[0]][moveArray[1]].validateMove(
        board, moveArray[0], moveArray[1], moveArray[2], moveArray[3])) {
      // This means the move was valid

      if (isInCheck(color)) {
        // Because the current player put him/herself in check
        // I need to find out what is going to happen to the board in this case
        System.out.println("1");
        throw new IOException();
      }

      if (actuallyMove) {
        // Switch the two spots on the board because the move was valid
        board[moveArray[2]][moveArray[3]] = board[moveArray[0]][moveArray[1]];
        board[moveArray[0]][moveArray[1]] = null;
      }

      if (board[moveArray[2]][moveArray[3]] != null) {
        if (board[moveArray[2]][moveArray[3]].getClass().isInstance(new King("white"))) {
          if (actuallyMove) {
            ((King) board[moveArray[2]][moveArray[3]]).hasMoved = true;
          }
          // This Piece is a King
          if (((King) board[moveArray[2]][moveArray[3]]).castled) {
            if (moveArray[3] - moveArray[1] == 2) {
              board[moveArray[2]][moveArray[3] - 1] = board[moveArray[2]][moveArray[3] + 1];
              board[moveArray[2]][moveArray[3] + 1] = null;
            } else {
              board[moveArray[2]][moveArray[3] + 1] = board[moveArray[2]][moveArray[3] - 1];
              board[moveArray[2]][moveArray[3] - 1] = null;
            }
            ((King) board[moveArray[2]][moveArray[3]]).castled = false;
          }
        }
      }

    } else {
      throw new IOException();
    }

    // Rules dealing with pawns
    if (actuallyMove) {
      Piece piece = board[moveArray[2]][moveArray[3]];
      // This way it gets toggled the next time it moves
      piece.ep_able = false;
      if (piece != null) {
        if (piece.getClass().isInstance(new Pawn("white"))) {
          // The piece is a pawn
          piece.hasMoved = true;

          // Promotion
          Piece replacement;
          if (move.split(" ").length < 3) {
            move += " s";
          }
          if (piece.getColor().equals("white")) {
            if (moveArray[2] == 7) {
              switch (move.split(" ")[2].charAt(0)) {
                case 'N':
                  replacement = new Knight("white");
                  break;
                case 'B':
                  replacement = new Bishop("white");
                  break;
                default:
                  replacement = new Queen("white");
                  break;
              }
              board[moveArray[2]][moveArray[3]] = replacement;
            }
          } else {
            if (moveArray[2] == 0) {
              switch (move.split(" ")[2].charAt(0)) {
                case 'N':
                  replacement = new Knight("black");
                  break;
                case 'B':
                  replacement = new Bishop("black");
                  break;
                default:
                  replacement = new Queen("black");
                  break;
              }
              board[moveArray[2]][moveArray[3]] = replacement;
            }
          }

          // En passante capture
          /*int newCol = moveArray[3];
          int newRow = moveArray[2];
          if(inSixthRank(color, newRow)){
          if(newCol + 1 < 8){
          if(board[newRow][newCol + 1] != null){
          if(board[newRow][newCol + 1].getClass().isInstance(new Pawn("white"))){
          if(board[][].ep_able){
          board[][] = null;
          }
          }
          }
          }else if(newCol - 1 > 0){
          if(board[newRow][newCol - 1] != null){
          if(board[newRow][newCol - 1].getClass().isInstance(new Pawn("white"))){
          if(board[][].ep_able){
          board[][] = null;
          }
          }
          }
          }
          }*/

        }
      }
    }
  }
Esempio n. 17
0
  @Override
  public ArrayList<Move> getMoves(Board board) {
    ArrayList<Move> movesList = new ArrayList<Move>();

    Location newLocation = null;
    Location currentLocation = board.getLocation(this);
    char column = currentLocation.getCharacter();
    int row = currentLocation.getInteger();
    int boardLength = 8;

    // Down Left
    for (int i = 1; i < boardLength; i++) {
      newLocation = new Location((char) (column - i), (row - i));
      if (board.isValidSquare(newLocation)) {
        Piece p = board.getPiece(newLocation);
        if (p != null && p.getColor() != this.getColor()) {
          movesList.add(new Move(currentLocation, newLocation));
        } else if (p == null) {
          movesList.add(new Move(currentLocation, newLocation));
        }

        if (pathIsObstructed(board, currentLocation, newLocation)) break;
      }
    }

    // Down Right
    for (int i = 1; i < boardLength; i++) {
      newLocation = new Location((char) (column + i), (row - i));
      if (board.isValidSquare(newLocation)) {
        Piece p = board.getPiece(newLocation);
        if (p != null && p.getColor() != this.getColor()) {
          movesList.add(new Move(currentLocation, newLocation));
        } else if (p == null) {
          movesList.add(new Move(currentLocation, newLocation));
        }

        if (pathIsObstructed(board, currentLocation, newLocation)) break;
      }
    }

    // Up Left
    for (int i = 1; i < boardLength; i++) {
      newLocation = new Location((char) (column - i), (row + i));
      if (board.isValidSquare(newLocation)) {
        Piece p = board.getPiece(newLocation);
        if (p != null && p.getColor() != this.getColor()) {
          movesList.add(new Move(currentLocation, newLocation));
        } else if (p == null) {
          movesList.add(new Move(currentLocation, newLocation));
        }

        if (pathIsObstructed(board, currentLocation, newLocation)) break;
      }
    }

    // Up Right
    for (int i = 1; i < boardLength; i++) {
      newLocation = new Location((char) (column + i), (row + i));
      if (board.isValidSquare(newLocation)) {
        Piece p = board.getPiece(newLocation);
        if (p != null && p.getColor() != this.getColor()) {
          movesList.add(new Move(currentLocation, newLocation));
        } else if (p == null) {
          movesList.add(new Move(currentLocation, newLocation));
        }

        if (pathIsObstructed(board, currentLocation, newLocation)) break;
      }
    }

    return movesList;
  }
Esempio n. 18
0
 /** Returns true if the given Piece has opposite color from this piece. */
 public boolean isOppositeColor(Piece piece) {
   return this.getColor() != piece.getColor();
 }
Esempio n. 19
0
 /** Returns trie of the given Piece has the same color as this Piece. */
 public boolean isSameColor(Piece piece) {
   return this.getColor() == piece.getColor();
 }
  /**
   * Returns a list of all possible jumps from the piece at (x,y). If there is no piece on that
   * square, or the piece cannot make a legal jump then return an empty list
   */
  public List<Jump> getJumps(final int x, final int y) {
    Piece piece = getPiece(y, x);
    if (piece == null) {
      return new ArrayList<Jump>(0);
    } else {
      List<Jump> jumps = new ArrayList<Jump>();
      if (Piece.WHITE_MAN.equals(piece)) {
        if (isOnBoard(x - 1, y + 1)
            && isOnBoard(x - 2, y + 2)
            && !isEmptySquare(x - 1, y + 1)
            && getPiece(y + 1, x - 1).isEnemyColor(piece.getColor())
            && isEmptySquare(x - 2, y + 2)) {
          jumps.add(new Jump(y, x, x - 1, y + 1, x - 2, y + 2));
        }
        if (isOnBoard(x + 1, y + 1)
            && isOnBoard(x + 2, y + 2)
            && !isEmptySquare(x + 1, y + 1)
            && getPiece(y + 1, x + 1).isEnemyColor(piece.getColor())
            && isEmptySquare(x + 2, y + 2)) {
          jumps.add(new Jump(y, x, x + 1, y + 1, x + 2, y + 2));
        }

      } else if (Piece.RED_MAN.equals(piece)) {
        if (isOnBoard(x - 1, y - 1)
            && isOnBoard(x - 2, y - 2)
            && !isEmptySquare(x - 1, y - 1)
            && getPiece(y - 1, x - 1).isEnemyColor(piece.getColor())
            && isEmptySquare(x - 2, y - 2)) {
          jumps.add(new Jump(y, x, x - 1, y - 1, x - 2, y - 2));
        }
        if (isOnBoard(x + 1, y - 1)
            && isOnBoard(x + 2, y - 2)
            && !isEmptySquare(x + 1, y - 1)
            && getPiece(y - 1, x + 1).isEnemyColor(piece.getColor())
            && isEmptySquare(x + 2, y - 2)) {
          jumps.add(new Jump(y, x, x + 1, y - 1, x + 2, y - 2));
        }
      } else {
        if (isOnBoard(x - 1, y - 1)
            && isOnBoard(x - 2, y - 2)
            && !isEmptySquare(x - 1, y - 1)
            && getPiece(y - 1, x - 1).isEnemyColor(piece.getColor())
            && isEmptySquare(x - 2, y - 2)) {
          jumps.add(new Jump(y, x, x - 1, y - 1, x - 2, y - 2));
        }
        if (isOnBoard(x + 1, y - 1)
            && isOnBoard(x + 2, y - 2)
            && !isEmptySquare(x + 1, y - 1)
            && getPiece(y - 1, x + 1).isEnemyColor(piece.getColor())
            && isEmptySquare(x + 2, y - 2)) {
          jumps.add(new Jump(y, x, x + 1, y - 1, x + 2, y - 2));
        }
        if (isOnBoard(x - 1, y + 1)
            && isOnBoard(x - 2, y + 2)
            && !isEmptySquare(x - 1, y + 1)
            && getPiece(y + 1, x - 1).isEnemyColor(piece.getColor())
            && isEmptySquare(x - 2, y + 2)) {
          jumps.add(new Jump(y, x, x - 1, y + 1, x - 2, y + 2));
        }
        if (isOnBoard(x + 1, y + 1)
            && isOnBoard(x + 2, y + 2)
            && !isEmptySquare(x + 1, y + 1)
            && getPiece(y + 1, x + 1).isEnemyColor(piece.getColor())
            && isEmptySquare(x + 2, y + 2)) {
          jumps.add(new Jump(y, x, x + 1, y + 1, x + 2, y + 2));
        }
      }
      return jumps;
    }
  }
Esempio n. 21
0
  public static Set<Coordinate> getPossibleCoordinates(
      Coordinate startingCoord, Board board, boolean includeThreateningOwnPiece) {
    Set<Coordinate> coordinates = new LinkedHashSet<Coordinate>();
    Color startingColor = board.getPiece(startingCoord).getColor();

    // add entries to the top left
    for (int i = 1; i < 8; i++) {
      Coordinate coord = startingCoord.transform(-i, +i);
      if (!board.contains(coord)) break;
      Piece piece = board.getPiece(coord);
      if (piece.isNone()) {
        coordinates.add(coord);
      } else if (includeThreateningOwnPiece && piece.getColor() == startingColor) {
        coordinates.add(coord);
        break;
      } else if (!includeThreateningOwnPiece && piece.getColor() == startingColor) {
        break;
      } else {
        coordinates.add(coord);
        break;
      }
    }

    // add entries to the top right
    for (int i = 1; i < 8; i++) {
      Coordinate coord = startingCoord.transform(+i, +i);
      if (!board.contains(coord)) break;
      Piece piece = board.getPiece(coord);
      if (piece.isNone()) {
        coordinates.add(coord);
      } else if (includeThreateningOwnPiece && piece.getColor() == startingColor) {
        coordinates.add(coord);
        break;
      } else if (!includeThreateningOwnPiece && piece.getColor() == startingColor) {
        break;
      } else {
        coordinates.add(coord);
        break;
      }
    }

    // add entries to the bottom left
    for (int i = 1; i < 8; i++) {
      Coordinate coord = startingCoord.transform(-i, -i);
      if (!board.contains(coord)) break;
      Piece piece = board.getPiece(coord);
      if (piece.isNone()) {
        coordinates.add(coord);
      } else if (includeThreateningOwnPiece && piece.getColor() == startingColor) {
        coordinates.add(coord);
        break;
      } else if (!includeThreateningOwnPiece && piece.getColor() == startingColor) {
        break;
      } else {
        coordinates.add(coord);
        break;
      }
    }

    // add entries to the bottom right
    for (int i = 1; i < 8; i++) {
      Coordinate coord = startingCoord.transform(+i, -i);
      if (!board.contains(coord)) break;
      Piece piece = board.getPiece(coord);
      if (piece.isNone()) {
        coordinates.add(coord);
      } else if (includeThreateningOwnPiece && piece.getColor() == startingColor) {
        coordinates.add(coord);
        break;
      } else if (!includeThreateningOwnPiece && piece.getColor() == startingColor) {
        break;
      } else {
        coordinates.add(coord);
        break;
      }
    }
    return coordinates;
  }
Esempio n. 22
0
    @Override
    public void actionPerformed(ActionEvent e) {
      JButton button = (JButton) e.getSource();
      Point rv = new Point();
      int rank = button.getLocation(rv).y / 100;
      int file = button.getLocation(rv).x / 100;
      Piece selection = game.gameBoard.spaces[rank][file];
      if (selectedPiece != null) {
        boolean reachable = false;
        Vector<Space> showMoves = BoardLogic.movesOnBoard(game.gameBoard, selectedPiece);
        for (int i = 0; i < showMoves.size(); i++) {
          if (showMoves.elementAt(i).getFile() == file && showMoves.elementAt(i).getRank() == rank)
            reachable = true;
        }
        if (reachable == false) {
          JOptionPane.showMessageDialog(null, "Selected space is unreachable");
          JButton moves;
          for (int i = 0; i < showMoves.size(); i++) {
            moves = jButtonList[showMoves.elementAt(i).getRank()][showMoves.elementAt(i).getFile()];
            Border thickBorder = new LineBorder(Color.BLACK, 1);
            moves.setBorder(thickBorder);
          }
          selectedPiece = null;
        } else {
          game.move.push(
              new Step(
                  selectedPiece.getRank(),
                  selectedPiece.getFile(),
                  rank,
                  file,
                  game.gameBoard.spaces[rank][file]));
          BoardLogic.movePiece(game.gameBoard, selectedPiece, rank, file);
          JButton moves;
          for (int i = 0; i < showMoves.size(); i++) {
            moves = jButtonList[showMoves.elementAt(i).getRank()][showMoves.elementAt(i).getFile()];
            Border thickBorder = new LineBorder(Color.BLACK, 1);
            moves.setBorder(thickBorder);
          }
          Icon img = selectedSquare.getIcon();
          button.setIcon(img);
          selectedSquare.setIcon(null);
          currPlayer = game.nextPlayer(currPlayer);
          selectedPiece = null;
          // memorization

          if (BoardLogic.inCheckmate(game.gameBoard, currPlayer.pieceColor)) {
            JOptionPane.showMessageDialog(
                null,
                currPlayer.name
                    + " is in CheckMate, "
                    + game.nextPlayer(currPlayer).name
                    + " win!");
            game.nextPlayer(currPlayer).score++;
          } else if (BoardLogic.inStalemate(game.gameBoard, currPlayer.pieceColor)) {
            JOptionPane.showMessageDialog(null, "The game is in StaleMate");
            currPlayer.score++;
            game.nextPlayer(currPlayer).score++;
          } else if (BoardLogic.inCheck(game.gameBoard, currPlayer.pieceColor)) {
            JOptionPane.showMessageDialog(null, currPlayer.name + " is in Check");
          }
        }
      } else if (selection.getColor() == currPlayer.pieceColor) {
        JButton moves;
        selectedPiece = game.gameBoard.spaces[rank][file];
        Vector<Space> showMoves = BoardLogic.movesOnBoard(game.gameBoard, selectedPiece);
        for (int i = 0; i < showMoves.size(); i++) {
          moves = jButtonList[showMoves.elementAt(i).getRank()][showMoves.elementAt(i).getFile()];
          Border thickBorder = new LineBorder(Color.YELLOW, 3);
          moves.setBorder(thickBorder);
        }
        selectedSquare = button;
      }
    }