码迷,mamicode.com
首页 > 编程语言 > 详细

5 数组之生命游戏

时间:2018-01-23 22:04:43      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:rtu   tar   art   概念   --   new   状态保持   span   包含   

学完数组的概念后,有一个简单的小游戏特别适合上手---生命游戏,假设有int Cells[30][30],也即有30×30个小格子,
每个小格子里面可以有细胞生命,或者细胞死亡。通过把这些状态输出出来,就可以显示出相应的图案。
生命游戏演化的规则:

每个矩阵方格可以包含一个有机体,不在边上的有机体有8个相邻方格。
1. 如果一个细胞周围有3个细胞为生,则该细胞为生(即该细胞若原先为死,则转为生,若原先为生,则保持不变)
2. 如果一个细胞周围有2个细胞为生,则该细胞的生死状态保持不变
3. 在其它情况下,该细胞为死(即该细胞若原先为生,则转为死,若原先为死,则保持不变)

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

#define High 25 //游戏画面尺寸
#define Width 50

int cells[High][Width];    //1生 0死

void gotoxy(int x, int y){
    HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;
    pos.X = x;
    pos.Y = y;
    SetConsoleCursorPosition(handle, pos);
}

void startup(){
    int i, j;
    for(i = 0; i < High; i++){
        for(j = 0; j < Width; j++){
            cells[i][j] = 1;
        }
    }
}

void show(){
    gotoxy(0, 0);
    int i, j;
    for(i = 1; i <= High - 1; i++){
        for(j = 1; j <= Width - 1; j++){
            if(cells[i][j] == 1)
                printf("*");    //活的细胞
            else
                printf(" ");    //输出空格
        }
        printf("\n");
    }
    Sleep(50);
}

void updateWithoutInput(){
    int NewCells[High][Width];    //下一帧的细胞情况
    int NeibourNumber;
    int i, j;
    for(i = 1; i <= High - 1; i++){
        for(j = 1; j <= Width - 1; j++){
            NeibourNumber = cells[i-1][j-1] + cells[i-1][j] + cells[i-1][j+1] + cells[i][j-1] + cells[i][j+1] + cells[i+1][j-1] + cells[i+1][j] + cells[i+1][j+1];
            if(NeibourNumber == 3)
                NewCells[i][j] = 1;
            else if(NeibourNumber == 2)
                NewCells[i][j] = cells[i][j];
            else
                NewCells[i][j] = 0;
        }
    }
    for(i = 1; i <= High - 1; i++)
        for(j = 1; j <= Width - 1; j++)
            cells[i][j] = NewCells[i][j];
}

void updateWithInput(){
    
}

void main(){
    startup();
    while(1){
        show();
        updateWithoutInput();
        updateWithInput();
    }
}

 

5 数组之生命游戏

标签:rtu   tar   art   概念   --   new   状态保持   span   包含   

原文地址:https://www.cnblogs.com/leosirius/p/8337959.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!