python中的文本RPG

时间:2012-08-03 02:07:37

标签: python

main.py

import engine
engine.objects['key'] = "It's a key"
engine.main()

engine.py

# inventory = []

objects = {

}

def main():
    while True:
        choice = raw_input(">>: ")
        command, obj = choice.split()
        if command == 'examine':
            if obj in objects:
                print objects[obj]
            else:
                print 'joking right?'
        else:
            print 'joking right?'

当我输入没有第二个字的“检查”时,参数,它会给我一个错误。

>>: asdf
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    engine.main()
  File "C:\Users\Patrick\Documents\Programming\Game engine test\engine.py", line
 11, in main
    command, obj = choice.split()
ValueError: need more than 1 value to unpack
Press any key to continue . . .

我理解为什么,但我该如何解决?

2 个答案:

答案 0 :(得分:3)

因此我们可以从问题中消除raw_input(),并将其归结为以下几行:

choice = 'examine'
result = choice.split()      # result == ['examine']
command, obj = result        # Boom.

split()的返回值是一个列表。当你只有一个单词(用空格分隔)时,比如&#34;检查&#34;,列表只包含一个单词。

然后,当您尝试将该列表解压缩到commandobj时,python说,&#34;我无法做到这一点。你期待两个条目,但我只有一个。&#34;

您需要做的是执行一些中间检查:

args = choice.split()
if len(args) < 2:
    print 'Invalid command.'
    continue
command, obj = args
# ...

答案 1 :(得分:0)

args = choice.split()
command = args[0]
#Branch according to command here
#Most likely you will want to separate them into functions
if command == 'examine':
    if len(args) < 2:
       print 'Missing argument'
    else:
       obj = args[1]
       if obj in objects:
           print objects[obj]
       else:
           print 'joking right?'
else:
    print 'joking right?'

您也可以查看cmd module in the python standard library。您基本上可以使用do_<MYCOMMANDNAME>函数创建一个对象,它将发出命令提示符并将第一个单词看作command并查找相应的do_command函数以执行其余的争论。