Hangman drawing regardless of correct letters (Python, turtle) - python

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()

Related

Trying to link my user name input and menu to my game function in python hangman

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.

Basic Python while/for question. Can't break out of a loop

Every function is working but can't quite get out of this whole function. even though I use break, something is not working. help, please.
def start():
wizard = "Wizard"
elf = "Elf"
human = "Human"
orc = "Orc"
wizard_hp = 70
elf_hp = 100
human_hp = 150
orc_hp = 400
wizard_damage = 150
elf_damage = 100
human_damage = 20
orc_damage = 200
dragon_hp = 300
dragon_damage = 50
while True:
print("✰✰ Welcome to the game ✰✰\n")
print("1) Wizard ")
print("2) Elf ")
print("3) Human ")
print("4) Orc ")
character = input("Choose your character: ").lower()
if character == "1" or character == "wizard":
character = wizard
my_hp = wizard_hp
my_damage = wizard_damage
break
elif character == "2" or character == "elf":
character = elf
my_hp = elf_hp
my_damage = elf_damage
break
elif character == "3" or character == "human":
character = human
my_hp = human_hp
my_damage = human_damage
break
elif character == "4" or character == "orc":
character = orc
my_hp = orc_hp
my_damage = orc_damage
break
else:
print("\n- Unknown Character \n")
break
print("\nYou have chosen the character: ", character)
print("\n- Health: ", my_hp)
print("- Damage: ", my_damage, "\n")
while True:
dragon_hp =- my_damage
print("The", character, "damaged the Dragon!")
print(f"The {character}'s hitpoints are now: {my_hp} \n")
if dragon_hp <= 0:
print("The Dragon has lost the battle", "\n")
my_hp =- dragon_damage
print("The Dragon strikes back at", character)
print("The Dragon's hitpoints are now: ", dragon_hp, "\n")
if my_hp <= 0:
print("You have lost your battle! ", "\n")
play_again = input("Do you want to play again? Type Yes or No: ").lower()
while True:
if play_again == "1" or "yes":
print("\n") # even if you only put start(); on line 80, the line 81 and 83 is reading line 80(start(;)) for some reasons
start();
elif play_again == "2" or "no":
break
else:
break
break
start();
This is just basic python stuff that I'm trying to get started. I know I'm missing a small thing but quiet cannot get to the result.
On the very last while loop, It has Its comment in it. please read it for an additional explanation
Two separate things:
Your logic at the very end is actually always True because you forgot to add or play_again == "yes.
Right now your game asks if the user wants to play again after every single turn. Your check to play again should be tabbed in, so that it only executes one time after the game is played, not after each time.
When you're comparing statements, Python will attempt to make your values booleans. So, it will execute bool(insert-statement-here). So, at the very end, your comparison, if play_again == "1" or "yes": is actually two parts.
bool(if play_again == "1") - this has a value. It depends on if they put in play_again.
bool("yes") - this is ALWAYS true. Since this is always true, your code will always enter this block.
Your head is in the right place, you should do:
if play_again == "1" or play_again == "yes":
print("\n") # even if you only put start(); on line 80, the line 81 and 83 is reading line 80(start(;)) for some reasons
elif play_again == "2" or play_again == "no":
break
else:
break
I think you're displaying the health backwards as well. After the dragon strikes, you should display the character's health, not the dragon's. This is a long answer, but I think it resolves several of the issues you're encountering. You are definitely very close, but try to slow down just a bit. Your code will only be as clear as your thoughts on the problem - not more. You only need the playing of the game to be on a while true, everything else is just configuration, which can be done up front when the game starts. The "playing of the game" - which is the "damaging going back and forth" is the only thing that needs to be in the while.
def start():
wizard = "Wizard"
elf = "Elf"
human = "Human"
orc = "Orc"
wizard_hp = 70
elf_hp = 100
human_hp = 150
orc_hp = 400
wizard_damage = 150
elf_damage = 100
human_damage = 20
orc_damage = 200
dragon_hp = 300
dragon_damage = 50
print("✰✰ Welcome to the game ✰✰\n")
print("1) Wizard ")
print("2) Elf ")
print("3) Human ")
print("4) Orc ")
character = input("Choose your character: ").lower()
if character == "1" or character == "wizard":
character = wizard
my_hp = wizard_hp
my_damage = wizard_damage
elif character == "2" or character == "elf":
character = elf
my_hp = elf_hp
my_damage = elf_damage
elif character == "3" or character == "human":
character = human
my_hp = human_hp
my_damage = human_damage
elif character == "4" or character == "orc":
character = orc
my_hp = orc_hp
my_damage = orc_damage
else:
print("\n- Unknown Character \n")
return
print("\nYou have chosen the character: ", character)
print("\n- Health: ", my_hp)
print("- Damage: ", my_damage, "\n")
while True:
dragon_hp -= my_damage
print("The", character, "damaged the Dragon!")
print("The Dragon's hitpoints are now: ", dragon_hp, "\n")
if dragon_hp <= 0:
print("The Dragon has lost the battle", "\n")
play_again = input("Do you want to play again? Type Yes or No: ").lower()
break
my_hp -= dragon_damage
print("The Dragon strikes back at", character)
print(f"The {character}'s hitpoints are now: {my_hp} \n")
if my_hp <= 0:
print("You have lost your battle! ", "\n")
play_again = input("Do you want to play again? Type Yes or No: ").lower()
break
if play_again == "1" or play_again == "yes":
print(
"\n") # even if you only put start(); on line 80, the line 81 and 83 is reading line 80(start(;)) for some reasons
start()
start()

