Design a Python program that creates an interactive 2D particle system simulation using the library. This simulation should show particles moving and interacting under the influence of gravity, with the ability to add new particles by clicking on the screen.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is an example Python script that usesPygameto create a simple 2D particle system where:
Particles move under pairwise gravitational attraction (each particle interacts with all others).
You can click on the screen to add new particles at the mouse location.
Particles move under pairwise gravitational attraction (each particle interacts with all others).
You can click on the screen to add new particles at the mouse location.
This example demonstrates basic concepts and can be used as a starting point for more complex simulations (collision detection, different rendering styles, etc.).
Gravitational constant (scaled to keep simulation stable and visible)
G = 0.1
For convenience, we’ll give each particle the same mass.
PARTICLE_MASS = 1
Initial velocity range for new particles (random direction/small magnitude if desired)
INITIAL_VELOCITY = (0, 0)
--------------------------------
class Particle:
def init(self, x, y, mass=PARTICLE_MASS, vx=0, vy=0, radius=5, color=(255, 255, 255)):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
ss = mass
self.radius = radius
self.color = color
code
def draw(self, surface):
pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), self.radius)
def update(self, particles):
"""
Update the particle's velocity and position under the influence of gravity
from all other particles in the simulation.
"""
# Calculate net gravitational force from other particles
fx_total, fy_total = 0, 0
for p in particles:
if p is self:
continue
# Distance components
dx = p.x - self.x
dy = <REDACTED>
dist_sq = dx * dx + dy * dy
dist = math.sqrt(dist_sq)
# Avoid very large forces when particles are extremely close
if dist < 1:
dist = 1
# Gravitational force magnitude
force = (G * <URL>ss * p.mass) / dist_sq
# Direction
fx = force * (dx / dist)
fy = force * (dy / dist)
fx_total += fx
fy_total += fy
# Update velocity (F = m * a => a = F / m)
ax = fx_total / <URL>ss
ay = fy_total / self.mass
self.vx += ax
self.vy += ay
# Update position
self.x += self.vx
self.y += self.vy
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2D Particle System with Gravity")
clock = pygame.time.Clock()
code
# Create a list to hold all particles
particles = []
# (Optional) Add a few initial particles
particles.append(Particle(WIDTH // 2 - 50, HEIGHT // 2, <REDACTED>, <REDACTED>, color=(255, 100, 100)))
particles.append(Particle(WIDTH // 2 + 50, HEIGHT // 2, vx=0, vy=0.5, color=(100, 255, 100)))
particles.append(Particle(WIDTH // 2, HEIGHT // 2 - 50, vx=0.5, vy=0, color=(100, 100, 255)))
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# Left-click to add a new particle at mouse position
if event.button == 1:
mx, my = pygame.mouse.get_pos()
# Create a new particle with optional random velocity or no velocity
new_particle = Particle(
mx,
my,
mass=PARTICLE_MASS,
vx=INITIAL_VELOCITY[0],
vy=INITIAL_VELOCITY[1],
radius=5,
color=(255, 255, 255) # white color for new particles
)
particles.append(new_particle)
# Update particles
for p in particles:
p.update(particles)
# Draw everything
screen.fill((0, 0, 0)) # black background
for p in particles:
p.draw(screen)
pygame.display.flip()
pygame.quit()
<REDACTED>()
if name == "main":
main()
How It Works
Particle ClassEach particle stores its own position (x,y), velocity (vx,vy), and mass. Theupdatemethod computes the net gravitational force by iterating over all other particles. It sums the force contributions (using an inverse-square law) and then uses this to update the velocity and position.
Main LoopWe initialize the Pygame window, set up a clock, and create a list of particles (with a few optional initial ones).Each frame, we process events. If the user left-clicks, we add a new particle at the cursor location.We then update each particle by callingp.update(particles)to compute gravitational interactions with all other particles.Finally, we clear the screen and draw all particles in their new positions.
We initialize the Pygame window, set up a clock, and create a list of particles (with a few optional initial ones).
Each frame, we process events. If the user left-clicks, we add a new particle at the cursor location.
We then update each particle by callingp.update(particles)to compute gravitational interactions with all other particles.
Finally, we clear the screen and draw all particles in their new positions.
ParametersGis a reduced gravitational constant for stability (especially if masses and distances are small).All particles have the same mass in this example, but you can easily randomize or customize mass.If you want an initial random velocity for new particles, you can tweakINITIAL_VELOCITYor randomize it for interesting behavior.
Gis a reduced gravitational constant for stability (especially if masses and distances are small).
All particles have the same mass in this example, but you can easily randomize or customize mass.
If you want an initial random velocity for new particles, you can tweakINITIAL_VELOCITYor randomize it for interesting behavior.
Potential EnhancementsCollision detection and merging or bouncing of particles.Color changes based on velocity or mass.Adding boundaries (e.g., walls to bounce off) or a central mass.Using more accurate integration methods (e.g., Runge-Kutta).Optimizing with spatial partitioning if you have a large number of particles.
Collision detection and merging or bouncing of particles.
Color changes based on velocity or mass.
Adding boundaries (e.g., walls to bounce off) or a central mass.
Using more accurate integration methods (e.g., Runge-Kutta).
Optimizing with spatial partitioning if you have a large number of particles.
Particle ClassEach particle stores its own position (x,y), velocity (vx,vy), and mass. Theupdatemethod computes the net gravitational force by iterating over all other particles. It sums the force contributions (using an inverse-square law) and then uses this to update the velocity and position.
Main Loop
We initialize the Pygame window, set up a clock, and create a list of particles (with a few optional initial ones).
Each frame, we process events. If the user left-clicks, we add a new particle at the cursor location.
We then update each particle by callingp.update(particles)to compute gravitational interactions with all other particles.
Finally, we clear the screen and draw all particles in their new positions.
We initialize the Pygame window, set up a clock, and create a list of particles (with a few optional initial ones).
Each frame, we process events. If the user left-clicks, we add a new particle at the cursor location.
We then update each particle by callingp.update(particles)to compute gravitational interactions with all other particles.
Finally, we clear the screen and draw all particles in their new positions.
Parameters
Gis a reduced gravitational constant for stability (especially if masses and distances are small).
All particles have the same mass in this example, but you can easily randomize or customize mass.
If you want an initial random velocity for new particles, you can tweakINITIAL_VELOCITYor randomize it for interesting behavior.
Gis a reduced gravitational constant for stability (especially if masses and distances are small).
All particles have the same mass in this example, but you can easily randomize or customize mass.
If you want an initial random velocity for new particles, you can tweakINITIAL_VELOCITYor randomize it for interesting behavior.
Potential Enhancements
Collision detection and merging or bouncing of particles.
Color changes based on velocity or mass.
Adding boundaries (e.g., walls to bounce off) or a central mass.
Using more accurate integration methods (e.g., Runge-Kutta).
Optimizing with spatial partitioning if you have a large number of particles.
Collision detection and merging or bouncing of particles.
Color changes based on velocity or mass.
Adding boundaries (e.g., walls to bounce off) or a central mass.
Using more accurate integration methods (e.g., Runge-Kutta).
Optimizing with spatial partitioning if you have a large number of particles.
Running the Program
Install Pygame (if install pygame
Run the Script:bashCopypython particle_simulation.py
Interact with the Simulation:Watch the existing particles orbit or move around under mutual gravitational attraction.Click (left mouse button) anywhere in the window to spawn new particles at that position.
Watch the existing particles orbit or move around under mutual gravitational attraction.
Click (left mouse button) anywhere in the window to spawn new particles at that position.
Watch the existing particles orbit or move around under mutual gravitational attraction.
Click (left mouse button) anywhere in the window to spawn new particles at that position.
Watch the existing particles orbit or move around under mutual gravitational attraction.
Click (left mouse button) anywhere in the window to spawn new particles at that position.
This should provide a fun and straightforward starting point for experimenting with gravitational simulations in 2D using Pygame. Adjust constants, add features, and enjoy exploring the dynamics!