首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Kotlin Minesweeper中的几乎无限环

Kotlin Minesweeper中的几乎无限环
EN

Stack Overflow用户
提问于 2022-06-14 09:39:24
回答 1查看 90关注 0票数 0

我正在扫雷船项目在JetBrainsAcademy工作。我得到了错误In this test, the program is running for a long time, more than 15 seconds. Most likely, the program has gone into an infinite loop.,我猜想,函数setMines()几乎有不定式循环,但是我不能处理这个问题。你能告诉我布设地雷的更好的解决办法吗?

代码语言:javascript
复制
package minesweeper

import kotlin.random.Random

const val SIZE = 9

fun main() {
    println("How many mines do you want on the field?")
    val numberOfMines = readln().toInt()

    println(Board(SIZE))

    println("Set/unset mine marks or claim a cell as free:")
    val (x, y, _) = readln().split(" ")
    val board = Board(SIZE, numberOfMines, mapOf("x" to x.toInt() - 1, "y" to y.toInt() - 1))

    while (board.isNotWon()) {
        println("Set/unset mine marks or claim a cell as free:")
        val (x, y, action) = readln().split(" ")

        val notMine = Pair(x.toInt() - 1, y.toInt() - 1)

        when (action) {
            "free" -> {
                if (board.checkCell(notMine.first, notMine.second)) board.endGame()
                else board.explore(notMine.first, notMine.second)
            }
            "mine" -> {
                board.toggleMarking(notMine.first, notMine.second)
            }
        }
        println(board)
    }
    println(board)
    println("Congratulations! You found all the mines!")
}

data class Cell(private val x: Int, private val y: Int, var isMine: Boolean = false) {
    private var number = 0
    var isMarked = false
    var isExplored = false

    fun add() = number++

    fun notHasMinesAround(): Boolean = number > 0

    fun makeMine() {
        isMine = true
    }

    fun toggleMark() {
        isMarked = !isMarked
    }

    fun explore() {
        isExplored = true
        isMarked = false
    }

    fun showMine() {
        if (isMine) explore()
    }

    override fun toString(): String {
        return if (isMarked) "*" else if (!isExplored) "." else if (isMine) "X" else if (number == 0) "/" else number.toString()
    }

    fun isNotMine(): Boolean = !isMine

}

data class Board(
    override val size: Int, val numberOfMines: Int = 0, val notMine: Map<String, Int> = emptyMap()
) : MutableList<MutableList<Cell>> by mutableListOf(mutableListOf()) {

    private val mines = mutableSetOf<Cell>()
    private val markedCells = mines
    private val unExploredCells = mines

    init {
        this.clear()
        for (x in indices) {
            val line = mutableListOf<Cell>()
            for (y in indices) {
                line.add(Cell(x, y))
                unExploredCells.add(line[y])
            }
            this.add(line)
        }
        setMines()
        if (notMine.isNotEmpty()) this[notMine["x"]!!][notMine["y"]!!].explore()

    }


    private fun setMines() {
        var minesToSet = numberOfMines

        while (minesToSet != 0) {
            val x = Random.nextInt(0, SIZE - 1)
            val y = Random.nextInt(0, SIZE - 1)

            val cell = this[x][y]
            if (!cell.isMine && x != notMine["x"] && y != notMine["y"]) {
                cell.makeMine()
                minesToSet--
                mines.add(cell)
                for (row in arrayOf(x - 1, x, x + 1)) {
                    if (row in indices) for (column in arrayOf(
                        y - 1, y, y + 1
                    )) if (column in indices) this[row][column].add()
                }
            }
        }
    }

    fun checkCell(x: Int, y: Int): Boolean = this[x][y].isMine

    fun toggleMarking(x: Int, y: Int) {
        val y = y - 1
        val cell = this[x][y]
        cell.toggleMark()
        if (cell.isMarked) markedCells.add(cell)
        else markedCells.remove(cell)

    }


    fun endGame() {
        this.forEach { it -> it.forEach { it.showMine() } }
        println("You stepped on a mine and failed!")
    }

    fun explore(x: Int, y: Int) {
        val cell = this[x][y]
        if (!cell.isExplored) {
            cell.explore()
            unExploredCells.remove(cell)

            for (row in arrayOf(x - 1, x, x + 1)) {
                if (row in this.indices)
                    for (column in arrayOf(y - 1, y, y + 1)) {
                    if (column in this.indices && cell.isNotMine() && cell.notHasMinesAround())
                        this[row][column].explore()
                }
            }
        }
    }

    fun isNotWon(): Boolean = !(markedCells == mines || unExploredCells == mines)

    override fun toString(): String {
        var output = " │123456789│\n—│—————————│\n"
        for (i in indices) output += this[i].joinToString(separator = "", prefix = "${i + 1}│", postfix = "|\n")

        output += "—│—————————│"
        return output

    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-14 10:36:37

if (!cell.isMine && !(x == cannotBeMine["x"] && y == cannotBeMine["y"]))

  • Generating到if (!cell.isMine && x != notMine["x"] && y != notMine["y"])
  1. 条件从Random.nextInt(0, SIZE - 1)Random.nextInt(0, SIZE)感谢@marstran和@Ivo
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72614760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档