如何在while循环中更新我的号码? (猜数字游戏)

时间:2019-04-27 13:27:30

标签: python-3.x

我要用电脑写一个猜谜游戏。

我脑海中选择一个数字,计算机将找出它,并且它可以在一个范围之间进行猜测。 问题是我不知道如何在程序运行期间更新此范围。

import random
x = 1
y = 99
guess= random.randint(x,y)
print(guess)
play='true'
while play=='true':
    a=x
    b=y
    results = input()
    if results == 'd':
        play='false'
    else:
        if results == 'b':
            a=guess
            print('my number is bigger')
            newguess= random.randint(a,b)
            print (newguess)
        elif results == 'k':
            b=guess
            print('my number is smaller')
            newguess= random.randint(a,b)
            print (newguess)
print ('wooow , computer you did it! ')

1 个答案:

答案 0 :(得分:0)

很抱歉代码中的所有解释,但这是我前一段时间做的游戏版本。我要做的是每次用户说高或低时都希望缩小猜测范围。例如如果计算机选择50,并且用户说“高”,则程序不会选择大于50的数字,“低”也是如此。

import random
count = 0 #Number of attemps. how many times while loop runs.
guess = random.randint(1,100)#The guess generator

(l,u) = (0,100) 
lower_guess = l
upper_guess = u
n = 0

print('Chose a number between ', l,  ' and ', u , '.' )


#The game. These are outside the function so that they don't print in every loop because they are unwanted for some Y inputs.
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')#User states

#The function

while n != 'guess':

    count +=1 #adds 1 to count each time loop runs

    if Y == 'L':
        lower_guess = guess+1
        guess = random.randint(lower_guess , upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
        print('Is it ' + str(guess))
        Y = input('Low = L, High = H and Yes = Y:')

    elif Y == 'H':
        upper_guess = guess - 1
        guess = random.randint(lower_guess, upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
        print('Is it ' + str(guess))
        Y = input('Low = L, High = H and Yes = Y:')


    elif Y == 'Y':
        print('I guessed it in ' + str(count) + ' attempts')
        break

    else:
        count = 0
        lower_guess = l
        upper_guess = u
        guess = random.randint(1,100)
        print('That input was invalid. The game has restarted.')
        print('You can chose a new number or keep your old one.')
        print('Is it ' + str(guess))
        Y = input('Low = L, High = H and Yes = Y:')