← all problems

Chess: Steps and Rules

Write six methods in ChessRules.java that decide whether a chess move is legal on a real board: three questions about a single square, the knight (the king is already written, as a worked example), the pawn with its direction, double step and captures, and an isLegalMove that sends each move to the right method. The board, pieces and moves are provided: open the API reference tab. Read the Instructions tab first. Run code runs your own main (ungraded); Run tests grades everything without saving; Submit tests grades and saves.

You're not logged in — Run code and Run tests work fine without an account, but Submit tests needs one to save your score, and your in-progress code won't be saved between visits either. Log in with Google before you submit.

ChessRules.java — editable
ChessAPI.java — reference only, not part of your program

class ChessPiece

One chess piece: a type and a colour. A piece never changes once it is made. The type is a lowercase word: "pawn", "knight", "bishop", "rook", "queen", "king" or "wizard" (a fairy-chess piece).

ChessPiece knight = new ChessPiece("knight", true);
knight.getType()                                   // "knight"
knight.isWhite()                                   // true
knight.toString()                                  // "N"
knight.equals(new ChessPiece("knight", false))     // false
MethodWhat it does
ChessPiece(String type, boolean isWhite)

Makes a piece.

  • type – one of the type words above
  • isWhite – true for a White piece, false for a Black one
String getType()

The piece's type word.

Returns "pawn", "knight", "bishop", "rook", "queen", "king" or "wizard"

boolean isWhite()

Which side the piece belongs to.

Returns true for White, false for Black

String toString()

The piece as its one-letter FEN symbol: uppercase for White, lowercase for Black. This is what System.out.println(piece) shows.

Returns one of "P", "N", "B", "R", "Q", "K", "W" for White, or the lowercase letter for Black

boolean equals(Object other)

Whether another object is a piece of the same type and the same colour.

  • other – the object to compare with

Returns true when type and colour both match; false otherwise, including for null

class Move

A move from one square to another, as (row, col) pairs. Row 0 is the top of the board (rank 8) and column 0 is file a, so e2 is row 6, column 4. A move never changes once it is made, and it does not know whether it is legal.

Move m = new Move(6, 4, 4, 4);                  // e2 to e4
m.getStartRow()                                 // 6
m.getEndRow()                                   // 4
m.toString()                                    // "e2e4"
m.equals(new Move(6, 4, 4, 4))                  // true
MethodWhat it does
Move(int startRow, int startCol, int endRow, int endCol)

Makes a move from the start square to the end square.

  • startRow – the row of the square the piece starts on
  • startCol – the column of the square the piece starts on
  • endRow – the row of the square it moves to
  • endCol – the column of the square it moves to
int getStartRow()

The row of the square the move starts on.

Returns a row, 0 to 7

int getStartCol()

The column of the square the move starts on.

Returns a column, 0 to 7

int getEndRow()

The row of the square the move ends on.

Returns a row, 0 to 7

int getEndCol()

The column of the square the move ends on.

Returns a column, 0 to 7

String toString()

The move as the two square names joined together, such as "e2e4". A pawn promotion to something other than a queen adds the new piece's letter ("e7e8n").

Returns the move as text

boolean equals(Object other)

Whether another object is a move between the same two squares (with the same promotion piece).

  • other – the object to compare with

Returns true or false; false for anything that is not a Move

class ChessBoard

An 8 by 8 chess position: which piece, or null, stands on each square. A board never changes once it is made: move gives you a new board. Row 0 is the top of the board (rank 8) and column 0 is file a, so a8 is (0, 0) and e1 is (7, 4).

ChessBoard board = new ChessBoard();
board.getPiece(7, 4).toString()                 // "K"
board.getPiece(4, 4)                            // null
board.getPiece(8, 0)                            // null
ChessBoard after = board.move(new Move(6, 4, 4, 4));
after.getPiece(4, 4).toString()                 // "P"
board.getPiece(4, 4)                            // null
MethodWhat it does
ChessBoard()

The standard starting position: White on rows 6 and 7 at the bottom, Black on rows 0 and 1 at the top.

ChessBoard(ChessPiece[][] source)

A board holding the pieces of an 8 by 8 array. The array is copied, so changing it later does not change the board.

  • source – an 8 by 8 array of pieces, with null for an empty square
ChessBoard(String fen)

A position from a FEN string, for example "8/8/8/4k3/8/8/8/4K3 w". Only the piece-placement field (before the first space) is read. Rank 8 comes first, a digit means that many empty squares, and uppercase letters are White's pieces.

  • fen – the position as a FEN string
ChessPiece getPiece(int row, int col)

The piece on a square.

  • row – the row, 0 (the top of the board, rank 8) to 7 (rank 1)
  • col – the column, 0 (file a) to 7 (file h)

Returns the ChessPiece there, or null for an empty square and for any square off the board, so coordinates such as -1 or 8 are safe to ask about

ChessBoard move(Move m)

A NEW board with the piece on the start square moved to the end square; anything on the end square is replaced. The move is not checked for legality and this board is not changed. A pawn that reaches the last row becomes a queen unless the move names another piece. If the start square is empty, the new board is just a copy.

  • m – the move to make

