Keying either individual letters or an entire word into hangman game

Viewed 49

I am currently creating a hangman game for a project. I have managed to code where a user can enter individual letters to guess the secret word. However, I am having trouble adding an additional feature where the user can guess the entire word upfront.

below is my code attempt, may I know what to write to have this new feature in my game?

def game_play():
    word = random.choice(WORDS)

    # Dashes for each letter in each word
    current_guess = "-" * len(word)

    # Wrong Guess Counter
    wrong_guesses = 0

    # Used letters Tracker
    used_letters = []

    while wrong_guesses < MAX_WRONG and current_guess != word:
        print (HANGMAN[wrong_guesses])
        print ("You have used the following letters: ", used_letters)
        print ("So far, the word is: ", current_guess)
    
        guess = input ("Enter your letter guess:")
        guess = guess.upper()
    
        # Check if letter was already used
        while guess in used_letters:
            print ("You have already guessed that letter", guess)
            guess = input ("Enter your letter guess: ")
            guess = guess.upper()

        # Add new guess letter to list
        used_letters.append(guess)

        # Check guess
        if guess in word:
            print ("You have guessed correctly!")
    
            # Update hidden word with mixed letters and dashes
            new_current_guess = ""
            for letter in range(len(word)):
                if guess == word[letter]:
                    new_current_guess += guess
                else:
                    new_current_guess += current_guess[letter]
                
            current_guess = new_current_guess
        else:
            print ("Sorry that was incorrect")
            # Increase the number of incorrect by 1
            wrong_guesses += 1
        
    # End the game
    if wrong_guesses == MAX_WRONG:
        print (HANGMAN[wrong_guesses])
        print ("You have been hanged!")
        print ("The correct word is", word)
    
    else:
        print ("You have won!!")

game_play()
3 Answers

Rather than prompting the user for a new guess each time, you could overwrite the line where you output their previous guesses so far, so the output may look something like:

Word: _ A N _ _ A N   Misses: B C D

This would mean they could just keep typing guess and the line would update. See python overwrite previous line for details on how to overwrite previous line.

The input command will let you enter multiple letters. I don't see anything stopping the user entering the full word there already?

Instead of counting each letter which matches/fails you could maintain a set of correct/failed guesses and check against the number of items in the set. Maybe something like:

import random

WORDS = ['STACK', 'OVERFLOW', 'HELP']

def playgame():
    word = random.choice(WORDS)

    # valid characters
    valid = set((chr(c) for c in range(ord('A'), ord('A') + 26)))

    # unique characters in word
    unique = set((c for c in word))
    hits = set()
    misses = set()
    allowed_misses = 5

    complete = False
    while complete == False:
        guess = input("Enter your guess: ").upper()
        for c in (c for c in guess if c in valid):
            if c in unique:
                hits.add(c)
            else:
                misses.add(c)

            # break out of for
            if len(hits) == len(unique) or len(misses) > allowed_misses:
                complete = True
                break

        if not complete:
            # output continuation messages
            print(f'Hits: {hits} misses: {misses}')

    if len(hits) == len(unique):
        # output sucess message
        print(f'Success: hits {hits} misses {misses}')
    else:
        # output fail message
        print(f'Fail: hits {hits} misses {misses}')

if __name__ == '__main__':
    playgame()

I have included the additional feature to enter the entire word, and also refactored your code. If the user entered the entire word correctly, I'd assign current_guess with the correct word and break the while loop. Please have a look

import random

WORDS = ['apple', 'kiwi', 'banana']
MAX_WRONG = 3

def game_play():
    word = random.choice(WORDS).upper()
    current_guess = '-' * len(word)    #hidden answer
    wrong_guesses = 0
    used_letters = []

    while wrong_guesses < MAX_WRONG and current_guess != word:
        print ('\nRemaining tries:', MAX_WRONG - wrong_guesses)
        print ('So far, the secret word is: ', current_guess)
        print ('You have used the following letters: ', used_letters)
        guess = input('Enter your letter guess:').upper()
        if guess == word:
            current_guess = word
            break    #exit the while-loop
    
        while guess in used_letters:    #check for duplicate input
            print ('You have guessed "' + guess + '" already!')
            guess = input ('Enter your letter guess: ').upper()
        
        used_letters.append(guess)    #append guess to used_letters
        if guess in word:
            print ('You have guessed correctly!')
            new_current_guess = ''
            for idx in range(len(word)):    #update hidden answer
                if guess == word[idx]:
                    new_current_guess += guess
                else:
                    new_current_guess += current_guess[idx]
            current_guess = new_current_guess
        else:
            print ('Sorry that was incorrect')
            wrong_guesses += 1
        
    if wrong_guesses == MAX_WRONG:
        print ('\nYou have been hanged!')
        print ('The correct word is', word)
    elif current_guess == word:
        print ('\nYou have won!! The word is:', word)

game_play()

Output:

Remaining tries: 3
So far, the secret word is:  ----
You have used the following letters:  []
Enter your letter guess: i
You have guessed correctly!

Remaining tries: 3
So far, the secret word is:  -I-I
You have used the following letters:  ['I']
Enter your letter guess: kiwi

You have won!! The word is: KIWI
Related