Skip to main content
 首页 » 编程设计

python之我不明白如何在 FallDown 游戏中在 pygame 中生成多个平台

2024年09月07日10开发

我最近开始开发一款名为 falldown 的游戏,并完成了控件、开始屏幕和球的制作,但我在随机生成平台方面遇到困难。我已经能够临时绘制一个随机平台,但为了给人一种特定平台正在向上移动的错觉,我需要再次绘制相同的平台,但我不知道该怎么做。

我研究了很多并找到了这两个代码示例:
https://github.com/Beavotropper2/FallDown
https://sourceforge.net/projects/falldown/
但我真的不明白他们是如何解决这个问题的。你能帮我理解如何创建像跌倒一样向上移动的多个平台吗?

请您参考如下方法:

我将按如下方式实现平台:Platform 类只需要包含一个图像 (pygame.Surface) 和一个 pygame.Rect 用于存储位置(也可用于碰撞检测)。

在 update 方法中,我只更改 self.rect.y 位置来移动 Sprite ,并在它位于屏幕顶部上方时将其删除。

为了存储平台 Sprite ,我使用了一个 pygame.sprite.Group,它允许我通过两个方法调用来更新和 blit 所有包含的 Sprite 。

Sprite 在 add_platforms 函数中分别添加到组中,我首先调用 random.randint 获取平台数量,然后传递它和 range(0, 800, 100) 到 random.sample获得 4-7 个随机 x 坐标。然后你可以遍历这个列表并将坐标传递给 Sprite 实例。

我使用 pygame.time.set_timer函数每两秒生成一个自定义事件 (ADD_PLATFORM_EVENT),您可以在事件循环中处理该事件以调用 add_platforms 函数。

import random 
import pygame 
 
 
pygame.init() 
game_display = pygame.display.set_mode((800, 600)) 
clock = pygame.time.Clock() 
PLATFORM_IMAGE = pygame.Surface((100, 20)) 
PLATFORM_IMAGE.fill((30, 220, 150)) 
# This event is needed for the timer and to add platforms. 
ADD_PLATFORM_EVENT = pygame.USEREVENT+1 
 
 
class Platform(pygame.sprite.Sprite): 
 
    def __init__(self, x, y, platform_image): 
        pygame.sprite.Sprite.__init__(self) 
        self.image = platform_image 
        self.rect = self.image.get_rect(topleft=(x, y)) 
 
    def update(self): 
        self.rect.y -= 1 
 
        if self.rect.y < -50: 
            self.kill() 
 
 
def add_platforms(group): 
    """Add platforms to a sprite group. 
 
    Choose 4-7 random x-positions, create the Platform sprites (pass 
    the x- and y-positions) and add them to the passed group. 
    """ 
    platform_count = random.randint(4, 7) 
    positions = random.sample(range(0, 800, 100), platform_count) 
    y = game_display.get_height() 
    for x in positions: 
        group.add(Platform(x, y, PLATFORM_IMAGE)) 
 
 
def main_game(): 
    # This will add a `ADD_PLATFORM_EVENT` to the event queue after two seconds. 
    pygame.time.set_timer(ADD_PLATFORM_EVENT, 2000) 
    platform_group = pygame.sprite.Group() 
    add_platforms(platform_group) 
 
    game_exit = False 
 
    while not game_exit: 
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT: 
                game_exit = True 
            # Call the `add_platforms` function if 
            # an `ADD_PLATFORM_EVENT` occurs. 
            elif event.type == ADD_PLATFORM_EVENT: 
                add_platforms(platform_group) 
 
        # Call the update methods of all contained sprites. 
        platform_group.update() 
 
        game_display.fill((30, 30, 30)) 
        # Blit the images of all sprites at their rects. 
        platform_group.draw(game_display) 
 
        pygame.display.flip() 
        clock.tick(60) 
 
main_game() 
pygame.quit()