Skip to content

Commit

Permalink
Code for the Hangman game
Browse files Browse the repository at this point in the history
  • Loading branch information
lpozo committed Sep 22, 2023
1 parent eab3d89 commit d373e96
Show file tree
Hide file tree
Showing 3 changed files with 385 additions and 0 deletions.
3 changes: 3 additions & 0 deletions hangman-tui/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Build a Hangman Game for the Command Line in Python

This folder provides the code examples for the Real Python tutorial [Build a Hangman Game for the Command Line in Python](https://realpython.com/python-hangman/).
182 changes: 182 additions & 0 deletions hangman-tui/source_code/hangman.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import string
from random import choice

MAX_INCORRECT_GUESSES = 6


def select_word():
with open("words.txt", mode="r") as words:
word_list = words.readlines()
return choice(word_list).strip()


def get_player_input(guessed_letters):
while True:
player_input = input("Guess a letter: ").lower()
if _validate_input(player_input, guessed_letters):
break
return player_input


def _validate_input(player_input, guessed_letters):
return (
len(player_input) == 1
and player_input in string.ascii_lowercase
and player_input not in guessed_letters
)


def join_guessed_letters(guessed_letters):
return " ".join(sorted(guessed_letters))


def build_guessed_word(target_word, guessed_letters):
current_letters = []
for letter in target_word:
if letter in guessed_letters:
current_letters.append(letter)
else:
current_letters.append("_")
return " ".join(current_letters)


def draw_hanged_man(wrong_guesses):
hanged_man = [
r"""
-----
| |
|
|
|
|
|
|
|
|
-------
""",
r"""
-----
| |
O |
|
|
|
|
|
|
|
-------
""",
r"""
-----
| |
O |
--- |
| |
| |
|
|
|
|
-------
""",
r"""
-----
| |
O |
--- |
/ | |
| |
|
|
|
|
-------
""",
r"""
-----
| |
O |
--- |
/ | \ |
| |
|
|
|
|
-------
""",
r"""
-----
| |
O |
--- |
/ | \ |
| |
--- |
/ |
| |
|
-------
""",
r"""
-----
| |
O |
--- |
/ | \ |
| |
--- |
/ \ |
| | |
|
-------
""",
]

print(hanged_man[wrong_guesses])


def game_over(wrong_guesses, target_word, guessed_letters):
if wrong_guesses == MAX_INCORRECT_GUESSES:
return True
if set(target_word) <= guessed_letters:
return True
return False


if __name__ == "__main__":
# Initial setup
target_word = select_word()
guessed_letters = set()
guessed_word = build_guessed_word(target_word, guessed_letters)
wrong_guesses = 0
print("Welcome to Hangman!")

# Game loop
while not game_over(wrong_guesses, target_word, guessed_letters):
draw_hanged_man(wrong_guesses)
print(f"Your word is: {guessed_word}")
print(
"Current guessed letters: "
f"{join_guessed_letters(guessed_letters)}\n"
)

player_guess = get_player_input(guessed_letters)
if player_guess in target_word:
print("Great guess!")
else:
print("Sorry, it's not there.")
wrong_guesses += 1

guessed_letters.add(player_guess)
guessed_word = build_guessed_word(target_word, guessed_letters)

# Game over
draw_hanged_man(wrong_guesses)
if wrong_guesses == MAX_INCORRECT_GUESSES:
print("Sorry, you lost!")
else:
print("Congrats! You did it!")
print(f"Your word was: {target_word}")
200 changes: 200 additions & 0 deletions hangman-tui/source_code/words.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
ugliest
close
dog
massive
hollow
cultured
seashore
explode
dizzy
minister
incompetent
thoughtless
harbor
messy
dance
children
zesty
clean
ball
nostalgic
plan
week
strap
board
slope
bat
steep
mourn
cat
girl
ancient
street
mice
dare
wasteful
tub
limping
whimsical
eager
eggs
detail
experience
beds
train
place
cows
admit
rare
respect
loose
group
enjoy
internal
macabre
imported
superb
crooked
confused
hug
feigned
unkempt
coal
meddle
hapless
country
zealous
sick
pray
lake
tiny
key
empty
labored
delirious
ants
need
omniscient
onerous
damp
subtract
sack
connection
toad
gather
record
new
trashy
flow
river
sparkling
kneel
daughter
glue
allow
raspy
eminent
weak
wrong
pretend
receipt
celery
plain
fire
heal
damaging
honorable
foot
ignorant
substance
box
crime
giant
learned
itchy
smoke
likeable
station
jaded
innocent
dead
straw
tray
chin
pack
geese
guess
wealthy
slippery
book
curly
swing
cure
flowers
rate
ignore
insidious
necessary
snakes
entertaining
rich
comb
lamentable
fuel
camera
multiply
army
exist
sulky
brief
worried
third
magical
wary
laborer
end
somber
authority
rainstorm
anxious
purpose
agreeable
spiky
toe
mixed
waiting
hungry
lopsided
flagrant
windy
ground
slap
please
white
hurry
governor
abandoned
reject
spiritual
abrasive
hunt
weather
endurable
hobbies
occur
bake
print
tire
juicy
blush
listen
trousers
daffy
scarecrow
rude
stem
bustling
nail
sneeze
bellicose
overdose

0 comments on commit d373e96

Please sign in to comment.