pygame写扫雷游戏
时间: 2023-08-16 07:54:18 浏览: 59
当然可以使用Pygame来编写扫雷游戏!以下是一个简单的示例代码:
```python
import pygame
import random
# 游戏窗口大小
WINDOW_WIDTH, WINDOW_HEIGHT = 400, 400
# 方块大小和行列数
BLOCK_SIZE = 20
ROWS, COLS = WINDOW_HEIGHT // BLOCK_SIZE, WINDOW_WIDTH // BLOCK_SIZE
# 雷的数量
NUM_MINES = 40
# 初始化Pygame
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# 设置窗口标题
pygame.display.set_caption("扫雷游戏")
# 定义颜色
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
WHITE = (255, 255, 255)
# 游戏结束标志
game_over = False
# 创建方块类
class Block:
def __init__(self, row, col):
self.row = row
self.col = col
self.x = col * BLOCK_SIZE
self.y = row * BLOCK_SIZE
self.is_mine = False
self.is_revealed = False
def draw(self):
if self.is_revealed:
pygame.draw.rect(window, GRAY, (self.x, self.y, BLOCK_SIZE, BLOCK_SIZE))
if self.is_mine:
pygame.draw.circle(window, BLACK, (self.x + BLOCK_SIZE // 2, self.y + BLOCK_SIZE // 2), BLOCK_SIZE // 4)
else:
pygame.draw.rect(window, WHITE, (self.x, self.y, BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(window, GRAY, (self.x, self.y, BLOCK_SIZE, BLOCK_SIZE), 1)
def reveal(self):
self.is_revealed = True
# 创建方块列表
blocks = [[Block(row, col) for col in range(COLS)] for row in range(ROWS)]
# 随机生成雷的位置
mines = random.sample(range(ROWS * COLS), NUM_MINES)
for mine in mines:
row = mine // COLS
col = mine % COLS
blocks[row][col].is_mine = True
# 游戏主循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed()[0]: # 左键点击
x, y = pygame.mouse.get_pos()
row = y // BLOCK_SIZE
col = x // BLOCK_SIZE
blocks[row][col].reveal()
# 绘制方块
for row in blocks:
for block in row:
block.draw()
# 更新屏幕
pygame.display.update()
# 退出游戏
pygame.quit()
```
这只是一个简单的示例,并没有包括计算周围雷数、判断游戏胜利条件、点击雷时的游戏失败等功能。你可以根据自己的需求进行扩展和修改。希望对你有帮助!