首页 > 解决方案 > 海龟动画随机加速/减速

问题描述

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

我一直在尝试用 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

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

标签: pythonturtle-graphics

解决方案


我不明白为什么你的动画会加速和减速。无论如何,下面是我如何根据以下问题编写相同的代码:

  • 循环在while True:像 turtle 这样的基于事件的环境中没有位置——如果当前不是问题,它将成为一个问题。我已经用计时器事件替换了它。

  • 0.1 的像素移动非常小,在海龟中看起来总是很慢。

  • 避免在关键循环中要求海龟做任何它不需要的事情。在对setx(), sety(),的调用之间xcor(), 您在您的 turtle 实例上进行了十几个方法调用。在我的重写中,我在关键循环中只有两个海龟调用,并且 .ycor()goto()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()

推荐阅读