python - Pygame + python : 1 part of code has pygame. 等待其余代码运行

标签 python pygame

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


有没有一种方法可以让脚本的一部分在其余部分运行时等待?

最佳答案

每个游戏都需要一个时钟来保持游戏循环同步并控制计时。 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.

关于python - Pygame + python : 1 part of code has pygame. 等待其余代码运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57082649/

相关文章:

Python Pylab 子图错误?

python - 在 Django 2.2 中为 GRAPHENE 设置 'SCHEMA' 导入模块时出现问题

python - Pygame:使用多个 channel 设置绝对音量

python - PyGame 局部变量

python - PyGame 图像保存颜色扭曲

python - 使用 Pandas 从类似于 json 的列表中检索值

python - 批处理主要 VS 时间主要 LSTM

python - 如何从 os.walk 过滤文件(已知类型)?

python - Pygame OpenGL 3D 立方体滞后

python - 俄罗斯方 block 从 block 生成彩色形状