首页 > 解决方案 > 将苹果放在用 Scala 编写的蛇游戏中

问题描述

要将苹果放在一个空的地方,我使用emptySpots()方法来定位空的或空闲的单元格的点。

当我实现下面的代码时,我的游戏运行良好:

    def emptySpots() : Point = {
        val emptyPointsList = new ArrayBuffer[Point]()
        var emptyLocation : Point = new Point(0,0)
        
        emptyLocation = Point(random.randomInt(upTo = 25), random.randomInt(upTo = 25))
        emptyLocation
      }

但是,当我尝试实现下面的代码时,它会显示错误:

    def emptySpots() : Point = {
        val emptyPointsList = new ArrayBuffer[Point]()
        var emptyLocation : Point = new Point(0,0)

        for(i <- 0 until gridDims.height) {
          for(j <- 0 until gridDims.width) {
            if(getCellType(Point(i, j)) == Empty()) {
              emptyPointsList += Point(i, j)
            }
          }
        }
        if(!emptyPointsList.isEmpty) {
          emptyLocation = emptyPointsList(random.randomInt(emptyPointsList.size))
        }
        emptyLocation
      }

错误是: 在此处输入图像描述

如果有人能指出我的第二个实现中有什么问题,向我展示我的第一个实现可以正常工作的错误,我将不胜感激。

PS这里的randomInt()没有错,因为它被导入的包和库支持

标签: scala

解决方案


推荐阅读