我在scala中有一个数组:
var walls: Array[LineSprite] = new Array[LineSprite](26)
然后我有这些if语句:
if(curPlayer.intersects(walls(0))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(1))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(2))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(3))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(4))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(5))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(6))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(7))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(8))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(9))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(10))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(11))) {
handleCollision
updateLives(-1)
}
...
我怎样才能为数组中调用handleCollision和updateLives(-1)的每个项设置单独的if语句,而不是为数组中的所有项只有一个if语句? / p>
谢谢。
答案 0 :(得分:3)
我认为这应该可以解决你的问题
walls.foreach(w => if (curPlayer.intersects(w)) {
handleCollision
updateLives(-1)
})
我想要你也可以使用带有下划线的更短解决方案
walls.foreach(if (curPlayer.intersects(_)) {...})
除了更简洁的语法之外,它不会给你任何东西