python并行输入和管道输出

时间:2017-07-06 01:23:12

标签: python

我想建立一个同时接受输入并将输出打印为研究项目的python游戏

游戏:

给用户一个句子。计时器倒计时(显示计数),同时用户尝试在输出中向后写句子。

如果输入正确,则会延长计时器 如果计时器用完或输入不正确,游戏结束

到目前为止:

我一直在浏览我能找到的不同模块(子进程,并行python,多处理),但是已经遇到了各个问题。我得到的最远的是concurrent futures module。唯一的问题是丢失的情况不会立即更新(即,您可能会用完时间而且它不会告诉您您已经丢失)

我发现我的方式有点hacky,我认为multiprocessing将是最好的方式,但我很早就陷入了对定时器和输入函数的异步调用

from concurrent.futures import ThreadPoolExecutor
import time

def timer(n, pipe):
    count = n
    # count down
    while count > 0 and not pipe.flag_lose:
        # add more time if flag has been raised
        if pipe.can_has_additional_time():
            count += 10

        count -= 1
        print(' '*10, end='\r') # hacky way to clear line when going from double to single digits
        print(count, end='\r')
        time.sleep(1)
    print()

def get_input(pipe):
    while not pipe.flag_lose:
        sentence = "I never should have started this project"
        print("Quick! Print this backwards:", sentence)
        answer = input("Your Answer: ")

        # validate
        if answer == sentence[::-1]:
            pipe.flag_additional_time = True
        else:
            print("Wrong!")
            pipe.flag_lose = True

class HackedPipeline:
    def __init__(self):
        # end game when this is True
        self.flag_lose = False
        # give more time when this is True
        self.flag_additional_time = False

    def can_has_additional_time(self):
        '''
        giving this flag an accessor because it needs to reset
        '''
        if self.flag_additional_time:
            self.flag_additional_time = False
            return True
        return False # NO!

with ThreadPoolExecutor(max_workers=2) as executor:
    hacked_pipeline = HackedPipeline()
    input_task = executor.submit(get_input, hacked_pipeline)
    output_task = executor.submit(timer, n=10, pipe=hacked_pipeline)

P.S。对于c + p目的,答案是tcejorp siht detrats evah dluohs reven I

0 个答案:

没有答案