You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python Turtle模块的Pong游戏:paddle为何远不如ball流畅?

Pong游戏中Paddle移动不流畅的问题分析

我将球的移动速率从10单位调整为2.5单位,循环每次迭代的sleep时间从0.05改为0.0125,成功把帧率提升了4倍,球的移动变得更流畅。但按我的理解,既然没把paddle的20单位移动距离缩减到1/4,paddle的速度应该也会提升4倍才对,可实际操作里paddle的移动远不如球流畅。我试过修改paddle的移动数值,还把按键绑定代码放进循环,都没解决问题。以下是简化后的相关代码(已省略计分板逻辑):

主游戏代码

from turtle import Screen
from paddle import Paddle
from ball import Ball
import time

screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor('black')
screen.title('Pong: First one to 7 wins!')
screen.listen()
screen.tracer(0)

r_paddle = Paddle((350,0))
l_paddle = Paddle((-350,0))
ball = Ball()


screen.onkey(fun=r_paddle.up, key='Up')
screen.onkey(fun=r_paddle.down, key='Down')
screen.onkey(fun=l_paddle.up, key='w')
screen.onkey(fun=l_paddle.down, key='s')


is_game_on = True

while is_game_on:
    ball.move()

    if ball.ycor() >= 285 or ball.ycor() <= -285:
        ball.wall_bounce()

    
    if ball.xcor() >= 330 and ball.xcor() < 350 and ball.distance(r_paddle) < 50:
        ball.paddle_bounce()
        while not ball.xcor() <  330:
            screen.update()
            time.sleep(0.0125)
            ball.move()

    elif ball.xcor() > 390:
        time.sleep(0.75)

    
    if ball.xcor() <= -330 and ball.xcor() > -350 and ball.distance(l_paddle) < 50:
        ball.paddle_bounce()
        while not ball.xcor() > -330:
            screen.update()
            time.sleep(0.0125)
            ball.move()
    elif ball.xcor() < -390:
        time.sleep(0.75)


    screen.update()
    time.sleep(0.0125)

screen.exitonclick()

Ball类代码

from turtle import Turtle
import random as r

class Ball(Turtle):

    def __init__(self):
        super().__init__()
        self.speed(0)
        self.color('white')
        self.pu()
        self.shape('circle')
        self.goto(0,0)
        self.rand_pos()

    def move(self):
        self.setx(self.xcor() + self.x_move)
        self.sety(self.ycor() + self.y_move)

    def rand_pos(self):
        self.x_move = 2.5* r.randrange(-1,2,2)
        self.y_move = 2.5* r.randrange(-1,2,2)

    def wall_bounce(self):
        self.y_move *= -1

    def paddle_bounce(self):
        self.x_move *= -1

    def reset(self):
        self.goto(0, 0)
        self.rand_pos()

Paddle类代码

from turtle import Turtle


MOVE_DISTANCE = 20

UP = 90

class Paddle(Turtle):

    def __init__(self, co_ordinates):
        super().__init__()
        self.speed(0)
        self.shape('square')
        self.pu()
        self.color('white')
        self.shapesize(stretch_len=5, stretch_wid=1)
        self.goto(co_ordinates)
        self.seth(UP)

    def up(self):
        self.fd(MOVE_DISTANCE)

    def down(self):
        self.bk(MOVE_DISTANCE) 

内容的提问来源于stack exchange,提问作者Junk Mail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 03:52:08