JSFiddle - React, Tailwind, and code Playground
HTML
<div class="central">
<h1>Conway's Game of Life</h1>
<canvas id="grid"></canvas>
<button id="btnPlay">Play</button>
<button id="btnStop">Stop</button>
<button id="btnRandom">Random</button>
</div>
CSS
.clearfix:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
html {
width: 100%;
height: 100%;
}
body {
font-size: 16px;
font-family: 'Century Gothic', Verdana;
margin: 30px auto;
width: 600px;
background-color: #eee;
}
h1,h2,h3,h4,h5,h6 {margin: 0px;}
h1 {
margin: -30px -30px 30px -30px;
padding: 10px 30px;
background-color: #ccc;
border-radius: 10px 10px 0px 0px;
text-transform: uppercase;
text-align: center;
font-family: Helvetica;
}
div.center {
text-align: center;
}
div.central {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0px 10px 20px -5px rgba(0,0,0,0.25);
border: #ccc solid 1px;
}
#grid {
border: gray solid 1px;
}
JavaScript
/**
*
*/
var Evolution = {
/**
*
*/
Infos: {
grid: [],
grid_tmp: [],
isPlaying: false,
playInterval: undefined,
canvas: undefined,
context: undefined
},
/**
*
*/
Settings: {
grid_size: 4,
grid_x: 135,
grid_y: 135,
speed: 100,
randomPercentage: 1
},
/**
* Initialize the evolution system.
*/
Init: function() {
this.Infos.canvas = document.getElementById("grid"),
this.Infos.context = this.Infos.canvas.getContext("2d");
this.Infos.canvas.width = this.Settings.grid_x * this.Settings.grid_size;
this.Infos.canvas.height = this.Settings.grid_y * this.Settings.grid_size;
this.Prepare();
this.ApplyRandom();
this.PrintGrid();
this.BindButtons();
},
Play: function() {
var $this = Evolution;
clearInterval($this.Infos.playInterval);
$this.Infos.playInterval = setInterval($this.PrintGrid, $this.Settings.speed);
$this.Infos.isPlaying = true;
},
Stop: function() {
var $this = Evolution;
clearInterval($this.Infos.playInterval);
$this.Infos.isPlaying = false;
},
/**
*
*/
BindButtons: function() {
$('#btnPlay').click(this.Play);
$('#btnStop').click(this.Stop);
$('#btnRandom').click(this.ApplyRandom);
},
/**
*
*/
Prepare: function() {
for(var y = 0; y < this.Settings.grid_y; y++) {
for(var x = 0; x < this.Settings.grid_x; x++) {
this.Infos.grid[(y * this.Settings.grid_x) + x] = false;
}
}
},
/**
*
*/
ApplyRandom: function() {
var $this = Evolution;
var total = $this.Settings.grid_x * $this.Settings.grid_y;
var number = parseInt(total * ($this.Settings.randomPercentage / 100));
for(var i = 0; i < total; i++) {
$this.Infos.grid[i] = false;
}
for(var i = 0; i < number; i++) {
var random = Math.floor((Math.random() * total) + 1);
...