Replacing "_" in Hangman Game with a Player Guess for All Matches

133 Views Asked by At

I'm getting started with coding and I tried to programm "Hangman". Now I figured most of the stuff on my own, but I'm struggling with this one. I want to save multiple indexes, so that i can replace "_" to the needed character.

guess = ""
for x in randomWord:
    guess = str(guess) + "_"

#Calculates the index for the found lette
for i in randomWord:
    wordIndex = randomWord.find(userInput)
#If Statement deconstructs string into list and adds found letter 
if wordIndex > -1:
    guess = list(guess)
    guess[wordIndex] = userInput
    guess = "".join(guess)
    missLett -= 1

I read somewhere, that enumerate could help me with my problem, but just couldn't get the hang of it.

3

There are 3 best solutions below

0
Janez Kuhar On BEST ANSWER

Using enumerate is indeed a perfect fit for your task. It yields pairs (index, value) at each step of the iteration.

To keep things simple, you could just iterate your randomWord a character at a time and replace the character in guess with userInput for all matching positions. Something like this should work:

randomWord = "hippopotamus"
guess = list("_" * len(randomWord))
userInput = "p"
for i, char in enumerate(randomWord):
    if char == userInput:
        guess[i] = userInput
print("".join(guess))
# Outputs: "__pp_p______"
0
Willy Lutz On

I am not very sure to why you want to get the indexes in the string. You can just define your guess as a list, so that you can access its elements easily and replace '_' by the correct letter for example.

Here is a way of implementing Hangman using a list instead :

randomWord = "helloworld"
guess = ["_" for x in randomWord] # use guess as a list instead to access elements easier

max_err = 5  # max number of trials
err = 0  # number of errors 
while err < max_err:
    letter = input("Guess a letter :\n")
    if letter in randomWord:
        for i in range(len(guess)):  # parsing each letter in guess
            if randomWord[i] == letter:
                guess[i] = letter  # correct letter => replace it in guess
        print(''.join(guess))
    else:
        print("Oh no !\n")
        err += 1
print("you lost...")
0
Michael Butscher On

Be aware that the same letter may appear multiple times in the randomWord. The relevant code with use of enumerate may then look like:

guess = list(guess)

# Typical usage of enumerate. i contains the letter and idx its index
for idx, i in enumerate(randomWord):
    if i == userInput:
        guess[idx] = userInput
        missLett -= 1

guess = "".join(guess)