Skip to main content

Design a Chess Game

Problem Statement

Design a Chess game system that allows two players to play a standard 8x8 chess game. The system should support all chess rules including valid piece movement, turn-based gameplay, move validation, and game-ending conditions like checkmate and stalemate.


Functional Requirements

  • Two-player turn-based chess game
  • Standard 8x8 chess board setup
  • Each piece follows its movement rules
  • Move validation before execution
  • Check and checkmate detection
  • Game status tracking (ACTIVE, CHECKMATE, STALEMATE)
  • Move history tracking

Objects Required

  • Game
  • Board
  • Cell
  • Piece (Abstract)
  • King, Queen, Rook, Bishop, Knight, Pawn
  • Player
  • Move
  • Color Enum
  • GameStatus Enum

Enums

Color Enum


public enum Color {
    WHITE,
    BLACK
}

The Color enum represents the two sides in a chess game. It is used by both Player and Piece classes to determine ownership and enforce turn-based rules.


GameStatus Enum


public enum GameStatus {
    ACTIVE,
    CHECKMATE,
    STALEMATE
}

GameStatus represents the lifecycle state of the chess game.

  • ACTIVE → Game is ongoing
  • CHECKMATE → King has no legal escape
  • STALEMATE → No valid moves but king not in check

Piece


public abstract class Piece {

    protected Color color;

    public Piece(Color color) {
        this.color = color;
    }

    public Color getColor() {
        return color;
    }

    public abstract boolean canMove(Board board, Cell from, Cell to);
}

This is the base class for all chess pieces. It enforces that every piece must define its own movement logic.

The canMove() method is overridden by each specific piece to validate legal moves based on chess rules.


Rook Class


public class Rook extends Piece {

    public Rook(Color color) {
        super(color);
    }

    @Override
    public boolean canMove(Board board, Cell from, Cell to) {
        return from.getRow() == to.getRow() ||
               from.getCol() == to.getCol();
    }
}

Rook moves horizontally or vertically across the board. The movement is valid only if row or column remains constant.


Cell Class


public class Cell {

    private int row;
    private int col;
    private Piece piece;

    public Cell(int row, int col) {
        this.row = row;
        this.col = col;
    }

    public Piece getPiece() {
        return piece;
    }

    public void setPiece(Piece piece) {
        this.piece = piece;
    }

    public int getRow() {
        return row;
    }

    public int getCol() {
        return col;
    }
}

Represents a single square on the chess board. Each cell may or may not contain a piece.

Getter and setter methods manage piece placement during moves.


Board Class


public class Board {

    private Cell[][] cells = new Cell[8][8];

    public Board() {
        initializeBoard();
    }

    private void initializeBoard() {
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                cells[i][j] = new Cell(i, j);
            }
        }
    }

    public Cell getCell(int row, int col) {
        return cells[row][col];
    }
}

Represents the 8x8 chess board. It is responsible for initializing all cells and providing access to any square.


Move Class


public class Move {

    private Player player;
    private Cell from;
    private Cell to;

    public Move(Player player, Cell from, Cell to) {
        this.player = player;
        this.from = from;
        this.to = to;
    }

    public Player getPlayer() {
        return player;
    }

    public Cell getFrom() {
        return from;
    }

    public Cell getTo() {
        return to;
    }
}

Represents a single move in the game, including source and destination cells and the player making the move.


Player Class


public class Player {

    private String name;
    private Color color;

    public Player(String name, Color color) {
        this.name = name;
        this.color = color;
    }

    public Color getColor() {
        return color;
    }
}

Represents a chess player. Each player is assigned a color which determines turn order and piece ownership.


Game Class


import java.util.*;

public class Game {

    private Board board;
    private Player whitePlayer;
    private Player blackPlayer;
    private Player currentPlayer;
    private GameStatus status;
    private List moveHistory;

    public Game(Player white, Player black) {
        this.board = new Board();
        this.whitePlayer = white;
        this.blackPlayer = black;
        this.currentPlayer = white;
        this.status = GameStatus.ACTIVE;
        this.moveHistory = new ArrayList<>();
    }

    public boolean makeMove(Move move) {

        Cell from = move.getFrom();
        Cell to = move.getTo();

        Piece piece = from.getPiece();

        if (piece == null) return false;

        if (piece.getColor() != currentPlayer.getColor()) return false;

        if (!piece.canMove(board, from, to)) return false;

        to.setPiece(piece);
        from.setPiece(null);

        moveHistory.add(move);

        switchTurn();

        return true;
    }

    private void switchTurn() {
        currentPlayer = (currentPlayer == whitePlayer) ? blackPlayer : whitePlayer;
    }
}

Core controller of the chess system. Handles move validation, turn switching, and game state tracking.

The makeMove() method ensures:

  • Piece exists at source
  • Correct player's turn
  • Move is valid according to piece rules
  • Board state is updated after move

The switchTurn() method alternates between players after each valid move.


Main Class


public class Main {

    public static void main(String[] args) {

        Player p1 = new Player("Alice", Color.WHITE);
        Player p2 = new Player("Bob", Color.BLACK);

        Game game = new Game(p1, p2);

        Cell from = game.getBoard().getCell(6, 0);
        Cell to = game.getBoard().getCell(5, 0);

        Move move = new Move(p1, from, to);

        game.makeMove(move);

        System.out.println("Move executed successfully");
    }
}

Entry point of the application that simulates a basic chess move between two players.


Class Diagram

GameBoard boardPlayer whitePlayerPlayer blackPlayerPlayer currentPlayerGameStatus statusList<Move> moveHistorymakeMove(Move) : booleanswitchTurn() : voidBoardCell[][] cellsinitializeBoard() : voidgetCell(int,int) : CellCellint rowint colPiece piecegetPiece() : PiecesetPiece(Piece) : voidPieceColor colorcanMove(Board, Cell, Cell) : booleangetColor() : ColorRookcanMove(Board, Cell, Cell) : booleanQueencanMove(Board, Cell, Cell) : booleanKingcanMove(Board, Cell, Cell) : booleanBishopcanMove(Board, Cell, Cell) : booleanKnightcanMove(Board, Cell, Cell) : booleanPawncanMove(Board, Cell, Cell) : booleanPlayerString nameColor colorgetColor() : ColorMovePlayer playerCell fromCell togetFrom() : CellgetTo() : CellColorWHITEBLACKGameStatusACTIVECHECKMATESTALEMATE

Also See

Comments

Popular posts from this blog

Designing a Parking Lot - Low Level Design

Problem Statement Design a parking lot that can handle vehicles entering and leaving while managing parking across multiple floors. Each vehicle should be assigned a suitable parking spot based on its type, and the spot should be freed once the vehicle exits. The design should also support generating a ticket at entry and optionally calculating the parking fee based on the duration of stay. Asked In Companies Amazon Google Microsoft Uber Walmart Flipkart Meta PayPal Oracle Salesforce Adobe Apple Intuit LinkedIn Atlassian Functional Requirements The design should support multiple vehicle types such as bikes, cars, and trucks A vehicle must be assigned a parking spot compatible with its type A parking spot cannot be assigned to more than one vehicle at a time The parking lot should support multiple levels (floors) The design should search and allocate an availa...

Most Frequently Asked Low Level Design(LLD) Interview Questions

Below are the curated list of most commonly asked Low Level Design (LLD) interview problems. Each problem includes a short description and a link to the complete solution with code and class diagrams. Design Parking Lot System The system should handle parking for different vehicle types such as bikes, cars, and trucks. It should manage slot allocation, availability tracking, and entry/exit flow. The design also ensures efficient usage of parking space under varying load conditions. View Solution Design Elevator / Lift System The system should support multiple elevators operating across floors with request handling logic. It focuses on scheduling algorithms to minimize wait time and optimize movement. It also manages direction control and concurrent floor requests. View Solution Design Movie Ticket Booking System The system should allow users to browse movies, select shows, and book seats. It handles seat ...

Software Design Patterns for LLD Interviews: A Complete Guide

Software Design Patterns for LLD Interviews: A Complete Guide In Software Development Engineer (SDE) interviews—especially for mid-level and senior roles—low-level design (LLD) rounds assess your ability to write clean, reusable, maintainable, and extensible code. The foundation of resolving these architectural challenges lies in the standard Gang of Four (GoF) Design Patterns. Rather than memorizing theoretical definitions, interviewers expect you to apply these patterns to real-world scenarios, identifying the trade-offs of each. Below is a comprehensive guide to the 12 most frequently asked design patterns in LLD interviews, categorized by their classification (Creational, Structural, and Behavioral). Each pattern contains a concrete, real-world Java implementation and a detailed breakdown of design decisions. Creational Design Patterns Creational design patterns deal with object creation mechanisms. They abstract the instantiation process, making a system independent of how...