[Python] Problems with the logic for checking answer in Code Breaker / Mastermind board game

Discussão em 'Python' iniciado por Stack, Setembro 3, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to make the game Mastermind with python, I want to give the user a green X for every correct number and position of number, a yellow X for right number but wrong position and a gray X for neither. However I cant figure out the logic, especially when there are 2 identical numbers.

    This is how far I've gotten but no matter what i try it doesnt work out in my head.

    import random

    class game():

    def __init__(self):

    self.solvednumberlist = list()
    self.correctamount = 0
    self.semicorrectamount = 0
    self.checklist = list()

    for i in range(4):

    self.numgen = str(random.randint(0,9))

    self.solvednumberlist.insert(i-1, self.numgen)

    self.solvednumber = "".join(self.solvednumberlist)


    print(self.solvednumber)


    def userinput(self):

    self.userin = input("Guess a 4 digit code: ")


    def dataprocess(self):

    for i in range(4):

    print("user", self.userin, i)

    for j in range(4):

    if self.userin in self.solvednumber[j]:

    print("true", self.solvednumber[j], j)

    if i==j:

    print("green")
    self.green = True

    else:

    print("yellow")
    self.green = False

    if self.green == True:
    print("green")
    self.checklist.insert(i, "g")
    print(self.checklist)
    break
    else:
    print("no green")

    else:

    print("false", self.solvednumber[j], j)
    print("")

    run = game()
    run.userinput()
    run.dataprocess()

    Continue reading...

Compartilhe esta Página