JSFiddle - React, Tailwind, and code Playground
by jackwanders
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css">
<div id="game">
<div id="board" class="stopped"></div>
<button class="btn btn-primary" id="go">Start</button>
<button class="btn btn-danger" disabled id="end">Stop</button>
<button class="btn" id="clear">Clear Board</button>
<div id="location">
Col: <span id="col">--</span><br>
Row: <span id="row">--</span>
</div>
</div>
CSS
body {
height: 100%;
width: 100%;
margin: 20px;
padding: 0;
}
#location {
position: absolute;
bottom: 0px;
right: 10px;
font-family: "Courier New", Courier, mono;
}
#board {
background: #eee;
overflow: hidden;
border: solid #ddd;
border-width: 1px 0 0 1px;
margin-bottom: 20px;
}
.cell {
float: left;
background: white;
border: solid #ddd;
border-width: 0 1px 1px 0;
}
.stopped .cell:hover {
background: #ccc;
}
.cell.clear {
clear: left;
}
.cell.live,
.cell.live:hover {
background: black !important;
}
JavaScript
var LifeGame = {
gridSize: 80,
cellSize: 8,
speed: 10,
playing: false,
cells: [],
liveCells: 0,
toggleCell: function() {
var $this = $(this),
pos = $this.data(),
neighborInc,
x,y;
if($this.hasClass('live')) {
LifeGame.liveCells -= 1;
$this.removeClass('live');
neighborInc = -1;
} else {
LifeGame.liveCells += 1;
$this.addClass('live');
neighborInc = 1;
}
for(x = pos.x-1; x <= pos.x+1; x++) {
for(y = pos.y-1; y <= pos.y+1; y++) {
if(!(x === pos.x && y === pos.y)) {
neighbor = $('#'+x+'-'+y);
if(neighbor.length) {
neighbor.data('neighbors',neighbor.data('neighbors')+neighborInc);
}
}
}
}
}
};
$(function() {
var x, y, cell,
board = $('#board'),
startButton = $('#go'),
stopButton = $('#end'),
clearButton = $('#clear'),
interval,
cells,
colSpan = $('#col'),
rowSpan = $('#row');
for (x = 0; x < LifeGame.gridSize; x++) {
LifeGame.cells[x] = [];
for (y = 0; y < LifeGame.gridSize; y++) {
cell = $('<div class="cell">');
cell.attr('id',x+'-'+y)
.css({
width: LifeGame.cellSize+'px',
height: LifeGame.cellSize+'px'
})
.data({
x: x,
y: y,
neighbors: 0
});
if (y === 0) {
cell.addClass('clear');
}
board.append(cell);
...