1

I'm trying to write conways game of life in Java but it's not working as it should. By that I mean, still lifes work but blinkers and ships do not.

Here is the code for my algorithm, the seeding is handled by a seperate mouse listener (which is working as intended).

    int[][] state1 = new int[80][80];
    int[][] state2 = new int[80][80];
    public void logic(){
        state2=state1;
        for(int i=0;i<80;i++){
            for(int j=0;j<80;j++){
                int sum=state1[(i-1+80)%80][j]+state1[(i-1+80)%80][(j-1+80)%80]+state1[i][(j-1+80)%80]+state1[(i+1)%80][(j-1+80)%80]+state1[(i+1)%80][j]+state1[(i+1)%80][(j+1)%80]+state1[i][(j+1)%80]+state1[(i-1+80)%80][(j+1)%80];

                if(sum!=2 && sum!=3){
                    state2[i][j]=0;
                }
                else if(sum==3){
                    state2[i][j]=1;
                }
            }
        }
        state1=state2;
    }
Mot
  • 28,248
  • 23
  • 84
  • 121

1 Answers1

5

state2=state1; is not doing what you think it does.

It only makes the two variables reference the same array.

so, you are actually changing the same matrix you are taking as "last step"

To solve it, you will need to copy state1 into state2.

amit
  • 175,853
  • 27
  • 231
  • 333
  • 1
    That is exactly what I was going to say, but you beat me to it. – Philip Sheard Mar 05 '12 at 11:38
  • I changed "state2=state1;" into "state2=state1.clone();" and viceversa for "state1=state2", however the problem persists. – Babar Shariff Mar 05 '12 at 11:53
  • 1
    `clone()` is a shallow clone, it will cause similar behavior. Have a look at [this thread](http://stackoverflow.com/questions/419858/how-to-deep-copy-an-irregular-2d-array) how to deep copy 2d arrays – amit Mar 05 '12 at 11:56
  • Thank you, it's workin fine and dandy now. It's some what odd that java doesn't have a built in method of deep copying 2d arrays but meh. – Babar Shariff Mar 05 '12 at 12:00