我对编程非常陌生,我试图制作一个简单的动画,在其中将10个随机大小,随机颜色和随机速度的球附加到画布上。这是代码:
from tkinter import *
import random
import time
WIDTH = 900
HEIGHT = 700
tk = Tk()
canvas = Canvas(tk, width = WIDTH, height = HEIGHT)
tk.title("Drawing")
canvas.pack()
COLORS = ["white", "black", "red", "blue", "green", "yellow", "purple", "orange", "gray"]
balls = []
class Ball:
def __init__(self, color, size):
self.shape = canvas.create_oval(10, 10, size, size, fill = color)
self.xspeed = random.randrange(-11, 11)
self.yspeed = random.randrange(-11, 11)
def move(self):
canvas.move(self.shape, self.xspeed, self.yspeed)
pos = canvas.coords(self.shape)
if pos[3] >= HEIGHT or pos[1] <= 0:
self.yspeed = -self.yspeed
if pos[2] >= WIDTH or pos[0] <= 0:
self.xspeed = -self.xspeed
for i in range(10):
size = random.randrange(20, 150)
color = random.choice(COLORS)
balls.append(Ball(color, size))
while True:
for ball in balls:
ball.move()
tk.update()
time.sleep(0.01)
tk.mainloop()
问题是球i彼此重叠。 e。当球彼此接触时,什么也没发生。我希望球在彼此接触时相互反弹。我花了几个小时来寻找答案并尝试不同的方法,但似乎无济于事。你们能帮我吗?