Returns the board after the move

String toString()

The board as eight lines of eight characters, row 0 first: the FEN letter of each piece and a dot for each empty square.

Returns a text picture of the board

class ChessGeometry

Square names, and the SHAPE of each piece's move on an empty board, ignoring every other piece. A square name is a file letter and a rank number, such as "e4". Row 0 is the top of the board (rank 8) and column 0 is file a; White moves toward lower rows.

ChessGeometry.squareName(0, 0)                  // "a8"
ChessGeometry.squareName(7, 4)                  // "e1"
ChessGeometry.rowOfSquare("e4")                 // 4
ChessGeometry.colOfSquare("e4")                 // 4
ChessGeometry.isValidKnightMove(7, 1, 5, 2)     // true
ChessGeometry.isValidRookMove(0, 0, 3, 3)       // false
MethodWhat it does
static boolean areValidCoordinates(int row, int col)

Whether a square is on the board.

  • row – the row, 0 (the top of the board, rank 8) to 7 (rank 1)
  • col – the column, 0 (file a) to 7 (file h)

Returns true when both the row and the column are 0 to 7

static boolean isValidRookMove(int startRow, int startCol, int endRow, int endCol)

Whether a rook could go from the start square to the end square on an empty board: along one row or one column, and not staying where it is. Every one of these is false if either square is off the board.

  • startRow – the row of the square the piece starts on
  • startCol – the column of the square the piece starts on
  • endRow – the row of the square it moves to
  • endCol – the column of the square it moves to

Returns true or false

static boolean isValidBishopMove(int startRow, int startCol, int endRow, int endCol)

Whether a bishop could go from the start square to the end square on an empty board: along a diagonal, by at least one square. Every one of these is false if either square is off the board.

  • startRow – the row of the square the piece starts on
  • startCol – the column of the square the piece starts on
  • endRow – the row of the square it moves to
  • endCol – the column of the square it moves to

Returns true or false

static boolean isValidQueenMove(int startRow, int startCol, int endRow, int endCol)

Whether a queen could go from the start square to the end square on an empty board: a rook move or a bishop move. Every one of these is false if either square is off the board.

  • startRow – the row of the square the piece starts on
  • startCol – the column of the square the piece starts on
  • endRow – the row of the square it moves to
  • endCol – the column of the square it moves to

Returns true or false

static boolean isValidKnightMove(int startRow, int startCol, int endRow, int endCol)

Whether a knight could go from the start square to the end square: an L shape, two squares in one direction and one at right angles. Every one of these is false if either square is off the board.

  • startRow – the row of the square the piece starts on
  • startCol – the column of the square the piece starts on
  • endRow – the row of the square it moves to
  • endCol – the column of the square it moves to

Returns true or false

static boolean isValidKingMove(int startRow, int startCol, int endRow, int endCol)

Whether a king could go from the start square to the end square: one step in any direction, not staying put. Every one of these is false if either square is off the board.

  • startRow – the row of the square the piece starts on
  • startCol – the column of the square the piece starts on
  • endRow – the row of the square it moves to
  • endCol – the column of the square it moves to

Returns true or false

static boolean isValidPawnMove(int startRow, int startCol, int endRow, int endCol, boolean isCapture)

Whether a WHITE pawn could make this move on an otherwise empty board; forward is toward lower rows. Without a capture it goes straight forward one square, or two squares from its starting row (row 6). With a capture it goes one square diagonally forward. Every one of these is false if either square is off the board.

  • startRow – the row of the square the piece starts on
  • startCol – the column of the square the piece starts on
  • endRow – the row of the square it moves to
  • endCol – the column of the square it moves to
  • isCapture – true if the move captures a piece, false for an ordinary move

Returns true or false

static boolean isValidWizardMove(int startRow, int startCol, int endRow, int endCol)

Whether the fairy-chess Wizard could go from the start square to the end square: one step diagonally, or a leap of three squares in one direction and one at right angles (either way round). Every one of these is false if either square is off the board.

  • startRow – the row of the square the piece starts on
  • startCol – the column of the square the piece starts on
  • endRow – the row of the square it moves to
  • endCol – the column of the square it moves to

Returns true or false

static String squareName(int row, int col)

The name of a square: (0, 0) is "a8" and (7, 4) is "e1".

  • row – the row, 0 (the top of the board, rank 8) to 7 (rank 1)
  • col – the column, 0 (file a) to 7 (file h)

Returns the file letter followed by the rank number

static int rowOfSquare(String square)

The row of a named square: "e4" is row 4, "a8" is row 0.

  • square – a square name such as "e4"

Returns the row, 0 to 7

static int colOfSquare(String square)

The column of a named square: "e4" is column 4, "a8" is column 0.

  • square – a square name such as "e4"

Returns the column, 0 to 7

static boolean isLightSquare(int row, int col)

Whether a square is a light square. a8 (row 0, column 0) is light and a1 is dark.

  • row – the row, 0 (the top of the board, rank 8) to 7 (rank 1)
  • col – the column, 0 (file a) to 7 (file h)

Returns true for a light square, false for a dark one

