Pong游戏球运动异常求助:速度突变、碰撞逻辑bug
Pong游戏异常问题排查与修复
问题1:球突然加速
问题出在while True循环没有添加固定延迟,循环执行速度完全依赖CPU性能,导致球的移动帧率忽快忽慢,看起来像是突然加速。
修复: 在循环内加入time.sleep(0.01)固定帧率,让球的移动速度稳定下来。
问题2:碰撞异常(边缘穿入、顶部反弹后水平高速)
原因:
- 原碰撞判断用
ball.distance(computer) < 20,但你的paddle是turtlesize(5,1)(实际高度100px、宽度20px),只有球中心贴到paddle中心才会触发碰撞,边缘区域距离超过20px,根本触发不了反弹,自然会穿进去。 - 只判断了
xcor() > 340和距离,没检查球的y坐标是否在paddle的垂直范围内。当球碰到paddle顶部/底部时,y坐标不在paddle的有效范围内,碰撞判断不生效;就算误触发,也只会反转x方向,y方向不变,结果就是球水平高速运动。
修复:
替换碰撞判断逻辑,先看球的x坐标是否到达paddle位置,再看y坐标是否在paddle的上下边界之间,这样能覆盖paddle整个垂直区域;同时给paddle加上移动边界限制,防止它移出屏幕。
修改后的完整代码
main.py
from turtle import Screen from paddle import Paddle from ball import Ball import time screen = Screen() ball = Ball() screen.bgcolor("black") screen.setup(width=800, height=600) screen.title("Pong") screen.tracer(0) screen.listen() computer = Paddle(x=350, y=0) user = Paddle(x=-350, y=0) screen.onkey(fun=computer.mv_fd, key="w") screen.onkey(fun=computer.mv_bk, key="s") while True: screen.update() time.sleep(0.01) # 固定帧率,稳定球速 ball.move() # 碰撞顶部/底部边界 if ball.ycor() >= 290 or ball.ycor() < -290: ball.bounce_y() # 碰撞右侧电脑paddle if ball.xcor() > 340 and computer.ycor() - 50 < ball.ycor() < computer.ycor() + 50: ball.bounce_x() # 碰撞左侧用户paddle(补充原代码缺失的逻辑) if ball.xcor() < -340 and user.ycor() - 50 < ball.ycor() < user.ycor() + 50: ball.bounce_x() screen.exitonclick()
ball.py
from turtle import Turtle class Ball(Turtle): def __init__(self): super().__init__() self.shape("circle") self.color("white") self.penup() self.x_move = 2 # 配合time.sleep调整速度,更直观稳定 self.y_move = 2 def move(self): new_x = self.xcor() + self.x_move new_y = self.ycor() + self.y_move self.goto(new_x, new_y) def bounce_y(self): self.y_move *= -1 def bounce_x(self): self.x_move *= -1
paddle.py
from turtle import Turtle class Paddle(Turtle): def __init__(self, x, y): super().__init__() self.shape("square") self.penup() self.color("white") self.turtlesize(5, 1) self.goto(x, y) def mv_fd(self): # 限制paddle不超出屏幕顶部 if self.ycor() < 250: self.goto(self.xcor(), self.ycor() + 30) def mv_bk(self): # 限制paddle不超出屏幕底部 if self.ycor() > -250: self.goto(self.xcor(), self.ycor() - 30)
内容的提问来源于stack exchange,提问作者techno adnan
相关产品推荐
相关产品推荐

