Daily Creative Coding

元「30 min. Processing」。毎日、Creative Codingします。

Nagel–Schreckenbergモデルによる交通流シミュレーション

/**
* Nagel–Schreckenberg model
*
* @author aa_debdeb
* @date 2016/08/04
*/

int maxVel = 5;
float p = 0.4;
ArrayList<Car> cars;

void setup(){
  size(500, 500);
  int pos = 0;
  cars = new ArrayList<Car>();
  while(pos < width){
    pos += int(random(1, 7));
    cars.add(new Car(pos));
  }
  background(0);
}


void draw(){
  int x = (frameCount - 1) % width;
  noStroke();
  fill(0);
  rect(x, 0, 1, height);
  stroke(255);
  for(Car car: cars){
    int y = height - car.pos - 1;
    point(x, y);
  }
  ArrayList<Car> nextCars = new ArrayList<Car>(); 
  for(int i = 0;  i < cars.size(); i++){
    Car c = cars.get(i);
    int nextPos = c.pos;
    int nextVel = c.vel;
    if(nextVel < maxVel){
      nextVel += 1;
    }
    int d = 10000;
    if(i != cars.size() - 1){
      d = cars.get(i + 1).pos - c.pos;
    } else {
      d = cars.get(0).pos + height - c.pos;
    }
    if(nextVel >= d){
      nextVel = d - 1;
    }
    if(nextVel >= 1){
      if(random(1) < p){
        nextVel -= 1;
      }
    }
    nextPos += nextVel;
    if(nextPos >= height){
      nextPos -= height;
      nextCars.add(0, new Car(nextPos, nextVel));
    } else {
      nextCars.add(new Car(nextPos, nextVel));      
    }
  }
  cars = nextCars;
}

class Car{
  int pos, vel;
  Car(int _pos){
    pos = _pos;
    vel = 3;
  }
  Car(int _pos, int _vel){
    pos = _pos;
    vel = _vel;
  }
}
f:id:aa_debdeb:20160729082717j:plain