Particle Lab Review

CS 108

Spot the Bug

Bug 1: Particles don’t move

def move(self, half_size):
    x = self.x + self.vel_x
    y = self.y + self.vel_y
    if x + self.radius > half_size or x - self.radius < -half_size:
        self.vel_x *= -1
    elif y + self.radius > half_size or y - self.radius < -half_size:
        self.vel_y *= -1

What’s wrong?

x and y are local variables — they disappear when the method ends. The method never updates self.x or self.y, so the particle stays put.

Fix: Add an else branch: self.x = x and self.y = y

(POGIL Q15: attributes live on self, local variables don’t.)

Bug 2: Main loop crashes or does nothing

for p in particles:

Which line goes inside this loop to move each particle?

  • self.move(HALF_SIZE)
  • Particle.move(HALF_SIZE)
  • p.move(HALF_SIZE)
  • move(p, HALF_SIZE)

Answer: C. p is the object; call the method on it with dot notation.

  • A fails: self only exists inside a method definition (POGIL Q13).
  • B fails: Particle is the class, not an instance — and self wouldn’t get filled in.
  • D fails: move is a method, not a global function.

Bug 3: Spacebar does nothing

def add_particle():
    radius = randint(5, 25)
    x = randint(-(HALF_SIZE - 25), HALF_SIZE - 25)
    y = randint(-(HALF_SIZE - 25), HALF_SIZE - 25)
    vel_x = randint(-(radius // 10), radius // 10)
    vel_y = randint(-(radius // 10), radius // 10)
    color = get_random_color()
    Particle(x, y, vel_x, vel_y, radius, color)

This runs without errors. Why doesn’t a particle appear?

The Particle is created but never added to the list.

Fix: particles.append(Particle(x, y, vel_x, vel_y, radius, color))

The main loop draws everything in particles — if it’s not in the list, it won’t show up.

Bug 4: Clicking doesn’t remove particles

def is_clicked(self, click_x, click_y):
    distance(click_x, click_y, self.x, self.y) < self.radius

The method runs without error. Why doesn’t it work?

The boolean expression is evaluated but not returned. Python methods return None by default, and None is falsy.

Fix: return distance(click_x, click_y, self.x, self.y) < self.radius