让球永远在屏幕上弹跳?

2024-04-18 04:24:24 发布

您现在位置:Python中文网/ 问答频道 /正文

from Tkinter import *
window = Tk()
canvas = Canvas(window, width=500, height=500, background="green")
canvas.pack()

x0 = 225
y0 = 225
x1 = 275
y1 = 275
speed_x = 2
speed_y = 3

ball = canvas.create_oval(x0,y0,x1,y1,fill="blue", tag='ball')
while True:
    canvas.move('ball', speed_x, speed_y)
    canvas.after(30)
    canvas.update()

    if x1 >= 500:
        speed_x = -2
    if x0 <= 500:
        speed_y = -3
    if y1 >= 0:
        speed_y = 2
    if y0 <= 0:
        speed_x = 3

    x0 += speed_x
    x1 += speed_x
    y0 += speed_y
    y1 += speed_y

mainloop()

我的目标是让球永远在屏幕上弹跳。现在球从右边的墙上弹开,然后消失在底部的墙上。在


Tags: fromimportiftkinterwindowwidthtkcanvas
1条回答
网友
1楼 · 发布于 2024-04-18 04:24:24

你的问题是一个非常简单的逻辑问题

这是你写的:

if x1 >= WIDTH: speed_x = -velocity
if x0 <= WIDTH: speed_y = -(velocity+1)
if y1 > 0:      speed_y = velocity
if y0 < 0:      speed_x = (velocity+1)

我们想说的是,如果我们在任何边界条件之外,沿着适当的分量反转我们的速度。在

也许你会立刻怀疑你从来没有对照高度来检查y位置,或者你怀疑你是在根据x位置来调整y速度。不管怎样,都要怀疑

这是你写的东西,按顺序排列

  1. 如果我们的右点太右,开始向左移动。检查一下。在
  2. 如果我们的左点是。。。在右边框内(?),向左移动。。。但要快一点。这没道理。在
  3. 如果我们的顶点在顶线以下,向下移动。可以。。。但不太有用。这不能纠正任何错误
  4. 如果我们的底线在顶线上,向下移动。接近,但当我们的顶点在顶线上,而不是底线时,我们可能想要反弹。差别不大,但只要我们在修理东西。在

与此逻辑相比:

^{pr2}$

相关问题 更多 >