python - 在没有函数的python中实现扫雷显示的问题
问题描述
我正在为一个项目制作游戏扫雷,但在游戏的显示部分遇到了问题(如果输入任何周围有 0 个地雷的单元格的坐标,那么游戏应该继续显示相邻的瓷砖除非达到非零单元格值)。我也为此在互联网上搜索过,但找不到任何合适的解决方案(我不允许使用函数,因为它不是今年课程的一部分)。有人可以提供任何关于我如何在 python 中实现它的见解。
PS作为参考,您可以查看此代码
def neighbours(r, col):
global mine_values
global numbers
global vis
# If the cell already not visited
if [r,col] not in vis:
# Mark the cell visited
vis.append([r,col])
# If the cell is zero-valued
if numbers[r][col] == 0:
# Display it to the user
mine_values[r][col] = numbers[r][col]
# Recursive calls for the neighbouring cells
if r > 0:
neighbours(r-1, col)
if r < n-1:
neighbours(r+1, col)
if col > 0:
neighbours(r, col-1)
if col < n-1:
neighbours(r, col+1)
if r > 0 and col > 0:
neighbours(r-1, col-1)
if r > 0 and col < n-1:
neighbours(r-1, col+1)
if r < n-1 and col > 0:
neighbours(r+1, col-1)
if r < n-1 and col < n-1:
neighbours(r+1, col+1)
# If the cell is not zero-valued
if numbers[r][col] != 0:
mine_values[r][col] = numbers[r][col]
链接 - https://www.askpython.com/python/examples/create-minesweeper-using-python
解决方案
这应该有效:
#before main loop
shifts = [
(-1,-1),
(-1, 1),
(-1, 0),
( 1,-1),
( 1, 1),
( 1, 0),
( 0,-1),
( 0, 1),
]
#main loop
to_reveal = []
if (x,y) not in vis:
to_reveal.append((x,y))
while to_reveal != []:
cell = to_reveal.pop()
vis.append(cell)
if board[cell[1]][cell[0]] == 0:
for shift in shifts:
if (cell[0] + shift[0],cell[1] + shift[1]) not in vis and 0 <= (cell[0] + shift[0]) <= 9 and 0 <= (cell[1] + shift[1]) <= 9:
to_reveal.append((cell[0] + shift[0],cell[1] + shift[1]))
这段代码的作用是在玩家选择要发现的瓷砖后,将该瓷砖添加到列表中。然后如果是 0,则将所有邻居添加到列表中,等等。
推荐阅读
- geometry - 如何使用 2D 无限线作为可以通过邻近度查询的关联容器的键?
- flutter - 如何在 Flutter 包中添加本地化支持
- r - 在字典向量中查找字符串的位置
- c - 程序构建成功,但 netbeans 在包含中显示错误
- node.js - 如何使用Objection.js计算在特定表中引用行的主键的次数
- css - Firefox 和 Safari 中的绝对定位问题
- firebase - 将图像文件夹从本地计算机复制到 Firebase 存储
- java - 是否可以通过 id 在查找视图中将对象参数作为 id 传递
- python - PySpark 展平数据框,其中一些列作为嵌套结构的数组
- c++ - 如何在运行时在 Qt 应用程序中动态切换 VSync?