Skip to content Skip to sidebar Skip to footer

Mastermind Game In Python

I have already looked at this thread Python Mastermind Game Troubles on your website but the question I am asking is slightly different as I have been given a different task. This

Solution 1:

Here is the updated code! I’ve used a variable c to keep track of the number of tries. I also break out of the infinite loop when the user has correctly guessed the number.

from random import randint

n1 = randint(1,9)
n2 = randint(1,9)
n3 = randint(1,9)
n4 = randint(1,9)
c = 1

while True:
    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)
    numberswrong = 0

    if guess1 != n1:
        numberswrong += 1
    if guess2 != n2:
        numberswrong += 1

    if guess3 != n3:
        numberswrong += 1

    if guess4 != n4:
        numberswrong += 1

    if numberswrong == 0:
        print('Well Done!')
        print('It took you ' + str(c) + ' ries to guess the number!')
        break
    else:
        print('You got ' + str(4-numberswrong) + ' numbers right.')
    c += 1

Solution 2:

You just forgot to reset your numberswrong variable to zero :)

As a side note, to spot bugs, try to make your code simpler.

  • Count the number of right numbers, instead of the number of wrong ones!
  • Use lists instead of copy pasting code.
  • Once you feel more confortable with loops, use python generators
  • Use text formatting instead of string concatenation.
  • Name your variables with names that make sense (avoid "c" when you can call it "num_tries")
  • Comment!

It you try to apply all this advices, you final code should look like this:

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)

Post a Comment for "Mastermind Game In Python"