你需要的是一个游戏主循环:
while game.is_running:
command = get_user_input()
user_do(command)
update_world()
这将重复三行代码的while
循环内,只要game.is_running
是True
。首先,你得到用户输入。接下来,你采取行动。最后,你执行游戏需要的任何其他更新,例如移动或产生怪物。此时,它循环回来并要求用户输入其他命令。
更新:这里是一个工作示例:
# In commands.py:
def bag():
print 'bag'
def other():
print 'other'
def unrecognized():
print 'unknown command'
# In main.py:
import commands
def user_input():
print 'a question'
return raw_input('>')
def user_do(command):
# get the matching command out of commands, or pass back
# the unrecognized function if it's not found
action = getattr(commands, command, commands.unrecognized)
action()
is_running = True
while is_running:
command = user_input()
if command == 'quit':
is_running = False
else:
user_do(command)
在这个例子中,我已经被骗和我依靠用户输入的命令是相同的函数的名称被调用。在user_do
中,getattr
调用将用户输入的字符串与command
模块的内容进行比较,如果存在相同名称的函数,则返回相同的函数;如果不存在,则返回后备功能unrecognized
。 action
现在将保存命令功能或unrecognized
。
如果你不想让你的用户命令,以便紧密结合实际函数本身,你可以使用一个dict
作为一个分支结构(或派遣),而不是有很多的if/elif/else
声明:
# Modified main.py
import commands
COMMAND_DISPATCH = {
'bag': commands.bag,
'sack': commands.bag,
'other': commands.other,
# ...
}
# ...
def user_do(command):
action = COMMAND_DISPATCH.get(command, commands.unrecognized)
action()
在本例中,我们不是在commands
模块中查找函数,而是在COMMAND_DISPATCH
中查找它们。
还有一点建议:不久之后,您会希望将用户输入解析为不止一个命令。对于这个例子,我们假设你想能够接受“command ...”形式的输入。您可以扩展user_input
函数来照顾这:
def user_input():
print 'a question'
user_input = raw_input('>').split(' ')
command = user_input[0]
arguments = user_input[1:]
return command, arguments
所以,如果你输入“富酒吧巴兹”,这将返回元组('foo', ['bar', 'baz'])
。接下来我们更新主循环来处理参数。
while is_running:
# use tuple unpacking to split into command, argument pairs
command, arguments = user_input()
if command == 'quit':
is_running = False
else:
user_do(command, arguments)
然后确保我们将它们传递到命令:
def user_do(command, arguments):
action = COMMAND_DISPATCH.get(command, commands.unrecognized)
action(arguments)
最后,我们修改命令接受并处理这些参数:
def bag(arguments):
for argument in arguments:
print 'bagged ', argument
对于文字冒险,你会想要一个更实质性的解析器,它可以处理command object
,command object preposition subject
,甚至可能command adjective object ...
。
大声笑看冒险模块...看看它的来源...也许 –
对不起,我不知道你说什么。谨慎澄清? –