import math
import random
import tkinter as tk
W, H = 800, 600
root = tk.Tk()
canvas = tk.Canvas(root, width=W, height=H, bg="black")
canvas.pack()
mouse = [-1000, -1000]
def on_move(e):
mouse[0] = e.x
mouse[1] = e.y
canvas.bind("<Motion>", on_move)
circles = []
for _ in range(random.randint(5, 15)):
r = random.randint(15, 50)
x = random.randint(r, W - r)
y = random.randint(r, H - r)
color = "#%02x%02x%02x" % (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
item = canvas.create_oval(x - r, y - r, x + r, y + r, fill=color, outline="")
circles.append({
"id": item,
"x": x,
"y": y,
"vx": random.choice([-1, 1]) * random.uniform(1, 4),
"vy": random.choice([-1, 1]) * random.uniform(1, 4),
"r": r,
})
def update():
mx, my = mouse
for c in circles:
c["x"] += c["vx"]
c["y"] += c["vy"]
if c["x"] < c["r"]:
c["x"] = c["r"]
c["vx"] = abs(c["vx"])
elif c["x"] > W - c["r"]:
c["x"] = W - c["r"]
c["vx"] = -abs(c["vx"])
if c["y"] < c["r"]:
c["y"] = c["r"]
c["vy"] = abs(c["vy"])
elif c["y"] > H - c["r"]:
c["y"] = H - c["r"]
c["vy"] = -abs(c["vy"])
dx = c["x"] - mx
dy = c["y"] - my
d = math.hypot(dx, dy)
if 0 < d < c["r"]:
nx, ny = dx / d, dy / d
dot = c["vx"] * nx + c["vy"] * ny
if dot < 0:
c["vx"] -= 2 * dot * nx
c["vy"] -= 2 * dot * ny
c["x"] = mx + nx * c["r"]
c["y"] = my + ny * c["r"]
canvas.coords(c["id"], c["x"] - c["r"], c["y"] - c["r"], c["x"] + c["r"], c["y"] + c["r"])
root.after(16, update)
update()
root.mainloop()