Search code examples
pythonpython-3.xindexingenumerate

Hangman: replacing an * with player input guess


I have been playing around with this code for some time now. I have tried many different methods of finding the index of the player's correctly guessed inputs within the randomly generated word - I think what I have currently written should work but I fear I am overlooking a really simple error. As it stands whenever I run the code every guess the player makes is deemed correct, furthermore when I try to reference the value player_guess it does not show up in my print statement print(f"Correct! {player_guess} is in the word!").

I am only a beginner with python (in fact, coding altogether) and I have spent around 8 hrs trying to solve these issues myself with the help of previous similar questions on stackoverflow but ultimately I have hit a wall, so any help would be much appreciated.

#random module to choose random word from word_list.txt
import random

#port in word_list.txt and create list
word_list = ['rarely', 'universe', 'notice', 'sugar', 'interference', 'constitution', 'we', 'minus', 'breath', 'clarify', 'take', 'recording', 'amendment', 'hut', 'tip', 'logical', 'cast', 'title', 'brief', 'none', 'relative', 'recently', 'detail', 'port', 'such', 'complex', 'bath', 'soul', 'holder', 'pleasant', 'buy', 'federal', 'lay', 'currently', 'saint', 'for', 'simple', 'deliberately', 'means', 'peace', 'prove', 'sexual', 'chief', 'department', 'bear', 'injection', 'off', 'son', 'reflect', 'fast', 'ago', 'education', 'prison', 'birthday', 'variation', 'exactly', 'expect', 'engine', 'difficulty', 'apply', 'hero', 'contemporary', 'that', 'surprised', 'fear', 'convert', 'daily', 'yours', 'pace', 'shot', 'income', 'democracy', 'albeit', 'genuinely', 'commit', 'caution', 'try', 'membership', 'elderly', 'enjoy', 'pet', 'detective', 'powerful', 'argue', 'escape', 'timetable', 'proceeding', 'sector', 'cattle', 'dissolve', 'suddenly', 'teach', 'spring', 'negotiation', 'solid', 'seek', 'enough', 'surface', 'small', 'search']

#Global variables
guesses = []
playing = True
lives = 7
#word generation
word = random.choice(word_list)
#create a display version on the generated word comprised of *
display = '*'* len(word)
#tracker of most recent player_guess
player_guess = ''

#create hangman graphics
def hangman():
    if lives == 7:
        print('____________')
        print('|/          ')
        print('|           ')
        print('|           ')
        print('|           ')
        print('|           ')
        print('|___________')
    if lives == 6:
        print('____________')
        print('|/        | ')
        print('|           ')
        print('|           ')
        print('|           ')
        print('|           ')
        print('|___________')
    if lives == 5:
        print('____________')
        print('|/        | ')
        print('|         O ')
        print('|           ')
        print('|           ')
        print('|           ')
        print('|___________')
    if lives == 4:
        print('____________')
        print('|/        | ')
        print('|         O ')
        print('|         | ')
        print('|           ')
        print('|           ')
        print('|___________')       
    if lives == 3:
        print('____________')
        print('|/        | ')
        print('|        _O ')
        print('|         | ')
        print('|           ')
        print('|           ')
        print('|___________')
    if lives == 2:
        print('____________')
        print('|/        | ')
        print('|        _O_')
        print('|         | ')
        print('|           ')
        print('|           ')
        print('|___________')
    if lives == 1:
        print('____________')
        print('|/        | ')
        print('|        _O_')
        print('|         | ')
        print('|        /  ')
        print('|           ')
        print('|___________')
    if lives == 0:
        print('____________')
        print('|/        | ')
        print('|        _O_')
        print('|         | ')
        print("|        / \ ")
        print('|           ')
        print('|___________')
        print("You lose")

def guess_input():
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    try:
        player_guess = str(input("\nSelect a letter between A-Z: ")).lower()
    except:
        print("\nThat was not a letter between A-Z, try again...")
    else:
        if len(player_guess) > 1:
            print("\nPlease only guess 1 letter - no cheating!")
        elif player_guess in guesses:
            print("\nYou have already guessed this letter, try again...")
        elif player_guess not in alphabet:
            print("\nThat was not a letter between A-Z, try again...")
        else:
            guesses.append(player_guess)
            return player_guess

def guess_checker():
    global lives, display, word, player_guess
    if player_guess in word:
        print(f"Correct! {player_guess} is in the word!")
        for i, letter in enumerate(word):
            if letter == player_guess:
                display[i] = player_guess
    else:
        lives -= 1

def win_check(word):
    if '*' not in display:
        print("Congratulations, you win!")
    else:
        False

############################# MAIN PROGRAM ####################################

#Introduction
print('Welcome to HANGMAN, I have randomly generated a word for your game. You have 7 lives - good luck!')

while playing == True:
    if lives > 0:
        #Guess input
        hangman()
        print('\n')
        print(display)
        guess_input()
        guess_checker()
        win_check(display)
        if win_check == True:
            playing = False
        if win_check == False:
            continue
    elif lives == 0:
        hangman()
        playing = False

Solution

  • The variable player_guess in the function guess_input is not the global variable with that name. It would work better if you would add

    global player_guess
    

    ... in that function.

    However, it is best practice to avoid (or at least, limit) the use of global. Instead, capture the value that guess_input returns in the main program, and then pass that as argument to guess_checker, like:

    guess_checker(guess_input())
    

    You would then no longer need that global variable -- remove the corresponding public instructions, and define the parameter for guess_checker:

    def guess_checker(player_guess):
    

    Remark

    Although not your question, there are several other issues in your code. One major issue is that display is a string, and so you cannot do display[i] = player_guess -- it will give an exception.

    Please check this where I improved and corrected several things. Check the comments.