Loop breaks without executing the last print statement - python

I've written a hangman program in python. The program is finished, but I have a problem with my main function. If I set a win or loss, it no longer execute my print statements from before. This means that if I have to guess a word, for example, it doesn't fill in the last letter in the placeholder, it just breaks out the loop without filling in the last letter. The same goes with my hangman. If I don't have any more attempts left, it won't finish drawing my hangman (just leave out the last part). Who knows why that is? Please help
Here is my code:
##### HANGMAN IN PYTHON #####
count_attempts = 0
guess_word = []
def guidance():
print('Welcome to Hangman in Python!')
print('''The point here is to guess a word by trying out letter combinations and
defining them with ENTER.''')
print('''For each word, you have 10 tries! If you can not solve the word,
the game is over.''')
print('You have 9 attempts to guess the word.')
print('Have fun!')
print('')
def user_word():
userinput = str(input("Type in the word you want to be guessed: "))
for character in userinput:
if character.isdigit():
print('There is a number in your word!')
userinput = str(input('Please try again: '))
return userinput.upper()
def change(userinput):
global guess_word
list_WordToBeGuessed = list(userinput)
for characters in list_WordToBeGuessed:
guess_word.append(' _')
def play_game(userinput):
global count_attempts
length_word = len(userinput)
user_guessed = []
print('Word to guess: ', *guess_word)
print("")
list_WordToBeGuessed = list(userinput)
guess = str(input('Guess a letter: ')).upper()
for number in guess:
if number.isdigit():
guess = str(input('Input not valid. Guess a letter: ')).upper()
if guess in user_guessed:
print('You have already given this letter. ')
elif guess in list_WordToBeGuessed:
user_guessed.append(guess)
print("You've guessed a letter correctly!")
for i in range(0, length_word):
if list_WordToBeGuessed[i] == guess:
guess_word[i] = guess
else:
count_attempts += 1
user_guessed.append(guess)
print('Sry your given letter is not in the word!')
print("You have failed", count_attempts, "of 5 attempts")
def draw_hangman(count_attempts):
print('-------' )
print(' | ' + ('|' if count_attempts > 0 else ''))
print(' | ' + ('O' if count_attempts > 1 else ''))
print(' | ' + ('/ \\' if count_attempts > 2 else ''))
print(' | ' + ('|' if count_attempts > 3 else ''))
print('--- ' + ('/ \\' if count_attempts > 4 else ''))
print("")
def main():
guidance()
userinput = user_word()
change(userinput)
while True:
draw_hangman(count_attempts)
play_game(userinput)
if count_attempts >= 5:
print("You haven't any attempts left. Bad luck")
break
elif ' _' not in guess_word:
print("")
print('You won, congratulation!')
break
main()

you are breaking out of a loop before it can draw the hangman and word.
in the endgame conditions, you can simply call draw_hangman(count_atttempts) before each print statement and change(userinput) as well.
Edit:
You will have to redraw the word as well. Since this is built into your play_game() function it is difficult, but you can use
for i in guess_word:
guess = guess + i + " "
print(guess)
before the print statements along with the draw_hangman(count_attempts) change you made before. Please note you will need to create a new variable called guess in your main() function prior to adding this code.

Since you have a "break" in your endgame condition, the loop stops and last "draw_hangman(count_attempts)" is not called. You can simply add "draw_hangman(count_attempts)" before "print("You haven't any attempts left. Bad luck")"

Related

Hangman game, whenever I try to put the same alphabet twice it takes 2 lives instead of just taking one

