Как проверить условия для соседей? - PullRequest
0 голосов
/ 05 июня 2019

Я упрямый о попытке решить, насколько я могу сам. Однако я думаю, что я зашел в тупик.

Я должен написать код для простой версии для игры в жизнь на сетке 20x20. Условия:

  • Ячейка с 0 или 1 живыми соседями умирает в следующем поколении.
  • Ячейка с 2 или 3 живыми соседями живет следующим поколением.
  • Ячейка с 4 или более живыми соседями умирает в следующем поколении.
  • Пустая клетка, в которой ровно 3 живых соседа, становится живой ячейка следующего поколения.

Моя конкретная проблема заключается в том, как написать алгоритм, который выполняет вышеупомянутые операции.

Я не очень старался, потому что у меня нет идей. Я действительно надеялся получить некоторые идеи, которые могли бы дать мне дополнительный толчок в завершении моей функции, которая обновляет мир / поле.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* Constants, representation of states */
#define ALIVE 'X'
#define DEAD '.'

/* Declaration of data structure */
typedef struct{
  char current;
  char next;
} cell;

/* Declaration of functions */
void initField(const int rows, const int cols, cell field[rows][cols]);
void loadGlider(const int rows, const int cols, cell field[rows][cols]);
void loadSemaphore(const int rows, const int cols, cell field[rows][cols]);
void loadRandom(const int rows, const int cols, cell field[rows][cols]);
void loadCustom(const int rows, const int cols, cell field[rows][cols]);
void printWorld(const int rows, const int cols, cell field[rows][cols]);
void evolve(const int rows,const int cols,cell field[rows][cols]);


/* Function:    main
* Description: Start and run games, interact with the user.
* Input:       About what initial structure and whether to step or exit.
* Output:      Information to the user, and the game field in each step.
*/

int main(void) {

  const int rows = 20;
  const int cols = 20;
  cell field[rows][cols];

  initField(rows,cols, field);
  printWorld(rows,cols,field);


  return 0;
}


/* Function:    initField
* Description: Initialize all the cells to dead, then asks the user about
*              which structure to load, and finally load the structure.
* Input:       The field array and its size.
* Output:      The field array is updated.
*/

void initField(const int rows, const int cols, cell field[rows][cols]) {

  for (int r = 0 ; r < rows ; r++) {
    for (int c = 0 ; c < cols ; c++) {
      field[r][c].current = DEAD;
    }
  }

  printf("Select field spec to load ([G]lider, [S]emaphore, [R]andom ");
  printf("or [C]ustom): ");

  int ch = getchar();

  /* Ignore following newline */
  if (ch != '\n') {
    getchar();
  }

  switch (ch) {
    case 'g':
    case 'G':
    loadGlider(rows, cols, field);
    break;
    case 's':
    case 'S':
    loadSemaphore(rows, cols, field);
    break;
    case 'r':
    case 'R':
    loadRandom(rows, cols, field);
    break;
    case 'c':
    case 'C':
    default:
    loadCustom(rows, cols, field);
    break;
  }
}


/* Function:    loadGlider
* Description: Inserts a glider into the field.
* Input:       The field array and its size.
* Output:      The field array is updated.
*/

void loadGlider(const int rows, const int cols, cell field[rows][cols]) {

  field[0][1].current = ALIVE;
  field[1][2].current = ALIVE;
  field[2][0].current = ALIVE;
  field[2][1].current = ALIVE;
  field[2][2].current = ALIVE;
}


/* Function:    loadSemaphore
* Description: Inserts a semaphore into the field.
* Input:       The field array and its size.
* Output:      The field array is updated.
*/

void loadSemaphore(const int rows, const int cols, cell field[rows][cols]) {

  field[8][1].current = ALIVE;
  field[8][2].current = ALIVE;
  field[8][3].current = ALIVE;
}


/* Function:    loadRandom
* Description: Inserts a random structure into the field.
* Input:       The field array and its size.
* Output:      The field array is updated. There is a 50 % chance that a cell
*              is alive.
*/

void loadRandom(const int rows, const int cols, cell field[rows][cols]) {

}


/* Function:    loadCustom
* Description: Lets the user specify a structure that then is inserted into
*              the field.
* Input:       The field array and its size.
* Output:      The field array is updated.
*/

void loadCustom(const int rows, const int cols, cell field[rows][cols]) {

  printf("Give custom format string: ");
  do {
    int r, c;
    scanf("%d,%d", &r, &c);
    field[r][c].current = ALIVE;
  } while (getchar() != '\n');
}
/* Function:    printWorld
* Description: Prints the current field
* Input:       The field array and its size.
* Output:      The field array is updated.
*/


void printWorld(const int rows, const int cols, cell field[rows][cols]){

  char c = '\n';

  while(c == '\n'){
    for (int i = 0; i < rows; i++) {
      for (int j = 0; j < cols; j++) {
        printf("%c ", field[i][j].current);
      }
      printf("\n");
    }
    c = getchar();
    if(c != '\n'){
      break;
  }
}

void evolve(const int rows,const int cols,cell field[rows][cols]){

for(int i = 0;i<rows;i++){
  for(int j =0;j<cols;j++){
    if()
  }
}


}

Вы можете видеть выше всего текущего прогресса. Все функции, кроме
printWorld() и evolve() уже сделаны и должны оставаться такими же.

Это мой текущий прогресс для evolve, это немного.

void evolve(const int rows,const int cols,cell field[rows][cols]){

for(int i = 0;i<rows;i++){
  for(int j =0;j<cols;j++){
    if()
  }
}


}

Все, что я сделал, это написал два вложенных цикла for, которые проверяют каждую ячейку.

Но я, однако, не уверен, как поступить и выполнить вышеуказанные условия. Есть идеи, как проверить соседей для каждой ячейки?

Английский не мой родной язык. Поэтому я заранее прошу прощения за любую грамматическую ошибку. А если у вас возникли проблемы с пониманием того, чего я хочу, спросите, и я уточню.

Я бы также добавил заявление об отказе от ответственности за то, что функция: printWorld не завершена, поскольку для нее все еще требуется функция evolve.

1 Ответ

1 голос
/ 05 июня 2019

Все, что я сделал, это написал два вложенных цикла for, которые проверяют каждую ячейку.

Ну, это начало.

Но я, однако, не уверен, как действовать и выполнять вышеуказанные условия. Любые идеи о том, как проверить соседей для каждой ячейки?

Функция evolve() получает field, по-видимому, описывая текущее состояние платы и следующее состояние. Казалось бы, данные для ячейки с индексами i, j будут в field[i][j]. Итак, главный вопрос: какие клетки являются соседями этой? Но это не должно быть сложно. Это восемь ячеек, отличных от (i, j), каждая из которых отличается не более чем на 1 от i или j соответственно. То есть, (i - 1, j - 1), (i - 1, j), (i - 1, j + 1), (i, j - 1), и т. Д. .. Разработайте пример, если вам нужно, с фактическими индексами ячеек, для одной ячейки.

Так что, похоже, вы бы посчитали живую популяцию всех соседних ячеек и использовали ее в сочетании с тем, жива ли текущая ячейка, чтобы определить и записать, как эта ячейка будет развиваться.

Обратите внимание, что края и углы являются особыми случаями: у них нет соседей по крайней мере на одной стороне, и вы не должны пытаться исследовать соседей, которые не существуют. Этого можно добиться, проверив, находятся ли индексы соседних ячеек в границах, прежде чем пытаться получить к ним доступ.

...