P5 example from https://p5js.org/examples/simulate-wolfram-ca.html
Built with blockbuilder.org
| license: mit |
P5 example from https://p5js.org/examples/simulate-wolfram-ca.html
Built with blockbuilder.org
| <!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> |