Python Hangman, Difficulty selector not working properly - python

I'm trying to make a hangman game that has 3 difficulty easy, medium and hard.
I'm facing a issue where my answer secretWord always return the value of "beautiful" in medium list regardless of what the user input. Can anyone help me see what is happening as I could not find the reason that this is happening.
import random
print("Welcome to Devil's Hangman")
#print("Lets Begin by choosing your difficulty for 'Easy', 'Medium' or 'Hard'.")
easy_list = ['trick','trout','youth','guess','gucci','treat']
medium_list = ['banker','traitor','monopoly','acoustic','beautiful','cafeteria']
hard_list = ['characteristics','sagittarius','personality','psychologist','photosynthesis','classification']
def printEmptyBlanks():
for letter in secretWord:
print("_", end=" ")
def hangmanGraphics(wrongCounter):
if(wrongCounter == 0):
print(' __________\n |\n |\n |\n |\n/_\ ')
elif(wrongCounter == 1):
print(' __________\n | |\n |\n |\n |\n/_\ ')
elif(wrongCounter == 2):
print(' __________\n | |\n | O\n |\n |\n/_\ ')
elif(wrongCounter == 3):
print(' __________\n | |\n | O\n | |\n |\n/_\ ')
elif(wrongCounter == 4):
print(' __________\n | |\n | O\n | /|\n |\n/_\ ')
elif(wrongCounter == 5):
print(' __________\n | |\n | O\n | /|\ \n |\n |\n/_\ ')
elif(wrongCounter == 6):
print(' __________\n | |\n | O\n | /|\ \n | /\n/_\ ')
elif(wrongCounter == 7):
print(' __________\n | |\n | O\n | /|\ \n | / \ \n/_\ ')
def previousInputs(lettersguessed):
counter = 0
rightLetters = 0
for char in secretWord:
if(char in lettersguessed):
print(secretWord[counter], end=" ")
rightLetters+=1
else:
print(" ", end=" ")
counter+=1
return rightLetters
def wordLines():
print("\r")
for char in secretWord:
print("\u203E", end=" ")
#this is the part where my user input difficulty and my code supposed to generate a secretWord from my lists.
def difficultySelector():
isValidInput=False
while not isValidInput:
userDifficulty = str(input("Lets Begin by choosing your difficulty for 'Easy', 'Medium' or 'Hard': ")).lower()
if (userDifficulty == 'easy'):
secretWord = random.choice(easy_list)
isValidInput = True
return secretWord
elif (userDifficulty == 'medium'):
isValidInput = True
secretWord = random.choice(medium_list)
return secretWord
elif (userDifficulty == 'hard'):
isValidInput = True
secretWord = random.choice(hard_list)
return secretWord
else:
print("Invalid Entry.Please type only 'Easy', 'Medium' or 'Hard'")
difficultySelector()
hangmanGraphics(wrongCounter)
printEmptyBlanks()
secretWordLength = len(secretWord)
wrongCounter = 0
noOfGuesses = 0
lettersTried = []
correctLetters = 0
while(wrongCounter !=8 and correctLetters != secretWordLength):
print("\nLetters guessed so far: ")
for letter in lettersTried:
print(letter, end=" ")
userGuess = input("\nGuess a letter: ").lower()
if(secretWord[noOfGuesses] == userGuess):
hangmanGraphics(wrongCounter)
noOfGuesses += 1
lettersTried.append(userGuess)
correctLetters = previousInputs(lettersTried)
wordLines()
else:
wrongCounter += 1
lettersTried.append(userGuess)
hangmanGraphics(wrongCounter)
correctLetters = previousInputs(lettersTried)
wordLines()
print("\nGame is over!")

Related

Hangman | Problem with using names and surnames as "word"

