HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMajor

Design a chess game using object-oriented principles

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
principlesdesignchessgameusingorientedobject

Problem

I would like to know if my approach is correct and how could it could be improved? Also, is there a way to get rid of the relation between the Piece and the Board? At the moment, I am storing the position of the piece both in the piece and on the board. Is there some way to change that?

I have considered a Game to contain an instance of the Board and the two Players (one black, one white). The pieces contain a connection to the Board, because in order to determine if they are valid, we need to know the relationship to other pieces.

Could I use design patterns for this? Should I use interfaces instead of the super class?

Game.java

public class Game {
    private Board board = new Board();
    private Player white;
    private Player black;
    public Game() {
        super();
    }

    public void setColorWhite(Player player) {
        this.white = player;
    }

    public void setColorBlack(Player player) {
        this.black = player;
    }

    public Board getBoard() {
        return board;
    }

    public void setBoard(Board board) {
        this.board = board;
    }

    public Player getWhite() {
        return white;
    }

    public void setWhite(Player white) {
        this.white = white;
    }

    public Player getBlack() {
        return black;
    }

    public void setBlack(Player black) {
        this.black = black;
    }

    public boolean initializeBoardGivenPlayers() {
        if(this.black == null || this.white == null)
            return false;
        this.board = new Board();
        for(int i=0; i<black.getPieces().size(); i++){
            board.getSpot(black.getPieces().get(i).getX(), black.getPieces().get(i).getY()).occupySpot(black.getPieces().get(i));
        }
        return true;
    }

}


Player.java

```
public class Player {
public final int PAWNS = 8;
public final int BISHOPS = 2;
public final int ROOKS = 2;
public boolean white;

private List pieces = new ArrayList<>();

public Pl

Solution

My comments are with respect to design of the game.
I see responsibilities of entities are mixed up in many places

  • Player should not initialize pieces. We can move the responsibility to board. Board and pieces doesn't need to know about players.



  • Pieces should not handle move. Pieces can provide list of possible moves to reach the destination path but board should choose a valid path.



  • Board should have check for "Check Mate" condition.



  • Game should track the players move history and piece color selection.



  • Player class should have only player details.



A rough class diagram is attached below

Context

StackExchange Code Review Q#71790, answer score: 37

Revisions (0)

No revisions yet.