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

Chess Architecture

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

Problem

I am currently developing a chess game but have made the mistake of putting all my Java code in one .java file.

I need help cutting up my code into more manageable chucks. Could someone show me how to take out all the piece movements and put them in a separate file which then links back in to the main file? I have tried myself but I end up just breaking the game.

Here is the full messy Java file currently I only have some of the pieces coded up so I thought I would not go further without solving the terrible architecture here.

```
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class ChessProject extends JFrame implements MouseListener, MouseMotionListener {

JLayeredPane layeredPane;
JPanel chessBoard;
JLabel chessPiece;
int xAdjustment;
int yAdjustment;
int startX;
int startY;
int initialX;
int initialY;
JPanel panels;
JLabel pieces;

public ChessProject() {
Dimension boardSize = new Dimension(600, 600);

// Use a Layered Pane for this application
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(this);
layeredPane.addMouseMotionListener(this);

//Add a chess board to the Layered Pane
chessBoard = new JPanel();
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout(new GridLayout(8, 8));
chessBoard.setPreferredSize(boardSize);
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);

for (int i = 0; i = 0) || (startX + 1 = 0))))) {
if (checkWhiteOponent(e.getX(), e.getY())) {
validMove = true;
if (startY == 6) {
success = true;
}
} else {
validMove = fal

Solution

You should separate the modelling of the game, board and pieces from the display components. (google: model-view-controller, separation of concerns).

  • You can create a Game class that models the game and the game-logic



  • You can create a Board class that models the internal state of the chess-board.



  • You can create a Piece class and subclasses for each Piece, e.g. Rook, King



  • You can create a Display class that uses this model to display a Board



All the UI interaction can be done in the Display class.
All the game-logic should be in the Game class and should ask stuff from the Board. For example the check.. methods should go there.
The movement checks can go into the Piece subclasses.

Context

StackExchange Code Review Q#68853, answer score: 11

Revisions (0)

No revisions yet.