用Python语言设计一个扫雷游戏的代码
时间: 2024-05-17 13:16:26 浏览: 68
Python 扫雷游戏 完整源代码+图片素材
5星 · 资源好评率100%
好的,以下是一个简单的Python扫雷游戏的代码示例,它实现了上述提到的游戏逻辑和功能:
```python
import random
# 游戏界面的大小
ROWS = 10
COLS = 10
# 地雷的数量
MINES = 10
# 初始化游戏界面
board = [[0 for x in range(COLS)] for y in range(ROWS)]
# 随机生成地雷的位置
mines = random.sample(range(ROWS * COLS), MINES)
# 在游戏界面上将地雷标记为-1
for m in mines:
row = m // COLS
col = m % COLS
board[row][col] = -1
# 计算每个方格周围地雷的数量
for r in range(ROWS):
for c in range(COLS):
if board[r][c] == -1:
continue
count = 0
for x in range(max(0, r-1), min(ROWS, r+2)):
for y in range(max(0, c-1), min(COLS, c+2)):
if board[x][y] == -1:
count += 1
board[r][c] = count
# 显示游戏界面
def display_board(board):
for r in range(ROWS):
for c in range(COLS):
if board[r][c] == -1:
print('*', end=' ')
else:
print(board[r][c], end=' ')
print()
# 递归地显示周围的方格
def reveal_board(board, r, c, visited):
if (r, c) in visited:
return
if board[r][c] != 0:
visited.append((r, c))
return
visited.append((r, c))
for x in range(max(0, r-1), min(ROWS, r+2)):
for y in range(max(0, c-1), min(COLS, c+2)):
if (x, y) not in visited:
reveal_board(board, x, y, visited)
# 游戏主循环
while True:
display_board(board)
row = int(input('请输入行号(1-10):')) - 1
col = int(input('请输入列号(1-10):')) - 1
if board[row][col] == -1:
print('游戏结束!')
break
else:
visited = []
reveal_board(board, row, col, visited)
for (r, c) in visited:
if board[r][c] != -1:
board[r][c] = -2
display_board(board)
if sum([x.count(0) for x in board]) == MINES:
print('你赢了!')
break
```
这段代码实现了一个简单的扫雷游戏,你可以参考这个代码来自己编写更复杂和完善的版本。
阅读全文