请用python写一个扫雷,并且可视化
时间: 2023-07-07 11:32:36 浏览: 120
好的,下面是一个基于 Pygame 库的扫雷游戏的 Python 实现。在程序中,我们使用了 `numpy` 库来表示和处理游戏区域。
```python
import pygame
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(screen, board, revealed, font):
height, width = board.shape
for i in range(height):
for j in range(width):
rect = pygame.Rect(j*30, i*30, 30, 30)
if revealed[i, j]:
pygame.draw.rect(screen, (192, 192, 192), rect)
if board[i, j] > 0:
text = font.render(str(board[i, j]), True, (0, 0, 0))
screen.blit(text, (j*30+10, i*30+5))
else:
pygame.draw.rect(screen, (128, 128, 128), rect)
pygame.draw.rect(screen, (192, 192, 192), rect, 2)
# 主程序
def main():
width = 10
height = 10
num_mines = 10
board = init_board(width, height, num_mines)
revealed = np.zeros((height, width), dtype=bool)
pygame.init()
screen = pygame.display.set_mode((width*30, height*30))
pygame.display.set_caption('Minesweeper')
font = pygame.font.SysFont(None, 24)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
i, j = y // 30, x // 30
if event.button == 1:
if board[i, j] == -1:
print('Boom! Game over.')
return
revealed[i, j] = True
elif event.button == 3:
revealed[i, j] = not revealed[i, j]
screen.fill((255, 255, 255))
show_board(screen, board, revealed, font)
pygame.display.update()
if np.count_nonzero(revealed) == width * height - num_mines:
print('You win!')
return
if __name__ == '__main__':
main()
```
运行程序后,你可以使用鼠标来揭开游戏区域中的格子。左键表示揭开格子,右键表示标记格子为地雷或取消标记。如果揭开的格子是地雷,游戏结束;否则,这个格子会显示出周围地雷的数量。当你揭开的所有格子都不是地雷时,你就赢了游戏。
阅读全文