python - 海龟动画随机加速/减速
问题描述
如何阻止海龟动画随机加速/减速?
我一直在尝试用 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:
像 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()
推荐阅读
- ios - 反应本机iOS构建问题在提供的路径中找不到应用程序包
- c# - 在没有 Parallel.For() 的情况下在 c# 中的 for 循环中实现多线程
- python - 如何在 abaqus python 脚本中引用 findAt 列表/元组
- c# - 打印列表对象 c#
- bash - bash - 下划线后的第一个字符大写
- html - 对齐同一行上的两个按钮有效,但不是 div
- python - 需要使用 Numpy 在较大的 3D 阵列中评估较小的 3D 阵列
- php - preg_replace all non-digit characters and except all numbers wth 10 digits
- php - 从下拉列表中获取 php 变量而不提交页面
- c-preprocessor - C预处理器替换多个参数