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

public class GraphicSimulation extends Canvas{
  Road r;
  int ncars;

  public static void main(String args[]){
    new GraphicSimulation(args);
  }
  GraphicSimulation(String args[]) {
    Frame f = new Frame();
    setBounds(0,0,600,50);
    f.setBounds(0,0,600,50);
    f.add(this);
    f.show();
    ncars = Integer.parseInt(args[0]);
    Random rand = new Random();
    r = new Road();
    r.limit = 30;
    r.len = 200;
    for(int ct=0;ct<2;ct++){
      Car c = new Car();
      c.speed = 0;
      c.maxAccel = 3;
      c.stdDeccel = 6;
      c.maxDeccel = 10;
      c.minStoppedTail = .1+(rand.nextFloat()*2);
      c.length = 3;
      c.reactionTime = (int) (rand.nextFloat()*7);
      c.minTail = (int) (c.reactionTime+2+(rand.nextFloat()*30));
      c.forecast = 35;
      c.eagerness = 1;
      c.position = 20+(ct*3.5);
      c.road = r;
//      c.debug = true;
      r.cars[ct] = c;
      System.out.println("Composite for #"+ct+" is "+(c.minTail-c.reactionTime));
    }
    
    long t=0, aact=0;
    double aas=0, aatot=0;
    while(true){
      r.tick(t++);
      repaint();
      f.repaint();
      if(t%ncars == 0)
	addACar();
      try { Thread.currentThread().sleep(10); } catch (Exception e) { }
      if((t%10) == 0){
	try { Thread.currentThread().sleep(10); } catch (Exception e) { }
      }
    }
  }

  public void addACar() {
      Random rand = new Random();
      Car c = new Car();
      c.speed = 0;
      c.maxAccel = 2+rand.nextFloat()*4;
      c.stdDeccel = c.maxAccel+(rand.nextFloat()*c.maxAccel);
      c.maxDeccel = c.maxAccel+3+(rand.nextFloat()*8);
      c.minStoppedTail = .1+(rand.nextFloat()*2);
      c.length = 3;
      c.reactionTime = (int) (rand.nextFloat()*7);
      c.minTail = (int) (c.reactionTime+2+(rand.nextFloat()*30));
      c.forecast = 35;
      c.eagerness = 1;
      double backupq = (r.nextCar(-50000)).position-6;
      c.position = (backupq > 20) ? 20:backupq;
      System.out.println("Added a car at position "+c.position);
      c.road = r;
//      c.debug = true;
      for(int ct=0;ct<100;ct++){
	if(r.cars[ct] == null){
	  r.cars[ct] = c;
	  break;
	}
      }
  }

  public void paint(Graphics g){
    double scale = 3.0;
    for(int ct=0;ct<100;ct++){
      if(r.cars[ct] != null)
	g.drawRect((int) (scale*(r.cars[ct].position-r.cars[ct].length)), 5, (int) (scale*r.cars[ct].length), (int) (scale*2));
    }
  }
}      



