*/
Looking for work? Check out our jobs area.
*/

View \Life_80X24.CPP

Classic Conway's Game of Life in text mode (80 * 24 cells)

Submitted By: Krishnakumar_M
Rating: (Not rated) (Rate It)


#include<iostream.h>
#include<conio.h>
#include<dos.h>
#include"sfx.cpp"
enum state{dead,alive};
state a[24][80],b[24][80];
state update(int,state);
int nsum(int,int);
void initdead()
{
int i,j;
for(i=0;i<24;i++)
  for(j=0;j<80;j++)
      {
      a[i][j]=dead;
      b[i][j]=dead;
      }
}
void display(state a[24][80])
{
int i,j;
for(i=0;i<24;i++)
  for(j=0;j<80;j++)
      {
      a[i][j]=b[i][j];
      gotoxy(j+1,i+1);
      if(a[i][j]==dead)
          cout<<" ";
      else
          cout<<" ";
      }
}
void start()
{
clrscr();
initdead();
display(a);
center("ThE GaMe Of LiFe",10);
center("KrIsHnAkUmAr M",14);
gotoxy(2,25);
cout<<" ESC-Quit Arrows-Move Space-Toggle life R-Run C-Clear";
}
void main()
{int x=40,y=12,i,j,n,k1;
char k,k0;
start();
do{
gotoxy(x,y);
k=getch();
switch(k)
{
case 0:k0=getch();
       switch(k0)
       {
       case 72:
                if(y>1)
                y--;
               break;
       case 80:
                if(y<24)y++;
               break;
       case 75:
                if(x>1)x--;
               break;
       case 77:
                if(x<80)x++;
               break;
       }
       break;
case ' ':a[y-1][x-1]=(a[y-1][x-1]==alive)?dead:alive;
         if(a[y-1][x-1]==alive)
                cout<<" ";
         else
                cout<<" ";
         break;
case 'R':
case 'r':_setcursortype(_NOCURSOR);
         while(!kbhit())
         {
         for(i=0;i<24;i++)
          for(j=0;j<80;j++)
         {
           n=nsum(i,j);
           b[i][j]=update(n,a[i][j]);
         }
         display(a);
         delay(100);
         }
         _setcursortype(_NORMALCURSOR);
         break;
case 'C':
case 'c':start();
         break;
}
}while(k!=27);
}
//
int nsum(int i,int j)
{int neisum=0;
 if(i>0)
 {neisum+=a[i-1][j];
   if(j>0)
       neisum+=a[i-1][j-1];
   if(j<79)
       neisum+=a[i-1][j+1];
 }
 if(i<23)
 {neisum+=a[i+1][j];
   if(j>0)
       neisum+=a[i+1][j-1];
   if(j<79)
       neisum+=a[i+1][j+1];
 }
  if(j>0)
       neisum+=a[i][j-1];
   if(j<79)
       neisum+=a[i][j+1];
 return(neisum);
}
state update(int n,state now)
{
if((n>3)||(n<2))
      return(dead);
if(n==3)
      return(alive);
if((n==2)&&(now==alive))
      return(alive);
return(dead);

}

corner
© 1996-2008 CommunityHeaven LLC. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
North American business development: Nicolai Wadstrom. Publisher: Lars Hagelin.