我正在编写一个简单的基于文本的游戏来增强我对 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.")