How to Make Conway's Game of Life in HTML5

Introduction 

 
The game of Conway is one of the examples of games because it's related to cellular automata. The game of life also called simply life. The game of Conway is a board game. In these games follow many different types of patterns occur in the game of life. In more common cases it is impossible to look at a starting position or pattern and see what will happen in the future. Here we find a way to find out is to follow the rules of the game.
 
There are some rules which as follows :
  • A cell with 0 or 1 neighbor dies because of underpopulation.
  • When a cell with 4 or more neighbors dies because of overpopulation.
  • If any empty space has exactly 3 cells then a new cell is born in that empty space.
  • If none of the above rules apply then the space does not change a live cell remains alive, and an empty space is still empty.
Step 1: Open any HTML editor (ex. Visual Studio, Notepad, etc) and in the source code page (the page where you want to write the HTML code) type the following lines.
 
Here first of all, given a title.
  1. <!doctype html><html><head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script><link rel="stylesheet" href="css/site.css" type="text/css" media="screen" /><title>Conway's Game of Life</title>  
Step 2: This step is writing the canvas tags with a default message in the case when the user's browser does not support it. So, apply this condition. 
  1. else {  
  2.        alert("Canvas is unsupported in your browser.");  
  3.      }  
Step 3: The given code works on there things simply.
  • Here we have to declare how many cells we want on the X/Y axes.
  • In there, different cells wide should be a cell and the delay between drawing the next generation of cells.
  • So create 2 arrays, one for storing the initial colony and one for the next generation.
  • We have to fill randomly with live cells in the initial part.
  • We have to draw the initial part and then process the initial part using the game's rules.
  1. < script type = "text/javascript" >  
  2.  $(document).ready(  
  3.   function() {  
  4.    Array.matrix = function(m, n, initial) {  
  5.     var a, i, j, mat = [];  
  6.     for (i = 0; i < m; i += 1) {  
  7.      a = [];  
  8.      for (j = 0; j < n; j += 1) {  
  9.       a[j] = 0;  
  10.      }  
  11.      mat[i] = a;  
  12.     }  
  13.     return mat;  
  14.    };  
  15.    var Life = {};  
  16.    Life.CELL_SIZE = 8;  
  17.    Life.X = 576;  
  18.    Life.Y = 320;  
  19.    Life.WIDTH = Life.X / Life.CELL_SIZE;  
  20.    Life.HEIGHT = Life.Y / Life.CELL_SIZE;  
  21.    Life.DEAD = 0;  
  22.    Life.ALIVE = 1;  
  23.    Life.DELAY = 500;  
  24.    Life.STOPPED = 0;  
  25.    Life.RUNNING = 1;  
  26.    Life.minimum = 2;  
  27.    Life.maximum = 3;  
  28.    Life.spawn = 3;  
  29.    Life.state = Life.STOPPED;  
  30.    Life.interval = null;  
  31.    Life.grid = Array.matrix(Life.HEIGHT, Life.WIDTH, 0);  
  32.    Life.counter = 0;  
  33.    Life.updateState = function() {  
  34.     var neighbours;  
  35.     var nextGenerationGrid = Array.matrix(Life.HEIGHT, Life.WIDTH, 0);  
  36.     for (var h = 0; h < Life.HEIGHT; h++) {  
  37.      for (var w = 0; w < Life.WIDTH; w++) {  
  38.       neighbours = Life.calculateNeighbours(h, w);  
  39.       if (Life.grid[h][w] !== Life.DEAD) {  
  40.        if ((neighbours >= Life.minimum) && (neighbours <= Life.maximum)) {  
  41.         nextGenerationGrid[h][w] = Life.ALIVE;  
  42.        }  
  43.       } else {  
  44.        if (neighbours === Life.spawn) {  
  45.         nextGenerationGrid[h][w] = Life.ALIVE;  
  46.        }  
  47.       }  
  48.      }  
  49.     }  
  50.     Life.copyGrid(nextGenerationGrid, Life.grid);  
  51.     Life.counter++;  
  52.    };  
  53.    Life.calculateNeighbours = function(y, x) {  
  54.     var total = (Life.grid[y][x] !== Life.DEAD) ? -1 : 0;  
  55.     for (var h = -1; h <= 1; h++) {  
  56.      for (var w = -1; w <= 1; w++) {  
  57.       if (Life.grid[(Life.HEIGHT + (y + h)) % Life.HEIGHT][(Life.WIDTH + (x + w)) % Life.WIDTH] !== Life.DEAD) {  
  58.        total++;  
  59.       }  
  60.      }  
  61.     }  
  62.     return total;  
  63.    };  
  64.    Life.copyGrid = function(source, destination) {  
  65.     for (var h = 0; h < Life.HEIGHT; h++) {  
  66.      /* 
  67.      for (var w = 0; w < Life.WIDTH; w++) { 
  68.      destination[h][w] = source[h][w]; 
  69.      } 
  70.      */  
  71.      destination[h] = source[h].slice(0);  
  72.     }  
  73.    };   
  74.    function Cell(row, column) {  
  75.     this.row = row;  
  76.     this.column = column;  
  77.    };  
  78.    var gridCanvas = document.getElementById('grid');  
  79.    var counterSpan = document.getElementById("counter");  
  80.    var controlLink = document.getElementById("controlLink");  
  81.    var clearLink = document.getElementById("clearLink");  
  82.    var minimumSelect = document.getElementById("minimumSelect");  
  83.    var maximumSelect = document.getElementById("maximumSelect");  
  84.    var spawnSelect = document.getElementById("spawnSelect");  
  85.    controlLink.onclick = function() {  
  86.     switch (Life.state) {  
  87.      case Life.STOPPED:  
  88.       Life.interval = setInterval(function() {  
  89.        update();  
  90.       }, Life.DELAY);  
  91.       Life.state = Life.RUNNING;  
  92.       break;  
  93.      default:  
  94.       clearInterval(Life.interval);  
  95.       Life.state = Life.STOPPED;  
  96.     }  
  97.    };  
  98.    clearLink.onclick = function() {  
  99.     Life.grid = Array.matrix(Life.HEIGHT, Life.WIDTH, 0);  
  100.     Life.counter = 0;  
  101.     clearInterval(Life.interval);  
  102.     Life.state = Life.STOPPED;  
  103.     updateAnimations();  
  104.    }  
  105.    minimumSelect.onchange = function() {  
  106.     clearInterval(Life.interval);  
  107.     Life.state = Life.STOPPED;  
  108.     Life.minimum = minimumSelect.value;  
  109.     updateAnimations();  
  110.    }  
  111.    maximumSelect.onchange = function() {  
  112.     clearInterval(Life.interval);  
  113.     Life.state = Life.STOPPED;  
  114.     Life.maximum = maximumSelect.value;  
  115.     updateAnimations();  
  116.    }  
  117.    spawnSelect.onchange = function() {  
  118.     clearInterval(Life.interval);  
  119.     Life.state = Life.STOPPED;  
  120.     Life.spawn = spawnSelect.value;  
  121.     updateAnimations();  
  122.    }  
  123.   
  124.    function update() {  
  125.     Life.updateState();  
  126.     //updateInput();  
  127.     //updateAI();  
  128.     //updatePhysics();  
  129.     updateAnimations();  
  130.     //updateSound();  
  131.     //updateVideo();  
  132.    };  
  133.    function updateAnimations() {  
  134.     for (var h = 0; h < Life.HEIGHT; h++) {  
  135.      for (var w = 0; w < Life.WIDTH; w++) {  
  136.       if (Life.grid[h][w] === Life.ALIVE) {  
  137.        context.fillStyle = "#000";  
  138.       } else {  
  139.        context.fillStyle = "#FF0000";  
  140.        //context.clearRect();  
  141.       }  
  142.       context.fillRect(  
  143.        w * Life.CELL_SIZE + 1,  
  144.        h * Life.CELL_SIZE + 1,  
  145.        Life.CELL_SIZE - 1,  
  146.        Life.CELL_SIZE - 1);  
  147.      }  
  148.     }  
  149.     counterSpan.innerHTML = Life.counter;  
  150.    };  
  151.    if (gridCanvas.getContext) {  
  152.     var context = gridCanvas.getContext('2d');  
  153.     var offset = Life.CELL_SIZE;  
  154.     for (var x = 0; x <= Life.X; x += Life.CELL_SIZE) {  
  155.      context.moveTo(0.5 + x, 0);  
  156.      context.lineTo(0.5 + x, Life.Y);  
  157.     }  
  158.     for (var y = 0; y <= Life.Y; y += Life.CELL_SIZE) {  
  159.      context.moveTo(0, 0.5 + y);  
  160.      context.lineTo(Life.X, 0.5 + y);  
  161.     }  
  162.     context.strokeStyle = "#254117";  
  163.     context.stroke();   
  164.     function canvasOnClickHandler(event) {  
  165.      var cell = getCursorPosition(event);  
  166.      var state = Life.grid[cell.row][cell.column] == Life.ALIVE ? Life.DEAD : Life.ALIVE;  
  167.      Life.grid[cell.row][cell.column] = state;  
  168.      updateAnimations();  
  169.     };  
  170.     function getCursorPosition(event) {  
  171.      var x;  
  172.      var y;  
  173.      if (event.pageX || event.pageY) {  
  174.       x = event.pageX;  
  175.       y = event.pageY;  
  176.      } else {  
  177.       x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;  
  178.       y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;  
  179.      }  
  180.      x -= gridCanvas.offsetLeft;  
  181.      y -= gridCanvas.offsetTop;  
  182.      var cell = new Cell(Math.floor((y - 4) / Life.CELL_SIZE), Math.floor((x - 2) / Life.CELL_SIZE));  
  183.      return cell;  
  184.     };  
  185.     gridCanvas.addEventListener("click", canvasOnClickHandler, false);  
  186.    } else {  
  187.     alert("Canvas is unsupported in your browser.");  
  188.    }  
  189.   }  
  190.  );   
  191. function minimumSelect_onclick() {  
  192. } <  
  193. /script><  
  194. script type = "text/javascript" >  
  195.  var _gaq = _gaq || [];  
  196. _gaq.push(['_setAccount''UA-2662092-4']);  
  197. _gaq.push(['_trackPageview']);  
  198. (function() {  
  199.  var ga = document.createElement('script');  
  200.  ga.type = 'text/javascript';  
  201.  ga.async = true;  
  202.  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';  
  203.  var s = document.getElementsByTagName('script')[0];  
  204.  s.parentNode.insertBefore(ga, s);  
  205. })() <  
  206. /script><  
  207. script type = "text/javascript" >  
  208.  var _gaq = _gaq || [];  
  209. _gaq.push(['_setAccount''UA-2662092-4']);  
  210. _gaq.push(['_trackPageview']);  
  211. (function() {  
  212.  var ga = document.createElement('script');  
  213.  ga.type = 'text/javascript';  
  214.  ga.async = true;  
  215.  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';  
  216.  var s = document.getElementsByTagName('script')[0];  
  217.  s.parentNode.insertBefore(ga, s);  
  218. })(); <  
  219. /script>  
Step 4: This application contains body follow the code given below.
  1. <body>  
  2.     <div id="container">  
  3.         <div id="header">  
  4.             <h1>Conway's Game of Life</h1>  
  5.         </div>  
  6.         <div id="left-content">  
  7.             <h2>Game</h2>  
  8.             <p>Generation counter:   
  9.                 <span id="counter">0</span>  
  10.             </p>  
  11.             <canvas id="grid" width="577" height="321"></canvas>  
  12.         </div>  
  13.         <div id="right-content">  
  14.             <h2>Controls</h2>  
  15.             <a id="controlLink" href="javascript:void(0)">Start/Stop</a>  
  16.             <br />  
  17.             <a id="clearLink" href="javascript:void(0)">Clear Grid</a>  
  18.             <select id="minimumSelect" disabled="disabled" onclick="return minimumSelect_onclick()"></select>  
  19.             <br />  
  20.             <select id="maximumSelect" disabled="disabled"></select>  
  21.             <br />  
  22.             <select id="spawnSelect" disabled="disabled"></select>  
  23.             <br />  
  24.             <p></p>  
  25.         </div>  
  26.     </div>  
  27. </body>  
Step 5: After writing this code the application an run in browser we have to see the figure given below.
 
 conway game.jpg
 
Step 6: After click on the game board we have to find it.
 
conwa.jpg
 
We have to play anything with cells.
 
conway.jpg
 
Step 7: With the start/stop button on click and clear the game board with the use of the clear button.
 
befor run.jpg
 
After making on cells click on start button we have to find this figure given below.
 
after run.jpg
 
Resources
 
Here are some useful resources: