【发布时间】:2017-05-18 17:48:59
【问题描述】:
代码是做conway的人生游戏,读取文件中的点就可以正常打印,做一次规则时,只打印我的棋盘。如果我删除规则部分,它会给我正确数量的 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");
}
【问题讨论】:
-
你只有一个板子。在更改当前板之前,您需要计算所有下一个板。最好的方法是交换指向两个板的指针,而不是复制数据。
-
不,一直有两块板。您从当前的板计算下一个板。然后你翻转(指向)板。
-
你用新配置覆盖了当前板,这会扭曲进一步的规则计算。
-
在改变当前状态之前,需要计算下一代的整体。最简单的方法首先是
memcpy,然后是当前一代。一种更复杂、更快速的方法是交换指向这对板的指针,而不是复制数据。 -
@Savitor 如果您更改您尝试读取的同一块板,它会弄乱存活计数,因为新细胞正在影响老一代。每次开始新的一代时,您都需要创建一个新板,或者每代在 2 个板之间交换。