-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpygame2-o1.py
98 lines (86 loc) · 2.91 KB
/
pygame2-o1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# ...existing code...
import pygame
import math
import sys
# Constants
WIDTH, HEIGHT = 800, 600
GRAVITY = 0.5 # gravitational acceleration
FPS = 60
class PhysicsObject:
"""Represents a 2D object with position, velocity, mass, and radius."""
def __init__(self, x, y, vx, vy, mass, radius, color):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
self.mass = mass
self.radius = radius
self.color = color
def update(self):
"""Update velocity with gravity and move."""
self.vy += GRAVITY
self.x += self.vx
self.y += self.vy
def check_boundary_collision(self):
"""Bounce off screen boundaries."""
if self.x - self.radius < 0:
self.x = self.radius
self.vx *= -1
if self.x + self.radius > WIDTH:
self.x = WIDTH - self.radius
self.vx *= -1
if self.y - self.radius < 0:
self.y = self.radius
self.vy *= -1
if self.y + self.radius > HEIGHT:
self.y = HEIGHT - self.radius
self.vy *= -1
def detect_and_handle_collisions(objects):
"""Detect circle collisions and handle elastic collision response."""
for i in range(len(objects)):
for j in range(i + 1, len(objects)):
obj1 = objects[i]
obj2 = objects[j]
dx = obj2.x - obj1.x
dy = obj2.y - obj1.y
distance = math.hypot(dx, dy)
if distance < obj1.radius + obj2.radius:
# Simple elastic collision response
nx, ny = dx / distance, dy / distance
p = 2 * (obj1.vx * nx + obj1.vy * ny - obj2.vx * nx - obj2.vy * ny) / (obj1.mass + obj2.mass)
obj1.vx -= p * obj2.mass * nx
obj1.vy -= p * obj2.mass * ny
obj2.vx += p * obj1.mass * nx
obj2.vy += p * obj1.mass * ny
def main():
"""Initialize Pygame and run the simulation loop."""
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
# Create multiple objects
objects = [
PhysicsObject(100, 100, 3, 2, 1, 20, (255, 0, 0)),
PhysicsObject(300, 150, -2, 2, 1, 30, (0, 255, 0)),
PhysicsObject(500, 200, 2, -3, 1, 25, (0, 0, 255))
]
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update physics
for obj in objects:
obj.update()
obj.check_boundary_collision()
detect_and_handle_collisions(objects)
# Render
screen.fill((255, 255, 255))
for obj in objects:
pygame.draw.circle(screen, obj.color, (int(obj.x), int(obj.y)), obj.radius)
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
# ...existing code...