使用Kotlin为迷宫游戏创建二维数组

时间:2019-06-07 00:50:36

标签: android arrays class matrix kotlin

所以我有一个叫做Cell的类,我想创建一个Cell的对象矩阵,但是我陷入了困境,这就是我到目前为止所获得的,并且它无法正常工作

如何正确执行此操作?谢谢

class GameView(context: Context?, attrs: AttributeSet?) : 
View(context, attrs) {

private val COLS:Int = 7
private val ROWS: Int = 10


fun createMaze(){

    //this gives me an error Type inference failed. Expected type 
    //mismatch: 
    //required:
    //Array<Array<Cell>>
    //found:
    //Array<IntArray>

    var cells: Array<Array<Cell>>  = Array(COLS, {IntArray(ROWS)})

    for(x in 0..COLS){
        for(y in 0..ROWS){
            cells[x][y] = Cell(x,y)
        }
    }

}

}

class Cell(var col:Int, var row: Int){
    var topWall = true
    var leftWall = true
    var bottomWall = true
    var rightWall = true

}

1 个答案:

答案 0 :(得分:1)

您将单元格类型定义为Array<Array<Cell>>,但初始化为Array<IntArry>

我认为只有很小的变化:

   class Cell(var col:Int=0, var row: Int=0){
        var topWall = true
        var leftWall = true
        var bottomWall = true
        var rightWall = true

    }
   var cells: Array<Array<Cell>>  = Array(COLS, {Array<Cell>(ROWS, {Cell()})})