class Blocking

Sliding pieces (the rook, bishop and queen) cannot jump over other pieces: these methods check what is in the way.

ChessBoard board = new ChessBoard();
Blocking.isPathClear(board, 7, 0, 5, 0)        // false
Blocking.isPathClear(board, 5, 0, 3, 0)        // true
Blocking.isLegalSliderMove(board, new Move(7, 0, 6, 0))   // false
MethodWhat it does
static boolean isPathClear(ChessBoard board, int startRow, int startCol, int endRow, int endCol)

Whether every square STRICTLY BETWEEN the start and end squares is empty. The two end squares themselves are not looked at.

  • board – the position to look at
  • startRow – the row of the square the piece starts on
  • startCol – the column of the square the piece starts on
  • endRow – the row of the square it moves to
  • endCol – the column of the square it moves to

Returns true when the squares share a row, a column or a diagonal and nothing stands between them; false if they are not on a common line or something is in the way

static boolean isLegalSliderMove(ChessBoard board, Move move)

Whether the rook, bishop or queen on the start square could make this move: the move has that piece's shape, nothing stands in the way, and the end square does not hold one of its own side's pieces.

  • board – the position to look at
  • move – the move to test; its start square should hold the piece

Returns true or false; false when the start square is empty or holds some other kind of piece

Background


In the last chess lab you wrote the geometry of the game. Now there are pieces on the board, and a move is only legal if the pieces allow it: you may not capture your own piece, a pawn cannot walk into a piece standing in front of it, and a pawn captures differently from how it moves. In this lab you write the rules that look at the board.

The board, the pieces and the moves are objects that this lab gives you. You do not write them. Open the API reference tab: it lists everything you can call on ChessPiece, Move, ChessBoard, and the geometry methods you wrote last time (ChessGeometry). You cannot see how they work and you do not need to.

Looking at squares


board.getPiece(row, col) gives you the ChessPiece standing on a square, or null when the square is empty. It also gives null for a square that is not on the board at all, so an empty square and an off-board square look the same to getPiece. Your methods have to tell them apart.

A null has no methods. Calling piece.isWhite() on a null crashes your program with a NullPointerException. The cure is the short-circuit behaviour of && that you have just learned: in a && b, Java never evaluates b when a is false, so you can put the "is there a piece at all?" check on the left and the question about the piece on the right.

A move


A Move holds a start square and an end square: new Move(6, 4, 4, 4) is the move e2e4. You read it back with getStartRow(), getStartCol(), getEndRow() and getEndCol(). A Move is only a description. It does not know whether the move is legal; that is what you are writing.

Who is moving?


You never get told whose turn it is. The colour of the piece on the start square says who is moving. If the start square is empty there is no move to make, so the answer is false (and your method must not crash).

The methods


isEmpty, isFriendly, isEnemy: three questions about one square. For all three, a square off the board answers false. isFriendly(board, row, col, isWhite) is true when the piece there has the colour isWhite; isEnemy is true when it has the other colour.

isLegalKnightMove (and isLegalKingMove, which is already written for you): the knight and the king are leapers in this lab: nothing can block them. The move is legal when the piece on the start square has the right shape (the ChessGeometry methods you wrote tell you that) and the end square is not occupied by a piece of the mover's own colour. Capturing an enemy is allowed.

isLegalKingMove is a worked example, and it is not graded. It is complete in your starter code. Read it before you write the knight: it checks that there is a piece on the start square, asks ChessGeometry about the shape, and uses your own isFriendly for the end square. The knight is the same method with a different shape. (isLegalMove still sends kings to it, so if you break it, the isLegalMove tests will tell you.)

isLegalPawnMove: pawns are the most interesting. For a White pawn "forward" is toward row 0 and its starting row is row 6; for a Black pawn forward is toward row 7 and its starting row is row 1.
  • One step forward is legal if that square is empty.
  • Two steps forward is legal only from the pawn's starting row, and only if both squares it passes over and lands on are empty.
  • One step diagonally forward is legal only if an enemy piece stands there (a capture). An empty square or a friendly piece makes it illegal.
  • Everything else is illegal: backward, sideways, a straight move into any piece, and a straight capture.

There is no en passant and no promotion rule in this lab.

isLegalMove: the dispatcher. Look at getType() of the piece on the start square ("pawn", "knight", "king", and for "rook", "bishop" and "queen" call Blocking.isLegalSliderMove(board, move), which is provided) and hand the move to the right method. Compare Strings with .equals(...), not ==. A start square with no piece is never legal.

This lab


You will write six methods in ChessRules.java: isEmpty, isFriendly, isEnemy, isLegalKnightMove, isLegalPawnMove and isLegalMove. Use Run code to try your own main method (it is never graded): printing a board with System.out.println(board) shows it as eight lines of letters, with . for an empty square, uppercase for White and lowercase for Black. Use Run tests to grade all six without saving a score, and Submit tests to save.

A suggestion: write isEmpty, isFriendly and isEnemy first, test them, and then build everything else on top of them. The pawn is easier to get right when you work out the direction and the starting row once, in variables, before you look at any move.