2013-05-14 90 views
-3

你好,我知道這已問了幾次,但我無法找到答案。 問題是關於我的數字遊戲的反面猜測。 代碼執行程序,但不是以「人性化」的方式執行。如果數字是50,它猜到20,它的響應更高,例如計算機說30,它得到的答案更低,它猜測15。我該如何解決?練習來自:絕對初學者的Python。 有人可以幫我嗎?請以簡單的方式,否則我會跳過書中的內容。 我想你可以通過查看代碼來了解我所知道的以及不知道的內容。 請幫我...反向遊戲python

代碼:

#Guess My Number 
# 
#The computer picks a random number between 1 and 100 
#The playes tries to guess it and the coputer lets 
#the player know if the guess is too high, too low 
#or right on the money 

print ("\t// // // // // // // // // //") 
print ("\tWelcome to 'Guess My Number'!") 
print ("\tComputer VS Human") 
print ("\t// // // // // // // // // //") 
name = input("What's your name?") 
print ("Hello,", name) 
print ("\nOkay, think of a number between 1 and 100.") 
print ("I'll try to guess it within 10 attemps.") 

import random 

#set the initial values 

the_number = int(input("Please type in the number to guess:")) 
tries = 0 
max_tries = 10 
guess = random.randint(1, 100) 

#guessing loop 
while guess != the_number and tries < max_tries: 
    print("Is it", guess,"?") 
    tries += 1 

    if guess > the_number and tries < max_tries: 
     print ("It's lower") 
     guess = random.randint(1, guess) 
    elif guess < the_number and tries < max_tries: 
     print ("It's higher") 
     guess = random.randint(guess, 100) 
    elif guess == the_number and tries < max_tries: 
     print("Woohoo, you guessed it!") 
     break 
    else: 
     print("HAHA you silly computer it was", the_number,"!") 

input ("\n\nTo exit, press enter key.") 

回答

4

您需要跟蹤最高可能值和最低可能值,以便您可以智能地進行猜測。

最初,最低可能值是1,最高值是100. 假設你猜50,並且計算機響應「更高」。你的兩個變量會發生什麼?現在可能的最低值爲50,因爲數字不能低於此值。最高值保持不變。

如果電腦響應「較低」,則會發生相反情況。

然後,你將最低和最高的可能值之間的猜測:

random.randint(lowest, highest)

和預期的一樣你的猜測會工作。

+0

謝謝,但是我在代碼中的位置呢? – bogaardesquat

+0

在'import random'後面聲明兩個變量'lowest'和'highest'。在if語句的「lower」和「higher」中,重新調整變量的值。任何時候你猜你會用'guess = random.randint(最低,最高)' – Lanaru

0

通常這些遊戲通過使每個可能的數字的範圍小於每次做出新的猜測來工作。即

1st guess = 20 
guess is too low 
--> range of guesses is now (21, 100) 

2nd guess = 45 
guess is too high 
--> range of guesses is now (21, 44) 
etc... 

在你的測試中,你忘了以前所有的猜測,所以它不能這樣做。您可以嘗試跟蹤範圍的下限和上限:

lower_range, higher_range = 1, 100 
max_tries = 10 

#guessing loop 
while tries < max_tries: 
    guess = random.randint(lower_range, higher_range) 
    print("Is it", guess,"?") 
    tries += 1 

    if guess > the_number:  
     print ("It's lower") 
     higher_range = guess - 1 

    elif guess < the_number: 
     print ("It's higher") 
     lower_range = guess + 1 

    else: # i.e. correct guess 
     print("Woohoo, you guessed it!") 
     input ("\n\nTo exit, press enter key.") 
     sys.exit(0) 

print("HAHA you silly computer it was", the_number,"!") 

也收拾了一些while循環。

通常,這些遊戲也會利用二進制搜索方法。爲了好玩,你可以試着實現這個:)希望這有助於!

+0

嗨,尼克斯尼克。在閒置時,你的工作對我來說並不真實(在debian linux上,使用python 3.1進行閒置)。但是,我添加了higher_range = guess -1作爲lower_range到我的代碼,因爲它是現在的一切正常工作。非常感謝 – bogaardesquat