首页 > 解决方案 > 奶牛和公牛游戏一直在说 0 头牛,0 头公牛?

问题描述

我正在做一个牛和牛游戏,你应该猜一个四位数。当我运行程序时,计算机一直说 0 头牛,0 头公牛,我不知道为什么或如何解决它

import random
print("Welcome to the cows and bulls game!") 

number = [random.randint(0,9), random.randint(0,9), random.randint(0,9), random.randint(0,9)] counter = 0 teller1 = 0 teller2 = 0

while True : 

    guess = input("Enter a four digit number:")
    bulls= 0
    cows = 0

    if cows == 4:
        print("Congratulations, you have won the game. you only used:", counter, " attempts")
        break

    for i in range(4):
        if guess[teller1] == number[teller2]:
            cows = cows + 1
            teller1 = teller1 + 1
            teller2 = teller2 + 1

    teller1 = 0

    for i in range(4):
        teller2 = teller1 - 1
        for i in range(3):
            if guess[teller1] == number[teller2]:
                bulls = bulls + 1
                teller1 = teller1 + 1

    print(cows," cows, ", bulls," bulls")

    counter = counter + 1

没有错误消息,但它一直说 0 头奶牛,0 头公牛。

标签: python

解决方案


Your number variable is a list of int, but your guess variable is a string. So when you do if guess[teller1] == number[teller2], you are comparing integers to strings, which is always false.

You can fix it by converting your string to a list of integers:

guess = [int(num) for num in input("Enter a four digit number:")]

Note that a proper solution would also validate the input given by the user (what happens if they type "12345"? "hello world"? nothing?).


推荐阅读