I created a guessing game and I can't understand why my -= command function doesn't work

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

Creating a guessing game in Python using while and for loops

I am trying to make a guess game. I've used while, if, elif, and else statements but I'm stuck on how to use for and while loops as well as randomizing single hints and single answers from a nested lists.
black_box = ["guam","lakers","flash","buddha","drake","fortnite","annabelle","xmen","mars","dad"]
nested_list = [["island","yigo","cocos","kelaguen"],["kobe","la","magic","lebron"],["scarlet","speedster","dc","ezra"], ["asiangod","meditation","monk","enlightenment"],["rapper","onedance","canadian","raptors"],["game","epic","notminecraft","dances"],["doll","conjuring","soultaker","creation"],["wolverine","mystique","magneto","apocalypse"],["red","fourth","planet","ares"], ["man","american","peter","lionking"]]
i = random.randint(0,9)
word = black_box[i]
hint = nested_list[i]
print("Guess the word with the following hint: ", hint, "you have 4 tries.")
numofguesses = 0
guess = input("What is the word? ")
while numofguesses < 4:
numofguesses = numofguesses + 1
if guess == word:
print("You win!")
option = input("Do you want to try again or quit? ")
if option == "try again":
print("")
elif option == "quit":
break
if guess != word:
print("Try again!")
guess = input("What is the word? ")
if guess != word:
print("Try again!")
guess = input("What is the word? ")
I expected to get a line of code that prints "Try again!" but it skipped and started to print "What is the word? " print("Guess the word with the following hint: ", hint, "you have 4 tries.") Originally, I used hint[i] which printed out only one hint in the nested list but then I tried to run the program again but I got an error saying, "list index is out of range.
Your condition checks and loops where not correct. Try the below code, it should work fine.
black_box = ["guam","lakers","flash","buddha","drake","fortnite","annabelle","xmen","mars","dad"]
nested_list = [["island","yigo","cocos","kelaguen"],["kobe","la","magic","lebron"],["scarlet","speedster","dc","ezra"], ["asiangod","meditation","monk","enlightenment"],["rapper","onedance","canadian","raptors"],["game","epic","notminecraft","dances"],["doll","conjuring","soultaker","creation"],["wolverine","mystique","magneto","apocalypse"],["red","fourth","planet","ares"], ["man","american","peter","lionking"]]
while True:
i = random.randint(0, 9)
word = black_box[i]
numofguesses = 0
while numofguesses < 4:
hint = nested_list[i][numofguesses]
print("Guess the word with the following hint: ", hint, ". You have ", 4 - numofguesses, " tries!")
guess = input("What is the word? ")
numofguesses = numofguesses + 1
if guess == word:
print("You win!")
break
if guess != word:
print("Try again!")
option = input("Do you want to try again or quit? ")
if option == "try again":
print("")
else:
break

hangman game in python after trying to exit after playing one round

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.

Categories

Resources