Scala 返回多维数组

Scala returning multi-dimensional arrays

我正在尝试在 Scala 中制作一个简单的扫雷游戏,并且我正在尝试制作一种调用嵌套方法以将地雷随机放置到网格中的方法。

我在 Array 上使用 ofDim 方法使其成为多维的,效果很好,直到我将其指定为方法 return 类型。我得到的错误是:

type ofDim is not a member of Object Array

代码如下:

class GridBuilder(x:Int, y:Int, mines:Int) {
  def generateGrid: Array.ofDim[String](x, y) = {
    def placeMines(mineLocations: Array.ofDim[String](x, y)): Array.ofDim[String](x, y) = {
      val xcoord = Random.nextInt(x)
      val ycoord = Random.nextInt(y)
      if (mineLocations.count(_ ==  "Bomb") == mines)
        mineLocations
      else if (mineLocations(xcoord) (ycoord) contains "Mine")
        placeMines(mineLocations)
      else 
        placeMines(mineLocations(xcoord)(ycoord) = "Mine")
      }
    placeMines(new Array.ofDim[String](x, y))
  }
}

我在任何地方都没有找到任何关于 returning 多维数组的信息。这在 Scala 中可能吗?我在这里错过了什么?

  1. Array.ofDim是方法,不是类型,
  2. 如果你看看它是怎样的 implemented,它是一堆重载方法,每个方法都有不同的 return 类型。在你的情况下 Array[Array[String]].

我拼凑了一个简单的小例子,这样你就可以比较你最终得到的结果。它绝不是完美的,并且不包括无效的用户输入或游戏结束等,但无论如何它就在这里。

import scala.annotation.tailrec
import scala.util.Random

sealed trait GridValue
case object Bomb extends GridValue
case object Empty extends GridValue
case object Checked extends GridValue

case class Grid(private var grid: List[List[GridValue]]){
  def click(x: Int, y: Int): String = {
    grid(x)(y) match {
      case Bomb    => "BOOM! You lose!"
      case Empty   =>
        grid = grid.updated(x, grid(x).updated(y, Checked))
        "No bomb! Good Job"
      case Checked => "You've already clicked here!"
    }
  }
}

object Grid{
  def buildGrid(x: Int, y: Int, mines: Int): Grid = {
    @tailrec
    def placeMines(grid: List[List[GridValue]] = List.fill(x)(List.fill(y)(Empty)), minesRemaining: Int = mines): List[List[GridValue]] = {
      if(minesRemaining == 0) {
        grid
      } else {
        val xcoord = Random.nextInt(x)
        val ycoord = Random.nextInt(y)
        grid(xcoord)(ycoord) match {
          case Bomb => placeMines(grid, minesRemaining)
          case Empty => placeMines(grid.updated(xcoord,grid(xcoord).updated(ycoord, Bomb)), minesRemaining - 1)
        }
      }
    }
    Grid(placeMines())
  }
}

//Start game: val game = Grid.buildGrid(100, 100, 5)

//Click: game.click(10, 10)