Skip to content

splotchysnow/Ball-Physics-Simulation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

Ball Physics Simulation

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.

Demo

8 colored balls spawn with random positions and velocities, collide elastically, and bounce off the walls indefinitely.

Physics

  • 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 (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

Requirements

  • Python 3.x
  • No external dependencies — uses only the standard library (turtle, math, random, time)

Run

python balls.py

Configuration

All 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

Code Structure

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

About

2D elastic collision simulator — balls bounce and collide with physically accurate momentum transfer, built with Python turtle

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages