尽管 getter 和 setter 无法在 Kotlin 中用方括号填充二维数组

Can't fill 2d-array by brackets in Kotlin despite getter and setter

它应该成为一个小的 consolewalker 程序,但我无法用方括号填充我在 class Field 中 class Player 中创建的二维数组,因为那里尽管有一个应该适合的函数,但 set 函数“有很多参数”。我还了解到在 Kotlin 中甚至没有必要。 所以我有点迷茫,没有进一步。

fun main() {
val gameField = Field()

gameField.buildField()

val player = Player(gameField.field)

gameField.printField()

var input: String? = " "

while (input != "x") {

    println("w: ↑ a: ← s: ↓ d: →")
    input = readLine()
    when (input) {
        "w" -> player.counter = 0
        "a" -> player.counter = 1
        "s" -> player.counter = 2
        "d" -> player.counter = 3
        "x" -> return println("Spiel wird beendet")
        " " -> player.move()
        else -> println("Ungültige Eingabe")
    }
    player.setPlayer()
    gameField.printField()
}

}

class Field() {
private var field = Array(10) {Array(10){" "}}

operator fun set(row: Int, col: Int, value: String) {
    field[row][col] = value
}
operator fun get(row: Int, col: Int) = field[row][col]

fun buildField() {
    for (i in field.indices) {
        field[i][0] = "# "
        field[i][field.size - 1] = "# "
        for (j in 1 until field.size - 1) {
            field[i][j] = "  "
            field[0][j] = "# "
            field[field.size - 1][j] = "# "
        }
    }
}

fun printField() {
    for (i in field.indices) {
        for (j in field[i].indices) {
            print(field[i][j])
        }
        println()
    }
}

}

class Player(private var gameField: Array<Array<String>>) {
private val playerSign = arrayOf<String>("↑ ", "← ", "↓ ", "→ ")
var currentRow = 4
var currentColumn = 4
var counter = 0

init {
    setPlayer()
}

fun setPlayer() {
    gameField[currentRow, currentColumn] = playerSign[counter]
}

fun reset() {
    gameField[currentRow, currentColumn] = "  "
}

fun move() {
    reset()
    when(counter) {
        0 -> if (currentRow > 1) currentRow--
        1 -> if (currentColumn > 1) currentColumn--
        2 -> if (currentRow < gameField.size-2) currentRow++
        3 -> if (currentColumn < gameField.size-2) currentColumn++
    }
    setPlayer()
}

}

提前致谢!

你的代码的问题在于 class Player field 是类型 Field,它不是 array,这就是为什么编译器是给你错误。如果你想访问 Field class 的字段数组,那么你应该做

field.field[3][3] = playerSign[counter]

您可以在语言文档中使用重载 get and set operator (see Operator Overloading | Indexed Access Operator 来扩展 Field class。

class Field() {
  // all your existing code

  operator fun set(row : Int, col : Int,  value : String) {
    field[row][col] = value
  }

  operator fun get(row : Int, col : Int) = field[row][col]
}

如文档所述:

Square brackets are translated to calls to get and set with appropriate numbers of arguments.

因此,您现在可以编写

field[currentRow, currentColumn] = playerSign[counter]

在您的 Player class 中,这比公开/访问数组本身(现在可以而且应该设为私有)更干净。