// Pollen ex 1 by Mike Davis // mike [at] lightcycle [dot] org // A short program for alife experiments. // // Each cell is represented by a pixel on the display as well as an entry in // the Vector 'cells'. Cells each have a run() method, which performs actions // based on the cell's surroundings. Cells run one at a time (to avoid conflicts // like wanting to move to the same space) in random order. World w; Vector cells; int spore_color; // set lower for smoother animation, higher for faster simulation int runs_per_loop = 10000; void setup() { size(100, 400); noBackground(); clearscr(); w = new World(); cells = new Vector(); spore_color = color(172, 255, 128); // Add a bunch of cells at random places for (int i = 0; i < 4000; i++) { int cX = (int)random(width); int cY = (int)random(height); if (w.get(cX, cY) == 0) { w.set(cX, cY, spore_color); cell a = new cell(cX, cY); cells.add(0, a); } } } void loop() { // Run cells in random order cell selected; for (int i = 0; i < runs_per_loop; i++) { selected = (cell)cells.elementAt(min((int)random(cells.size()), cells.size() - 1)); selected.run(); } } void clearscr() { for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) setPixel(x, y, 0); } class cell { int x, y; cell(int x, int y) { this.x = x; this.y = y; } // Perform action based on surroundings void run() { // Fix cell coordinates while(x < 0) x+=width; while(x > width - 1) x-=width; while(y < 0) y+=height; while(y > height - 1) y-=height; // Cell instructions if (w.get(x + 1, y) == 0) { if (w.get(x, y + 1) != 0) { move(-1, 0); } else { move((int)random(3) - 1, 1); } } } // Will move the cell (dx, dy) units if that space is empty void move(int dx, int dy) { if (w.get(x + dx, y + dy) == 0) { w.set(x + dx, y + dy, w.get(x, y)); w.set(x, y, 0); x += dx; y += dy; } } } // The World class simply provides two functions, get and set, which access the // display in the same way as getPixel and setPixel. The only difference is that // the World class's get and set do screen wraparound ("toroidal coordinates"). class World { void set(int x, int y, int c) { while(x < 0) x+=width; while(x > width - 1) x-=width; while(y < 0) y+=height; while(y > height - 1) y-=height; setPixel(x, y, c); } int get(int x, int y) { while(x < 0) x+=width; while(x > width - 1) x-=width; while(y < 0) y+=height; while(y > height - 1) y-=height; return getPixel(x, y); } } void mousePressed() { setup(); }