Game of life cellular automata

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "TFT_4DGL.h"
00002 
00003 TFT_4DGL lcd(p9,p10,p11);
00004 
00005 #define GRID_X 30
00006 #define GRID_Y 30
00007 
00008 #define MAX_GENERATIONS 250
00009 
00010 uint8_t grid[2][GRID_X][GRID_Y];
00011 uint8_t current_grid = 0;
00012 uint8_t generations = 0;
00013 
00014 
00015 void initGrid()
00016 {
00017  int i, j;
00018  lcd.cls();
00019  current_grid = 0;
00020  for (i = 0; i < GRID_X; i++) {
00021  for (j = 0; j < GRID_Y; j++) {
00022  if ((uint8_t) rand() % 3 == 0) {
00023  grid[0][i][j] = 1;
00024  } else {
00025  grid[0][i][j] = 0;
00026  }
00027  }
00028  }
00029 }
00030 
00031 
00032 void drawGrid()
00033 {
00034  uint8_t  x,  y;
00035  uint8_t cx, cy;
00036  cx = 1;
00037  cy = 1;
00038  for (y = 0; y < GRID_Y; y++) {
00039  cx = 1;
00040  for (x = 0; x < GRID_X; x++) {
00041  if (grid[1-current_grid][x][y] != grid[current_grid][x][y]) {
00042  if(grid[current_grid][x][y]) {
00043     lcd.circle(cx,40+cy,2,WHITE);
00044  }
00045     else {
00046    lcd.circle(cx,40+cy,2,BLACK);
00047  }
00048  }
00049  cx += 8;
00050  }
00051  cy += 8;
00052  }
00053 }
00054 
00055 
00056 int count_neighbours(int x, int y)
00057 {
00058  int i, j;
00059  int result = 0;
00060 
00061  x--;
00062  y--;
00063  for (i = 0; i < 3; i++) {
00064  if (y < 0 || y > (GRID_Y - 1)) { continue; }
00065  for (j = 0; j < 3; j++) {
00066  if (x < 0 || x > (GRID_X - 1)) { continue; }
00067  if (i==1 && j == 1) { x++; continue; }
00068  if (grid[current_grid][x][y]) { result++; }
00069  x++;
00070  }
00071  y++;
00072  x -= 3;
00073  }
00074  return result;
00075 }
00076 
00077 
00078 int cmpGrid()
00079 {
00080  int i, j;
00081  for (i=0; i < GRID_Y; i++) {
00082  for (j=0; j < GRID_X; j++) {
00083  if (grid[0][i][j] != grid[1][i][j]) { return 0; }
00084  }
00085  }
00086  return 1;
00087 }
00088 
00089 void runGrid()
00090 {
00091  uint8_t x, y;
00092  int count;
00093  uint8_t value = 0;
00094  uint8_t new_grid;
00095 
00096  new_grid = 1 - current_grid;
00097  for (y = 0; y < GRID_Y; y++) {
00098  for (x = 0; x < GRID_X; x++) {
00099  count = count_neighbours(x, y);
00100  if (count < 2 || count > 3) { value = 0; }
00101  else if (count == 3) { value = 3; }
00102  else { value = grid[current_grid][x][y]; }
00103  grid[new_grid][x][y] = value;
00104  }
00105  }
00106  current_grid = new_grid;
00107 }
00108 
00109 int main()
00110 {
00111   
00112         initGrid();
00113         drawGrid();
00114 
00115 
00116 while(1)
00117 {
00118  runGrid();
00119  drawGrid();
00120  generations++;
00121  if (generations > MAX_GENERATIONS || cmpGrid()) {
00122  generations = 0;
00123  initGrid();
00124  }
00125 }
00126 }