日常の進捗

主に自分のための,行為とその習慣化の記録

Mod:Coding Challenge #89: Langton's Ant

f:id:takawo:20180109185307g:plain

ブロックノイズがすごいので実際に実行してみて欲しい.

コード

int[][] grid;
int x;
int y;
int dir;

int ANTUP = 0;
int ANTLEFT = 1;
int ANTDOWN = 2;
int ANTRIGHT = 3;

color c1, c2, c3, c4;

PImage ant;

void setup() {
  //fullScreen();
  size(960, 540);
  colorMode(HSB, 360, 100, 100);

  shuffleColor();

  grid = new int[width][height];
  ant = createImage(width, height, RGB);
  ant.loadPixels();
  for (int i = 0; i < ant.pixels.length; i++) {
    ant.pixels[i] = c1;
  }
  ant.updatePixels();
  x = width / 2;
  y = height / 2;
  dir = ANTUP;
}

void draw() {


  ant.loadPixels();
  for (int n = 0; n < 100000; n++) {
    int state = grid[x][y];
    if (state == 0) {
      turnLeft();
      grid[x][y] = 1;
    } else {
      turnRight();
      grid[x][y] = 0;
    }
    color c;
    if (grid[x][y] ==1) {
      c = c2;
    } else {
      c = c3;
    }
    int pix = x + y * ant.width;
    ant.pixels[pix] = c;
    moveForward();
  }
  ant.updatePixels();
  image(ant, 0, 0);

  int sumBlack = 0;
  int sumWhite = 0; 
  for (int i = 0; i < ant.pixels.length; i++) {
    if (brightness(ant.pixels[i]) > 50) {
      sumWhite++;
    } else {
      sumBlack++;
    }
  }
  int m = millis()%3000;
  if (m > 2990) {
    resetGrid();
    shuffleColor();
  }
}

void moveForward() {
  if (dir == ANTUP) {
    y--;
  } else if (dir == ANTRIGHT) {
    x++;
  } else if (dir == ANTDOWN) {
    y++;
  } else if (dir == ANTLEFT) {
    x--;
  }
  if (x > width-1) {
    x = 0;
  } else if (x < 0) {
    x = width-1;
  }
  if (y > height-1) {
    y = 0;
  } else if (y < 0) {
    y = height-1;
  }
}
void turnRight() {
  dir++;
  dir = dir%4;
}
void turnLeft() {
  dir--;
  dir = abs(dir%4);
}

void mousePressed() {
  resetGrid();
}

void resetGrid() {
  for (int i = 0; i < ant.pixels.length; i++) {
    ant.pixels[i] = c4;
  }
  for (int j = 0; j < grid.length; j++) {
    for (int i = 0; i < grid[j].length; i++) {
      grid[j][i] = 0;
    }
  }
  dir = (int)random(4);
  x = (int)random(width);
  y = (int)random(height);
}

void shuffleColor() {
  float hue = random(360);
  c1 = color(hue, 80, 100);
  c2 = color((hue+120)%360, 80, 100);
  c3 = color((hue+240)%360, 80, 100);
  c4 = color(0, 0, 100);
  IntList colors = new IntList(4);
  colors.append(c1);
  colors.append(c2);
  colors.append(c3);
  colors.append(c4);
  colors.shuffle();
  c1 = colors.get(0);
  c2 = colors.get(1);
  c3 = colors.get(2);
  c4 = colors.get(3);
}

リファレンス

www.youtube.com