从“游戏是怎么跑起来的”到两个完整 pygame 项目。第 1–3 课只用标准库,可直接在在线代码编辑器运行;第 4–6 课需要本地安装 pygame。
所有游戏本质上是同一个死循环:读输入 → 更新状态 → 画画面,每秒重复几十次。先用标准库模拟一个 1 秒 2 帧的“游戏循环”:
import time
hp = 100
frame = 0
while hp > 0:
frame += 1
# 1. 更新:模拟每帧掉血
hp -= 3
# 2. 渲染:打印状态条
bar = "#" * (hp // 2)
print(f"[第{frame:02d}帧] HP {hp:3d} |{bar}")
# 3. 等待:控制帧率(0.5 秒一帧)
time.sleep(0.5)
print("游戏结束")
运行后你会看到血条一帧帧减少。真正的游戏只是把“打印”换成“绘制像素”。练习:把掉血速度改成随机值(提示:import random; random.randint(1, 5))。
第一个完整小游戏:程序随机想一个数,玩家来猜,每猜一次给出“大了 / 小了”提示。用到了随机数、循环、分支、输入四大基础。
import random
secret = random.randint(1, 100)
count = 0
print("我想了一个 1~100 之间的数,猜猜看!")
while True:
try:
guess = int(input("请输入你的猜测: "))
except ValueError:
print("请输入整数哦")
continue
count += 1
if guess == secret:
print(f"答对啦!你一共猜了 {count} 次")
break
elif guess < secret:
print("小了,再大一点")
else:
print("大了,再小一点")
input() 要读的内容填到“标准输入”文本框即可模拟键盘输入(每行一个)。练习:① 限制最多 10 次;② 记录历史猜测并显示;③ 做成“玩家 A 出题、玩家 B 猜”的双人版。
用二维列表表示棋盘,实现双人对战的井字棋。核心知识点:列表、循环、函数、胜负判断。
board = [[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "]]
def show():
print(" 0 1 2")
for i, row in enumerate(board):
print(i, " " + " | ".join(row))
if i < 2:
print(" ---+---+---")
def win(player):
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] == player: return True
if board[0][i] == board[1][i] == board[2][i] == player: return True
if board[0][0] == board[1][1] == board[2][2] == player: return True
if board[0][2] == board[1][1] == board[2][0] == player: return True
return False
player = "X"
for turn in range(9):
show()
try:
r, c = map(int, input(f"玩家 {player} 落子(行 列): ").split())
except ValueError:
print("格式错误,请输入例如: 1 2"); continue
if not (0 <= r <= 2 and 0 <= c <= 2) or board[r][c] != " ":
print("无效位置,重新下"); continue
board[r][c] = player
if win(player):
show(); print(f"玩家 {player} 获胜!"); break
player = "O" if player == "X" else "X"
else:
show(); print("平局!")
练习:① 加上“重新开始”选项;② 写一个简单 AI(优先堵对方两连)。
从这一课开始进入图形游戏。先在电脑上安装:pip install pygame(Python 3.8+)。在线编辑器沙箱不含 pygame,本课起请在本地运行。
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("我的第一个游戏窗口")
clock = pygame.time.Clock()
x, y = 320, 240 # 方块位置
speed = 5
running = True
while running:
for event in pygame.event.get(): # 读输入
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]: x -= speed
if keys[pygame.K_RIGHT]: x += speed
if keys[pygame.K_UP]: y -= speed
if keys[pygame.K_DOWN]: y += speed
screen.fill((15, 23, 42)) # 画背景
pygame.draw.rect(screen, (59, 130, 246), (x, y, 30, 30)) # 画方块
pygame.display.flip() # 刷新画面
clock.tick(60) # 锁定 60 帧
pygame.quit()
对比第 1 课的循环:结构完全一样,只是输入换成事件、渲染换成绘制。这就是游戏开发的“通用骨架”。
经典贪吃蛇,完整可玩版本(约 80 行)。重点:蛇身用列表模拟、方向队列防反向、碰撞检测、分数。
import pygame, random
CELL = 20
COLS, ROWS = 30, 22
pygame.init()
screen = pygame.display.set_mode((COLS * CELL, ROWS * CELL))
pygame.display.set_caption("贪吃蛇 - scirco 教程")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 32)
snake = [(COLS // 2, ROWS // 2)]
direction = (1, 0)
food = (random.randrange(COLS), random.randrange(ROWS))
while food in snake:
food = (random.randrange(COLS), random.randrange(ROWS))
score = 0
running = True
move_timer = 0
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and direction != (1, 0): direction = (-1, 0)
elif event.key == pygame.K_RIGHT and direction != (-1, 0): direction = (1, 0)
elif event.key == pygame.K_UP and direction != (0, 1): direction = (0, -1)
elif event.key == pygame.K_DOWN and direction != (0, -1): direction = (0, 1)
move_timer += 1
if move_timer >= 6: # 每 6 帧移动一格(速度可调)
move_timer = 0
head = snake[0]
new = ((head[0] + direction[0]) % COLS, (head[1] + direction[1]) % ROWS)
if new in snake: # 撞到自己
running = False
break
snake.insert(0, new)
if new == food:
score += 10
food = (random.randrange(COLS), random.randrange(ROWS))
while food in snake:
food = (random.randrange(COLS), random.randrange(ROWS))
else:
snake.pop() # 没吃到就缩尾
screen.fill((15, 23, 42))
for seg in snake:
pygame.draw.rect(screen, (74, 222, 128), (seg[0] * CELL, seg[1] * CELL, CELL - 2, CELL - 2))
pygame.draw.rect(screen, (248, 113, 113), (food[0] * CELL, food[1] * CELL, CELL - 2, CELL - 2))
screen.blit(font.render(f"score: {score}", True, (226, 232, 240)), (10, 8))
pygame.display.flip()
clock.tick(60)
screen.blit(font.render(f"GAME OVER score: {score}", True, (248, 113, 113)), (COLS*CELL//2 - 130, ROWS*CELL//2))
pygame.display.flip()
pygame.time.wait(2500)
pygame.quit()
练习:① 加速道具;② 增加障碍物;③ 死亡后按空格重开。
打砖块练习反弹物理与大量物体管理。核心逻辑:小球与挡板/砖块/墙壁的碰撞。
import pygame
W, H = 640, 480
pygame.init()
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("打砖块 - scirco 教程")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 36)
paddle = pygame.Rect(W // 2 - 50, H - 40, 100, 14)
ball = pygame.Rect(W // 2 - 7, H - 60, 14, 14)
vx, vy = 4, -4
bricks = [pygame.Rect(c * 70 + 10, r * 28 + 60, 56, 20)
for r in range(5) for c in range(9)]
score = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]: paddle.x -= 8
if keys[pygame.K_RIGHT]: paddle.x += 8
paddle.clamp_ip(screen.get_rect())
ball.x += vx
ball.y += vy
if ball.left <= 0 or ball.right >= W: vx = -vx
if ball.top <= 0: vy = -vy
if ball.colliderect(paddle): vy = -abs(vy)
if ball.bottom >= H: running = False # 漏球结束
for brick in bricks[:]:
if ball.colliderect(brick):
bricks.remove(brick)
score += 5
vy = -vy
break
if not bricks:
print("恭喜通关!"); running = False
screen.fill((15, 23, 42))
pygame.draw.rect(screen, (59, 130, 246), paddle, border_radius=6)
pygame.draw.rect(screen, (226, 232, 240), ball, border_radius=7)
for brick in bricks:
pygame.draw.rect(screen, (250, 204, 21), brick, border_radius=4)
screen.blit(font.render(f"score: {score}", True, (226, 232, 240)), (10, 8))
pygame.display.flip()
clock.tick(60)
pygame.quit()
打包成 exe 分享给同学:
pip install pyinstaller
pyinstaller --onefile --windowed breakout.py
生成的 dist/breakout.exe 双击即可运行,对方无需安装 Python。