/* 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[][] cells;
boolean[] state = new boolean[256];

public void setup()
{
  /* size commented out by preprocessor */;
  frameRate(60);
  fill(0xFF00FFFF);
  textSize(50);
  /* noSmooth commented out by preprocessor */;

  cells = new boolean[width][height];

  randomize();

  loadPixels();
}

public void draw()
{
  cells = gameTick(cells);

  userInput();

  setPixels();

  updatePixels();
}
public int borderWrapX(int x)
{
  if (x == -1) return width - 1;
  if (x == width) return 0;
  return x;
}

public int borderWrapY(int y)
{
  if (y == -1) return height - 1;
  if (y == height) return 0;
  return y;
}
public boolean[][] gameTick(boolean[][] oldCells)
{
  boolean[][] newCells = new boolean[width][height];

  for (int i = 0; i < width; i++) for (int j = 0; j < height; j++)
  {
    int neighbours = 0;
    if (oldCells[borderWrapX(i - 1)][borderWrapY(j - 1)]) neighbours++;
    if (oldCells[borderWrapX(i)][borderWrapY(j - 1)]) neighbours++;
    if (oldCells[borderWrapX(i + 1)][borderWrapY(j - 1)]) neighbours++;
    if (oldCells[borderWrapX(i - 1)][borderWrapY(j)]) neighbours++;
    if (neighbours < 4 && oldCells[borderWrapX(i + 1)][borderWrapY(j)]) neighbours++;
    if (neighbours < 4 && oldCells[borderWrapX(i - 1)][borderWrapY(j + 1)]) neighbours++;
    if (neighbours < 4 && oldCells[borderWrapX(i)][borderWrapY(j + 1)]) neighbours++;
    if (neighbours < 4 && oldCells[borderWrapX(i + 1)][borderWrapY(j + 1)]) neighbours++;

    if (oldCells[i][j])
    {
      newCells[i][j] = (neighbours == 2 || neighbours == 3);
    } else if (neighbours == 3) newCells[i][j] = true;
  }

  return newCells;
}
public void setPixels()
{
  for (int i = 0; i < width; i++)
  {
    int pixelsIndex = i;
    for (int j = 0; j < height; j++)
    {
      pixels[pixelsIndex] = cells[i][j] ? 0xFFFFFFFF : 0xFF000000;
      pixelsIndex += width;
    }
  }
}
public void userInput()
{
  if (mousePressed)
  {
    randomize();
  }
}

public void randomize()
{
  for (int i = 0; i < width; i++) for (int j = 0; j < height; j++)
  {
    if (PApplet.parseInt(random(2)) == 0) cells[i][j] = true;
  }
}


  public void settings() { fullScreen();
noSmooth(); }

  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);
    }
  }
}
