我正在制作一款国际象棋和跳棋棋盘游戏(以及我想做的一些变体)。我有一个 Board 类,它扩展了 JPanel 并设置了一个 JPanel 的双维数组来充当我的板。这是我的板类的一些代码:
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 是一个我将用于所有作品的界面。我已经设置了接口(interface)并设置了一个实现该接口(interface)的类(Checker 类)。我已经把所有这些都设置好了。这些片段是带有 ImageIcons 的 JLabels。到目前为止我遇到的唯一问题是编写 move 方法。我可以弄清楚逻辑以确保 move 是有效的,但我只是不知道如何实际使 move 发生。
编辑:我什至不问鼠标监听器或类似的东西,我只是想要一些伪代码来解释如何将一个 block 从数组中的一个位置 move 到另一个位置。
编辑2:这是我的跳棋类的代码。
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
所以我的想法是我调用西洋跳棋棋子的 move 方法,假设我从屏幕底部 move 到顶部,它将是 piece.move(-1,1);
并且我必须从当前位置删除 piece
,那么它在数组中的新位置是 [x + dx][y + dy]
最佳答案
你能用这样的东西吗:
public void movePiece(Piece piece, int dx, int dy) {
// Save current position, so we can erase the piece.
int oldX = piece.getX();
int oldY = piece.getY();
// Update the location.
piece.setX(oldX + dx);
piece.setY(oldY + dy);
// Remove piece from old position
board[oldX][oldY].clear();
// Add it to the new position.
addPiece(piece);
}
您可能想要使用Point
而不是单独的 x 和 y 坐标;我只是觉得这样会更容易理解。
关于java - 在多维数组中 move 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9510099/