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(
'''
☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺
☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺
'''
)
Related
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]
I'm trying to create a hangman game with python. I know there is still a lot to complete but I'm trying to figure out the main component of the game which is how to compare the user inputted string (one letter) with the letters in one of the three randomly selected words.
import random
print("Welcome to hangman,guess the five letter word")
words =["china", "ducks", "glass"]
correct_word = (random.choice(words))
guess = input(str("Enter your guess:"))
guess_left = 10
guess_subtract = 1
if guess == "":
guess_left = guess_left - guess_subtract
print("you have" + guess_left + "guesses left")
I think you need a skeleton and then spend some time to improve the game.
import random
print "Welcome to hangman, guess the five letter word"
words = ["china", "ducks", "glass"]
correct_word = (random.choice(words))
trials = 10
for trial in range(trials):
guess = str(raw_input("Enter character: "))
if (len(guess) > 1):
print "You are not allowed to enter more than one character at time"
continue
if guess in correct_word:
print "Well done! '" + guess + "' is in the list!"
else:
print "Sorry " + guess + " does not included..."
Your next step could be print out something like c_i__ as well as the number of trials left. Have fun :)
When you finish with the implementation, take some time and re-implement it using functions.
I've completed this project yesterday; (to anyone else reading this question) take inspiration if needed.
import random
stages = ['''
+---+
| |
O |
/|\ |
/ \ |
|
=========
''', '''
+---+
| |
O |
/|\ |
/ |
|
=========
''', '''
+---+
| |
O |
/|\ |
|
|
=========
''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========
''', '''
+---+
| |
O |
|
|
|
=========
''', '''
+---+
| |
|
|
|
|
=========
''']
#used to choose random word
random_lst=['addition','adequate','adjacent','adjusted','advanced','advisory','advocate','affected','aircraft','alliance','although','aluminum','analysis','announce','anything','anywhere','apparent','appendix','approach','approval','argument','artistic','assembly']
chosen_word = random.choice(random_lst)
#used to create display list + guess var
print("Welcome to hangman! ")
print("--------------------")
print("you have 6 lives." )
print(" ")
print (stages[-1])
display = []
for letters in chosen_word:
display += "_"
print(display)
print(" ")
#used to check if guess is equal to letter, and replace pos in display if yes.
lives = 6
game_over = False
#use the var guesses to store guesses and print at every guess to let player know what letters they tried already.
guesses = ""
while not game_over:
guess = input("Guess a letter. ")
print(" ")
guesses += (guess + " , ")
for pos in range(len(chosen_word)):
letter = chosen_word[pos
if letter == guess:]
display[pos] = letter
print("√")
print("- - -")
print(" ")
if display.count("_") == 0:
print("Game over. ")
game_over = True
elif guess not in chosen_word:
lives -= 1
print(f"Wrong letter. {lives} lives left. ")
print("- - - - - - - - - - - - - - - - - - -")
print(" ")
if lives == 0:
print (stages[0])
elif lives == 1:
print (stages[1])
elif lives == 2:
print (stages[2])
elif lives == 3:
print(stages[3])
elif lives == 4:
print(stages[4])
elif lives == 5:
print(stages[5])
elif lives == 6:
print(stages[6])
elif lives == 0:
game_over = True
print("Game over. ")
print(f"letters chosen: {guesses}")
print(" ")
print(display)
print(" ")
if lives == 0 or display.count("_") == 0:
break
if lives == 0:
print("Game over. You lose.")
elif lives > 0:
print("Congrats, you win! ")
What you can do is treat the string like an array/list.
So if you use loops:
x = ""#let's assume this is the users input
for i in range(len(y)): #y is the string your checking against
if x == y[i]:
from here what I'm thinking is that if they are equal it would add that letter to a string
Let's say the string is "Today was fun" then would have an array like this, [""."" and so on but you'd have to find a way to factor in spaces and apostrophes. So if the letter is == to that part of the string
#this is a continuation of the code, so under if
thearray[theposition] == the letter
But looking a your code your game is diffrent from the regular one so, also consider using a while look
gamewon = False
number of trials = 10
while gamewon == False and number of trials > 0:
#the whole checking process
if x == guess:
gamewon == True
print ........# this is if your doing word for word else use
the code above
else:
number of trials = number of trials - 1
I think that's it I know its a bit all over the place but you can always ask for help and I'll explain plus I was referring to your code things i thought you could fix
First you should accept both a and A by using guess = guess.lower(). The you have to search the string for the character guessed and find the positions.
guess = guess.lower()
# Find the position(s) of the character guessed
pos = [idx for idx,ch in enumerate(correct_word) if ch == guess]
if pos:
print('Letter Found')
guess_left -= 1
Another way to understand the for-loop is:
pos = []
for idx,ch in enumerate(correct_word):
if ch == guess:
pos.append(idx)
I tried to add graphics to my code for a hangman game. The graphics didn't appeared and when you guess a letter it automatically says that the game is over. I am not sure what is wrong as I am very new to python and coding.
import random
Graphics=['''
------------
| |''','''
------------
| |
| O''','''
------------
| |
| O
| / |''','''
------------
| |
| O
| / |
| | ''','''
------------
| |
| O
| / |
| |
| / |
|
| ''']
start = str(input("Welcome to Hangman!"))
failures = 0
allowed = 6
guesses_left = 6
guessed = str()
wordlist = ['kittens' , 'keen', 'right', 'square', 'baseball','soccer', 'square','house', 'safe', 'pizza', 'pasta', 'Loyola', 'cat', 'dog', 'rambler', 'Chicago', 'Pittsburgh']
def correct(guess):
if guess in word:
if guess not in guessed:
print("Correct")
return(True)
else:
if guess not in word and len(guess) == 1 and guess in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ':
if guess not in guessed:
print("Incorrect!")
return(False)
print("Guess this word!")
print("You can input any letter from A to Z and the space key.")
wordnumber = random.randint(0, len(wordlist))
word = (wordlist[wordnumber])
guessed_letters = len(word) * ['_']
print(' '.join(guessed_letters))
while failures < allowed:
guess = str(input("Guess a letter!"))
if len(guess) != 1 or guess not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ':
print("That is not a letter, try again.")
if guess in guessed:
print("You have already guessed that letter, try again.")
iscorrect = correct(guess)
guessed = guessed, guess
if iscorrect == True:
for position, letter in enumerate(word):
if letter == guess:
guessed_letters[position] = letter
print(' '.join(guessed_letters))
if iscorrect == False:
print("Wrong!")
failures = failures+1
guesses_left -= 1 # Number of guesses left
print("You have", guesses_left , "guesses left.")
if (guessed_letters == word):
print('''
You have successfully guessed the word!
''')
else:
print('''
You have lost the game!
''')
break
The reason the game exists is due to a break that is called at the end of the very first loop. The else should also be based on the condition that there are no guesses left:
if (guessed_letters == word):
print('''
You have successfully guessed the word!
''')
break
elif not guesses_left:
print('''
You have lost the game!
''')
break
Regarding the "graphics". This can be printed each time you get a wrong answer. And I recommend using if/else instead of two ifs here:
if iscorrect == True:
for position, letter in enumerate(word):
if letter == guess:
guessed_letters[position] = letter
print(' '.join(guessed_letters))
else:
print("Wrong!")
failures = failures+1
guesses_left -= 1 # Number of guesses left
print(Graphics[6-guesses_left])
print("You have", guesses_left , "guesses left.")
Graphics[6-guesses_left] means go look up the index in Graphics that is equal to the original number of guesses (6), minus the number of remaining guesses.
Imagine the user has input(ed) the letter 'f'. Then the error below pops up.
wrdsplit = list('ferret')
guess = input('> ')
# user inputs `f`
print(wrdsplit.index(guess))
But this results in ValueError: 'f' is not in list.
OMG....... Thank you guys so much for your help. I finally fixed it. Here... have fun playing my Hangman Game:
import random
import time
import collections
def pics():
if count == 0:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /|\ ")
print ("| / \ ")
print ("| ")
print ("| ")
elif count == 1:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /|\ ")
print ("| / ")
print ("| ")
print ("| ")
elif count == 2:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /|\ ")
print ("| ")
print ("| ")
print ("| ")
elif count == 3:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /| ")
print ("| ")
print ("| ")
print ("| ")
elif count == 4:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| | ")
print ("| ")
print ("| ")
print ("| ")
elif count == 5:
print (" _________ ")
print ("| | ")
print ("| GAME OVER ")
print ("| YOU LOSE ")
print ("| ")
print ("| ")
print ("| (**)--- ")
print("Welcome to HANGMAN \nHave Fun =)")
print("You can only get 5 wrong. You will lose your :\n1. Right Leg\n2.Left Leg\n3.Right Arm\n4.Left Arm\n5.YOUR HEAD... YOUR DEAD")
print("")
time.sleep(2)
words = "ferret".split()
word = random.choice(words)
w = 0
g = 0
count = 0
correct = []
wrong = []
for i in range(len(word)):
correct.append('#')
wrdsplit = [char for char in "ferret"]
while count < 5 :
pics()
print("")
print("CORRECT LETTERS : ",''.join(correct))
print("WRONG LETTERS : ",wrong)
print("")
print("Please input a letter")
guess = input("> ")
loop = wrdsplit.count(guess)
if guess in wrdsplit:
for count in range(loop):
x = wrdsplit.index(guess)
correct[x] = guess
wrdsplit[x] = '&'
g = g + 1
if "".join(correct) == word:
print("Well done... You guessed the word in", g ,"guesses and you got", w , "wrong")
print("YOU LIVED")
break
elif guess not in wrdsplit:
wrong.append(guess)
w = w + 1
g = g + 1
count = count +1
pics()
print("The correct word was : ",word)
Try this code to see if it works and does what you want
# Get this from a real place and not hardcoded
wrdsplit = list("ferret")
correct = ["-"]*len(wrdsplit) # We fill a string with "-" chars
# Ask the user for a letter
guess = input('> ')
if guess in wrdsplit:
for i, char in enumerate(wrdsplit):
if char == guess:
correct[i-1] = guess
# Calculate the number of guesses
if "-" in correct:
g = len(set(correct)) - 1
else:
g = len(set(correct))
# Print the right word
print("".join(correct))
The set generates an array without duplicates to count how many guesses he has done, if a "-" is found, one is substracted as that character is not a guess.
The only error I am seeing in here (based on your earlier code) is:
if guess in wrdsplit:
for count in range(len(wrdsplit)):
x = wrdsplit.index(guess)
wrdsplit[x] = '&'
correct[x] = guess
g = g + 1
wrdsplit[x] = '&' # x is out of scope
if "".join(correct) == word:
print("Well done... You guessed the word in", g ,"guesses and you got", w , "wrong")
print("YOU LIVED")
break
Now if you were to continue to retry things in here looking for f, it won't work because you've changed 'f' to '&' so you will get an error for f not in list. You just got caught in a nasty little bug cycle.
You should consider using dictionaries for this instead.
So, I've finished my Hangman project for a coding class and it's stuck in a loop where it just keeps asking if you want to play, after that it defines the word to play but it also TELLS you which word to play you're going to play. I think the chained whiles and ifs have some wrong variables.
So, I beg for your help.
__author__ = 'Rodrigo Cano'
#Modulos
import random
import re
#Variables Globales
intentos = 0
incorrectos = 0
palabras = [(1,"disclosure"),(1,"thenational"),(1,"foals"),(1,"skepta"),(1,"shamir"),(1,"kanye"),
(1,"fidlar"),(1,"lcdsoundsystem"),(1,"lorde"),(1,"fkatwigs"),(1,"miguel"),(1,"rtj"),
(1,"boniver"),(1,"strokes"),(2,"vaporwave"),(2,"witchouse"),(2,"shoegaze"),(2,"memerap"),
(2,"paulblartisoursaviour"),(3,"glockenspiel"),(3,"aesthetic"),(3,"schadenfreude"),
(3,"bonvivant"),(3,"swag"),(3,"jue")]
Ascii_Art =[""]
Dibujo = ' '
palabra_a_jugar = ''
Array_Palabra = []
Nuevas_Letras = ''
letras = []
Vidas = 0
i = len(Array_Palabra)
#Funciones
def Definir_Palabra():
eleccion = int(input("Bienvenido, que categoria quiere usar:"
'\n'"1 - Musica que Escuche Mientras Lo Hacia"
'\n'"2 - Generos Musicales"
'\n'"3 - Palabras Pretenciosas"))
palabras_escogidas = [i for i in palabras if eleccion in i ]
palabra_a_jugar = str(palabras_escogidas[random.randint(0,len(palabras_escogidas))].__getitem__(1))
Array_Palabra = len(palabra_a_jugar) * ['*']
return palabra_a_jugar, Array_Palabra
def Letras_En_Palabra(letra):
letras = [i for i, x in enumerate(palabra_a_jugar) if x == letra]
for i in range (0, len(letras)):
Array_Palabra[letras] = letra
return letras,Array_Palabra
def Letras_Jugadas(letra):
for i in range(0,len(Nuevas_Letras)):
Nuevas_Letras = re.findall(letra,Nuevas_Letras[i])
if Nuevas_Letras != []:
return 1
return Nuevas_Letras
def Eleccion():
Choice = input("Quiere Jugar?")
if Choice == 'si':
Choice = 1
elif Choice == 'no':
Choice = 0
return Choice
# Juego
Choice = Eleccion()
def Juego(Choice):
i = len(Array_Palabra)
while Choice == 1:
print(Definir_Palabra())
while i != 0 :
tiro = str.lower(input("adivine una letra"))
if Letras_Jugadas(tiro) != 1:
Nuevas_Letras = Nuevas_Letras + tiro
letras = Letras_En_Palabra(tiro)
if Letras_Jugadas(tiro) != []:
i = len(letras) - 1
print("Letras Utilizadas",Nuevas_Letras)
print(Letras_En_Palabra(tiro))
else:
Vidas = Vidas + 1
Dibujo += Ascii_Art[Vidas]
print("WROOOONG")
print(Dibujo)
print("Letras Utilizadas",Nuevas_Letras)
if Vidas ==9:
i = 0
else:
print("Letra ya Juagada",Nuevas_Letras)
Eleccion()
Juego(Choice)
The last line in your Juego should be Choice = Eleccion(), otherwise, you're not actually changing the value of Choice, so the loop continues indefinitely.
def Juego(Choice):
i = len(Array_Palabra)
while Choice == 1:
print(Definir_Palabra())
while i != 0 :
tiro = str.lower(input("adivine una letra"))
if Letras_Jugadas(tiro) != 1:
Nuevas_Letras = Nuevas_Letras + tiro
letras = Letras_En_Palabra(tiro)
if Letras_Jugadas(tiro) != []:
i = len(letras) - 1
print("Letras Utilizadas",Nuevas_Letras)
print(Letras_En_Palabra(tiro))
else:
Vidas = Vidas + 1
Dibujo += Ascii_Art[Vidas]
print("WROOOONG")
print(Dibujo)
print("Letras Utilizadas",Nuevas_Letras)
if Vidas ==9:
i = 0
else:
print("Letra ya Juagada",Nuevas_Letras)
"""
>>>> CHANGED <<<<
"""
Choice = Eleccion()
Otherwise, the way you had it simply calls the function Eleccion but doesn't return the value to the Choice variable in scope of Juego function.
Just need to indent :)
import random
# defining the main method
def main():
print "Hello Welcome to Python Hangman!!!"
random_word()
user_input()
# defining the dictionary_list to be used as the guessing word
def random_word():
dictionary_list= ["ant", "bath", "car", "dog", "electric", "foil", "grape", "heat", "ice", "jolly",
"knight", "lemon", "money", "need", "open", "park", "quote", "rough", "salty",
"teach", "under", "village", "warmth", "xavier", "yelp", "zipper"]
# making rand global so it can be used within deifferent functions
global rand
# randomly choosing a word from the dictionary_list and assign to the variable rand
rand = random.choice(dictionary_list)
return rand
# user guessing
def user_input():
guesses = 0
wrong_guess = 0
guess_left = 10
correct_letters_list = ""
wrong_letters_list =""
print "You have \033[1;34;15m 10 \033[0;30;15m guesses"
#getting the length of the word
length = len(rand)
print "The word is: " + "\033[1;35;15m" + str(length) + "\033[0;30;15m" + " characters long"
# loops around until the user has used all their 6 guesses are used up
while guesses < 10 :
guess = raw_input("Guess a Letter [a-z]: ").lower()
# stop case sensitivity
# if the letter guessed by the user is in rand string print correct else print wrong
if guess in rand:
correct_letters_list += guess
print "\033[1;32;15mcorrect"
print "correct letters:"
print "\033[0;30;15m" + correct_letters_list
print "incorrect letters:"
print "\033[0;30;15m" + wrong_letters_list
# each time the user guesses + 1 to the guesses tally
guesses +=1
guess_cal = guess_left - guesses
print "You have: " + str(guess_cal) + " guesses left"
# if rand contains guess more than once tell user
if rand.count(guess) > 1 :
print "The word contains the letter " + str(guess) + " " + "\033[1;36;15m" + str(rand.count(guess)) + "\033[0;30;15m" + " times"
else:
wrong_letters_list += guess
print "\033[1;31;15mwrong"
print "incorrect letters:"
print "\033[0;30;15m" + wrong_letters_list
print "correct letters:"
print "\033[0;30;15m" + correct_letters_list
guesses += 1
guess_cal = guess_left - guesses
print "You have: " + str(guess_cal) + " guesses left"
wrong_guess += 1
if wrong_guess == 1:
print "________ "
print "| | "
print "| "
print "| "
print "| "
print "| "
if wrong_guess == 2:
print "________ "
print "| | "
print "| 0 "
print "| "
print "| "
print "| "
if wrong_guess == 3:
print "________ "
print "| | "
print "| 0 "
print "| / "
print "| "
print "| "
if wrong_guess == 4:
print "________ "
print "| | "
print "| 0 "
print "| /| "
print "| "
print "| "
if wrong_guess == 5:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| "
print "| "
if wrong_guess == 6:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| / "
print "| "
if wrong_guess >= 7:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| / \ "
print "| "
choice = raw_input("Do you wish to guess the word? (Y/N): ").lower()
if choice == 'y':
word = raw_input("Please enter the word: ").lower()
if word == rand:
print "Well Done you Guessed Correctly, the word was: " + rand
# if the user has guessed correctly + 10 to the guesses tally to end the game
guesses += 10
else:
print "Incorrect, Game Over!! The word was: " + rand
guesses += 10
# if user chooses n continue with the game
if choice == 'n':
continue
# if the user has used up all their 10 guesses print Game Over!!
if guesses == 10:
print "End of Game you ran out of guesses!!!"
if __name__ == "__main__":
main()