I'm new to programming. I was doing a classic hangman game, but I wanted it to be guessing some character's names from a show (name and surname).
My problem: the dashes print the space between name and surname instead of ignoring it, example:
Secret word: Rupert Giles
How it prints when all the letters are guessed: Rupert_ Giles
(yes, it has a space after the dash)
I've tried:
split()
writing character instead of letter (as space doesn't count
as character in lines 41,42 and 43)
separating the name as ["Name""Surname,
"Name2""Surname1"]
and ['Name'' ''Surname','Name1'' ''Surname1']
What I think it's the problem: the secret "word" is stored in main, and main is in charge of putting dashes instead of the letters, the code of that part goes like this
main = main + "_" + " "
So maybe there's something that should be changed in there so it ignores the spaces
My code:
import random, sys, time, os
def typingPrint(text):
for character in text:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
def typingInput(text):
for character in text:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
value = input()
return value
def clearScreen():
if os.name == 'posix':
_ = os.system('clear')
else:
_ = os.system('cls')
def hangman():
word = random.choice(
["Spike", "Rupert Giles", "Tara Maclay", "Willow Rosenberg", "Buffy Summers", "Xander Harris",
"Wesley Wyndam Price", "Faith Lehane", "Angel", "Darla", "Cordelia Chase", "Dawn Summers",
"Anya Jenkins", "Riley Finn", "Drusilla", "Oz Osbourne", "Kendra Young", "Joyce Summers", "Master",
"Harmony Kendall",
"Jenny Calendar", "Robin Wood", "Jonathan Levinson",
"Ethan Rayne", "Principal Snyder", "Kennedy", "Veruca", "Hank Summers", "Halfrek", "DHoffryn", "Mr Tick"])
validLetters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
turns = 10
guessmade = ''
while len(word) > 0:
main = ""
missed = 0
for character in word:
if character in guessmade.lower() or character in guessmade.upper():
main = main + character
else:
main = main + "_" + " "
if main == word:
print(main)
typingPrint("Congratulations! You win... for now.\nLet's try again")
typingPrint("\nin 3...2...1")
clearScreen()
break
print("\nGuess the word:", main)
guess = input()
if guess in validLetters:
guessmade = guessmade + guess
else:
typingPrint("Enter a valid character: ")
guess = input()
if guess.lower() not in word and guess.upper() not in word:
turns = turns - 1
if turns == 9:
typingPrint("You have 9 turns left")
print("\n -------- this is a ceiling, don't laugh at it")
if turns == 8:
typingPrint("You have 8 turns left")
print("\n -------- ")
print(" O ")
if turns == 7:
typingPrint("You have 7 turns left")
print("\n -------- ")
print(" O ")
print(" | ")
if turns == 6:
typingPrint("You have 6 turns left")
print("\n -------- ")
print(" O ")
print(" | ")
print(" / ")
if turns == 5:
typingPrint("You have 5 turns left")
print("\n -------- ")
print(" O ")
print(" | ")
print(" / \ ")
if turns == 4:
typingPrint("You have 4 turns left")
typingPrint("\nYou are walking on thin ice")
print("\n -------- ")
print(" \ O ")
print(" | ")
print(" / \ ")
if turns == 3:
typingPrint("You have 3 turns left")
typingPrint("\n No pressure")
print("\n -------- ")
print(" \ O / ")
print(" | ")
print(" / \ ")
if turns == 2:
typingPrint("You have 2 turns left")
typingPrint("\nYou call yourself a Buffy fan?")
print("\n -------- ")
print(" \ O / | ")
print(" | O ")
print(" / \ ")
if turns == 1:
typingPrint("You have 1 turn left")
typingPrint("\nYou should re-watch all seasons")
print("\n -------- ")
print(" \ O_|/ ")
print(" | ")
print(" / \ ")
if turns == 0:
typingPrint("You lose, ")
typingPrint(name)
typingPrint("\nThe name was...")
typingPrint(word)
print("\n -------- ")
print(" O_| ")
print(" /|\ ")
print(" / \ ")
typingPrint("Good night")
typingPrint("\nin 3...2...1")
clearScreen()
break
while 1:
name = typingInput("Enter your name: ")
typingPrint("Welcome, ")
typingPrint(name)
typingPrint(". You have been fooled\n")
typingPrint("Now you are my prisioner, my dear ")
typingPrint(name)
typingPrint("\nMwahahaha")
print("\n-------------------------------------")
typingPrint("Try to guess the name of this Buffy's character in less than 10 attempts")
typingPrint("\nIf you can't, you will be hanged")
typingPrint("\nNo pressure, ")
typingPrint(name)
typingPrint("\nOh... and one little, itty bitty thing...")
typingPrint("\nThe names are from Season 1 to 7")
typingPrint("\nGood luck, break a neck... I mean, a leg")
hangman()
print()
You can make this adjustment. Replace
if character in guessmade.lower() or character in guessmade.upper():
main = main + character
With
if character in guessmade.lower() or character in guessmade.upper() or character == " ":
main = main + character
As it stands, you are expecting your users to guess a space character. This new if statement removes that requirement.
Nice. I'd print out guessed letters as well. Think this is what you're going for. You don't have to keep caps in validLetters that way.
for character in word:
if character .lower() in guessmade .lower():
main = main + character
elif character == ' ':
main = main + ' '
else:
main = main + '_' + ' '
main is a terrible variable name, so I'll be using word_as_shown instead. Also, I'll replace guessmade with guessed_letters. If you replace
if guess in validLetters:
guessmade = guessmade + guess
with
if guess in validLetters:
guessed_letters += guess.lower()
and define
def char_as_shown(char):
if char == ' ':
return ' '
if char.lower() in guessed_letters:
return char
return "_"
then you can do
word_as_shown = [char_as_shown(char) for char in word]

