2012-06-08 3 views
6

기본적으로 텍스트 기반 전투 게임 인 단일 플레이어 머드를 제작하고 있습니다. 네트워크에 연결되어 있지 않습니다.비동기 적으로 사용자 입력을 가져 와서 파이썬의 이벤트 루프에 전달하십시오.

사용자 명령을 수집하여이를 내 이벤트 루프에 비동기 적으로 전달하는 방법을 이해하지 못합니다. 플레이어는 게임 이벤트가 시작되면 언제든지 명령을 입력 할 수 있어야합니다. 따라서 raw_input을 사용하여 프로세스를 일시 중지하면 작동하지 않습니다. select.select와 thread를 사용할 필요가 있다고 생각합니다.

아래 예제에서 나는 명령을 받고 싶은 곳의 userInputListener() 모형을 가지고 있는데, 입력이 있으면 명령을 Que에 추가합니다.

이벤트 루프 등이있는 경우 :

from threading import Timer 
import time 

#Main game loop, runs and outputs continuously 
def gameLoop(tickrate): 

    #Asynchronously get some user input and add it to a command que 
    commandQue.append(userInputListener()) 
    curCommand = commandQue(0) 
    commandQue.pop(0) 

    #Evaluate input of current command with regular expressions 
    if re.match('move *', curCommand): 
     movePlayer(curCommand) 
    elif re.match('attack *', curCommand): 
     attackMonster(curCommand) 
    elif re.match('quit', curCommand): 
     runGame.stop() 
    #... etc  

    #Run various game functions... 
    doStuff() 

    #All Done with loop, sleep 
    time.sleep(tickrate) 

#Thread that runs the game loop 
runGame = Timer(0.1, gameLoop(1)) 
runGame.start() 

가 어떻게 거기에 내 사용자 입력을받을 수 있나요을?

간단히 말해서 다른 루프가 동시에 실행되는 동안 사용자 입력을 저장하는 예를 보여줄 수 있습니까? 우리가 멀리 얻을 수 있다면 나머지는 알아낼 수 있습니다.

+0

는 [트위스트 (http://twistedmatrix.com/) 옵션인가요을 – sarnold

+2

자신 만의 롤링보다는 PyGame 또는 curses를 사용하여 입력을 처리 할 수 ​​있습니다. –

+0

멀티 유저 던전을위한 머드가 아닌가요? 어쨌든 @AndrewGorcester에 동의합니다. 휠 재발견을 피하는 것이 더 쉬울 것입니다. –

답변

2

실제로 두 개의 스레드가 필요합니다. 하나는 메인 게임 루프와 관련된 것이고 다른 하나는 사용자 입력을 처리하는 것입니다. 두 사람은 Queue을 통해 통신 할 것입니다.

메인 프로세스가 게임 루프 스레드를 시작한 다음 사용자로부터 텍스트 줄을 가져 와서 큐에 넣을 수 있습니다 (예 : runGame.start()). 다음과 같이 간단 할 수 있습니다 :

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

게임 루프 스레드는 대기열, 인터퍼트에서 텍스트 줄을 "가져오고"실행할 것입니다.

파이썬에는 thread-safe queue implementation (가이드로 사용할 수있는 멀티 스레드 사용을위한 매우 기본적인 예제 포함)이 있습니다.

이러한 종류의 프로젝트에 유용 할 수도있는 간단한 명령 행 인터페터 모듈 (실제적인 개요를 보려면 cmd modulehere)이 있습니다.

1

은 비동기 I here

입력 읽어 파이 게임 하노이 영상 효과를 만들어 중요한 라인은 :

#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() 
관련 문제