Bouncing Balls in Spinning Hexagons
Here's a Python program using Pygame that simulates two balls (red and blue) bouncing inside two intersecting spinning hexagons. The balls are affected by gravity and friction, and they bounce off the rotating walls.
import pygame
import sys
import math
import random
# Initialize pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 600
FPS = 60
GRAVITY = 0.2
FRICTION = 0.99
BOUNCE_FACTOR = 0.8
BALL_RADIUS = 10
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
HEXAGON_COLOR = (100, 100, 200)
# Set up the display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Bouncing Balls in Spinning Hexagons")
clock = pygame.time.Clock()
class Ball:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.radius = BALL_RADIUS
self.vx = random.uniform(-2, 2)
self.vy = random.uniform(-2, 2)
def update(self):
# Apply gravity
self.vy += GRAVITY
# Apply friction
self.vx *= FRICTION
self.vy *= FRICTION
# Update position
self.x += self.vx
self.y += self.vy
def draw(self):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
def check_collision(self, hexagon1, hexagon2):
# Check collision with hexagon edges
for hexagon in [hexagon1, hexagon2]:
for i in range(len(hexagon)):
x1, y1 = hexagon[i]
x2, y2 = hexagon[(i + 1) % len(hexagon)]
# Calculate line equation: ax + by + c = 0
a = y2 - y1
b = x1 - x2
c = x2 * y1 - x1 * y2
# Distance from ball center to line
distance = abs(a * self.x + b * self.y + c) / math.sqrt(a**2 + b**2)
if distance < self.radius:
# Calculate reflection
normal_x = a / math.sqrt(a**2 + b**2)
normal_y = b / math.sqrt(a**2 + b**2)
# Dot product of velocity and normal
dot = self.vx * normal_x + self.vy * normal_y
# Reflect velocity
self.vx = self.vx - 2 * dot * normal_x
self.vy = self.vy - 2 * dot * normal_y
# Apply bounce factor
self.vx *= BOUNCE_FACTOR
self.vy *= BOUNCE_FACTOR
# Move ball outside the wall to prevent sticking
overlap = self.radius - distance
self.x += normal_x * overlap * 1.1
self.y += normal_y * overlap * 1.1
def create_hexagon(center_x, center_y, size, rotation=0):
hexagon = []
for i in range(6):
angle = math.radians(60 * i + rotation)
x = center_x + size * math.cos(angle)
y = center_y + size * math.sin(angle)
hexagon.append((x, y))
return hexagon
def main():
# Create balls
red_ball = Ball(WIDTH // 4, HEIGHT // 2, RED)
blue_ball = Ball(3 * WIDTH // 4, HEIGHT // 2, BLUE)
# Hexagon parameters
hex_size = 150
rotation_angle = 0
rotation_speed = 0.5
# Main game loop
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# Clear the screen
screen.fill(BLACK)
# Update rotation angle
rotation_angle += rotation_speed
# Create two intersecting hexagons
hexagon1 = create_hexagon(WIDTH // 3, HEIGHT // 2, hex_size, rotation_angle)
hexagon2 = create_hexagon(2 * WIDTH // 3, HEIGHT // 2, hex_size, -rotation_angle)
# Update balls
red_ball.update()
blue_ball.update()
# Check collisions with hexagon edges
red_ball.check_collision(hexagon1, hexagon2)
blue_ball.check_collision(hexagon1, hexagon2)
# Check boundary collisions
for ball in [red_ball, blue_ball]:
if ball.x - ball.radius < 0:
ball.x = ball.radius
ball.vx = -ball.vx * BOUNCE_FACTOR
elif ball.x + ball.radius > WIDTH:
ball.x = WIDTH - ball.radius
ball.vx = -ball.vx * BOUNCE_FACTOR
if ball.y - ball.radius < 0:
ball.y = ball.radius
ball.vy = -ball.vy * BOUNCE_FACTOR
elif ball.y + ball.radius > HEIGHT:
ball.y = HEIGHT - ball.radius
ball.vy = -ball.vy * BOUNCE_FACTOR
# Draw hexagons
pygame.draw.polygon(screen, HEXAGON_COLOR, hexagon1)
pygame.draw.polygon(screen, HEXAGON_COLOR, hexagon2)
# Draw balls
red_ball.draw()
blue_ball.draw()
# Update the display
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
How the Program Works:
-
Initialization: Sets up the Pygame environment with constants for physics parameters.
-
Ball Class:
- Tracks position, velocity, and color of each ball
- Handles physics updates (gravity and friction)
- Implements collision detection and response with hexagon edges
-
Hexagon Creation:
- Creates two hexagons that rotate in opposite directions
- The hexagons intersect in the center of the screen
-
Physics Simulation:
- Gravity pulls balls downward
- Friction slows down the balls over time
- Balls bounce off hexagon edges with realistic physics
- Balls also bounce off screen boundaries
-
Collision Detection:
- Uses line equations to detect when a ball hits a hexagon edge
- Calculates reflection vectors for realistic bouncing
- Prevents balls from getting stuck in walls
To run this program, you'll need to have Pygame installed. If you don't have it, you can install it with:
pip install pygame
The program creates a visually interesting simulation with two balls bouncing around in spinning hexagons, demonstrating physics principles like gravity, friction, and elastic collisions.