top of page

Fun and Educational Hangman Game with Pygame

Hangman is a classic word-guessing game where one player thinks of a word and the other player tries to guess it by suggesting letters. The word to guess is represented by a row of dashes, representing each letter of the word. The guessing player has a limited number of guesses, and each incorrect guess adds to a drawing of a hanged man.


In this blog post, I'll walk you through the process of creating a simple Hangman game using the popular Python library, Pygame. Whether you're a beginner or an experienced programmer, you'll find this project both enjoyable and enlightening.


Getting Started

First, make sure you have Pygame installed. You can install it using pip

pip install pygame

Next, create a new Python file for your Hangman game. We'll start by importing the necessary modules

import pygame, os
import random
import time
import requests
import json

Setting Up the Game

Now, let's set up the basic structure of our game. I'll define some constants for colors and fonts, as well as initialize Pygame

### SCREEN SIZE
WIDTH = 1024
HEIGHT = 683

### COLORS
WHITE = (255,255,255)
BLACK = (0,0,0)
GREY  = (192,192,192)
DGREY  = (50,50,50)
RED  = (207,0,0)
BLUE  = (70,70,207)
GREEN  = (70,207,70)

### INITIALIZE PYGAME
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0 ,32)
systemExit=False
buffer = 50
alphabet=['a','b','c','d','e','f','g','h','i','j',
          'k','l','m','n','o','p','q','r','s','t',
          'u','v','w','x','y','z','-']
letters=['a','b','c','d','e','f','g','h','i','j',
    'k','l','m','n','o','p','q','r','s','t',
    'u','v','w','x','y','z','A','B','C','D',
     'E','F','G','H','I','J','K','L','M','N',
     'O','P','Q','R','S','T','U','V','W','X','Y','Z']

Using Dictionary

Get a random new word from the dictionary. Register for a dev account and get your API key: https://www.dictionaryapi.com/register/index

def picklePicker():
    global wordToGuess
    word_file = "/usr/share/dict/words"
    WORDS = open(word_file).read().splitlines()
    if active_sp==True:
        randomWord = fix_word(random.choice(WORDS))
        randomWord = randomWord.replace("'","").strip()
        return randomWord.replace(" ", "-")
    else:
        return wordToGuess    
    
def fix_word(word):
    response = requests.get("https://www.dictionaryapi.com/api/v3/references/collegiate/json/" + 
                            word + "?key=<substitute with your API Key>")
    responseString = json.dumps(response.json())
    if "shortdef" in responseString:
        return word
    else:
        print("shortdef missing, got response:", responseString)
        return random.choice(response.json())

Giving user a hint before the last move

Use dictionaryapi.com to get definition of the word.

def lookup_dictionary(word):
    response = requests.get("https://www.dictionaryapi.com/api/v3/references/collegiate/json/" + word + "?key=<substitute with your API Key>")
    if response.status_code != 200:
        # This means something went wrong.
        print("Error in dictionary lookup:", response.json())
        return ""
    else:
        short_def = response.json()[0]['shortdef']
        print("short_def:",short_def)
        return short_def

Drawing the Hangman

Draw the Hangman based on the number of remaining guesses


def draw_hangman(count):
    Pi=3.14
    global state, gamesLost, invalidTries
    if count > 0: ##Head
        pygame.draw.circle(screen, GREY, (300, 180), 50, 10)
    if count > 1: ##Eyes
        pygame.draw.circle(screen, GREY, (280, 165), 10, 5)
        pygame.draw.circle(screen, GREY, (320, 165), 10, 5)
    if count > 2: ##Mouth
        if len(invalidTries) == 3:
            pygame.draw.arc(screen, GREY, [280,180,40,30], Pi, 2*Pi, 4) #Smile
        elif len(invalidTries) == 4:
            pygame.draw.arc(screen, GREY, [280,184,40,20], Pi, 2*Pi, 4) #Smile
        elif len(invalidTries) == 5:
            pygame.draw.arc(screen, GREY, [280,188,40,10], Pi, 2*Pi, 4) #Smile
        elif len(invalidTries) == 6:
            pygame.draw.arc(screen, GREY, [280,188,40,20], 2*Pi, Pi, 4) #Frown            
        elif len(invalidTries) == 7:
            pygame.draw.arc(screen, GREY, [280,188,40,30], 2*Pi, Pi, 4) #Frown            
    if count > 3:
        pygame.draw.line(screen, GREY, (300, 230), (300, 380),10)
    if count > 4:
        pygame.draw.line(screen, GREY, (300, 270), (380, 230),10)
    if count > 5:
        pygame.draw.line(screen, GREY, (300, 270), (220, 230),10)
    if count > 6:
        pygame.draw.line(screen, GREY, (300, 380), (340, 450),10)
        showWordDefinition(610)
    if count > 7:
        pygame.draw.line(screen, GREY, (300, 380), (260, 450),10)
        state+=1
        gamesLost+=1

Play the Game

def play():
    global systemExit, state, invalidTries, wordToGuess, answer, gamesWon, p1name, p2name, active_player, mpStats
    letter_clicked = ''
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            systemExit=True
            return

        # when the user clicks the start button, change to the playing state
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if ((event.pos[0] - 495)%60 <= 30) and ((event.pos[1] - 100)%100 <= 30):
                    xIndex= int((event.pos[0] - 495)/60)
                    yIndex= int((event.pos[1] - 100)/100)
                    if xIndex >= 0 and yIndex >= 0:
                        letter_clicked = alphabet[xIndex + yIndex*7]
                        if letter_clicked in wordToGuess:
                            found_indexes=find(wordToGuess, letter_clicked)
                            for i in found_indexes:
                                answer[i]=letter_clicked
                        else:
                            if letter_clicked not in invalidTries:
                                invalidTries.append(letter_clicked)
    draw_background()
    if active_sp==True:
        showGameNumber()
    else:
        showMpStats()
    draw_hangman(len(invalidTries))
    if list(wordToGuess)==answer:
        state+=1
        if active_sp == True:
            gamesWon+=1
        else:
            if active_player == 1:
                mpStats[p1name]+=1
            else:
                mpStats[p2name]+=1
    pygame.display.flip()

Main Game Loop

Finally, let's create the main game loop. In this loop, we'll handle user input, update the game state, and draw the game

if __name__ == "__main__":
	os.environ['SDL_VIDEO_CENTERED'] = '1' #center screen
	pygame.init()
	pygame.display.set_caption("Hangman")
	screen = pygame.display.set_mode((WIDTH, HEIGHT), 0 ,32)
	
	Myclock = pygame.time.Clock()
	while True:
		if systemExit==True:
			pygame.quit()
			break;
		if state == 0:
			welcome()
		elif state == 1:
			enter_a_word()
		elif state == 2:
			play()
		elif state == 3:
			results()
		Myclock.tick(64)    
	exit()

Conclusion

And there you have it! With just a few lines of code, you can create a fun and educational Hangman game using Pygame. Feel free to customize the game further by adding more words, improving the graphics, or implementing multiplayer functionality.


Have fun playing and learning with your new game!


Hangman
Hangman

302 views1 comment

Recent Posts

See All

1 Comment

Rated 0 out of 5 stars.
No ratings yet

Add a rating
Guest
Jun 14

Best hangman rendering ever!

Like

Subscribe

Subscribe to our mailing list for regular updates on news, events, insightful blogs, and free code!

Thanks for subscribing!

bottom of page