Skip to content

Instantly share code, notes, and snippets.

@dpjanes
Last active April 12, 2020 22:54
Show Gist options
  • Save dpjanes/789af74602cae6ef3bd823ddfb09a51f to your computer and use it in GitHub Desktop.
Save dpjanes/789af74602cae6ef3bd823ddfb09a51f to your computer and use it in GitHub Desktop.
Game of Life : Node.JS
const _ = require("iotdb-helpers")
const Board = _size => {
const self = Object.assign({})
let _d = {}
const _key = (x, y) => `${x}//${y}`
const _set = (d, x, y, v) => d[_key(x,y)] = v
const _get = (d, x, y) => d[_key(x,y)] || 0
self.print = () => {
for (let y = 0; y < _size; y++) {
const row = []
for (let x = 0; x < _size; x++) {
row.push(_get(_d, x, y) ? "X " : ". ")
}
console.log(row.join(""))
}
}
self.seed = n => {
for (let i = 0; i < n; i++) {
_set(_d, _.random.integer(_size), _.random.integer(_size), true)
}
}
self.evolve = () => {
const _cd = {}
for (let y = 0; y < _size; y++) {
for (let x = 0; x < _size; x++) {
_set(_cd, x, y, 0)
}
}
for (let y = 0; y < _size; y++) {
for (let x = 0; x < _size; x++) {
if (!_get(_d, x, y)) {
continue
}
_cd[_key(x - 1, y - 1)] += 1
_cd[_key(x - 1, y)] += 1
_cd[_key(x - 1, y + 1)] += 1
_cd[_key(x, y - 1)] += 1
_cd[_key(x, y + 1)] += 1
_cd[_key(x + 1, y - 1)] += 1
_cd[_key(x + 1, y)] += 1
_cd[_key(x + 1, y + 1)] += 1
}
}
const _nd = {}
for (let y = 0; y < _size; y++) {
for (let x = 0; x < _size; x++) {
const alive = !!_get(_d, x, y)
const count = _get(_cd, x, y)
if (alive && ((count === 2) || (count === 3))) {
_set(_nd, x, y, true)
} else if (!alive && (count === 3)) {
_set(_nd, x, y, true)
}
}
}
_d = _nd
}
return self
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
const size = 30
const seed = 200
const generations = 3000
const delay = 100
async function main() {
const board = Board(size)
board.seed(seed)
for (let i = 0; i < generations; i++) {
console.clear()
console.log("--", i, "--")
board.print()
board.evolve()
await sleep(delay);
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment