我想制作一个使用类AnimationTimer来处理它的游戏。我的代码的摘要看起来是这样的:导致递归的Scalafx动画计时器:可以避免这种情况吗?
主类
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()
}
RestartController
@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()方法将完全结束之前,我开始一个新的?