gpt4 book ai didi

java - Scalafx动画计时器导致递归: Possible to avoid that?

转载 作者:行者123 更新时间:2023-11-30 02:28:37 31 4
gpt4 key购买 nike

我正在尝试制作一个使用类 AnimationTimer 来处理它的游戏。我的代码摘要如下所示:

主类

object Game extends JFXApp{

def showMenu{
//code that show the .fxml layout and controller will handle the controller
}

def showInstruction{
//code that show the .fxml instruction
}

def showGame():Unit = {
this.roots.center = {
new AnchorPane(){
children = new Group(){

val timer:AnimationTimer = AnimationTimer(t=> {
//game code

if(playerDie){
timer.stop
val gameOver:AnimationTimer = AnimationTimer(t => {
if(exitPressed){
showMenu
} else if (restartPressed){
restartGame
}
})
gameOver.start
}
})
timer.start
}
}
}
}

def restartGame(){
//show restart layout
}

showMenu()
}

重新启动 Controller

@sfxml
class RestartController(private val countDownLabel:Label){
var lastTimer:Double = 0
var countDownSec:Double = 5.999
val countDown:AnimationTimer = AnimationTimer(t => {
val delta = (t-lastTimer)/1e9
if(delta < 1) countDownSec -= delta
countDownLabel.text = countDownSec.toInt.toString
if(countDownSec <= 0) {
countDown.stop
Game.showGame
}
lastTimer = t
})//end AnimationTimer pauseTimer
countDown.start

//I think Game.showGame should be located at here but tried several ways still can't implement it

}

我有一些变量,例如游戏关卡,它们位于伴生对象中的某个类,所以我想避免递归,因为如果它递归,则会导致关卡结果不一致。

当玩家死亡时,如果用户退出,用户将显示菜单,如果玩家再次按下开始游戏,则伴随对象中的这些变量不会显示任何不一致。

但是,如果玩家按重新启动,它将进入递归,这意味着该方法调用另一个方法,因此旧方法不会结束并说我是否执行类似的操作

ShootingGame.level += 1 //be trigger when certain requirement meet

有时会 += 2 甚至更多

是否有任何解决方案使其不递归,其行为与我退出游戏时完全相同,并且旧的 showGame() 方法将在我开始新游戏之前完全结束?

最佳答案

我通过不回调相同的函数解决了这个问题,而是重新初始化整个程序,如下所示:

射击游戏

class ShootingGame{
def restart:ListBuffer[Circle] = {
var toBeRemove:ListBuffer[Circle]

//initialize and add those needed to be remove into toBeRemove

toBeRemove
}
}

主类

object Game extends JFXApp{

def showMenu{
//code that show the .fxml layout and controller will handle the controller
}

def showInstruction{
//code that show the .fxml instruction
}

def showGame():Unit = {
this.roots.center = {
new AnchorPane(){
children = new Group(){

val timer:AnimationTimer = AnimationTimer(t=> {
//game code

if(playerDie){
timer.stop
val gameOver:AnimationTimer = AnimationTimer(t => {
if(exitPressed){
showMenu
} else if (restartPressed){
for(i <- game.restart) children.remove(i)
timer.start
}
})
gameOver.start
}
})
timer.start
}
}
}
}

showMenu()
}

关于java - Scalafx动画计时器导致递归: Possible to avoid that?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44857721/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com