首页 > 解决方案 > Pygame + python:1 部分代码有 pygame.wait 而其余代码运行

问题描述

我正在制作一个游戏,你必须将移动物体从一个地方带到另一个地方。我可以将我的角色移动到我需要放置东西的区域。我希望玩家在该区域等待 5 秒钟,然后将对象放置在那里,但是,如果我这样做,如果您决定不想将对象放置在该区域中,您将无法再移动,因为整个脚本将暂停。


有没有办法让脚本的一部分在其余部分运行时等待?

标签: pythonpygame

解决方案


每个游戏都需要一个时钟来保持游戏循环同步并控制时间。Pygame 有一个pygame.time.Clock带有tick()方法的对象。这是一个游戏循环可能看起来像你想要的行为(不是完整的代码,只是一个例子)。

clock = pygame.time.Clock()

wait_time = 0
have_visited_zone = False
waiting_for_block_placement = False

# Game loop.
while True:

    # Get the time (in milliseconds) since last loop (and lock framerate at 60 FPS).
    dt = clock.tick(60)

    # Move the player.
    player.position += player.velocity * dt

    # Player enters the zone for the first time.
    if player.rect.colliderect(zone.rect) and not have_visited_zone:
        have_visited_zone = True            # Remember to set this to True!
        waiting_for_block_placement = True  # We're now waiting.
        wait_time = 5000                    # We'll wait 5000 milliseconds.

    # Check if we're currently waiting for the block-placing action.
    if waiting_for_block_placement:
        wait_time -= dt                          # Decrease the time if we're waiting.
        if wait_time <= 0:                       # If the time has gone to 0 (or past 0)
            waiting_for_block_placement = False  # stop waiting
            place_block()                        # and place the block.

推荐阅读