我必须对我必须生成4个随机数的Cows and Bulls game进行编码,并要求用户猜测它。过去几个小时我一直在尝试对其进行编码,但似乎无法提出解决方案。
我想要的输出是:
Welcome to cows and Bulls game.
Enter a number:
>> 1234
2 Cows, 0 Bulls.
>> 1286
1 Cows, 1 Bulls.
>> 1038
Congrats, you got it in 3 tries.
到目前为止,我已经得到了这个:
print("Welcome to Cows and Bulls game.")
import random
def number(x, y):
cowsNbulls = [0, 0]
for i in range(len(x)):
if x[1] == y[i]:
cowsNbulls[1] += 1
else:
cowsNbulls[0] += 1
return cowsNbulls;
x = str(random.randint(0, 9999))
guess = 0
while True:
y = input("Enter a number: ")
count = number(x, y)
guess += 1
print(str(count[0]), "Cows.", str(count[1]), "Bulls")
if count[1] == 4:
False
print("Congrats, you done it in", str(guess))
else:
break;
输出是:
Welcome to Cows and Bull game.
Enter a number: 1234
4 Cows, 0 Bulls.
它不会继续。我只是想知道问题是什么。
答案 0 :(得分:0)
试试这个:
print(str(count[0]), "Cows.", str(count[1]), "Bulls")
if count[0] == 4:
print("Congrats, you done it in", str(guess))
break
如果计数等于4,您想要中断while
循环,否则它应该继续运行。
答案 1 :(得分:0)
您的代码存在一些问题:
x[1] == y[i]
这不会做任何事情,它只会比较字符串的第一个字符下面我对您的代码进行了一些修复,看看它是否是您正在寻找的类似内容:
import random
def number(rand_num, guess):
cowsNbulls = {
'cow': 0,
'bull': 0,
}
for i in range(len(rand_num)):
try:
if rand_num[i] == guess[i]:
cowsNbulls['cow'] += 1
else:
cowsNbulls['bull'] += 1
except:
pass
return cowsNbulls;
def game_start():
rand_number = str(random.randint(1, 9999))
tries = 0
locked = True
print("Welcome to Cows and Bulls game.")
while locked:
print(rand_number)
guess = input("Enter a number (Limit = 9999): ")
cows_n_bulls = number(rand_number, guess)
tries += 1
print(str(cows_n_bulls['cow']), "Cows.", str(cows_n_bulls['bull']), "Bulls")
if cows_n_bulls['cow'] == 4:
print("Congrats, you done it in", str(tries))
locked = False
game_start()