Skip to content

Instantly share code, notes, and snippets.

@roppa
Last active August 29, 2019 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roppa/b7c3c8d7edef5c4f041fe8fef54e851e to your computer and use it in GitHub Desktop.
Save roppa/b7c3c8d7edef5c4f041fe8fef54e851e to your computer and use it in GitHub Desktop.
Game of life experiment
/**
Quick POC for game of life. Terrible side effects. Actually doing this in Rust but wanted to quickly knock something out in js
**/
let width = 40
function getCells() {
return new Array(width * width).fill(false)
}
let cells = getCells()
cells[1] = true
cells[2] = true
cells[6] = true
cells[30] = true
cells[31] = true
cells[26] = true
cells[51] = true
cells[52] = true
cells[53] = true
cells[54] = true
cells[125] = true
cells[126] = true
cells[145] = true
cells[146] = true
cells[167] = true
cells[168] = true
cells[187] = true
cells[188] = true
cells[221] = true
cells[222] = true
cells[223] = true
cells[382] = true
cells[403] = true
cells[421] = true
cells[422] = true
cells[423] = true
// Any live cell with fewer than two live neighbours dies, as if by underpopulation
// Any live cell with two or three live neighbours lives on to the next generation
// Any live cell with more than three live neighbours dies, as if by overpopulation
// Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction
function getCell(cell, neighbours) {
if (cell) {
if (neighbours === 2 || neighbours === 3) {
return true
}
return false
} else {
if (neighbours === 3) {
return true
}
return false
}
}
function regenerate() {
let newCells = []
for (let i = 0, w = 0; i < width * width; i++, w++) {
if (!(i % width)) {
w = 0
}
let neighbours = [cells[i - (width - 1)],
cells[i - width], cells[i - (width + 1)],
cells[i - 1], cells[i + 1],
cells[i + (width - 1)], cells[i + width], cells[i + (width + 1)]
].reduce((curr, next) => next ? curr + 1 : curr, 0)
newCells.push(getCell(cells[i], neighbours))
w++
}
cells = newCells
}
function drawGrid() {
let grid = ''
for (let i = 0, w = 0; i < width * width; i++) {
if (!(i % width)) {
w = 0
grid += '\n'
}
grid += `| ${cells[i] ? 'x' : ' '} |`
}
console.log(grid)
}
setInterval(() => {
drawGrid()
regenerate()
}, 500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment