pythonvalidationprocedural-programming

Mastermind game using alphabets and validation in python


I am relatively new to coding and would like to create a mastermind game using letters instead of colors/numbers.

The secret code in my MasterMind is a sequence of 4 letters. Each letter in a secret code is unique, and is from ‘A’ to ‘H’. Some examples of valid secret code are “ABDF”, “EGHC” and “DAFE”.

The following examples are invalid:

I currently have this done:

import random
def chooseOneLetter (base1, base2):
  ratio = 10
  seed = int(random.uniform (0, ratio*len(base1)+len(base2)))
  if seed < ratio*len(base1):
    chosenLetter = base1[int(seed/ratio)]
    base1.remove(chosenLetter)
  else:
    chosenLetter = base2[(seed - ratio*len(base1))]
    base2.remove(chosenLetter)
    return chosenLetter
def getSecretCode(base1, base2):
  secretCode = ""
  for i in range(4):
    chosenLetter = chooseOneLetter (base1, base2)
    secretCode += chosenLetter
    return secretCode
# base1 = ["A", "B", "C", "D"]
# base2 = ["E", "F", "G", "H"]

However, I would like to include 2 more variables. The first variable references a list of letters in their correct positions or None if the letter in the guess is not correct. The second variable references a dictionary with letters guessed in incorrect positions as keys, and the number of times the letters were guessed in incorrect positions as values.

E.g. if the secret code is BAFD,

The first variable references ['B', None, None, None]. The player has correctly guessed that letter B is in the first position, but all other letters in other positions are incorrect.

The second variable references {'A': 2, 'B': 1, 'D': 2}. The player has guessed 3 correct letters thus far: A is guessed in wrong positions twice, B in a wrong position once, and D in wrong positions twice.

I am also looking for the game engine to prompt the user to play another game and to re-enter the string if it does not meet the criteria. It should look something like this.

Enter a guess to continue or RETURN to quit: abda
Please enter 4 unique letters, A to H
Enter a guess to continue or RETURN to quit: ade
Please enter 4 unique letters, A to H
Enter a guess to continue or RETURN to quit: asbc
Please enter 4 unique letters, A to H
Enter a guess to continue or RETURN to quit: abcd
The guess is not correct, attempt no. 1
The correct letters in correct positions: [None, None, None,
None]
The correct letters and the number of times found in incorrect
positions: {'B': 1, 'C': 1, 'D': 1}
Enter a guess to continue or RETURN to quit: dhcb
The guess is not correct, attempt no. 2
The correct letters in correct positions: [None, None, None,
'B']
The correct letters and the number of times found in incorrect
positions: {'B': 1, 'C': 2, 'D': 2, 'H': 1}
Enter a guess to continue or RETURN to quit: cdhb
You guessed it correctly in 3 attempts, the secret word is CDHB
Do you want to play again? Y to play again: y

Thank you so much for your help!


Solution

  • Here is a way you can do this. random.sample() forms the secret code. A feedback list is prepared after each guess. For each letter in the guess it will show either (1) the letter, if it was in the correct position (2) True, if the letter is in the code but in the wrong position or (3) False, if it's not in the code at all. The count dictionary will keep count of how many letters were guessed in the wrong position.

    import random
    
    def mastermind():
        key = random.sample('ABCDEFGH', 4)
        count = {}
        feedback = []
        guess = ''
        while guess != key:
            feedback.clear()
            guess = list(input('Enter your guess: '))
            for i, v in enumerate(guess):
                if v == key[i]:
                    feedback.append(v)
                elif v in key:
                    feedback.append(True)
                    count[v] = 1 if v not in count else count[v] + 1
                else:
                    feedback.append(False)
            print(feedback, count)
        print('Correct!')
    
    while True:
        mastermind()
        if input('Play again? (Y/N): ').lower() == 'n':
            break
    

    Gameplay:

    Enter your guess: ABCD
    [False, True, True, False] {'B': 1, 'C': 1}
    Enter your guess: BCEF
    [True, True, True, False] {'B': 2, 'C': 2, 'E': 1}
    Enter your guess: CEBG
    ['C', 'E', True, False] {'B': 3, 'C': 2, 'E': 1}
    Enter your guess: CEHB
    ['C', 'E', 'H', 'B'] {'B': 3, 'C': 2, 'E': 1}
    Correct!
    Play again? (Y/N): y
    Enter your guess: ABCD
    [True, False, False, True] {'A': 1, 'D': 1}
    Enter your guess: DAEF
    ['D', True, False, 'F'] {'A': 2, 'D': 1}
    Enter your guess: DGAF
    ['D', 'G', 'A', 'F'] {'A': 2, 'D': 1}
    Correct!
    Play again? (Y/N): n
    >>>