Hangman game trouble with keep_playing - python

So I'm new to python and went trough a tutorial to write a hangman game in python 2.7 on my new pi. Well, anyway I liked the code and everything, and it ran fine but then I wanted to add something to make it ask ,"if you wanted to continue playing", and I did a lot of research and talked on some chat rooms about it and came up with/found this script to exit:
while keep_playing == False:
user = raw_input("\n\tShall we play another game? [y|n] ")
again = "yes".startswith(user.strip().lower())
if again:
keep_playing = True
if not again:
break
raw_input ("\n\n\nPress enter to exit")
but I get this error:
Traceback (most recent call last):
File "/home/pi/Desktop/Scripts/scrappy/ls/ls/hangman3.py", line 40, in <module>
while keep_playing == False:
NameError: name 'keep_playing' is not defined
when its ran with this script
import random
import urllib
print 'time to play hangman'
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
secret = random.choice(animals)
guesses = 'aeiou'
turns = 5
while turns > 0:
missed = 0
for letter in secret:
if letter in guesses:
print letter,
else:
print '_',
missed += 1
print
if missed == 0:
print 'You win!'
break
guess = raw_input('guess a letter: ')
guesses += guess
if guess not in secret:
turns -= 1
print 'Nope.'
print turns, 'more turns'
if turns < 5: print ' O '
if turns < 4: print ' \_|_/ '
if turns < 3: print ' | '
if turns < 2: print ' / \ '
if turns < 1: print ' d b '
if turns == 0:
print 'The answer is', secret
while keep_playing == False:
user = raw_input("\n\tShall we play another game? [y|n] ")
again = "yes".startswith(user.strip().lower())
if again:
keep_playing = True
if not again:
break
raw_input ("\n\n\nPress enter to exit")
Can anyone help me?
****edit*****
someone can close this tread using the tips provided i have solved my problem this is the final code
import random
import urllib
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
while True:
print 'time to play hangman'
secret = random.choice(animals)
guesses = 'aeiou'
turns = 5
while turns > 0:
missed = 0
for letter in secret:
if letter in guesses:
print letter,
else:
print '_',
missed += 1
print
if missed == 0:
print 'You win!'
break
guess = raw_input('guess a letter: ')
guesses += guess
if guess not in secret:
turns -= 1
print 'Nope.'
print turns, 'more turns'
if turns < 5: print ' O '
if turns < 4: print ' \_|_/ '
if turns < 3: print ' | '
if turns < 2: print ' / \ '
if turns < 1: print ' d b '
if turns == 0:
print 'The answer is', secret
break
user = raw_input("\n\tShall we play another game? [y|n] ")
again = "yes".startswith(user.strip().lower())
if not again:
raw_input ("\n\n\nPress enter to exit")
break

I'm not into python, but I can see you're indeed trying to compare an empty/undefined variable "keep_playing" to false. To my knowledge, you can't compare a variable to something, if you haven't declared the variable before the comparison, not sure if this is different in Python though.
What happens if you write this line along the other variables:
keep_playing = False
so you'll get :
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
secret = random.choice(animals)
guesses = 'aeiou'
turns = 5
keep_playing = False

animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
secret = random.choice(animals)
guesses = 'aeiou'
turns = 5
keep_playing = False
if guess not in secret:
turns -= 1
print 'Nope.'
print turns, 'more turns'
if turns < 5: print ' O '
if turns < 4: print ' \_|_/ '
if turns < 3: print ' | '
if turns < 2: print ' / \ '
if turns < 1: print ' d b '
if turns == 0:
print 'The answer is', secret
keep_playing = False
This should do it

Related

What is the best way to make a guessing loop in python?

