import random
HANGMANPICS = ['''
+------+
| |
| |
|
|
|
|
|
|
|
|
==============''', '''
+ +
| |
| |
O |
|
|
|
|
|
|
|
==============''', '''
+------+
| |
| |
| |
O |
| |
| |
| |
|
|
==============''']
words = 'ant baboon badger bat bear beaver beetle bird camel cat clam cobra cougar coyote crab crane crow deer dog donkey duck eagle ferret fish fox frog goat goose hawk iguana jackal koala leech lemur lion lizard llama mite monkey moose moth mouse mule newt otter owl oyster panda parrot pigeon python quail rabbit ram rat raven rhino salmon seal shark sheep skunk sloth slug snail snake spider squid stork swan tick tiger toad trout turkey turtle wasp weasel whale wolf wombat worm zebra'.split()
# This function returns a random string from the list of strings.
def getRandomWord(wordList):
wordIndex = random.randint(0, len(wordList) - 1)
return wordList[wordIndex]
def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
print HANGMANPICS[len(missedLetters)]
print
print 'Missed Letters:',
for letter in missedLetters:
print letter,
print
blanks = '_' * len(secretWord)
for i in range(len(secretWord)):
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
for letter in blanks:
print letter,
print
def getGuess(alreadyGuessed):
while True:
print 'Guess a letter.'
guess = raw_input()
guess = guess.lower()
if len(guess) != 1:
print 'Please enter a single letter.'
elif guess in alreadyGuessed:
print 'You have already guessed that letter. Choose again.'
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print 'Please enter a LETTER.'
else:
return guess
def playAgain():
print 'Do you want to play again? (yes or no)'
return raw_input().lower().startswith('y')
print 'HANGMAN'
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False
while True:
displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
guess = getGuess(missedLetters + correctLetters)
if guess in secretWord:
correctLetters = correctLetters + guess
foundAllLetters = True
for i in range(len(secretWord)):
if secretWord[i] not in correctLetters:
foundAllLetters = False
break
if foundAllLetters:
print 'Yes! The secret word is "' + secretWord + '"! You have won!'
gameIsDone = True
else:
missedLetters = missedLetters + guess
if len(missedLetters) == len(HANGMANPICS) - 1:
displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
print 'You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"'
gameIsDone = True
if gameIsDone:
if playAgain():
missedLetters = ''
correctLetters = ''
gameIsDone = False
secretWord = getRandomWord(words)
else:
break
In the second function displayBoard, 4 parameters are passed. I understand HANGMANPICS, missedLetters and secretWord, but I don't understand where the argument for correctLetters is defined/substituted.
In layman's term (as I am a newbie), where does it say what correctLetters should do? I have been studying this game for a week now, and so far everything seems Ok, except this one.
Please help.
correctLetters is initialized in this line:
correctLetters = ''
and appended to inside the while loop that contains the bulk of the game logic:
if guess in secretWord:
correctLetters = correctLetters + guess
It is used to keep track of correctly guessed letters, and passed to displayBoard so that they can be shown on screen.
As an aside, since white space is important in Python code, it's worth formatting your question correctly.
Doing a quick keyword search for correctLetters you can see it is described as a string. In the function displayBoard you can see it used on line 78.
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
It is being used to put in the letter instead of a blank if the user has guessed that letter.
It is described on one of the bullets here
It's usage is explained here
Related
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)
So I'm working on inventwithpython, and I'm on the hangman 2 chapter. But when the game starts, it's already at the 7th strike hangman picture. I'm not sure where the problem is. Here is my code:
import random
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''', '''
+----+
| |
[O |
/|\ |
/ \ |
|
==========''', '''
+----+
| |
[O] |
/|\ |
/ \ |
|
==========''']
words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()
def getRandomWord(wordList):
# This function returns a random string from the passed list of strings.
wordIndex = random.randint(0, len(wordList) - 1)
return wordList[wordIndex]
def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
print(HANGMANPICS[len(HANGMANPICS) -1])
print()
print('Missed letters:', end=' ')
for letter in missedLetters:
print(letter, end=' ')
print()
blanks = '_' * len(secretWord)
for i in range(len(secretWord)): # replace blanks with correctly guessed letters
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
for letter in blanks: # show the secret word with spaces in between each letter
print(letter, end=' ')
print()
def getGuess(alreadyGuessed):
# Returns the letter the player entered. This function makes sure the player entered a single letter, and not something else.
while True:
print('Guess a letter.')
guess = input()
guess = guess.lower()
if len(guess) != 1:
print('Please enter a single letter.')
elif guess in alreadyGuessed:
print('You have already guessed that letter. Choose again.')
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print('Please enter a LETTER.')
else:
return guess
def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False
while True:
displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
# Let the player type in a letter.
guess = getGuess(missedLetters + correctLetters)
if guess in secretWord:
correctLetters = correctLetters + guess
# Check if the player has won
foundAllLetters = True
for i in range(len(secretWord)):
if secretWord[i] not in correctLetters:
foundAllLetters = False
break
if foundAllLetters:
print('Yes! The secret word is "' + secretWord + '"! You have won!')
gameIsDone = True
else:
missedLetters = missedLetters + guess
# Check if player has guessed too many times and lost
if len(missedLetters) == len(HANGMANPICS) - 1:
displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
print('You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
gameIsDone = True
# Ask the player if they want to play again (but only if the game is done).
if gameIsDone:
if playAgain():
missedLetters = ''
correctLetters = ''
gameIsDone = False
secretWord = getRandomWord(words)
else:
break
(To explain more about my problem:) So when you start the game, the hangman image should be the first picture in HANGMANPICS, but instead, it's the last picture in HANGMANPICS. I do have a feeling the problem in on print(HANGMANPICS[len(HANGMANPICS) -1]) but may not be there either. All help would be appreciated!
Yes, that's the problem. You specifically tell it to print the last element of the file. Instead, use the length of the missed letters list.
print(HANGMANPICS[len(missedLetters)])
With that change, it seems to work pretty well.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have created a hangman game in python 3. The game is working fine. The letters are working fine. Everything is working fine. There is one thing that is bothering me. After I type the wrong word, the ascii drawing is not updating. It is still on the first drawing though the life gets reduced. It is made for five chances and after five attempts player gets killed. The drawing is not updating.
I am doing lessons from invent with python.
import random
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()
def getRandomWord(wordList):
wordIndex = random.randint(0, len(wordList) - 1)
return wordList[wordIndex]
def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
print(HANGMANPICS[len(missedLetters)])
print()
print('Missed letters:', end =' ')
for letter in missedLetters:
print(letter, end=' ')
print()
blanks = '_' * len(secretWord)
for i in range(len(secretWord)):
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
for letter in blanks:
print(letter, end=' ')
print()
def getGuess(alreadyGuessed):
while True:
print('Guess a letter.')
guess = input()
guess = guess.lower()
if len(guess) != 1:
print('Please enter a single letter')
elif guess in alreadyGuessed:
print('You have already guessed this letter.Choose again')
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print('Please enter a letter.')
else:
return guess
def playAgain():
print('Want to play again, yes or no?')
return input().lower().startswith('y')
print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False
while True:
displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
#let the player type the letter
guess = getGuess(missedLetters + correctLetters)
if guess in secretWord:
correctLetters = correctLetters + guess
foundAllLetters = True
for i in range(len(secretWord)):
if secretWord[i] not in correctLetters:
foundAllletters = False
break
if foundAllLetters:
print('Yes the secret word is' + secretWord + 'You have won')
gameIsDone = True
else:
missedletters = missedLetters + guess
#check players has guessed to many times and lost
if len(missedLetters) == len(HANGMANPICS) - 1:
displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
print('You have run out of guesses! \nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses , the word was ' + secretword + '!')
gameIsDone = True
#Ask the player if they want to play again
if gameIsDone:
if playAgain():
missedLetters = ''
correctLetters = ''
gameIsDone = False
secretWord = getRandomWord(words)
else:
break
Check your capitalization of your variables:
# You have
missedletters = missedLetters + guess
# should be
missedLetters = missedLetters + guess
^
Also:
# You have
... + ' correct guesses , the word was ' + secretword + '!')
# should be
... + ' correct guesses , the word was ' + secretWord + '!')
^
The first issue was causing your board not to update -- the second one caused it not run (for me).
I need to make a hangman program with python program but i don't know how to continue.
in the program
i are given 6 chances, otherwise known as a “life line”, to guess the letters in the word. Every wrong guess will shorten the “life line”. The game will end when you guess the word correctly or you have used up all your “life line”. Here is the sample output:
['_', '_', '_', '_']
***Life Line***
-+-+-+-+-+-+
$|$|$|$|$|$|
-+-+-+-+-+-+
Enter your guess: a
['_', '_', '_', '_']
***Life Line***
-+-+-+-+-+
$|$|$|$|$|
-+-+-+-+-+
Incorrect Guess: ['a']
...................................
Enter your guess: b
['b', '_', '_', '_']
***Life Line***
-+-+-+-+-+
$|$|$|$|$|
-+-+-+-+-+
Incorrect Guess: ['a']
...................................
Enter your guess: l
['b', 'l', '_', '_']
***Life Line***
-+-+-+-+-+
$|$|$|$|$|
-+-+-+-+-+
Incorrect Guess: ['a']
...................................
Enter your guess: o
['b', 'l', '_', '_']
***Life Line***
-+-+-+-+
$|$|$|$|
-+-+-+-+
Incorrect Guess: ['a', 'o']
...................................
Enter your guess: u
['b', 'l', 'u', '_']
***Life Line***
-+-+-+-+
$|$|$|$|
-+-+-+-+
Incorrect Guess: ['a', 'o']
...................................
Enter your guess: e
['b', 'l', 'u', 'e']
***Life Line***
-+-+-+-+
$|$|$|$|
-+-+-+-+
Incorrect Guess: ['a', 'o']
...................................
You Got it Right! Well Done!
i have already typed in the first few codes but got stuck.
import random
wordList = ["Mary","Tian Pei","Pong"]
randname = random.choice ( wordList)
print randname
resultList = [ ]
for i in range(len(randname)):
resultList.append("_")
print resultList
Create the blank list:
>>> name = "Mary"
>>> blanks = ["_" for letter in name]
>>> blanks
['_', '_', '_', '_']
Create a list of incorrect guesses:
>>> incorrect_guesses = # you figure this one out
Set up your life-lines:
>>> life_lines = # you figure this one out
Prompt for a guess:
>>> guess = raw_input("Guess: ")
Guess: a
>>> guess
'a'
Save a variable which says whether or not the guess was incorrect:
>>> incorrect = # you figure this one out
Iterate over the name and replace the respective blank line in blanks with the letter if the respective letter in name is the same as the guess:
>>> for i in range(len(name)):
... if name[i] == guess:
... incorrect = # you figure this one out
... blanks[i] = # you figure this one out
...
>>> blanks
['_', 'a', '_', '_']
If incorrect is True, add the guess to the incorrect_guesses (in this case, since the guess was correct, it wouldn't update) and subtract a life-line:
>>> if incorrect:
... incorrect_guesses.append( # you figure this one out )
... life_lines -= # you figure this one out
...
To check for equivalence, join the letters in blanks to re-form the original word so that you can compare the two:
>>> final = ''.join(blanks) # this connects each letter with an empty string
>>> final
'_a__'
The general control structure could be the following:
choose random word
create blanks list
set up life-lines
while life_lines is greater than 0 and word not completed:
print blanks list
print life_lines graphic
if there are incorrect guesses:
print incorrect guesses
prompt for guess
check if correct and fill in blanks
if incorrect:
add to incorrect guesses and subtract a life-line
if word completed:
you win
else:
you lose
It's up to you to fill in the blanks I wrote here (and to write your own routines for printing the life-line graphics and such).
You can do something like this. See the comments in the code for explanations about the logic.
#!/usr/bin/env python
import random
wordList = ["Mary","Tian Pei","Pong"]
randname = random.choice ( wordList)
resultList = []
# When creating the resultList you will want the spaces already filled in
# You probably don't want the user to guess for spaces, only letters.
for letter in randname:
if letter == ' ':
resultList.append(' ')
else:
resultList.append("_")
# We are storing the number of lifeline 'chances' we have here
# and the letters that have already been guessed
lifeline = 6
guesses = []
# The game does not end until you win, on run out of guesses
while guesses != 0:
# This prints the 'scoreboard'
print resultList
print '***Life Line***'
print '-+' * lifeline
print '$|' * lifeline
print '-+' * lifeline
print 'Incorrect Guess: %s' % guesses
# If the win condition is met, then we break out of the while loop
# I placed it here so that you see the scoreboard once more before
# the game ends
if ''.join(resultList) == randname:
print 'You win!'
break
# raw_input because I'm using 2.7
g = raw_input("What letter do you want to guess?:")
# If the user has already guessed the letter incorrectly,
# we want to forgive them and skip this iteration
if g in guesses:
print 'You already guessed that!'
continue
# The lower port here is important, without it guesses are
# case sensitive, which seems wrong.
if g.lower() in [letter.lower() for letter in randname]:
# this goes over each letter in randname, then flips
# the appropriate postions in resultList
for pos, letter in enumerate(randname):
if g.lower() == letter.lower():
resultList[pos] = letter
# If the letter is not in randname, we reduce lifeline
# add the guess to guesses and move on
else:
lifeline -= 1
guesses.append(g)
Let me know if you need anything clarified.
import random
"""
Uncomment this section to use these instead of life-lines
HANGMAN_PICS = ['''
+---+
|
|
|
===''', '''
+---+
O |
|
|
===''', '''
+---+
O |
| |
|
===''', '''
+---+
O |
/| |
|
===''', '''
+---+
O |
/|\ |
|
===''', '''
+---+
O |
/|\ |
/ |
===''', '''
+---+
O |
/|\ |
/ \ |
===''']
"""
HANGMAN_PICS = ['''
-+-+-+-+-+-+
$|$|$|$|$|$|
-+-+-+-+-+-+ ''','''
-+-+-+-+-+
$|$|$|$|$|
-+-+-+-+-+ ''','''
-+-+-+-+
$|$|$|$|
-+-+-+-+ ''','''
-+-+-+
$|$|$|
-+-+-+ ''','''
-+-+
$|$|
-+-+ ''','''
-+
$|
-+ ''','''
-+
|
-+''']
words = '''ant baboon badger bat bear beaver camel kangaroo chicken panda giraffe
raccoon frog shark fish cat clam cobra crow deer dog donkey duck eagle ferret fox frog
goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot
pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork
swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'''.split()
# List of all the words
def getRandomWord(wordList):
wordIndex = random.randint(0, len(wordList) - 1) # Random index
# Indexes in python start from 0, therefore len(wordList) - 1
return wordList[wordIndex] # Chooses a random word from the list which is a passed through the function
# Returns the random word
def displayBoard(missedLetters, correctLetters, secretWord):
print(HANGMAN_PICS[len(missedLetters)])
print()
print('Missed letters:', end=' ')
for letter in missedLetters:
print(letter, end=' ')
# Displaying each letter of the string 'missedLetters'
print()
blanks = '_' * len(secretWord)
for i in range(len(secretWord)):
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
# Checking for characters that match and replacing the blank with the character
for letter in blanks:
print(letter, end=' ')
print()
# Printing the blanks and correct guesses
def getGuess(alreadyGuessed):
while True:
print('Guess a letter.')
guess = input()
guess = guess.lower()
if len(guess) != 1: # more than 1 letters entered
print('Please enter a single letter.')
elif guess in alreadyGuessed: # letter already guessed
print('You have already guessed that letter. Choose again.')
elif guess not in 'abcdefghijklmnopqrstuvwxyz': # not a letter
print('Please enter a LETTER.')
else:
return guess
# Taking a guess as input and checking if it's valid
# The loop will keep reiterating till it reaches 'else'
def playAgain():
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
# Returns a boolean value
print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words) # Calls the 'getRandomWord' function
gameIsDone = False
while True:
displayBoard(missedLetters, correctLetters, secretWord)
guess = getGuess(missedLetters + correctLetters)
if guess in secretWord:
correctLetters = correctLetters + guess
foundAllLetters = True
for i in range(len(secretWord)):
if secretWord[i] not in correctLetters:
foundAllLetters = False
break
# if any letter of the 'secretWord' is not in 'correctLetters', 'foundAllLetters' is made False
# If the program doesn't enter the if statement, it means all the letters of the 'secretWord' are in 'correctLetters'
if foundAllLetters: # if foundAllLetters = True
print('Yes! The secret word is "' + secretWord +
'"! You have won!')
# Printing the secret word
gameIsDone = True
else:
missedLetters = missedLetters + guess
if len(missedLetters) == len(HANGMAN_PICS) - 1:
displayBoard(missedLetters, correctLetters, secretWord)
print('You have run out of guesses!\nAfter ' +
str(len(missedLetters)) + ' missed guesses and ' +
str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
# Prints the answer and the all guesses
gameIsDone = True
if gameIsDone:
if playAgain():
missedLetters = ''
correctLetters = ''
gameIsDone = False
secretWord = getRandomWord(words)
# Restarts Game
else:
break
# Program finishes
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have trouble here.
In the Hangman Game (Python) .
What is the part of this code that makes this:?
For example:
(The Secret Word is "door")
_ _ _ r
Guess the letter: o
_ o o r <---puts 2 times the letter "o"
Here is the code:
import random
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()
def getRandomWord(wordList):
# This function returns a random string from the passed list of strings.
wordIndex = random.randint(0, len(wordList) - 1)
return wordList[wordIndex]
def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
print(HANGMANPICS[len(missedLetters)])
print()
print('Missed letters:', end=' ')
for letter in missedLetters:
print(letter, end=' ')
print()
blanks = '_' * len(secretWord)
for i in range(len(secretWord)): # replace blanks with correctly guessed letters
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
for letter in blanks: # show the secret word with spaces in between each letter
print(letter, end=' ')
print()
def getGuess(alreadyGuessed):
# Returns the letter the player entered. This function makes sure the player entered a single letter, and not something else.
while True:
print('Guess a letter.')
guess = input()
guess = guess.lower()
if len(guess) != 1:
print('Please enter a single letter.')
elif guess in alreadyGuessed:
print('You have already guessed that letter. Choose again.')
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print('Please enter a LETTER.')
else:
return guess
def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False
while True:
displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
# Let the player type in a letter.
guess = getGuess(missedLetters + correctLetters)
if guess in secretWord:
correctLetters = correctLetters + guess
# Check if the player has won
foundAllLetters = True
for i in range(len(secretWord)):
if secretWord[i] not in correctLetters:
foundAllLetters = False
break
if foundAllLetters:
print('Yes! The secret word is "' + secretWord + '"! You have won!')
gameIsDone = True
else:
missedLetters = missedLetters + guess
# Check if player has guessed too many times and lost
if len(missedLetters) == len(HANGMANPICS) - 1:
displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
print('You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
gameIsDone = True
# Ask the player if they want to play again (but only if the game is done).
if gameIsDone:
if playAgain():
missedLetters = ''
correctLetters = ''
gameIsDone = False
secretWord = getRandomWord(words)
else:
break
Thank you guys :)
This part right here:
blanks = '_' * len(secretWord)
for i in range(len(secretWord)): # replace blanks with correctly guessed letters
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
for letter in blanks: # show the secret word with spaces in between each letter
print(letter, end=' ')