Good day! Can you help me with my code regarding the game, GAME OF LIFE. Please try to edit my code cause it keeps on lagging when I run it. Your help would be so much appreciated. Thank you!:)
fp=fopen(argv[1],"rt");
if (fp!=NULL) {
board=(char**)malloc(sizeof(char*)*BSIZE);
for (i=0; i<BSIZE; i++)
board[i]=(char*)malloc(sizeof(char)*(BSIZE+1));
for (i=0; i<BSIZE; i++)
board[i]=fgets(board[i],1000,fp);
fclose(fp);
}
else
board=NULL;
return board;
}
int writefile(char *argv[],char **board) {
int i,j;
FILE *fp;
fp=fopen(argv[2],"wt");
if (fp!=NULL) {
for (i=0; i<BSIZE; i++) {
for (j=0; j<BSIZE; j++)
fprintf(fp,"%c",board[i][j]);
fprintf(fp,"\n");
}
fclose(fp);
}
else
return 1;
return 0;
}
char **nextgen(char **board) {
int i,j, k, y; /*y is #of neighbors storage*/
char **temp;
int neighbor[BSIZE][BSIZE]; /*neighbors counting, storage per box*/
temp=(char**)malloc(sizeof(char*)*BSIZE);
for (i=0; i<BSIZE; i++)
temp[i]=(char*)malloc(sizeof(char)*(BSIZE+1));
/*
Your algorithm goes here. You don't need to modify any other part of the program.
You can use the array temp[][] to store the next generation.
The code below copies the contents of temp[][] back to the array board[][]
before returning.
*/
/*neighbor counting*/
for(k=0; k<=25; k++){
y=0;
if(board[1][k]== 'x') y++;
if(board[BSIZE][k]== 'x') y++;
if(board[k][1]== 'x') y++;
if(board[k][BSIZE]== 'x') y++;
neighbor[i][j]=y;
}
for(i=0;i<BSIZE;i++)
for(j=0;j<BSIZE;j++){
y=0;
if (board[i-1][j-1]=='x')
y++;
if (board[i][j-1]=='x')
y++;
if (board[i+1][j-1]=='x')
y++;
if (board[i-1][j]=='x')
y++;
if (board[i+1][j]=='x')
y++;
if (board[i-1][j+1]=='x')
y++;
if (board[i][j+1]=='x')
y++;
if (board[i+1][j+1]=='x')
y++;
neighbor[i][j]=y;
}
/*forming of 2nd generation*/
temp[i][j] = board[i][j];
for(i=0;i<BSIZE;i++)
for(j=0;j<BSIZE;j++){
if (board[i][j]=='x'){
if (neighbor[i][j]>=4 || neighbor[i][j]<=1)
temp[i][j]=' ';
if (neighbor[i][j]==2 || neighbor[i][j]==3)
temp[i][j]='x';
}
if (board[i][j]==' '){
if (neighbor[i][j]==3)
temp[i][j]='x';
else
temp[i][j]=' ';
}
}
for (i=0; i<BSIZE; i++) {
for (j=0; j<BSIZE; j++)
board[i][j]=temp[i][j];
free(temp[i]);
}
free(temp);
I'm a newbie to reading C++ code so I can only understand bits your code completely. Can you please tell me with it's suppose to do? (I found the title of your thread interesting :))
I have edited the first one with this but still the 2nd gen produced is wrong.:( help please!
for(i=1;i<BSIZE-1;i++)
for(j=1;j<BSIZE-1;j++){
y=0;
if (board[i-1][j-1]=='x')
y++;
if (board[i][j-1]=='x')
y++;
if (board[i+1][j-1]=='x')
y++;
if (board[i-1][j]=='x')
y++;
if (board[i+1][j]=='x')
y++;
if (board[i-1][j+1]=='x')
y++;
if (board[i][j+1]=='x')
y++;
if (board[i+1][j+1]=='x')
y++;
}
/*forming of 2nd generation*/
for (i=0; i<BSIZE; i++){
for (j=0; j<BSIZE; j++){
if (board[i][j] == ' ' && y == 3 ){
temp[i][j] = 'x';
}
else if (board[i][j] == 'x' && y == 2){
temp[i][j] = 'x';
}
else if (board[i][j] == 'x' && y == 3){
temp[i][j] = 'x';
}
else {
temp[i][j] = ' ';
}
}
}