Develop a game with PyGame: “Jumping Rabbit” (5)

preface

This section will add a scoring mechanism, i.e. how many platforms are jumped, how many points are earned, and if the player falls out of the game frame, the player dies and a new game starts.

Incremental integration mechanism

The principle of the score mechanism is actually very simple, using PyGame to draw the corresponding text in the game box, when the player jumps to the new platform, the score changes accordingly, en… Logic is too simple, just look at the code

# main.py/Game

    # When starting a new game
    def new(self):
        Initialize the integral
        self.score = 0

    def update(self):
        #...
        
        # when the player reaches 1/4 of the game frame (note that the head of the game frame is 0, the bottom is the length of the game frame, and the top part of the game frame is reached)
        if self.player.rect.top <= HEIGHT / 4:
            # Player position movement (move down)
            self.player.pos.y += abs(self.player.vel.y)
            # When the platform is outside the game frame, log it out to avoid resource waste
            for plat in self.platforms:
                # Platform movement position (move down, move the same distance as the player, so that the player can still stand on the original platform)
                plat.rect.y += abs(self.player.vel.y)
                if plat.rect.top >= HEIGHT: 
                    plat.kill()
                    # Score increase - Platform destroy, score add
                    self.score += 10
Copy the code

In the new() method, the integral object is initialized and then updated in the update() method. Instead of getting points for jumping to a new platform, players get points after the old platform is destroyed. This prevents the player from getting points by jumping in the same place instead of jumping up.

Next comes the logic for drawing integral text, which is implemented by placing it in the draw() method.

# main.py/Game

def draw(self):
   # draw
   self.screen.fill(BLACK)
   self.all_sprites.draw(self.screen)
   # Draw text - specific score
   self.draw_text(str(self.score), 22, WHITE, WIDTH / 2.15)
   # flip
   pg.display.flip()
Copy the code

In the draw() method, the self.draw_text() method is called to display the text as follows.

# main.py/Game

    def __init__(self):
        #...
        # Set the font to use when drawing, you can also use the font of the system itself
        self.font_name = pg.font.match_font(FONT_NAME)
        
    # draw text
    def draw_text(self, text, size, color, x, y):
        font = pg.font.Font(self.font_name, size) # set font and size
        text_surface = font.render(text, True, color) # set color
        text_rect = text_surface.get_rect() Get the font object
        text_rect.midtop = (x, y) # define position
        self.screen.blit(text_surface, text_rect) Draw a font on the screen
Copy the code

Detailed comments are given in the code and will not be repeated.

Add the above code, run the game, there will be corresponding points effect

The player death

If the player’s block is outside the bounds of the gamebox, the player dies. Implement this logic into the Update () method of the Game class

#main.py/Game

    def update(self):
        # Death - The bottom of the player is larger than the height of the game frame
        if self.player.rect.bottom > HEIGHT:
            for sprite in self.all_sprites:
                sprite.rect.y -= max(self.player.vel.y, 10)
                # Element bottom less than 0 - indicates outside the gamebox, remove it
                if sprite.rect.bottom < 0:
                    sprite.kill()
Copy the code

At the beginning, determine whether the bottom of the player’s object block is larger than the height of the game frame. If it is, the player is already at the bottom of the game frame, and some of it is already outside the game frame. At this point, the player dies and the game ends.

Draw the game start screen

Do you remember the overall structure given in section 2, which includes the show_start_screen() and show_go_screen() methods, because the overall running logic is as follows:

g = Game()
g.show_start_screen() # Logic that will be implemented before the game starts
while g.running:
    g.new()
    g.show_go_screen() # Logic that will be executed at the end of a round

pg.quit()
Copy the code

The show_start_screen() method can draw the game’s start screen logic as follows:

# main.py/Game

    # The hook function to start the game
    def show_start_screen(self):
        self.screen.fill(BGCOLOR) # Fill color
        self.draw_text(TITLE, 48, WHITE, WIDTH / 2, HEIGHT / 4)
        # draw text
        self.draw_text("Left and right button move, space bar jump".22, WHITE, WIDTH / 2, HEIGHT / 2)
        self.draw_text("Press any key to start the game".22, WHITE, WIDTH / 2, HEIGHT * 3 / 4)
        # Canvas flip
        pg.display.flip()
        self.wait_for_key() # Wait for the user to hit the position in the keyboard
Copy the code

In the show_start_screen() method, first fill the entire background color, and then call the draw_text() method to draw the text, which cannot be displayed in Chinese. In pyGame, to display Chinese, you need to specify the corresponding system font, such as “Song Style”, “bold”, etc. Finally, the wait_for_key() method is called to wait, with the following logic:

# main.py/Game

def wait_for_key(self):
        waiting = True
        while waiting:
            self.clock.tick(FPS)
            for event in pg.event.get():
                if event.type == pg.QUIT: Click exit to end the waiting loop
                    waiting = False
                    self.running = False
                if event.type == pg.KEYUP: # Press the keyboard to end the waiting loop
                    waiting = False
Copy the code

The logic of the wait_for_key() method is an infinite loop that can only be exited by clicking the close button or any key on the keyboard.

After exiting the loop, you can enter the real game loop and start the game.

At the end

In this section, we implemented the scoring logic, the death logic, and the simple welcome screen logic at launch.

Due to space, the complete code is not given in this article, but for your convenience, I have uploaded the corresponding code to Github

Github.com/ayuLiao/jum…

If the article is helpful or interesting to you, click “Watching” to support the author in a wave.