我试图将坐标(x,y)存储在文本文件中,其中x表示行号,y表示列。然后我将使用此信息将数组元素更改为1,其他元素将保持为0.我想多次对同一个.txt文件执行此操作。我试图模拟着名的生命游戏。问题是只能从文件中成功读取一次,因此数组无法更新,因此数组只会打印出与以前相同的内容。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROWS 30
#define COLS 20
#define ITERATIONS 6
int fillBoard(int b[ROWS][COLS]);
int newRound(FILE *i, int b[ROWS][COLS]);
int cellAliveOrDead(FILE *p, int b[ROWS][COLS]);
int cellBirth(FILE *p, int b[ROWS][COLS]);
int main(void) {
int board[ROWS][COLS];
char fileName[] = "#life 1.06";
int i, j;
int x, y;
int round = 0;
FILE *fp, *ifp;
char fileFormat[11];
int p, o;
fp = fopen("life.txt", "r");
ifp = fopen("life2.txt", "r");
if (fp == NULL) {
printf("Error\n");
exit(1);
}
if (ifp == NULL) {
exit(1);
}
fillBoard(board);
fgets(fileFormat, 11, fp); // read input from first line
if (strcmp(fileName, fileFormat) == 0) {
while (fscanf(fp, "%d %d", &x, &y) == 2) {
board[x][y] = 1;
printf("x:%d y:%d\n", x, y);
}
} else {
printf("Wrong file");
}
// print game with the starter cells
for (i = 0; i < ROWS; i++) {
printf("\n");
for (j = 0; j < COLS; j++) {
printf("%d", board[i][j]);
}
}
newRound(ifp, board);
fclose(fp);
fclose(ifp);
return(0);
}
int newRound(FILE *ij, int b[ROWS][COLS]) {
int round = 0;
int x, y;
int i, j;
while (round < ITERATIONS) {
printf("\n");
cellAliveOrDead(ij, b);
cellBirth(ij, b);
fillBoard(b);
while (fscanf(ij, "%d %d", &x, &y) == 2) {
b[x][y] = 1;
printf("x:%d y:%d\n", x, y);
}
round++;
// print game round 2
for (i = 0; i < ROWS; i++) {
printf("\n");
for (j = 0; j < COLS; j++) {
printf("%d", b[i][j]);
}
}
}
}
int fillBoard(int b[ROWS][COLS]) {
int i, j;
for(i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
b[i][j] = 0;
}
}
}
int cellAliveOrDead(FILE *p, int b[ROWS][COLS]) {
int count;
int i, j;
for(i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
count = 0;
if(b[i][j] == 1) {
if(b[i-1][j] == 1) count++;
if(b[i+1][j] == 1) count++;
if(b[i][j-1] == 1) count++;
if(b[i][j+1] == 1) count++;
if(b[i-1][j-1] == 1) count++;
if(b[i-1][j+1] == 1) count++;
if(b[i+1][j-1] == 1) count++;
if(b[i+1][j+1] == 1) count++;
if(count == 2 || count == 3) {
//b[i][j] = 1;
fprintf(p, "%d %d\n", i, j);
}
}
}
}
}
int cellBirth(FILE *p, int b[ROWS][COLS]) {
int count;
int i, j;
for(i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
count = 0;
if (b[i][j] == 0) {
if(b[i-1][j] == 1) count++;
if(b[i+1][j] == 1) count++;
if(b[i][j-1] == 1) count++;
if(b[i][j+1] == 1) count++;
if(b[i-1][j-1] == 1) count++;
if(b[i-1][j+1] == 1) count++;
if(b[i+1][j-1] == 1) count++;
if(b[i+1][j+1] == 1) count++;
if (count == 3) {
//b[i][j] = 1;
fprintf(p, "%d %d\n", i, j);
}
}
}
}
}