在Text-adventure中匹配用户选择的问题。

时间:2013-02-03 17:21:55

标签: python python-2.7 text-based adventure

我目前正在使用python进行简单的文本冒险。基本上我希望randint选择1或2然后分配给right_wire,然后raw_input为wire_choice,然后匹配2以提供所需的结果。我相信你们可以弄清楚我到底想做什么。我在这附近还是离开了?谢谢!

    right_wire = randint(1, 2)

    wrong_wire = 0

    if right_wire == 1:
        wrong_wire = 2
    elif right_wire == 2:
        wrong_wire = 1
    else:
        print "ERROR"

    while True:
        print "Which wire do you pull?"
        print
        print "1. The red one."
        print "2. The blue one."
        print
        wire_choice = raw_input('*>>*')

        if wire_choice == 1 and right_wire == 1:
            print "**BOMB DEFUSED**"
            return 'engineering2'
        elif wire_choice == 2 and right_wire == 2:
            print "**BOMB DEFUSED**"
            return 'engineering2'
        elif wire_choice == 1 and right_wire == 2:
            print "**FAILED**"
            return 'death'
        elif wire_choice == 2 and right_wire ==1:
            print "**FAILED**"
            return 'death'
        else:
            print no_understand

2 个答案:

答案 0 :(得分:5)

为什么不呢:

while True:
    print "Which wire do you pull?"
    print
    print "1. The red one."
    print "2. The blue one."
    print
    raw_input('*>>*')
    if randint(0, 1):
        print "**BOMB DEFUSED**"
        return 'engineering2'
    else:
        print "**FAILED**"
        return 'death'

/!\ raw_input返回一个字符串,你将返回值与整数进行比较,它永远不会匹配:

$ python
Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 == "1"
False

答案 1 :(得分:4)

Python是一种“强类型”语言。它不会自动将文本(字符串)转换为数字(int)。它也不会将数字randint(0, 1)转换为布尔值。但您可以告诉它进行转化,例如str(right_write)int(wire_choice)

将数字转换为布尔值略有不同。 Python objects have a method nonzero which Python calls when needed, implicitly,以确定该对象是被视为false还是true。布尔值是int的子类,因此它们具有整数值。您仍然可以选择明确转换为bool(randint(0, 1))或使用randint(0, 1) == 0这样的表达式。

我没有详细解释如何编写解决方案的代码,因为我确信您可以从那里开始,因为您可以自己选择表达代码的方式。

P.S。我想链接到有关非布尔对象的布尔值的特殊情况的更多信息。特别是,Python特别允许我们test the truth value of non-booleans。建议我们这样做,或者至少Google's guide recommends testing the truth value of non-booleans