用pygame写一个扫雷游戏
时间: 2023-06-27 15:06:23 浏览: 167
好的,下面是一个简单的扫雷游戏,使用 Python 的 Pygame 库实现。
首先,需要安装 Pygame 库:
```
pip install pygame
```
然后,创建一个名为 `minesweeper.py` 的 Python 文件,将以下代码粘贴到文件中:
```python
import pygame
import random
WIDTH = 400
HEIGHT = 400
SIZE = 20
FPS = 30
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (200, 200, 200)
RED = (255, 0, 0)
# 初始化 Pygame
pygame.init()
# 创建窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Minesweeper")
# 设置时钟
clock = pygame.time.Clock()
# 加载图像
flag_img = pygame.image.load("flag.png")
mine_img = pygame.image.load("mine.png")
# 设置字体
font = pygame.font.Font(None, 25)
class Tile(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((SIZE, SIZE))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.is_mine = False
self.is_flagged = False
self.is_revealed = False
self.adjacent_mines = 0
def reveal(self):
self.is_revealed = True
if self.is_mine:
return False
if self.adjacent_mines == 0:
for tile in tiles:
if tile != self and abs(tile.rect.x - self.rect.x) <= SIZE and abs(tile.rect.y - self.rect.y) <= SIZE:
if not tile.is_revealed:
tile.reveal()
return True
def update(self):
if self.is_flagged:
screen.blit(flag_img, self.rect)
if self.is_revealed:
pygame.draw.rect(screen, WHITE, self.rect)
if self.is_mine:
screen.blit(mine_img, self.rect)
elif self.adjacent_mines > 0:
text = font.render(str(self.adjacent_mines), True, BLACK)
text_rect = text.get_rect(center=self.rect.center)
screen.blit(text, text_rect)
else:
pygame.draw.rect(screen, GRAY, self.rect)
def flag(self):
self.is_flagged = not self.is_flagged
# 创建网格
grid = []
for row in range(HEIGHT // SIZE):
grid.append([])
for column in range(WIDTH // SIZE):
tile = Tile(column * SIZE, row * SIZE)
grid[row].append(tile)
# 添加地雷
mines = []
for i in range(10):
row = random.randint(0, len(grid) - 1)
column = random.randint(0, len(grid[0]) - 1)
tile = grid[row][column]
while tile.is_mine:
row = random.randint(0, len(grid) - 1)
column = random.randint(0, len(grid[0]) - 1)
tile = grid[row][column]
tile.is_mine = True
mines.append(tile)
# 计算每个瓷砖周围的地雷数量
for row in range(len(grid)):
for column in range(len(grid[0])):
tile = grid[row][column]
if tile.is_mine:
continue
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
if row + i < 0 or row + i >= len(grid) or column + j < 0 or column + j >= len(grid[0]):
continue
if grid[row + i][column + j].is_mine:
tile.adjacent_mines += 1
# 创建精灵组
tiles = pygame.sprite.Group()
for row in range(len(grid)):
for column in range(len(grid[0])):
tiles.add(grid[row][column])
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
pos = pygame.mouse.get_pos()
for tile in tiles:
if tile.rect.collidepoint(pos):
if not tile.is_revealed:
if not tile.reveal():
# 点到地雷,游戏结束
for mine in mines:
mine.is_revealed = True
print("Game over!")
running = False
break
elif event.button == 3:
pos = pygame.mouse.get_pos()
for tile in tiles:
if tile.rect.collidepoint(pos):
tile.flag()
break
# 更新精灵
tiles.update()
# 绘制屏幕
screen.fill(BLACK)
tiles.draw(screen)
pygame.display.flip()
# 控制游戏速度
clock.tick(FPS)
# 退出 Pygame
pygame.quit()
```
注意,这个代码需要两张图片,一张用于标记地雷的旗帜,另一张用于显示地雷。你可以在本地文件夹中放置这些图片,并将它们命名为 `flag.png` 和 `mine.png`。
运行 `minesweeper.py` 文件,即可开始游戏。左键单击瓷砖以揭示它,右键单击瓷砖以标记地雷。如果揭示到地雷,游戏结束。
阅读全文