海龟动画随机加速/减速



如何阻止动画随机加速/减速?

我一直在尝试用Python做一个乒乓球游戏;然而,球似乎不时地随机加速和减速。 如何阻止这种情况发生?

我尝试改变球的速度变量,但这无济于事。我也研究了这个问题的解决方法,但我找不到任何有用的东西。

import turtle
# Window settings
wn = turtle.Screen()
wn.title('Classic Pong v1.0')
wn.bgcolor('black')
wn.setup(width=800, height=600)
wn.tracer(0)
# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape('square')
ball.color('white')
ball.penup()
ball.dx = 0.1   # Ball moves by 0.1 pixels every time
ball.dy = 0.1
# Main game loop
while True:
wn.update()
# Moving the ball
ball.setx(ball.xcor() + ball.dx)    # Updates the position of the ball every time
ball.sety(ball.ycor() + ball.dy)
# Border collision checking
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
if ball.ycor() < -280:      # Set to 280 to account for extra space
ball.sety(-280)
ball.dy *= -1
if ball.xcor() > 380:       # Set to 280 to account for extra space
ball.goto(0, 0)
ball.dx *= -1

if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1

我希望球的动画是平滑的;但是,动画的速度是随机变化的。

我看不出为什么你的动画会加快和变慢。 无论如何,以下是我如何根据以下问题编写相同的代码:

  • while True:循环在基于事件的环境中没有位置,例如 - 如果它目前不是问题,它将成为一个。 我有 将其替换为计时器事件。

  • 0.1 的像素移动非常小,在 。

  • 避免要求在关键循环中做任何不需要的事情。 在调用setx()sety()xcor()ycor()goto()之间 您在 Turtle 实例上进行了十几次方法调用。 在我的 重写我只有两个叫在关键循环中,position()setposition().

  • 我放下tracer()update(),因为我的乐器 关键循环,只有一次海龟叫声改变了 屏幕,这是tracer()的默认设置 ——所以一无所获。

修订后的代码:

from turtle import Screen, Turtle
WIDTH, HEIGHT = 800, 600
CURSOR_SIZE = 20
ball_dx = 1
ball_dy = -2.5
def move():
global ball_dx, ball_dy
x, y = ball.position()
y += ball_dy
# Border collision checking
if not CURSOR_SIZE - HEIGHT/2 < y < HEIGHT/2 - CURSOR_SIZE:
ball_dy *= -1
x += ball_dx
if not CURSOR_SIZE - WIDTH/2 < x < WIDTH/2 - CURSOR_SIZE:
x = y = 0
ball_dx *= -1
ball.setposition(x, y)
screen.ontimer(move, 50)
# Window settings
screen = Screen()
screen.title('Classic Pong v1.1')
screen.setup(WIDTH, HEIGHT)
screen.bgcolor('black')
# Ball
ball = Turtle()
ball.shape('square')
ball.color('white')
ball.speed('fastest')
ball.penup()
move()
screen.mainloop()

**

import turtle
import time  # change1
# Window settings
wn = turtle.Screen()
wn.title('Classic Pong v1.0')
wn.bgcolor('black')
wn.setup(width=800, height=600)
wn.tracer(0)
# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape('square')
ball.color('white')
ball.penup()
ball.dx = 4              # Ball moves by 0.1 pixels every time
ball.dy = 4              # change3    you can move faster by change it to 8,8
# Main game loop
while True:
wn.update()
# Moving the ball
# Updates the position of the ball every time
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
time.sleep(.03)  # change2
# Border collision checking
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
if ball.ycor() < -280:      # Set to 280 to account for extra space
ball.sety(-280)
ball.dy *= -1
if ball.xcor() > 380:       # Set to 280 to account for extra space
ball.goto(0, 0)
ball.dx *= -1
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1

**

最新更新