Sure! Below is a complete Python program using pygame to simulate:
✅ Two balls (red and blue)
✅ Bouncing inside two intersecting rotating hexagons
✅ Affected by gravity and friction
✅ Balls bounce realistically off rotating walls
🔧 Requirements
Make sure you have pygame installed:
pip install pygame
🐍 Full Python Code
import pygame
import sys
import math
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 600
FPS = 60
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
# Physics constants
GRAVITY = 0.5
FRICTION = 0.995
# Set up display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Balls Bouncing in Rotating Hexagons")
clock = pygame.time.Clock()
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __rmul__(self, scalar):
return self.__mul__(scalar)
def dot(self, other):
return self.x * other.x + self.y * other.y
def mag(self):
return math.sqrt(self.x ** 2 + self.y ** 2)
def normalize(self):
m = self.mag()
if m == 0:
return Vector(0, 0)
return self * (1 / m)
def rotate(self, angle):
"""Rotate vector by angle (in radians)"""
cos_a = math.cos(angle)
sin_a = math.sin(angle)
x = self.x * cos_a - self.y * sin_a
y = self.x * sin_a + self.y * cos_a
return Vector(x, y)
class Ball:
def __init__(self, x, y, color):
self.pos = Vector(x, y)
self.vel = Vector(0, 0)
self.radius = 15
self.color = color
def update(self):
# Apply gravity
self.vel += Vector(0, GRAVITY)
# Apply friction
self.vel *= FRICTION
# Update position
self.pos += self.vel
def draw(self, surface):
pygame.draw.circle(surface, self.color, (int(self.pos.x), int(self.pos.y)), self.radius)
class Hexagon:
def __init__(self, center, radius, rotation_speed=0):
self.center = center # Vector
self.radius = radius # distance from center to vertex
self.angle = 0
self.rotation_speed = rotation_speed # radians per frame
def rotate(self):
self.angle += self.rotation_speed
def get_vertices(self):
vertices = []
for i in range(6):
angle_rad = math.pi / 3 * i + self.angle
vx = self.center.x + self.radius * math.cos(angle_rad)
vy = self.center.y + self.radius * math.sin(angle_rad)
vertices.append(Vector(vx, vy))
return vertices
def get_edges(self):
verts = self.get_vertices()
edges = []
n = len(verts)
for i in range(n):
edges.append((verts[i], verts[(i + 1) % n]))
return edges
def collide_with_ball(self, ball):
"""
Check collision between ball and hexagon edges,
and resolve collision by reflecting velocity.
"""
edges = self.get_edges()
min_dist = float('inf')
closest_edge = None
for edge in edges:
a, b = edge
# Vector AB
ab = b - a
# Vector AC (from edge start to ball)
ac = ball.pos - a
# Project AC onto AB
ab_norm = ab.normalize()
projection_length = ac.dot(ab_norm)
# Clamp projection to [0, |AB|]
projection_length = max(0, min(projection_length, ab.mag()))
closest = a + ab_norm * projection_length
dist = (ball.pos - closest).mag()
if dist < min_dist:
min_dist = dist
closest_edge = (a, b)
if min_dist <= ball.radius:
a, b = closest_edge
ab = b - a
ba = a - b
normal = ab.rotate(math.pi / 2) # perpendicular vector
normal = normal.normalize()
# Make sure normal points towards ball
if normal.dot(ball.pos - a) < 0:
normal *= -1
# Reflect velocity
if normal.dot(ball.vel) != 0: # avoid division by zero
dot = ball.vel.dot(normal)
reflected_vel = ball.vel - 2 * dot * normal
# Move ball outside of collision to prevent sticking
correction = normal * (ball.radius - min_dist + 0.1)
ball.pos += correction
# Apply new velocity (could add energy loss here too)
ball.vel = reflected_vel
return True
return False
def main():
# Create hexagons
hex1_center = Vector(WIDTH // 3, HEIGHT // 2)
hex2_center = Vector(2 * WIDTH // 3, HEIGHT // 2)
hex_radius = 200
hexagon1 = Hexagon(hex1_center, hex_radius, rotation_speed=0.005)
hexagon2 = Hexagon(hex2_center, hex_radius, rotation_speed=-0.007)
# Create balls
ball1 = Ball(WIDTH // 4, HEIGHT // 2, RED)
ball2 = Ball(3 * WIDTH // 4, HEIGHT // 2, BLUE)
running = True
while running:
clock.tick(FPS)
screen.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update hexagons
hexagon1.rotate()
hexagon2.rotate()
# Update balls
ball1.update()
ball2.update()
# Check collisions with hexagons
hexagon1.collide_with_ball(ball1)
hexagon2.collide_with_ball(ball1)
hexagon1.collide_with_ball(ball2)
hexagon2.collide_with_ball(ball2)
# Draw hexagons
edges1 = hexagon1.get_edges()
edges2 = hexagon2.get_edges()
for a, b in edges1:
pygame.draw.line(screen, (100, 100, 255), (int(a.x), int(a.y)), (int(b.x), int(b.y)), 2)
for a, b in edges2:
pygame.draw.line(screen, (255, 200, 100), (int(a.x), int(a.y)), (int(b.x), int(b.y)), 2)
# Draw balls
ball1.draw(screen)
ball2.draw(screen)
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
🧠 Features Explained:
- Vector Class: Handles all vector math like movement, rotation, and bouncing.
- Ball Class: Applies gravity & friction each frame and checks for collisions.
- Hexagon Class:
- Rotates at given speed.
- Detects edge collisions with balls.
- Reflects ball velocity based on normal of the collided edge.
- Two Intersecting Hexagons: Drawn with different colors and rotating in opposite directions.
🎮 Controls:
Just run the script. Close the window to quit.
🛠️ You Can Tweak:
GRAVITY, FRICTION constants
- Hexagon
rotation_speed
- Initial ball positions
- Hexagon sizes / positions
Let me know if you want to add sound, trails, or controls to pause/reset!