用python语言编写一个扫雷小游戏
时间: 2023-07-18 19:28:59 浏览: 75
好的,下面是一个简单的扫雷小游戏的Python代码:
``` python
import random
def create_board(num_mines, size):
board = [[0 for _ in range(size)] for _ in range(size)]
mines = 0
while mines < num_mines:
x, y = random.randint(0, size - 1), random.randint(0, size - 1)
if board[x][y] != '*':
board[x][y] = '*'
mines += 1
for i in range(size):
for j in range(size):
if board[i][j] == '*':
continue
nearby_mines = 0
for dx in range(-1, 2):
for dy in range(-1, 2):
if dx == dy == 0:
continue
if 0 <= i + dx < size and 0 <= j + dy < size and board[i + dx][j + dy] == '*':
nearby_mines += 1
board[i][j] = nearby_mines
return board
def print_board(board):
size = len(board)
for i in range(size):
for j in range(size):
if board[i][j] == '*':
print('*', end=' ')
else:
print(board[i][j], end=' ')
print()
def reveal_board(board, revealed, x, y):
if revealed[x][y]:
return
revealed[x][y] = True
if board[x][y] == '*':
return
if board[x][y] > 0:
return
size = len(board)
for dx in range(-1, 2):
for dy in range(-1, 2):
if dx == dy == 0:
continue
if 0 <= x + dx < size and 0 <= y + dy < size:
reveal_board(board, revealed, x + dx, y + dy)
def play_game():
size = 10
num_mines = 10
board = create_board(num_mines, size)
revealed = [[False for _ in range(size)] for _ in range(size)]
while True:
print_board(revealed)
x = int(input('Enter x coordinate: '))
y = int(input('Enter y coordinate: '))
if board[x][y] == '*':
print('Game over!')
break
reveal_board(board, revealed, x, y)
play_game()
```
这个游戏使用了二维列表来表示扫雷棋盘,其中数字表示该位置周围的地雷数量,"*"表示该位置是地雷。当玩家选择一个位置时,程序会显示该位置周围的地雷数量或者"Game over!"(如果该位置是地雷)。玩家可以一直玩下去,直到触雷或者扫描完所有非地雷位置。
阅读全文