我已经在你的网站上查看了这个帖子Python Mastermind Game Troubles,但我问的问题略有不同,因为我被赋予了不同的任务。
这就是问题:
生成一个随机的四位数字。玩家必须继续输入四位数字,直到他们猜测随机生成的数字。在每次尝试失败之后,应该说出他们得到了多少正确的数字,但是他们没有找到正确的位置。在游戏结束时,应该祝贺用户,并说出花了多少尝试。
到目前为止我已经做到了这一点:
from random import randint
n1 = randint (1,9)
n2 = randint (1,9)
n3 = randint (1,9)
n4 = randint (1,9)
numberswrong = 0
print (n1,n2,n3,n4)
guess1 = input("guess the first number")
guess2 = input("guess the second number")
guess3 = input("guess the third number")
guess4 = input("guess the fourth number")
guess1 = int (guess1)
guess2 = int (guess2)
guess3 = int (guess3)
guess4 = int (guess4)
if guess1 != n1:
numberswrong +=1
else:
numberswrong +=0
if guess2 != n2:
numberswrong +=1
else:
numberswrong +=0
if guess3 != n3:
numberswrong +=1
else:
numberswrong +=0
if guess4 != n4:
numberswrong +=1
else:
numberswrong +=0
print ("you got",numberswrong, "numbers wrong")
if numberswrong == 0:
print ("Well done")
while numberswrong != 0:
guess1 = input("guess the first number")
guess2 = input("guess the second number")
guess3 = input("guess the third number")
guess4 = input("guess the fourth number")
guess1 = int (guess1)
guess2 = int (guess2)
guess3 = int (guess3)
guess4 = int (guess4)
if guess1 != n1:
numberswrong +=1
else:
numberswrong +=0
if guess2 != n2:
numberswrong +=1
else:
numberswrong +=0
if guess3 != n3:
numberswrong +=1
else:
numberswrong +=0
if guess4 != n4:
numberswrong +=1
else:
numberswrong +=0
print ("you got",numberswrong, "numbers wrong")
print ("Well done")
print(n1,n2,n3,n4)只是为了测试代码而不是实际代码。我有两个问题。首先,如果你第一次猜到这个数字,那么就会显示两个“做得好”,第二个如何在不破坏while循环的情况下清除数字变量。如果我什么都不做,那么每当你得到一个数字变量就会变高不正确的猜测已经过了四年,所以即使你猜对了,你也没有得到完美的消息,因为数字错误等于25或类似的东西。另外,如果你只是在while循环结束时说numberwrong = 0,那么while循环认为你得到了正确的结果并说完了。我不知道解决方案是什么。循环计数器可能?
帮助将不胜感激
编辑:我明白为什么“完成”会被打印两次。至于第二个查询。仍然看不到它。
编辑No.2:@moose。我将尽我所能回答这个问题。当我按下运行程序时,程序会说这个数字会询问1-4是什么数字,然后告诉我错误的数字。唯一的问题是数字的数量增加而且没有被清除。让我说我错了3次所有数字。第三次它说你有12个号码错了。显然我不能错12个数字,因为只有4个数字可以猜测。我看到发生了什么,每次传递后while循环都没有清除。我想我知道解决方案。说某处numberwrong = 0来清除循环。但我不知道在哪里发表这一声明。
答案 0 :(得分:0)
您忘了将您的numberswrong变量重置为零:)
作为旁注,要发现错误,请尝试使代码更简单。
您尝试应用所有这些建议,最终代码应如下所示:
from random import randint
# Init variable
numbers = [randint(1, 9) for _ in range(4)]
num_tries = 0
guesses = None
# Loop while numbers and guesses are not the same.
while numbers != guesses:
# Ask user to guess the 4 values
guesses = [
int(input("guess the first number: ")),
int(input("guess the second number: ")),
int(input("guess the third number: ")),
int(input("guess the fourth number: "))
]
num_tries += 1
# Display message with number of right numbers.
num_right_numbers = len([1 for i in range(4) if numbers[i] == guesses[i]])
print 'You got {0} numbers right.'.format(num_right_numbers)
# User won, print message and quit.
print 'Well Done!'
print 'It took you {0} tries to guess the number!'.format(num_tries)