/* autogenerated by Processing revision 1293 on 2024-04-28 */
import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;

import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

public class game_of_life extends PApplet {

boolean[][] curr;
boolean[][] next;
float c = 0;
int time = 0;
int g = 2;
int w;
int h;

public void setup() {
  /* size commented out by preprocessor */;
  noCursor();
  colorMode(HSB, 100);
  w = width/g+2;
  h = height/g+2;
  curr = new boolean[w][h];
  next = new boolean[w][h];
  rand();
  render();
}

public void draw() {
  periodicBoundary();
  generate();
  convert();
  render();
  time();
}

public void keyPressed() {
  if (key == ' ') {
    rand();
    render();
  }
}
public void convert() {
  for (int i = 1; i < w-1; i++)
    for (int j = 1; j < h-1; j++) {
      curr[i][j] = next[i][j] ? true : false;
      next[i][j] = false;
    }
}
public void generate() {
  int n;
  for (int i = 1; i < w-1; i++)
    for (int j = 1; j < h-1; j++) {
      n = 0;
      for (int x = -1; x < 2 && n < 5; x++)
        for (int y = -1; y < 2 && n < 5; y++) {
          n += curr[i+x][j+y] ? 1 : 0;
        }
      next[i][j] = curr[i][j] ? n == 3 || n == 4 ? true : false : n == 3 ? true : false;
    }
}
public void periodicBoundary() {
  for (int i = 1; i < w-1; i++) {
    curr[i][0] = curr[i][h-2];
    curr[i][h-1] = curr[i][1];
  }
  for (int j = 1; j < h-1; j++) {
    curr[0][j] = curr[w-2][j];
    curr[w-1][j] = curr[1][j];
  }
  boolean s = curr[1][1];
  curr[0][0] = curr[w-2][h-2];
  curr[w-1][h-1] = s;
  s = curr[w-2][1];
  curr[w-1][0] = curr[1][h-2];
  curr[0][h-1] = s;
}
public void rand() {
  time = 0;
  for (int i = 1; i < w; i++)
    for (int j = 1; j < h; j++) {
      curr[i][j] = round(random(1)) == 1 ? true : false;
      next[i][j] = false;
    }
}
public void render() {
  loadPixels();
  for (int i = 0; i < width; i++)
    for (int j = 0; j < height; j++) {
      pixels[i+j*width] = curr[ceil(i/g)+1][ceil(j/g)+1] ? color(c, 100, 100) : color(0);
    }
  updatePixels();
  c += c > 100 ? -c : .05f;
}
public void time() {
  time++;
  if (time > 4096) {
    rand();
  }
}


  public void settings() { fullScreen(); }

  static public void main(String[] passedArgs) {
    String[] appletArgs = new String[] { "--full-screen", "--bgcolor=#666666", "--stop-color=#cccccc", "game_of_life" };
    if (passedArgs != null) {
      PApplet.main(concat(appletArgs, passedArgs));
    } else {
      PApplet.main(appletArgs);
    }
  }
}
