[Python] Trying to get the game to end when the full hangman displays [closed]

Discussão em 'Python' iniciado por Stack, Maio 9, 2025.

  1. Stack

    Stack Membro Participativo

    My problem is that when the last ascii art with the guy hanging displays the game still goes one more round.

    I tried changing the lives from 6 to 5 but that doesn't seem to resolve the issue. What do I need to change?

    import random

    stages = ['''
    +---+
    | |
    O |
    /|\ |
    / \ |
    |
    =========
    ''', '''
    +---+
    | |
    O |
    /|\ |
    / |
    |
    =========
    ''', '''
    +---+
    | |
    O |
    /|\ |
    |
    |
    =========
    ''', '''
    +---+
    | |
    O |
    /| |
    |
    |
    =========
    ''', '''
    +---+
    | |
    O |
    | |
    |
    |
    =========
    ''', '''
    +---+
    | |
    O |
    |
    |
    |
    =========
    ''', '''
    +---+
    | |
    |
    |
    |
    |
    =========
    ''']

    word_list = ["aardvark", "baboon", "camel"]

    # TODO-1: - Create a variable called 'lives' to keep track of the number of lives left.
    # Set 'lives' to equal 6.

    chosen_word = random.choice(word_list)
    print(chosen_word)


    placeholder = ""
    word_length = len(chosen_word)
    for position in range(word_length):
    placeholder += "_"
    print(placeholder)

    game_over = False
    correct_letters = []
    lives = 6

    while not game_over:
    guess = input("Guess a letter: ").lower()

    display = ""

    for letter in chosen_word:
    if letter == guess:
    display += letter
    correct_letters.append(guess)
    elif letter in correct_letters:
    display += letter
    else:
    display += "_"


    print(display)
    print(lives)

    # TODO-2: - If guess is not a letter in the chosen_word, Then reduce 'lives' by 1.
    # If lives goes down to 0 then the game should stop and it should print "You lose."

    if "_" not in display:
    game_over = True
    print("You win.")
    elif lives == 0:
    game_over = True
    print("You lose.")
    else:
    if guess in chosen_word:
    for position in range(len(chosen_word)):
    if chosen_word[position] == guess:
    display = display[:position] + guess + display[position + 1:]
    else:
    lives -= 1 # if letter not found, only 1 life deduction will happen
    print(stages[lives])

    # TODO-3: - print the ASCII art from 'stages'
    # that corresponds to the current number of 'lives' the user has remaining.

    Continue reading...

Compartilhe esta Página