Skip to content

Instantly share code, notes, and snippets.

@nonZero
Created June 14, 2016 14:12
Show Gist options
  • Save nonZero/7d569511efd004d729f194be87008270 to your computer and use it in GitHub Desktop.
Save nonZero/7d569511efd004d729f194be87008270 to your computer and use it in GitHub Desktop.
jqlife 1
.r {
clear:left;
}
.cell {
border: 1px solid #555;
width: 40px;
height: 40px;
float:left;
}
.alive {
background: #555;
}
<link rel="stylesheet" href="jqlife.css">
<input type="number" value="8" id="cols">
<input type="number" value="12" id="rows">
<button id="next">Next</button>
<div id="life">
</div>
<script src="jquery-2.2.4.js"></script>
<script src="jqlife.js"></script>
"use strict";
var life = function (board) {
// Make an empty board for next level;
return board.map(function (row, y) {
return row.map(function (cell, x) {
var n = 0;
if (y > 0) {
if (x > 0) {
n += board[y - 1][x - 1];
}
n += board[y - 1][x];
if (x < row.length - 1) {
n += board[y - 1][x + 1];
}
}
if (x > 0) {
n += board[y][x - 1];
}
if (x < row.length - 1) {
n += board[y][x + 1];
}
if (y < board.length - 1) {
if (x > 0) {
n += board[y + 1][x - 1];
}
n += board[y + 1][x];
if (x < row.length - 1) {
n += board[y + 1][x + 1];
}
}
var b = cell ? n == 2 || n == 3 : n == 3;
return b ? 1 : 0;
});
});
};
$(function () {
const draw = board => {
$("#life").empty();
board.forEach(row => {
let r = $('<div class="r"></div>');
row.forEach(col => {
r.append('<div class="cell"></div>');
});
$("#life").append(r);
});
};
const refresh = () => {
let rows = +$("#rows").val();
let cols = +$("#cols").val();
var board = Array.from(new Array(rows)).map(() => {
return Array.from(new Array(cols)).map(() => 0);
});
draw(board);
};
refresh();
$("#cols,#rows").on("input", refresh);
$("#life").on("click", ".cell", function() {
$(this).toggleClass("alive");
});
$("#next").click(function () {
var board = $("#life .r").toArray().map(function(row) {
return $(row).find(".cell").toArray().map(function(cell) {
return $(cell).hasClass('alive') ? 1 : 0;
});
});
var nextGen = life(board);
const rows = $("#life .r");
nextGen.forEach((row, j) => {
row.forEach((cell, i) => {
console.log(i, j, cell);
rows.eq(j).find('.cell').eq(i).toggleClass('alive', !!cell);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment