您好我知道这已被问过几次,但我找不到答案。 问题是反向猜测我的数字游戏。 代码执行程序但不是以“类似人”的方式。如果数字是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.")
答案 0 :(得分:4)
您需要跟踪最高可能值和最低可能值,以便您可以智能地猜测。
最初,最低可能值为1,最高值为100。 假设你猜50,计算机响应“更高”。你的两个变量怎么了?最低可能值现在变为50,因为该数字不能低于该值。最高值保持不变。
如果计算机响应“较低”,则会发生相反的情况。
然后你会在最低和最高值之间猜测:
random.randint(lowest, highest)
您的猜测将按预期进行。
答案 1 :(得分:2)
阅读Binary Search应该指出正确的方向。
答案 2 :(得分: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循环。
通常,这些游戏也会利用二进制搜索方法。为了好玩,你可以试着实现这个:)希望这会有所帮助!