【问题标题】:Pygame + python: 1 part of code has pygame.wait while rest of code runsPygame + python:1 部分代码有 pygame.wait 而其余代码运行
【发布时间】:2019-08-18 17:16:24
【问题描述】:

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


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

【问题讨论】:

  • 你考虑过创建一个话题吗?
  • @JakeP 那是什么?这就是你同时处理事情的方式吗?
  • 允许您同时运行代码。信息herethread.join()(代码见链接)将使主线程等待,直到启动的线程完成才能继续运行。
  • @JakeP 好的,你能用一个简短的例子来回答在这种情况下如何做吗?
  • 那么就获得声望

标签: python pygame


【解决方案1】:

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

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.

【讨论】:

  • 我希望能够在等待时移动
  • @Glitchd 那么你只需要删除if语句
【解决方案2】:

线程示例:

from threading import Thread

def threaded_function(arg):
    # check if it's been 5 seconds or user has left

thread = Thread(target = threaded_function, args = (10, ))
if user is in zone:
    thread.start()
# continue normal code

另一种可能的解决方案是检查用户进入该区域的时间,并不断检查当前时间是否为 5 秒

时间检查示例:

import time

entered = false
while true:
    if user has entered zone:
        entered_time = time.time()
        entered = true
    if entered and time.time() - entered_time >= 5: # i believe time.time() is in seconds not milliseconds
        # it has been 5 seconds
    if user has left:
        entered=false
    #other game code

【讨论】:

  • 当我试图想一个合乎逻辑的解决方案时,我在想第二个,但不知道该怎么做XD ty寻求帮助
  • pygame 有 pygame.time.get_ticks,你可以用它来代替 time
  • @furas 是的,只需将 5 更改为 5000 以转换为毫秒,就可以实现同样的效果
  • @JakeP 在你的线程示例中它说检查它是否已经 5 秒。我可以使用 pygame.wait(5) 然后删除对象吗?
  • 如果你相信的话,如果你在线程函数中使用sleep(5) 它不会影响主线程,我不确定pygame.wait(5) 的行为如何
猜你喜欢
  • 2017-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
相关资源
最近更新 更多