python写一个可以正常玩的扫雷游戏, 并在代码上做好中文注释
时间: 2024-06-10 07:03:54 浏览: 157
Python实现自动扫雷游戏的方法源码
好的,我可以为您提供一个 Python 编写的扫雷游戏代码,代码中将会有注释说明每个函数的作用。
```
import random
def create_board(num_rows, num_cols, num_bombs):
"""
创建扫雷游戏棋盘
num_rows:行数
num_cols:列数
num_bombs:地雷数量
"""
board = [[0 for _ in range(num_cols)] for _ in range(num_rows)] # 初始化棋盘
bombs_planted = 0
while bombs_planted < num_bombs:
row = random.randint(0, num_rows - 1)
col = random.randint(0, num_cols - 1)
if board[row][col] == '*': # 如果该位置已经有地雷,则重新生成随机坐标
continue
board[row][col] = '*' # 在该位置放置地雷
bombs_planted += 1
assign_values(board) # 为每个非地雷格子分配数字值
return board
def assign_values(board):
"""
为每个非地雷格子分配数字值
"""
for r in range(len(board)):
for c in range(len(board[0])):
if board[r][c] == '*': # 如果当前格子是地雷,跳过
continue
# 计算当前格子周围的地雷数量
num_bombs = 0
if r > 0 and c > 0 and board[r-1][c-1] == '*':
num_bombs += 1
if r > 0 and board[r-1][c] == '*':
num_bombs += 1
if r > 0 and c < len(board[0]) - 1 and board[r-1][c+1] == '*':
num_bombs += 1
if c > 0 and board[r][c-1] == '*':
num_bombs += 1
if c < len(board[0]) - 1 and board[r][c+1] == '*':
num_bombs += 1
if r < len(board) - 1 and c > 0 and board[r+1][c-1] == '*':
num_bombs += 1
if r < len(board) - 1 and board[r+1][c] == '*':
num_bombs += 1
if r < len(board) - 1 and c < len(board[0]) - 1 and board[r+1][c+1] == '*':
num_bombs += 1
board[r][c] = num_bombs # 将当前格子的数字值赋值为周围地雷数量
def reveal_board(board, r, c, visited):
"""
递归展示棋盘,即使得除了地雷格子外,所有的空白格子都会被展示
"""
# 判断当前格子坐标是否越界或者当前格子已经被展示
if r < 0 or c < 0 or r >= len(board) or c >= len(board[0]) or visited[r][c]:
return
visited[r][c] = True # 标记当前格子已经展示
if board[r][c] > 0: # 如果当前格子不是空白格子,则只展示当前格子
return
# 如果当前格子是空白格子,则展示当前格子,并递归展示其周围的所有空白格子
reveal_board(board, r-1, c, visited)
reveal_board(board, r+1, c, visited)
reveal_board(board, r, c-1, visited)
reveal_board(board, r, c+1, visited)
reveal_board(board, r-1, c-1, visited)
reveal_board(board, r-1, c+1, visited)
reveal_board(board, r+1, c-1, visited)
reveal_board(board, r+1, c+1, visited)
return
def play_game(board):
"""
主要游戏逻辑代码
"""
num_rows = len(board)
num_cols = len(board[0])
num_moves = num_rows * num_cols - num_bombs
visited = [[False for _ in range(num_cols)] for _ in range(num_rows)] # 初始化标记列表,用于标记哪些格子已经被展示
while num_moves > 0:
print("当前棋盘状态:")
for row in board:
print(row)
print("\n")
row_guess = int(input("请输入所猜测的行数(从1开始计数):"))
col_guess = int(input("请输入所猜测的列数(从1开始计数):"))
row_guess -= 1
col_guess -= 1
if visited[row_guess][col_guess]: # 如果该格子已经被展示过了
print("该格子已经被展示过了,请重新选择!\n")
continue
visited[row_guess][col_guess] = True # 标记该格子已被展示
if board[row_guess][col_guess] == "*": # 如果猜测到的格子是地雷
print("很抱歉,您猜错了!游戏结束!")
return
reveal_board(board, row_guess, col_guess, visited) # 根据递归函数展示当前棋盘
num_moves -= 1
print("恭喜您,您已经找出了所有的地雷,游戏胜利!")
# 游戏参数配置
num_rows = 10
num_cols = 10
num_bombs = 10
board = create_board(num_rows, num_cols, num_bombs)
play_game(board)
```
以上就是扫雷游戏的 Python 实现代码,希望能够帮助到您!
阅读全文