game of life

Description: The game of life was proposed by British mathematician JH Conway in 1970. The neighbors of a cell include the cells adjacent to the upper, lower, left, right, upper left, lower left, upper right and lower right. The rules of the game as follows:

Solitary death: If the cell has less than one neighbor, the cell will die in the next state.

Crowded death: If a cell has more than four neighbors, the cell will die in the next state.

Stable: If the cell has two or three neighbors, the next state is stable alive.

Resurrection: If no cell survives at a location, and the location has three neighbors, the location will resurrect one cell.
 

Solution: The rules of the game of life can be simplified as follows, and can be implemented using a program using CASE comparison:

When the number of neighbors is 0, 1, 4, 5, 6, 7, and 8, the next state of the cell is death.

When the number of neighbors is 2, the next state of the cell is resurrection.

When the number of neighbors is 3, the next state of the cell is stable.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXROW 10
#define MAXCOL 25
#define DEAD 0
#define ALIVE 1
int map[MAXROW][MAXCOL], newmap[MAXROW][MAXCOL];
void init();
int neighbors(int, int);
void outputMap();
void copyMap();
int main() {
    int row, col;
    char ans;
    init();
    while(1){
        outputMap();
        for(row = 0; row < MAXROW; row++) {
            for(col = 0; col < MAXCOL; col++) {
                switch (neighbors(row, col)) {
                    case 0:
                    case 1:
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                    case 8:newmap[row][col] = DEAD;break;
                    case 2:newmap[row][col] = map[row][col];break;
                    case 3:newmap[row][col] = ALIVE;break;
                }
            }
        }
        copyMap();
        printf("\nContinue next Generation ? ");
        getchar();
        ans = toupper(getchar());
        if(ans != 'Y') break;
    }
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324503091&siteId=291194637