Pygame+python:1代码的一部分包含Pygame.wait,而其余代码运行

Pygame+python:1代码的一部分包含Pygame.wait,而其余代码运行,python,pygame,Python,Pygame,我正在做一个游戏,你必须把移动的物体从一个地方带到另一个地方。我可以将我的角色移动到需要放置东西的区域。我希望玩家在区域中等待5秒钟,然后再将对象放置在那里,但是,如果我这样做,如果你决定不将对象放置在区域中,你将无法再移动,因为整个脚本将暂停 有没有办法让脚本的一部分在其余部分运行时等待?线程示例: from threading import Thread def threaded_function(arg): # check if it's been 5 seconds or us

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


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

线程示例:

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

每个游戏都需要一个时钟来保持游戏循环同步并控制计时。Pygame有一个带有方法的对象。下面是一个游戏循环的样子,以获得您想要的行为,而不是完整的代码,只是一个示例

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.

你考虑过创建一个线程吗?@JakeP那是什么?这就是您同时运行东西的方式吗?允许您同时运行代码。信息thread.join查看代码链接将使主线程等待启动的线程完成后才能继续运行。@JakeP好的,你能用一个简单的例子来回答在这种情况下如何执行吗?然后你会得到声誉当我试图想出一个逻辑解决方案时,我想到了第二个解决方案,但不知道如何执行XD对于helppygame,您可以使用它来代替time@furas是的,只要将5改为5000就可以了millisecond@JakeP在您的线程示例中,它表示检查是否为5秒。我可以使用pygame.wait5然后删除对象吗?如果我相信,如果在线程函数中使用sleep5,它将不会影响主线程,我不确定pygame.wait5的行为方式我希望在waiting@Glitchd然后只需要删除if语句