用python写一个扫雷游戏代码
时间: 2023-12-05 13:06:09 浏览: 87
好的,可以开始编写了。以下是一个简单的扫雷游戏代码示例:
```python
import random
def make_board(width, height, bombs):
# 创建一个空白扫雷游戏面板
board = [[0 for _ in range(width)] for _ in range(height)]
# 随机放置地雷
bomb_locations = random.sample([(x, y) for x in range(width) for y in range(height)], bombs)
for x, y in bomb_locations:
board[y][x] = -1
# 计算每个单元格周边地雷数目
for x in range(width):
for y in range(height):
if board[y][x] == -1:
continue
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]:
if x + dx < 0 or x + dx >= width or y + dy < 0 or y + dy >= height:
continue
if board[y + dy][x + dx] == -1:
board[y][x] += 1
return board
def print_board(board):
# 打印游戏面板
for row in board:
print(' '.join(str(cell) for cell in row))
def play_game(width, height, bombs):
board = make_board(width, height, bombs)
revealed = [[False for _ in range(width)] for _ in range(height)]
def reveal(x, y):
if revealed[y][x]:
return
revealed[y][x] = True
if board[y][x] == -1:
print('你输了!')
print_board(board)
return
if board[y][x] == 0:
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]:
if x + dx < 0 or x + dx >= width or y + dy < 0 or y + dy >= height:
continue
reveal(x + dx, y + dy)
else:
print_board(revealed)
while True:
print_board(revealed)
x = input('请输入X坐标:')
y = input('请输入Y坐标:')
if not x.isdigit() or not y.isdigit():
print('无效输入,请输入数字坐标')
continue
x, y = int(x), int(y)
if x < 0 or x >= width or y < 0 or y >= height:
print('坐标超出范围,请重新输入')
continue
reveal(x, y)
if all(all(revealed[y][x] or board[y][x] == -1 for x in range(width)) for y in range(height)):
print('你赢了!')
print_board(board)
break
if __name__ == '__main__':
play_game(10, 10, 10)
```
以上代码会在10x10的面板上随机生成10个地雷。你可以根据自己的需求调整面板大小和地雷数量。运行代码后,输入X坐标和Y坐标,然后按回车键进行操作。游戏面板将在每个回合之后更新,并在游戏结束后打印出完整解决方案。祝你好运!
阅读全文