Search code examples
javaarraysconditional-statementsconways-game-of-life

Is my new conditional logic correct for Game of Life rules? (differentiating BIRTH and LIVING conditions)


I previously asked for help looking over my Game of Life code here:Issue with Game of life code method? (User interface is complete but actual GOL methods aren't generating what they should) and received feedback (except to my last question which formed the basis to this question), but I wasn't sure how to post an updated question with my code formatted correctly in reply.

Here is my updated code to the rules only for Game of Life. I tried to factor in the suggestion that I needed to make the BIRTH and LIVING condition differentiate. But it still doesn't work and does even less than it did before (now it blanks after the first generation instead of generating nonsense). If someone could look it over and tell me if my logic is true that would be very helpful as it seems like it should work given the format of:

if ((map = true) && ((count == 2) || (count == 3))){
map2 = true;} else {map2 = false;}

if (map = false) && count == 3)
map2 = true; 
.
.
.
update map = map2;

Code:

for (int j = 0; j < y; j++) {
      for (int i = 0; i < x; i++) {
        if ((map[j][i] = true) && ((neighborCount[j][i] == 2) || (neighborCount[j][i] == 3))){//alive/dead
          map2[j][i] = true;
        } else {map2[j][i] = false;
        }

        if ((map[j][i] = false) && (neighborCount[j][i] == 3)){//birth
          map2[j][i] = true;
        }
        }
    } 

    map = map2;
  }

Solution

  • Take a look at this condition:

    if ((map[j][i] = true) && ... ) {
    

    Notice that you're writing

    (map[j][i] = true)
    

    which means "set map[j][i] to be true, then evaluate to true." In other words, this changes the contents of map[j][i] (oops!) and then continues on to the rest of the if statement.

    I believe you meant to write something like

    if ((map[j][i] == true) && ... ) {
    

    or, even better,

    if (map[j][i] && ... ) {
    

    which means the same thing and doesn't risk the accidental assignment.

    Similarly, here you write

    if ((map[j][i] = false) && ...
    

    which updates map[j][i] to be false (oops!). I think you meant

    if ((map[j][i] == false) && ...
    

    or, better yet,

    if (!map[j][i] && ...
    

    As a note, many compilers will issue warnings if they see code like what you wrote, since it's almost always the wrong thing to do. You may want to check to see whether you had such a warning. If so, now you know what that means! If not, you might want to crank up the warning level on your compiler so that it's less likely that you can make mistakes like this in the future.