← All video projects

Free video project · Intermediate

Hangman where Python plays itself 🪢

Two hangman bots: one that guesses the commonest letters and loses, and one that only considers words that still fit, which wins almost every time.

The video is out Friday 6 November at 6pm.

The code from the video

# Hangman, where Python plays itself
WORDS = ["rocket", "banana", "jazz", "pizza", "rhythm", "puzzle", "galaxy", "python",
         "light", "night", "might", "right", "sight", "fight", "tight", "wight"]

def show(word, guessed):
    shown = ""
    for letter in word:
        if letter in guessed:
            shown += letter + " "
        else:
            shown += "_ "
    return shown

ORDER = "etaoinsrhldcumfpgwybvkxjqz"

def pick(word, guessed):
    counts = {}
    for candidate in WORDS:
        if len(candidate) == len(word) and show(candidate, guessed) == show(word, guessed):
            for letter in ORDER:
                if letter in candidate and letter not in guessed:
                    counts[letter] = counts.get(letter, 0) + 1
    return max(counts, key=counts.get)

def play(word, lives=6, talk=False):
    guessed = []
    while lives > 0:
        letter = pick(word, guessed)
        guessed.append(letter)
        if letter not in word:
            lives -= 1
        if talk:
            print(letter, "->", show(word, guessed), "lives:", lives)
        if "_" not in show(word, guessed):
            return True
    return False


for word in WORDS:
    if play(word):
        print(f"{word:<8} Python wins")
    else:
        print(f"{word:<8} You win!")

Run it in your browser with nothing to install, right here on this page.

Make it your own

  1. Add your own word list and find the word your smart bot finds hardest.
  2. Let a human play against the word list, with the bot giving hints.
  3. Count the average number of wrong guesses across every word.

Skills: lists, dictionaries, while loops, functions

Start the free lessons More video projects