首页 > 解决方案 > 如何检查从已保存位置到玩家当前位置的赏金

问题描述

/**
  * 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

标签: scalafunctiondelegates2d

解决方案


我认为你不使用xyfrom 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,或者您可以使用不可变结构重写代码。


推荐阅读