这是「Python 100 天」系列第 22 天的学习笔记:Pong:碰撞检测与计分 。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。
今天要解决的问题
经典街机 Pong:两块球拍(左 W/S,右 ↑/↓),一个球来回弹,球出界对方得分。README 知识点:按键控制球拍、球拍类、球类与运动、反弹逻辑、碰撞检测、出界检测、计分与变速。
一、用"速度分量"表示运动
球不需要角度,只需要两个增量:
1 2 3 4 5 self.x_move = 10 self.y_move = 10 def move(self): self.goto(self.xcor() + self.x_move, self.ycor() + self.y_move)
撞上下边界:y_move *= -1(垂直方向反向);
撞到球拍:x_move *= -1(水平方向反向)。
这就是最朴素的"反射",后面做 3D/物理引擎时,本质仍是这个思路的推广。
二、碰撞检测
1 ball.distance(paddle) < 50
用"球心到球拍中心的距离"近似判定。球拍被拉长到 100 像素高(shapesize(stretch_wid=5),默认 20×5=100),所以 50 是合理阈值。
再加一个方向条件,避免球在球拍背面也被弹回来:
1 ball.distance(r_paddle) < 50 and ball.xcor() > 320
三、碰撞检测中的运算符优先级
1 if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(l_paddle) < 50 and ball.xcor() < -320:
and 的优先级高于 or,所以等价于 (A and B) or (C and D),这里是对的 。但读起来费劲,工程上应该加括号,让意图一眼可见。
代码全文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 # ============================================================ # day22/main.py —— Pong(乒乓球对打) # 作用:左右两块球拍,球来回弹,谁漏球对方得分。 # 知识点:多对象 + 键盘事件、distance() 判碰拍、and/or 优先级、 # 用 ball.move_speed 动态控制帧间隔 # 运行:python main.py(需 paddle.py / ball.py / scoreboard.py) # ============================================================ from turtle import Screen from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time screen = Screen() screen.bgcolor("black") # 800×600:x 范围约 -400~400,y 范围约 -300~300。 screen.setup(width=800, height=600) screen.title("Pong") screen.tracer(0) # 创建两块球拍:构造参数是位置,右拍在 (350, 0),左拍在 (-350, 0)。 r_paddle = Paddle((350, 0)) l_paddle = Paddle((-350, 0)) ball = Ball() scoreboard = Scoreboard() screen.listen() # onkeypress 与 onkey 几乎等价,区别是 onkeypress 只在“按下”时触发(不像 onkey 可能重复触发)。 # 注意传的是方法对象(不带括号)。 screen.onkeypress(r_paddle.go_up, "Up") screen.onkeypress(r_paddle.go_down, "Down") screen.onkeypress(l_paddle.go_up, "w") screen.onkeypress(l_paddle.go_down, "s") game_is_on = True while game_is_on: # 每次碰拍 move_speed 会乘 0.9(越来越小),于是球速越来越快——难度递增就是这么实现的。 time.sleep(ball.move_speed) screen.update() ball.move() # 上下撞墙:y 超过 ±280 就反弹。 if ball.ycor() > 280 or ball.ycor() < -280: ball.bounce_y() # 左右碰拍: # and 的优先级高于 or,所以这行等价于 (A and B) or (C and D): # 右拍:(离右拍近) 且 (球跑到了右侧) # 左拍:(离左拍近) 且 (球跑到了左侧) # 两个条件都要有,否则球在对面半场飞过时也会被误判为“碰到”。 if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(l_paddle) < 50 and ball.xcor() < -320: ball.bounce_x() # 球飞出右边界 → 左方得分(因为右拍没接住)。 if ball.xcor() > 380: ball.reset_position() scoreboard.l_point() # 球飞出左边界 → 右方得分。 if ball.xcor() < -380: ball.reset_position() scoreboard.r_point() screen.exitonclick()
ball.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 # ============================================================ # day22/ball.py —— 球 # 作用:按固定增量移动;撞墙翻转 y 方向,撞拍翻转 x 方向;每次碰撞微微加速。 # 知识点:继承 Turtle、速度用“增量变量”表示、*= -1 反向、 # home() 回到原点、速度与帧间隔的关系 # ============================================================ from turtle import Turtle class Ball(Turtle): def __init__(self): # 初始化父类,才能用 shape / goto 等方法。 super().__init__() self.shape("square") self.color("white") self.penup() # x_move / y_move 是“每帧位移量”(像素),不是速度单位。 # 真正的速度 = 位移量 ÷ 帧间隔,所以改这两个数或改 move_speed 都能变速。 self.x_move = 10 self.y_move = 10 # move_speed 是主循环里 time.sleep 的秒数:越小越快。 self.move_speed = 0.1 # 移动一帧:当前位置 + 位移量。 def move(self): new_x = self.xcor() + self.x_move new_y = self.ycor() + self.y_move self.goto(new_x, new_y) # 上下反弹:把 y 方向的增量反向(正变负、负变正)。 def bounce_y(self): self.y_move *= -1 # 每次碰撞把间隔乘 0.9 → 间隔变小 → 球变快。跑久了会快到看不清,这是原设计。 self.move_speed *= 0.9 # 左右反弹:把 x 方向增量反向。 def bounce_x(self): self.x_move *= -1 self.move_speed *= 0.9 # 得分后重置:回中心、恢复初始速度,并让球朝“上一次的反方向”发球。 def reset_position(self): # home():回到坐标原点 (0, 0) 并恢复初始朝向(向右)。 self.home() self.move_speed = 0.1 # 调用 bounce_x 只是为了翻转 x_move,让发球方向左右交替。 self.bounce_x()
paddle.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 # ============================================================ # day22/paddle.py —— 球拍 # 作用:一个被拉长的方块,只能上下移动。 # 知识点:构造参数、shapesize 拉伸成竖条、goto 同时改 x/y # ============================================================ from turtle import Turtle class Paddle(Turtle): # 参数 position:(x, y) 元组,指定球拍初始位置 # 返回值:无(构造函数) def __init__(self, position): super().__init__() self.shape("square") self.color("white") # 默认方块 20×20;stretch_wid=5 纵向拉 5 倍 → 100 像素高, # stretch_len=1 横向不变 → 20 像素宽,正好是根竖条。 self.shapesize(stretch_wid=5, stretch_len=1) self.penup() self.goto(position) # 上移 20 像素。无参数、无返回值。 def go_up(self): new_y = self.ycor() + 20 # goto(x, y):x 保持不变、只改 y——这就是“只能上下动”的实现方式。 self.goto(self.xcor(), new_y) # 下移 20 像素,逻辑同上。 def go_down(self): new_y = self.ycor() - 20 self.goto(self.xcor(), new_y)
scoreboard.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 # ============================================================ # day22/scoreboard.py —— Pong 计分板(左右两个数字) # 作用:屏幕上端显示左、右两方分数,得分就重画。 # 知识点:一个海龟画两处文字、clear() 后必须重新 goto(位置会被保留但内容被清)、 # 80 号大字 # ============================================================ from turtle import Turtle class Scoreboard(Turtle): def __init__(self): super().__init__() self.color("white") self.penup() self.hideturtle() # 左右两个独立分数。 self.l_score = 0 self.r_score = 0 # 造好先画一次 0 : 0。 self.update_scoreboard() # 重画比分。无参数、无返回值。 def update_scoreboard(self): # clear() 擦掉上一次写的两个数字,避免叠字。 self.clear() # 先挪到左侧位置写左分。 self.goto(-100, 190) # write 的第一个参数可以是数字(turtle 会自动转成字符串显示)。 self.write(self.l_score, align="center", font=("Times New Roman", 80, "normal")) # 再挪到右侧写右分——同一只海龟可以在不同位置多次 write。 self.goto(100, 190) self.write(self.r_score, align="center", font=("Times New Roman", 80, "normal")) # 左方得分:加 1 后重画。 def l_point(self): self.l_score += 1 self.update_scoreboard() # 右方得分:加 1 后重画。 def r_point(self): self.r_score += 1 self.update_scoreboard()
代码走读
Paddle(Turtle):shapesize(stretch_wid=5, stretch_len=1) 把默认 20×20 的方块拉成 100×20 的球拍;go_up/go_down 每次 ±20,用 goto 而不是 forward ,这样不管朝向如何都沿 y 轴移动。
Ball(Turtle):x_move/y_move 是速度分量,move_speed 是每帧的休眠时间(越小越快)。
bounce_y() / bounce_x():分量取反,同时 move_speed *= 0.9 让球越打越快。注意两个方向都会加速 ,几轮之后会快到看不清。
reset_position():home() 回原点、速度重置、bounce_x() 让球朝刚才丢分的那一侧发球。
主循环:sleep(ball.move_speed) → update() → move() → 三个判定(上下边界、球拍、左右出界)。
计分板:l_point() / r_point() 加分后重绘。write() 的第一个参数可以直接是数字。
这段代码的问题
球拍可以飞出屏幕 :go_up 没有上限判断。
球速递减没有下限 :move_speed 会趋近 0,sleep(0) 之后 CPU 占用飙升。
home() 把朝向也重置了 :home() 会让海龟回到原点并恢复初始朝向,配合 bounce_x 行为不一定符合预期。
碰撞用圆形距离近似 :球拍是长条,用中心距离判定在边角处会误判。工业级做法是 AABB(矩形包围盒)相交检测。
运行效果
黑色背景,左右两块白色球拍,白球来回弹,出界后对方加分并重新发球。
易错点
onkeypress 与 onkey 的区别 :onkeypress 按住会连发,onkey 只响应一次。做游戏用前者。
不用 xcor()/ycor() 而用 pos() :pos() 返回元组,还得再取下标。
改了 x_move 忘了改 y_move :球只会水平移动。
tracer(0) 后忘记 update() :画面完全不动。
动手改
球拍加上下边界限制:new_y = min(max(new_y, -240), 240)。
给 move_speed 设下限 0.02。
用矩形相交重写碰撞检测,对比手感差异。
源文件逐个讲解
5 个文件 ,结构几乎照抄 Day 21 的贪吃蛇:一个对象一个文件 + 一个组装层。
文件
行数
职责
ball.py32 Ball(Turtle):移动、反弹、加速、复位
paddle.py21 Paddle(Turtle):上下移动
scoreboard.py29 Scoreboard(Turtle):左右比分
main.py45 组装 + 碰撞与出界判定
README.md12 说明页
ball.py(32 行)
1 2 3 4 5 6 7 8 9 class Ball(Turtle): def __init__(self): super().__init__() self.shape("square") self.color("white") self.penup() self.x_move = 10 self.y_move = 10 self.move_speed = 0.1
球用 square 形状 ——因为 Pong(1972)原版就是一个白方块,不是圆。还原历史 ,不是偷懒。
x_move / y_move 是「每帧位移」 ,不是速度本身。用「增量」表示方向 + 速率,是这份代码最核心的设计 :反弹只要把其中一个乘 -1,不用管角度、不用三角函数。
1 2 3 4 def move(self): new_x = self.xcor() + self.x_move new_y = self.ycor() + self.y_move self.goto(new_x, new_y)
三行。goto 是「瞬移」 ,配合 screen.tracer(0) 就变成了动画。
1 2 3 4 5 6 7 def bounce_y(self): self.y_move *= -1 self.move_speed *= 0.9 def bounce_x(self): self.x_move *= -1 self.move_speed *= 0.9
两个反弹函数都顺手加速 (move_speed *= 0.9,因为 move_speed 是 sleep 的秒数,越小越快)。
问题在于 bounce_y 也加速 :撞上下墙只是「反弹」,不该让游戏变快。结果是一局打得越久、上下墙撞得越多、球越快 ,最后快到穿模。真实的 Pong 只在击中球拍 时加速。
1 2 3 4 def reset_position(self): self.home() self.move_speed = 0.1 self.bounce_x()
home() 把球送回 (0,0) 并恢复初始朝向 (Turtle 的内置方法)。
bounce_x() 在复位后调用,是为了「把球发向失分的那一方」 ——上一球向右出界,复位后 x_move 已经是负的(向左);再 bounce_x() 又变正(向右)……这里逻辑是反的 :
右边界出界 → reset_position() → home() → bounce_x() 把 x_move 从 +10 翻成 -10;
但 bounce_x 在出界时并没有被调用过 ,所以 x_move 本来还是 +10,翻成 -10 后球向左飞 ——正好发给「丢分的那一方」是对的 ?
再想一遍:右边界出界 = 左玩家得分(l_point),球应该发给右玩家 (向右)。但复位后 x_move = -10(向左),发给了刚得分的左玩家 。方向反了 。
正确做法是「复位后朝失分方发球」:
1 2 3 4 def reset_position(self, direction=1): self.home() self.move_speed = 0.1 self.x_move = 10 * direction # 右出界发向右(+1),左出界发向左(-1)
paddle.py(21 行)
1 2 3 4 5 6 7 8 class Paddle(Turtle): def __init__(self, position): super().__init__() self.shape("square") self.color("white") self.shapesize(stretch_wid=5, stretch_len=1) self.penup() self.goto(position)
__init__(self, position) 接收一个坐标元组 ——同一份代码造出左右两个球拍(Paddle((350,0)) 和 Paddle((-350,0)))。参数化位置,是「一个类造多个实例」的标准做法 。
shapesize(stretch_wid=5, stretch_len=1) :宽拉 5 倍(20×5=100 像素高)、长不变(20 宽)。注意参数名 :wid 是纵向(y),len 是横向(x)——和直觉相反,容易搞错。
1 2 3 def go_up(self): new_y = self.ycor() + 20 self.goto(self.xcor(), new_y)
每次按键盘移 20 像素 。goto 需要 x、y 两个坐标,所以 xcor() 原样传回去。
没有边界限制 :一直按上,球拍会跑出屏幕顶部,再也回不来(虽然还能按下)。应该加 if new_y < 250 。
scoreboard.py(29 行)
1 2 3 4 5 6 def update_scoreboard(self): self.clear() self.goto(-100, 190) self.write(self.l_score, align="center", font=("Times New Roman", 80, "normal")) self.goto(100, 190) self.write(self.r_score, align="center", font=("Times New Roman", 80, "normal"))
左分在 (-100,190),右分在 (100,190) ,字号 80——巨大的数字是 Pong 的标志性视觉 。
write(self.l_score, ...) 直接传 int :turtle 会内部转字符串,能跑,但严格说该 str(self.l_score)。
clear() 会清掉这个海龟写过的所有东西 ,然后重写两个分数——左右两个数字是同一次重绘 ,所以不会出现「只更新一边」的闪烁。
main.py(45 行)
1 2 3 screen.setup(width=800, height=600) r_paddle = Paddle((350, 0)) l_paddle = Paddle((-350, 0))
800×600 比贪吃蛇的 600×600 宽 ,因为是横向对打。
1 2 screen.onkeypress(r_paddle.go_up, "Up") screen.onkeypress(l_paddle.go_up, "w")
onkeypress 和 onkey 的区别 :onkeypress 在按住时连续触发 (适合移动),onkey 只在按下那一刻触发一次 。Pong 必须用 onkeypress。
1 2 3 4 5 6 7 8 9 10 while game_is_on: time.sleep(ball.move_speed) screen.update() ball.move() if ball.ycor() > 280 or ball.ycor() < -280: ball.bounce_y() if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(l_paddle) < 50 and ball.xcor() < -320: ball.bounce_x()
这行 if 依赖运算符优先级 :and 比 or 高,所以等价于 (A and B) or (C and D)——恰好是想要的 。但可读性差,应该加括号。
distance(r_paddle) < 50 :球拍高 100、球 20,中心距小于 50 才算碰到。ball.xcor() > 320 是「球已经接近右拍」的条件 ——防止球在左半场时「隔着半个屏幕距离很近」误判(其实 distance 已经包含了 x 距离,这个附加条件是为了防止球从球拍背后穿过时又反弹一次)。
致命缺陷:没有「穿透」防护 。球每帧移 10 像素,球拍宽 20——正常速度下能挡住 。但 bounce_y 会让球越来越快,move_speed 降到 0.03 时一帧还是 10 像素(位移没变,只是刷新变快)……位移恒定 10,所以不会穿透 。这条其实安全。
真正的问题是「球贴住球拍时反复反弹」 :反弹后球还在球拍附近(距离仍 <50),下一帧又会命中同一个 if,再翻一次方向 ——球会在拍面上「抖动」。加个「刚反弹过就跳过一帧」的标志位能解决。
1 2 3 if ball.xcor() > 380: ball.reset_position() scoreboard.l_point()
球心超过 380 算出界 (窗口半宽 400,球半宽 10)。
这份代码的问题
reset_position 发球方向反了 (发给刚得分的一方)。
撞上下墙也加速 (bounce_y 里的 move_speed *= 0.9)。
球拍没有边界限制 ,能推出屏幕。
球贴拍时可能反复反弹 (无冷却)。
if 依赖优先级 ,应加括号。
scoreboard 写 int 而非 str 。
README.md(12 行)
标题 Day 22 - Build Pong: The Famous Arcade Game,知识点:Create Paddles and Ball、Write Paddle and Ball Logic、Detect Collisions with Wall and Paddles、Detect When Paddle Misses、Score Keeping、Increase Ball Speed。
「Increase Ball Speed」正是 move_speed *= 0.9 那两行 ——课程明确要求「越打越快」,只是这份实现把「撞墙」也算成了加速条件。
五个文件的关系
1 2 3 4 main.py ├── paddle.Paddle((350,0)) / ((-350,0)) ├── ball.Ball() └── scoreboard.Scoreboard()
和 Day 21 完全同构 :三个「继承 Turtle 的小类」+ 一个「知道所有规则的 main」。这种结构可以直接套到任何 2D 游戏上 ——Day 86 的 Breakout 就是它的变体(多了砖块)。