如何在电脑猜谜游戏中删除用过的数字?

时间:2014-07-03 02:11:39

标签: python python-2.7

我正在尝试创建一个计算机与计算机猜谜游戏,问题是计算机会猜两次相同的数字。我尝试使用变量.remove(),但计算机仍会猜测变量的位置,所以我会收到错误。我将代码还原到了它的工作位置。

print 'Get ready for some action!'
time.sleep(1)
firstname = raw_input('Enter in a name for computer 1... ')
time.sleep(1)
secondname = raw_input('Enter in a name for computer 2... ')
time.sleep(1)
howlittle = int(raw_input('Enter in the min... '))
time.sleep(1)
howmuch = int(raw_input('Enter in the max... '))
computernumber = random.randint(howlittle,howmuch)
print firstname + 'choses %s as its lucky number.' %computernumber
time.sleep(1)
print '%s is thinking...'%secondname
time.sleep(1)
firsts=random.randint(howlittle,howmuch)
if firsts == computernumber:
    print 'The %s won!'%secondname
guessers = 0
computers=[]
while firsts != computernumber:
    guessers += 1
    if firsts == computernumber:
        print 'The computer won in %s guesses'%guessers
    elif firsts > computernumber:
        firsts = random.randint(howlittle,firsts)
        computers.append(firsts)
    elif firsts < computernumber:
        firsts = random.randint(firsts, howmuch)
        computers.append(firsts)
print secondname + " took %s guesses to guess the number" %guessers
print computers

我仍然在为它添加功能,但我只需要首先解决这个问题。谢谢!

2 个答案:

答案 0 :(得分:1)

在您的elif中添加if条件,以便:

如果number_guessed在computer_guesses_list中:   再次生成一个随机数

答案 1 :(得分:0)

问题可能是random.randint(a,b)在[a,b]中返回一个数字x,即a <= x <= b

因此,在您的代码中,random.randint(howlittle,firsts)可能会返回firsts,请将其更改为random.randint(howlittle,firsts-1)

random.randint(firsts,howmuch)random.randint(firsts+1,howmuch)

您应该发布不起作用的代码。