上节课我们用 turtle 画了漂亮的图案。这节课更刺激——用 Python 做一个真正可以玩的小游戏!我们要用 pygame 这个游戏开发库,从零开始做一个弹跳球小游戏。
一、什么是 pygame?
pygame 是 Python 最流行的游戏开发库,可以制作 2D 游戏、动画、音乐播放器等。它不是 Python 自带的,需要安装:
# 在终端/命令行中运行:
pip install pygame
💡 如果提示 pip 不是命令,用:python -m pip install pygame
二、第一个窗口:Hello Pygame!
先来创建一个游戏窗口:
import pygame
import sys
# 初始化
pygame.init()
# 创建窗口:宽800,高600
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("我的第一个游戏!") # ✅ 设置窗口标题
# 游戏主循环
running = True
while running:
# 处理事件(比如点击关闭按钮)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 刷新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
sys.exit()运行后你会看到一个黑色窗口!这就是你的游戏画布 🎮
三、核心概念:游戏循环
每个 pygame 程序都有一个游戏循环(Game Loop),它每秒运行60次左右,每次做三件事:
-
- 处理输入:键盘、鼠标有没有操作?
-
- 更新状态:球的位置变了没?分数加了没?
-
- 绘制画面:把最新画面显示出来
-
while running:
# 1️⃣ 处理输入
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
print("按下了空格键!")
# 2️⃣ 更新状态
ball_x += speed_x # 球移动
# 3️⃣ 绘制画面
screen.fill("black") # 清屏
pygame.draw.circle(screen, "red", (ball_x, ball_y), 20) # 画球
pygame.display.flip() # 刷新显示四、实战:弹跳球游戏 🔴
完整代码!一个球在窗口里弹来弹去,碰到边缘就反弹:
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("弹跳球") # ✅ 正确的设置标题方法
clock = pygame.time.Clock() # 控制帧率
# 球的属性
ball_x = 400 # x坐标
ball_y = 300 # y坐标
speed_x = 5 # 水平速度
speed_y = 3 # 垂直速度
radius = 20 # 半径
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 移动球
ball_x += speed_x
ball_y += speed_y
# 碰到左右边缘,水平反弹
if ball_x <= radius or ball_x >= 800 - radius:
speed_x = -speed_x
# 碰到上下边缘,垂直反弹
if ball_y <= radius or ball_y >= 600 - radius:
speed_y = -speed_y
# 绘制
screen.fill("#1a1a2e") # 深蓝背景
pygame.draw.circle(screen, "#ff6b6b", # 红色球
(int(ball_x), int(ball_y)), radius)
pygame.display.flip()
clock.tick(60) # 限制60帧/秒
pygame.quit()运行效果:一个红色小球在深蓝色背景上弹来弹去!🔴
五、进阶:加个挡板接球 🏓
用鼠标控制挡板,让球不要掉下去:
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("挡板接球") # ✅ 修正
clock = pygame.time.Clock()
# 球
ball = [400, 300, 5, 3] # x, y, vx, vy
radius = 12
# 挡板
paddle_width = 120
paddle_height = 15
paddle_x = 340 # 挡板x坐标
paddle_y = 560 # 挡板y坐标(靠近底部)
score = 0 # 分数
font = pygame.font.Font(None, 36)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 鼠标控制挡板
mouse_x = pygame.mouse.get_pos()[0]
paddle_x = mouse_x - paddle_width // 2
# 移动球
ball[0] += ball[2]
ball[1] += ball[3]
# 左右碰壁反弹
if ball[0] <= radius or ball[0] >= 800 - radius:
ball[2] = -ball[2]
# 顶部反弹
if ball[1] <= radius:
ball[3] = -ball[3]
# 接住挡板
if (paddle_x <= ball[0] <= paddle_x + paddle_width and
paddle_y <= ball[1] + radius <= paddle_y + paddle_height):
ball[3] = -abs(ball[3]) # 向上弹
score += 10 # 加分!
# 掉到底部,重置
if ball[1] > 620:
ball = [400, 300, 5, 3] # 重置位置
# 绘制
screen.fill("#16213e") # 背景
pygame.draw.circle(screen, "#e94560", # 红球
(int(ball[0]), int(ball[1])), radius)
pygame.draw.rect(screen, "#4ecca3", # 绿色挡板
(paddle_x, paddle_y,
paddle_width, paddle_height), border_radius=5)
# 显示分数
text = font.render(f"Score: {score}", True, "white")
screen.blit(text, (10, 10))
pygame.display.flip()
clock.tick(60)
pygame.quit()现在你可以用鼠标左右移动挡板来接球了!每接到一次得10分!🎯
六、再加点特效 ✨
给游戏加点颜色变化:
# 颜色列表,每次接球换色
colors = ["#ff6b6b", "#4ecdc4", "#ffe66d", "#95e1d3",
"#f38181", "#aa96da", "#fcbad3"]
color_index = 0
ball_color = colors[0]
# 在接球的代码里加上:
if (paddle_x <= ball[0] <= paddle_x + paddle_width and
paddle_y <= ball[1] + radius <= paddle_y + paddle_height):
ball[3] = -abs(ball[3])
score += 10
color_index = (color_index + 1) % len(colors) # 换色
ball_color = colors[color_index]七、今天学到了什么?
-
- pygame 安装与初始化:
pip install pygame -
- 创建游戏窗口:
display.set_mode((宽, 高)) -
- 设置标题:
display.set_caption("标题") ✅ -
- 游戏循环:处理输入 → 更新状态 → 绘制画面
-
- 绘制图形:
draw.circle 画圆,draw.rect 画矩形 -
- 碰撞检测:判断坐标范围是否重叠
-
- 鼠标控制:
mouse.get_pos() 获取鼠标位置 -
- 帧率控制:
clock.tick(60) 限制60帧 -
八、挑战任务 🎮
试试完成这些挑战:
-
- 🟢 简单:让球的速度随分数增加而变快
-
- 🟡 中等:添加多个球同时弹跳
-
- 🔴 困难:做成打砖块游戏(上面加一排砖块)
-
九、系列总结 🎉
到这里,我们的 Python 进阶系列就全部完成了!回顾一下整个旅程:
| 篇目 | 主题 |
| 第1-12篇 | Python基础(变量/运算/条件/循环/列表/字典/函数/模块/文件/异常/OOP/字符串/input+推导式) |
| 第13篇 | AI API入门 |
| 第14篇 | AI聊天助手 |
| 第15篇 | AI写作工具 |
| 第16篇 | turtle画图 |
| 第17篇 | pygame游戏 ← 你在这里! |
恭喜你完成了全部17篇教程!你已经掌握了从基础语法到 AI 应用再到游戏开发的完整技能链!🏆
有问题欢迎留言!感谢一路陪伴!