用Python写一个扫雷小游戏程序
时间: 2023-11-30 18:02:54 浏览: 131
当然,下面是一个使用Python编写的简单扫雷小游戏程序的示例:
```python
import random
# 创建游戏板
def create_board(rows, cols, bombs):
board = [[' ' for _ in range(cols)] for _ in range(rows)]
bombs_planted = 0
while bombs_planted < bombs:
row = random.randint(0, rows - 1)
col = random.randint(0, cols - 1)
if board[row][col] != 'B':
board[row][col] = 'B'
bombs_planted += 1
return board
# 显示游戏板
def display_board(board):
rows = len(board)
cols = len(board[0])
print(' ', end='')
for col in range(cols):
print(f'{col} ', end='')
print()
print(' ┌' + '───┬' * (cols - 1) + '───┐')
for row in range(rows):
print(f'{row} │ ', end='')
for col in range(cols):
print(f'{board[row][col]} │ ', end='')
print()
if row != rows - 1:
print(' ├───' + '┼───' * (cols - 1) + '┤')
print(' └' + '───┴' * (cols - 1) + '───┘')
# 检查相邻位置的雷数
def check_adjacent(board, row, col):
rows = len(board)
cols = len(board[0])
count = 0
for i in range(max(0, row - 1), min(row + 2, rows)):
for j in range(max(0, col - 1), min(col + 2, cols)):
if board[i][j] == 'B':
count += 1
return count
# 打开方块
def open_cell(board, revealed, row, col):
rows = len(board)
cols = len(board[0])
if revealed[row][col]:
return
revealed[row][col] = True
if board[row][col] == 'B':
return
if board[row][col] == ' ':
for i in range(max(0, row - 1), min(row + 2, rows)):
for j in range(max(0, col - 1), min(col + 2, cols)):
open_cell(board, revealed, i, j)
else:
return
# 主游戏循环
def play_game(rows, cols, bombs):
board = create_board(rows, cols, bombs)
revealed = [[False for _ in range(cols)] for _ in range(rows)]
game_over = False
while not game_over:
display_board(revealed)
row = int(input('请输入行号:'))
col = int(input('请输入列号:'))
if board[row][col] == 'B':
print('很遗憾,***
阅读全文