我正在为一个项目做一个小的“智囊团”游戏,在我的最后一个while循环之前似乎运行良好,我以为我有一个结束声明,但它似乎在重复运行。我已经被困在这个问题上有一段时间了,我将非常感谢任何和所有的帮助,谢谢!代码如下:
import random
def generate_code():
"""Create a random code as a list"""
for i in range(0,4):
i = random.randint(0,5)
code.append(i)
print(code)
def make_guess():
"""Let's the user input a guess"""
while len(guess) < 4:
element = input("your guess, one at the time: " )
if element.isnumeric():
element = int(element)
global amountOfGuesses
if element in range(0,6):
guess.append(element)
amountOfGuesses = amountOfGuesses +1
else:
print("number has to be between 0 and 5")
else:
print("has to be a number between 0 and 5")
def right_position(guess, code):
"""Calculate how many correkt numbers on right position the guess have"""
howManyRight = 0
for i in range(4):
if guess[i] == code[i]:
howManyRight = howManyRight +1
return howManyRight
def wrong_position(guess, code):
"""Calculate how many numbers are corret but wrong position"""
howManyWrongPosition = 0
tempCode = code[:]
for i in guess:
if i in tempCode:
tempCode.remove(i)
howManyWrongPosition = howManyWrongPosition +1
howManyWrongPosition = howManyWrongPosition - right_position(guess, code)
return howManyWrongPosition
code = []
guess = []
wrongPosition = []
rightPosition = []
codeCopy = code.copy()
amountOfGuesses = 0
print("Welcome to Mastermind.\nYou get seven guesses to gues a random 4 digit code with 6 different numbers between 0 and 5.")
generate_code()
while amountOfGuesses <= 7:
make_guess()
print("you have", right_position(guess, code), "right numbers on the right position")
print("you have", wrong_position(guess, code), "numbers on that is right but on the wrong posiotion")
if guess[:] == code[:]:
print("Congratulation you won!!! you used", amountOfGuesses, "guesses.")
据我所知,你想要一个尝试成为4个数字的一个输入,所以我也解决了这个问题。你得到一个无限循环的原因是因为你没有在最后打破循环。您还应该清除guess数组,否则make_guess()中的for循环将由于长度为4而跳过(以防猜测错误并希望重试)
固定代码(假设一次尝试输入4个数字):
相关问题 更多 >
编程相关推荐