gpt4 book ai didi

python - python 中的简化扫雷递归 : why is this code not succeeding?

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:27 26 4
gpt4 key购买 nike

我正在用 python 开发扫雷克隆,但在让揭露功能工作时遇到问题。目前,我收到以下无限错误消息:

File "/Users/home/Desktop/minesweeper.py", line 79, in uncover_cells
uncover_cells(i - 1, j, board)

其中uncover_cells定义如下(编辑:在帖子末尾添加更简单的问题示例):

def uncover_cells(i, j, board):

length = len(board)
width = len(board[0])

if i > -1 and j > -1 and i < length and j < width and not board[i][j].visited:

board[i][j].visited = True

# unproblematic code removed

uncover_cells(i + 1, j, board)
uncover_cells(i - 1, j, board)
uncover_cells(i, j + 1, board)
uncover_cells(i, j - 1, board)

uncover_cells(i + 1, j + 1, board)
uncover_cells(i + 1, j - 1, board)
uncover_cells(i - 1, j + 1, board)
uncover_cells(i - 1, j - 1, board)

return

原来的调用是:

b, locs = setup_game(100, 100, 50)
uncover_cells(0, 0, b)

我认为尚未达到递归限制,并且担心可能存在逻辑错误。任何投入将不胜感激。

其他可能重要的代码:board 的每个元素都是 Cell 类型:

class Cell:

def __init__(self, isMine, loc, visited = False, flagged = False):
self.visited = visited # think of visited as 'uncovered'
self.flagged = flagged
self.isMine = isMine
self.x = loc[0]
self.y = loc[1]

self.label = 0

以下是该板的设置方式:

def setup_game(length, width, n_mines):

idx = [(i, j) for j in range(width) for i in range(length)]
board = [[None for j in range(width)] for i in range(length)]


mine_locs = random.sample(idx, n_mines)

for i, j in idx:

if (i, j) in mine_locs:
board[i][j] = Cell(isMine = True, loc = (i, j))

else:
board[i][j] = Cell(isMine = False, loc = (i, j))

return board, mine_locs

编辑:这是我的问题的最简单的例子:

def simple_fill(i, j, b):


length = len(b)
width = len(b[0])

if i > -1 and j > -1 and i < length and j < width and b[i][j] != 1:

b[i][j] == 1

simple_fill(i + 1, j, b)
simple_fill(i - 1, j, b)
simple_fill(i, j + 1, b)
simple_fill(i, j - 1, b)

simple_fill(i + 1, j + 1, b)
simple_fill(i + 1, j - 1, b)
simple_fill(i - 1, j + 1, b)
simple_fill(i - 1, j - 1, b)

return

原始调用:

b = [[0 for j in range(100)] for i in range(100)]
simple_fill(0, 0, b)

最佳答案

simple_fill()中:

b[i][j] == 1  # You have.
b[i][j] = 1 # Should be.

使用此代码,您的 uncover_cells() 可以工作......但仅适用于较小的 n。之后,我们达到最大递归深度。

class Cell(object):
def __init__(self, i, j):
self.i = i
self.j = j
self.visited = False

def main():
n = 30 # Works ... but not, for example, for 40.
board = [[Cell(i,j) for j in range(n)] for i in range(n)]
uncover_cells(0, 0, board)
for row in board:
for cell in row:
assert cell.visited

main()

关于python - python 中的简化扫雷递归 : why is this code not succeeding?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21668873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com