Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_elastic_collision_by_time.py
- import tkinter as tk
- import random
- import math
- import time
- WW, HH = 600, 600
- BALL_RADIUS = 20
- NUM_BALLS = 60
- root = tk.Tk()
- root.geometry(f"{WW}x{HH}+0+0")
- canvas = tk.Canvas(root, width=WW, height=HH)
- canvas.pack()
- balls = []
- for _ in range(NUM_BALLS):
- x = random.randint(BALL_RADIUS, WW - BALL_RADIUS)
- y = random.randint(BALL_RADIUS, HH - BALL_RADIUS)
- angle = random.uniform(0, 2 * math.pi)
- speed = 90
- vx = speed * math.cos(angle)
- vy = speed * math.sin(angle)
- id = canvas.create_oval(x - BALL_RADIUS, y - BALL_RADIUS,
- x + BALL_RADIUS, y + BALL_RADIUS,
- fill="#%06x" % random.randint(0, 0xFFFFFF))
- balls.append((x, y, vx, vy, id, time.time()))
- BALL_RADIUS2 = BALL_RADIUS + 2
- while 1:
- current_time = time.time()
- for i, (x, y, vx, vy, id, last_update) in enumerate(balls):
- dt = current_time - last_update
- x += vx * dt
- y += vy * dt
- for j, (x2, y2, vx2, vy2, id2, _) in enumerate(balls):
- if i != j:
- dx = x - x2
- dy = y - y2
- distance = math.sqrt(dx ** 2 + dy ** 2)
- if distance < 2 * BALL_RADIUS:
- # Calculate the normal vector
- nx = dx / distance
- ny = dy / distance
- # Calculate the tangent vector
- tx = -ny
- ty = nx
- # Project the velocities onto the tangent and normal vectors
- v1n = vx * nx + vy * ny
- v1t = vx * tx + vy * ty
- v2n = vx2 * nx + vy2 * ny
- v2t = vx2 * tx + vy2 * ty
- # Swap the normal components of the velocities
- v1n, v2n = v2n, v1n
- # Convert the velocities back to the original coordinate system
- vx = v1n * nx + v1t * tx
- vy = v1n * ny + v1t * ty
- vx2 = v2n * nx + v2t * tx
- vy2 = v2n * ny + v2t * ty
- # Update the positions to ensure the balls don't overlap
- x += (2 * BALL_RADIUS2 - distance) * nx / 2
- y += (2 * BALL_RADIUS2 - distance) * ny / 2
- x2 -= (2 * BALL_RADIUS2 - distance) * nx / 2
- y2 -= (2 * BALL_RADIUS2 - distance) * ny / 2
- balls[i] = (x, y, vx, vy, id, current_time)
- balls[j] = (x2, y2, vx2, vy2, id2, current_time)
- if x - BALL_RADIUS < 0:
- x = BALL_RADIUS2
- vx *= -1
- elif x + BALL_RADIUS > WW:
- x = WW - BALL_RADIUS2
- vx *= -1
- if y - BALL_RADIUS < 0:
- y = BALL_RADIUS2
- vy *= -1
- elif y + BALL_RADIUS > HH:
- y = HH - BALL_RADIUS2
- vy *= -1
- canvas.coords(id, x - BALL_RADIUS, y - BALL_RADIUS,
- x + BALL_RADIUS, y + BALL_RADIUS)
- balls[i] = (x, y, vx, vy, id, current_time)
- root.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement