Grab user input asynchronously and pass to an Event loop in python

青春壹個敷衍的年華 提交于 2019-11-29 10:03:33

You will indeed need two threads. One to be concerned with the main game loop and one to handle user input. The two would be communicating through a Queue.

You can have your main process start the game loop thread and then have it obtaining a line of text from the user and "puting" it to the queue (i.e following runGame.start()). This can be as simple as:

while not gameFinished:
    myQueue.put(raw_input()). 

The game loop thread will simply be "geting" a line of text from the queue, interpert and execute it.

Python has a thread-safe queue implementation which you can use (including a very basic example for multi-threaded usage that you can use as a guide).

There's also a simple command line interperter module (the cmd module and here for a good practical overview) which might also be useful for this kind of project.

I made a pygame hanoi-visualiser that reads input asynchronously here

The important lines are:

#creates an input buffer for stdin 
bufferLock=threading.Lock()
inputBuffer=[]

class StdinParser(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        global inputBuffer
        running = True
        while running:
            try:
                instruction=raw_input()
                bufferLock.acquire()
                if inputBuffer == False:
                    running = False
                else:
                    inputBuffer.insert(0,instruction)
                bufferLock.release()
            except EOFError:
                running = False
        pyglet.app.exit()

def check_for_input(dt):
    bufferLock.acquire()
    if len(inputBuffer)>0:
        instruction = inputBuffer.pop()
        parseLine(instruction,board)
    bufferLock.release()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!