代码是做康威的生活游戏,读取文件中的点并且可以正确打印,一旦做了规则,它只会打印我的板。如果我删除规则部分,它会给我正确数量的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");
}
答案 0 :(得分:0)
你需要两个板:当前的和未来的(下一个)板:char b[80][80], next[80][80]
。评估规则时,请从当前板(b
)获取数据,但将结果记录到未来的板(next[..][..]=...
)中。 在之后,您遍历所有单元格,将未来电路板的内容复制到当前电路板中bcopy()
或嵌套循环。