Skip to content

Instantly share code, notes, and snippets.

@mathew-fleisch
Last active October 16, 2019 18:17
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 mathew-fleisch/c9522f21aba5b6b5035889ef92b5aa57 to your computer and use it in GitHub Desktop.
Save mathew-fleisch/c9522f21aba5b6b5035889ef92b5aa57 to your computer and use it in GitHub Desktop.
Conways Game of Life
/**
*
* Conway's Game of Life
* 1. If a live cell has less than 2 live neighbors, it dies. *
* 2. If a live cell has more than 3 live neighbors, it dies. *
* 3. If a live cell has exactly 2-3 live neighbors, it lives. *
* 4. If a dead cell has exactly 3 live neighbors, it comes to life. *
* 0 == DEAD
* 1 == ALIVE
*/
const speed = 500
//const BASE_STATE = [
// [0, 0, 0, 0, 0],
// [0, 0, 1, 0, 0],
// [0, 0, 0, 1, 0],
// [0, 1, 1, 1, 0],
// [0, 0, 0, 0, 0]
//]
const BASE_STATE = makeMatrix(30, true)
function gameOfLife(state, num) {
let newState = makeMatrix(state.length)
let matrixlength = state[0].length
for (let i = 0; i < matrixlength; i++) {
for (let j = 0; j < matrixlength; j++) {
let currentState = state[i][j]
// console.log(currentState)
// Check if it is alive
let neighbors = getNeighbors(state, i, j)
// console.log(`neighbors: ${neighbors}`)
// Die
if ( neighbors < 2 || neighbors > 3) {
newState[i][j] = 0
} else {
newState[i][j] = 1
}
}
}
//return newState
console.clear()
console.log(newState)
setTimeout(function(){ gameOfLife(newState, num+1) }, speed);
}
function getNeighbors(state, x, y) {
let matrixlength = parseInt(state[0].length-1)
let countLiveNeighbors = 0
//left
if (x > 0) {
if (state[x-1][y] == 1) {
countLiveNeighbors++
}
}
//right
if (x < matrixlength) {
if (state[x+1][y] == 1) {
countLiveNeighbors++
}
}
//down
if (y > 0) {
if (state[x][y+1] == 1) {
countLiveNeighbors++
}
}
//up
if (y < matrixlength) {
if (state[x][y-1] == 1) {
countLiveNeighbors++
}
}
//left/up
if (x > 0 && y > 0) {
if (state[x-1][y-1] == 1) {
countLiveNeighbors++
}
}
//left/down
if (x > 0 && y < matrixlength) {
if (state[x-1][y+1] == 1) {
countLiveNeighbors++
}
}
//right/down
if (x < matrixlength && y < matrixlength) {
if (state[x+1][y+1] == 1) {
countLiveNeighbors++
}
}
//right/up
if (x < matrixlength && y > 0 ) {
if (state[x][y-1] == 1) {
countLiveNeighbors++
}
}
return countLiveNeighbors
}
function makeMatrix(matrixLength = 5, random = false) {
let matrix = []
let setValue = 0
for(let i = 0; i < matrixLength; i++) {
for(let j = 0; j < matrixLength; j++) {
if (random) {
let randVal = Math.random()
setValue = (randVal > 0.5 ? 1 : 0)
}
if (j === 0) {
matrix[i] = new Array()
}
matrix[i][j] = setValue
}
}
return matrix
}
setTimeout(function() { gameOfLife(BASE_STATE, 0) }, speed);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment