Python 实施牛牛博弈
我必须编码,我必须在其中生成4个随机数,并要求用户猜测它。在过去的几个小时里,我一直在尝试编写代码,但似乎找不到解决方案 我想要的输出是:Python 实施牛牛博弈,python,python-3.x,Python,Python 3.x,我必须编码,我必须在其中生成4个随机数,并要求用户猜测它。在过去的几个小时里,我一直在尝试编写代码,但似乎找不到解决方案 我想要的输出是: 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. 到目前为止,我得到了
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.
它不会继续下去。我只是想知道问题出在哪里 试试这个:
print(str(count[0]), "Cows.", str(count[1]), "Bulls")
if count[0] == 4:
print("Congrats, you done it in", str(guess))
break
如果计数等于4,则要中断
while
循环,否则应继续运行 您的代码有一些问题:
- while True语句具有与函数相同的缩进级别
- 在while语句中,您使用了break,这就是为什么如果第一次未能获得正确的anwser,该语句只执行一次
- “x&y”变量??请在将来使用不仅对您而且对其他人都有意义的变量
- 在函数“number”中,您有一个此验证
这不会做任何事情,它只会比较字符串的第一个字符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()
FWIW,我不知道什么是牛和牛的游戏…试着删除
else:break代码>行。它必须随机生成一个4位数的数字,并让用户猜出来。对于用户在正确位置正确猜测的每个数字,他们都有一头“奶牛”。用户在错误位置正确猜到的每一个数字都是一个“公牛”。@decezeSo在错误位置有四个数字,你赢了吗?(根据您的代码付费)请参阅