Certainly! Here's a simple particle system implemented in Python using dataclasses:
import random
from dataclasses import dataclass
import matplotlib.pyplot as plt
@dataclass
class Particle:
x: float
y: float
vx: float
vy: float
life: int
@dataclass
class ParticleSystem:
particles: list
max_particles: int
spawn_rate: int
max_life: int
def update(self):
self.particles = [p for p in self.particles if p.life > 0]
for _ in range(self.spawn_rate):
if len(self.particles) < self.max_particles:
self.particles.append(Particle(
x=0,
y=0,
vx=random.uniform(-1, 1),
vy=random.uniform(-1, 1),
life=self.max_life
))
for p in self.particles:
p.x += p.vx
p.y += p.vy
p.life -= 1
def display(self):
x = [p.x for p in self.particles]
y = [p.y for p in self.particles]
plt.clf()
plt.scatter(x, y)
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.draw()
plt.pause(0.01)
# Create a particle system
ps = ParticleSystem(
particles=[],
max_particles=100,
spawn_rate=5,
max_life=50
)
# Simulate the particle system
for _ in range(100):
ps.update()
ps.display()
In this example, we define two dataclasses:
-
Particle: Represents a single particle with attributes x, y, vx, vy, and life.
x and y represent the position of the particle.
vx and vy represent the velocity of the particle.
life represents the remaining lifetime of the particle.
-
ParticleSystem: Represents the particle system with attributes particles, max_particles, spawn_rate, and max_life.
particles is a list that holds all the particles in the system.
max_particles determines the maximum number of particles allowed in the system.
spawn_rate determines the number of particles spawned in each update step.
max_life determines the maximum lifetime of each particle.
The ParticleSystem class has two methods:
update(): Updates the particle system by removing expired particles, spawning new particles based on the spawn rate, and updating the position and life of each particle.
display(): Displays the particles using Matplotlib by clearing the plot, plotting the particles as scatter points, setting the plot limits, and pausing briefly to create an animation effect.
In the example usage, we create a particle system with a maximum of 100 particles, a spawn rate of 5 particles per update, and a maximum life of 50 steps for each particle.
We then simulate the particle system for 100 steps, updating and displaying the particles in each step.
Note: Make sure you have Matplotlib installed (pip install matplotlib) before running this code.