PYTHON-反数猜测Gam

2024-09-30 12:12:21 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我一直在想办法写一个程序,让电脑猜出我想的数字,而不是用另一种方法猜出电脑选择的数字。它在大多数情况下都是有效的,但是在某些情况下,它会在链上重复数字,即使我之前告诉过它,例如,我正在考虑的值高于“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'")

Tags: youresponse情况it数字randomlowercomputer
3条回答

在提到的其他问题中,你的一个问题是:

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

你正在设置一个新的界限,这是好的,但然后你选择另一个随机数!

你应该做的,是将界限减半,然后从那里向用户询问高低。看看二进制搜索算法。

highBound = randomNumber
randomNumber = randomNumber / 2

你的程序仍然可以工作(这里提到的其他更改),但这会在大多数情况下更快地猜出你的号码。

实际上有an example of this game on Wikipedia.

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

random.randint(a, b)返回一个介于ab之间的数字。生成新的随机数时,应使用random.randint(lowBound+1, highBound-1)

相关问题 更多 >

    热门问题