Write a Python class Simulation
that represents a simple particle motion simulation. The class should have a method to update positions of the particles, handle collisions between particles, and visualize the current state. Assume each particle is a point in 2D space with an x and y coordinate.
Example 1:
Input: sim = Simulation() sim.add_particle(1, 1, 1) sim.add_particle(2, 2, 2) sim.update_positions() sim.visualize() Output: (2, 2) (3, 3)
This problem requires knowledge of kinematics and physics. For simplicity, assume that all particles move with a constant velocity, and a collision results in an exchange of velocity between two particles.
class Simulation: def __init__(self): self.particles = [] def add_particle(self, x, y, velocity): self.particles.append([x, y, velocity]) def update_positions(self): for particle in self.particles: particle[0] += particle[2] particle[1] += particle[2] def handle_collisions(self): for i in range(len(self.particles)): for j in range(i+1, len(self.particles)): if self.particles[i][0] == self.particles[j][0] and self.particles[i][1] == self.particles[j][1]: self.particles[i][2], self.particles[j][2] = self.particles[j][2], self.particles[i][2] def visualize(self): for particle in self.particles: print((particle[0], particle[1]))
Unlock AI & Data Science treasures. Log in!