Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_Ball_To_Ball_Collisions.py
- from tkinter import *
- import math
- import random
- # Define constants
- NUM_POINTS = 30
- RADIUS = 10
- WIDTH = 500
- HEIGHT = 500
- # Initialize tkinter window
- root = Tk()
- root.title("Ball-To-Ball Collisions")
- canvas = Canvas(root, width=WIDTH, height=HEIGHT)
- canvas.pack()
- # Define function for calculating distance between two points
- def distance(x1, y1, x2, y2):
- return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
- # Create list of points with random locations and velocities
- points = []
- for i in range(NUM_POINTS):
- x = random.randint(RADIUS, WIDTH-RADIUS)
- y = random.randint(RADIUS, HEIGHT-RADIUS)
- angle = 2 * math.pi * random.random()
- speed = random.randint(1,5) # each ball has different speed (random between 1 to 5)
- vx = speed * math.cos(angle)
- vy = speed * math.sin(angle)
- points.append({'x': x, 'y': y, 'vx': vx, 'vy': vy, 'speed': speed})
- # Define function for updating the positions of the points
- def update_points():
- for i, point in enumerate(points):
- # Move point
- point['x'] = (point['x'] + point['vx'])
- point['y'] = (point['y'] + point['vy'])
- # Check for wall collisions and adjust position
- if point['x'] - RADIUS <= 0:
- point['x'] = RADIUS
- point['vx'] = -point['vx']
- if point['x'] + RADIUS >= WIDTH:
- point['x'] = WIDTH - RADIUS
- point['vx'] = -point['vx']
- if point['y'] - RADIUS <= 0:
- point['y'] = RADIUS
- point['vy'] = -point['vy']
- if point['y'] + RADIUS >= HEIGHT:
- point['y'] = HEIGHT - RADIUS
- point['vy'] = -point['vy']
- # Check for collisions with other points
- for j in range(i+1, len(points)):
- other = points[j]
- d = distance(point['x'], point['y'], other['x'], other['y'])
- if d < 2*RADIUS:
- # Calculate new velocities to avoid collision
- angle = math.atan2(other['y'] - point['y'], other['x'] - point['x'])
- new_vx = -point['speed'] * math.cos(angle)
- new_vy = -point['speed'] * math.sin(angle)
- # Update velocities of both points
- point['vx'], point['vy'] = new_vx, new_vy
- other['vx'], other['vy'] = -new_vx, -new_vy
- # Redraw point on canvas
- canvas.coords(point['circle'], point['x']-RADIUS, point['y']-RADIUS, point['x']+RADIUS, point['y']+RADIUS)
- # Call this function again after a delay
- root.after(15, update_points)
- # Create circles on canvas for each point
- for point in points:
- point['circle'] = canvas.create_oval(point['x']-RADIUS, point['y']-RADIUS, point['x']+RADIUS, point['y']+RADIUS, fill='yellow')
- # Start animation loop
- update_points()
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement