Skip to content

Instantly share code, notes, and snippets.

@nonZero
Created June 14, 2016 14:30
Show Gist options
  • Save nonZero/bf259edd54611897e48d280a4d94edd9 to your computer and use it in GitHub Desktop.
Save nonZero/bf259edd54611897e48d280a4d94edd9 to your computer and use it in GitHub Desktop.
jqlife 2 (buggy)
.r {
clear:left;
}
.cell {
transition: background 0.4s;
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 getBoard = function () {
return $("#life .r").toArray().map(function (row) {
return $(row).find(".cell").toArray().map(function (cell) {
return $(cell).hasClass('alive') ? 1 : 0;
});
});
};
const serializeBoard = function(board) {
return board.map(row => row.map(cell => cell ? "X" : ".").join("")).join("\n");
};
const saveBoard = function() {
localStorage.setItem('board', serializeBoard(getBoard()));
};
const draw = board => {
$("#life").empty();
board.forEach(row => {
let r = $('<div class="r"></div>');
row.forEach(col => {
r.append($('<div class="cell"></div>').toggleClass('alive', !!col));
});
$("#life").append(r);
});
};
const refresh = () => {
let rows = +$("#rows").val();
let cols = +$("#cols").val();
try {
var board = localStorage.getItem('board').split("\n").map(
row => row.split('').map(cell => cell === "X" ? 1 : 0))
console.log(board);
} catch (e) {
console.log(e);
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");
saveBoard();
});
$("#next").click(function () {
var board = getBoard();
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);
});
});
saveBoard();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment