Skip to content Skip to sidebar Skip to footer

Game Of Life - Overwriting The Current Generation Instead Of Updating To The Next

Below I have added my game of life code. The rules are defined correctly, and it runs smoothly. However, the game does not work as supposed. It is not updating to the next generati

Solution 1:

You've to deep copy next_generation to current_generation. But

current_generation = list(next_generation)

doesn't do what you expect it to do, since the elements of next_generation are a list, too.

To deep copy a list of where each element is a list of numbers (objects won't be copied) you've to:

current_generation = [list(e) for e in next_generation]

or

current_generation = [[i for i in j] for j in next_generation]

or

current_generation = [e[:] for e in next_generation]

Since there is a nested loop in the method GameOfLife.update_gen, the issue can be solved by an simple assignment, too:

classGameOfLife:

    # [...]# Updating the cells in the current generation.defupdate_gen(self):
        global current_generation
        for y inrange(Y_CELLS):
            for x inrange(X_CELLS):
                c = next_generation[x][y]
                self.draw_cell(x, y, c)
                current_generation[x][y] = next_generation[x][y] # assign element by element

There is a further issue, when the animation is running and the game is manipulated by the mouse. When the mouse is pressed, then next_generation is changed by either .activate_living_cell or .deactivate_living_cell. But after that next_generation is recalculated by the data in current_generation.

while not self.game_over:
     self.handle_events()       # change "next_generation" by clickifself.next_iteration:
         self.create_next_gen() # compute "next_generation" from "current_generation"self.update_gen()          # copy "current_generation" from "next_generation"

The issue can be solved with ease. Consider that when the game is manipulated by the mouse, the content of current_generation and next_generation is equal.

Either change current_generation instead of next_generation or update current_generation after the manipulation:

defhandle_events(self):
    for event in pygame.event.get():

        # [...]        # Pressing the left mouse button to activate or deactivate a cell.if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if next_generation[x][y] == COLOR_DEAD:
                    self.activate_living_cell(x, y)
                else:
                   self.deactivate_living_cell(x, y)
                self.update_gen() # <----------------------------

Post a Comment for "Game Of Life - Overwriting The Current Generation Instead Of Updating To The Next"