如何重启猜数字游戏
我正在使用 Python 2.7.1 这个版本。
我想让游戏可以根据用户的输入来重新开始,这样用户就可以选择重新开始,而不是直接退出游戏再重新打开。有人能帮我想想办法吗?谢谢!
import random
the_number = random.randrange(10)+1
tries = 0
valid = False
while valid == False:
guess = raw_input("\nTake a guess: ")
tries += 1
if guess.isdigit():
guess = int(guess)
if guess >= 1 and guess <= 10:
if guess < the_number:
print "Your guessed too low"
elif guess > the_number:
print "Your guessed too high"
elif tries <= 3 and guess == the_number:
print "\n\t\tCongratulations!"
print "You only took",tries,"tries!"
break
else:
print "\nYou guessed it! The number was", the_number,"\n"
print "you took",tries,"tries!"
break
else:
print "Sorry, only between number 1 to 10"
else:
print "Error,enter a numeric guess"
print "Only between number 1 to 10"
if tries == 3 and guess != the_number:
print "\nYou didn't guess the number in 3 tries, but you still can continue"
continue
while tries > 3 and guess != the_number:
q = raw_input("\nGive up??\t(yes/no)")
q = q.lower()
if (q != "yes") and (q != "no"):
print "Only yes or no"
continue
if q != "no":
print "The number is", the_number
valid = True
break
else:
break
3 个回答
0
while True:
play_guessing_game()
user = raw_input("Play again? (Y/n) ")
again = "yes".startswith(user.strip().lower())
if not again:
break
... 这里的 "yes".startswith() 这一部分的意思是,它可以接受像 'Ye'、' yeS' 这样的输入,或者你只要按一下回车键也可以。
1
添加一个变量,给它起个名字,比如叫 continue
,然后把它的初始值设为 true
。接着,把你的整个代码放在一个 while(continue)
循环里。在循环的最后,打印出 play again?
,然后接受用户的输入,根据他们的回答来设置 continue
的值。
3
把你现在的代码放到一个函数里,比如叫 play_game
或者其他你喜欢的名字。然后写一个循环,让这个函数一直运行,直到用户觉得够了为止。比如:
def global_thermonuclear_war():
print "Boom!"
while raw_input("Shall we play a game? [y|n] ") == 'y':
global_thermonuclear_war()