我对编程很陌生,所以大约 4 或 5 天前我决定开始使用 Python。我遇到了一个挑战,要求我创建一个“猜数字”游戏。完成后,“硬挑战”是创建一个猜数字游戏,用户创建数字并由计算机 (AI) 猜测。
到目前为止,我已经想出了这个并且它有效,但它可能会更好,我会解释。
from random import randint
print ("In this program you will enter a number between 1 - 100."
"\nAfter the computer will try to guess your number!")
number = 0
while number < 1 or number >100:
number = int(input("\n\nEnter a number for the computer to guess: "))
if number > 100:
print ("Number must be lower than or equal to 100!")
if number < 1:
print ("Number must be greater than or equal to 1!")
guess = randint(1, 100)
print ("The computer takes a guess...", guess)
while guess != number:
if guess > number:
guess -= 1
guess = randint(1, guess)
else:
guess += 1
guess = randint(guess, 100)
print ("The computer takes a guess...", guess)
print ("The computer guessed", guess, "and it was correct!")
这是我上次跑步时发生的事情:
输入一个数字让计算机猜:78
计算机猜测... 74
计算机猜测... 89
计算机猜测... 55
计算机猜测... 78
电脑猜78,猜对了!
请注意,它可以工作,但是当计算机猜测 74 时,它会猜测更高的数字为 89。数字太高,因此计算机猜测的数字较低,但选择的数字是 55。有没有办法让我计算机猜一个低于 89 但高于 74 的数字?这是否需要额外的变量或更复杂的 if、elif、else 语句?
谢谢瑞恩海宁
我使用了您回复中的代码并稍作更改,因此猜测始终是随机的。如果你看到这个,请告诉我这是否是最好的方法。
from random import randint
def computer_guess(num):
low = 1
high = 100
# This will make the computer's first guess random
guess = randint(1,100)
while guess != num:
print("The computer takes a guess...", guess)
if guess > num:
high = guess
elif guess < num:
low = guess + 1
# having the next guess be after the elif statement
# will allow for the random guess to take place
# instead of the first guess being 50 each time
# or whatever the outcome of your low+high division
guess = (low+high)//2
print("The computer guessed", guess, "and it was correct!")
def main():
num = int(input("Enter a number: "))
if num < 1 or num > 100:
print("Must be in range [1, 100]")
else:
computer_guess(num)
if __name__ == '__main__':
main()