等到按下任何按钮?

时间:2018-02-17 10:21:52

标签: button javafx timer wait tic-tac-toe

我正在JavaFX中编写TicTacToe游戏。我已决定将一块电路板设为9(3x3)个按钮,其中包含更改文字:"" (如果是空的)或" X"或者" O"。除了一件事,一切都还好......我被困在这里:

numpy

如何等待用户按下这9个按钮中的任何一个,然后继续计算机转动?

我需要在控制台应用程序中等待扫描仪输入,但此输入必须是9个按钮之一......

我知道很少有"可能重复",但实际上这些问题是使用我在这里不能使用的方法解决的,例如计时器。如果我错了,请纠正我。

1 个答案:

答案 0 :(得分:0)

不应该在JavaFX中阻止应用程序线程,因为它冻结了UI。因此,像这样的循环不适合JavaFX应用程序。相反,你应该对用户输入做出反应:

public void game() {
    if (keepPlaying && computerTurn) {
        computerMove();
        if (checkResult()) {
            keepPlaying = false;
        }
        computerTurn = false;
    }
}

// button event handler
private void button(ActionEvent event) {
    if (keepPlaying) {
        Button source = (Button) event.getSource();

        // probably the following 2 coordinates are computed from GridPane indices
        int x = getX(source);
        int y = getY(source);

        // TODO: update state according to button pressed

        if (checkResult()) {
            keepPlaying = false;
        } else {
            computerMove();
            if (checkResult()) {
                keepPlaying = false;
            }
        }
    }

}

从javafx 9开始,有一个用于在应用程序线程上“暂停”的公共API:

private static class GridCoordinates {
    int x,y;
    GridCoordinates (int x, int y) {
        this.x = x;
        this.y = y;
    }
}

private final Object loopKey = new Object();

public void game() {
    while(keepPlaying) {
        if(computerTurn) {
            computerMove();
        } else {
            // wait for call of Platform.exitNestedEventLoop​(loopKey, *)
            GridCoordinates coord = (GridCoordinates)  Platform.enterNestedEventLoop​(loopKey);

            // TODO: update state
        }

        if (checkResult()) {
            keepPlaying = false;
        }
        computerTurn = !computerTurn;
    }
}

private void button(ActionEvent event) {
    if (keepPlaying) {
        Button source = (Button) event.getSource();

        // probably the following 2 coordinates are computed from GridPane indices
        int x = getX(source);
        int y = getY(source);

        Platform.exitNestedEventLoop​(loopKey, new GridCoordinates(x, y));
    }
}