-4

您好,我知道这已经被问了几次,但我找不到答案。问题是关于反向猜我的数字游戏。代码执行程序,但不是以“类人”的方式。如果数字是 50 并且它猜测 20 它响应更高,例如计算机说 30,它得到响应更低它猜测 15。我该如何解决这个问题?练习来自:绝对初学者的 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

3 回答 3

4

您需要跟踪可能的最高值和可能的最低值,以便进行智能猜测。

最初,可能的最小值是 1,最大值是 100。假设您猜 50,计算机会响应“更高”。你的两个变量会发生什么?现在可能的最低值变为 50,因为该数字不能低于该数字。最高值保持不变。

如果计算机响应“降低”,则会发生相反的情况。

然后您将在最低和最高可能值之间进行猜测:

random.randint(lowest, highest)

你的猜测会按预期工作。

于 2013-05-14T22:03:25.150 回答
2

阅读二分搜索应该会为您指明正确的方向。

于 2013-05-14T21:59:12.007 回答
0

通常,这些游戏的工作原理是每次做出新的猜测时都会缩小可能数字的范围。IE

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 循环。

通常,这些游戏也利用了二分搜索方法。为了好玩,你可以尝试实现这个:) 希望这会有所帮助!

于 2013-05-14T22:08:39.347 回答