Question:
Repl link:
code snippet
I can’t get this code to stop looping with the correct answer:
https://replit.com/@hayataarrass/hangman#main.py
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")
limit = 5
play_game = ""
# 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
already_guessed = []
display = '_' * length
hangman(word, count, length, display, already_guessed)
# A loop to re-execute the game when the first round ends:
def play_loop():
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):
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, count, length, 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")
hangman(word, count, length, display, already_guessed)
elif guess in already_guessed:
print("You already used that letter.\n")
hangman(word, count, length, display, already_guessed)
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()
return
if word == '_' * length:
print("You're brilliant!! WINNER WINNER!!!")
play_loop()
exit()
elif count != limit:
hangman(word, count, length, display, already_guessed)
if __name__ == "__main__":
main()