用python的pygame做个扫雷
时间: 2023-06-30 20:02:48 浏览: 118
使用Python的扫雷游戏
5星 · 资源好评率100%
好的,下面是一个简单的扫雷游戏的代码,使用Python的Pygame库实现:
```python
import pygame
import random
pygame.init()
# 设置游戏窗口大小
WINDOW_SIZE = (400, 400)
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption('扫雷')
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (128, 128, 128)
RED = (255, 0, 0)
# 定义方格大小
CELL_SIZE = 20
# 定义游戏区域大小
BOARD_SIZE = (10, 10)
# 定义雷的数量
MINE_COUNT = 20
# 加载图像
mine_image = pygame.image.load('mine.png')
flag_image = pygame.image.load('flag.png')
# 设置字体
font = pygame.font.Font(None, 25)
# 创建游戏区域
board = [[0 for y in range(BOARD_SIZE[1])] for x in range(BOARD_SIZE[0])]
# 随机生成地雷位置
mines = []
while len(mines) < MINE_COUNT:
mine = (random.randint(0, BOARD_SIZE[0] - 1), random.randint(0, BOARD_SIZE[1] - 1))
if mine not in mines:
mines.append(mine)
board[mine[0]][mine[1]] = -1
# 计算每个方格周围的地雷数量
for x in range(BOARD_SIZE[0]):
for y in range(BOARD_SIZE[1]):
if board[x][y] != -1:
count = 0
for i in range(max(0, x - 1), min(x + 2, BOARD_SIZE[0])):
for j in range(max(0, y - 1), min(y + 2, BOARD_SIZE[1])):
if board[i][j] == -1:
count += 1
board[x][y] = count
# 创建游戏状态矩阵
revealed = [[False for y in range(BOARD_SIZE[1])] for x in range(BOARD_SIZE[0])]
flags = [[False for y in range(BOARD_SIZE[1])] for x in range(BOARD_SIZE[0])]
# 游戏主循环
game_over = False
while not game_over:
# 事件处理循环
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
x = pos[0] // CELL_SIZE
y = pos[1] // CELL_SIZE
if event.button == 1:
if flags[x][y]:
continue
revealed[x][y] = True
if board[x][y] == -1:
game_over = True
message = font.render('Game over!', True, RED)
elif board[x][y] == 0:
for i in range(max(0, x - 1), min(x + 2, BOARD_SIZE[0])):
for j in range(max(0, y - 1), min(y + 2, BOARD_SIZE[1])):
if not revealed[i][j]:
revealed[i][j] = True
elif event.button == 3:
flags[x][y] = not flags[x][y]
# 绘制游戏界面
screen.fill(GRAY)
for x in range(BOARD_SIZE[0]):
for y in range(BOARD_SIZE[1]):
rect = pygame.Rect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, WHITE, rect, 1)
if revealed[x][y]:
if board[x][y] == -1:
screen.blit(mine_image, rect)
elif board[x][y] == 0:
pass
else:
text = font.render(str(board[x][y]), True, BLACK)
screen.blit(text, rect.move(CELL_SIZE // 2, CELL_SIZE // 2))
elif flags[x][y]:
screen.blit(flag_image, rect)
pygame.display.flip()
pygame.quit()
```
运行程序后,你将看到一个扫雷游戏界面。左键点击方格可以打开方格,右键点击方格可以标记为地雷。游戏结束后,会在界面上显示“Game over!”字样。
阅读全文