游戏算法-生命游戏

游戏算法-生命游戏


生命游戏又称细胞自动机。反映了生命演化的规则。

生命游戏原理:生命生活在二维环境中,每个生命生活在一个方格中,每个细胞在下一个时刻的状态取决于周围8个细胞的活着或死了的状态。

1) 如果周围活着的细胞数量少于设定的值,细胞将孤独而死。

2) 如果周围活着的细胞数量多于设定的值,细胞将拥挤而死。


状态机举例:



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


#define BOARD 10
char world[BOARD][BOARD] = 
{
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,
0,0,0,1,1,1,0,0,0,0,
0,0,0,1,0,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,
0,0,0,0,0,1,0,0,0,0,
0,0,0,1,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0
};


void game_run(char world[10][10], int nLive)
{
    int i = 0, j = 0;
    int nAliveCnt = 0;
    int nContinue = 0;

    for (i=0; i< 10; i++)
    {
        for (j = 0; j < 10; j++)
        {
            printf("%d ", world[i][j]);
        }
        printf("\n");
    }

    printf("***********************************\n\n");

    while (1)
    {
        for (i = 0; i < BOARD; i++)
        {
            for (j = 0; j < BOARD; j++)
            {
                nAliveCnt = 0;
                if ((i-1>0)&&(j-1>0)&&(world[i-1][j-1]) > 0)
                {
                    nAliveCnt++;
                }
                if ((i-1>0)&&(world[i-1][j]>0))
                {
                    nAliveCnt++;
                }

                if ((j+1<BOARD)&&(i-1>0)&&(world[i-1][j+1] >0))
                {
                    nAliveCnt++;
                }
                if ((j-1>0)&&(world[i][j-1]>0))
                {
                    nAliveCnt++;
                }

                if ((j+1<BOARD)&&(world[i][j+1]>0))
                {
                    nAliveCnt++;
                }

                if ((i+1<BOARD)&&(j-1>0)&&(world[i+1][j-1]>0))
                {
                    nAliveCnt++;
                }

                if ((i+1<BOARD)&&(world[i+1][j]>0))
                {
                    nAliveCnt++;
                }
                if ((i+1<BOARD)&&(j+1<BOARD)&&(world[i+1][j+1]> 0))
                {
                    nAliveCnt++;
                }

                if ((world[i][j] == 0) && (nAliveCnt == 3))
                {
                    world[i][j] = 1;
                    nLive++;
                }
                else if (world[i][j] == 1)
                {
                    if (nAliveCnt != 2)
                    {
                        world[i][j] = 0;
                        nLive--;
                    }
                }
            }
        }

        for (i=0; i < 10; i++)
        {
            for (j =0; j < 10; j++)
            {
                printf("%d ", world[i][j]);
            }
            printf("\n");
        }

        printf("===========================\n");
        scanf("%d", &nContinue);
        if ((nLive == 100) || (nLive == 0))
        {
            printf("Live: %d\n", nLive);
            break;
        }
    } // end of while
}


int main()
{
    int n = 0;
    printf("\n");
    game_run(world, 8);
    scanf("%d", &n);
    return 0;
}





你可能感兴趣的:(游戏,算法,生活)