Skip to content

Instantly share code, notes, and snippets.

@Fil
Created February 8, 2017 09:41
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 Fil/5eb51b886d1c004ac59fd5d58e121cdf to your computer and use it in GitHub Desktop.
Save Fil/5eb51b886d1c004ac59fd5d58e121cdf to your computer and use it in GitHub Desktop.
p5 wolfram CA
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.6/p5.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var w = 10;
// An array of 0s and 1s
var cells;
// We arbitrarily start with just the middle cell having a state of "1"
var generation = 0;
// An array to store the ruleset, for example {0,1,1,0,1,1,0,1}
var ruleset = [0, 1, 0, 1, 1, 0, 1, 0];
function setup() {
createCanvas(640, 400);
cells = Array(floor(width/w));
for (var i = 0; i < cells.length; i++) {
cells[i] = 0;
}
cells[cells.length/2] = 1;
}
function draw() {
for (var i = 0; i < cells.length; i++) {
if (cells[i] === 1) {
fill(200);
} else {
fill(51);
noStroke();
rect(i*w, generation*w, w, w);
}
}
if (generation < height/w) {
generate();
}
}
// The process of creating the new generation
function generate() {
// First we create an empty array for the new values
var nextgen = Array(cells.length);
// For every spot, determine new state by examing current state, and neighbor states
// Ignore edges that only have one neighor
for (var i = 1; i < cells.length-1; i++) {
var left = cells[i-1]; // Left neighbor state
var me = cells[i]; // Current state
var right = cells[i+1]; // Right neighbor state
nextgen[i] = rules(left, me, right); // Compute next generation state based on ruleset
}
// The current generation is the new generation
cells = nextgen;
generation++;
}
// Implementing the Wolfram rules
// Could be improved and made more concise, but here we can explicitly see what is going on for each case
function rules(a, b, c) {
if (a == 1 && b == 1 && c == 1) return ruleset[0];
if (a == 1 && b == 1 && c == 0) return ruleset[1];
if (a == 1 && b == 0 && c == 1) return ruleset[2];
if (a == 1 && b == 0 && c == 0) return ruleset[3];
if (a == 0 && b == 1 && c == 1) return ruleset[4];
if (a == 0 && b == 1 && c == 0) return ruleset[5];
if (a == 0 && b == 0 && c == 1) return ruleset[6];
if (a == 0 && b == 0 && c == 0) return ruleset[7];
return 0;
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment