我对编程很陌生,所以我决定在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语句?
谢谢Ryan Haining
我使用了你回复的代码,并稍微修改了一下,所以猜测总是随机的。如果你看到了,告诉我这是不是最好的办法。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()