Setup Python + Bouncyball simulation code

Setup Python + Bouncyball simulation code

Pythonic Playground: Build Your Own Bouncing Ball Simulation

Hello, Coders!

Today, we’re diving into a hands-on Python project that will bring a satisfying, physics-based animation right to your screen. Imagine a ball bouncing around a box, reacting to gravity, friction, and walls—perfect for getting familiar with coding, physics concepts, and animation! With Python, you can set up and customize this simulation to watch your own virtual ball bounce with mesmerizing realism.

Let’s get started!

Step 1: Setting Up Python

If Python isn’t already installed, don’t worry—it’s quick and easy to set up.

  1. Download Python: Head over to python.org and grab the latest version.

  2. Install Python: Run the installer, and be sure to select “Add Python to PATH” during setup. This will allow you to use Python from the terminal.

Step 2: Install Required Libraries

For our simulation, we’ll use pygame, a popular library for making games and animations in Python.

  • To install pygame: Open a terminal or command prompt and run:

    pip install pygame

Step 3: Download and Run the Code

Now let’s get the simulation up and running!

  1. Get the Code: Copy the code below and save it as bouncing_ball.py in a folder on your computer.

  2. Run the Simulation: Open bouncing_ball.py in a code editor (such as VS Code or PyCharm) and click “Run,” or open your terminal in the file’s directory and type:

    python bouncing_ball.py
    

When you run this code, a window will open showing the ball bouncing within a circle, changing colors, and responding to gravity. It’s satisfying to watch—and even better, you can tweak the settings to create your perfect animation!

Code for the Bouncing Ball Simulation

import pygame
import math
import random

# Initialize pygame
pygame.init()
pygame.mixer.set_num_channels(500)

# Screen dimensions
WIDTH, HEIGHT = 1080, 1080
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Circle Physics Simulation")

# Colors of the rainbow
RAINBOW_COLORS = [(255, 0, 0), (255, 165, 0), (255, 255, 0), (0, 128, 0), (0, 255, 0),
                  (0, 255, 255), (0, 0, 255), (75, 0, 130), (148, 0, 211)]

# Ball settings
ball_radius = 20
ball_center = [WIDTH // 2, HEIGHT // 3.5]
ball_velocity = [9.5, 10.5]
elasticity = 0.9
gravity = 1.4

# Clock to control frame rate
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)

# Smooth color transition function
def transition_color(phase, speed):
    color_index = phase * (len(RAINBOW_COLORS) - 1)
    color1 = RAINBOW_COLORS[int(color_index) % len(RAINBOW_COLORS)]
    color2 = RAINBOW_COLORS[(int(color_index) + 1) % len(RAINBOW_COLORS)]
    factor = color_index % 1
    return [int(color1[i] + (color2[i] - color1[i]) * factor) for i in range(3)]

# Main loop
running = True
color_phase = 0

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Apply gravity and update position
    ball_velocity[1] += gravity
    ball_center[0] += ball_velocity[0]
    ball_center[1] += ball_velocity[1]

    # Check for collision with walls and reverse direction if needed
    if ball_center[0] <= ball_radius or ball_center[0] >= WIDTH - ball_radius:
        ball_velocity[0] *= -elasticity
    if ball_center[1] <= ball_radius or ball_center[1] >= HEIGHT - ball_radius:
        ball_velocity[1] *= -elasticity

    # Transition ball color
    ball_color = transition_color(color_phase, 0.01)

    # Draw background and ball
    screen.fill((0, 0, 0))
    pygame.draw.circle(screen, ball_color, [int(c) for c in ball_center], ball_radius)
    pygame.display.flip()

    # Update color phase and frame rate
    color_phase += 0.01
    clock.tick(60)

pygame.quit()

Customize and Experiment

Feel free to play around with the code! You can change the ball’s speed, size, gravity, or even add multiple balls to make it your own. Python makes it easy to tweak and experiment, so have fun finding the most satisfying settings.