import pygame import random

定义常量

WIDTH = 800 HEIGHT = 600 BLOCK_SIZE = 40 MINE_NUM = 10

初始化 pygame

pygame.init()

创建游戏窗口

screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("扫雷小游戏")

加载图片

block = pygame.image.load("block.png").convert() mine = pygame.image.load("mine.png").convert() flag = pygame.image.load("flag.png").convert()

定义游戏区域

board = [] for i in range(WIDTH // BLOCK_SIZE): row = [] for j in range(HEIGHT // BLOCK_SIZE): row.append(0) board.append(row)

随机生成地雷

for i in range(MINE_NUM): x = random.randint(0, WIDTH // BLOCK_SIZE - 1) y = random.randint(0, HEIGHT // BLOCK_SIZE - 1) board[x][y] = -1

计算每个方块周围地雷数量

for i in range(WIDTH // BLOCK_SIZE): for j in range(HEIGHT // BLOCK_SIZE): if board[i][j] == -1: continue count = 0 for dx in [-1, 0, 1]: for dy in [-1, 0, 1]: if i+dx < 0 or i+dx >= WIDTH // BLOCK_SIZE or j+dy < 0 or j+dy >= HEIGHT // BLOCK_SIZE: continue if board[i+dx][j+dy] == -1: count += 1 board[i][j] = count

游戏主循环

while True: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit()

# 绘制游戏区域
for i in range(WIDTH // BLOCK_SIZE):
    for j in range(HEIGHT // BLOCK_SIZE):
        if board[i][j] == -1:
            screen.blit(mine, (i*BLOCK_SIZE, j*BLOCK_SIZE))
        elif board[i][j] == 0:
            screen.blit(block, (i*BLOCK_SIZE, j*BLOCK_SIZE))
        else:
            font = pygame.font.Font(None, 36)
            text = font.render(str(board[i][j]), 1, (255, 255, 255))
            screen.blit(block, (i*BLOCK_SIZE, j*BLOCK_SIZE))
            screen.blit(text, (i*BLOCK_SIZE+BLOCK_SIZE//2-text.get_width()//2, j*BLOCK_SIZE+BLOCK_SIZE//2-text.get_height()//2))

# 刷新窗口
pygame.display.flip(
请模仿下面这段代码的编码风格和方式给出一段扫雷小游戏的代码我已经将地雷和小红旗图片放在与代码文件相同的文件夹里最好每部分代码再标注出作用。

原文地址: https://www.cveoy.top/t/topic/g2mB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录