我正在建立一个单人游戏MUD,它基本上是一个基于文本的战斗游戏.它没有联网.
我不明白如何收集用户命令并将它们异步传递到我的事件循环中.当游戏事件发生时,玩家需要能够随时输入命令.因此,使用raw_input暂停该过程将不起作用.我想我需要做一些像select.select和使用线程的东西.
在下面的示例中,我有一个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, …Run Code Online (Sandbox Code Playgroud)