// an object-oriented implementation of GoL // ugly global GameBoard gb; void setup(){ size(500, 500); background(0); gb = new GameBoard(500, 500, 50); gb.randPop(); } void draw(){ for(int i = 0; i < gb.sizeX; i++){ for(int j = 0; j < gb.sizeY; j++){ switch(gb.board[i][j].state){ case 0: stroke(0); point(i, j); break; case 1: stroke(0, 255, 0); point(i, j); break; case 2: stroke(0, 0, 255); point(i, j); break; case 3: stroke(255, 0, 0); point(i, j); break; } } } gb.generation(1); } class Cell{ int state; //constructor Cell(int s){ state = s; } } class GameBoard{ int sizeX; int sizeY; int popAlive; Cell[][] board; GameBoard(int x, int y, int pA){ sizeX = x; sizeY = y; popAlive = pA; board = new Cell[x][y]; } void randPop(){ for(int i = 0; i < sizeX; i++){ for(int j = 0; j < sizeY; j++){ if(int(random(1,101)) <= popAlive){ board[i][j] = new Cell(1); } else { board[i][j] = new Cell(0); } } } } int countNeighbors(int x, int y){ int neighbors = 0; if(board[(x + sizeX - 1) % sizeX][(y + sizeY - 1) % sizeY].state != 0){ neighbors++; } if(board[x][(y + sizeY - 1) % sizeY].state != 0){ neighbors++; } if(board[(x + 1) % sizeX][(y + sizeY - 1) % sizeY].state != 0){ neighbors++; } if(board[(x + sizeX - 1) % sizeX][y].state != 0){ neighbors++; } if(board[(x + 1) % sizeX][y].state != 0){ neighbors++; } if(board[(x + sizeX - 1) % sizeX][(y + 1) % sizeY].state != 0){ neighbors++; } if(board[x][(y + 1) % sizeY].state != 0){ neighbors++; } if(board[(x + 1) % sizeX][(y + 1) % sizeY].state != 0){ neighbors++; } return neighbors; } int countState(int state){ return state; } void generation(int cycles){ int neighbors = 0; Cell[][] next = new Cell[sizeX][sizeY]; for(int c = 0; c < cycles; c++){ for(int i = 0; i < sizeX; i++){ for(int j = 0; j < sizeY; j++){ neighbors = countNeighbors(i, j); next[i][j] = new Cell(0); if(board[i][j].state != 0){ if(neighbors == 2) { next[i][j].state = 2; } else if(neighbors == 3){ next[i][j].state = 3; } else{ next[i][j].state = 0; } } else{ if(neighbors == 3){ next[i][j].state = 1; } else{ next[i][j].state = 0; } } } } for(int i = 0; i < sizeX; i++){ for(int j = 0; j < sizeY; j++){ board[i][j].state = next[i][j].state; } } } } }