使用Python增加扫雷中的相邻地雷

问题描述 投票:0回答:1

我目前正在努力让与地雷(#)相邻的单元格根据其旁边的地雷数量来增加。

我当前的代码返回 0 而不是递增 - 请有人帮忙吗?

我遇到的主要问题是我的 border_check 函数正在计算但没有将计数存储到我的 new_grid 变量

positions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]

mine = "#"
dash = 0
grid = [
    ["-", "-", "-", "#", "#"],
    ["-", "#", "-", "-", "-"],
    ["-", "-", "#", "-", "-"],
    ["-", "#", "#", "-", "-"],
    ["-", "-", "-", "-", "-"],
]

def minesweeper(grid):
    new_grid = [[[dash, mine][col_i == mine] for col_i in row] for row in grid]
    def border_check(new_grid):
        for row_i, row in enumerate(grid):
            for col_i, value in enumerate(row):
                for dr, dc in positions:
                    def increment(new_grid):
                        if row_i + dr in range(len(value)) and col_i + dc in range(
                        len(row)
                    ):
                            if (
                            new_grid[row_i + dr][col_i + dc] == mine
                            and grid[row_i][col_i] != mine
                        ):
                                new_grid[row_i][col_i] +=1
                        return increment(new_grid)
        return border_check(new_grid)
    def minesweeper_output(new_grid):
        for row in new_grid:
            for col_i in row:
                print(col_i, end=" ")
            print()
    return minesweeper_output(new_grid)
minesweeper(grid)

这是我需要的输出:

1 1 2 # # 
1 # 3 3 2 
2 4 # 2 0
1 # # 2 0
1 2 2 1 0
python increment minesweeper
1个回答
0
投票

您的扫雷函数实际上并未评估除

minesweeper_output(new_grid)
之外的任何函数。我们需要清理一些东西。首先,要执行函数,您不应该调用
return
。其次,调用被放置在定义的函数内部而不是之后,因此它们根本不会被执行。这里最简单的修复方法是左移
return increment(new_grid)
return increment(new_grid)
,并删除返回调用。这至少可以让你的代码完全执行。

我还从内部删除了一些函数定义

minesweeper()
以增加可读性。我留下了
increment()
的想法,即您可能不想将所有这些值传递给它,因此如果函数是在
border_check()

的范围内定义的,那么它会更容易
positions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]

mine = "#"
dash = 0
grid = [
    ["-", "-", "-", "#", "#"],
    ["-", "#", "-", "-", "-"],
    ["-", "-", "#", "-", "-"],
    ["-", "#", "#", "-", "-"],
    ["-", "-", "-", "-", "-"],
]

def minesweeper_output(new_grid):
    for row in new_grid:
        for col_i in row:
            print(col_i, end=" ")
        print()

def border_check(new_grid):
    def increment(new_grid):
        if row_i + dr in range(len(value)) and col_i + dc in range(len(row)):
            if new_grid[row_i + dr][col_i + dc] == mine and grid[row_i][col_i] != mine:
                new_grid[row_i][col_i] +=1

    for row_i, row in enumerate(grid):
        for col_i, value in enumerate(row):
            for dr, dc in positions:
                increment(new_grid)

def minesweeper(grid):
    new_grid = [[[dash, mine][col_i == mine] for col_i in row] for row in grid]
    border_check(new_grid)
    minesweeper_output(new_grid)


minesweeper(grid)

这个问题还没有解决,因为增量没有正确计算每个地雷,但我将把它留给你来解决。

© www.soinside.com 2019 - 2024. All rights reserved.