java - JavaFX 使用 GridPane 创建游戏板
问题描述
当应用程序运行时,游戏板显示正常,尽管单击图块时,文本始终显示在板的左上角 [0][0]。
我也在为逻辑而苦苦挣扎。我有一个带有 makeMove 函数的 int 棋盘矩阵,可以将玩家移动到矩阵中,尽管我无法让玩家在矩阵上移动并在图块索引上打印相应的“O”。
我将如何创建一个可以传递行、列索引并更改棋盘矩阵并在 GUI 上打印玩家棋子的函数(例如用于 AI 移动)
并且当玩家单击 GUI 瓷砖时,也会进行相应的移动。
到目前为止,我已经创建了一个 GridPane 并在 GUI 的每个索引处添加了带有文本的 Rectangle。
我创建了一个 Board 类,它构造一个 int 棋盘矩阵来保存玩家移动(P1,P2,空)。
public class Board {
private int[][] board_matrix;
private int board_size;
private int win_length;
public Board(int board_size, int win_length) {
this.board_matrix = new int[board_size][board_size];
this.board_size = board_size;
this.win_length = win_length;
for (int i = 0; i < board_size; i++) {
for (int j = 0; j < board_size; j++) {
this.board_matrix[i][j] = 0;
}
}
}
public void make_move(int player, int x_pos, int y_pos) {
if (player == 1) board_matrix[x_pos][y_pos] = 1;
else board_matrix[x_pos][y_pos] = 2;
}
public class BoardGUI_ extends Application {
private final int BOARD_SIZE = 15;
public Parent createBoard() {
GridPane gameBoard = new GridPane();
gameBoard.setPrefSize(755, 755);
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
Rectangle tile = new Rectangle(50, 50);
tile.setFill(Color.BURLYWOOD);
tile.setStroke(Color.BLACK);
Text text = new Text();
text.setFont(Font.font(40));
GridPane.setRowIndex(tile, i);
GridPane.setColumnIndex(tile, j);
tile.setOnMouseClicked(event -> drawMove(text));
gameBoard.getChildren().addAll(tile, text);
}
}
return gameBoard;
}
public void drawMove(Text text) {
text.setText("O");
text.setFill(Color.BLACK);
}
解决方案
如果要在Text
对象顶部添加对象,则将Rectangle
两者都包装在 a 中StackPane
:
public Parent createBoard() {
GridPane gameBoard = new GridPane();
gameBoard.setPrefSize(755, 755);
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
Rectangle tile = new Rectangle(50, 50);
tile.setFill(Color.BURLYWOOD);
tile.setStroke(Color.BLACK);
Text text = new Text();
text.setFont(Font.font(40));
gameBoard.add(new StackPane(tile, text), j, i);
//GridPane.setRowIndex(tile, i);
//GridPane.setColumnIndex(tile, j);
//gameBoard.getChildren().addAll(tile, text);
tile.setOnMouseClicked(event -> drawMove(text));
}
}
return gameBoard;
}
推荐阅读
- oracle - 从 UPDATE 子查询调用 Oracle 关联数组会导致 PLS-00201 错误
- php - 显示包含所有类别列表的 ACF 类别分类字段
- rust - 在 Rust `Default` 实现中只设置一个字段
- python - 熊猫无法使用公式从单元格中获取值
- cookies - 邮递员 - 如何在没有任何 cookie 的情况下使用 pm.sendRequest?
- optimization - 在 Julia 中使用 Nelder Mead 算法时出现域错误
- arrays - 使用不打印值的 int 函数从数组中返回最大数
- python - 在 windows 终端中打开特定的图像路径并运行 script.py
- python - 为什么将列表转换为字典在 python 中不起作用?
- python - 在 Python 中使用具有 NaN 列的 mplfinance 绘制财务图