是否可以只让部分代码等待?

问题描述 投票:0回答:1

我想延迟我的代码,但我不想延迟我的所有代码,只是这部分。可以这样做吗?像

time
os
等模块只能选择在使用后延迟 all 代码。

这部分代码处于

for
循环中:

def EnemyMove():
    for i in range(29):
        # I want the delay to be here
        if (i <= 4):
          canvas.move(Enemy, 29, 0)  
        elif (i <= 11):
            canvas.move(Enemy, 0, -28.5)
        elif (i <= 17):
            canvas.move(Enemy, 29, 0)
        elif (i <= 24):
            canvas.move(Enemy, 0, 28.5)
        elif (i <= 29):
            canvas.move(Enemy, 29, 0)

我认为按照我的想法是不可能的,但也许有更好的方法。

python sleep
1个回答
0
投票

正如您所提到的,您不同意暂时阻塞主程序/线程,您可以使用

asyncio

import asyncio

# Simulated canvas and enemy for demonstration
class Canvas:
    def move(self, enemy, x, y):
        print(f"Moving {enemy} by ({x}, {y})")


canvas = Canvas()
Enemy = "Enemy"

async def move_enemy(i):
    if (i <= 4):
        canvas.move(Enemy, 29, 0)  
    elif (i <= 11):
        canvas.move(Enemy, 0, -28.5)
    elif (i <= 17):
        canvas.move(Enemy, 29, 0)
    elif (i <= 24):
        canvas.move(Enemy, 0, 28.5)
    elif (i <= 29):
        canvas.move(Enemy, 29, 0)

async def EnemyMove():
    for i in range(29):
        await move_enemy(i)  # Move the enemy
        await asyncio.sleep(0.5)  # Non-blocking delay

async def main():
    await EnemyMove()

# Run the asynchronous main function
if __name__ == "__main__":
    asyncio.run(main())
© www.soinside.com 2019 - 2024. All rights reserved.