Python猜猜游戏

时间:2016-03-08 16:59:16

标签: python

我是使用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()
  1. 我如何整合一个系统,使用它如此每次用户猜测正确的数字时,它包含的反馈给出了正确猜测数字所需的最少数量的猜测。就像他们花了多少猜测一样高分,并且只有当它被击败时才改变它

3 个答案:

答案 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))