package chainreaction;

import java.awt.*;
import java.util.ArrayList;

class Particle implements Runnable {

static ArrayList<Particle> particles = new ArrayList<Particle>();
private int x;
private int y;
private final Direction direction;

Particle(int x, int y, Direction direction) {
  this.x = x;
  this.y = y;
  this.direction = direction;
  Thread thread = new Thread(this);
  thread.start();
}

@Override
public void run() {
  while (!ChainReactionPanel.outOfBounds(x, y)) {
    switch (direction) {
    case DOWN:
      y++;
      break;
    case LEFT:
      x++;
      break;
    case RIGHT:
      x--;
      break;
    case UP:
      y--;
      break;
    }
    Atom atom = Atom.atoms.get(new Point(x - 25, y - 25));
    if (atom != null) {
      synchronized (atom) {
        atom.grow();
      }
      synchronized (particles) {
        particles.remove(this);
        break;
      }
    }
    try {
      Thread.sleep(20);
    } catch (InterruptedException ex) {
    }
  }
  synchronized (particles) {
    particles.remove(this);
  }
}

enum Direction {

UP, DOWN, LEFT, RIGHT
}

void paint(Graphics g) {
  g.setColor(Color.RED);
  g.translate(x, y);
  g.fillOval(-3, -3, 6, 6);
  g.translate(-x, -y);
}
}
