You could make this prettier by printing the hangman state (gallows):
Setup a list of gallows states:
hung = [ "+-------+ ", #0
"| | ", #1
"| ^ ", #2
"| (' ') ", #3
"| ~ ", #4
"| __/ \\__ ", #5
"| / | | \\ ", #6
"| / === \\", #7
"| o [___] o", #8
"| | | ", #9
"| | | ", #10
"| / \\ ", #11
"|\\ ", #12
"| \\____________"] #13
states = [hung.copy()] # last state is hung
hung[9] = hung[9].replace("| |", "| ",1)
hung[10] = hung[10].replace("| |","| ",1)
hung[11] = hung[11].replace("\\"," ")
states.insert(0,hung.copy()) # hide right leg
hung[9:12] = ["|"]*3
states.insert(0,hung.copy()) # hide left leg
hung[5] = hung[5].replace("__ "," ",)
hung[6] = hung[6].replace("\\"," ",1)
hung[7] = hung[7].replace("\\"," ",1)
hung[8] = hung[8].replace(" o"," ",1)
states.insert(0,hung.copy()) # hide right arm
hung[5] = hung[5].replace("__"," ",)
hung[6] = hung[6].replace("/"," ")
hung[7] = hung[7].replace("/"," ")
hung[8] = hung[8].replace("o"," ")
states.insert(0,hung.copy()) # hide left arm
hung[5:9] = ["|"]*4
states.insert(0,hung.copy()) # hide body
hung[2:5] = ["|"]*3
states.insert(0,hung.copy()) # hide head (1st state)
Game play:
word = "elephant".upper() # select a random uppercase word here
hidden = dict.fromkeys(word,"_") # map "_" to letters still hidden
for s in states[:-1]:
print(*s,sep='\n') # show gallow
while hidden: # uncover letters
mask = " ".join(hidden.get(c,c) for c in word)
letter = input(mask+" : ").upper() # get a letter
if letter not in hidden: break # bad letter -> for loop
del hidden[letter] # uncover good letter
else:
print(" ".join(word),"You win!!!") # no more hidden letters
break
print()
print(f"Letter {letter} not found") # bad letter -> next state
else:
print(*states[-1],sep='\n') # last state -> loss
print("You Lose !!!")
Sample run:
+-------+
| |
|
|
|
|
|
|
|
|
|
|
|\
| \____________
_ _ _ _ _ _ _ _ : e
E _ E _ _ _ _ _ : a
E _ E _ _ A _ _ : i
Letter I not found
+-------+
| |
| ^
| (' ')
| ~
|
|
|
|
|
|
|
|\
| \____________
E _ E _ _ A _ _ : t
E _ E _ _ A _ T : n
E _ E _ _ A N T : l
E L E _ _ A N T : g
Letter G not found
+-------+
| |
| ^
| (' ')
| ~
| / \
| | |
| ===
| [___]
|
|
|
|\
| \____________
E L E _ _ A N T : p
E L E P _ A N T : h
E L E P H A N T You win!!!