2
\$\begingroup\$

Game of life is the simplest example of zero player game for cellular automata and it was proposed by mathematician John Conway. I have tried to re implement Nicolas P. Rougier's tutorial for python code with arrays for game of life in C.

#include<stdio.h>

#define clear() printf("\033[H\033[J")

void compute(int N[6][6],int Z[6][6])
{
//compute neighbours
    int i,j;
    for (i = 1; i < 5; i++)
    {
        for (j = 1; j < 5; j++)
        {
            N[i][j]=Z[i-1][j-1]+Z[i][j-1]+Z[i+1][j-1] \
                    + Z[i-1][j]            +Z[i+1][j]   \
                    + Z[i-1][j+1]+Z[i][j+1]+Z[i+1][j+1];
        }
    }

}

void show(int Z[6][6])
{
//show output
    int i,j;
    for (i = 0; i < 6; i++)
    {
        for (j = 0; j < 6; j++)
        {
            printf("%d ", Z[i][j]);
        }
        printf("\n");
    }

}


void iteration(int Z[6][6])
{
    int N[6][6]= {{0}};
    int i,j;
    compute(N,Z);

    for (i = 0; i < 6; i++)
    {
        for (j = 0; j < 6; j++)
        {
            if((Z[i][j] == 1)&&(N[i][j] < 2 || N[i][j] > 3))
            {
                Z[i][j] = 0;
            }
            else if((Z[i][j] == 0)&&(N[i][j] == 3))
            {
                Z[i][j] = 1;
            }
        }
    }

}


int main()
{

    /* 2D arraj declaration*/
    int Z[6][6]=
    {
        {0, 0, 0, 0, 0, 0},
        {0, 0, 0, 1, 0, 0},
        {0, 1, 0, 1, 0, 0},
        {0, 0, 1, 1, 0, 0},
        {0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0},
    };
    int i;
    show(Z);
    printf("\n");
    for(i=0; i<20; i++)
    {
        //clear(); //clear screen
        iteration(Z);

    }
    show(Z);
    return 0;
}
\$\endgroup\$
2
  • \$\begingroup\$ You've shown the initial state and the state after skipping 19 generations. That's not typical for the Game of Life. \$\endgroup\$ Commented Oct 4, 2016 at 7:05
  • \$\begingroup\$ Not sure what your question is? \$\endgroup\$
    – Tolani
    Commented Oct 4, 2016 at 7:15

1 Answer 1

3
\$\begingroup\$
#define clear() printf("\033[H\033[J")

Prefer making explicit functions instead of macros. They are more easily debuggable and compilers like to inline such short functions anyway.


        N[i][j]=Z[i-1][j-1]+Z[i][j-1]+Z[i+1][j-1] \
                + Z[i-1][j]            +Z[i+1][j]   \
                + Z[i-1][j+1]+Z[i][j+1]+Z[i+1][j+1];

No need for the \ when starting a new line in the middle of a expression. The semicolon is the delimiter of statements.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.