用Python写一个扫雷游戏的代码
时间: 2024-04-17 15:24:45 浏览: 135
用python写扫雷游戏实例代码分享
5星 · 资源好评率100%
当然,下面是一个简单的扫雷游戏的Python代码示例:
```python
import random
def create_board(size, num_mines):
board = [[' ' for _ in range(size)] for _ in range(size)]
mines = random.sample(range(size*size), num_mines)
for mine in mines:
row = mine // size
col = mine % size
board[row][col] = '*'
return board
def count_adjacent_mines(board, row, col):
count = 0
size = len(board)
for i in range(max(0, row-1), min(row+2, size)):
for j in range(max(0, col-1), min(col+2, size)):
if board[i][j] == '*':
count += 1
return count
def reveal_board(board):
size = len(board)
for i in range(size):
for j in range(size):
if board[i][j] == '*':
continue
count = count_adjacent_mines(board, i, j)
board[i][j] = str(count) if count > 0 else ' '
return board
def print_board(board):
size = len(board)
print(' ', end='')
for i in range(size):
print(f'{i} ', end='')
print()
print(' ', end='')
for _ in range(size):
print('--', end='')
print()
for i, row in enumerate(board):
print(f'{i}|', end='')
for cell in row:
print(f'{cell}|', end='')
print()
def play_game():
size = int(input("请输入游戏板大小(正方形):"))
num_mines = int(input("请输入雷的数量:"))
board = create_board(size, num_mines)
revealed_board = reveal_board(board)
game_over = False
while not game_over:
print_board(board)
row = int(input("请输入行号:"))
col = int(input("请输入列号:"))
if board[row][col] == '*':
print('游戏结束!你踩到雷了!')
game_over = True
else:
board[row][col] = revealed_board[row][col]
if all(cell != ' ' for row in board for cell in row if cell != '*'):
print('恭喜你,扫雷成功!')
game_over = True
play_game()
```
这是一个简单的命令行扫雷游戏,你可以根据需要进行修改或扩展。
阅读全文