I'm working on making a board game for chess and checkers (and a few variations that I want to make). I've got a Board class that extends JPanel and sets up a doubly dimensioned array of JPanels to act as my board. Here's some of the code for my board class:
public class Board extends JPanel {
private static final int COLS = 8;
private static final int ROWS = 8;
private JPanel[][] board = new JPanel[COLS][ROWS];
private JPanel chessBoard;
public Board() {
super();
super.setLayout(new BorderLayout());
chessBoard = new JPanel();
chessBoard.setLayout(new GridLayout(COLS,ROWS));
// Set up JPanels on bottom and right to display letters and numbers for the board
// JPanels are called south and west
super.add(chessBoard, BorderLayout.CENTER);
super.add(south, BorderLayout.SOUTH);
super.add(west, BorderLayout.WEST);
for (int i=0; i<COLS; i++) {
for (int j=0; j<ROWS; j++) {
// Set up the grid
board[i][j] = new JPanel();
board[i][j].setBackground(getColor(i,j));
chessBoard.add(board[i][j]);
}
}
super.validate();
}
private Color getColor(int x, int y) {
if ((x + y) % 2 == 0) {
return Constants.GOLD;
} else {
return Constants.PURPLE;
}
}
public void addPiece(Piece piece) {
JLabel p = piece.getImage();
board[piece.getX()][piece.getY()].add(p);
chessBoard.validate();
}
}
Piece is an interface that that I'm going to use for all my pieces. I've set up the interface and set up one class that implements the interface (Checker class). I have all of that set up. The pieces are JLabels with ImageIcons in them. The only problem I'm having so far is writing a move method. I can figure out the logic make sure a move is a valid one, I just don't know how to actually make the move happen.
EDIT: I'm not even asking about mouse listeners or anything like that, I just want some pseudocode to explain making a piece move from one spot in the array to another.
EDIT 2: Here's the code for my Checkers class.
public class Checker implements Piece {
private int side,xPos,yPos;
private JLabel img;
public Checker(int team, int x, int y) {
BufferedImage image;
try {
if (team == 0)
image = ImageIO.read(new File("img/RedPiece.png"));
else
image = ImageIO.read(new File("img/BlackPiece.png"));
} catch(IOException e) {
image = null;
System.out.printf("Image file wasn't found!!!");
System.exit(1);
}
img = new JLabel(new ImageIcon(image), SwingConstants.CENTER);
img.setVerticalAlignment(SwingConstants.CENTER);
xPos = x;
yPos = y;
}
// TODO Figure out move method
public void move(int dx, int dy) {
}
// Also typical gets and sets for instance variables
So my thought is I call the move method for a checkers piece and, assuming I'm moving from the bottom of the screen to the top it would be piece.move(-1,1); and I have to remove the piece from it's current position, then it's new position in the array is [x + dx][y + dy]