msy*_*ems 8 python input event-loop mud
我正在建立一个单人游戏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, gameLoop(1))
runGame.start()
Run Code Online (Sandbox Code Playgroud)
如何在那里获取用户输入?
或者更简单,任何人都可以向我展示存储用户输入的任何示例,而另一个循环同时运行吗?如果我们能够做到这一点,我可以弄清楚剩下的.
您确实需要两个线程。一个负责主游戏循环,另一个负责处理用户输入。两者将通过Queue进行通信。
您可以让主进程启动游戏循环线程,然后让它从用户那里获取一行文本并将其“放入”队列中(即在 runGame.start() 之后)。这可以很简单:
while not gameFinished:
myQueue.put(raw_input()).
Run Code Online (Sandbox Code Playgroud)
游戏循环线程只是从队列中“获取”一行文本,解释并执行它。
Python 有一个线程安全的队列实现可供您使用(包括一个非常基本的多线程使用示例,您可以将其用作指南)。
还有一个简单的命令行解释器模块(cmd 模块,这里有一个很好的实用概述),它对于此类项目也可能有用。