If I play one round of the game and select the option to quit, the game finishes, BUT, if I play a second round and try to quit, the game continues and the user is prompted to enter a guess again, instead of terminating the game.
It seems to be stuck in a loop.
Here is my code:
from random import randint
def core_game():
def init_hangman():
hangman = []
for x in range(7):
hangman.append([" "] * 7)
hangman[0][0] = "_"
hangman[0][1] = "_"
hangman[0][2] = "_"
hangman[1][3] = "|"
return hangman
hangman = init_hangman()
def print_hangman():
for x in hangman:
print(str.join("", x))
def get_input(guess):
your_guess = input(guess)
if your_guess in guessed_letters:
print("You already guessed that letter!")
return get_input(guess)
elif your_guess.isalpha() and len(your_guess) == 1:
return your_guess
else:
print("Please guess a single letter!")
return get_input(guess)
words_list = ["monkey", "cow"]
city_list = ["Amarillo", "Houston"]
lists = ["animals", "cities"]
random_list = randint(0,1)
random_word = randint(0,1)
if lists[random_list] == "cities":
rand_list = city_list
elif lists[random_list] == "animals":
rand_list = words_list
word = rand_list[random_word]
guessed = ""
guessed_letters = []
hang = 6
Cont = True
for letter in word:
guessed += "-"
print("\n\n\nWELCOME TO HANGMAN!")
print("The category is: ", lists[random_list])
print("The secret word: ", guessed, "is", len(guessed), "letters")
while Cont:
your_guess = get_input("\nEnter your guess: ")
if your_guess in word.lower():
for x in range(len(word)):
if word[x].lower() == your_guess.lower():
guessed = guessed[:x] + word[x] + guessed[x+1:]
guessed_letters.append(your_guess)
print("\nThe secret word: ", guessed)
if guessed.lower() == word.lower():
print("\n\nCongratulations, you guessed the word!")
play_again = input("\nWould you like to play again?(y/n) ")
if play_again == "y" or play_again == "yes":
core_game()
else:
Cont = False
else:
hang -= 1
guessed_letters.append(your_guess)
print("\nGuessed letters: ", guessed_letters)
if hang == 5:
hangman[2][3] = "O"
print_hangman()
print(guessed)
elif hang == 4:
hangman[3][3] = "|"
print_hangman()
print(guessed)
elif hang == 3:
hangman[3][2] = "-"
print_hangman()
print(guessed)
elif hang == 2:
hangman[3][4] = "-"
print_hangman()
print(guessed)
elif hang == 1:
hangman[4][2] = "/"
print_hangman()
print(guessed)
elif hang == 0:
hangman[4][4] = "\\"
print_hangman()
print("Game Over!")
print("The word was: ", word)
play_again = input("Would you like to play again?(y/n) ")
if play_again == "y" or play_again == "yes":
core_game()
else:
Cont = False
core_game()
The main function is core_game() and this is called when the program is run.
Okay- yes, I like the game- played it in the browser at trinket.io
Then I walked through an entire game here. Use this to debug your code, step by step and you can view all of the variables, lists etc. as well as enter input and view output.
The reason that your game is repeating is because:
1) In the function core_game you have the following code:
if play_again == "y" or play_again == "yes":
core_game()
This means that when you select yes after the first game, you are opening another "instance" of the function- you can see this if you trace through the code. You can also see this in the screenshot below (f19).
2) after you play the second game (remember that the first instance is still open) and select "n", this causes the "Cont" variable to change to False, but only in the second instance. The "while" is closed then, and the code goes back to the first instance where Cont is still True. You can also see both instances in the screenshot, and the state of each value of "Cont". The closed frame is "greyed out".
3) The program resumes in the first instance of the core_game at the start of the while loop, and the user is prompted to enter a guess.
This is difficult to see until you trace through the code, but I have included a snapshot here where you can (I hope) see what I mean.
So the issue is that you are calling the function from within itself.
Consider something more like this:
def core_game():
print("I was called")
while Cont:
ans = ("Do you wish to play a game? (Y/N)")
if ans[0].lower() == "y": # works for Y, y, Yup, Yeah, Yes etc.
core_game()
else:
Cont = False
PS
there are other really good reference sources out there, such as this as well.
Never give up- you'll find the step-thru really handy, and you might try Rice Universities MOOC on Coursera at some later stage.
Related
I'm trying to link my ask_for_name() and menu() functions to my play() function but where
ever I place the function headings it doesn't seem to work or get called. The game starts up first and at the end of gameplay asks if you want to restart, yes or no, If you click no, it goes back to what I want at the beginning of my game, my user-input asking for name and the menu, press 1 to play the game and 2 for instructions. When I click 1 the game wont start and throws an error message, does anyone know what I'm missing here? I'm new to python and seem to keep going in circles with this problem, the code is mentioned below:
def ask_for_name():
while True:
name = input(YELLOW_COLOR + "Please Enter Your Name:\n")
if not name.isalpha():
print("Name must be letters only\n")
else:
print(f"Hello {name}, Welcome to Chris's Hangman and Good Luck!\n")
menu()
return name
def menu():
"""
menu function which gives the user two options
- Press 1 to play or 2 for instructions
- only accepts valid keys or error message comes up
"""
while True:
user_input = input("Press P to Play game\nPress I for Instructions\n").upper()
if user_input == "P":
play()
elif user_input == "I":
print(
"1.The computer will generate a random word and it's\n"
"your task to guess the letters from the word.\n"
"2.To guess, type a letter of your choice and hit enter.\n"
"3.If you guess correctly, the letter will be revealed.\n"
"4.If you guess incorrectly, you will lose a life and \n"
" the Hangman will start to appear.\n"
"5.You have 8 lives to guess the correct word.\n"
"Good Luck!\n")
enter_input = input("Press Enter to go back to the menu\n").upper()
if enter_input == "":
menu()
else:
print(RED_COLOR + "Oops look's like you pressed the wrong key!\n")
else:
print("Invalid Character, please try again!\n")
word = "dog" #random.choice(WORDS)
word = word.upper()
reveal = list(len(word)*'_')
lives = 8
game_is_won = False
def check_letter(letter, word):
global reveal
for i in range(0,len(word)):
letter = word[i]
if guess == letter:
reveal[i] = guess
if '_' not in reveal:
return True
else:
return False
def restart_game():
"""
Gives player option to restart, otherwise returns to menu
"""
game_restart = False
while not game_restart:
restart = input("Would you like to play again?"
"Y/N").upper()
try:
if restart == "Y":
game_restart = True
play()
elif restart == "N":
game_restart = True
print("\n")
header()
ask_for_name()
menu()
else:
raise ValueError(
"You must type in Y or N"
)
except ValueError as e:
print("\n You must type in Y or N Please try again.\n")
def play():
os.system("clear")
header()
print(hangman[8-lives])
print(' '.join([str(e) for e in reveal]))
print(f"You have {lives} lives")
while game_is_won == False and lives > 0:
play()
guess = input('Guess a letter or an entire word:')
guess = guess.upper()
if guess == word:
game_is_won = True
reveal = word
elif len(guess) == 1 and guess in word:
game_is_won = check_letter(guess, word)
else:
lives -= 1
if game_is_won:
player_won()
print("WELL DONE")
else:
player_lost()
print(f"YOU FAILED the word was: {word}")
restart_game()
Since there were portions of the game program missing, I filled in the missing bits with some placeholder functions. After trying out the game and seeing where it appeared to get stuck, I made some tweaks to it to make it function in the spirit of a hangman game. Following is the tweaked code for your analysis.
import os
word = "dog" #random.choice(WORDS)
word = word.upper()
reveal = list(len(word)*'_')
lives = 8
game_is_won = False
hangman = [] # Added this so as to make the game work - temporary
for g in range(0,8):
hangman.append('-')
def header():
return
def ask_for_name():
while True:
name = input("Please Enter Your Name:\n")
if not name.isalpha():
print("Name must be letters only\n")
else:
print(f"Hello {name}, Welcome to Chris's Hangman and Good Luck!\n")
menu()
break # Added this to get out of the while loop
return name
def menu():
while True:
user_input = input("Press P to Play game\nPress I for Instructions\n").upper()
if user_input == "P":
lives = 8
game_is_won = False
break
elif user_input == "I":
print("1.The computer will generate a random word and it's\n"
"your task to guess the letters from the word.\n"
"2.To guess, type a letter of your choice and hit enter.\n"
"3.If you guess correctly, the letter will be revealed.\n"
"4.If you guess incorrectly, you will lose a life and \n"
" the Hangman will start to appear.\n"
"5.You have 8 lives to guess the correct word.\n"
"Good Luck!\n")
enter_input = input("Press Enter to go back to the menu\n").upper()
if enter_input == "":
pass
#menu()
else:
print("Oops look's like you pressed the wrong key!\n")
else:
print("Invalid Character, please try again!\n")
def check_letter(guess, word):
global reveal
for i in range(0,len(word)):
letter = str(word[i])
if guess == letter:
reveal[i] = guess
if '_' not in reveal:
return True
else:
return False
def restart_game(): # Added return of decision
"""
Gives player option to restart, otherwise returns to menu
"""
game_restart = False
while not game_restart:
restart = input("Would you like to play again?" "Y/N/Q ").upper() # Added a quit option
try:
if restart == "Y":
return True
elif restart == "N":
game_restart = True
print("\n")
header()
ask_for_name()
#menu()
return True
elif restart == "Q":
return False
else:
raise ValueError("You must type in Y or N")
except ValueError as e:
print("\n You must type in Y or N Please try again.\n")
def player_won(): # Added this to make the game work
print("Yea!")
return
def player_lost(): # Added this to make the game work
print("Boohoo")
return
def play():
os.system("clear")
header()
print(hangman[8-lives])
print(' '.join([str(e) for e in reveal]))
print(f"You have {lives} lives")
header()
ask_for_name()
while game_is_won == False and lives > 0:
play()
guess = input('Guess a letter or an entire word:')
guess = guess.upper()
if guess == word:
game_is_won = True
reveal = word
elif len(guess) == 1 and guess in word:
game_is_won = check_letter(guess, word)
else:
lives -= 1
if game_is_won:
player_won()
print("WELL DONE")
else:
if lives <= 0:
player_lost()
print(f"YOU FAILED the word was: {word}")
if game_is_won == True or lives <=0: # Conditioned restart
if restart_game() == True:
game_is_won = False
lives = 8
reveal = list(len(word)*'_')
The key bits were adjusting some of the "if" tests to allow for life decrements, prompting for a name, prompting the menu, and restarts.
Here is a quick sample at the terminal.
-
_ _ _
You have 8 lives
Guess a letter or an entire word:Dog
Yea!
WELL DONE
Would you like to play again?Y/N/Q Q
Give those a try.
i would like to know how to tell the computer to print different input for player using hint
and for someone who doesn't used it to congratulate them
import random
words = dict(
python = "type of snake",
honda = "type of car",
spanish = "type of language",)
word = list(words)
var = random.choice(word)
score = 0
chance = 5
x = list(var)
random.shuffle(x)
jumble = "".join(x)
print("the jumble word is :", jumble,)
while True:
guess = input(" this is my guess :")
if guess == "hint":
print(words[var])
if guess == var:
print("well done you only used ", score,"to guessed it ")
break
else:
print("try again")
score +=1
if score == chance:
print("better luck next time")
break
What about adding a boolean, say hintUsed, that keeps track of whether or not the user used a hint:
hintUsed = False
while True:
guess = input(" this is my guess :")
if guess == "hint":
hintUsed = True # change hintUsed to True !!
print(words[var])
And then, to congratulate:
if guess == var:
if hintUsed:
#print a message
else:
#print another message
break
I'm a very new programmer(started less than a month ago). I really need some help with this.
Sorry if it's a bit long...
How this works is that my guesses go down every time I get something wrong(pretty obvious). Or it is supposed to, anyway.
This is a program I created as a prototype for a hangman project. Once I get this right, I'll be able to attempt the bigger project. Tell me if the full command above works differently for you or if you have any suggestion as to how to make it shorter or better or it's too early for me to attempt a project as big as this. Thank you!
import random
player_name = input("What is your name? ")
print("Good luck, " + player_name + "!")
words = ["program", "giraffe", "python", "lesson", "rainbows", "unicorns", "keys", "exercise"]
guess = " "
repeat = True
word = random.choice(words)
guesses = int(len(word))
while repeat is True:
print("The word is " + str(len(word)) + " characters long.")
guess = input("Enter your guess: ")
if guess != word:
guesses -= 1
print("Incorrect")
print("Try again")
elif guess == word:
print("Good job!")
print(str.capitalize(word) + " is the right answer!")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
word = random.choice(words)
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
if guesses == 1:
print("You only have one chance left.")
if guesses <= 0:
print("You lose...")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
the issue is with the scope of your conditionals
while repeat is True:
print("The word is " + str(len(word)) + " characters long.")
guess = input("Enter your guess: ")
if guess != word:
guesses -= 1
print("Incorrect")
print("Try again")
elif guess == word:
print("Good job!")
print(str.capitalize(word) + " is the right answer!")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
word = random.choice(words)
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
if guesses == 1:
print("You only have one chance left.")
if guesses <= 0:
print("You lose...")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
this will fix the guesses issue, but you'll need to refactor the play-again logic.
Something like this
repeat = True
gameOver = False
while repeat is True:
print("The word is " + str(len(word)) + " characters long.")
guess = input("Enter your guess: ")
if guess != word:
guesses -= 1
print("Incorrect")
print("Try again")
elif guess == word:
print("Good job!")
print(str.capitalize(word) + " is the right answer!")
gameOver = True
if guesses == 1:
print("You only have one chance left.")
if guesses <= 0:
print("You lose...")
gameOver = True
if gameOver:
playAgain = input("Do you want to play again? (input Yes/No)")
if playAgain == "Yes" or "yes":
word = random.choice(words)
repeat = True
gameOver = False
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
What i want to accomplish is when you input a letter and if the letter is correct there will be an automatic response that it was correct but it will not be the same response every time a letter of the correct answer inputted.
I made a list of responses and placed a random function for the list
reaction=['good job','lucky guess!',you\'re on a roll]
react=random.choice(reaction)
I tried placing it after the
for letter in rand:
rand_list.append(letter)
but this is not what I want because what this does is it gives the same response over and over again on each correct letter you input and would change at the next word that you'll be guessing.
The complete code is:
import random
alphabeth = 'abcdefghijklmnopqrstuvwxyz'
rand_list = []
guessed_list = []
def prepWord():
global rand, guessed_list, blank, rand_list,good,react_good
react_good = ['Good job!', 'Lucky guess!', 'Took you a while to guess that letter!', 'You\'re on a roll!']
words = ['note', 'pencil', 'paper','foo']
rand = random.choice(words)
guessed_list = []
blank = ['_']*len(rand)
rand_list = []
for letter in rand:
rand_list.append(letter)
startPlay()
def startPlay():
print('Welcome to Hangman. You have 8 tires to guess the secret word.')
gameQ = input('Ready to play Hangman? y or n: ')
if gameQ == 'y' or gameQ == 'Y':
print('Guess the letters:')
print(blank)
checkAnswer()
elif gameQ == 'n' or gameQ == 'N':
print('goodbye')
print('*********************')
else:
print('Invalid answer. Please try again')
startPlay()
def playAgain():
again = input('Would you like to play again? y or n --> ')
if again == 'y':
prepWord()
elif again == 'n':
print('Thanks for playing')
else:
print('Invalid answer. Please type y or n only')
print(' ')
playAgain()
def checkAnswer():
tries = 0
x = True
while x:
answer = input('').lower()
if answer not in guessed_list:
guessed_list.append(answer)
if len(answer)>1:
print('One letter at a time.')
elif answer not in alphabeth:
print('Invalid character, please try again.')
else:
if answer in rand:
print("The letter {} is in the word.".format(answer))
indices = [b for b, letter in enumerate(rand_list) if letter == answer]
for b in indices:
blank[b] = answer
print (blank)
else:
print ("I'm sorry the letter {} is not in the word. Please try again.".format(answer))
tries +=1
if tries
if tries == 8:
print('Game over. You are out of tries')
playAgain()
else:
print('Letter {} already used. Try another.'.format(answer))
if '_' not in blank:
print('You guessed the secret word. You win!')
final_word = 'The secret word is '
for letter in blank:
final_word += letter.upper()
print(final_word)
print('')
x = False
playAgain()
prepWord()
You have to call random each time you want a new message. Calling it once and saving the result means your react variable never changes. The following defines the reaction list at the top for easy editing, but has this line in checkAnswer() that calls random.choice every time a correct letter is entered print(random.choice(reaction)).
import random
alphabeth = 'abcdefghijklmnopqrstuvwxyz'
rand_list = []
guessed_list = []
reaction=["good job","lucky guess!","you're on a roll"]
def prepWord():
global rand, guessed_list, blank, rand_list,good,react_good
react_good = ['Good job!', 'Lucky guess!', 'Took you a while to guess that letter!', 'You\'re on a roll!']
words = ['note', 'pencil', 'paper','foo']
rand = random.choice(words)
guessed_list = []
blank = ['_']*len(rand)
rand_list = []
for letter in rand:
rand_list.append(letter)
startPlay()
def startPlay():
print('Welcome to Hangman. You have 8 tires to guess the secret word.')
gameQ = input('Ready to play Hangman? y or n: ')
if gameQ == 'y' or gameQ == 'Y':
print('Guess the letters:')
print(blank)
checkAnswer()
elif gameQ == 'n' or gameQ == 'N':
print('goodbye')
print('*********************')
else:
print('Invalid answer. Please try again')
startPlay()
def playAgain():
again = input('Would you like to play again? y or n --> ')
if again == 'y':
prepWord()
elif again == 'n':
print('Thanks for playing')
else:
print('Invalid answer. Please type y or n only')
print(' ')
playAgain()
def checkAnswer():
tries = 0
x = True
while x:
answer = input('').lower()
if answer not in guessed_list:
guessed_list.append(answer)
if len(answer)>1:
print('One letter at a time.')
elif answer not in alphabeth:
print('Invalid character, please try again.')
else:
if answer in rand:
print("The letter {} is in the word.".format(answer))
print(random.choice(reaction))
indices = [b for b, letter in enumerate(rand_list) if letter == answer]
for b in indices:
blank[b] = answer
print (blank)
else:
print ("I'm sorry the letter {} is not in the word. Please try again.".format(answer))
tries +=1
if tries == 8:
print('Game over. You are out of tries')
playAgain()
else:
print('Letter {} already used. Try another.'.format(answer))
if '_' not in blank:
print('You guessed the secret word. You win!')
final_word = 'The secret word is '
for letter in blank:
final_word += letter.upper()
print(final_word)
print('')
x = False
playAgain()
prepWord()
I rewrote some of your code. I'm posting it here so hopefully looking at the difference will be helpful to you. Some of the changes are:
No recursion: while it can be very powerful, it's usually safer to use a loop. For example in startPlay() every time the user enters an invalid character you open another nested startPlay() function. This could lead to many nested functions loaded at once. Worse startPlay() can call checkAnswer() which can call playAgain() which can call prepWord() which can call startPlay(). The longer the user plays, the more memory your program will take. It will eventually crash.
No global variables that change. While defining global variables at the top of the script can be useful, calling globals and editing them in a function is risky and makes your code harder to debug and reuse. It's better to pass what is needed from function to function. Some might argue against defining any variables at the top, but I find it useful. Especially if someone else will customize the details, but does not need to understand how the code works.
Some details working with lists and strings are different. You don't need to define the alphabet, that already exists as string.ascii_lowercase. You can check for characters in a string directly with the equivalent of if 'p' in 'python': so you never have to convert the chosen word into a list. You can covert lists back to strings with join like " ".join(blank) which converts blank from a list to a string with a space between each element of blank. Using a different string before the join would change the character inserted between each element.
I hope this helps you. You can do whatever you want with this code:
import random
import string
# Global and on top for easy editing, not changed in any function
words = ['note', 'pencil', 'paper','foo']
react_good = ["Good job!",
"Lucky guess!",
"Took you a while to guess that letter!",
"You're on a roll!"]
def game():
games = 0
while start(games): # Checks if they want to play.
games += 1
play_game()
def play_game(): # returns True if won and returns False if lost.
rand_word = random.choice(words) # Choose the word to use.
blank = ['_']*len(rand_word)
guessed = []
tries = 0
while True: # Not infinite, ends when a return statement is called
print("")
print(" ".join(blank)) # Converting to string first looks better
answer = input('Guess a letter: ').strip().lower() # remove whitespace
if answer == 'exit' or answer == 'quit':
return False # Exit Game
elif len(answer) != 1:
print('One letter at a time.')
elif answer not in string.ascii_lowercase: # same as alphabet string
print('Invalid character, please try again.')
elif answer in guessed:
print('Letter {} already used. Try another.'.format(answer))
elif answer in rand_word: # Correct Guess
# Update progress
indices = [i for i, x in enumerate(rand_word) if x == answer]
for i in indices:
blank[i] = answer
# Check if they have won
if blank == list(rand_word): # Or could convert blank to a string
print('You guessed the secret word. You win!')
print('The secret word is ' + rand_word.upper())
print('')
return True # Exit Game
guessed.append(answer)
print("The letter {} is in the word.".format(answer))
print(random.choice(react_good))
else: # Incorrect Guess
tries += 1
# Check if they have lost.
if tries >= 8:
print('Game over. You are out of tries')
return False # Exit Game
print ("I'm sorry the letter {} is not in the word. Please try again.".format(answer))
guessed.append(answer)
def start(games = 0): # Gives different messages for first time
if games == 0: # If first time
print('Welcome to Hangman. You have 8 tires to guess the secret word.')
# Loops until they give a valid answer and a return statement is called
while True:
# Get answer
if games > 0: # or just 'if games' works too
game_q = input('Would you like to play again? y or n --> ')
else:
game_q = input('Ready to play Hangman? y or n: ')
# Check answer
if game_q.lower() == 'y':
return True
elif game_q.lower() == 'n':
if games > 0:
print('Thanks for playing')
else:
print('goodbye')
print('*********************')
return False
else:
print('Invalid answer. Please try again')
game()
I'm creating a hangman game in Python 3.5.1 and everything is going well except for when it comes to the guessing part. I print "Hurray" when the letter is guessed correctly and I have it draw an additional body part when it is not guessed correctly. My problem is that even when a letter is guessed correctly it will also draw another body part:
import drawHangman
import turtle
import random
def main():
window = turtle.Screen()
window.setup(400, 400, 200, 200)
HG = turtle.Turtle()
drawHangman.default(HG)
wrongGuess = 0
maxGuesses = 0
lines = open('wordlist.txt').read().splitlines()
myline =random.choice(lines)
print(myline)
name = input("Welcome to hangman! What is your name? \n")
print("Welcome", name + "! \n The rules are as follows: \n 1) No looking at answer list! \n 2) Do not have fun!! \n 3) No hacking my game!")
tos = input("Do you accept the rules provided above? Type Yes or No. \n")
if tos == "no":
print("Who cares! The rules suck anyways!")
elif tos == "yes":
print("HI")
else:
print("You don't listen very well. I guess proceed ugh")
while maxGuesses < 6:
guess = input("Please input your guess!")
maxGuesses += 1
for char in myline:
if char in guess:
print("Hurray")
else:
wrongGuess += 1
print("You have", 6 - maxGuesses, "guesses left!")
if wrongGuess == 1:
drawHangman.drawHead(HG)
elif wrongGuess == 2:
drawHangman.drawBody(HG)
elif wrongGuess == 3:
drawHangman.drawLeftArm(HG)
elif wrongGuess == 4:
drawHangman.drawRightArm(HG)
elif wrongGuess == 5:
drawHangman.drawLeftLeg(HG)
elif wrongGuess == 6:
drawHangman.drawRightLeg(HG)
else:
playAgain = input('Do you want to play again? (yes or no)')
if playAgain == "yes":
drawHangman.reset(HG)
main()
else:
print("Thanks for playing!")
return
main()
I know it has something to do with the part where else tells it there is a wrong letter but I can't figure it out. I've tried indenting it one more space, but that just prints the amount of guesses left. Any help is appreciated.
PS. The drawHangman.* routines come from a file I have in my src folder that contains body parts.
You have indented the else clause (and the following lines) incorrectly - it's in the scope of the for loop instead of the if statement:
for char in myline:
if char in guess:
print("Hurray")
else:
wrongGuess += 1
print("You have", 6 - maxGuesses, "guesses left!")
if wrongGuess == 1:
drawHangman.drawHead(HG)
# etc.
As you wrote it, the else clause and all the drawings are executed only after the entire for loop has finished.
Besides the problem raised in your question, there seem to be other issues with your code: your logic assumes/hardcodes 6 letter words; you're repeat game logic is actually recursive; you don't close the words file after you're finished with it; your yes/no question handling isn't robust; you repeat things, by recalling main(), that need only be done once; you don't display the current correct/unknown letter status.
Below is a rework of your code to address these issues and play an actual game of hangman:
from turtle import Turtle, Screen
import random
import drawHangman
BODY_PARTS = [ \
drawHangman.drawHead, drawHangman.drawBody, drawHangman.drawLeftArm, \
drawHangman.drawRightArm, drawHangman.drawLeftLeg, drawHangman.drawRightLeg, \
]
MAXIMUM_WRONG_GUESSES = len(BODY_PARTS)
def hangman(HG):
drawHangman.default(HG)
with open('wordlist.txt') as file:
lines = file.read().splitlines()
word = random.choice(lines)
letters = set(word)
wrongGuesses = 0
while letters and wrongGuesses < MAXIMUM_WRONG_GUESSES:
for letter in word:
print("*" if letter in letters else letter, end="")
print(".")
letter = input("Please input your guess: ")
if letter in letters:
print("Hurray!")
letters.remove(letter)
else:
BODY_PARTS[wrongGuesses](HG)
wrongGuesses += 1
print("You have", MAXIMUM_WRONG_GUESSES - wrongGuesses, "guesses left!")
def main():
screen = Screen()
screen.setup(400, 400, 200, 200)
turtle = Turtle()
playAgain = True
print("Welcome to hangman!")
name = input("Enter your name: ")
print("Welcome", name + "!")
print("The rules are as follows:")
print(" 1) No looking at answer list!")
print(" 2) Do not have fun!!")
print(" 3) No hacking my game!")
tos = input("Do you accept the rules provided above? (yes or no): ")
if tos.lower().startswith("n"):
print("Who cares! The rules suck anyways!")
elif tos.lower().startswith("y"):
print("Hi")
else:
print("You don't listen very well. I guess proceed ugh")
while playAgain:
hangman(turtle)
answer = input('Do you want to play again? (yes or no): ')
playAgain = answer.lower().startswith("y")
if playAgain:
drawHangman.reset(turtle)
else:
print("Thanks for playing!")
main()