Skip to content

Instantly share code, notes, and snippets.

@sudaraka
Last active September 17, 2016 10:51
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 sudaraka/df64ad4c0d54226e69c7b1e61351f8e5 to your computer and use it in GitHub Desktop.
Save sudaraka/df64ad4c0d54226e69c7b1e61351f8e5 to your computer and use it in GitHub Desktop.
Cellular Automata Demo - as in https://www.youtube.com/watch?v=bc-fVdbjAwk
(function() {
'use strict'
const
MEMBERS = 181,
GENERATIONS = 100,
randomState = () => Math.random() > .5,
createCell = () => {
const
cell = document.createElement('div')
cell.className = randomState() ? 'active' : 'inactive'
return cell
},
createGeneration = members => {
const
row = document.createElement('div')
row.className = 'generation'
for(let i = 0; i < members + 1; i++) {
row.appendChild(createCell())
}
return row
},
getNewState = (prev, current, next) => {
const
rulesMap = {
'active': {
'active': {
'active': 'inactive',
'inactive': 'active'
},
'inactive': {
'active': 'inactive',
'inactive': 'inactive'
}
},
'inactive': {
'active': {
'active': 'active',
'inactive': 'inactive'
},
'inactive': {
'active': 'inactive',
'inactive': 'active'
}
}
}
return rulesMap[prev.className][current.className][next.className] || 'unknown'
},
cloneGeneration = parent => {
const
nextGen = parent.cloneNode(true)
nextGen.childNodes.forEach((cell, i) => {
cell.className = getNewState(
parent.childNodes[i - 1] || parent.childNodes[parent.childNodes.length - 1],
parent.childNodes[i],
parent.childNodes[i + 1] || parent.childNodes[0]
)
})
return nextGen
}
let
cellGeneration,
timer
timer = window.setInterval(() => {
const
universe = document.querySelector('#universe')
cellGeneration = cellGeneration ? cloneGeneration(cellGeneration) : createGeneration(MEMBERS)
universe.appendChild(cellGeneration)
if(GENERATIONS < universe.childNodes.length) {
universe.removeChild(universe.childNodes[0])
// window.clearInterval(timer)
}
}, 100)
}())
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cellular Automata Example</title>
<link href="./styles.css" rel="stylesheet">
</head>
<body>
<div id="universe"></div>
<script src="./automata.js"></script>
</body>
</html>
.generation {
height: 5px;
margin: 0;
}
.generation > div {
background-color: #9cf;
width: 5px;
height: 5px;
margin: 0;
display: inline-block;
}
.generation > .active {
background-color: #000;
}
.generation > .unknown {
background-color: #f00;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment