mardi 26 mai 2015

Conway's Game of Life-Cells Dying When They're Not Supposed to? (Java)

I am trying to code a very basic version of Conway's Game of Life. My program almost works but the 1's (which represent the alive cells) keep dying even when they have two or three live neighbors. It's strange because the blinker works but when I try the beacon pattern it no longer works.

Here is a wikipedia link that has the patterns I am talking about. http://ift.tt/nUiY4B's_Game_of_Life.

Here is my code:

public class GameofLife {
public static void main(String[] args){
    int [][] array = new int [12][12];
    array[8][8]=1;
    array[8][9]=1;
    array[8][7]=1;
    int [][] end = new int [12][12];
    printArray(array);
    System.out.println("");
    System.out.println("");
    int a=0;
    while(a<30){
    for(int i=1; i<=10; i++)
    {
        for(int j=1; j<=10; j++)
        {
            int counter = surround(array,i,j);
            if(array[i][j]==1 && counter<2)
            {
                end[i][j]=0;
            }
            if(array[i][j]==1 && counter==2)
            {
                array[i][j]=1;
            }
            if(array[i][j]==1 && counter>4)
            {
                end[i][j]=0;
            }
            if(array[i][j]==0 && counter==3)
            {
                end[i][j]=1;
            }
            if(array[i][j]==1 && counter==3)
            {
                end[i][j]=1;
            }
        }
    }
    printArray(end);    
    a++;
    for(int i=0; i<12; i++)
    {
        for(int j=0; j<12; j++)
        {
            array[i][j]=end[i][j];
            end[i][j]=0;
        }
    }
    System.out.println("");
    System.out.println("");
    }

}

    public static int surround(int[][] initial, int i, int j){
    int[][] surrounding = {{initial[i-1][j-1],initial[i-1][j],initial[i-1][j+1]},
            {initial[i][j-1],initial[i][j],initial[i][j+1]},
            {initial[i+1][j-1],initial[i+1][j],initial[i+1][j+1]}};
    int counter = 0;
    for(int a=0; a<=2; a++)
    {
        for(int b=0; b<=2; b++)
        {
            if(surrounding[a][b]==1)
            {
                counter ++;
            }
        }
    }
    return counter;
}
public static void printArray(int[][] input)
{
    for(int x =0; x<input.length; x++)
    {
        for(int y=0; y< input[0].length; y++)
        {
            System.out.print(input[x][y]);
        }
        System.out.println("");
    }
}

}

Thank you for any help!

Aucun commentaire:

Enregistrer un commentaire