首页 > 解决方案 > 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);
    }

标签: javajavafx

解决方案


如果要在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;
}

推荐阅读