The Game of Life Write a complete C program that implements
The Game of Life
Write a complete C program that implements Conway\'s Game of Life.
The rules for the Game of Life are simple. The universe consists of a two-dimensional matrix of cells with each cell being alive or dead. For each generation every cell determines its next phase of life as follows:
If the cell is alive:
it dies if it has 0, 1, 4 or more living neighbours (starvation), or
it lives if it has 2 or 3 living neighbours (balance).
If the cell is dead:
it springs to life if it has exactly 3 neighbours (procreation).
A cycle occurs as soon as the state of the universe of the latest generation is the same as a previous generation. You should be able to see that once this occurs the Game of Life will repeat the intermediate generations forever.
Solution
#include <iostream>
#include <cstdlib>
const int gridsize = 75; //Making this a global constant to avoid array issues.
void Display(bool grid[gridsize+1][gridsize+1]){
for(int a = 1; a < gridsize; a++){
for(int b = 1; b < gridsize; b++){
if(grid[a][b] == true){
std::cout << \" *\";
}
else{
std::cout << \" \";
}
if(b == gridsize-1){
std::cout << std::endl;
}
}
}
}
//This copy\'s the grid for comparision purposes.
void CopyGrid (bool grid[gridsize+1][gridsize+1],bool grid2[gridsize+1][gridsize+1]){
for(int a =0; a < gridsize; a++){
for(int b = 0; b < gridsize; b++){grid2[a][b] = grid[a][b];}
}
}
//Calculates Life or Death
void liveOrDie(bool grid[gridsize+1][gridsize+1]){
bool grid2[gridsize+1][gridsize+1] = {};
CopyGrid(grid, grid2);
for(int a = 1; a < gridsize; a++){
for(int b = 1; b < gridsize; b++){
int life = 0;
for(int c = -1; c < 2; c++){
for(int d = -1; d < 2; d++){
if(!(c == 0 && d == 0)){
if(grid2[a+c][b+d]) {++life;}
}
}
}
if(life < 2) {grid[a][b] = false;}
else if(life == 3){grid[a][b] = true;}
else if(life > 3){grid[a][b] = false;}
}
}
}
int main(){
//const int gridsize = 50;
bool grid[gridsize+1][gridsize+1] = {};
//Still have to manually enter the starting cells.
grid[gridsize/2][gridsize/2] = true;
grid[gridsize/2-1][gridsize/2] = true;
grid[gridsize/2][gridsize/2+1] = true;
grid[gridsize/2][gridsize/2-1] = true;
grid[gridsize/2+1][gridsize/2+1] = true;
while (true){
//The following copies our grid.
Display(grid); //This is our display.
liveOrDie(grid); //calculate if it lives or dies.
system(\"CLS\");
}
}

