Creating a Python program that simulates two balls (red and blue) bouncing inside rotating, intersecting hexagons, with gravity and friction, involves several components:
Requirements:
- Use a graphics library (we'll use Pygame).
- Physics simulation: gravity, friction, wall collision.
- Geometry: rotating hexagons that intersect each other.
- Ball collision with rotating walls.
🚀 Summary of the Code
We will:
- Set up a Pygame window.
- Define two rotating hexagons centered at the screen.
- Implement two balls with basic physics (gravity, velocity, friction).
- Detect collisions between balls and rotating hexagon edges.
- Handle bounce using vector reflection.
✅ Prerequisites
Install pygame if you haven't:
pip install pygame
🧠 Key Concepts Used
- Vector math for ball motion and reflection.
- Rotation matrices for spinning polygons.
- Line-circle collision detection.
- Basic physics: acceleration due to gravity, friction damping.
💻 Full Python Program
import pygame
import math
import sys
# Initialize Pygame
pygame.init()
# Screen settings
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Bouncing Balls in Rotating Hexagons")
clock = pygame.time.Clock()
# Constants
FPS = 60
GRAVITY = 0.3
FRICTION = 0.99
ROTATION_SPEED = 0.01 # radians per frame
# Colors
RED = (255, 0, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Ball class
class Ball:
def __init__(self, x, y, color, radius=10):
self.pos = pygame.Vector2(x, y)
self.vel = pygame.Vector2(0, 0)
self.color = color
self.radius = radius
def update(self):
self.vel.y += GRAVITY
self.vel *= FRICTION
self.pos += self.vel
def draw(self, surface):
pygame.draw.circle(surface, self.color, (int(self.pos.x), int(self.pos.y)), self.radius)
# Generate hexagon points
def generate_hexagon(center, size, angle_offset=0):
points = []
for i in range(6):
angle = angle_offset + i * math.pi / 3
x = center[0] + size * math.cos(angle)
y = center[1] + size * math.sin(angle)
points.append((x, y))
return points
# Reflect point over a line segment
def reflect_velocity(ball_pos, ball_vel, p1, p2):
edge = pygame.Vector2(p2[0] - p1[0], p2[1] - p1[1])
normal = pygame.Vector2(-edge.y, edge.x).normalize()
distance = abs(normal.dot(pygame.Vector2(ball_pos) - pygame.Vector2(p1)))
if distance <= ball.radius:
# Reflect velocity
vel = pygame.Vector2(ball_vel)
dot = vel.dot(normal)
if dot < 0:
vel = vel - 2 * dot * normal
return vel
return ball_vel
# Main loop
rotation1 = 0
rotation2 = math.pi / 6 # Start offset
balls = [
Ball(WIDTH // 2 - 30, HEIGHT // 2, RED),
Ball(WIDTH // 2 + 30, HEIGHT // 2, BLUE)
]
running = True
while running:
dt = clock.tick(FPS) / 1000 # Delta time in seconds
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update rotations
rotation1 += ROTATION_SPEED
rotation2 -= ROTATION_SPEED
# Clear screen
screen.fill(BLACK)
# Generate hexagon points
hex1 = generate_hexagon((WIDTH // 2, HEIGHT // 2), 200, rotation1)
hex2 = generate_hexagon((WIDTH // 2, HEIGHT // 2), 150, rotation2)
# Draw hexagons
pygame.draw.polygon(screen, WHITE, hex1, 2)
pygame.draw.polygon(screen, WHITE, hex2, 2)
# Update and draw balls
for ball in balls:
ball.update()
# Check collision with both hexagons
for hexagon in [hex1, hex2]:
for i in range(len(hexagon)):
p1 = hexagon[i]
p2 = hexagon[(i + 1) % len(hexagon)]
ball.vel = reflect_velocity(ball.pos, ball.vel, p1, p2)
# Boundary check to keep ball on screen (optional)
if ball.pos.x < -ball.radius or ball.pos.x > WIDTH + ball.radius or \
ball.pos.y < -ball.radius or ball.pos.y > HEIGHT + ball.radius:
ball.pos = pygame.Vector2(WIDTH // 2, HEIGHT // 2)
ball.vel = pygame.Vector2(0, 0)
ball.draw(screen)
pygame.display.flip()
pygame.quit()
sys.exit()
🎮 Features Implemented
- Two balls (red and blue) with physics.
- Two rotating hexagons intersecting each other.
- Gravity pulls balls downward.
- Friction slows down the balls over time.
- Balls bounce off rotating hexagon walls.
- Real-time visual feedback via Pygame.
🧪 You Can Try Enhancing It By:
- Adding sound effects on collision.
- Making hexagons rotate independently.
- Adding more balls or obstacles.
- Using polygon collision instead of line-by-line checking.
Let me know if you want this implemented with Tkinter, PyOpenGL, or Web-based (JavaScript/Canvas)!