游戏概述
记忆翻牌游戏是一种经典的益智游戏,玩家需要翻开卡片并记住它们的位置,找出所有匹配的卡片对。本教程将使用Python的Pygame库开发一个完整的记忆翻牌游戏。
开发环境搭建
1. 安装Python
- 从Python官网:https://www.python.org/downloads/下载并安装最新版Python
- 安装时勾选"Add Python to PATH"选项
2. 安装Pygame
pip install pygame
3. 中文字体准备
- Windows系统自带中文字体(如simhei.ttf)
- 或下载免费中文字体如文泉驿:https://wenq.org/字体
核心代码解析
1. 游戏初始化
import pygame
import random
import time
import os
# 初始化pygame
pygame.init()
# 屏幕设置
WIDTH, HEIGHT = 600, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("六一儿童节快乐 - 记忆翻牌游戏")
知识点:
- pygame.init(): 初始化所有pygame模块
- set_mode(): 创建游戏窗口,参数为(宽度,高度)
- set_caption(): 设置窗口标题
2. 中文字体处理
# 尝试加载中文字体
font_paths = [
"C:/Windows/Fonts/simhei.ttf", # Windows黑体
"/System/Library/Fonts/STHeiti Medium.ttc", # Mac黑体
"/usr/share/fonts/truetype/wqy/wqy-microhei.ttc" # Linux文泉驿
]
chinese_font = None
for path in font_paths:
if os.path.exists(path):
chinese_font = pygame.font.Font(path, 36)
break
if chinese_font is None:
chinese_font = pygame.font.SysFont(None, 36)
知识点:
- 跨平台字体路径处理
- pygame.font.Font(): 从文件加载字体
- os.path.exists(): 检查文件是否存在
- 回退机制:找不到字体时使用系统默认字体
3. 游戏数据结构
def create_board():
symbols = []
for i in range(ROWS * COLS // 2):
symbols.append(i)
symbols.append(i)
random.shuffle(symbols)
board = []
for row in range(ROWS):
board_row = []
for col in range(COLS):
symbol = symbols.pop()
board_row.append({
'symbol': symbol,
'color': COLORS[symbol % len(COLORS)],
'flipped': False,
'matched':
False
})
board.append(board_row)
return board
知识点:
- 二维数组表示游戏板
- 每张卡片是一个字典,包含符号、颜色、是否翻开、是否匹配状态
- random.shuffle(): 随机打乱列表顺序
- 列表推导式创建游戏板
游戏流程图
完整代码
import pygame
import random
import time
import os
# 初始化pygame
pygame.init()
# 屏幕设置
WIDTH, HEIGHT = 600, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("六一儿童节快乐 - 记忆翻牌游戏")
# 尝试加载中文字体(使用系统自带字体或指定路径)
try:
# Windows系统常见中文字体路径
font_paths = [
"C:/Windows/Fonts/simhei.ttf", # 黑体
"C:/Windows/Fonts/simkai.ttf", # 楷体
"C:/Windows/Fonts/simsun.ttc", # 宋体
"/System/Library/Fonts/STHeiti Medium.ttc", # Mac系统黑体
"/usr/share/fonts/truetype/wqy/wqy-microhei.ttc" # Linux文泉驿微米黑
]
# 找到第一个可用的字体
chinese_font = None
for path in font_paths:
if os.path.exists(path):
chinese_font = pygame.font.Font(path, 36)
break
# 如果没有找到系统字体,使用默认字体(可能不支持中文)
if chinese_font is None:
chinese_font = pygame.font.SysFont(None, 36)
except:
chinese_font = pygame.font.SysFont(None, 36)
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
COLORS = [BLUE, GREEN, RED, (255, 255, 0), (255, 0, 255), (0, 255, 255)]
# 游戏参数
ROWS, COLS = 4, 4
CARD_WIDTH = WIDTH // COLS - 10
CARD_HEIGHT = HEIGHT // ROWS - 10
CARD_MARGIN = 5
# 创建卡片
def create_board():
symbols = []
for i in range(ROWS * COLS // 2):
symbols.append(i)
symbols.append(i)
random.shuffle(symbols)
board = []
for row in range(ROWS):
board_row = []
for col in range(COLS):
symbol = symbols.pop()
board_row.append({
'symbol': symbol,
'color': COLORS[symbol % len(COLORS)],
'flipped': False,
'matched': False
})
board.append(board_row)
return board
# 绘制卡片
def draw_board(board):
screen.fill(WHITE)
for row in range(ROWS):
for col in range(COLS):
card = board[row][col]
rect = pygame.Rect(
col * (CARD_WIDTH + CARD_MARGIN) + CARD_MARGIN,
row * (CARD_HEIGHT + CARD_MARGIN) + CARD_MARGIN,
CARD_WIDTH,
CARD_HEIGHT
)
if card['flipped'] or card['matched']:
pygame.draw.rect(screen, card['color'], rect)
pygame.draw.rect(screen, BLACK, rect, 2)
text = chinese_font.render(str(card['symbol']), True, BLACK)
text_rect = text.get_rect(center=rect.center)
screen.blit(text, text_rect)
else:
pygame.draw.rect(screen, (200, 200, 200), rect)
pygame.draw.rect(screen, BLACK, rect, 2)
pygame.display.flip()
# 显示中文消息
def show_message(message, color, duration=2000):
screen.fill(WHITE)
text = chinese_font.render(message, True, color)
text_rect = text.get_rect(center=(WIDTH//2, HEIGHT//2))
screen.blit(text, text_rect)
pygame.display.flip()
pygame.time.delay(duration)
# 主游戏循环
def main():
board = create_board()
flipped_cards = []
matched_pairs = 0
total_pairs = ROWS * COLS // 2
running = True
show_message("六一儿童节快乐!", RED, 1500)
show_message("点击卡片开始游戏", BLUE, 1500)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
col = pos[0] // (CARD_WIDTH + CARD_MARGIN)
row = pos[1] // (CARD_HEIGHT + CARD_MARGIN)
if 0 <= row < ROWS and 0 <= col < COLS:
card = board[row][col]
if not card['flipped'] and not card['matched'] and len(flipped_cards) < 2:
card['flipped'] = True
flipped_cards.append((row, col))
# 检查是否翻开了两张卡片
if len(flipped_cards) == 2:
draw_board(board)
pygame.time.delay(500) # 短暂延迟以便玩家看到
(row1, col1), (row2, col2) = flipped_cards
card1 = board[row1][col1]
card2 = board[row2][col2]
if card1['symbol'] == card2['symbol']:
card1['matched'] = True
card2['matched'] = True
matched_pairs += 1
# 检查游戏是否结束
if matched_pairs == total_pairs:
show_message("恭喜你赢了!", RED)
board = create_board()
flipped_cards = []
matched_pairs = 0
else:
card1['flipped'] = False
card2['flipped'] = False
flipped_cards = []
draw_board(board)
pygame.quit()
if __name__ == "__main__":
main()
扩展学习路线图
扩展方向详解
- 计分系统:
- 根据尝试次数计算分数
- 添加计时功能
- 实现分数排行榜
- 难度调整:
- 增加卡片行数和列数
- 添加卡片图案而不仅是数字
- 实现关卡系统
- 音效增强:
- 添加卡片翻动音效
- 匹配成功音效
- 背景音乐
- 图形优化:
- 使用图片替代简单色块
- 添加动画效果
- 实现主题皮肤切换
总结与进阶
关键知识点总结
- Pygame基础:
- 游戏循环结构
- 事件处理机制
- 图形绘制方法
- 数据结构:
- 二维数组表示游戏状态
- 字典存储卡片属性
- 列表操作(append, pop, shuffle)
- 中文处理:
- 字体加载方法
- 跨平台路径处理
- 回退机制设计
进阶挑战
- 添加卡片图案(使用图片资源)
- 实现游戏暂停功能
- 添加"提示"功能(短暂显示所有卡片)
- 开发移动端版本(使用Kivy框架)
补充资源
推荐学习资料
- Pygame官方文档: https://www.pygame.org/docs/
- Python游戏开发书籍:
- 《Python游戏编程快速上手》
- 《Making Games with Python & Pygame》
- 在线教程:
- Pygame中文教程:https://eyehere.net/2011/python-pygame-novice-professional/
常见问题解答
Q: 游戏窗口无法显示中文怎么办? A: 1. 确保字体路径正确 2. 下载中文字体放入项目目录 3. 修改代码指向本地字体文件
Q: 如何调整游戏难度? A: 修改ROWS和COLS的值,例如改为6x6的网格
Q: 如何添加更多卡片图案? A: 1. 准备图片资源 2. 修改create_board()函数加载图片 3. 更新绘制逻辑
六一儿童节快乐,愿编程带给你童年的乐趣!
持续更新Python编程学习日志与技巧,敬请关注!
#编程# #学习# #在头条记录我的2025# #python#