// ライフゲーム #include "stdafx.h" #include "time.h" #include "conio.h" #include "stdlib.h" #include "console.h" #define rand01() (rand()*2/RAND_MAX) #define NumX 20 #define NumY 20 HANDLE g_h; char Dtab[2][NumY+2][NumX+2]; int currP, nextP; void deadth(int i, int j){ Dtab[nextP][i][j]=0;} void active(int i, int j){ Dtab[nextP][i][j]=1;} int noStop(){ for(int j=1;j<=NumX;j++) for(int i=1;i<=NumY;i++) if(Dtab[currP][i][j]!=Dtab[1-currP][i][j]) return true; return false; } void initialize(){ srand((unsigned) time(NULL)); currP=0;nextP=1-currP; int NX=NumX+1;int NY=NumY+1; for(int i=0;i<=NX;i++) Dtab[currP][0][i]=Dtab[currP][NY][i]=Dtab[nextP][0][i]=Dtab[nextP][NY][i]=0; for(int i=0;i<=NY;i++) Dtab[currP][i][0]=Dtab[currP][i][NX]=Dtab[nextP][i][0]=Dtab[nextP][i][NY]=0; for(int j=1;j<=NumX;j++) for(int i=1;i<=NumY;i++){ Dtab[currP][i][j]=(char) rand01(); Dtab[nextP][i][j]=0; } g_h=getOutConsole(); setCursorInfo(g_h, 100, false); clearConsole(g_h); } void pr(){ setCursorPosition(g_h,0,0);setColor(g_h,L_RED,H_YELLOW); for(int i=1;i<=NumY;i++){ printf("\n"); for(int j=1;j<=NumX;j++) printf(Dtab[currP][i][j]==0? "□": "■"); } } void game(){ pr();int bj,aj, bi, ai, count;nextP=1-currP; for(int j=1;j<=NumX;j++){ bj=j-1; aj=j+1; for(int i=1; i<=NumY; i++){ bi=i -1; ai=i+1; count=0; if(Dtab[currP][bi][bj]) count++; if(Dtab[currP][bi][ j]) count++; if(Dtab[currP][bi][aj]) count++; if(Dtab[currP][ i][bj]) count++; if(Dtab[currP][ i][aj]) count++; if(Dtab[currP][ai][bj]) count++; if(Dtab[currP][ai][ j]) count++; if(Dtab[currP][ai][aj]) count++; if(Dtab[currP][i][j]){//周りの個数による生き死に  if(count==2 || count==3) active(i,j);else deadth(i,j); } else if(count==3) active(i,j);else deadth(i,j); } } currP=nextP; } int _tmain(int argc, _TCHAR* argv[]) { do { initialize(); setCursorPosition(g_h,0,0);setColor(g_h,H_WHITE,L_BLACK); printf(" *停止するには[ESC]キーを押します"); pr(); while(noStop()){ game(); ::Sleep(100); if(_kbhit())if(_getch()==27) break; } setCursorPosition(g_h,0,0); setColor(g_h,H_WHITE,L_BLACK); printf("* 停止しました。終了するには[ESC],続行するにはその他のキーを押します。"); }while(_getch()!=27); return 0; }