通过pygame创建扫雷游戏,基本框架代码如下:
import pygame
import random
import time
# 游戏参数
WIDTH, HEIGHT = 800, 600
ROWS, COLS = 20, 20
CELL_SIZE = WIDTH // COLS
NUM_MINES = 40
# 颜色
WHITE = (255, 255, 255)
GRAY = (192, 192, 192)
BLACK = (0, 0, 0)
# 初始化 Pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("扫雷游戏")
# 游戏状态
RUNNING = True
LOSE = False
WIN = False
# 创建雷区
board = [[0 for _ in range(COLS)] for _ in range(ROWS)]
revealed = [[False for _ in range(COLS)] for _ in range(ROWS)]
mines = set()
# 生成雷的位置
while len(mines) < NUM_MINES:
row = random.randint(0, ROWS - 1)
col = random.randint(0, COLS - 1)
mines.add((row, col))
board[row][col] = -1