qwen3-235b-a22b-no-thinking· Alibaba (Qwen) LMArena Human Preference 140K
write a particle simulation code in python
- User
write a particle simulation code in python
- Assistant
Here's a basic particle simulation in Python using the
pygamelibrary. This simulation creates particles that move around the screen, bounce off walls, and interact with each other through simple gravitational-like attraction or repulsion.
🧪 Features:
- Particles move randomly.
- Bounce off window edges.
- Interact with each other (optional attraction/repulsion).
- Easily extendable for more complex physics.
🔧 Requirements
Make sure you have
pygameinstalled:pip install pygame
🧠 Particle Simulation Code
import pygame import random import math # Initialize Pygame pygame.init() # Screen dimensions WIDTH, HEIGHT = 800, 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Particle Simulation") # Clock to control frame rate clock = pygame.time.Clock() # Particle class class Particle: def __init__(self, x, y, vx=None, vy=None): self.x = x self.y = y self.vx = vx if vx is not None else random.uniform(-2, 2) self.vy = vy if vy is not None else random.uniform(-2, 2) self.radius = 5 self.color = (255, 255, 255) def move(self): self.x += self.vx self.y += self.vy # Bounce off walls if self.x <= 0 or self.x >= WIDTH: self.vx *= -1 if self.y <= 0 or self.y >= HEIGHT: self.vy *= -1 # Keep within bounds self.x = max(0, min(WIDTH, self.x)) self.y = max(0, min(HEIGHT, self.y)) def draw(self, surface): pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), self.radius) def apply_gravity(self, particles, strength=0.01): """Apply simple gravity-like interaction with other particles.""" for other in particles: if other != self: dx = other.x - self.x dy = other.y - self.y dist = math.hypot(dx, dy) + 0.1 # prevent division by zero force = strength / dist self.vx += force * dx self.vy += force * dy # Create particles num_particles = 50 particles = [Particle(random.randint(0, WIDTH), random.randint(0, HEIGHT)) for _ in range(num_particles)] # Main loop running = True while running: clock.tick(60) # 60 FPS screen.fill((0, 0, 0)) # Clear screen for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Update particles for p in particles: p.apply_gravity(particles, strength=0.05) p.move() p.draw(screen) pygame.display.flip() pygame.quit()
🧩 How to Customize
- Change number of particles: Modify
num_particles. - Adjust speed: Change velocity ranges (
random.uniform(-2, 2)). - Add color based on velocity or mass.
- Implement collision detection between particles.
- Use mouse to attract/repel particles.
Would you like me to add any specific feature like collisions, mouse interaction, or color gradients?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.