Beginner Projects (3) – Hangman (Python)

Welcome to the third beginner project in python. My goal with this project was, to implement a simple „Hangman“ game.

Basic Thoughts and Explanation

Simple explanation for someone who doesn’t know the game „Hangman“:

Hangman is a simple guessing game with usually two or more players, where one player thinks of a specific word, while the other players have to guess what word he/she is thinking about. The players can ask whether certain letters are contained in the word to be guessed, while the guessing players only have limited attempts in order to do so.

Again, basic explanations are given in the code example with „### @“

Step 1 Think about the game logic first
  • The game therefore should contain a variable with the maximum number of guesses allowed per game
  • The game should allow a user to input a specific word that has to be guessed
  • The game should, in case the user does not want to input a specific word, allow to simply take a random word from a pre-defined list containing random words
  • The game should, at the beginning and after every guessed letter, display the number of letters the word contains while not showing the correct word, display the number of wrong guesses the user has made so far
  • Also, if one of the letters in the word is guessed correctly, the specific letter should be displayed at the correct location of the word on screen
    • Furthermore, if the guessed letter exists more than once in the word, the game should display all of these letters at the correct locations on screen
Step 2 Importing Libraries and defining Variables
import random

#################
# Simple Code for a Hangman Game
#################

def hangman():
    max_wrong_guesses = 5 ### Can be changed to whatever you like
    word_list = [] ### This will be a list containing all the letters that have been used in the game
    correct_letters = [] ### This will be a list containing all the correct guesses
    word = [] ### This will be used as a placeholder in the beginning that is being initialized with "*" for each letter in the word to be guessed
    default_word_list = ["Akquise", "nichtsdestotrotz", "Burgverlies", "Ouvertüre",
                         "Chrysantheme", "Portemonnaie", "Dekolleté", "Quarzuhr", "Einfaltspinsel", "Rückgrat",
                         "Fronleichnam", "Schlafittchen", "Galionsfigur", "Terrasse", "hanebüchen", "unentgeltlich",
                         "Incentive", "Verlies", "Jackett", "weismachen", "Kernspintomografie", "lizenzieren",
                         "Yuccapalme", "Mischpoke", "Zucchini"] ### For someone wondering what kind of language that is.. that is German :) And yes I am German as well
Step 3 Implement the Game
    print(f"Do you want to take a random default Word or choose your own? (Default/Own)") ### Ask the user for own or default word
    decision = str(input()).upper()
    if decision == "DEFAULT": ### Depending on the decision choose either a random word or take the user input
        random_word = random.randrange(len(default_word_list))
        word_to_be_guessed = default_word_list[random_word].upper()
    elif decision == "OWN":
        print(f"Please type in a Word that has to be guessed")
        word_to_be_guessed = str(input()).upper()
    else:
        print(f"That was no a valid answer, a Default word is now being taken") ### In case the user enters something else, just take a random word from the list
        random_word = random.randrange(len(default_word_list))
        word_to_be_guessed = default_word_list[random_word].upper()

    word_length = len(word_to_be_guessed) ### Check how many letters are in the word
    guess_counter = 0

    for i in range(word_length): ### For every letter in the word, create a new list that contains only "*" for as many letters in the word to be guessed
        letter = "*"
        word.append(letter)

    while True:
        print("Please make a letter guess")
        guess = str(input()).upper()
        if guess.upper() == word_to_be_guessed.upper(): ### If the user enters the correct word the loop stops and the game is over
            print(f"Yess! You guessed the word correctly!")
            break
        if len(guess) >= 2: ### Break if user enters two or more letters
            print(f"You inserted two or more letters, only one letter allowed. Please try again")
            break
        if guess in word_to_be_guessed: ### What to do if the word to be guessed contains the guessed letter
          if guess in correct_letters: ### Also check if the user has used that letter before
                print(f"You have already used {guess} try again")
                guess_counter += 1
                print(f"You have {max_wrong_guesses - guess_counter} chances left") ### Tell the user how many guesses he/she has left
                if guess_counter >= max_wrong_guesses:
                    print(f"The correct word was: {word_to_be_guessed.lower().capitalize()}")
                    break
            else:
                print(f"You are correct, {guess.lower()} is one character of the word to be guessed") ### If letter is correct, append to correct_letters list an give no penalty
                correct_letters.append(guess)
        elif guess not in word_to_be_guessed: ### What to do if the letter that has been guessed does not exist in the word
            print(f"That letter is not contained in the Word")
            guess_counter += 1
            print(f"You have {max_wrong_guesses-guess_counter} chances left")
            if guess_counter >= max_wrong_guesses: ### What to do if you have taken the maximum number of guesses
                print(f"The Word you were looking for is: {word_to_be_guessed.lower().capitalize()}")
                break
        else:
            break

        word_placeholder = []
        for i in range(word_length):
            letter = word_to_be_guessed[i]
            word_placeholder.append(letter)
        correct_guess_index = []
        for i in range(len(word_to_be_guessed)):
            if word_to_be_guessed[i] == guess:
                correct_guess_index.append(i)

        if word == word_to_be_guessed:
            print(f"Congratulations, you have collected all missing letters. The word is: {word_to_be_guessed}")
            break

        for i in range(len(correct_guess_index)):
            word[correct_guess_index[i]] = guess

        print(word)

        word_list.append(guess)
        print(f"Your current letters used are: {word_list}")
        print(f"The correct guesses are: {correct_letters}")

hangman() ### Don't forget to call the function

Kommentar verfassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert