我用python编写了一个游戏,其中的目标是将球弹离平台。 一切都很好,但平台的运动不是那么平稳。你能帮我把站台移动得更平稳些吗?如果代码不太清楚,我很抱歉,但我是python新手
import tkinter as tk
import random
root = tk.Tk()
width = 900
height = 500
canvas = tk.Canvas(root, bg='white', width=width, height=height)
canvas.pack()
x = random.randrange(700)
ball = canvas.create_oval(x+10, 10, x+50, 50, fill='green')
platform_y = height - 20
platform = canvas.create_rectangle(width//2-50, platform_y, width//2+50, platform_y+10, fill='black')
xspeed = 2
yspeed = 2
skore = 0
body = 0
def move_ball():
global xspeed
global yspeed
x1, y1, x2, y2 = canvas.coords(ball)
if x1 <= 0 or x2 >= width:
xspeed = -xspeed
if y1 <= 0:
yspeed = 10
elif y2 == platform_y:
cx = (x1 + x2) // 2
px1, _, px2, _ = canvas.coords(platform)
if px1 <= cx <= px2:
yspeed = -10
else:
canvas.create_text(width//2, height//2, text='Game Over', font=('Arial Bold', 32), fill='red')
return
canvas.move(ball, xspeed, yspeed)
canvas.after(20, move_ball)
def board_right(event):
x1, y1, x2, y2 = canvas.coords(platform)
if x2 < width:
dx = min(width-x2, 10)
canvas.move(platform, dx, 0)
def board_left(event):
x1, y1, x2, y2 = canvas.coords(platform)
if x1 > 0:
dx = min(x1, 10)
canvas.move(platform, -dx, 0)
canvas.bind_all('<Right>', board_right)
canvas.bind_all('<Left>', board_left)
move_ball()
root.mainloop()
问题是平台的速度取决于键盘的自动重复速度
不要为每个
<Right>
或<Left>
事件移动一次,而是使用按键开始平台向所需方向移动,并使用按键释放停止平台移动。然后,使用after
沿给定方向重复移动平台例如:
上面的代码不能处理您可能同时按下两个键的情况,但是可以使用一些额外的逻辑来处理。重点是演示如何使用关键点启动和停止动画
相关问题 更多 >
编程相关推荐