[英]Conway's Game of life logic error in the function
The code is to do conway's game of life, read points in a file and it can print properly, when do once the rule, it only print me the board. 该代码用于执行conway的游戏,读取文件中的点,并且可以正确打印,一旦执行规则,则仅将其打印在板上。 If i delete the rule part, it gives me the right number of nb and locations. 如果我删除规则部分,它将为我提供正确数量的nb和位置。
#include <stdio.h>
#include <stdlib.h>
int l, w, i, n, a, x, y;
char b[80][80], ip[10];
int main(int argc, char *argv[])
{
n=argc;/*check the number of elements in argv*/
if (n!=5){
fprintf(stderr, "ENTERED ELEMENTS IS WRONG\n");
exit (0);
}
w=atoi(argv[2]);/*read from a file*/
l=atoi(argv[3]);
FILE* f;
f = fopen(argv[1],"r");
if (f == NULL){/*print ERROR when file the is null*/
fprintf(stderr, "ERROR READING FILE\n");
exit (0);
}
for (x = 0; x < l; x++){/*all points are 0*/
for(y = 0; y < w; y++){
b[x][y] = 0;
}
}
fscanf(f, "%d", &a);/*get the number of points*/
for (i=0; i<a; i++){
fscanf(f, "%d %d", &x, &y);
b[x][y] = 1;/*the points that mentioned are 1*/
}
printf("*");/*To print the first line of the board*/
for (i=0; i< w; i++){
printf("-");
}
printf("*\n");
for (x=0; x<l; x++){
printf("|");
for (y=0; y<w; y++){
if (b[x][y]==1){
printf("X");/*frint all the ponints, 0 is ' ', 1 is 'X'*/
}
else {
printf(" ");
}
}
printf("|\n");
}
printf("*");/*To print the last line of the board*/
for (i=0; i< w; i++){
printf("-");
}
printf("*\n\n");
/*the end of printing the first graph*/
fgets(ip,10,stdin);
while (ip!= NULL){
generate();
fgets(ip,10,stdin);
}
}
void generate(void){
int nb;
/*4 rules*/
for (x = 1; x < l-1; x++){
for(y = 1; y < w-1; y++){
nb = b[x-1][y-1]
+b[x-1][y]
+b[x-1][y+1]
+b[x][y-1]
+b[x][y+1]
+b[x+1][y-1]
+b[x+1][y]
+b[x+1][y+1];
if (b[x][y]==1){
if (nb<2||nb>3){
b[x][y]=0;
}else {
b[x][y]=1;
}
}
if (b[x][y]==0){
if (nb==3){
b[x][y]=1;
}
}
}
}
/*To print the board same as printing the graph in main function*/
printf("*");
for (i=0; i< w; i++){
printf("-");
}
printf("*\n");
for (x=0; x<l; x++){
printf("|");
for (y=0; y<w; y++){
if (b[x][y]==1){
printf("X");
}
else {
printf(" ");
}
}
printf("|\n");
}
printf("*");
for (i=0; i< w; i++){
printf("-");
}
printf("*\n\n");
}
You need two boards: the current one and the future (next) one: char b[80][80], next[80][80]
. 您需要两个板块:当前板块和将来(下一个)板块: char b[80][80], next[80][80]
。 When you evaluate the rules, take the data from the current board ( b
), but record the results into the future board ( next[..][..]=...
). 在评估规则时,请从当前板( b
)中获取数据,但将结果记录到将来的板中( next[..][..]=...
)。 After you iterate through all cells, copy the content of the future board into the current board with bcopy()
or in a nested loop. 当你通过所有细胞循环,未来主板的内容复制到当前的董事会bcopy()
或嵌套循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.