Problem Statement: The problem is to design a Chess Game using Object Oriented Principles.
Asked In: Adobe, Amazon, Microsoft, etc.
Solution:
These type of questions are asked in interviews to Judge the Object-Oriented Design skill of a candidate. So, first of all we should think about the classes.
The main classes will be:
- Spot: A spot represents one block of the 8×8 grid and an optional piece.
- Piece: The basic building block of the system, every piece will be placed on a spot. Piece class is an abstract class. The extended classes (Pawn, King, Queen, Rook, Knight, Bishop) implements the abstracted operations.
- Board: Board is an 8×8 set of boxes containing all active chess pieces.
- Player: Player class represents one of the participants playing the game.
- Move: Represents a game move, containing the starting and ending spot. The Move class will also keep track of the player who made the move.
- Game: This class controls the flow of a game. It keeps track of all the game moves, which player has the current turn, and the final result of the game.
Let’s look at the details. These codes are self-explanatory. You can have a look at the properties/variables and methods of different classes.
Spot: To represent a cell on the chess board:
publicclassSpot {privatePiece piece;privateintx;privateinty;publicSpot(intx,inty, Piece piece){this.setPiece(piece);this.setX(x);this.setY(y);}publicPiece getPiece(){returnthis.piece;}publicvoidsetPiece(Piece p){this.piece = p;}publicintgetX(){returnthis.x;}publicvoidsetX(intx){this.x = x;}publicintgetY(){returnthis.y;}publicvoidsetY(inty){this.y = y;}}Piece: An abstract class to represent common functionality of all chess pieces:
publicabstractclassPiece {privatebooleankilled =false;privatebooleanwhite =false;publicPiece(booleanwhite){this.setWhite(white);}publicbooleanisWhite(){returnthis.white;}publicvoidsetWhite(booleanwhite){this.white = white;}publicbooleanisKilled(){returnthis.killed;}publicvoidsetKilled(booleankilled){this.killed = killed;}publicabstractbooleancanMove(Board board,Spot start, Spot end);}King: To represent King as a chess piece:
publicclassKingextendsPiece {privatebooleancastlingDone =false;publicKing(booleanwhite){super(white);}publicbooleanisCastlingDone(){returnthis.castlingDone;}publicvoidsetCastlingDone(booleancastlingDone){this.castlingDone = castlingDone;}@OverridepublicbooleancanMove(Board board, Spot start, Spot end){// we can't move the piece to a Spot that// has a piece of the same colorif(end.getPiece().isWhite() ==this.isWhite()) {returnfalse;}intx = Math.abs(start.getX() - end.getX());inty = Math.abs(start.getY() - end.getY());if(x + y ==1) {// check if this move will not result in the king// being attacked if so return truereturntrue;}returnthis.isValidCastling(board, start, end);}privatebooleanisValidCastling(Board board,Spot start, Spot end){if(this.isCastlingDone()) {returnfalse;}// Logic for returning true or false}publicbooleanisCastlingMove(Spot start, Spot end){// check if the starting and// ending position are correct}}Knight: To represent Knight as a chess piece
publicclassKnightextendsPiece {publicKnight(booleanwhite){super(white);}@OverridepublicbooleancanMove(Board board, Spot start,Spot end){// we can't move the piece to a spot that has// a piece of the same colourif(end.getPiece().isWhite() ==this.isWhite()) {returnfalse;}intx = Math.abs(start.getX() - end.getX());inty = Math.abs(start.getY() - end.getY());returnx * y ==2;}}Similarly, we can create classes for other pieces like Queen, Pawns, Rooks, Bishops etc.
Board: To represent a chess board:
publicclassBoard {Spot[][] boxes;publicBoard(){this.resetBoard();}publicSpot getBox(intx,inty){if(x <0|| x >7|| y <0|| y >7) {thrownewException("Index out of bound");}returnboxes[x][y];}publicvoidresetBoard(){// initialize white piecesboxes[0][0] =newSpot(0,0,newRook(true));boxes[0][1] =newSpot(0,1,newKnight(true));boxes[0][2] =newSpot(0,2,newBishop(true));//...boxes[1][0] =newSpot(1,0,newPawn(true));boxes[1][1] =newSpot(1,1,newPawn(true));//...// initialize black piecesboxes[7][0] =newSpot(7,0,newRook(false));boxes[7][1] =newSpot(7,1,newKnight(false));boxes[7][2] =newSpot(7,2,newBishop(false));//...boxes[6][0] =newSpot(6,0,newPawn(false));boxes[6][1] =newSpot(6,1,newPawn(false));//...// initialize remaining boxes without any piecefor(inti =2; i <6; i++) {for(intj =0; j <8; j++) {boxes[i][j] =newSpot(i, j,null);}}}}Player: An abstract class for player, it can be a human or a computer.
publicabstractclassPlayer {publicbooleanwhiteSide;publicbooleanhumanPlayer;publicbooleanisWhiteSide(){returnthis.whiteSide;}publicbooleanisHumanPlayer(){returnthis.humanPlayer;}}publicclassHumanPlayerextendsPlayer {publicHumanPlayer(booleanwhiteSide){this.whiteSide = whiteSide;this.humanPlayer =true;}}publicclassComputerPlayerextendsPlayer {publicComputerPlayer(booleanwhiteSide){this.whiteSide = whiteSide;this.humanPlayer =false;}}Move: To represent a chess move:
publicclassMove {privatePlayer player;privateSpot start;privateSpot end;privatePiece pieceMoved;privatePiece pieceKilled;privatebooleancastlingMove =false;publicMove(Player player, Spot start, Spot end){this.player = player;this.start = start;this.end = end;this.pieceMoved = start.getPiece();}publicbooleanisCastlingMove(){returnthis.castlingMove;}publicvoidsetCastlingMove(booleancastlingMove){this.castlingMove = castlingMove;}}publicenumGameStatus {ACTIVE,BLACK_WIN,WHITE_WIN,FORFEIT,STALEMATE,RESIGNATION}Game: To represent a chess game:
publicclassGame {privatePlayer[] players;privateBoard board;privatePlayer currentTurn;privateGameStatus status;privateList<Move> movesPlayed;privatevoidinitialize(Player p1, Player p2){players[0] = p1;players[1] = p2;board.resetBoard();if(p1.isWhiteSide()) {this.currentTurn = p1;}else{this.currentTurn = p2;}movesPlayed.clear();}publicbooleanisEnd(){returnthis.getStatus() != GameStatus.ACTIVE;}publicbooleangetStatus(){returnthis.status;}publicvoidsetStatus(GameStatus status){this.status = status;}publicbooleanplayerMove(Player player,intstartX,intstartY,intendX,intendY){Spot startBox = board.getBox(startX, startY);Spot endBox = board.getBox(startY, endY);Move move =newMove(player, startBox, endBox);returnthis.makeMove(move, player);}privatebooleanmakeMove(Move move, Player player){Piece sourcePiece = move.getStart().getPiece();if(sourcePiece ==null) {returnfalse;}// valid playerif(player != currentTurn) {returnfalse;}if(sourcePiece.isWhite() != player.isWhiteSide()) {returnfalse;}// valid move?if(!sourcePiece.canMove(board, move.getStart(),move.getEnd())) {returnfalse;}// kill?Piece destPiece = move.getStart().getPiece();if(destPiece !=null) {destPiece.setKilled(true);move.setPieceKilled(destPiece);}// castling?if(sourcePiece !=null&& sourcePieceinstanceofKing&& sourcePiece.isCastlingMove()) {move.setCastlingMove(true);}// store the movemovesPlayed.add(move);// move piece from the stat box to end boxmove.getEnd().setPiece(move.getStart().getPiece());move.getStart.setPiece(null);if(destPiece !=null&& destPieceinstanceofKing) {if(player.isWhiteSide()) {this.setStatus(GameStatus.WHITE_WIN);}else{this.setStatus(GameStatus.BLACK_WIN);}}// set the current turn to the other playerif(this.currentTurn == players[0]) {this.currentTurn = players[1];}else{this.currentTurn = players[0];}returntrue;}}Reference: http://massivetechinterview.blogspot.com/2015/07/design-chess-game-using-oo-principles.html
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live and Geeks Classes Live USA


