Friday, March 7, 2014

CONWAY's GAME OF LIFE USING BUTTON in JAVA

                                GAME OF LIFE is a very common problem in which you have to create a grid of button ( so called cells) . Some of these cells are alive and others are dead.
there are three rules for a cell which decides the cell will be alive in next step or dead.

1. If a perticular cell is alive and surrounded by 3 or more than 3 it will die due to over crouding . If cell is surrounded by less than 2 alive then it will die due to lonleyness.

2.If the perticular cell is dead then it will alive in next step if it is surrounded by exactly 2 alive cells.
 
  1st step                                                      nest step
alive(surrounded by 3 or more than 3)           dead
alive (surrounded by less then 2)                   dead
dead(surrounded by exactly 2)                      alive



take a button array
  Button[][] grid=new Button[10][10];    //create a view
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++){
n[i][j]=0;
grid[i][j]=new Button();
add(grid[i][j]);
grid[i][j].addActionListener(this);
}
}

setLayout(new GridLayout(11,10));

take a 2-D array which stores 1 OR 0. 1 means alive and 0 means dead. array 'n'.

now repaete the function a number of time. like 5 times. in the  public void actionPerformed(ActionEvent a) function.


public void actionPerformed(ActionEvent a)
{

for(int i=1;i<9;i++)
{

for(int j=1;j<9;j++)
{
if(a.getSource()==grid[i][j])
{
n[i][j]=1;
grid[i][j].setBackground(Color.red);
grid[i][j].setEnabled(true);
}
}
}


go.setBackground(Color.black);
go.setEnabled(true);
int h=0;
while(h<=20)
{ h++;
int count=0;
int[][] loc=new int[20][3];
int life[]=new int[40];

for(int k=1;k<9;k++)
{
for(int l=1;l<9;l++)
{

int ctr=0;
int ut1=3,ut2=3,x=0,y=0;


x=k-1;
y=l-1;

for(int c=x;c<ut1+x;c++)
{
for(int b=y;b<ut2+y;b++)
{
if(n[c][b]==1)
{ ctr++;

}
}
}
if(n[k][l]==1)
ctr--;

if(n[k][l]==1)
{

if(ctr<2||ctr>3)
{
loc[count][0]=k;
loc[count][1]=l;
life[count++]=0;
}
if(ctr==2)
{
loc[count][0]=k;
loc[count][1]=l;
life[count++]=1;
}

}
else
{

if(ctr==3)
{
loc[count][0]=k;
loc[count][1]=l;
life[count++]=1;
}

}
}
    }
for(int i1=0;i1<count;i1++)
{
if(life[i1]==0)
{
n[loc[i1][0]][loc[i1][1]]=0;

grid[loc[i1][0]][loc[i1][1]].setBackground(Color.white);
grid[loc[i1][0]][loc[i1][1]].setEnabled(true);
}

else if(life[i1]==1)
{
n[loc[i1][0]][loc[i1][1]]=1;
grid[loc[i1][0]][loc[i1][1]].setBackground(Color.red);
grid[loc[i1][0]][loc[i1][1]].setEnabled(true);
}
}

try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
}
}


}

No comments:

Post a Comment

Contributors

Translate