簡體   English   中英

如何使用文本文件制作生活游戲的C程序

[英]How to make a C Program for Game of Life using text file

我被要求:

創建一個ANSI C程序,該程序將讀取包含25 x 25字符“ x”或空格的文本文件。

Display the initial generation using the function printf.

Calculate the next generation using the rules mentioned above and save it in another textfile.

The filenames of the input and output textfiles should be specified as command-line parameters.

到目前為止,我所擁有的只是一個要求輸入文本文件的代碼,然后我的代碼將其打印出來。 我缺乏適用Conway人生游戲規則的代碼。 我不知道放在哪里。 以及使用什么代碼。 :( 請幫我。

這是我現在所擁有的:

#include <stdio.h>
#include <string.h>

#define MAX_LINE_LEN 80
#define N 25

void display(char [][N+1], size_t);

int main(int argc, char *argv[]) {
  FILE *fp;
  char in[MAX_LINE_LEN];
  char grid[N][N+1] = { { '\0' } };
  size_t i = 0;

  printf("Enter filename: ");
  fgets(in, MAX_LINE_LEN, stdin);
  *(strchr(in, '\n')) = '\0';
  if ((fp = fopen(in, "r")) != NULL) {
    while ((i < N) && (fgets(in, MAX_LINE_LEN, fp) != NULL)) {
      *(strchr(in, '\n')) = '\0';
      /* should verify only 'x' and space in string before storing */
      strncpy(grid[i++], in, N);
    }
    /* pad each row with spaces, if necessary, for NxN array */
    for (i = 0; i < N; i++) {
      while (strlen(grid[i]) < N) {
        strcat(grid[i], " ");
      }
    }
    /* For all generations ...
            compute next generation */
            display(grid, N);
    /* End for all generations */
  } else {
    printf("%s not found.\n", in);
    getch();
  }
  getch();
}

void display(char a[][N+1], size_t n) {
    size_t i;
    for (i = 0; i < n; puts(a[i++]));
}
*(strchr(in, '\n')) = '\0'; 

壞棗 如果strchr返回NULL,則將出現段錯誤。 我知道您的數據將始終有換行符,但這是一個壞習慣。 始終strchr的結果分配給變量,並首先執行NULL檢查:

char *tmp = strchr(in, '\n');
if (tmp)
  *tmp = 0;

坦白說,我認為將您的網格視為字符串數組會帶來比其難以解決的更多痛苦。 像對待其他任何類型的二維數組一樣對待它。 無論您做什么,在輸入文件中每行末尾處理換行符都會很麻煩。

至於如何構造代碼,請從高層次考慮問題:

  1. 您需要加載一個文件作為起始網格;
  2. 您需要為某些世代計算下一代的網格。
  3. 您需要顯示每個網格;
  4. 您需要每個網格寫入文件。

您已經將顯示代碼拆分為自己的功能; 您只需要對加載,計算和編寫函數執行相同的操作(您可以將文件加載代碼保留在main ,但是如果將其放在自己的函數中,則可以使代碼更整潔)。

void load(const char *filename, char (*grid)[N], size_t rows) {...}
void calc(char (*grid)[N], size_t rows) {...}
void save(const char *filename, char (*grid)[N], size_t rows) {...}

因此,每次通過main調用時,您只需在調用display之前在網格上調用calc ,然后調用save將新的網格寫入文件。

至於如何計算下一個網格,那是您分配的一部分,我不想全力以赴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM