scala - 如何检查从已保存位置到玩家当前位置的赏金
问题描述
/**
* 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
from for loop in 的问题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
,或者您可以使用不可变结构重写代码。
推荐阅读
- php - Laravel 5.5 首次尝试后重定向到登录页面
- notepad++ - Notepad++:禁用旧标签但记住最后一行
- django - 基本模板上的 div 未出现在扩展中
- javascript - .map & .slice 数据集中的唯一值
- node.js - req.body.[name] 未定义
- c - 使用结果偶向量进行高斯归约
- javascript - 便携式电子应用程序每次打开时都会提取到不同的文件夹中
- reactjs - 如何使用带有快照的酶来测试 reduxForm 组件?
- java - java.time.format.DateTimeParseException:无法在索引 2 处解析文本“13.05.2018”
- jquery - 在 jquery 中使用更多的 css 属性