Is there some way that I can that i can add up the random values and print it?

Random is obviously needed, but it makes it harder to gather the values. =) This is an unnecessary comment.
import random
class Die:
def __init__ (self, face, face_value):
self.face = face
self.face_value = face_value
def roll(self):
I have tried making the class do this twice, but for some reason it does not work.
self.face = random.randint(1, 6)
if self.face == 1:
face = ( ' ------\n| |\n| o |\n| |\n ------')
num = 1
elif self.face == 2:
face = (' ------\n| |\n| o o |\n| |\n ------')
num = 2
elif self.face == 3:
face = (' ------\n| o |\n| o |\n| o |\n ------')
num = 3
elif self.face == 4:
face = (' ------\n| o o |\n| o o |\n| |\n ------')
num = 4
elif self.face == 5:
face = (' ------\n| o o |\n| o o |\n| o |\n ------')
num = 5
elif self.face == 6:
face = (' ------\n| o o |\n| o o |\n| o o |\n ------' )
num = 6
return print(face)
**My goal is to add up the two random values that I get from the Die class, I have tried to put two rolls in that class, but then it has the same output still. **
from DieClass import Die
user = input('Do you want to play this Dicegame?')
num = random.randint(1,6)
I only need this num so that I have some value to put into the class.
if num == 1:
face = ( ' ------\n| |\n| o |\n| |\n ------')
elif num == 2:
face = (' ------\n| |\n| o o |\n| |\n ------')
elif num == 3:
face = (' ------\n| o |\n| o |\n| o |\n ------')
elif num == 4:
face = (' ------\n| o o |\n| o o |\n| |\n ------')
elif num == 5:
face = (' ------\n| o o |\n| o o |\n| o |\n ------')
elif num == 6:
face = (' ------\n| o o |\n| o o |\n| o o |\n ------' )
class Dicegame(Die):
def __init__ (self, name):
self.name = name
def play(self):
Die1 = Die(face, num)
return Die1.roll()
I am trying to make this code more efficient, if you have any suggestions tell me
if user == 'yes' or 'yep' or 'y' or 'Yes' or 'YES!' or 'YES' or 'Yurp' or 'Yeppers' or
'si'or'1':
while user != 5:
user = input('Press 1 to roll, 2 to quit.')
if user == '1':
Dice1 = Dicegame('name')
Dice1.play()
Dice2 = Dicegame('bob')
Dice2.play()
print('')
print('Thanks for playing!')
print('')
elif user == '2':
print('Thanks for playing!')
print('')
exit()
Your user == 'yes' or 'yep' or 'y' ... line will always return True because or is a low-priority option, and a non-empty string's boolean value is True.
I tried to clean your code up a bit, here's what I have
import random
class Die:
def __init__ (self, face, face_value):
self.face = face
self.face_value = face_value
def roll(self):
self.face = random.randint(1, 6)
if self.face == 1:
face = ( ' ------\n| |\n| o |\n| |\n ------')
num = 1
elif self.face == 2:
face = (' ------\n| |\n| o o |\n| |\n ------')
num = 2
elif self.face == 3:
face = (' ------\n| o |\n| o |\n| o |\n ------')
num = 3
elif self.face == 4:
face = (' ------\n| o o |\n| o o |\n| |\n ------')
num = 4
elif self.face == 5:
face = (' ------\n| o o |\n| o o |\n| o |\n ------')
num = 5
elif self.face == 6:
face = (' ------\n| o o |\n| o o |\n| o o |\n ------' )
num = 6
print(face)
return num
user = input('Do you want to play this Dicegame? ')
num = random.randint(1, 6)
if num == 1:
face = ( ' ------\n| |\n| o |\n| |\n ------')
elif num == 2:
face = (' ------\n| |\n| o o |\n| |\n ------')
elif num == 3:
face = (' ------\n| o |\n| o |\n| o |\n ------')
elif num == 4:
face = (' ------\n| o o |\n| o o |\n| |\n ------')
elif num == 5:
face = (' ------\n| o o |\n| o o |\n| o |\n ------')
elif num == 6:
face = (' ------\n| o o |\n| o o |\n| o o |\n ------' )
class Dicegame(Die):
def __init__ (self, name):
self.name = name
def play(self):
Die1 = Die(face, num)
return Die1.roll()
if user in ('yes', 'yep', 'y', 'Yes', 'YES!', 'YES', 'Yurp', 'Yeppers', 'si', '1'):
while user != '5': # what is the purpose of this line?
user = input('Press 1 to roll, 2 to quit. ')
if user == '1':
Dice1 = Dicegame('name')
a = Dice1.play()
Dice2 = Dicegame('bob')
b = Dice2.play()
print(f'Your total is {a+b}')
print('Thanks for playing!')
print('')
elif user == '2':
print('Thanks for playing!')
print('')
exit()
A lookup dictionary will simplify the code a whole lot.
import random
FACES = {
1: " ------\n| |\n| o |\n| |\n ------",
2: " ------\n| |\n| o o |\n| |\n ------",
3: " ------\n| o |\n| o |\n| o |\n ------",
4: " ------\n| o o |\n| o o |\n| |\n ------",
5: " ------\n| o o |\n| o o |\n| o |\n ------",
6: " ------\n| o o |\n| o o |\n| o o |\n ------",
}
YES_REPLIES = {
'yes', 'yep', 'y', 'Yes', 'YES!', 'YES', 'Yurp', 'Yeppers', 'si', '1'
}
class Die:
def __init__(self, face, face_value):
self.face = face
self.face_value = face_value
def roll(self):
num = self.face = random.randint(1, 6)
face = FACES[num]
print(face)
return num
class Dicegame(Die):
def __init__(self, name):
self.name = name
def play(self):
num = random.randint(1, 6)
face = FACES[num]
Die1 = Die(face, num)
return Die1.roll()
user = input('Do you want to play this Dicegame? ')
if user in YES_REPLIES:
while True:
user = input('Press 1 to roll, 2 to quit. ')
if user == '1':
Dice1 = Dicegame('name')
a = Dice1.play()
Dice2 = Dicegame('bob')
b = Dice2.play()
print(f'Your total is {a+b}')
print('Thanks for playing!')
print('')
elif user == '2':
print('Thanks for playing!')
print('')
break