Basically I'm trying to make a guessing game. There are 3 questions and you have 3 guesses for every question. The problem is I'm bad at coding, this is only my first time.
print("Guessing Game")
player_name = input("Hi! What's your name? ")
number_of_guesses1 = 0
number_of_guesses2 = 0
number_of_guesses3 = 0
guess1 = input("What is the most popular car company in America? ")
while number_of_guesses1 < 3:
number_of_guesses1 += 1
if guess1 == ("Ford"):
break
if guess1 == ("Ford"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess2 = input("Try again:")
if guess2 == ("Ford"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess3 = input("Try again:")
if guess3 == ("Ford"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
print('You did not guess the answer, The answer was Ford')
guess1b = input("What color do you get when you mix red and brown?")
while number_of_guesses2 < 3:
number_of_guesses2 += 1
if guess1 == ("Maroon"):
break
if guess1b == ("Maroon"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess2b = input("Try again:")
if guess2b == ("Maroon"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess3b = input("Try again:")
if guess3b == ("Maroon"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
print('You did not guess the answer, The answer was Maroon')
This code kind of works, but only if you get the answer wrong 2 times in a row for every question lol. I also haven't thought of a way to implement a score keeper yet (at the end I want it to say how many points you got out of 3.) The code also is obviously not done. Basically, my questions are: How come when I get the answer wrong once and then get it right on the second try it says that it took 3 tries? And if you get the answer right on the first or second try how can I make it so it ignores the remaining tries you have left? This is the error code for example if I get it right on the second try:
Traceback (most recent call last):
File "main.py", line 20, in <module>
if guess3 == ("Ford"):
NameError: name 'guess3' is not defined
By utilizing the data structures within Python and a couple of functions, you can simplify your code considerably as shown below:
from collections import namedtuple
# Create a tuyple containing the Question, number of allowed tries and the answer
Question = namedtuple("Question", ["quest", 'maxTries', 'ans'])
def askQuestion(quest: str, mxTry: int, ans: str) -> int:
""" Ask the question, process answer, keep track of tries, return score"""
score = mxTry
while score > 0:
resp = input(quest)
if resp.lower() == ans:
print('Yes, you got it')
break
else:
score -= 1
print(f'Sorry {resp} is incorrect, try again')
if score == 0:
print("Too Bad, you didn't get the correct answer.")
print(f"The correct answer is {ans}")
return score
def playGame():
# Create a list of questions defiend using the Question structure defined above
question_list =[Question('What is the most popular car company in America? ' , 3, 'ford'),
Question("What color do you get when you mix red and brown?", 3, 'maroon')]
plyr_score = 0
for q in question_list:
plyr_score += askQuestion(q.quest, q.maxTries, q.ans)
print(f'Your final score is {plyr_score}')
The above approach allows you to extend the question repertoire as well as provide a different number of max tries by question.
simply execute playGame() to run the game
Don't use a different variable to keep track of each guess, instead just use one variable, and continually update it using input(). Then you can check it over and over again, without writing a whole mess of if-else statements. For keeping track of the number correct, you can use a variable, and increment it every time a correct answer is entered.
print("Guessing Game")
player_name = input("Hi! What's your name? ")
score = 0
answer1 = "Ford"
answer2 = "Maroon"
guess = input("What is the most popular car company in America? ")
number_of_guesses = 1
while guess != answer1 and number_of_guesses < 3:
guess = input("Try again: ")
number_of_guesses += 1
if guess == answer1:
print('You guessed the answer in ' + str(number_of_guesses) + ' tries!')
score += 1
else:
print('You did not guess the answer, The answer was Ford')
guess = input("What color do you get when you mix red and brown? ")
number_of_guesses = 1
while guess != answer2 and number_of_guesses < 3:
guess = input("Try again: ")
number_of_guesses += 1
if guess == answer2:
print('You guessed the answer in ' + str(number_of_guesses) + ' tries!')
score += 1
else:
print('You did not guess the answer, The answer was Maroon')
print('You got ' + str(score) + ' out of 2 questions.')

Loop breaks without executing the last print statement

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

Python Hangman code

For my Computing Science controlled assessment I have been asked to create a Hangman game with Python. However, in creating the game, there has been an error message that specifies something not in my code.
Traceback (most recent call last):
File "Z:\Documents\hangman.py", line 40, in <module>
generated_word = random.choice(random)
File "Q:\Pywpygam.001\Python3.2.3\lib\random.py", line 249, in choice
i = self._randbelow(len(seq))
TypeError: object of type 'module' has no len()
I don't see anything wrong in the code and it doesn't specify what's wrong. Here is my code:
import time
print('Lets play hangman')
print("""
_______
| |
| O
| |
| \- -/
| |
| / \\
| / \\
____|____
\n""")
print("""
you get 7 lives to guess the letters in the word. if you guess
incorrectly more of the hangman will appear and you lose a life. when you have
used your 7 lives, the man will have hung and you will have lost. If you guess a
correct letter, it will be show and if you guess the word without using the 7
turns, you win!
\n""")
easy_words = ['string', 'loop', 'python', 'print', 'run']
medium_words = ['module', 'input', 'logic', 'output']
hard_words = ['graphics window', 'variable', 'iteration', 'modules']
random_words = ['string', 'loop', 'python', 'print', 'run', 'graphics window', 'variable', 'iteration', 'modules', 'module', 'input', 'logic', 'output ']
time.sleep(2)
print ("What level would you like to play at? Easy, Medium or Hard or Random?")
level_of_difficulty = input()
time.sleep(2)
print ("The program is now generating your word...")
if level_of_difficulty == 'Easy':
generated_word = random.choice(easy_words)
elif level_of_difficulty == 'Medium':
generated_word = random.choice(medium_words)
elif level_of_difficulty == 'Hard':
generated_word = random.choice(hard_words)
elif level_of_difficulty == 'Random':
generated_word = random.choice(random_words)
else:
generated_word = random.choice(random_words)
guessed = ''
lives = 7
while lives > 0:
missed = 0
print()
for letter in generated_word:
if letter in guessed:
print (letter,end=' ')
else:
print ('_',end=' ')
missed = missed + 1
if missed == 0:
print ('\n\nYou win!')
quit()
break
guess=input("please guess a letter:")
guessed = guessed + guess
if guess not in generated_word:
print ('\n that letter is not in this word, your lives have been decreased by 1.')
print ('please try another letter.')
lives = lives - 1
missed = missed + 1
print('your new lives value is')
print(lives)
if lives < 7:
print(''' _______
| | ''')
if lives < 6:
print(' | O ')
if lives < 5:
print(' | | ')
if lives < 4:
print(' | \- -/ ')
if lives < 3:
print(' | | ')
if lives < 2:
print(' | / \\ ')
if lives < 1:
print(' | / \\ ')
if lives == 0:
print('___|___ ')
print('GAME OVER! You have run out of lives and lost the game')
print('the secret word was')
print(generated_word)
quit()
What I am trying to do is make it so the generated word is displayed in the window with a _, and when the letter is guessed correctly, the appropriate _ is filled with the letter.
Any ideas will be appreciated!
I think these lines are wrong:
generated_word = random.choice(random)
You are passing the module "random" as parameter. I think you should pass the variable "random_words"?
I see what I did wrong, thanks for pointing out the
generated_word = random.choice(random)
bit, but I also saw that on the
while lives > 0:
missed = 0
print()
for letter in generated_word:
if letter in guessed:
I have made a spelling mistake.
Thanks everyone!

Trying to create bagel game in python

I am getting this error. Please help me explain the cause and the meaning of the error
Traceback (most recent call last):
File "E:\Python\bagels.py", line 61, in <module>
while len(guess) != NUMDIGITS or not isOnlyDigits(guess):
TypeError: object of type 'builtin_function_or_method' has no len()
I am doing lessons from invent with python and stuck on this lesson
https://inventwithpython.com/chapter11.html
here is my code
import random
def getSecretNum(numDigits):
numbers = list(range(10))
random.shuffle(numbers)
secretNum = ''
for i in range(numDigits):
secretNum += str(numbers[i])
return secretNum
def getClues(guess, secretNum):
if guess == secretNum:
return 'You got it!'
clue = []
for i in range(len(guess)):
if guess[i] == secretNum[i]:
clue.append('fermi')
elif guess[i] in secretNum:
clue.append('Pico')
if len(clue) == 0:
return 'Bagels'
clue.sort()
return ' '.join(clue)
def isOnlyDigits(num):
if num == '':
return False
for i in num:
if i not in '0 1 2 3 4 5 6 7 8 9'.split():
return False
return True
def playAgain():
print('Do you want to play again?(yes or no)')
return input().lower().startswith('y')
NUMDIGITS = 3
MAXGUESS = 10
print('I am thinking of a %s-digit number. Try to guess what it is.' %(NUMDIGITS))
print('here are some clues:')
print('When I say: That means:')
print(' Pico One digit is correct but in the wrong position.')
print(' Fermi One digit is correct and in right position.')
print(' Bagels No digit is correct.')
while True:
secretNum = getSecretNum(NUMDIGITS)
print('I have thought of a number. You have %s guesses to guess it' %(MAXGUESS))
numGuesses = 1
while numGuesses <= MAXGUESS:
guess = ''
while len(guess) != NUMDIGITS or not isOnlyDigits(guess):
print('Guess #%s: ' % (numGuesses))
guess = input
clue = getClues(guess, secretNum)
print(clue)
numGuesses ++ 1
if guess == secretNum:
break
if numGuesses > MAXGUESS:
print('You ran out of guesses. The answer was %s. ' %(secretNum))
if not playAgain():
break
In the while loop you overwrite guess with the builtin function input.
You need to call the input function (please notice the extra pair of parentheses).
while len(guess) != NUMDIGITS or not isOnlyDigits(guess):
print('Guess #%s: ' % (numGuesses))
guess = input()
The problem is here:
guess = input
clue = getClues(guess, secretNum)
guess is now a reference to input, which is a python built-in function (like the error said).
You might want to do
guess = int(input("please enter guess"))

Hangman Python Repeats Functions

When I try to run the code it keeps repeating,"So far you have guessed" when I only want it to repeat once. The output for the name when a guess is made should be like : secret_word = hello , then after every word it should be h???o or h?ll?
def get_secret_word():
while True:
secret_word = input('Please enter a word to be guessed\nthat does not contain ? or whitespace:')
if not ('?' in secret_word or ' ' in secret_word or secret_word == ''):
return secret_word
def is_game_over(wrong_guess, secret_word, output, chars_guessed):
if wrong_guess == 7:
print('You failed to guess the secret word:', secret_word)
return True
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '?'
if not ('?' in output):
print('You correctly guessed the secret word:', secret_word)
return True
else:
return False
def display_hangman(wrong_guess):
if wrong_guess == 1:
print('\n |')
elif wrong_guess == 2:
print('\n |', '\n O')
elif wrong_guess == 3:
print('\n |', '\n O', '\n |')
elif wrong_guess == 4:
print('\n |', '\n O', '\n/|')
elif wrong_guess == 5:
print('\n |', '\n O', '\n/|\\')
elif wrong_guess == 6:
print('\n |', '\n O', '\n/|\\', '\n/')
elif wrong_guess == 7:
print('\n |', '\n O', '\n/|\\', '\n/', '\\')
def display_guess(secret_word, chars_guessed):
output = ''
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '\nSo far you have guessed: '
for guess in chars_guessed:
output += guess + ","
print(output.strip(","))
def get_guess(secret_word, chars_guessed):
while True:
guess_character = input('Please enter your next guess: ')
if guess_character == '':
print('You must enter a guess.')
continue
elif len(guess_character) > 1:
print('You can only guess a single character.')
elif guess_character in chars_guessed:
print('You already guessed the character:', guess_character)
else:
return guess_character
def main():
wrong_guess = 0
chars_guessed = []
secret_word = get_secret_word()
output = ''
while not is_game_over(wrong_guess, secret_word, output, chars_guessed):
display_hangman(wrong_guess)
display_guess(secret_word, chars_guessed)
guess_character = get_guess(secret_word, chars_guessed)
chars_guessed.append(guess_character)
chars_guessed.sort()
if not guess_character in secret_word:
wrong_guess += 1
return wrong_guess
pass
if __name__ == '__main__':
main()
so issues that I can see are:
indentation issues(as pointed out by some of the other posters already):
- get_secret_word() function with the if statement
- display_hangman() function with all the elif's
also with the below bit of code from the main function
if not guess_character in secret_word:
wrong_guess += 1
return wrong_guess
pass
this exits out of the app for me and as far as I can see the return and pass lines are not needed. The return exits from the main function when an incorrect guess is made and so pass is never reached and since the wrong_guess is a "global" variable in the main function the new count is available to everything in that function for the length of time that the function is active.
as for the repeated looping with displaying the users guesses it is the way in how you are looping in the display_guess() function. in the case that the character being guessed is not in the secret word it loops over everything twice, once for the outer for loop and then again for the inner loop.
I think you should change the display_guess() to something like the below. this way a user will always see what they have previously guessed
def display_guess():
output = "\nSo far you have guessed: "
count = 0
if len(chars_guessed) > 0:
for guess in chars_guessed:
if count < len(chars_guessed) and count != 0:
output += ','
output += guess
count +=1
print output
as for displaying the secret word with the guessed characters and the rest as ?'s, it doesn't seem that you are printing the value of the output variable from the is_game_over() function anywhere. i haven't tested it but adding a print just after that for loop should sort that out.
on a side note you might wish to add validation on user input as it excepts numbers and special characters

Categories

Resources