计算机猜用户心里想的数字,猜数游戏优化(用户创建数字,电脑猜数)

我对编程很陌生,所以我决定在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()

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值