如何在后台循环运行

时间:2019-04-01 16:56:28

标签: python-3.x while-loop

我正在尝试编写回合制游戏,其中某些事情发生不止一个回合。我发现可以在函数中放入一个while循环,该循环使动作可以轮流进行。这是我的测试:

#This function is supposed to 'work' after 3 turns
def action(current_turn):
    while global_turn - current_turn != 3:
        pass
    test = "works"

test = "doesn't work"
game =True
global_turn = 0
while game:
    global_turn += 1
    print(f'\nThis is turn #{global_turn}\n')
    user_input = input('Do [1]yes [2]no')
    if user_input == '2':
        pass
    elif user_input == '1':
        action(global_turn)

我以为这将永远打印“ This is turn#{global_turn}”,即使我调用了该函数,但它只是坐在那里。有什么办法可以使while循环继续进行,同时还能进行外部循环?

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

#This function is supposed to 'work' after 3 turns
def action(current_turn, action_turn):
    if global_turn != action_turn:
        return
    print('action!')

game = True
global_turn = 0
action_turn = None
while game:
    global_turn += 1
    print(f'\nThis is turn #{global_turn}\n')
    user_input = input('Do [1]yes [2]no')
    if user_input == '2':
        pass
    elif user_input == '1':
        action_turn = global_turn + 3
    action(global_turn, action_turn)

注意:这实际上不会在后台运行while循环。在您的示例中,这似乎没有必要。但是,如果您的游戏变得更加复杂,则可能需要研究

在后台运行。


编辑

asyncio版本:

import asyncio


class Game:
    def __init__(self):
        self.game_running = True
        self.global_turn = 0
        self.turn_started = asyncio.Event()
        self.turn_ended = asyncio.Event()

    async def action(self, wait_turns):
        while wait_turns > 0:
            await self.turn_ended.wait()
            await self.turn_started.wait()
            wait_turns -= 1
        print('action!')


    async def main(self):
        while self.game_running:
            self.global_turn += 1
            print(f'\nThis is turn #{self.global_turn}\n')
            self.turn_ended.clear()
            self.turn_started.set()
            await asyncio.sleep(0)  # yield control to other tasks
            user_input = input('Do [1]yes [2]no')
            if user_input == '2':
                pass
            elif user_input == '1':
                asyncio.ensure_future(self.action(3))
            self.turn_started.clear()
            self.turn_ended.set()
            await asyncio.sleep(0)  # yield control to other tasks


if __name__ == '__main__':
    game = Game();
    loop = asyncio.get_event_loop()
    loop.run_until_complete(game.main())

说明:

  • 当用户输入1时,action协程会使用asyncio.ensure_future在“后台”安排
  • 每转两个,将设置两个asyncio.Event信号。一个代表转弯,一个代表转弯。
  • action协程在打印“动作”之前等待定义的转弯次数开始和结束
  • action协程可以在后台运行多次,每次向下计数匝数直至变为活动状态。
  • 要继续运行await asyncio.sleep(0)协程,需要
  • action
  • 如果在main功能等待用户输入时需要激活操作,则可以使用aioconsole.ainput

    from aioconsole import ainput
    
    async def main(self):
        [...]
        user_input = await ainput("Do [1]yes [2]no")
        [...]