public
Created

Conway's Game Of Life running on an Arduino, displaying on a string of RGB LEDs arranged in a matrix

  • Download Gist
LifeInColor.pde
Processing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
/*
* Conway's "Life"
*
* Adapted from the Life example
* on the Processing.org site
*
* Written by David Kavanagh (dkavanagh@gmail.com).
*/
#include "SPI.h"
#include "Adafruit_WS2801.h"
 
int dataPin = 2; // Yellow wire on Adafruit Pixels
int clockPin = 3; // Green wire on Adafruit Pixels
 
Adafruit_WS2801 display = Adafruit_WS2801((uint16_t)7, (uint16_t)7, dataPin, clockPin);
 
#define DELAY 300
#define SIZE 7
extern byte leds[SIZE][SIZE];
byte world[SIZE][SIZE][3]; // 0=currentgen, 1=nextgen, 2=age
long density = 50;
uint32_t colors[8] = {0x000000, 0x444400, 0x004444, 0x440044, 0x880000, 0x008800, 0x000088, 0x999999};
 
void setup() {
display.begin();
display.show();
randomSeed(analogRead(5));
 
}
 
void randomize() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (random(100) < density) {
world[i][j][0] = 1;
}
else {
world[i][j][0] = 0;
}
world[i][j][1] = 0;
world[i][j][2] = 0;
}
}
}
void loop() {
// Display current generation
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
display.setPixelColor(i, j, colors[world[i][j][2]]);
}
}
display.show();
delay(DELAY);
 
// Birth and death cycle
for (int x = 0; x < SIZE; x++) {
for (int y = 0; y < SIZE; y++) {
// Default is for cell to stay the same
world[x][y][1] = world[x][y][0];
int count = neighbours(x, y);
if (count == 3 && world[x][y][0] == 0) {
// A new cell is born
world[x][y][1] = 1;
}
if (world[x][y][2] < 7) {
world[x][y][2] += world[x][y][1];
}
if ((count < 2 || count > 3) && world[x][y][0] == 1) {
// Cell dies
world[x][y][1] = 0;
world[x][y][2] = 0;
}
}
}
boolean changes = false;
// Copy next generation into place
for (int x = 0; x < SIZE; x++) {
for (int y = 0; y < SIZE; y++) {
if (world[x][y][0] != world[x][y][1]) {
changes = true;
}
world[x][y][0] = world[x][y][1];
}
}
if (!changes) {
randomize();
}
}
 
int neighbours(int x, int y) {
return world[(x + 1) % SIZE][y][0] +
world[x][(y + 1) % SIZE][0] +
world[(x + SIZE - 1) % SIZE][y][0] +
world[x][(y + SIZE - 1) % SIZE][0] +
world[(x + 1) % SIZE][(y + 1) % SIZE][0] +
world[(x + SIZE - 1) % SIZE][(y + 1) % SIZE][0] +
world[(x + SIZE - 1) % SIZE][(y + SIZE - 1) % SIZE][0] +
world[(x + 1) % SIZE][(y + SIZE - 1) % SIZE][0];
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.