请用python写一个扫雷
时间: 2023-07-07 18:32:37 浏览: 160
好的,下面是一个简单的命令行扫雷游戏的 Python 实现。在程序中,我们使用了 `numpy` 库来表示和处理游戏区域。
```python
import numpy as np
import random
# 初始化游戏区域
def init_board(width, height, num_mines):
board = np.zeros((height, width), dtype=int)
for i in range(num_mines):
while True:
x = random.randint(0, width-1)
y = random.randint(0, height-1)
if board[y, x] == 0:
board[y, x] = -1
break
for i in range(height):
for j in range(width):
if board[i, j] == -1:
continue
count = 0
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue
x2 = j + dx
y2 = i + dy
if x2 >= 0 and x2 < width and y2 >= 0 and y2 < height and board[y2, x2] == -1:
count += 1
board[i, j] = count
return board
# 显示游戏区域
def show_board(board, revealed):
height, width = board.shape
for i in range(height):
for j in range(width):
if revealed[i, j]:
print(str(board[i, j]).rjust(3), end='')
else:
print('###', end='')
print()
# 主程序
def main():
width = 10
height = 10
num_mines = 10
board = init_board(width, height, num_mines)
revealed = np.zeros((height, width), dtype=bool)
while True:
show_board(board, revealed)
x = int(input('Please input x: '))
y = int(input('Please input y: '))
if board[y, x] == -1:
print('Boom! Game over.')
break
revealed[y, x] = True
if np.count_nonzero(revealed) == width * height - num_mines:
print('You win!')
break
if __name__ == '__main__':
main()
```
运行程序后,你可以输入坐标来揭开游戏区域中的格子。如果揭开的格子是地雷,游戏结束;否则,这个格子会显示出周围地雷的数量。当你揭开的所有格子都不是地雷时,你就赢了游戏。
阅读全文