// Include Sordie's "wonderful" libraries include("bitmap"); include("timer"); // Width/height constants var GOL_WIDTH = 60; var GOL_HEIGHT = 60; // Creates an array large enough to hold the board ... var gol = new Array(GOL_HEIGHT); // ... and it's sub-arrays for (var i = 0; i < GOL_HEIGHT; ++i) gol[i] = new Array(GOL_WIDTH); // Puts the initial board state // Loops over each row ... for (var y = 0; y < GOL_HEIGHT; ++y) { // ... and every cell ... for (var x = 0; x < GOL_WIDTH; ++x) { // Set every cell with a random 5% chance if (Math.random() < 0.05) gol[y][x] = 1 } } // Creates the image to draw the board state on var gol_bmp = new bitmap(GOL_WIDTH, GOL_HEIGHT); // Counts the number of living neighbours a cell has function gol_neighbours(x, y) { var neighbours = 0; // Loops over the 3 rows surrounding the cell ... for (var oy = -1; oy <= 1; ++oy) { // ... and the 3 columns for (var ox = -1; ox <= 1; ++ox) { // Don't count the cell we're looking at if (ox == 0 && oy == 0) continue; // Skips the current "for" iteration // Holds the absolute value on the board var nx = x + ox; var ny = y + oy; // Make sure the cell we check is inside the board if (nx >= 0 && nx < GOL_WIDTH && ny >= 0 && ny < GOL_HEIGHT) { // If the cell is alive, add 1 to the neighbour count if (gol[ny][nx]) ++neighbours; // Increase neighbours by 1 } } } return neighbours; } // Draws the base grid data to the bitmap function gol_init() { // Loops over each row ... for (var y = 0; y < GOL_HEIGHT; ++y) { // ... and every cell ... for (var x = 0; x < GOL_WIDTH; ++x) { // Sets the appropriate pixel depending on the cell state if (gol[y][x]) gol_bmp.setPixel(x, y, "white"); else gol_bmp.setPixel(x, y, "black"); } } } // Ticks one game logic step function gol_step() { // Creates a temporary array to write the new state to var new_gol = new Array(GOL_HEIGHT); // Copies each index of the original array for (var i = 0; i < GOL_HEIGHT; ++i) new_gol[i] = gol[i].slice(0); // Array copy // Loops over each row ... for (var y = 0; y < GOL_HEIGHT; ++y) { // ... and every cell ... for (var x = 0; x < GOL_WIDTH; ++x) { // Calls the neighbour counting function var neighbours = gol_neighbours(x, y); // The rules of the game state that a cell with 3 neighbours will // become living, and a cell with less than 2 or more than 3 dies. if (neighbours < 2 || neighbours > 3) { new_gol[y][x] = 0; gol_bmp.setPixel(x, y, "black"); } else if (neighbours == 3) { new_gol[y][x] = 1; gol_bmp.setPixel(x, y, "white"); } } } // Copies the temporary array over the original gol = new_gol; } // Call the initialize function gol_init(); // Create a timer to tick the simulator every 250ms and start it tick = new timer(100); tick.event = function() { gol_step(); }; // Creates a closure that calls gol_step() tick.start();