用python写一个完整的扫雷游戏, 要求运行后就可以直接玩
时间: 2024-04-14 20:26:19 浏览: 8
当然可以!以下是一个用Python编写的简单扫雷游戏。运行后,你可以直接在终端上进行游戏。
```python
import random
def print_board(board):
for row in board:
print(" ".join(row))
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_mines(board, row, col):
size = len(board)
count = 0
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
new_row = row + dx
new_col = col + dy
if 0 <= new_row < size and 0 <= new_col < size and board[new_row][new_col] == "*":
count += 1
return count
def reveal_cell(board, revealed, row, col):
size = len(board)
if revealed[row][col]:
return
revealed[row][col] = True
if board[row][col] != " ":
return
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
new_row = row + dx
new_col = col + dy
if 0 <= new_row < size and 0 <= new_col < size:
reveal_cell(board, revealed, new_row, new_col)
def play_game():
size = int(input("请输入游戏大小:"))
num_mines = int(input("请输入雷的数量:"))
board = create_board(size, num_mines)
revealed = [[False for _ in range(size)] for _ in range(size)]
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:
reveal_cell(board, revealed, row, col)
if all(all(row) for row in revealed):
print("恭喜你,扫雷成功!")
game_over = True
play_game()
```
请注意,在游戏进行过程中,请确保输入正确的行和列号,以免出现错误。祝你玩得愉快!