On Monday, Mar. 28, we did this illustration of the first half of Chapter 7. It is Exercise 7.1: CA with random ruleset.
int w = 5;
int[] cells = new int[width / w];
class CA {
int[] cells;
int[] ruleset;
int generation = 0;
CA(int rule) {
println("Cellular automataton with rule " + rule + ".");
cells = new int[width / w];
ruleset = new int[8];
for (int i = 0; i < 8; ++i) {
int power_of_2 = 1 << (7 - i);
ruleset[i] = rule / power_of_2;
rule = rule % power_of_2;
}
for (int i = 0; i < cells.length; ++i) {
cells[i] = 0;
}
cells[cells.length/2] = 1;
}
void generate() {
int[] nextgen = new int[cells.length];
for (int i = 0; i < cells.length; ++i) {
int left = i - 1 < 0 ? cells[cells.length - 1] : cells[i - 1];
int middle = cells[i];
int right = i + 1 >= cells.length ? cells[0] : cells[i + 1];
nextgen[i] = ruleset[4 * left + 2 * middle + right];
}
cells = nextgen;
generation++;
}
void drawCA() {
for (int i = 0; i < cells.length; ++i) {
if (cells[i] == 1) {
fill(0);
} else {
fill(255);
}
rect(i * w, generation * w % height, w, w);
}
}
}
CA ca;
void setup() {
frameRate(10);
size(805, 1200); // should be multiples of w -- more symmetrical if width is an odd multiple
ca = new CA(90);
ca.drawCA();
}
void draw() {
ca.generate();
ca.drawCA();
}
void mousePressed() {
int newRule = (int)random(0.0, 256.0);
ca = new CA(newRule);
background(newRule);
ca.drawCA();
}