Search code examples
javaimplementationclass-diagram

Board Game Implementation in Java


First of all, I am not sure whether it is allowed to ask this kind of question. So I am trying to create a board game and I was stuck at the implementation of generating valid moves for Piece. Here is the extract of the class diagram.

Class Diagram

You can think this board game like chess, so we need to know the location of other pieces while generating valid moves. The problem is I have no idea how to check it. Is my class diagram wrong? Or should I check at the board every time I check a square? And how do I do that in Java? Thanks for helping.


Solution

  • The piece should not decide what its valid moves are, it should only be aware of where it is and how it's capable of moving. It is not responsible for that sort of logic.

    The board should manage whether or not that's allowed or not (that is, it takes a piece which returns its possible moves to it, and in turn returns the valid moves).

    The Piece class exposes a getPossibleMoves method that returns the list of positions it can reach:

    public List<Square> getPossibleMoves(){ // might want to differentiate types of moves
    

    Then, the board class has a getValidMoves method that takes a piece and returns its valid moves.

    public List<Square> getValidMoves(Piece piece) {
        return piece.getPossibleMoves().
                     stream(). // and filter by 
                     filter(move -> isOnValidBoardCoordinate(move)). // can shorten
                     filter(move -> doesNotIntersectOtherPiece(move)).
                     filter(move -> otherValidation(move)).
                     collect(Collectors.toList());
    }