Sign InNuggetsCoursesCodePadCheatsheet

Adding Scores and Levels

To make the game more fun, we want to increase the level when the player kills all the mobs. Also, we want to score some points when the player's bullet hits a mob. We may create two variables level and score and initialize them before creating the sprites in our main( ) function.

# Initialize level and score level = 1 score = 0

You may design your game to level up in different ways. Here we simply increase the level when all the mobs are killed. We create a new group of mobs with increased speed to make the game more challenging. Add the following code inside the main game loop right after collision detections. Run the code to see if it works correctly. Expecting faster mobs falling down with higher levels.

# If all mobs are gone, level up and create new mobs if not mobs: level += 1 # Create new mobs for i in range(10): m = Mob(250 + i * 50, 40, 36, level + 2) all_sprites.add(m) mobs.add(m)

We should also increase score when a bullet hits a mob. Where shall we do that? Yes, when a group collision between bullets and mobs are detected. We iterate the hits and increase score for each hit. Here the score is increased by level * 5 so that more points are earned with higher level. You may try different policies to change the score.

# If a bullet hits the mobs, remove both bullet_hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in bullet_hits: score += level * 5

Although we have levels and scores now, we still can't see them. We need to find a way to display them on screen.

© CS Wonders·Home·About·Contact·Classes·Gallery·Glossary·Fun Facts