This is my first post on StackOverflow, so if I do anything wrong, please let me know. This game, called Cows and Bulls, is similar to a game called Mastermind https://en.wikipedia.org/wiki/Bulls_and_Cows. Essentially, you have to guess the four digit code without giving any duplicate numbers. The error that I am having is that when I get to the section named "Check code for repeated numbers", if there are duplicates in the randomized code, it will enter an infinite loop at the while statement. Would anyone be able to help me with this?
import random
def main():
bulls=0 #Correct Number in Correct Position
cows=0 #Correct Number in Wrong Position
CODE=random.randint(1000,9999)
CODE=str(CODE)
codeFirst=int(CODE[0])
codeSecond=int(CODE[1])
codeThird=int(CODE[2])
codeFourth=int(CODE[3])
GUESS=int(input("Guess:"))
repeatedCode=True
#Check for exactly four digits
if GUESS <= 1000 or GUESS >= 9999:
print("Invalid input - Guess must be four digits!")
return
elif GUESS >= 1000 and GUESS <= 9999:
#If all previous conditions cleared set guess values
GUESS=str(GUESS)
guessFirst=int(GUESS[0])
guessSecond=int(GUESS[1])
guessThird=int(GUESS[2])
guessFourth=int(GUESS[3])
#Check code for repeated numbers
while repeatedCode == True:
if codeFirst == codeSecond or codeFirst == codeThird or codeFirst ==
codeFourth:
CODE=random.randint(1000,9999)
print("Test1")
repeatedCode == True
elif codeSecond == codeThird or codeSecond == codeFourth:
CODE=random.randint(1000,9999)
print("Test2")
repeatedCode == True
elif codeThird == codeFourth:
CODE=random.randint(1000,9999)
print("Test3")
repeatedCode == True
else:
repeatedCode==False
break
print('Test passes repeated code')
#Check for repeated numbers
if guessFirst == guessSecond or guessFirst == guessThird or guessFirst
== guessFourth:
print("Invalid Input - guess cannot contain duplicates")
return
elif guessSecond == guessThird or guessSecond == guessFourth:
print("Invalid Input - guess cannot contain duplicates")
return
elif guessThird == guessFourth:
print("Invalid Input - guess cannot contain duplicates")
return
#Bulls and Cows
if guessFirst == codeFirst:
bulls=bulls + 1
elif guessFirst == codeSecond or guessFirst == codeThird or guessFirst
== codeFourth:
cows=cows + 1
if guessSecond == codeSecond:
bulls + 1
elif guessSecond == codeFirst or guessSecond == codeThird or guessSecond
== codeFourth:
cows=cows + 1
if guessThird == codeThird:
bulls=bulls + 1
elif guessThird == codeFirst or guessThird == codeSecond or guessThird
== codeFourth:
cows=cows + 1
if guessFourth == codeFourth:
bulls=bulls + 1
elif guessFourth == codeFirst or guessFourth == codeSecond or guessFourth == codeThird:
cows=cows + 1
#Final Text Output
print("Guess:",guessFirst, guessSecond,guessThird,guessFourth,"Code:",codeFirst,codeSecond,\
codeThird,codeFourth,"Results:", bulls,"-",cows)
return
main()
Aucun commentaire:
Enregistrer un commentaire