2016-03-08 174 views
2

我是使用2.7.11的Python初學者,我做了一個猜謎遊戲。這是到目前爲止我的代碼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. 我將如何整合的系統,使得它如此每當用戶猜測正確的號碼,它包括反饋給儘可能少的花費要正確預測的數量的猜測。像有多少猜測高分花了他們,並改變它,只有當它被打
+2

你可能想改變'如果playAagain ==「Y」或「Y」:''到如果playAagain.lower()==「y」:'或'如果playAagain ==「y」或playAgain ==「Y」:' –

+1

只是一些建議和與您的問題無關的問題。 1)。你應該使用一致的縮進,(通常約定是每層4個空格)。 2)。不要在你的函數中導入模塊,在腳本的頂部執行它。 3)。爲什麼你打破了糟糕的輸入循環? 4)。不要通過在自己內部調用'game()'來重新啓動遊戲,請使用循環。 5)。通過重構你的代碼,你可以擺脫其中的2個'guess = input(...')行。 –

回答

0

您可以創建這樣一個靜態變量: game.highscore = 10

  • ,你在每一次更新用戶贏得比賽(檢查是否嘗試低於高分)
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 
    ... 
0

在你的代碼的開始(定義函數之前),添加全局變量BEST_SCORE(或任何你想將它命名),並將其初始化爲無:在

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