Skip to main content
Engineering LibreTexts

10.18: Checking if the Level is Finished

  • Page ID
    14679
  • def isLevelFinished(levelObj, gameStateObj):
        """Returns True if all the goals have stars in them."""
        for goal in levelObj['goals']:
            if goal not in gameStateObj['stars']:
                # Found a space with a goal but no star on it.
                return False
        return True
    
    
    def terminate():
        pygame.quit()
        sys.exit()
    
    
    if __name__ == '__main__':
        main()
    

    The isLevelFinished() function returns True if all the goals are covered stars. Some levels could have more stars than goals, so it’s important to check that all the goals are covered by stars, rather than checking if all the stars are over goals.

    The for loop on line 3 [585] goes through the goals in levelObj['goals'] (which is a list of tuples of XY coordinates for each goal) and checks if there is a star in the gameStateObj['stars'] list that has those same XY coordinates (the not in operators work here because gameStateObj['stars'] is a list of those same tuples of XY coordinates). The first time the code finds a goal with no star at the same position, the function returns False.

    If it gets through all of the goals and finds a star on each of them, isLevelFinished() returns True.

    This terminate() function is the same as in all the previous programs.

    After all the functions have been defined, the main() function is called on line 16 [598] to begin the game.

    • Was this article helpful?