Python Forum

Full Version: A hangman game.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
A hangman type game I wrote. It's fully functional but I'm still trying to improve on it.
It does require a list of words in a .txt file. I used this list.

import random


def hang_man():
    """Hangman game"""

    with open("words_alpha.txt", "r") as f:
        lines = f.readlines()
        raw_word = random.choice(lines)

    letter_list = list(raw_word)
    del letter_list[-1] # Deletes \n charater.
    final_word = "".join(letter_list)

    vowels = ["a", "e", "i", "o", "u"]
    count = 0
    incorrect_letters = []
    spaces = ["-" for letter in final_word]

    for count in range(len(letter_list * 2)):
        print(f"There are {len(letter_list)} letters in the word.")
        guess_letter = input("Guess a letter. ")

        if guess_letter in letter_list:
            locate = letter_list.index(guess_letter)
            spaces[locate] = guess_letter
            
            if guess_letter in vowels:
                print(f"There is an {guess_letter} at {locate}.")
            else:
                print(f"There is a {guess_letter} at {locate}.")

            print("".join(spaces))

            count += 1
            while count >= len(final_word) \ 2:
                guess_word = input("Guess the word, y/n? ")
                if guess_word == "y":
                    guess = input("What is the word? ")
                    if guess in final_word:
                        print("You avoided death!")
                        raise SystemExit
                    else:
                        print("Wrong!")
                        break
                else:
                    break

        else:
            if guess_letter not in incorrect_letters:
                incorrect_letters.append(guess_letter)
            else:
                print("You already guessed that letter!")

            print(f"There is no {guess_letter}.")

    else:
        print(f"You're hung! The word was {final_word}.")


if __name__ == "__main__":
    hang_man()
There's a problem with line 26 (I think, maybe this was intentional). The first word I got was 'prosecutor'. I got to 'prosecut--', but then couldn't go any farther. If I guessed 'o' or 'r' it just refound the ones at the beginning of the word.

I would generally solve this with a try/except block in a loop, using the start parameter of the index method:

start = 0
while True:
    try:
        locate = letter_list.index(guess_letter, start)
        spaces[locate] = guess_letter
        start = locate + 1
    except:
        break
You can also do it in a loop:

start = 0
for letter in range(letter_list.count(guess_letter)):
    location = letter_list.index(guess_letter, start)
    spaces[locate] = guess_letter
    start = locate + 1
Also, I would inform the user of how many guesses they have left.