Does my code for game of life look good enough? What changes can I make to optimize the code?
I am a beginner to java and I've coded the Game of Life! For those not familiar, the game entails creating a grid of specified dimensions with each box in the grid being either dead or alive. The grid starts with a random dead or alive state for each box. New generations have new dead/alive boxes based on the following conditions: If there are 3 alive boxes neighbouring any dead box, it becomes alive. If there are less than 2 alive boxes neighbouring an alive box, that box dies. It also dies if there are more than 3 alive boxes around it.
#include<cstdlib>
#include<ctime>
const int Grid_Width = 10;
const int Grid_Height = 10;
int Grid [Grid_Width][Grid_Height]; //2-D array to hold the grids
//initialize grid with random cell states
void initializegrid() {
std::srand(std::time(nullptr)); //seed the random number generator
for(auto i=0; i<Grid_Width;++i){
for(auto j=0; j<Grid_Height; ++j){
Grid[i][j]=std::rand() % 2; //gives each cell a value of 1 or 0
}
}
}
//function to print the grid to the console
void print_grid() {
for(auto i=0; i<Grid_Width;++i){
for(auto j=0; j<Grid_Height; ++j){
std::cout<< (Grid[i][j] == 1 ? "*" : ".")<<" "; //print * for live cell and . for dead one
}
std::cout<<std::endl;
}
}
//function to count live neihghbour
int countliveNeighbour( int x, int y){
int count =0;
for(auto i=-1; i<=1; ++i){
for(auto j=-1; j<=1; ++j){ //covering 3X3 grid
int neighbourX = x + i;
int neighbourY = y + j;
if(i==0 && y==0) continue; //skipping the cell itself
if(neighbourX>=0 && neighbourX< Grid_Width && neighbourY>=0 && neighbourY< Grid_Height ){
count+= Grid[neighbourX][neighbourY];
}
}
}
return count;
}
//function to update the grid based on the rules of the game
void updateGrid(){
int newGrid[Grid_Width][Grid_Height];
for(auto i=0; i<Grid_Width; ++i){
for(auto j=0; j<Grid_Height; ++j){
int liveNeighbours = countliveNeighbour(i,j);
if(Grid[i][j]==1){
if(liveNeighbours <2 || liveNeighbours >3){
newGrid[i][j]=0; //cell dies due to underpopulation
}else{
newGrid[i][j]=1;
}
}else{
if(liveNeighbours ==3){
newGrid[i][j]=1; //cell becomes alive due to overpopulation
}else{
newGrid[i][j]=0; //remains dead
}
}
}
}
//update the old grid with the new grid
for(auto i=0; i<Grid_Width; ++i){
for(auto j=0; j<Grid_Height; ++j){
Grid[i][j]=newGrid[i][j];
}
}
}
int main(){
initializegrid();
print_grid();
updateGrid();
print_grid();
}