Quote of AWESOMENESS: “First, solve the problem. Then, write the code.” ~ John Johnson
Yup, I know, this is like the fourth blog in a row that relates to Python. BUT, it’s okay! This one is really fun. The program we will be making today is Hangman. The code is shown below:
import random
def print_game_rules(max_incorrect,word_len):
print("This game we will be playing hangman!")
def display_figure(bad_guesses):
gallows = (
"""
+----------+
|
|
|
|
|
================
""",
"""
+----------+
| o
|
|
|
|
================
""",
"""
+----------+
| o
| +---
|
|
|
================
""",
"""
+----------+
| o
| ---+---
|
|
|
================
""",
"""
+----------+
| o
| ---+---
| |
|
|
================
""",
"""
+----------+
| o
| ---+---
| |
| /
| /
================
""",
"""
+----------+
| o
| ---+---
| |
| / \
| / \
================
"""
)
print(gallows[bad_guesses])
return()
def prompt_for_letter():
print("")
player_guess = str(input("Guess a letter in the mystery word: "))
player_guess = player_guess.strip()
player_guess = player_guess.lower()
print("")
return(player_guess)
animal_words = ("horse", "mall", "desktop", "apple", "earth", "tree", "sun", "can", "love", "dog", "door", "house", "mansion", "beach", "computer", "window", "keyboard", "airplane", "hotel", "cat")
theword = random.choice(animal_words)
word_len = len(theword)
letterguess = word_len * ["_"]
max_incorrect = 6
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_tried = []
number_guesses = 0
letters_correct = 0
incorrect_guesses = 0
###############################
# PROCESSING SECTION
# Branching code: if/else
# Looping code: for-loop, while-loop
###############################
print("This game is hangman.")
while (incorrect_guesses != max_incorrect) and (letters_correct != word_len):
letter = prompt_for_letter()
if letter in alphabet:
if letter in letters_tried:
print("You already picked", letter)
else:
letters_tried.append(letter)
if theword.find(letter) == -1:
print("the letter", letter,"is not in the word")
incorrect_guesses += 1
print("***********************")
print(incorrect_guesses)
else:
print("the letter", letter,"is in the word")
for i in range(word_len):
if letter == theword[i]:
letterguess[i] = letter
letters_correct += 1
else:
pass
else:
print("Please guess a single letter in the alphabet.")
x = ""
print(x.join(letterguess))
a = ""
print("Letters tried so far: ", a.join(letters_tried))
if incorrect_guesses == max_incorrect:
print("Sorry, too many incorrect guesses. You are hanged.")
print("The word was", theword)
if letters_correct == word_len:
print("You guessed all the letters in the word!")
print("The word was", theword)
display_figure(incorrect_guesses)
Honestly, this was a challenging project at the start and I had quite a few obstacles that were highly annoying but eventually here we are!
Pssst, don’t forget to be awesome today.
Yours truly,
L.O.A.S.H
© Elizabeth Anne Villoria