Игра Python "Коровы и быки" - бесконечный цикл - PullRequest
0 голосов
/ 18 марта 2019

Это мой первый пост в StackOverflow, поэтому, если я что-то не так делаю, пожалуйста, дайте мне знать.Эта игра, которая называется «Коровы и быки», похожа на игру под названием Mastermind https://en.wikipedia.org/wiki/Bulls_and_Cows.. По сути, вы должны угадать четырехзначный код без указания повторяющихся чисел.Ошибка, которая у меня возникает, заключается в том, что когда я попадаю в раздел «Проверка кода на повторяющиеся числа», если в рандомизированном коде есть дубликаты, он входит в бесконечный цикл в операторе while.Кто-нибудь сможет мне помочь с этим?

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()

1 Ответ

1 голос
/ 18 марта 2019

Это входит в бесконечный цикл, потому что, когда присутствуют повторяющиеся числа, вы просто обновляете значение Code, а не CodeFirst, CodeSecond, CodeThird и CodeFourth, которые используются в условиях. Должно быть что-то вроде этого

    while repeatedCode == True:
        if codeFirst == codeSecond or codeFirst == codeThird or codeFirst == codeFourth:
             CODE=random.randint(1000,9999)
             CODE=str(CODE)
             codeFirst=int(CODE[0])
             codeSecond=int(CODE[1])
             codeThird=int(CODE[2])
             codeFourth=int(CODE[3])
             print("Test1")
        elif codeSecond == codeThird or codeSecond == codeFourth:
             CODE=random.randint(1000,9999)
             CODE=str(CODE)
             codeFirst=int(CODE[0])
             codeSecond=int(CODE[1])
             codeThird=int(CODE[2])
             codeFourth=int(CODE[3])
             print("Test2")
        elif codeThird == codeFourth:
             CODE=random.randint(1000,9999)
             CODE=str(CODE)
             codeFirst=int(CODE[0])
             codeSecond=int(CODE[1])
             codeThird=int(CODE[2])
             codeFourth=int(CODE[3])
             print("Test3")
        else:
            repeatedCode=False

Также вы можете использовать набор для проверки, если код имеет повторяющиеся числа, вместо создания четырех переменных. Я дам вам понять, как вы можете использовать наборы.

...