A 2D elastic collision simulator built with Python's turtle graphics library. Balls bounce around a bounded canvas with physically accurate momentum transfer on both wall and ball-to-ball collisions.
8 colored balls spawn with random positions and velocities, collide elastically, and bounce off the walls indefinitely.
- Elastic collisions — momentum and kinetic energy are conserved using the 2D elastic collision formula resolved along the collision normal
- Mass — each ball's mass is proportional to
r³(radius cubed), matching volumetric scaling - Wall bounce — velocity component normal to the wall is reflected on impact
- Overlap correction — a static correction pass separates overlapping balls each frame to prevent tunneling artifacts
- Python 3.x
- No external dependencies — uses only the standard library (
turtle,math,random,time)
python balls.pyAll tunable constants are at the top of the file:
| Constant | Default | Description |
|---|---|---|
SCREEN_SIZE |
400 |
Canvas width and height in pixels |
SCREEN_PADDING |
20 |
Inset from canvas edge to the wall boundary |
TURTLE_RADIUS |
8 |
Radius of each ball (also affects mass) |
num_of_balls |
8 |
Number of balls spawned |
ball_colors |
9 colors | Pool of colors randomly assigned to balls |
| Section | Description |
|---|---|
Ball class |
Stores position, velocity, mass, and the turtle drawer; exposes speed(), angle(), kinetic_energy(), move() |
wall_collision() |
Reflects velocity on boundary contact and clamps position inside bounds |
ball_collision() |
Detects next-frame overlap (dnf) and applies the 2D elastic collision formula |
static_collision() |
Separates balls that are currently overlapping (position correction) |
| Game loop | while True — moves all balls, then runs collision detection each frame |