/*
 * we use the following conventions:
 * directions 0: up, 1: left, 2: down: 3: right
 *
 * pixel white: true, black: false
 *
 * turn right: true, left: false
 *
 */

// number of iteration steps per frame
// set this to 1 to see a slow animation of each
// step or to 10 or 100 for a faster animation

final int STEP=100;

int x;
int y;
int direction;

void setup() {
  // 100x100 is large enough to show the
  // corridor after about 10000 cycles
  size(100, 100, P2D);

  background(#ffffff);

  x=width/2;
  y=height/2;

  direction=0;
}

int count=0;

void draw() {
  for(int i=0;i<STEP;i++) {
    count++;
    boolean pix=get(x,y)!=-1; //white =-1
    setBool(x,y,pix);

    turn(pix);
    move();

    if(x<0||y<0||x>=width||y>=height) {
      println("finished");
      noLoop();
      break;
    }
  }
  if(count%1000==0) {
    println("iteration "+count);
  }
}

void move() {
  switch(direction) {
    case 0:
      y--;
      break;
    case 1:
      x--;
      break;
    case 2:
      y++;
      break;
    case 3:
      x++;
      break;
  }
}

void turn(boolean rightleft) {
  direction+=rightleft?1:-1;
  if(direction==-1) direction=3;
  if(direction==4) direction=0;
}

void setBool(int x, int y, boolean white) {
  set(x,y,white?#ffffff:#000000);
}
