踩地雷程式 Swift Code

給定列數(row)和行數(col)以及全部的地雷個數,寫出踩地雷遊戲

// -1 represents mine
//  N represents mine around the grid, N ∈ [0, 8]
func createGame(row: Int, col: Int, mine_num: Int) -> [[Int]]{
    var map: [[Int]] = Array(repeating: Array(repeating: 0, count: col), count: row)
    for _ in 0 ..< mine_num {
        let (i, j) = generateMine(map, row, col)
        map[i][j] = -1
    }
    for i in 0 ..< row {
        for j in 0 ..< col {
            if map[i][j] != -1 {
                map[i][j] = checkMineNum(map, row, col, i, j)
            }
        }
    }
    return map
}

func generateRandomNum(max: Int) -> Int {
    return Int.random(in: 0 ..< max)
}

func generateMine(_ map: [[Int]], _ row: Int, _ col: Int) -> (Int, Int) {
    var rowIndex = -1
    var colIndex = -1
    repeat {
        rowIndex = generateRandomNum(max: row)
        colIndex = generateRandomNum(max: col)
    } while map[rowIndex][colIndex] == -1
    return (rowIndex, colIndex)
}

func checkMineNum(_ map: [[Int]], _ row: Int, _ col: Int, _ x: Int, _ y: Int) -> Int {
    func isXWithin(_ x: Int) -> Bool {
        return x >= 0 && x < row
    }
    func isYWithin(_ y: Int) -> Bool {
        return y >= 0 && y < col
    }
    var result = 0
    for i in (x - 1) ..< (x + 1) {
        for j in (y - 1) ..< (y + 1) {
            if isXWithin(i) && isYWithin(j) {
                if map[i][j] == -1 {
                    result += 1
                }
            }
        }
    }
    return result
}

func printMineGame(_ map: [[Int]]) {
    for i in 0 ..< map.count {
        var result = ""
        for j in 0 ..< map[i].count {
            let str = String(format:"%2d",map[i][j])
            result += "\(str),"
        }
        print(result)
    }
}

let game = createGame(row: 5, col: 5, mine_num: 5)
printMineGame(game)

Sample Output:

 0, 0, 0, 0, 0,
 0, 0,-1,-1,-1,
-1, 1, 1,-1, 3,
 1, 1, 0, 1, 1,
 0, 0, 0, 0, 0,