Hangman
Guess the word letter by letter before the hangman is drawn. Teaches strings, in, looping over characters and checking input.
Open in Tokbit Level: Intermediate. Free in the browser, nothing to install, no account needed.
Run the example in Tokbit and step through it: before each step say what will happen and check it in the Variables panel. Then change it your way.
Flowchart
Python program
The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.
"""Guess a word letter by letter, seven mistakes and you hang. Teaches strings and the in operator."""
from random import choice
# Tokbit screen functions, not in plain Python:
from tokbit import (
cls, at, color, beep, WHITE, YELLOW, ORANGE, LIGHT_RED, LIGHT_GREEN,
)
def gallows(misses: int):
"""Draws the gallows by the number of mistakes; each mistake adds a part."""
color(ORANGE)
if misses >= 1:
at(2, 9)
print("==========", end="")
if misses >= 2:
for y in range(2, 9):
at(4, y)
print("|", end="")
if misses >= 3:
at(4, 1)
print("+-----+", end="")
if misses >= 4:
at(10, 2)
print("|", end="")
if misses >= 5:
at(10, 3)
print("O", end="")
if misses >= 6:
at(10, 4)
print("|", end="")
at(10, 5)
print("|", end="")
if misses >= 7:
at(9, 4)
print("/", end="")
at(11, 4)
print("\\", end="")
at(9, 6)
print("/", end="")
at(11, 6)
print("\\", end="")
words: list[str] = ["PROGRAM", "MONITOR", "DIAGRAM", "LOOP", "FUNCTION", "ROBOT", "SCREEN", "INTERNET", "TABLET", "KEYBOARD"]
lower: str = "abcdefghijklmnopqrstuvwxyz"
upper: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
word: str = choice(words)
tried: str = ""
message: str = ""
mask: str = ""
p: str = ""
misses: int = 0
guessed: bool = False
while misses < 7 and not guessed:
cls()
color(WHITE)
at(2, 0)
print("HANGMAN", end="")
gallows(misses)
mask = ""
# The mask shows guessed letters and underscores for the rest.
for i in range(len(word)):
if word[i] in tried:
mask = mask + word[i] + " "
else:
mask = mask + "_ "
color(YELLOW)
at(2, 12)
print(mask, end="")
color(WHITE)
at(2, 14)
print("Tried: " + tried, end="")
color(LIGHT_RED)
at(2, 16)
print(message, end="")
color(WHITE)
guessed = "_" not in mask
if not guessed:
at(2, 18)
p = input("Letter:")
# Turns a lowercase letter into uppercase; the words are uppercase.
if len(p) == 1:
for i in range(26):
if lower[i] == p:
p = upper[i]
if len(p) != 1 or p not in upper:
message = "Type one letter A to Z."
else:
if p in tried:
message = "You already tried that letter."
else:
tried = tried + p
message = ""
if p not in word:
misses = misses + 1
beep(196, 150)
else:
beep(880, 60)
if guessed:
color(LIGHT_GREEN)
at(2, 18)
print("You won! The word is complete.", end="")
else:
cls()
gallows(7)
color(LIGHT_RED)
at(2, 18)
print("Hanged! The word was " + word, end="")
color(WHITE)
at(0, 20)
Follow-up tasks
Tasks in which you change the example (with a model solution):