Instructions
Objective
In order to complete a C++ assignment, you will need to write a program that implements the game of life. The Game of Life is a cellular automaton devised by John Conway, which involves a grid of cells that can be either alive or dead. The program should simulate the evolution of these cells based on a set of rules. You'll need to create a C++ program that can take user input to set up the initial state of the grid and then iteratively update the grid according to the rules. The output should display the grid at each step, showing how the cells evolve over time.
Requirements and Specifications
![program to implement life game in c++](https://www.programminghomeworkhelp.com/uploads/images/program-to-implement-life-game-in-c++.webp)
Source Code
#include
using namespace std;
bool isValid(int x, int y) {
return x >= 0 && x < 10 && y >= 0 && y < 10;
}
int numNeighbours(int generation[][10], int x, int y) {
int num = 0;
if(isValid(x-1,y-1) && generation[x-1][y-1] == 1)
num++;
if(isValid(x,y-1) && generation[x][y-1] == 1)
num++;
if(isValid(x+1,y-1) && generation[x+1][y-1] == 1)
num++;
if(isValid(x-1,y) && generation[x-1][y] == 1)
num++;
if(isValid(x+1,y) && generation[x+1][y] == 1)
num++;
if(isValid(x-1,y+1) && generation[x-1][y+1] == 1)
num++;
if(isValid(x,y+1) && generation[x][y+1] == 1)
num++;
if(isValid(x+1,y+1) && generation[x+1][y+1] == 1)
num++;
return num;
}
void printGeneration(int generation[][10], int num) {
if(num == 0) {
cout << "Initial state: " << endl;
} else {
cout << "\nGeneration " << num << endl;
}
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(generation[i][j] == 0){
cout << " - ";
} else {
cout << " X ";
}
}
cout << endl;
}
}
bool nextGeneration(int generation[][10]) {
int temp[10][10];
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
temp[i][j] = generation[i][j];
}
}
bool changed = false;
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
int num = numNeighbours(temp, i, j);
if(num < 2 || num > 3) {
if(generation[i][j] != 0){
changed = true;
}
generation[i][j] = 0;
} else if (num == 3) {
if(generation[i][j] != 1){
changed = true;
}
generation[i][j] = 1;
}
}
}
return changed;
}
int main() {
int generation[10][10];
int numGenerations;
cout << "Enter the number of stages that should be played: ";
cin >> numGenerations;
cout << "Enter initial state of the board: " << endl;
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
cin >> generation[i][j];
}
}
printGeneration(generation, 0);
for(int i = 1; i <= numGenerations; i++) {
if(!nextGeneration(generation)) {
break;
}
printGeneration(generation, i);
}
return 0;
}
Related Samples
View our free C++ assignment samples for clarity and a better understanding. These samples provide detailed solutions and practical examples, helping you grasp C++ concepts effectively.
C++
C++
C++
C++
C++
C++
C++
C++
C++
C++
C++
C++
C++
C++
C++
C++
C++
C++
C++
C++