帮我写一个扫雷游戏使用python
时间: 2023-12-22 17:04:39 浏览: 10
好的,下面是一个简单的扫雷游戏的代码示例,使用Python 3编写:
```python
import random
# 游戏棋盘大小
BOARD_SIZE = 10
# 地雷数量
NUM_MINES = 15
# 棋盘格子的状态
HIDDEN = 0
MINE = -1
# 初始化棋盘
board = [[HIDDEN for i in range(BOARD_SIZE)] for j in range(BOARD_SIZE)]
# 随机布雷
count = 0
while count < NUM_MINES:
x = random.randint(0, BOARD_SIZE-1)
y = random.randint(0, BOARD_SIZE-1)
if board[x][y] == HIDDEN:
board[x][y] = MINE
count += 1
# 计算每个格子周围的地雷数量
for x in range(BOARD_SIZE):
for y in range(BOARD_SIZE):
if board[x][y] != MINE:
count = 0
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if 0 <= x+dx < BOARD_SIZE and 0 <= y+dy < BOARD_SIZE and board[x+dx][y+dy] == MINE:
count += 1
board[x][y] = count
# 显示棋盘
def print_board(reveal=False):
for x in range(BOARD_SIZE):
for y in range(BOARD_SIZE):
if reveal or board[x][y] != HIDDEN:
print(board[x][y], end=' ')
else:
print('-', end=' ')
print()
# 主循环
while True:
print_board()
x = int(input('Enter row: '))
y = int(input('Enter column: '))
if board[x][y] == MINE:
print('Game over!')
print_board(True)
break
elif board[x][y] == 0:
# 自动翻开周围格子
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if 0 <= x+dx < BOARD_SIZE and 0 <= y+dy < BOARD_SIZE and board[x+dx][y+dy] == HIDDEN:
board[x+dx][y+dy] = 0
print_board()
else:
board[x][y] = -board[x][y]
```
这是一个简单的控制台游戏,玩家输入行和列的坐标,然后翻开对应的格子。如果翻开的是地雷,游戏结束;如果翻开的是数字,则表示该格子周围有多少个地雷。如果翻开的是空格,则自动翻开周围所有空格。游戏继续进行,直到所有非地雷的格子都被翻开,或者玩家翻开了地雷。
阅读全文