Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP desing, Java Swing, chess game, instanceof

OK, I'm in the process of making a simple java swing chess game. This question is more about OOP design then Java Swing.

I have the following:

  • I have a Panel class that implements JPanel.
  • I then have an abstract class Piece that extends from my Panel class
  • Then I have my classes for the different Pieces: Pawn, King, Bishop etc that extend from my Pieces class

In my main ChessGame Class:

  • I am using an array of Panel to store the layout of my board
  • So the array will store, Panel objects, for board places with no pieces on it.
  • And it will store, the subclasses such as Pawn, Queen, Bishop etc (board places with pieces)

So, the top left square (0,0) maps to myArray[0][0]

My problem is that, to check if the place is empty or has chess pieces in it I have to use:

        if(panels[x][y] instanceof Piece){
            ((Piece)panels[x][y]).makeMove();
        }

What I'm asking is this terrible design? I know I should try and stay away from instanceof. What would be a better approach?

Thanks.

like image 771
user1543871 Avatar asked Oct 02 '22 04:10

user1543871


1 Answers

You shouldn't combine the Model code (Piece) with the view code (JPanels). If you ever want to change how the board is displayed you have to change how pieces are stored!

A better design might be to separate Piece from JPanels. Then you can use a single JPanel to display a matrix of Pieces : Pieces[8][8].

My problem is that, to check if the place is empty or has chess pieces in it I have to use:

If you use a matrix, you can just have a null cell or use the Null Object Pattern to have an "empty" piece.

EDIT

Each cell in the piece matrix is a square in the board so piece[0][0] would be the top corner of the board (A8).

To paint the board your paintComponent() method would have to iterate over this matrix and draw each cell appropriately. There are several ways to implement this:

  1. You would need to do a similar instanceof check to draw each type of piece differently

  2. Make a new intermediate "paint strategy" object using the strategy pattern. This may require a matrix of strategy objects instead of piece objects. You may still need to do instance of checks, but maybe only the once to create the strategy objects.

like image 189
dkatzel Avatar answered Oct 07 '22 20:10

dkatzel