Im trying to see when all the letters have been discoved in Hangman but it is just not working

I have been testing it with just the work TEST and have every letter converting to uppercase for it to register. The part I am having trouble with is:
if Counter(guesses) == Counter(testw):
winner = 1
break
All I want it to do is break out of the while loop and maybe print a message. I have tried to do something I saw online with the counter but it didnt work which is why that counter thing is there (even though I don't really understand it).
import random
import os
import time
from collections import Counter
#someWords = '''apple banana mango strawberry
#orange grape pineapple apricot lemon coconut watermelon
#cherry papaya berry peach lychee muskmelon'''
#someWords = someWords.split(' ')
#word = random.choice(someWords)
testw = "TEST"
point = 0
print("Welcome to Hangman!")
winner = 0
guesses = ''
wrong = ''
total = 0
while point < 6:
if point == 0:
print("-----I\n I\n I\n I\n========")
if point == 1:
print("-----I\n O I\n I\n I\n========")
if point == 2:
print("-----I\n O I\n | I\n I\n========")
if point == 3:
print("-----I\n O I\n /| I\n I\n========")
if point == 4:
print("-----I\n O I\n /|\ I\n I\n========")
if point == 5:
print("-----I\n O I\n /|\ I\n \ I\n========")
if point == 6:
print("-----I\n O I\n /|\ I\n /\ I\n========")
for char in testw:
if char in guesses:
print(char, end = ' ')
else:
print('_ ', end = '')
print("\n")
print('You have ', 6-point, ' guesses left!')
guess = input("Guess a letter: ")
guess = str.upper(guess)
guesses += guess
if guess not in testw:
print("Wrong!")
point += 1
guess += wrong
if guess in testw:
print("Correct!")
guesses += guess
total += 1
if Counter(guesses) == Counter(testw):
winner = 1
break
#end
if winner == 1:
print("Winner")
else:
print("You Lose")
You had two issues here which are causing your wincheck to always fail.
In future, it is handy to utilise print() when you encounter errors that require you to exit a loop based on a condition, as it is likely the check is failing.
You have added the guessed letter to the variable you're using to check for victory before checking if the letter is correct.
guess = str.upper(guess)
guesses += guess
When you resolve this, you are not storing multiple letters if they're found. You only add one instance to guesses
if guess in testw:
print("Correct!")
for letter in testw:
if letter.upper() == guess.upper():
guesses += guess
The above code will fix this, by iterating over every letter in the correct word, and adding the letter to the guesses string each time it is found.
All in all, the below code fixes both of these issues.
import random
import os
import time
from collections import Counter
#someWords = '''apple banana mango strawberry
#orange grape pineapple apricot lemon coconut watermelon
#cherry papaya berry peach lychee muskmelon'''
#someWords = someWords.split(' ')
#word = random.choice(someWords)
testw = "TEST"
point = 0
print("Welcome to Hangman!")
winner = 0
guesses = ''
wrong = ''
total = 0
while point < 6:
if point == 0:
print("-----I\n I\n I\n I\n========")
if point == 1:
print("-----I\n O I\n I\n I\n========")
if point == 2:
print("-----I\n O I\n | I\n I\n========")
if point == 3:
print("-----I\n O I\n /| I\n I\n========")
if point == 4:
print("-----I\n O I\n /|\ I\n I\n========")
if point == 5:
print("-----I\n O I\n /|\ I\n \ I\n========")
if point == 6:
print("-----I\n O I\n /|\ I\n /\ I\n========")
for char in testw:
if char in guesses:
print(char, end = ' ')
else:
print('_ ', end = '')
print("\n")
print('You have ', 6-point, ' guesses left!')
guess = input("Guess a letter: ")
guess = str.upper(guess)
if guess not in testw:
print("Wrong!")
point += 1
guess += wrong
if guess in testw:
print("Correct!")
for letter in testw:
if letter.upper() == guess.upper():
guesses += guess
total += 1
if Counter(guesses) == Counter(testw):
winner = 1
break
#end
if winner == 1:
print("Winner")
else:
print("You Lose")

If statement no longer recognizing input in while loop python

I am writing a hangman game in python and I have variable called userguess and the user will type in what letter they want to use to guess. However, when the while loop begins it's second repeat, the if statement no longer recognizes the userguess and immediately concludes it to be an incorrect guess. I hope you don't mind the amount of code I am using as an example.
movieletters contains the hiddenword split into letters
defaultletters represents the blanks that have to be filled in by the user
I have tried using exception handlers by creating boolean variables but this hasn't done what I needed it to do.
userguess = input("Guess a letter: ")
while True:
for letter in movieletters:
for defaultletter in defaultletters:
if userguess == letter:
print("You guessed correctly")
score += 1
guessedletters.append(userguess)
print(score, "/", totalletters)
print(guessedletters)
print(movie)
if score == totalletters:
print("\n")
print("*************************************************************************************************")
print(movie)
print("*************************************************************************************************")
print("\n")
print("You guessed all the letters correctly and uncovered the word!")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
elif userguess != letter:
incorrectlyguessed += 1
print("INCORRECT!")
print(str(incorrectlyguessed) + "/" + str(tally))
if incorrectlyguessed == 1:
print("""
__________""")
elif incorrectlyguessed == 2:
print("""
|
|
|
|
|__________ """)
elif incorrectlyguessed == 3:
print("""
-----------
|
|
|
|
|__________ """)
elif incorrectlyguessed == 4:
print("""
-----------
| |
|
|
|
|__________ """)
elif incorrectlyguessed == 5:
print("""
-----------
| |
| 0
|
|
|__________ """)
elif incorrectlyguessed == 6:
print("""
-----------
| |
| 0
| |
|
|__________ """)
elif incorrectlyguessed == 7:
print("""
-----------
| |
| 0
| \|/
|
|__________ """)
elif incorrectlyguessed == 8:
print("""
-----------
| |
| 0
| \|/
| |
|__________ """)
elif incorrectlyguessed == 9:
print("""
-----------
| |
| 0
| \|/
| |
|________/_\ """)
if incorrectlyguessed == tally:
print("GAME OVER!")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print(movie)
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
I expect the output to show that the character is recognized as one of the letters in the hidden word in the while loop's second phase. This also effects all of the while loop's phases except for the first one.
Here's an example of the current output:
Output
if the movie was cars then movieletters would be ['c', 'a', 'r', 's']
defaultletters would be _ _ _ _
The problem is that it always matches with the first letter in the list of movieletters.
use if userguess in movieletters to check whether it matches or not
userguess = input("Guess a letter: ")
if userguess in movieletters:
print("You guessed correctly")
score += 1
guessedletters.append(userguess)
print(score, "/", totalletters)
print(guessedletters)
print(movie)
if score == totalletters:
print("\n")
print("*************************************************************************************************")
print(movie)
print("*************************************************************************************************")
print("\n")
print("You guessed all the letters correctly and uncovered the word!")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
else :
incorrectlyguessed += 1
print("INCORRECT!")
print(str(incorrectlyguessed) + "/" + str(tally))
if incorrectlyguessed == 1:
print("""
__________""")
elif incorrectlyguessed == 2:
print("""
|
|
|
|
|__________ """)
elif incorrectlyguessed == 3:
print("""
-----------
|
|
|
|
|__________ """)
elif incorrectlyguessed == 4:
print("""
-----------
| |
|
|
|
|__________ """)
elif incorrectlyguessed == 5:
print("""
-----------
| |
| 0
|
|
|__________ """)
elif incorrectlyguessed == 6:
print("""
-----------
| |
| 0
| |
|
|__________ """)
elif incorrectlyguessed == 7:
print("""
-----------
| |
| 0
| \|/
|
|__________ """)
elif incorrectlyguessed == 8:
print("""
-----------
| |
| 0
| \|/
| |
|__________ """)
elif incorrectlyguessed == 9:
print("""
-----------
| |
| 0
| \|/
| |
|________/_\ """)
if incorrectlyguessed == tally:
print("GAME OVER!")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print(movie)
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue

Hangman game code

I would like to get some help regarding the hangman game. I've created this piece of code and have spent a lot of time trying to refine it but I still can't get the correct output. Would really appreciate your help!
word = choose_word(wordlist)
letters = 'abcdefghijklmnopqrstuvwxyz'
numLetters = len(word)
print numLetters
import re
def hangman(word, numLetters):
print 'Welcome to the game, Hangman!'
print 'I am thinking of a word that is', numLetters, 'letters long'
remainingGuesses = 8
print 'You have', remainingGuesses, 'guesses left.'
letters = 'abcdefghijklmnopqrstuvwxyz'
print 'Available letters:', letters
guess = raw_input("Please guess a letter:")
def filled_word(wordy, guessy):
emptyWord = ['_']*numLetters
if wordy.find(guessy) != -1:
position = [m.start() for m in re.finditer(guessy, wordy)]
for x in position:
emptyWord[x] = guessy
strWord = ''.join(emptyWord)
print 'Good guess =', strWord
else:
strWord = ''.join(emptyWord)
print 'Oops! That letter is not in my word:', strWord
filled_word(word, guess)
emptyWord = ['_']*numLetters
print 'emptyWord =', ['_']*numLetters
while '_' in emptyWord and remainingGuesses>0:
remainingGuesses -= 1
print 'You have', remainingGuesses, 'guesses left'
letters = 'abcdefghijklmnopqrstuvwxyz'
def unused_letters(letters):
letters = 'abcdefghijklmnopqrstuvwxyz'
unusedLetters = str(list(letters).remove(guess))
letters = unusedLetters
return unusedLetters
letters = unused_letters(letters)
print 'Available letters:', letters
guess = raw_input("Please guess a letter:")
if word.find(guess) != -1:
position = [m.start() for m in re.finditer(guess, word)]
for x in position:
emptyWord[x] = guess
strWord = ''.join(emptyWord)
print 'Good guess ='+strWord
emptyWord = list(strWord)
else:
strWord = ''.join(emptyWord)
print 'Oops! That letter is not in my word:', strWord
print hangman(word, numLetters)
print '___________'
print 'Congratulations, you won!'
So the problem is that when I run this, the code runs smoothly until from the second guess onwards, I get Available letters = None instead of the specific letters.
Also, the letter I guess which does appear in the word is not stored. i.e. in guess 1, the code returns the word (for example) 'd____', but in guess 2, upon guessing 'e', the code returns the word 'e_' instead of 'd_e__'. Is it because of the assignment of variables? Of local and global variables? Am quite confused about this.
Would really appreciate the help! Thanks a lot! :)
def choose_word():
word = 'alphabeth'
return {'word':word, 'length':len(word)}
def guess_letter(word_, hidden_word_, no_guesses_, letters_):
print '---------------------------------------'
print 'You have', no_guesses_, 'guesses left.'
print 'Available letters:', letters_
guess = raw_input("Please guess a letter:")
guess = guess.lower()
if guess in letters_:
letters_ = letters_.replace(guess, '')
if guess in word_:
progress = list(hidden_word_)
character_position = -1
for character in word_:
character_position += 1
if guess == character:
progress[character_position] = guess
hidden_word_ = ''.join(progress)
print 'Good guess =', hidden_word_
else:
print 'Oops! That letter is not in my word:', hidden_word_
no_guesses_ = no_guesses_ - 1
else:
print 'The letter "', guess, '" was already used!'
no_guesses_ = no_guesses_ - 1
if hidden_word_ == word_:
print 'Congratulations, you won!'
return True
if no_guesses_ == 0 and hidden_word_ != word_:
print 'Game over! Try again!'
return False
return guess_letter(word_, hidden_word_, no_guesses_, letters_)
def hangman():
hangman_word = choose_word()
print 'Welcome to the game, Hangman!'
print 'I am thinking of a word that is', hangman_word['length'], 'letters long.'
hidden_word = ''.join(['_'] * hangman_word['length'])
no_guesses = 8
letters = 'abcdefghijklmnopqrstuvwxyz'
guess_letter(hangman_word['word'], hidden_word, no_guesses, letters)
hangman()
There are multiple errors in the code. Here it is corrected:-
import re
def unused_letters( letters, guess ): # your main problem is corrected here.
unusedLetters = list( letters )
unusedLetters.remove( guess )
letters = ''.join( unusedLetters )
return letters
def filled_word( wordy, guessy ):
if wordy.find( guessy ) != -1:
position = [m.start() for m in re.finditer( guessy, wordy )]
for x in position:
filled_word.emptyWord[x] = guessy
strWord = ''.join( filled_word.emptyWord )
print 'Good guess.'
print 'Current word: %s' % ''.join( filled_word.emptyWord )
else:
strWord = ''.join( filled_word.emptyWord )
print 'Oops! That letter is not in my word:', strWord
def hangman( word, numLetters ): # you dont need the previous check. Let all be done in the main loop
print 'Welcome to the game, Hangman!'
print 'I am thinking of a word that is', numLetters, 'letters long'
remainingGuesses = 8
letters = 'abcdefghijklmnopqrstuvwxyz'
try:
# # memoizing the current word. for more info, try to understand that functions are
# # also objects and that we are assigning a new attribute the function object here.
filled_word.emptyWord
except:
filled_word.emptyWord = ['_'] * numLetters
while '_' in filled_word.emptyWord and remainingGuesses > 0:
print 'You have', remainingGuesses, 'guesses left'
print 'Available letters:', letters
guess = raw_input( "Please guess a letter:" )
# print 'guess: %s' % guess
if guess in letters:
filled_word( word, guess )
letters = unused_letters( letters, guess )
else:
print 'You guessed: %s, which is not in Available letters: %s' % ( guess, ''.join( letters ) )
print 'Current word: %s' % ''.join( filled_word.emptyWord )
remainingGuesses -= 1
word = "godman"
print hangman( word, numLetters = len( word ) )
if '_' in filled_word.emptyWord:
print 'Ahh ! you lost....The hangman is hung'
else:
print 'Congratulations, you won!'
You can still make it better by checking if the remaining number of guesses are less than the letters to be filled, and take a decision on whether to fail the player or allow it to continue playing.
class Hangman():
def init(self):
print "Welcome to 'Hangman', are you ready to die?"
print "(1)Yes, for I am already dead.\n(2)No, get me outta here!"
user_choice_1 = raw_input("->")
if user_choice_1 == '1':
print "Loading nooses, murderers, rapists, thiefs, lunatics..."
self.start_game()
elif user_choice_1 == '2':
print "Bye bye now..."
exit()
else:
print "I'm sorry, I'm hard of hearing, could you repeat that?"
self.__init__()
def start_game(self):
print "A crowd begins to gather, they can't wait to see some real"
print "justice. There's just one thing, you aren't a real criminal."
print "No, no. You're the wrong time, wrong place type. You may think"
print "you're dead, but it's not like that at all. Yes, yes. You've"
print "got a chance to live. All you've gotta do is guess the right"
print "words and you can live to see another day. But don't get so"
print "happy yet. If you make 6 wrong guess, YOU'RE TOAST! VAMANOS!"
self.core_game()
def core_game(self):
guesses = 0
letters_used = ""
the_word = "pizza"
progress = ["?", "?", "?", "?", "?"]
while guesses < 6:
guess = raw_input("Guess a letter ->")
if guess in the_word and not in letters_used:
print "As it turns out, your guess was RIGHT!"
letters_used += "," + guess
self.hangman_graphic(guesses)
print "Progress: " + self.progress_updater(guess, the_word, progress)
print "Letter used: " + letters_used
elif guess not in the_word and not(in letters_used):
guesses += 1
print "Things aren't looking so good, that guess was WRONG!"
print "Oh man, that crowd is getting happy, I thought you"
print "wanted to make them mad?"
letters_used += "," + guess
self.hangman_graphic(guesses)
print "Progress: " + "".join(progress)
print "Letter used: " + letters_used
else:
print "That's the wrong letter, you wanna be out here all day?"
print "Try again!"
def hangman_graphic(self, guesses):
if guesses == 0:
print "________ "
print "| | "
print "| "
print "| "
print "| "
print "| "
elif guesses == 1:
print "________ "
print "| | "
print "| 0 "
print "| "
print "| "
print "| "
elif guesses == 2:
print "________ "
print "| | "
print "| 0 "
print "| / "
print "| "
print "| "
elif guesses == 3:
print "________ "
print "| | "
print "| 0 "
print "| /| "
print "| "
print "| "
elif guesses == 4:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| "
print "| "
elif guesses == 5:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| / "
print "| "
else:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| / \ "
print "| "
print "The noose tightens around your neck, and you feel the"
print "sudden urge to urinate."
print "GAME OVER!"
self.__init__()
def progress_updater(self, guess, the_word, progress):
i = 0
while i < len(the_word):
if guess == the_word[i]:
progress[i] = guess
i += 1
else:
i += 1
return "".join(progress)
game = Hangman()
You can take an idea from my my program. RUN IT FIRST.
import random
# Starter code start
# The variable word is a random word from the text file 'words.txt'
words = list()
with open("words.txt") as f:
for line in f:
words.append(line.lower())
word = random.choice(words).strip().upper()
# This is the starter code that chooses a word
# Starter code end
letter = ''
# This is the input of letters the user will type in over and over
word_index = 0
# This is the index for the input correct word to be checked against the correct letters
correct_letters = ''
# This is the variable for the correct letters as a list, once the user types them in and they are deemed correct
correct_letters_index = 0
# This is the index to print the correct letters from, in a while statement below. This gets reset to 0 after every time the letters are printed
incorrect_letters = ''
# This is the variable to hold the incorrect letters in.
lives = 6 # ♥
# is the variable to hold the 6 lives, printed as hearts in
win_user = 0
# This is the variable that determines if the user wins or not
guessed_letters = ''
# this variable checks for repeated letters (incorrect + correct ones)
while win_user != len(word) and lives != 0: # 1 mean yes the user have win
if lives == 6:
print(
'''
|--------------------|
| |
|
|
|
|
|
|
|
|
|
|
|
|
|
|_________________________________________
'''
)
elif lives == 5:
print(
'''
|--------------------|
| |
| **|**
| * ()() *
| ** ▼ **
| ** (---) **
| *****
|
|
|
|
|
|
|
|
|_________________________________________
'''
)
elif lives == 4:
print(
'''
|--------------------|
| |
| **|**
| * ()() *
| ** ▼ **
| ** (---) **
| *****
| |
| |
| |
|
|
|
|
|
|_________________________________________
'''
)
elif lives == 3:
print(
'''
|--------------------|
| |
| **|**
| * ()() *
| ** ▼ **
| ** (---) **
| *****
| \ |
| \ |
| \|
|
|
|
|
|
|_________________________________________
'''
)
elif lives == 2:
print(
'''
|--------------------|
| |
| **|**
| * ()() *
| ** ▼ **
| ** (---) **
| *****
| \ | /
| \ | /
| \|/
|
|
|
|
|
|_________________________________________
'''
)
elif lives == 1:
print(
'''
|--------------------|
| |
| **|**
| * ()() *
| ** ▼ **
| ** (---) **
| *****
| \ | /
| \ | /
| \|/
| |
| |
| /
| /
| /
|_________________________________________
'''
)
# This is the while loop that prints only if the player has remaining lives and has not won yet; It prints the ascii drawing for the hangman with the body parts
print("Remaining lives:", end=' ')
for left_lives in range(lives):
print("♥", end=' ') # This prints the remaining lives as hearts
print()
# labels all correct letters like: cake into _ _ _ _
while word_index != (len(word)) and word_index <= (len(word) - 1):
while correct_letters_index != (len(correct_letters)) and word_index <= (len(word) - 1):
if word[word_index] != correct_letters[correct_letters_index]:
correct_letters_index += 1
elif word[word_index] == correct_letters[correct_letters_index]:
print(word[word_index], end=' ')
word_index += 1
correct_letters_index = 0
if word_index <= (len(word) - 1):
print("__", end=' ')
correct_letters_index = 0
word_index += 1
print()
# This goes through the correct word, and prints out the correct letters that have been typed in, in order
# It also types out the blank spaces for letters
if win_user != len(word):
# This asks the user for another letter, and sets the checking value on the correct word back to 0 for the next run through
letter = str(input("Enter a letter: ")).upper()
if letter in guessed_letters:
print("The letter had already been guessed: " + str(letter))
if letter not in guessed_letters:
if letter not in word:
incorrect_letters += letter
guessed_letters += incorrect_letters
lives -= 1
elif letter in word:
correct_letters += letter
guessed_letters += correct_letters
for user_word in word:
if letter in user_word:
win_user += 1
# This takes in the letter if it has not previously been deemed in a variable, either correct or not.
# It also checks if the letter is correct, or not, and adds it to the variable
# If the letter has already been typed, it will also let the user know that
word_index = 0
if lives == 0:
print(
'''
|--------------------|
| |
| **|**
| * ()() *
| ** ▼ **
| ** (---) **
| *****
| \ | /
| \ | /
| \|/
| |
| |
| / \\
| / \\
| / \\
|_________________________________________
'''
)
# This prints the full hangman, and that the user loses if their lives reach 0
print("User Looses !!")
print("Incorrect letters typed: " + str(incorrect_letters))
print("The word is: " + str(word))
elif win_user == len(word):
print("The word is: " + str(word))
# This prints the user wins if all characters are printed out for the correct word
print("Incorrect letters typed: " + str(incorrect_letters))
print("User Wins !")
print(
'''
☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺
☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺
'''
)

Categories

Resources