【发布时间】:2020-11-29 15:44:00
【问题描述】:
所以,我正在使用 JavaFX 创建贪吃蛇游戏,但我似乎无法让游戏正确暂停,即它偶尔会暂停,有时游戏会忽略暂停。所以,基本上我有一个 Main 类,我在其中初始化所有 GUI 组件,它还充当 javafx 应用程序的控制器。
我有一个名为gameControl 的Button 用于启动/暂停游戏,一个变量Boolean pause 用于跟踪游戏状态(新建/暂停/运行),以及方法startGame、pauseGame .
gameControl按钮的EventHandler如下:
gameControl.setOnClicked(event->{
if(paused == null) startGame(); //new game
else if(paused) continueGame(); //for paused game
else pauseGame(); //for running game
});
startGame 函数看起来像这样:
void startGame(){
paused = false;
Snake snake = new Snake(); //the snake sprite
//following gameLoop controls the animation of the snake
gameLoop = new AnimationTimer(){
@Override
public void handle(long now){
drawSnake(); //draws the snake on the game
snake.move(); //move snake ahead
//following code is for slowing down the gameLoop renders to make it easier to play
Task<Void> sleeper = new Task<>(){
@Override
protected Void call() throws Exception {
gameLoop.stop();
Thread.sleep(30);
gameLoop.start();
return null;
}
};
new Thread(sleeper).start();
//force garbage collection or else throws a bunch of exceptions after a while of running.
//not sure of the cause...
System.gc();
}
};
gameLoop.start();
}
AnimationTimer gameLoop 是类的变量,允许从其他函数调用。
还有pauseGame 函数:
void pauseGame() {
paused = true;
gameLoop.stop();
}
所以,正如我之前所说,每次我点击gameControl 按钮时游戏都不会暂停,我怀疑这是由于gameLoop 的Task 内的Thread.sleep(30); 行所致。话虽如此,我仍然不完全确定,也不知道如何解决这个问题。任何帮助将不胜感激。
【问题讨论】:
标签: java javafx task java-threads