Create a complete Pygame implementation of a physics sandbox in a single .py script. The sandbox should include the following features:
Basic Setup:
Initialize Pygame and set up the display window with a specified width and height.
Include a game loop that handles events, updates the game state, and renders graphics.
Physics Engine:
Implement basic physics features such as gravity, collision detection, and response.
Allow for the addition of different shapes (circles, rectangles) that can be moved and affected by physics.
Include support for user-defined shapes.
User Interactions:
Enable users to click and drag objects to move them around.
Provide keyboard controls to create new shapes (e.g., pressing specific keys to spawn circles or rectangles).
Allow users to clear the sandbox and reset all objects.
Visual Elements:
Render the objects in different colors based on their type.
Display the current frame rate in the corner of the screen.
Add a background grid to visualize the physics better.
Optional Features:
Implement simple particle effects (e.g., explosions or force fields).
Add an option for users to toggle between different simulation modes (e.g., with/without gravity).
Make sure to include comments throughout the code to explain the key sections and functionality. The script should be organized and modular, following good coding practices.
Assistant
python
"""
Physics Sandbox using Pygame
===========================
This script implements a simple physics sandbox using Pygame, allowing users to interact
with various shapes affected by physics such as gravity and collisions. Users can add
circles and rectangles, drag them around, toggle gravity, and reset the sandbox. The
sandbox features a background grid, different colors for shape types, frame rate display,
and simple particle effects upon collisions.
Author: OpenAI ChatGPT
Date: 2023-10
"""
import pygame
import sys
import math
import random
# Initialize Pygame
pygame.init()
# ------------------------------ Constants -------------------------------------
# Screen dimensions
WIDTH, HEIGHT = 800, 600
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Physics Sandbox")
# Colors
BACKGROUND_COLOR = (30, 30, 30)
GRID_COLOR = (50, 50, 50)
FPS_COLOR = (255, 255, 255)
CIRCLE_COLOR = (200, 100, 100)
RECT_COLOR = (100, 200, 100)
USER_DEFINED_COLOR = (100, 100, 200)
PARTICLE_COLOR = (255, 255, 0)
# Physics constants
GRAVITY = pygame.math.Vector2(0, 500) # pixels per second^2
ELASTICITY = 0.8 # Coefficient of restitution
# Grid settings
GRID_SIZE = 50
# Particle settings
PARTICLE_COUNT = 10
PARTICLE_LIFETIME = 1.0 # seconds
# ------------------------------ Classes ---------------------------------------
class Particle:
"""Simple particle for visual effects."""
def __init__(self, position):
self.position = pygame.math.Vector2(position)
angle = random.uniform(0, 2 * math.pi)
speed = random.uniform(50, 200)
self.velocity = pygame.math.Vector2(math.cos(angle), math.sin(angle)) * speed
self.lifetime = PARTICLE_LIFETIME
self.radius = random.randint(2, 4)
def update(self, dt):
self.position += self.velocity * dt
self.lifetime -= dt
def draw(self, surface):
if self.lifetime > 0:
alpha = int(255 * (self.lifetime / PARTICLE_LIFETIME))
particle_color = PARTICLE_COLOR + (alpha,)
s = pygame.Surface((self.radius * 2, self.radius * 2), pygame.SRCALPHA)
pygame.draw.circle(s, particle_color, (self.radius, self.radius), self.radius)
surface.blit(s, (self.position.x - self.radius, self.position.y - self.radius))
class Shape:
"""Base class for all shapes."""
def __init__(self, position, velocity, mass, color):
self.position = pygame.math.Vector2(position)
self.velocity = pygame.math.Vector2(velocity)
self.mass = mass
self.color = color
self.forces = pygame.math.Vector2(0, 0)
def apply_force(self, force):
"""Apply a force to the shape."""
self.forces += force
def update(self, dt, gravity_enabled):
"""Update the shape's physics."""
if gravity_enabled:
self.apply_force(GRAVITY * self.mass)
# Acceleration = Force / Mass
acceleration = self.forces / self.mass
# Update velocity
self.velocity += acceleration * dt
# Update position
self.position += self.velocity * dt
# Reset forces
self.forces = pygame.math.Vector2(0, 0)
def draw(self, surface):
"""Draw the shape. To be implemented by subclasses."""
pass
def check_boundary_collision(self, width, height):
"""Check and respond to collision with screen boundaries."""
pass
def is_clicked(self, mouse_pos):
"""Check if the shape is clicked. To be implemented by subclasses."""
return False
class Circle(Shape):
"""Circle shape affected by physics."""
def __init__(self, position, velocity, radius=20, mass=1, color=CIRCLE_COLOR):
super().__init__(position, velocity, mass, color)
self.radius = radius
def draw(self, surface):
pygame.draw.circle(surface, self.color, (int(self.position.x), int(self.position.y)), self.radius)
def check_boundary_collision(self, width, height):
collided = False
# Left boundary
if self.position.x - self.radius < 0:
self.position.x = self.radius
self.velocity.x *= -ELASTICITY
collided = True
# Right boundary
if self.position.x + self.radius > width:
self.position.x = width - self.radius
self.velocity.x *= -ELASTICITY
collided = True
# Top boundary
if self.position.y - self.radius < 0:
self.position.y = self.radius
self.velocity.y *= -ELASTICITY
collided = True
# Bottom boundary
if self.position.y + self.radius > height:
self.position.y = height - self.radius
self.velocity.y *= -ELASTICITY
collided = True
return collided
def is_clicked(self, mouse_pos):
distance = self.position.distance_to(mouse_pos)
return distance <= self.radius
class Rectangle(Shape):
"""Rectangle shape affected by physics."""
def __init__(self, position, velocity, width=40, height=30, mass=2, color=RECT_COLOR):
super().__init__(position, velocity, mass, color)
self.width = width
self.height = height
self.rect = pygame.Rect(self.position.x - self.width/2,
self.position.y - self.height/2,
self.width, self.height)
def update(self, dt, gravity_enabled):
super().update(dt, gravity_enabled)
self.rect.center = self.position
def draw(self, surface):
pygame.draw.rect(surface, self.color, self.rect)
def check_boundary_collision(self, width, height):
collided = False
# Left boundary
if self.rect.left < 0:
self.position.x = self.width / 2
self.velocity.x *= -ELASTICITY
collided = True
# Right boundary
if self.rect.right > width:
self.position.x = width - self.width / 2
self.velocity.x *= -ELASTICITY
collided = True
# Top boundary
if self.rect.top < 0:
self.position.y = self.height / 2
self.velocity.y *= -ELASTICITY
collided = True
# Bottom boundary
if self.rect.bottom > height:
self.position.y = height - self.height / 2
self.velocity.y *= -ELASTICITY
collided = True
return collided
def is_clicked(self, mouse_pos):
return self.rect.collidepoint(mouse_pos)
class ParticleEffect:
"""Handles particle effects for collisions."""
def __init__(self):
self.particles = []
def emit(self, position):
for _ in range(PARTICLE_COUNT):
self.particles.append(Particle(position))
def update(self, dt):
self.particles = [p for p in self.particles if p.lifetime > 0]
for particle in self.particles:
particle.update(dt)
def draw(self, surface):
for particle in self.particles:
particle.draw(surface)
# ------------------------------ Helper Functions -------------------------------
def draw_grid(surface):
"""Draw background grid."""
for x in range(0, WIDTH, GRID_SIZE):
pygame.draw.line(surface, GRID_COLOR, (x, 0), (x, HEIGHT))
for y in range(0, HEIGHT, GRID_SIZE):
pygame.draw.line(surface, GRID_COLOR, (0, y), (WIDTH, y))
def display_fps(surface, clock):
"""Display current FPS on the screen."""
fps = int(clock.get_fps())
font = pygame.font.SysFont(None, 24)
fps_surface = font.render(f'FPS: {fps}', True, FPS_COLOR)
surface.blit(fps_surface, (10, 10))
def detect_collision(shape1, shape2):
"""Detect collision between two shapes."""
if isinstance(shape1, Circle) and isinstance(shape2, Circle):
distance = shape1.position.distance_to(shape2.position)
return distance < (shape1.radius + shape2.radius)
elif isinstance(shape1, Rectangle) and isinstance(shape2, Rectangle):
return shape1.rect.colliderect(shape2.rect)
elif isinstance(shape1, Circle) and isinstance(shape2, Rectangle):
# Find the closest point on the rectangle to the circle
closest_x = clamp(shape1.position.x, shape2.rect.left, shape2.rect.right)
closest_y = clamp(shape1.position.y, shape2.rect.top, shape2.rect.bottom)
distance = math.hypot(shape1.position.x - closest_x, shape1.position.y - closest_y)
return distance < shape1.radius
elif isinstance(shape1, Rectangle) and isinstance(shape2, Circle):
return detect_collision(shape2, shape1)
return False
def clamp(value, min_value, max_value):
"""Clamp a value between min_value and max_value."""
return max(min_value, min(value, max_value))
def resolve_collision(shape1, shape2):
"""Resolve collision between two shapes."""
if isinstance(shape1, Circle) and isinstance(shape2, Circle):
delta = shape1.position - shape2.position
distance = delta.length()
if distance == 0:
# Prevent division by zero
distance = 0.1
delta = pygame.math.Vector2(random.uniform(-1, 1), random.uniform(-1, 1)).normalize()
penetration_depth = shape1.radius + shape2.radius - distance
# Push shapes apart
push_dir = delta.normalize()
total_mass = shape1.mass + shape2.mass
shape1.position += push_dir * (penetration_depth * (shape2.mass / total_mass))
shape2.position -= push_dir * (penetration_depth * (shape1.mass / total_mass))
# Relative velocity
relative_velocity = shape1.velocity - shape2.velocity
# Velocity along the normal
vel_along_normal = relative_velocity.dot(push_dir)
if vel_along_normal > 0:
return
# Calculate impulse scalar
impulse = -(1 + ELASTICITY) * vel_along_normal
impulse /= (1 / shape1.mass) + (1 / shape2.mass)
# Apply impulse
impulse_vec = push_dir * impulse
shape1.velocity += impulse_vec / shape1.mass
shape2.velocity -= impulse_vec / shape2.mass
# Emit particles
particle_effect.emit((shape1.position + shape2.position) / 2)
elif isinstance(shape1, Rectangle) and isinstance(shape2, Rectangle):
# Simple collision resolution by reversing velocity
# More accurate resolution can be implemented
overlap_rect = shape1.rect.clip(shape2.rect)
if overlap_rect.width < overlap_rect.height:
if shape1.position.x < shape2.position.x:
shape1.position.x -= overlap_rect.width / 2
shape2.position.x += overlap_rect.width / 2
else:
shape1.position.x += overlap_rect.width / 2
shape2.position.x -= overlap_rect.width / 2
shape1.velocity.x *= -ELASTICITY
shape2.velocity.x *= -ELASTICITY
else:
if shape1.position.y < shape2.position.y:
shape1.position.y -= overlap_rect.height / 2
shape2.position.y += overlap_rect.height / 2
else:
shape1.position.y += overlap_rect.height / 2
shape2.position.y -= overlap_rect.height / 2
shape1.velocity.y *= -ELASTICITY
shape2.velocity.y *= -ELASTICITY
# Emit particles
particle_effect.emit(overlap_rect.center)
elif (isinstance(shape1, Circle) and isinstance(shape2, Rectangle)) or \
(isinstance(shape1, Rectangle) and isinstance(shape2, Circle)):
# Determine which is circle and which is rectangle
if isinstance(shape1, Circle):
circle = shape1
rect = shape2
else:
circle = shape2
rect = shape1
# Find the closest point on the rectangle to the circle
closest_x = clamp(circle.position.x, rect.rect.left, rect.rect.right)
closest_y = clamp(circle.position.y, rect.rect.top, rect.rect.bottom)
closest_point = pygame.math.Vector2(closest_x, closest_y)
delta = circle.position - closest_point
distance = delta.length()
if distance == 0:
distance = 0.1
delta = pygame.math.Vector2(random.uniform(-1, 1), random.uniform(-1, 1)).normalize()
penetration_depth = circle.radius - distance
push_dir = delta.normalize()
# Push circle out of rectangle
circle.position += push_dir * penetration_depth
# Reflect circle's velocity
vel_along_normal = circle.velocity.dot(push_dir)
if vel_along_normal < 0:
circle.velocity -= (1 + ELASTICITY) * vel_along_normal * push_dir
# Optionally, move rectangle if it's movable
if hasattr(rect, 'mass') and rect.mass != float('inf'):
rect.velocity += (1 + ELASTICITY) * vel_along_normal * push_dir / rect.mass
# Emit particles
particle_effect.emit(closest_point)
# ------------------------------ Initialization ---------------------------------
clock = pygame.time.Clock()
shapes = []
particle_effect = ParticleEffect()
gravity_enabled = True
selected_shape = None
mouse_offset = pygame.math.Vector2(0, 0)
# ------------------------------ Main Loop --------------------------------------
def main():
global gravity_enabled, selected_shape, mouse_offset
running = True
while running:
dt = clock.tick(60) / 1000.0 # Delta time in seconds
# -------------------------- Event Handling -----------------------------
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Mouse button down
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # Left click
mouse_pos = pygame.math.Vector2(event.pos)
# Iterate in reverse to select topmost shape
for shape in reversed(shapes):
if shape.is_clicked(mouse_pos):
selected_shape = shape
mouse_offset = shape.position - mouse_pos
break
# Mouse button up
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
selected_shape = None
# Mouse motion
elif event.type == pygame.MOUSEMOTION:
if selected_shape:
mouse_pos = pygame.math.Vector2(event.pos)
selected_shape.position = mouse_pos + mouse_offset
selected_shape.velocity = pygame.math.Vector2(0, 0) # Reset velocity
# Key press
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
# Create a new circle at random position
pos = (random.randint(100, WIDTH-100), random.randint(100, HEIGHT-100))
velocity = (random.uniform(-100, 100), random.uniform(-100, 100))
new_circle = Circle(pos, velocity)
shapes.append(new_circle)
elif event.key == pygame.K_r:
# Create a new rectangle at random position
pos = (random.randint(100, WIDTH-100), random.randint(100, HEIGHT-100))
velocity = (random.uniform(-100, 100), random.uniform(-100, 100))
new_rect = Rectangle(pos, velocity)
shapes.append(new_rect)
elif event.key == pygame.K_d:
# Clear all shapes
shapes.clear()
elif event.key == pygame.K_g:
# Toggle gravity
gravity_enabled = not gravity_enabled
elif event.key == pygame.K_ESCAPE:
running = False
# -------------------------- Physics Update ------------------------------
# Update all shapes
for shape in shapes:
shape.update(dt, gravity_enabled)
if shape.check_boundary_collision(WIDTH, HEIGHT):
# Emit particles on boundary collision
particle_effect.emit(shape.position)
# Check for collisions between shapes
for i in range(len(shapes)):
for j in range(i + 1, len(shapes)):
shape1 = shapes[i]
shape2 = shapes[j]
if detect_collision(shape1, shape2):
resolve_collision(shape1, shape2)
# Update particles
particle_effect.update(dt)
# -------------------------- Rendering -----------------------------------
SCREEN.fill(BACKGROUND_COLOR)
draw_grid(SCREEN)
# Draw all shapes
for shape in shapes:
shape.draw(SCREEN)
# Draw particles
particle_effect.draw(SCREEN)
# Display FPS
display_fps(SCREEN, clock)
# Display gravity status
font = pygame.font.SysFont(None, 24)
gravity_text = f'Gravity: {"On" if gravity_enabled else "Off"} (Press G to toggle)'
gravity_surface = font.render(gravity_text, True, FPS_COLOR)
SCREEN.blit(gravity_surface, (10, 30))
pygame.display.flip()
pygame.quit()
sys.exit()
# ------------------------------ Entry Point -----------------------------------
if __name__ == "__main__":
main()