我是使用2.7.11的python的初学者,我做了一个猜谜游戏。这是我到目前为止的代码
def game():
import random
random_number = random.randint(1,100)
tries = 0
low = 0
high = 100
while tries < 8:
if(tries == 0):
guess = input("Guess a random number between {} and {}.".format(low, high))
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if guess_num < low or guess_num > high:
print("That number is not between {} and {}.".format(low, high))
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
playAagain = raw_input ("Excellent! You guessed the number! Would you like to play again (y or n)? ")
if playAagain == "y" or "Y":
game()
elif guess_num > random_number:
print("Sorry that number is too high.")
high = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
elif guess_num < random_number:
print("Sorry that number is too low.")
low = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
game()
答案 0 :(得分:0)
你可以像这样创建一个静态变量:
game.highscore = 10
答案 1 :(得分:0)
您可以在best_score
功能中添加game
参数:
def game(best_score=None):
...
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
# update best score
if best_score is None:
best_score = tries
else:
best_score = min(tries, best_score)
print("Best score so far: {} tries".format(best_score))
play_again = raw_input("Excellent! You guessed the number! Would you like to play again (y or n)? ")
if play_again.lower() == "y":
game(best_score) # launch new game with new best score
...
答案 2 :(得分:0)
在代码开始时(在定义函数之前),添加全局变量best_score(或任何你想要调用它的东西),并将其初始化为None:
best_score = None
在检查数字是否正确的猜测期间,您可以检查针对best_score的尝试次数,并相应地更新:
elif guess_num == random_number:
global best_score
# check if best_score needs to be updated
if best_score == None or tries < best_score:
best_score = tries
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
# print out a message about the best score
print("Your best score is {} tries.".format(best_score))