Question:
Repl link:
Hi! I’m a beginner in Python and trying to write a code for a hangman game but I’m having trouble running it. The code will run but won’t loop and I’m not seeing what I’m doing wrong. Could someone help me fix my code?
import random
# Initial Steps to invite in the game:
print("Let's play hangman!")
print("You only have 5 tries, but I believe in you.")
print("\nGood luck!\n")
# The parameters we require to execute the game:
def main():
words_to_guess = ["ceramic","house","after","gift","please","about","tofu","angry","mound","sauce"
,"cat", "music", "paint", "choice", "move", "desk", "greatly"]
word = random.choice(words_to_guess)
length = len(word)
count = 0
limit = 5
already_guessed = []
display = '_' * length
play_game = ""
# A loop to re-execute the game when the first round ends:
def play_loop(play_game):
play_game = ""
play_game = input("Try again? y = yes, n = no \n")
while play_game not in ["y", "n","Y","N"]:
play_game = input("Try again? y = yes, n = no \n")
if play_game == "y":
main()
elif play_game == "n":
print("Sore loser!")
exit()
# Initializing all the conditions required for the game:
def hangman(word, count, length, display, already_guessed):
limit = 5
already_guessed = []
display = '_' * length
count = 0
guess = input("I've chosen this word: " + display + " guess another letter if you dare: \n")
guess = guess.strip()
if len(guess.strip()) == 0 or len(guess.strip()) >= 2 or guess <= "9":
print("You gotta choose a letter, dummy.\n")
hangman(word, length, count, display, already_guessed)
elif guess in word:
already_guessed.extend([guess])
index = word.find(guess)
word = word[:index] + "_" + word[index + 1:]
display = display[:index] + guess + display[index + 1:]
print(display + "\n")
elif guess in already_guessed:
print("You already used that letter.\n")
else:
count += 1
if count == 1:
print(" _____ \n"
" | \n"
" | \n"
" | \n"
" | \n"
" | \n"
" | \n"
"__|__\n")
print("Nah! Guess again\n")
elif count == 2:
print(" _____ \n"
" | | \n"
" | |\n"
" | \n"
" | \n"
" | \n"
" | \n"
"__|__\n")
print("Wrong! Guess again\n")
elif count == 3:
print(" _____ \n"
" | | \n"
" | |\n"
" | | \n"
" | \n"
" | \n"
" | \n"
"__|__\n")
print("Still wrong. Guess again\n")
elif count == 4:
print(" _____ \n"
" | | \n"
" | |\n"
" | | \n"
" | O \n"
" | \n"
" | \n"
"__|__\n")
print("Wow you're not good at this. Uh oh, last try.\n")
elif count == 5:
print(" _____ \n"
" | | \n"
" | |\n"
" | | \n"
" | O \n"
" | /|\ \n"
" | / \ \n"
"__|__\n")
print("So wrong, RIP hangman. Better luck next time?\n")
print("The word we chose was:", already_guessed, word)
play_loop()
if word == '_' * length:
print("You're brilliant!! WINNER WINNER!!!")
play_loop()
elif count != limit:
hangman(word, count, length, display, already_guessed)
if __name__ == "__main__":
main()