python - 获取 RecursionError:比较超过最大递归深度
问题描述
在 pygame 中创建扫雷游戏,运行代码时出现递归错误。我该如何减轻这种情况?这是我拥有的代码,用于检查单击的网格方块是否为空,如果是,则它会显示该网格方块以及所有相邻的方块。出现此错误的部分如下:
def reveal_empty(rn,c, grid, revealed,box):
if grid[rn][c] != '0' and grid[rn][c] != '*':
revealed[rn][c] = True
if grid[rn][c] == '0':
revealed[rn][c] = True
# change row above
if rn-1 > -1:
r = grid[rn-1]
if c-1 > -1:
if not r[c-1] == '*':
revealed[rn-1][c-1] = True
reveal_empty(rn-1,c-1, grid, revealed,box)
if not r[c] == '*':
revealed[rn-1][c] = True
reveal_empty(rn-1,c, grid, revealed,box)
if c+1 < 10:
if not r[c+1] == '*':
revealed[rn-1][c+1] = True
reveal_empty(rn-1,c+1, grid, revealed,box)
#change same row
r = grid[rn]
if c-1 > -1:
if not r[c-1] == '*':
revealed[rn][c-1] + True
reveal_empty(rn,c-1, grid, revealed,box)
if c+1 < 10:
if not r[c+1] == '*':
revealed[rn][c+1] = True
reveal_empty(rn,c+1, grid, revealed,box)
#change row below
if rn+1 < 11:
r = grid[rn + 1]
if c-1 > -1:
if not r[c-1] == '*':
revealed[rn+1][c-1] = True
reveal_empty(rn+1,c-1, grid, revealed,box)
if not r[c] == '*':
revealed[rn+1][c] = True
reveal_empty(rn+1,c, grid, revealed,box)
if c+1 < 11:
if not r[c+1] == '*':
revealed[rn+1][c+1] = True
reveal_empty(rn+1,c+1, grid, revealed,box)
解决方案
我猜你有这个问题,因为你的递归函数没有快速退出子句。我怀疑因为您不检查单元格是否已经显示(revealed[row][col] == True
),所以它永远不会退出 - 它会不断递归处理队列(堆栈)中已经完成一半的单元格。
也许在函数开头的快速检查会解决它:
def reveal_empty( row, col, grid, revealed, box ):
if ( revealed[row][col] == False ):
# do recursive check else here!
else:
print("Cell[%d][%d] is already revealed" % ( row, col ) )
推荐阅读
- visual-studio-code - typescript IntelliSense 在我的 vscode 中不起作用
- python-3.x - Pandas 使用 MultiIndex 重新排列列
- android - 从 Android 上的 Firebase Analytics 中排除年龄、性别和地区
- javascript - 异步调用一直返回失败处理程序
- php - PHP 警告除以零
- python-3.x - 在 docker 容器中运行 pip install 适用于每个 python 包,除了依赖注入器
- angular - 按字母顺序排列下拉菜单
- python - ValueError:为 pd df 和 np.array 设置具有序列的数组元素
- android - Camera2 API 在 android Marshmallow 中不起作用
- excel - 无法将表格移动到 Workbook_SheetBeforeDelete 事件中的隐藏工作表