Samuel Sehnert
Samuel Sehnert

Reputation: 5

Trying to figure out a game of Hangman

I am an extreme beginner and am currently trying to create a game of hangman with Python 3.

Seemingly, the only issue that I am having trouble with is when the user inputs a character, I am not quite sure how to replace the "_"s with the correct letter that the user inputs.

import random


def hangman():
    # setting up the word and spacing
    possible_words = ["SOFTWARE", "COMPUTER", "RESEARCH", "BLIZZARD"]
    chosen_word = random.choice(possible_words)
    unknown_word = chosen_word
    # del
    print(chosen_word)
    # del
    for char in unknown_word:
        unknown_word = unknown_word.replace(char, "_ ")
    print(unknown_word)
    y = list(unknown_word)
    print()

    # Playing the game
    mistakes = 0
    incorrect_guesses = []
    while mistakes < 5:
        guess = input("Enter a guess:\n")
        length = len(guess)
        # PROBLEMS
        if guess.upper() in chosen_word and length == 1:
            print(unknown_word)
            print()
        # PROBLEMS
        elif length != 1:  # For if more than 2 characters are entered.
            print("Please enter a single character.")
            print()
            continue
        else:  # If the guess isn't in the string
            print("Incorrect guess!")
            mistakes += 1
            print("You have {0} attempts left".format(5 - mistakes))
            incorrect_guesses.append(guess)
            print("You have used {0} so far.".format(incorrect_guesses))
            print()
    print("GAME OVER")


hangman()

So, the issue that I need to figure out is what happens if the user enters the correct character.

Thank you in advance!

Upvotes: 0

Views: 157

Answers (3)

Derek Eden
Derek Eden

Reputation: 4618

you could do something like...

unknown_word = chosen_word #define the word
current_guess = '_'*len(unknown_word) #get the blanks (if you keep the spaces the loc parameter below will be multiplied by 2)
guessed_letter = input("Enter a guess:\n") #get the guessed letter

if guessed_letter in unknown_word:
    loc=unknown_word.index(guessed_letter)
    current_guess=current_guess[:loc]+guessed_letter+current_guess[loc+1:]

this will replace the blank with the letter in it's respective position, if it's in the unknown_word

as another mentioned..the index position (loc) will be multiplied by two if you keep the spaces

EDIT - above only works with one occurrence of each letter...this will work for words with multiple occurrences of the same letter:

guessed_letter = input("Enter a guess:\n")
for loc in range(len(unknown_word)):
    if unknown_word[loc] == guessed_letter:
        current_guess = current_guess[:loc]+guessed_letter+current_guess[loc+1:]

Upvotes: 0

Lee Garcon
Lee Garcon

Reputation: 192

The code below will replace the _'s with the original character:

unknown_word = ' '.join([guess.upper() if chosen_word[i] == \
                guess.upper() else c for i, c in enumerate(
                 unknown_word.replace(' ', ''))]
                ) + ' '

Upvotes: 0

jacalvo
jacalvo

Reputation: 666

First of all, I would suggest using a set() instead of a list for incorrect_guesses (you will need to use .add instead of .append). That way you will avoid having repeated values if the user repeats the same character.

You can also have a correct_guesses variable to keep track of the successful attempts and use them to avoid replace them with _ in unknown_word.

Here's how the affected piece of code would like after that change:

    incorrect_guesses = set()
    correct_guesses = set()
    while mistakes < 5:
        guess = input("Enter a guess:\n")
        length = len(guess)
        char = guess.upper()
        if char in chosen_word and length == 1:
            correct_guesses.add(char)
            unknown_word = chosen_word
            for char in (c for c in unknown_word if c not in correct_guesses):
                unknown_word = unknown_word.replace(char, "_ ")
            print(unknown_word)

Upvotes: 1

Related Questions