// Conway's Game of Life // Implementation by Patrick J. Hebron int boardWidth = 75; int boardHeight = 75; boolean[][] arr; int cellWidth; int cellHeight; boolean runCA = false; void setup() { size(675,675); arr = new boolean[boardWidth][boardHeight]; cellWidth = width/boardWidth; cellHeight = height/boardHeight; println("'r' key toggles setup/run board mode"); println("'c' key clears board"); } void keyReleased() { // Toggle setup/run board mode if(key == 'r') runCA = !runCA; // Clear board else if(key == 'c') { for(int x = 0; x < boardWidth; x++) { for(int y = 0; y < boardHeight; y++) { arr[x][y] = false; } } } } void mousePressed() { arr[mouseX/cellWidth][mouseY/cellHeight] = !arr[mouseX/cellWidth][mouseY/cellHeight]; } void draw() { background(120); if(runCA) { // Compute state boolean[][] temp = new boolean[boardWidth][boardHeight]; for(int x = 0; x < boardWidth; x++) { for(int y = 0; y < boardHeight; y++) { // Evaluate neighbors int kcount = 0; boolean cellVal = false; for(int kx = -1; kx <= 1; kx++) { for(int ky = -1; ky <=1 ; ky++) { int cx,cy; // Wrap around left,right edges if(x+kx >= boardWidth) cx = x+kx-boardWidth; else if(x+kx < 0) cx = boardWidth-x+kx; else cx = x+kx; // Wrap around top,bottom edges if(y+ky >= boardHeight) cy = y+ky-boardHeight; else if(y+ky < 0) cy = boardWidth-y+ky; else cy = y+ky; // Count live neighbors if(!(kx==0 && ky==0)) { if(arr[cx][cy] == true) kcount++; } // Store current cell's value else { cellVal = arr[cx][cy]; } } } // Apply rules if((kcount < 2 || kcount > 3) && cellVal) temp[x][y] = false; else if(cellVal) temp[x][y] = true; else if(kcount == 3) temp[x][y] = true; } } // Copy current state from temporary buffer arr = temp; } // Draw current state for(int x = 0; x < boardWidth; x++) { for(int y = 0; y < boardHeight; y++) { // Set draw color if(!arr[x][y]) fill(255); else fill(0); // Draw spot rect(x*cellWidth,y*cellHeight,cellWidth,cellHeight); } } }