Basic hangman game

There isn’t much to say about this but I coded a basic hangman game to demonstrate comparing variables and while I will never do anything with this code I thought it might be kinda cool to pop it on GitHub in case it helps anyone else and I finally have something to put on the STEM section of this website!

import tkinter as tk
import random

# Create a class for the Hangman game
class HangmanGame:
    def __init__(self, master):
        # Initialize the game and set up the main window (master)
        self.master = master
        self.master.title("Hangman Game")

        # Define a list of words for the game
        self.wordlist = ["python", "hangman", "programming", "developer", "interface", "example"]

        # Choose a random word from the wordlist
        self.word = random.choice(self.wordlist)

        # Initialize variables to keep track of game state
        self.guesses = 0
        self.max_guesses = 5

        # Create a list to store the current state of the word with underscores for hidden letters
        self.hidden_word = ["_" if char.isalpha() else char for char in self.word]

        # Create a label to display the current state of the word
        self.word_label = tk.Label(master, text=" ".join(self.hidden_word), font=("Helvetica", 20))
        self.word_label.pack()

        # Create labels and input elements for user interaction
        self.input_label = tk.Label(master, text="Guess a letter: ", font=("Helvetica", 12))
        self.input_label.pack()

        self.entry = tk.Entry(master, font=("Helvetica", 12))
        self.entry.pack()

        # Create a button for making a guess
        self.guess_button = tk.Button(master, text="Guess", command=self.make_guess, font=("Helvetica", 12))
        self.guess_button.pack()

        # Create a label to display messages to the user
        self.message_label = tk.Label(master, text="", font=("Helvetica", 12))
        self.message_label.pack()

    # Function to handle the user's guess
    def make_guess(self):
        guess = self.entry.get()

        # Check if the guess is a valid single letter
        if len(guess) != 1 or not guess.isalpha():
            self.message_label.config(text="Please enter a valid letter.")
            return

        # If the guess is in the word, update the hidden word and display it
        if guess in self.word:
            for i in range(len(self.word)):
                if self.word[i] == guess:
                    self.hidden_word[i] = guess
            self.word_label.config(text=" ".join(self.hidden_word))

            # Check if the player has guessed the entire word
            if "".join(self.hidden_word) == self.word:
                self.message_label.config(text="You won! The word was: " + self.word)
                self.entry.config(state="disabled")
            self.entry.delete(0, "end")
        else:
            # Handle incorrect guess
            self.guesses += 1

            # Check if the player has used up all their guesses
            if self.guesses >= self.max_guesses:
                self.message_label.config(text="You lost! The word was: " + self.word)
                self.entry.config(state="disabled")
            else:
                self.message_label.config(text=f"Wrong guess! {self.max_guesses - self.guesses} guesses left.")
            self.entry.delete(0, "end")

# Entry point for the program
def main():
    # Create the main window
    root = tk.Tk()
    hangman = HangmanGame(root)
    root.mainloop()

# Run the main function if this script is executed
if __name__ == "__main__":
    main()

You can find the latest code online on GitHub.

Need to reference?

Ellis, M. (2023). Basic hangman game. [online] Snat's Narratives & Tales. Available at: https://snat.co.uk/stem/scripts/basic-hangman-game.html [Accessed 11 Dec 2024].

Thanks for reading! You may be interested in this …

Join the Discussion

Have you ever coded a simple game like this Hangman example? What would you add or change to improve it?

Add to the discussion!

This site uses Akismet to reduce spam. Learn how your comment data is processed.