I am a beginner in Python and I am making Hangman game project
So whenever I try to put the same alphabet twice it takes 2 lives
instead of just taking one
because both conditions are getting true.
My code is running fine but output is coming wrong due to both
conditions in if statement
given is satisfied
here is my code below
import time #importinf random module
#from hangman_art import logo #importing logo which i have in my PC, you ignore.
print("Welcome to HANGMAN")
#print(logo) #printing the logo which imported
user = input("\nWhat's Your Name : ") # take input for user name
print(f"\nHello {user}! Best Of Luck") #just for code to feel good.
x = (input("\nReady to play??? : ")) #input from user weather he/she wants to play or no.
if x == "yes" or x =="YES" or x =="Yes" or x == "y" or x == "Y": print("\nGame Loading in
3..2..1")
else:
print("\nOk Sadly ending the game!! BYE BYE")
exit()
#time.sleep(3)
print("\nGame Start!!")
#time.sleep(1)
print("\nRules as follows :-\n1. Guess the right word letter by letter.\n2. You only got 6
lives.\n3. Do not repeat the same alphabet entry it will reduce your life.\n4. Enjoy the game.")
#time.sleep(3)
import random #importing random module for code to choose any random number.
word_list=["TIGER","ELEPHANT","LION","CAT","DOG","HORSE"] #you can add n numbers of words.
chosen_word = random.choice(word_list) #giving variable to chosen random word.
length = len(chosen_word) #variable to find length of chosen word.
display=[] #creating an empty list.
in_game = True #for while loop to run continously
lives = 6 #user get 6 lives.
display=[]
duplicate=[] #creating an empty list to store duplicate values.
for _ in range (length):
display += "_"
#here looping for guess and game
while in_game:
guess = input("\nCome On Guess a word letter by letter : ").upper()
#make a list called duplicate
#add guess letter to duplicate list
#check if the entered letter is already present in that list
#if present then show msg stating already used word
#else follow the normal process
#duplicate=[]
if guess in display:
print("\nYou guessed",guess)
for position in range(length): #for getting length of number to be guessed
letter = chosen_word[position]
if letter == guess:
print("\nYou guessed",guess,"which is right aplhabet!!")
display[position] = letter
print(" ".join(display)) #joiningdisplay
if guess in duplicate:
lives -= 1 #this condition for taking life if duplicate entry.
print(f"\n{user} Do not repeat same alphabet entry. A LIFE LOST due to continues same
alphabet entry.") #here condition gets true and then goes to another if statment there also it gets true and code takes 2 life.
if lives == 0:
in_game = False
print(f"\n{user} You lost all your life, YOU LOSE.")
duplicate.append(guess)
#here 2 conditions are getting true so code is taking 2 lives please help
if guess not in chosen_word:
print("\nYou guessed", guess, "which is not the alphabet, life lost.")
lives -= 1
if lives == 0:
in_game = False
print(f"\n Try next
time {user}, You lost all your life, YOU LOSE.")
if not "_" in display:
in_game = False
print(f"\n Congrats {user} You WIN.")
from hangman_art import stages
print(stages[lives])
There are 2 if conditions that are true, so each will minus 1 live. You should use if and elif to ensure only 1 true condition is allowed. The code can be improved with 3 changes, see below:
<truncated>
while in_game:
guess = input("\nCome On Guess a word letter by letter : ").upper()
<truncated>
if guess in duplicate:
lives -= 1
print(f"\n{user} Do not repeat same alphabet entry. A LIFE LOST due to continues same alphabet entry.")
if lives == 0:
in_game = False
print(f"\n{user} You lost all your life, YOU LOSE.")
# duplicate.append(guess) #1. remove line from here
elif guess not in chosen_word: #2. change if to elif
print("\nYou guessed", guess, "which is not the alphabet, life lost.")
lives -= 1
if lives == 0:
in_game = False
print(f"\n Try next time {user}, You lost all your life, YOU LOSE.")
duplicate.append(guess) #3. add this line here instead
if not "_" in display:
in_game = False
print(f"\n Congrats {user} You WIN.")
Here's another way to do it, with MAX_WRONG = 6 means user gets 6 lives.
import random
WORDS = ['apple', 'banana', 'kiwi', 'orange', 'helicopter']
MAX_WRONG = 6
def game_play():
word = random.choice(WORDS).upper()
current_guess = '-' * len(word) #hidden answer
wrong_guesses = 0
used_letters = []
while wrong_guesses < MAX_WRONG and current_guess != word:
print ('\nRemaining tries:', MAX_WRONG - wrong_guesses)
print ('So far, the word is: ', current_guess)
print ('You have used the following letters: ', used_letters)
guess = input('Enter your letter guess:').upper()
if guess == word:
current_guess = word
break #exit the while-loop
while guess in used_letters: #check for duplicate input
print ('You have guessed "' + guess + '" already!')
guess = input ('Enter your letter guess: ').upper()
used_letters.append(guess) #append guess to used_letters
if guess in word:
print ('You have guessed correctly!')
new_current_guess = ''
for idx in range(len(word)): #update hidden answer
if guess == word[idx]:
new_current_guess += guess
else:
new_current_guess += current_guess[idx]
current_guess = new_current_guess
else:
print ('Sorry that was incorrect')
wrong_guesses += 1
if wrong_guesses == MAX_WRONG:
print ('\nYou have been hanged!')
print ('The correct word is', word)
elif current_guess == word:
print ('\nYou have won!! The word is:', word)
game_play()
Output:
Remaining tries: 6
So far, the word is: ----------
You have used the following letters: []
Enter your letter guess: helicopter
You have won!! The word is: HELICOPTER

Hangman game letter guessing

that plays hangman game.
I guess a have an error in my guessWord(word) function, because its not working properly, and I'm not getting why?
the file for readDictionary contains rows of words for the game. but in the main code words can also be used.
current output:
Welcome to the hangman game.
You will be guessing words, one letter at a time
Guess a letter
a
Would you like to guess a new word? Y/N: y
Guess a letter
h
Would you like to guess a new word? Y/N: g
You guessed 2 words out of 2
desired output:
Your guess so far: -------
Guess a letter from the secret word: a
Good guess;
Your guess so far: -A----A
Guess a letter from the secret word: e
Wrong guess
--------
|
Your guess so far: -A----A
Guess a letter from the secret word: s
Wrong guess
--------
|
O
#and so on…
here are the parameters to do:
readDictionary() which reads the accompanying file “dictionary.txt” and returns a list of all the words appearing in the file.
• guessWord(word) which runs the user interface for guessing the word passed as argument, as described above. guessWord() calls hangmanSketch() with the appropriate argument, whenever a wrong guess is entered by the player.
Note that, even though all the words in the are in all-capital letters, the player should be able to enter the guesses in lower case.
The function returns True, if the player manages to guess the whole word before making 8 wrong guesses. The function returns False, if the player makes 8 wrong guesses and does not guess the whole word.
Below is an extract of a sample run of the whole application, showing the interface for successfully and unsuccessfully guessing words.
code:
from random import choice
def readDictionary():
file = open("dictionary.txt", "r")
lines = file.readlines()
return list(lines)
def hangmanSketch(n):
if n <= 0:
pic = ''' --------\n'''
return pic
pic = hangmanSketch(n-1)
if n == 1:
pic += ''' |\n'''
elif n == 2:
pic += ''' O\n'''
elif n == 3:
pic += '''_/'''
elif n == 4:
pic += '''|'''
elif n == 5:
pic += '''\_ \n'''
elif n == 6:
pic += ''' |\n'''
elif n == 7:
pic += '''_/'''
elif n == 8:
pic += ''' \_ \n'''
return pic
def guessWord(word):
while True:
print("Guess a letter")
userGuess = input()
userGuess = userGuess.lower()
if len(userGuess) != 1:
print("Please enter a single letter")
elif userGuess in word:
print("letter already guessed, try another")
else:
return userGuess
def main():
print("Welcome to the hangman game.")
print("You will be guessing words, one letter at a time")
words = readDictionary()
words = ['ABANDON', 'INQUIRING', 'LACROSSE', 'REINITIALISED'] # use this list if you don't manage to implement readDictionary()
nAttemptedWords = 0
nGuessedWords = 0
play = "Y"
while play == "Y":
secretWord = choice(words) # random choice of one word from the list of words
nAttemptedWords += 1
if guessWord(secretWord):
nGuessedWords += 1
play = input("Would you like to guess a new word? Y/N: ")
play = play.upper()
print("You guessed", nGuessedWords, "words out of", nAttemptedWords)
if __name__ == "__main__":
main()
I suggest you having one while for iterating between words and inner while for iterating through player's guesses:
import random
WORDS = ['abandon', 'inquiring', 'lacrosse', 'reinitialised']
def guessed_word(word, guessed_letters):
""" Build guessed word. E.g.: "--c--r" """
result = ''
for letter in word:
if letter in guessed_letters:
result += letter
else:
result += '-'
return result
print('Welcome to the hangman game.')
print('You will be guessing words, one letter at a time')
play = 'y'
while play == 'y':
word = random.choice(WORDS)
guessed_letters = []
hp = 8
while True:
print(f'Your guess so far: {guessed_word(word, guessed_letters)}')
letter = input('Guess a letter from the secret word: ')
if letter in list(word):
print('Good guess')
guessed_letters.append(letter)
else:
print('Wrong guess')
hp -= 1
if hp == 0:
print('You loose!')
break
elif len(guessed_letters) == len(set(word)):
print(f'You win! The word is: {word}')
break
play = input('Would you like to guess a new word? y/n: ')
Output:
Welcome to the hangman game.
You will be guessing words, one letter at a time
Your guess so far: --------
Guess a letter from the secret word: a
Good guess
Your guess so far: -a------
Guess a letter from the secret word: b
Wrong guess
Your guess so far: -a------
Guess a letter from the secret word: c
Good guess
Your guess so far: -ac-----

How terminate this loop after a a given number of attempts?

For the most part it seems to be working, but not how I'm trying to get it to work. When I run it I am allowed unlimited tries to guess every single letter in the word until I spell out the word.
But that's not what I am going for, I'm trying to give the users 5 guesses with single letters if the letter is in the word then it will tell them "Yes", there is a(n) (users guess) in my word, but if the letter is not in my word then it will tell them "No", there is not a(n) (users guess) in my word.
After 5 attempt's at guessing different letters I want them to have to guess the full word but I can't figure out how.
This is what I have now:
import random
def get_word():
words = ['cat', 'dog', 'man', 'fox', 'jar']
return random.choice(words).upper()
def check(word,guesses,guess):
status = ''
matches = 0
for letter in word:
if letter in guesses:
status += letter
else:
status += '*'
if letter == guess:
matches += 1
count = 0
limit = 5
if matches > 1:
print ('Yes! there is a(n)',guess,' in my word.')
guesses += guess
elif matches ==1:
print ('Yes! there is a(n)',guess,' in my word.')
guesses += guess
while count > limit:
input('What do you think my word is')
else:
print('No, there is not a(n)',guess,' in my word.')
guesses += guess
while count > limit:
input('What do you think my word is')
return status
def main():
word = get_word()
guesses = ""
guessed = False
print ('I am thinking of a 3 letter word with no repeating letters. You get five guesses of the letters in my word and then you have to guess the word.')
while not guessed:
text = 'Guess a letter in my word:'
guess = input(text)
guess = guess.upper()
count = 0
limit = 5
if guess in guesses:
print ('You already guessed "' + guess + '"')
elif len(guess) == len(word):
guesses += guess
if guess == word:
guessed = True
else:
print('No, there is not a(n) "' + guess + '"')
elif len(guess) == 1:
guesses += guess
result = check(word,guesses,guess)
if result == word:
guessed = True
else:
print (result)
else:
print ('Invalid entry.')
print ('Yes! you correctly guessed')
main()
For starters while not guessed: will continue until guessed is true -> the word was guessed. Next if you want there to be 5 guesses then an answer guess you want to do for i in range(0, 5): then run your guess logic replacing
if result == word:
guessed = True
with
if result == word:
guessed = true
break
to break out of the loop on a correct guess. Then to allow a guess afterwards, outside of the loop, check if already guessed and allow a guess if not.
Also as a side note you should check that they enter one character with something like
guess = input(text)
while len(guess) != 1:
guess = input(text)
I tried to mostly keep your original code and trail of thought. The main changes I made was getting rid of the check-function as I felt it didn't do anything too useful. I also changed the guessed-variable into a list, and utilized it's properties for your evaluations.
import random
def get_word():
words = ['cat', 'dog', 'man', 'fox', 'jar']
return random.choice(words).upper()
def main():
word = get_word()
guesses = []
guessed = False
print('I am thinking of a 3 letter word with no repeating letters.'
' You get five guesses of the letters in my word and then you have'
' to guess the word.\n')
while not guessed and len(guesses)<5:
text = 'Guess a letter in my word:\n'
guess = input(text)
guess = guess.upper()
if guess in guesses:
print ('You already guessed "', guess, '"\n')
elif len(guess) > 1:
guesses.append(guess)
if guess == word:
guessed = True
else:
print('No, ', guess, 'is not the word!\n')
elif len(guess) == 1:
guesses.append(guess)
if guess in word:
print('Yes there is a(n) ', guess, 'in the word!\n')
else:
print('No, there is not a(n)', guess, 'in the word!\n')
else:
print ('Invalid entry.\n')
if guessed:
print ('You correctly guessed the word!\n')
else:
correct_guesses = [guess for guess in guesses if guess in word]
print('Last chance, what is the full word? (HINT: You have'
'correctly guessed ', str(correct_guesses), ')"')
fword = input()
if fword.upper() == word:
print('You correctly guessed the word!\n')
else: print('Tough luck! You are out of chances! The correct'
'word was ', word, '\n')
main()
playing = True
while playing:
print('Would you like to play again?')
answ = input()
if answ.upper() == 'YES':
main()
else:
print('Thank you for playing.')
playing = False

Python : Input an answer and receive a response that is randomly given on a list of responses

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

How to get python to recognize the next occurrence of letter in hangman

My hangman program is fully functioning except there is one problem, let's say the word is mathematics, I guess m, a, t, h, e - but once I guess the other m, it says I guessed it (as opposed to saying "You already guessed this letter") but it doesn't replace the _.
My Code:
def start():
import random
words = ["barbershop", "cuddle", "furious", "demolition", "centaur", "forest", "pineapple", "mathematics", "turkish"]
word = random.choice(words);
hiddenword = len(word) * "-"
used_letters = []
lives = 6
print "Welcome to Hangman! You have 6 guesses, good luck!"
while True:
print word
print "".join(hiddenword)
guess = raw_input("> ")
hiddenword = list(hiddenword)
if len(guess) > 1:
print "Error: 1 Letter Maximum"
elif len(guess) < 1:
guess = raw_input("> ")
else:
if guess.isdigit() == True:
print "Error: Hangman only accepts letters."
else:
if guess in used_letters and word.count(guess) == 1:
print "You already guessed that letter"
else:
if guess.lower() in word:
print "You got the letter " + "'" + guess + "'" + "!"
hiddenword[word.index(guess)] = guess
used_letters.append(guess)
else:
lives -= 1
print "-1 Guesses"
print "Guesses:", lives
used_letters.append(guess)
if lives == 0:
print "GAME OVER: You're out of guesses, try again!"
break
if hiddenword == word:
print "Cangratulations, you got the word!"
break
start()
P.S. - I know I have a lot of excess code e.g. if statements, please do not comment on that.
The problem appears to be with the line:
hiddenword[word.index(guess)] = guess
The string method .index(x) returns the index of the first incidence of x. So this line will persistently fill in the first "m" in mathematics.
Assuming you want the game to reveal all instances of a letter when it is guessed (e.g., show both m's in "mathematics" when you guess "m"), you can substitute this:
for i, x in enumerate(word):
if word[i] == guess:
hiddenword[i] = guess
for your line:
hiddenword[word.index(guess)] = guess
Also, to get the "Congratulations!" message to appear, you will need to change if hiddenword == word to if ''.join(hiddenword) == word, since hiddenword is a list at this point.
Removing multiple occurences of a character in a string in python is easily achieved using:
your_string.replace("m", "");
http://www.tutorialspoint.com/python/string_replace.htm

Categories

Resources