/**
* Updates saveX and saveY to the current player position.
*/
def save(): Unit = {
saveX = playerX
saveY = playerY
}
/**
* Returns the current save position as a tuple, in (x,y) order.
*/
def getSavePos(): (Int, Int) = {
return (saveX, saveY);
}
def checkBounty() {
if(bounties (playerX)(playerY) != null){
var bounty: Int => Int = bounties(playerX)(playerY)
score = bounty(score)
bounties(playerX)(playerY) == null
}
}
checkBounty()函数检查玩家当前位置的赏金,也就是(playerX, playerY),如果有赏金,就会被收集,然后删除赏金,因此bounties(playerX)(playerY)== null。
/**
* Checks if the rectangle defined by the current position and saved position
* covers nine or more positions. If yes, it collects bounties in it, increases the
* score, and erases the bounties.
*/
def checkBounties() {
if(((playerX - saveX)+1).abs * ((playerY - saveY) + 1).abs >= 9){
for(x <- saveX to playerX; y <- saveY to playerY){
checkBounty();
}
saveX = -1
saveY = -1
}
}
CheckBounties()函数按照注释中说的做,如果覆盖了9个或更多的位置,则将保存位置设为(-1,-1).我试着用for循环来检查从保存位置移动到当前位置后在保存位置和当前位置内的任何赏金,然后我委托checkBounty()函数来检查在保存位置和当前位置之间移动的每个单元格。但是这段代码并不像我预期的那样工作,for循环中的saveX和saveY并不代表保存的X和Y位置,而是saveX是-1,saveY是-1,所以它是在检查从-1到playerX的赏金,但我需要它检查从最后保存的位置到playerX的形式。
我认为问题在于你没有使用 x
和 y
循环往复 checkBounty()
. 也许将它们作为参数传递会解决你的问题。
def checkBounty(x: Int, y: Int): Int = {
if(bounties (x)(y) != null){
val bounty: Int => Int = bounties(x)(y)
score += bounty(score)
bounties(x)(y) == null
}
score
}
def checkBounties() {
if (((playerX - saveX) + 1).abs * ((playerY - saveY) + 1).abs >= 9) {
for (x <- saveX to playerX; y <- saveY to playerY) {
checkBounty(x, y);
}
saveX = -1
saveY = -1
}
}
另外,在scala中,使用可突变语句是不好的做法。如果你想使用可突变变量,我建议你使用 Ref
或者你可以使用不可变结构重写你的代码。