在scala我有这个功能:
def handleCollision {
walls.foreach(w => if (curPlayer.intersects(w)) {
curPlayer.setLocation(playerStartPos._1, playerStartPos._2)
updateLives(-1)
})
obstacles.foreach(o => if (curPlayer.intersects(o)) {
curPlayer.setLocation(playerStartPos._1, playerStartPos._2)
updateLives(-1)
})
} // End "handleCollision"
我想要做的是当一名玩家在我的比赛声明中点击“c”键时:
case 'c' =>
我希望它调用此函数并覆盖上面的函数,使其不再起作用:
def cheatKey {
walls.foreach(w => if (curPlayer.intersects(w)) {
updateLives(+0)
})
obstacles.foreach(o => if (curPlayer.intersects(o)) {
updateLives(+0)
})
}
谢谢
答案 0 :(得分:2)
你可以先声明一个var
来保存处理冲突的默认函数,如下所示:
var collisionFunction = () => {
curPlayer.setLocation(playerStartPos._1, playerStartPos._2)
updateLives(-1)
}
然后,您的handleCollision函数将更改为:
def handleCollision {
walls.foreach(w => if (curPlayer.intersects(w)) {
collisionFunction()
})
obstacles.foreach(o => if (curPlayer.intersects(o)) {
collisionFunction()
})
}
然后,当你遇到作弊情况时,你会像这样更新collisionFunction:
collisionFunction = () => {
updateLives(+0)
}
这有点粗糙,因为它有一个可变的函数交换变量,但它适用于你想要做的事情。
答案 1 :(得分:1)
您可以引入var f
,初始化为
f = handleCollision
然后在你的案例陈述集
f = cheatKey
使用f
,您可以使用cheatKey
或handleCollision
。
这基本上是Strategy pattern。
答案 2 :(得分:1)
子类然后:
override def handleCollision = {
if (cheat) cheatKey else super.handleCollision
}