make a python app of a hexagon rotating with balls bouncing inside it, the balls should…
- User
make a python app of a hexagon rotating with balls bouncing inside it, the balls should have collision between each other and also should have gravity, make it an appealing color scheme. Avoid issues with the balls spawning inside each other and make sure that they do not phase through the hexagon
Assistant
Here's a Python app that creates a rotating hexagon with bouncing balls inside, featuring collision physics and gravity:
import pygame import sys import math import random from pygame.locals import * # Initialize pygame pygame.init() # Screen dimensions WIDTH, HEIGHT = 800, 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Rotating Hexagon with Bouncing Balls") # Colors - Pastel color scheme BACKGROUND = (25, 25, 35) HEXAGON_COLOR = (142, 68, 173) # Purple BALL_COLORS = [ (231, 76, 60), # Red (52, 152, 219), # Blue (46, 204, 113), # Green (241, 196, 15), # Yellow (230, 126, 34), # Orange ] # Physics parameters FPS = 60 GRAVITY = 0.2 FRICTION = 0.99 ELASTICITY = 0.8 ROTATION_SPEED = 0.5 # degrees per frame # Ball parameters NUM_BALLS = 10 MIN_RADIUS = 10 MAX_RADIUS = 20 MIN_SPEED = 1 MAX_SPEED = 3 # Hexagon parameters HEX_RADIUS = 200 hex_angle = 0 hex_center = (WIDTH // 2, HEIGHT // 2) class Ball: def __init__(self, x, y, radius, color): self.x = x self.y = y self.radius = radius self.color = color self.dx = random.uniform(-MAX_SPEED, MAX_SPEED) self.dy = random.uniform(-MAX_SPEED, MAX_SPEED) self.mass = radius ** 2 # Mass proportional to area def move(self): self.dy += GRAVITY self.x += self.dx self.y += self.dy self.dx *= FRICTION self.dy *= FRICTION def draw(self): pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius) # Add a highlight for 3D effect highlight = pygame.Surface((self.radius*2, self.radius*2), pygame.SRCALPHA) pygame.draw.circle(highlight, (255, 255, 255, 80), (self.radius, self.radius), self.radius//3) screen.blit(highlight, (int(self.x - self.radius), int(self.y - self.radius))) def get_hexagon_vertices(center, radius, angle): vertices = [] for i in range(6): theta = math.radians(angle + 60 * i) x = center[0] + radius * math.cos(theta) y = center[1] + radius * math.sin(theta) vertices.append((x, y)) return vertices def is_point_in_hexagon(point, vertices): x, y = point n = len(vertices) inside = False p1x, p1y = vertices[0] for i in range(n + 1): p2x, p2y = vertices[i % n] if y > min(p1y, p2y) and y <= max(p1y, p2y) and x <= max(p1x, p2x): if p1y != p2y: xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x if p1x == p2x or x <= xinters: inside = not inside p1x, p1y = p2x, p2y return inside def distance_to_line(point, line_start, line_end): x, y = point x1, y1 = line_start x2, y2 = line_end # Line length length = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) # Calculate distance if length == 0: return math.sqrt((x - x1)**2 + (y - y1)**2) # Calculate projection t = max(0, min(1, ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / (length**2))) # Calculate closest point on line proj_x = x1 + t * (x2 - x1) proj_y = y1 + t * (y2 - y1) # Return distance to closest point return math.sqrt((x - proj_x)**2 + (y - proj_y)**2) def get_collision_normal(ball, line_start, line_end): # Find closest point on line x1, y1 = line_start x2, y2 = line_end length_squared = (x2 - x1)**2 + (y2 - y1)**2 if length_squared == 0: return (ball.x - x1, ball.y - y1) t = max(0, min(1, ((ball.x - x1) * (x2 - x1) + (ball.y - y1) * (y2 - y1)) / length_squared)) closest_x = x1 + t * (x2 - x1) closest_y = y1 + t * (y2 - y1) # Normal vector from line to ball nx = ball.x - closest_x ny = ball.y - closest_y # Normalize length = math.sqrt(nx**2 + ny**2) if length > 0: nx /= length ny /= length return (nx, ny) def check_ball_hexagon_collision(ball, vertices): # Check if ball is inside hexagon if not is_point_in_hexagon((ball.x, ball.y), vertices): # Find closest edge and bounce min_dist = float('inf') closest_edge = None for i in range(len(vertices)): start = vertices[i] end = vertices[(i + 1) % len(vertices)] dist = distance_to_line((ball.x, ball.y), start, end) if dist < min_dist: min_dist = dist closest_edge = (start, end) if min_dist < ball.radius: # Collision detected, calculate bounce normal = get_collision_normal(ball, closest_edge[0], closest_edge[1]) # Calculate velocity component along normal dot_product = ball.dx * normal[0] + ball.dy * normal[1] # Apply bounce with elasticity ball.dx -= (1 + ELASTICITY) * dot_product * normal[0] ball.dy -= (1 + ELASTICITY) * dot_product * normal[1] # Move ball to prevent sticking overlap = ball.radius - min_dist ball.x += overlap * normal[0] ball.y += overlap * normal[1] return True return False def check_ball_collision(ball1, ball2): dx = ball2.x - ball1.x dy = ball2.y - ball1.y distance = math.sqrt(dx**2 + dy**2) if distance < ball1.radius + ball2.radius: # Collision detected # Normal vector if distance == 0: # Avoid division by zero nx, ny = 1, 0 else: nx, ny = dx/distance, dy/distance # Relative velocity dvx = ball2.dx - ball1.dx dvy = ball2.dy - ball1.dy # Velocity along normal velocity_along_normal = dvx * nx + dvy * ny # No collision if balls are moving away from each other if velocity_along_normal > 0: return # Impulse scalar impulse = -(1 + ELASTICITY) * velocity_along_normal impulse /= 1/ball1.mass + 1/ball2.mass # Apply impulse ball1.dx -= impulse * nx / ball1.mass ball1.dy -= impulse * ny / ball1.mass ball2.dx += impulse * nx / ball2.mass ball2.dy += impulse * ny / ball2.mass # Move balls apart to prevent sticking overlap = (ball1.radius + ball2.radius - distance) / 2 ball1.x -= overlap * nx ball1.y -= overlap * ny ball2.x += overlap * nx ball2.y += overlap * ny def create_non_overlapping_ball(balls, vertices): max_attempts = 100 for _ in range(max_attempts): radius = random.uniform(MIN_RADIUS, MAX_RADIUS) x = random.uniform(hex_center[0] - HEX_RADIUS + radius, hex_center[0] + HEX_RADIUS - radius) y = random.uniform(hex_center[1] - HEX_RADIUS + radius, hex_center[1] + HEX_RADIUS - radius) # Check if inside hexagon if not is_point_in_hexagon((x, y), vertices): continue # Check if overlapping with other balls overlapping = False for ball in balls: dx = x - ball.x dy = y - ball.y distance = math.sqrt(dx**2 + dy**2) if distance < radius + ball.radius: overlapping = True break if not overlapping: return Ball(x, y, radius, random.choice(BALL_COLORS)) # If we couldn't create a non-overlapping ball, try with minimum radius return Ball(hex_center[0], hex_center[1], MIN_RADIUS, random.choice(BALL_COLORS)) # Create balls balls = [] initial_vertices = get_hexagon_vertices(hex_center, HEX_RADIUS, hex_angle) for _ in range(NUM_BALLS): balls.append(create_non_overlapping_ball(balls, initial_vertices)) # Main game loop clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == QUIT: running = False # Update hexagon rotation hex_angle += ROTATION_SPEED vertices = get_hexagon_vertices(hex_center, HEX_RADIUS, hex_angle) # Move balls for ball in balls: ball.move() # Check ball-hexagon collisions for ball in balls: check_ball_hexagon_collision(ball, vertices) # Check ball-ball collisions for i in range(len(balls)): for j in range(i+1, len(balls)): check_ball_collision(balls[i], balls[j]) # Draw everything screen.fill(BACKGROUND) # Draw hexagon pygame.draw.polygon(screen, HEXAGON_COLOR, vertices, 0) # Add a subtle glow effect for i in range(3): pygame.draw.polygon(screen, (HEXAGON_COLOR[0], HEXAGON_COLOR[1], HEXAGON_COLOR[2], 50-i*15), get_hexagon_vertices(hex_center, HEX_RADIUS+i*5, hex_angle), 2) # Draw balls for ball in balls: ball.draw() pygame.display.flip() clock.tick(FPS) pygame.quit() sys.exit()Would you like me to explain or break down the code?
- User
make sure balls only spawn randomly inside the hexagon, also fix issues where balls phase through objects at high speeds
Assistant
Here's an improved version that ensures balls only spawn inside the hexagon and fixes the high-speed phasing issue:
import pygame import sys import math import random from pygame.locals import * # Initialize pygame pygame.init() # Screen dimensions WIDTH, HEIGHT = 800, 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Rotating Hexagon with Bouncing Balls") # Colors - Pastel color scheme BACKGROUND = (25, 25, 35) HEXAGON_COLOR = (142, 68, 173) # Purple BALL_COLORS = [ (231, 76, 60), # Red (52, 152, 219), # Blue (46, 204, 113), # Green (241, 196, 15), # Yellow (230, 126, 34), # Orange ] # Physics parameters FPS = 60 GRAVITY = 0.2 FRICTION = 0.99 ELASTICITY = 0.8 ROTATION_SPEED = 0.5 # degrees per frame MAX_SPEED = 10 # Speed limit to prevent tunneling # Ball parameters NUM_BALLS = 10 MIN_RADIUS = 10 MAX_RADIUS = 20 MIN_SPEED = 1 MAX_INITIAL_SPEED = 3 # Hexagon parameters HEX_RADIUS = 200 hex_angle = 0 hex_center = (WIDTH // 2, HEIGHT // 2) class Ball: def __init__(self, x, y, radius, color): self.x = x self.y = y self.radius = radius self.color = color self.dx = random.uniform(-MAX_INITIAL_SPEED, MAX_INITIAL_SPEED) self.dy = random.uniform(-MAX_INITIAL_SPEED, MAX_INITIAL_SPEED) self.mass = radius ** 2 # Mass proportional to area self.prev_x = x # For continuous collision detection self.prev_y = y def move(self): # Store previous position for continuous collision detection self.prev_x = self.x self.prev_y = self.y # Apply gravity self.dy += GRAVITY # Limit speed to prevent tunneling speed = math.sqrt(self.dx**2 + self.dy**2) if speed > MAX_SPEED: self.dx = (self.dx / speed) * MAX_SPEED self.dy = (self.dy / speed) * MAX_SPEED # Update position self.x += self.dx self.y += self.dy # Apply friction self.dx *= FRICTION self.dy *= FRICTION def draw(self): pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius) # Add a highlight for 3D effect highlight = pygame.Surface((self.radius*2, self.radius*2), pygame.SRCALPHA) pygame.draw.circle(highlight, (255, 255, 255, 80), (self.radius, self.radius), self.radius//3) screen.blit(highlight, (int(self.x - self.radius), int(self.y - self.radius))) def get_hexagon_vertices(center, radius, angle): vertices = [] for i in range(6): theta = math.radians(angle + 60 * i) x = center[0] + radius * math.cos(theta) y = center[1] + radius * math.sin(theta) vertices.append((x, y)) return vertices def is_point_in_hexagon(point, vertices): x, y = point n = len(vertices) inside = False p1x, p1y = vertices[0] for i in range(n + 1): p2x, p2y = vertices[i % n] if y > min(p1y, p2y) and y <= max(p1y, p2y) and x <= max(p1x, p2x): if p1y != p2y: xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x if p1x == p2x or x <= xinters: inside = not inside p1x, p1y = p2x, p2y return inside def distance_to_line_segment(point, line_start, line_end): x, y = point x1, y1 = line_start x2, y2 = line_end # Line length squared length_squared = (x2 - x1)**2 + (y2 - y1)**2 # If line is a point, return distance to that point if length_squared == 0: return math.sqrt((x - x1)**2 + (y - y1)**2) # Calculate projection t = max(0, min(1, ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / length_squared)) # Calculate closest point on line proj_x = x1 + t * (x2 - x1) proj_y = y1 + t * (y2 - y1) # Return distance to closest point return math.sqrt((x - proj_x)**2 + (y - proj_y)**2), (proj_x, proj_y) def get_collision_normal(ball, line_start, line_end): # Find closest point on line distance, closest_point = distance_to_line_segment((ball.x, ball.y), line_start, line_end) closest_x, closest_y = closest_point # Normal vector from line to ball nx = ball.x - closest_x ny = ball.y - closest_y # Normalize length = math.sqrt(nx**2 + ny**2) if length > 0: nx /= length ny /= length return (nx, ny) def line_segment_intersection(p1, p2, p3, p4): """Check if line segments (p1,p2) and (p3,p4) intersect""" x1, y1 = p1 x2, y2 = p2 x3, y3 = p3 x4, y4 = p4 # Calculate denominators den = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1) if den == 0: return False # Lines are parallel ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / den ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / den # Check if intersection is within both line segments if 0 <= ua <= 1 and 0 <= ub <= 1: x = x1 + ua * (x2 - x1) y = y1 + ua * (y2 - y1) return True, (x, y) return False, None def check_ball_hexagon_collision(ball, vertices): # First check if ball is outside hexagon inside = is_point_in_hexagon((ball.x, ball.y), vertices) if not inside: # Find closest edge and bounce min_dist = float('inf') closest_edge = None for i in range(len(vertices)): start = vertices[i] end = vertices[(i + 1) % len(vertices)] dist, _ = distance_to_line_segment((ball.x, ball.y), start, end) if dist < min_dist: min_dist = dist closest_edge = (start, end) if min_dist < ball.radius: # Collision detected, calculate bounce normal = get_collision_normal(ball, closest_edge[0], closest_edge[1]) # Calculate velocity component along normal dot_product = ball.dx * normal[0] + ball.dy * normal[1] # Apply bounce with elasticity ball.dx -= (1 + ELASTICITY) * dot_product * normal[0] ball.dy -= (1 + ELASTICITY) * dot_product * normal[1] # Move ball to prevent sticking overlap = ball.radius - min_dist ball.x += overlap * normal[0] * 1.01 # Add a little extra to prevent sticking ball.y += overlap * normal[1] * 1.01 return True # Check for continuous collision detection (line-line intersection) ball_path = ((ball.prev_x, ball.prev_y), (ball.x, ball.y)) for i in range(len(vertices)): edge = (vertices[i], vertices[(i + 1) % len(vertices)]) # Expand edge by ball radius edge_vector = (edge[1][0] - edge[0][0], edge[1][1] - edge[0][1]) edge_length = math.sqrt(edge_vector[0]**2 + edge_vector[1]**2) if edge_length == 0: continue normal = (-edge_vector[1]/edge_length, edge_vector[0]/edge_length) # Create expanded edge expanded_edge = ( (edge[0][0] + normal[0] * ball.radius, edge[0][1] + normal[1] * ball.radius), (edge[1][0] + normal[0] * ball.radius, edge[1][1] + normal[1] * ball.radius) ) # Check intersection intersect, point = line_segment_intersection(ball_path[0], ball_path[1], expanded_edge[0], expanded_edge[1]) if intersect: # Place ball at intersection point ball.x, ball.y = point # Calculate bounce normal = get_collision_normal(ball, edge[0], edge[1]) dot_product = ball.dx * normal[0] + ball.dy * normal[1] ball.dx -= (1 + ELASTICITY) * dot_product * normal[0] ball.dy -= (1 + ELASTICITY) * dot_product * normal[1] # Move ball slightly inside to prevent sticking ball.x += normal[0] * 0.1 ball.y += normal[1] * 0.1 return True return False def check_ball_collision(ball1, ball2): dx = ball2.x - ball1.x dy = ball2.y - ball1.y distance = math.sqrt(dx**2 + dy**2) if distance < ball1.radius + ball2.radius: # Collision detected # Normal vector if distance == 0: # Avoid division by zero nx, ny = 1, 0 else: nx, ny = dx/distance, dy/distance # Relative velocity dvx = ball2.dx - ball1.dx dvy = ball2.dy - ball1.dy # Velocity along normal velocity_along_normal = dvx * nx + dvy * ny # No collision if balls are moving away from each other if velocity_along_normal > 0: return # Impulse scalar impulse = -(1 + ELASTICITY) * velocity_along_normal impulse /= 1/ball1.mass + 1/ball2.mass # Apply impulse ball1.dx -= impulse * nx / ball1.mass ball1.dy -= impulse * ny / ball1.mass ball2.dx += impulse * nx / ball2.mass ball2.dy += impulse * ny / ball2.mass # Move balls apart to prevent sticking overlap = (ball1.radius + ball2.radius - distance) / 2 ball1.x -= overlap * nx * 1.01 # Add a little extra to prevent sticking ball1.y -= overlap * ny * 1.01 ball2.x += overlap * nx * 1.01 ball2.y += overlap * ny * 1.01 return True # Check for continuous collision detection # Calculate relative velocity rel_vx = ball2.dx - ball1.dx rel_vy = ball2.dy - ball1.dy # Calculate relative position rel_px = ball2.prev_x - ball1.prev_x rel_py = ball2.prev_y - ball1.prev_y # Solve quadratic equation for time of collision a = rel_vx**2 + rel_vy**2 b = 2 * (rel_px * rel_vx + rel_py * rel_vy) c = rel_px**2 + rel_py**2 - (ball1.radius + ball2.radius)**2 discriminant = b**2 - 4 * a * c if a != 0 and discriminant >= 0: t = (-b - math.sqrt(discriminant)) / (2 * a) if 0 <= t <= 1: # Collision happened during this frame # Calculate collision point ball1_x = ball1.prev_x + t * (ball1.x - ball1.prev_x) ball1_y = ball1.prev_y + t * (ball1.y - ball1.prev_y) ball2_x = ball2.prev_x + t * (ball2.x - ball2.prev_x) ball2_y = ball2.prev_y + t * (ball2.y - ball2.prev_y) # Set balls to collision point ball1.x = ball1_x ball1.y = ball1_y ball2.x = ball2_x ball2.y = ball2_y # Calculate normal at collision dx = ball2.x - ball1.x dy = ball2.y - ball1.y distance = math.sqrt(dx**2 + dy**2) if distance == 0: nx, ny = 1, 0 else: nx, ny = dx/distance, dy/distance # Calculate relative velocity dvx = ball2.dx - ball1.dx dvy = ball2.dy - ball1.dy # Velocity along normal velocity_along_normal = dvx * nx + dvy * ny # Impulse scalar impulse = -(1 + ELASTICITY) * velocity_along_normal impulse /= 1/ball1.mass + 1/ball2.mass # Apply impulse ball1.dx -= impulse * nx / ball1.mass ball1.dy -= impulse * ny / ball1.mass ball2.dx += impulse * nx / ball2.mass ball2.dy += impulse * ny / ball2.mass # Move balls apart slightly ball1.x -= nx * 0.1 ball1.y -= ny * 0.1 ball2.x += nx * 0.1 ball2.y += ny * 0.1 return True return False def create_random_point_in_hexagon(vertices, radius): # Create a bounding box for the hexagon min_x = min(v[0] for v in vertices) max_x = max(v[0]
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.