1

I am trying to make a hangman game for class and I am stuck on how to replace a dash (-) with a correctly guessed letter.

Like if the word was HAPPY and the user guessed the letter p, so it would replace the dash for a letter and look like this: --PP-

Here is my code so far:

def play_game(secret_word):
guesses_left = 8
hangman_dash = len(secret_word) * "-"
while guesses_left > 0:
    print("The word now looks like this: " + (hangman_dash))
    print("You have " + str(guesses_left) + " guesses left")
    letter = input("Type a single letter, then press enter: ")
    letter = letter.upper()
    if len(letter) != 1:
        print("Please enter only one letter.")
    elif letter not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWYXZ':
        print("Please guess a letter.")
    if letter in secret_word:
        print("That guess is correct")

    else:
        print("There are no {}'s in the word".format(letter))
        guesses_left = guesses_left - 1
Chris Tina
  • 21
  • 2

3 Answers3

1

I created a very simple example for this. Essentially if user_input in word then we find the index of the user input and replace it with the hidden letter. The code is not very well written :) but it does the job

def hangman(word):
    # Replace word with dashes    
    hidden_word = "-" * len(word)
    print("This is the hidden word " + hidden_word)
    # Get user's guess
    user_input = input("Guess a letter: ")
    # If the user's guess exists in the string
    if user_input in word:
        # Find all occurences of user's guess in word
        occurences = findOccurrences(word, user_input)
        # For each occurenc, replace that dash in the string with the correct letter
        for index in occurences:
            hidden_word = hidden_word[:index] + user_input + hidden_word[index + 1:]
        # Return the updated hidden_word
        print(hidden_word)
    # If the user's guess isn't in the string
    else:
        user_input = input("Sorry that letter was not found, please try again: ")

# Find all occurences method
def findOccurrences(s, ch):
    return [i for i, letter in enumerate(s) if letter == ch]

hangman("hello")nput("Guess a letter: ")
    if user_input in word:
        occurences = findOccurrences(word, user_input)
        for index in occurences:
            hidden_word = hidden_word[:index] + user_input + hidden_word[index + 1:]
        print(hidden_word)
    else:
        user_input = input("Sorry that letter was not found, please try again: ")

def findOccurrences(s, ch):
    return [i for i, letter in enumerate(s) if letter == ch]

hangman("hello")
Ibraheem Ahmed
  • 11,652
  • 2
  • 48
  • 54
  • I was trying to do the same, but I got stuck on appending to hidden_word. +1 – 10 Rep May 22 '20 at 22:26
  • The code worked - thank you! The problem now is that I don't understand how it worked or how [:index] or [index + 1:] is being used. – Chris Tina May 22 '20 at 22:51
  • When I run the code, there is a problem. If the letter guessed is in the word twice, like "p" is in the word "happy" twice, it's only showing one p and not 2 p's – Chris Tina May 22 '20 at 23:02
  • Type a single letter, then press enter: p That guess is correct The word now looks like this: HAP-- You have 8 guesses left – Chris Tina May 22 '20 at 23:03
  • @ChrisTina I updated my code to handle multiple occurences of the same letter – Ibraheem Ahmed May 23 '20 at 15:13
  • @ChrisTina The string splicing method you is explained in the answer to [this question](https://stackoverflow.com/questions/1228299/changing-one-character-in-a-string-in-python/1228327#1228327) by MartinBeckett – Ibraheem Ahmed May 23 '20 at 15:14
  • @ChrisTina If the answer helped you with your question, consider marking it as accepted by clicking the tick next to it. – Ted Klein Bergman May 23 '20 at 15:24
0

Going through the string is not worth programming. Just set the hangman_dash variable to '' every iteration of the loop and make a for loop like the one below to check if each of the letters are correct:

def play_game(secret_word):
guesses_left = 8
while guesses_left > 0:
    hangman_dash=''
    for i in secret_word:
        if i in good_guesses:
            hangman_dash+=i
        else:
            hangman_dash+='-'
    print("The word now looks like this: " + (hangman_dash))
...

So if a letter in secret_word has been guessed (or is in the good_guesses string) then whatever that letter is will be added to hangman_dash. Otherwise, '-' will be added.

Riley
  • 179
  • 9
  • This isn't the entire code, however. Please post the entire code, as it will help the op more. – 10 Rep May 22 '20 at 22:26
0

I've expanded upon the code that redline provided. It checks for alpha characters as well.

def hangman(word):
    hidden_word = "-" * len(word)
    print("This is the hidden word " + hidden_word)
    while True:
        user_input = input("Guess a letter: ")
        if user_input.isalpha():
            if user_input in word:
                index = word.find(user_input)
                hidden_word = hidden_word[:index] + user_input + hidden_word[index + 1:]
                print(hidden_word)
            else:
                print("Sorry that letter was not found, please try again.")
        else:
            print("Please use letters in the alphabet.")

hangman("word")

As requested, I've added an example of words that contain two of the same letters. I hope this helps.

def hangman(secret_word):
    hangman_dash = len(secret_word) * "-"
    while True:
        user_input = input("Guess:")
        index = 0
        for char in secret_word:
            if char == user_input:
                hangman_dash = hangman_dash[:index] + char + hangman_dash[index + 1:]
                print(hangman_dash)
            index += 1

hangman("happy")
Brett La Pierre
  • 493
  • 6
  • 15
  • 1
    The only problem is if the letter is in the word twice, it's only converting one of the letters not both. For the word HAPPY, it converted one of the dashes to P not both dashes to P. It looks like this --P-- instead of --PP- I need it to convert both P's not just one. – Chris Tina May 22 '20 at 23:19