Ape Creation Essay|Program Ape Rides the Wind and Waves Python Pygame Original Mini Game [source code + analysis]

        It is the first time to participate in the ape creation essay writing activity, and there will definitely be a big wave! Σ(⊙▽⊙"a!!!

        Before the end of summer, let's surf again, and feel the assiduous spirit of programmers under the summer sun, and nowhere to put the foundation.

        I learned a little bit of Pygame skills recently, and I feel a little over the top. I created a game of "Program Ape Riding the Wind and Waves" with a wave of operations. I hope everyone likes it.

1. Game display

        The so-called: start with a picture, and it all depends on editing . Put pictures and animations first.

        The gameplay is very simple, press the space monkey ↑ to jump up, avoid the huge wave attack, the longer the time, the higher the score, and the game ends when the huge wave is encountered .

game display screen

 2. Game logic

        For the sake of simplicity, it is not explained here in terms of code structure. The game can be roughly divided into four parts, namely:

        (1) Game background

                1. Sky background. The white sky dotted with multiple blue horizontal lines uses Python code to make the sky background move continuously from right to left , thereby creating the illusion that the monkey is moving to the right .

sky background

Background sprite code:

class Background(GameSprite):
    """游戏背景精灵"""
    def __init__(self,image_path, is_alt=False):
        # 1.调用父类方法实现精灵的创建(image/rect/speed)
        super().__init__(image_path)
        # 2.判断是否是交替图像,如果是,需要设置初始位置
        if is_alt is True:
            self.rect.x = self.rect.width
        else:
            self.rect.x = 0

    def update(self):
        # 1.调用父类的方法实现
        super().update()
        # 2.判断是否移出屏幕,如果移出屏幕,将图像设置到屏幕的上方
        if self.rect.x <= -SCREEN_RECT.width:
            self.rect.x = self.rect.width

                2. Ocean background. The ocean background uses two background images of the inner ocean and the outer ocean , and at the same time makes their moving speed inconsistent with the sky background , and the moving speed between the two inner and outer oceans is also inconsistent , thus creating a three-dimensional sense of the game. , so that 2D games can increase the three-dimensional feeling of 3D.

    def __create_sprites(self):
        """创建背景精灵和精灵组"""

        # 天空背景
        bg1 = Background("./images/background_16_9.png", False)
        bg2 = Background("./images/background_16_9.png", True)
        self.back_group = pygame.sprite.Group(bg1, bg2)

        # 内层海洋背景
        sea_bg_1 = Background("./images/sea_bg_1_16_9.png", False)
        sea_bg_2 = Background("./images/sea_bg_1_16_9.png", True)
        #移动速度
        sea_bg_1.speed = 2
        sea_bg_2.speed = 2
        sea_bg_1.rect.bottom = SCREEN_RECT.height
        sea_bg_2.rect.bottom = SCREEN_RECT.height
        self.sea_bg_ground_1 = pygame.sprite.Group(sea_bg_1, sea_bg_2)

        # 外层海洋背景
        sea_bg_3 = Background("./images/sea_bg_2_16_9.png", False)
        sea_bg_4 = Background("./images/sea_bg_2_16_9.png", True)
        # 移动速度
        sea_bg_3.speed = 3
        sea_bg_4.speed = 3
        sea_bg_3.rect.bottom = SCREEN_RECT.height
        sea_bg_4.rect.bottom = SCREEN_RECT.height
        self.sea_bg_ground_2 = pygame.sprite.Group(sea_bg_3, sea_bg_4)

        (2) Monkey game sprite (player)

                1. Make the monkey sprite jump up and down. Use Python to monitor the keyboard time. When the keyboard space bar is pressed, give the monkey sprite an upward (negative value on the y-axis) speed, and when the keyboard space bar is not pressed, give the monkey sprite a downward (positive value on the y-axis) speed. , so that the monkey sprite can jump up and down.

The main code is as follows:

        # 使用键盘提供的方法获取键盘按键 - 按键元组
        keys_pressed = pygame.key.get_pressed()
        # 判断用户按下键盘空格键
        if keys_pressed[pygame.K_SPACE]:
            # 跳起
            self.man.speed = -10
        else:
            # 下降
            self.man.speed = 10

                2. Keep the monkeys from flying out of the game screen. Use Python code to monitor the monkey's position. When the monkey's y-axis value is less than 0 (touching the top edge of the screen), the y-axis value is reset to 0, and when the monkey's y-axis value is greater than 360 (touching the bottom edge of the screen) y The axis is reset to 360.

The main code is as follows: 

    def update(self):
        # 猴子在水平方向移动
        self.rect.y += self.speed
        # 控制猴子不能移出屏幕
        if self.rect.y < 0:
            self.rect.y = 0
        elif self.rect.bottom > self.bottom_to_ground:
            self.rect.bottom = self.bottom_to_ground

                3. Let the monkeys be placed between the inner ocean and the outer ocean to increase the sense of layering in the game. When calling the Pygame refresh interface function, first call the inner ocean refresh function, then call the monkey sprite refresh function, and finally call the outer ocean refresh function, which can achieve the desired effect.

        

The main code is as follows:

    def __update_sprites(self):
        """刷新各个精灵组"""
        # 先刷新内层海洋
        self.sea_bg_ground_1.update()
        self.sea_bg_ground_1.draw(self.screen)
        # 再刷新猴子
        self.man_group.update()
        self.man_group.draw(self.screen)
        # 最后刷新外层海洋
        self.sea_bg_ground_2.update()
        self.sea_bg_ground_2.draw(self.screen)

        (3) Julang game energy (enemy)

                1. A huge wave is generated every period of time. The huge wave appears from right to left, and the speed is fast or slow. First inherit pygame.sprite.Sprite to create a giant wave sprite class with attributes such as speed.

class Wave(GameSprite):
    """海浪精灵"""

    def __init__(self):
        # 1.调用父类方法,创建海浪精灵,同时指定海浪图片
        super().__init__("./images/wave.png")

        # 2.指定海浪的初始随机速度
        self.speed = random.randint(2, 4)

        # 3.指定海浪的初始随机位置
        self.rect.x = SCREEN_RECT.width
        self.rect.bottom = SCREEN_RECT.height

        Then create the Pygame custom event CREATE_WAVE_EVENT.

# 创建海浪的定时器事件常量
CREATE_WAVE_EVENT = pygame.USEREVENT+1

        At the same time, use pygame.time.set_timer to create a timer, which fires the event every 3 seconds. 

# 4.设置定时器事件——每3秒创建一次海浪
pygame.time.set_timer(CREATE_WAVE_EVENT, 3000)

        Finally, if the event listener handler finds the event , it creates a giant wave sprite and joins the sprite group.

elif event.type == CREATE_WAVE_EVENT:
    # 创建海浪精灵
    wave = Wave()
    # 将海浪精灵添加到海浪精灵组
    self.wave_group.add(wave)

                2. The game ends after the giant waves collide with the monkeys. Each frame uses def __check_collide(self) to detect whether the monkey sprite and the giant wave sprite collide. If there is a collision , the game ends this round.

 The collision detection code is as follows:

    def __check_collide(self):
        # 1.撞到海浪
        waves = pygame.sprite.spritecollide(self.man, self.wave_group, True)
        # 2.判断碰撞列表长度
        if len(waves) > 0:
            # 该回合游戏结束,显示菜单
            self.menu_sprite.display = True
            self.game_state = 0

                3. After the giant wave moves out of the left screen, delete the giant wave. To save memory, the wave sprite should be deleted when an untouched wave moves from right to left off the left edge of the screen. The deletion operation can be implemented by judging whether the right side of the giant wave is smaller than the left edge of the screen every frame .

        (4) Timer and scoring

                1. Custom timer events, each 1 second number minus 1 . The default play time of the game is 30 seconds. After the game starts, the countdown starts, and the numbers 30, 29, and 28 are updated in the upper right corner. Similar to creating a huge wave, you can first create a countdown event, then use a timer to trigger every second, and finally perform the refresh number operation in the listener event function.

        

The main code is as follows:

        Create custom event CREATE_I_EVENT .

# 创建游戏倒计时的定时器常量
CREATE_I_EVENT = pygame.USEREVENT+2

         At the same time, use pygame.time.set_timer to create a timer, which triggers the event every 1 second. 

# 5.设置定时器事件——倒计时每1秒触发一次
pygame.time.set_timer(CREATE_I_EVENT, 1000)

         Finally, if the event listener handler finds the event , the countdown is decremented by 1 .

elif event.type == CREATE_I_EVENT:
    # 倒计时减1秒
    self.countdown_sprite.start_time = self.countdown_sprite.start_time - 1

                2. Add ten points for every second. It's the same as the countdown, but here it adds ten points every second.

elif event.type == CREATE_I_EVENT:
    # 每过1秒加十分
    self.score_sprite.score = self.score_sprite.score + 10

               3. When the game restarts, reset the timer and score. If the user clicks to restart the game, reset the relevant properties to restart the game.

 

3. The complete source code of the game

        The game is finally done! Nima! I have to program and write articles again. Tired! o(╥﹏╥)o, code text is not easy, please support me a lot, Thanks♪(・ω・)ノ, we will make another wave on this basis to enrich the gameplay.

        Finally, paste the complete source code and materials (some materials come from the Internet, if you have any problems, please contact the blogger to deal with it, thank you!) It can only be packaged and downloaded.

        https://download.csdn.net/download/qq616491978/86512478

Guess you like

Origin blog.csdn.net/qq616491978/article/details/126769079