代码是做康威的生命游戏,读取文件中的点,它可以正确打印,当执行一次规则时,它只打印棋盘。如果我删除规则部分,它会给我正确的 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");
}
最佳答案
您需要两个板:当前的板和 future (下一个)板:char b[80][80]、next[80][80]
。当您评估规则时,从当前板 (b
) 获取数据,但将结果记录到 future 板 (next[..][..]=...
)。 遍历所有单元格后,使用 bcopy()
或在嵌套循环中将 future 板的内容复制到当前板中。
关于康威生命游戏函数中的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44054705/