Python 文字游戏:使用 while 循环和 try-except 构建猜数字游戏

62 阅读3分钟

我正在编写一个简单的文字游戏来增强我对 Python 的了解。在游戏的某个阶段,用户需要猜出集合[1, 5]中的一个数字才能实现自己的愿望。他们只有三次尝试机会。我有两个问题:

1、假设 genie_number 随机选为 3。这个值在用户每次猜测后是否会改变?我不想让程序在每次猜测后随机选择另一个整数。它应该保持不变,这样用户就有 3/5 的机会猜对。

2、我希望对那些不只猜测整数的用户进行惩罚,我已经在 except ValueError 部分完成这一点。但是,如果用户连续三次猜测非整数并用尽所有尝试机会,我希望循环重定向到 else:dead("The genie turns you into a frog."). 现在它给了我下面的错误信息。我该如何解决这个问题?

'Before I grant your first wish,' says the genie, 'you must answer this
'I am thinking of a discrete integer contained in the set [1, 5]. You ha
(That isn't much of a riddle, but you'd better do what he says.)
What is your guess? > what
That is not an option. Tries remaining: 2
What is your guess? > what
That is not an option. Tries remaining: 1
What is your guess? > what
That is not an option. Tries remaining: 0
Traceback (most recent call last):
  File "ex36.py", line 76, in <module>
    start()
  File "ex36.py", line 68, in start
    lamp()
  File "ex36.py", line 48, in lamp
    rub()
  File "ex36.py", line 38, in rub
    wish_1_riddle()
  File "ex36.py", line 30, in wish_1_riddle
    if guess == genie_number:
UnboundLocalError: local variable 'guess' referenced before assignment

以下是我的部分代码:

def wish_1_riddle():
    print "\n'Before I grant your first wish,' says the genie, 'you must answer this riddle!'"
    print "'I am thinking of a discrete integer contained in the set [1, 5]. You have three tries.'"
    print "(That isn't much of a riddle, but you'd better do what he says.)"

    genie_number = randint(1, 5)
    tries = 0
    tries_remaining = 3

    while tries < 3:
        try:
            guess = int(raw_input("What is your guess? > "))
            tries += 1
            tries_remaining -= 1

            if guess == genie_number:
                print "Correct!"
                wish_1_grant()
            else:
                print "Incorrect! Tries remaining: %d" % tries_remaining
                continue
        except ValueError:
            tries += 1
            tries_remaining -= 1
            print "That is not an option. The genie penalizes you a try. Be careful!"
            print "Tries remaining: %d" % tries_remaining

    if guess == genie_number:
        wish_1_grant()
    else:
        dead("The genie turns you into a frog.")

解决方案

问题 1 的解答:

不,不会改变。如果您不断调用 randint(1, 5),是的,它会改变,但一旦您分配它,该值就固定了:

>>> import random
>>> x = random.randint(1, 10)
>>> x
8
>>> x
8
>>> x
8
>>> random.randint(1, 10)
4
>>> random.randint(1, 10)
8
>>> random.randint(1, 10)
10

如您所见,一旦我们将随机数分配给 x,x 始终保持不变。但是,如果我们继续调用 randint(),它就会改变。

问题 2 的解答:

在 int(raw_input()) 之后,您不应该让 tries 加 1,如果该值是一个整数,它也会把 tries 加 1。相反,尝试将您的代码合并到类似以下的内容中:

tries = 0
while tries < 3:
    try:
            x = raw_input('Hello: ')
            x = int(x)
    except ValueError:
            tries+=1

您收到错误,因为您已经错误地回答了所有 3 次问题。因此,没有为 guess 分配任何值。在 while 循环之后,您尝试查看 guess 是否为某个值,而它不是:

tries = 0
while tries < 3:
    try:
            guess = int(raw_input('Enter input: '))
            print guess
    except ValueError:
            tries+=1

完整代码如下:

def wish_1_riddle():
    print "\n'Before I grant your first wish,' says the genie, 'you must answer this riddle!'"
    print "'I am thinking of a discrete integer contained in the set [1, 5]. You have three tries.'"
    print "(That isn't much of a riddle, but you'd better do what he says.)"

    genie_number = randint(1, 5)
    tries = 0
    tries_remaining = 3

    while tries < 3:
        try:
            guess = int(raw_input("What is your guess? > "))
            tries += 1
            tries_remaining -= 1

            if guess == genie_number:
                print "Correct!"
                wish_1_grant()
            else:
                print "Incorrect! Tries remaining: %d" % tries_remaining
        except ValueError:
            tries += 1
            tries_remaining -= 1
            print "That is not an option. The genie penalizes you a try. Be careful!"
            print "Tries remaining: %d" % tries_remaining

    if guess == genie_number:
        wish_1_grant()
    else:
        dead("The genie turns you into a frog.")