Python - 反向数字猜谜游戏 -

0 投票
5 回答
14112 浏览
提问于 2025-04-17 15:57

我一直在尝试写一个程序,让电脑来猜我心里想的数字,而不是我去猜电脑选的数字。这个程序大部分时候都能正常工作,但有时候它会重复猜测一些数字。比如我已经告诉它我想的数字比“7”大,但它还是会在后面的猜测中重复这个数字。有时候,即使我告诉它某个数字是高还是低,它也会再次猜测同样的数字。如果有经验的人能帮我看看这些循环中我缺少了什么,那就太好了。

#computer enters a value x
#lower - computer guesses lower than x
#higher - computer guesses higher than x
#when string "You got it!" - game over

import random

lowBound = 0
highBound = 100
randomNumber = random.randint(lowBound,highBound)

print ("Is it ", randomNumber, " ?")
response = input()

while response != "You got it!":
    if response == "higher":
        lowBound = randomNumber    
        randomNumber = random.randint (lowBound, highBound)
        print ("Is it ", randomNumber, " ?")
        response = input()

    elif response == "lower":
        highBound = randomNumber
        randomNumber = random.randint (lowBound, highBound)
        print ("Is it ", randomNumber, " ?")
        response = input()

    if response == "You got it!":

        print ("Woohooo, I'm so bitchin'")

5 个回答

0

你提到的几个问题中,有一个是这样的:

highBound = randomNumber
randomNumber = random.randint (lowBound, highBound)

你在设置一个新的范围,这样做是对的,但接着你又选择了另一个随机数!

你应该做的是将范围减半,然后问用户是更高还是更低。从这里开始,看看二分查找算法。

highBound = randomNumber
randomNumber = randomNumber / 2

你的程序仍然会正常运行(如果做了其他提到的改动),但这样做大多数情况下能更快猜到你的数字。

实际上,维基百科上有这个游戏的例子。

1

random.randint(a, b) 这个函数会返回一个在 ab 之间的随机数,包括 ab 本身。也就是说,结果可能是 a 或者 b,也可能是它们之间的任何一个数。当你想生成一个新的随机数时,应该使用 random.randint(lowBound+1, highBound-1),这样可以确保生成的随机数不会是边界值。

3

random.randint 是包含边界的,也就是说:

if response == 'higher':
    lowBound = randomNumber + 1

还有

if response == 'lower':
    highBound = randomNumber - 1

另外,如果用户没有输入有效的回应,input() 就不会再被调用,程序会一直卡在一个无限循环里。

这里有个更稳妥的方法,但对说谎的人无能为力:

import random

lowBound = 0
highBound = 100
response = ''
randomNumber = random.randint(lowBound,highBound)

while response != "yes":
    print ("Is it ", randomNumber, " ?")
    response = input()
    if response == "higher":
        lowBound = randomNumber + 1   
        randomNumber = random.randint(lowBound,highBound)
    elif response == "lower":
        highBound = randomNumber - 1
        randomNumber = random.randint(lowBound,highBound)
    elif response == "yes":
        print ("Woohooo, I'm so bitchin'")
        break
    else:
        print ('Huh? "higher", "lower", or "yes" are valid responses.')

撰写回答