你需要的是一個遊戲主循環:
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 ...
。
大聲笑看冒險模塊...看看它的來源...也許 –
對不起,我不知道你說什麼。謹慎澄清? –