Код: Выделить всё
import pygame
import sys
import math
import random
# Initialize Pygame
pygame.init()
# Set up the window
width, height = 600, 600
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bouncing Balls Inside a Circle")
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
# Circle parameters
circle_center = (width // 2, height // 2)
circle_radius = 200
circle_thickness = 3
# Ball parameters
ball_radius = 10
balls = []
# Function to create a new ball with a random color
def create_ball():
angle = random.uniform(0, 2 * math.pi)
distance = random.uniform(0, circle_radius - ball_radius)
x = circle_center[0] + distance * math.cos(angle)
y = circle_center[1] + distance * math.sin(angle)
speed = [random.choice([-.25, .25]), random.choice([-.25, .25])] # Random initial speed
color = random.choice(colors)
return {"pos": [x, y], "speed": speed, "color": color}
# Function to check collision between balls
def check_collision(ball1, ball2):
dist = math.sqrt((ball1["pos"][0] - ball2["pos"][0]) ** 2 + (ball1["pos"][1] - ball2["pos"][1]) ** 2)
return dist 0:
balls.append(create_ball())
# Add two initial balls
balls.append(create_ball())
balls.append(create_ball())
# Main loop
while True:
window.fill(BLACK)
# Check for events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Update ball positions
for ball in balls:
ball["pos"][0] += ball["speed"][0]
ball["pos"][1] += ball["speed"][1]
# Check if any two balls collide
for i in range(len(balls)):
for j in range(i + 1, len(balls)):
if check_collision(balls[i], balls[j]):
handle_collision(balls[i], balls[j])
add_new_ball() # Add a new ball if collision occurs
# Check if the balls hit the walls of the circle
for ball in balls:
distance_to_center = math.sqrt((ball["pos"][0] - circle_center[0]) ** 2 + (ball["pos"][1] - circle_center[1]) ** 2)
if distance_to_center + ball_radius >= circle_radius:
# Calculate reflection angle
dx, dy = ball["speed"]
normal_x = ball["pos"][0] - circle_center[0]
normal_y = ball["pos"][1] - circle_center[1]
mag_normal = math.sqrt(normal_x ** 2 + normal_y ** 2)
normal_x /= mag_normal
normal_y /= mag_normal
dot_product = dx * normal_x + dy * normal_y
reflect_x = dx - 2 * dot_product * normal_x
reflect_y = dy - 2 * dot_product * normal_y
ball["speed"][0] = reflect_x
ball["speed"][1] = reflect_y
# Draw the circle
pygame.draw.circle(window, WHITE, circle_center, circle_radius, circle_thickness)
# Draw the balls
for ball in balls:
pygame.draw.circle(window, ball["color"], (int(ball["pos"][0]), int(ball["pos"][1])), ball_radius)
pygame.display.flip()
Спасибо.
Подробнее здесь: https://stackoverflow.com/questions/784 ... -in-a-list