二维数组的应用举例(生态)/(五子棋)

/* N == 3 产生宝宝
* N > 3 饿死
* N < 2 孤独而死
*       根据周围活细胞的情况,决定细胞的生死。
*   若周围大于三个,中间的细胞死;若周围为3个,中间原来没有,就生宝宝。
*/

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
/*
#include <unistd.h>//标准unix借口
#include <sys/ioctl.h>
#include <termios.h>
*/
#define  WIDTH 10
#define  HEIGHT 10
int main()
{
    char cells[HEIGHT][WIDTH];//字符型矩阵
    srand(time(NULL));//系统时间置随机种子
    int i = 0;
    int j = 0;
    //生命赋初值
    for (i = 0; i < HEIGHT; i++)
        for (j = 0; j < WIDTH; j++)
            cells[i][j] = rand() % 2 ? '*' : ' ';//0 死掉 1 有生命
    int gen;

    //画出这个群落
    for (gen = 1; ; gen++)//生物代繁殖
    {
        printf("+-");
        for (i = 0; i < WIDTH * 2; i++)
            printf("-");
        printf("+\n");
        int live = 0;
        for (i = 0; i < HEIGHT; i++)
        {
            printf("| ");
            for (j = 0; j < WIDTH; j++)
            {
                printf("%c ", cells[i][j]);
                if (cells[i][j] == '*')
                    live++;
            }
            printf("|\n");
        }
        printf("+-");
        for (i = 0; i < WIDTH * 2; i++)
            printf("-");
        printf("+\n");

        printf("第%d代,有%d个活的。\n", gen, live);
        int ch = getchar();
        if( ch == 'Q' || ch == 'q')
            break;
        //每一个细胞都要控制其生死,考虑边角条件
        for ( i =0; i < HEIGHT; i++)
        {
            for ( j = 0; j < WIDTH; j++)
            {
                int u = i - 1;
                int d = i + 1;
                int l = j - 1;
                int r = j + 1;
                int around = 0;
                if (u >= 0 && cells[u][j] == '*')
                    around++;
                if (d < HEIGHT && cells[d][j] == '*')
                    around++;
                if (l >= 0 && cells[i][l] == '*')
                    around++;
                if (r < WIDTH && cells[i][r] == '*')
                    around++;
                if (u >= 0 && l >= 0 && cells[u][l] == '*')
                    around++;
                if (u >= 0 && r < WIDTH&&cells[u][r] == '*')
                    around++;
                if (d < HEIGHT&&l >= 0 && cells[d][l] == '*')
                    around++;
                if (d < HEIGHT&&r < WIDTH&&cells[d][r] == '*')
                    around++;
                if (around == 3)
                    cells[i][j] = '*';
                else if (around != 2)
                    cells[i][j] = ' ';

            }
        }

    }
    return 0;
}


/*
//改变getchar函数的回显与回车功能
int getch(void)
{
    struct termois term_old;
    ioctl(STDIN_FILENO, TCGETS, &term_old);
    struct termois term_new = term_old;
    term_new.c_lflag &= ~(ECHO | ICANNO);
    ioctl(STDIN_FILENO, TCSETS, &term_new);
    int ch = getchar();
    ioctl(STDIN_FILENO, TCSETS, &term_old);
    return ch;
}
*/

猜你喜欢

转载自blog.csdn.net/haronchou/article/details/69664771