I am trying to write an Hangman game in Python, which I almost figure it out for simple words but when there is a duplicate it mess up with the return indexing. Here is the code:
def hangman_game():
words = ["aback", "abaft", "abandoned", "abashed", "aberrant", "abhorrent", "abiding", "abject", "ablaze", "able",
"abnormal", "aboard", "aboriginal", "abortive", "abounding", "abrasive", "abrupt", "absent", "absorbed",
"absorbing", "abstracted", "absurd", "abundant", "abusive", "acceptable", "accessible", "accidental",
"accurate", "acid", "acidic", "acoustic", "acrid", "actually", "ad hoc", "adamant", "adaptable", "addicted",
"adhesive", "adjoining", "adorable", "adventurous", "afraid", "aggressive", "agonizing", "agreeable", "ahead",
"ajar", "alcoholic", "alert", "alike", "alive", "alleged", "alluring", "aloof", "amazing", "ambiguous",
"ambitious", "amuck", "amused", "amusing", "ancient", "angry", "animated", "annoyed", "annoying", "anxious",
word = random.choice(words)
print(f'Random word = {word} (backtesting)')
letter_set = []
word_set = []
for i in word:
word_set.append(i)
print(f'Letter remaining to be found ={word_set}')
while len(letter_set) < len(word_set):
for i in word:
letter = input("Guess a letter: ")
if letter in word_set:
letter_set.insert(word.index(letter)), letter) # issue here
word_set.remove(letter)
print(f'Word with letters removed: {word}')
print(f"Letter {letter} found at word index: {word.index(letter)}")
print(f'Letters found in word: {letter_set}')
print(f'Word set = {word_set}')
else:
print(f'Letter not found in word: {word}')
print(letter_set)
print("".join(map(str, letter_set)))
When it find duplicates in word, it removes the letter who is a duplicate from word_set but not from word. So when it finds a word like "letter" it will insert "e" always at index[1]. So it will print like "leettr". I found out that sometimes it mess up with the index even if there are no duplicates, usually on longer words, but couldn't really figure out why.
I was thinking to make it so letter_set have a i number of "_" depending on the word by default, and than replacing it using word_set.
Any advice on how to return letter always to the right index?
You can refactor the code a little bit. For example you can make a list hidden_word that will contain the same amount of # as letters in word. User will be guessing the letter and you will reveal the letter in hidden word untill there isn't anything left to reveal. For example:
def hangman_game():
word = "letter" # <-- chose a random word here instead of hardcoding it
hidden_word = list("#" * len(word))
while "#" in hidden_word:
print("STATUS")
print("------")
print(word)
print(hidden_word)
print("------")
letter = input("Guess a letter: ")
for idx, (w, h) in enumerate(zip(word, hidden_word)):
if w == letter and h == "#":
hidden_word[idx] = letter
print("Letter found!")
break
else:
print("Letter not found!")
hangman_game()
Prints:
STATUS
------
letter
['#', '#', '#', '#', '#', '#']
------
Guess a letter: e
Letter found!
STATUS
------
letter
['#', 'e', '#', '#', '#', '#']
------
Guess a letter: e
Letter found!
STATUS
------
letter
['#', 'e', '#', '#', 'e', '#']
------
Guess a letter: t
Letter found!
STATUS
------
letter
['#', 'e', 't', '#', 'e', '#']
------
Guess a letter: t
Letter found!
STATUS
------
letter
['#', 'e', 't', 't', 'e', '#']
------
Guess a letter: r
Letter found!
STATUS
------
letter
['#', 'e', 't', 't', 'e', 'r']
------
Guess a letter: x
Letter not found!
STATUS
------
letter
['#', 'e', 't', 't', 'e', 'r']
------
Guess a letter: l
Letter found!
I copy my code here in case someone will need something similar in the future. `
`
def hangman_game():
new_game = input("Press enter for new game")
word = random.choice(words)
print(f'Random word = {word} (testing)')
letter_set = list("_" * len(word))
lives = 3
while "_" in letter_set:
letter = input("Guess a letter: ").upper()
letter_count = word.count(letter)
if letter.isnumeric() or len(letter) > 1:
print("Insert valid character: a-z")
for index, (find_word, hidden) in enumerate(zip(word, letter_set)): # create new list with "_"*len(word)
if find_word == letter.lower() and hidden == "_": # check if letter is found in word, and if it is already revealed
letter_set[index] = letter # change "_" at the found indexes with letter
print(f'Letter found!')
if len(letter) > 1:
lives += 1
print(f"One letter at the time! ")
if letter.lower() not in word and letter.isnumeric() == False:
lives -= 1
print(f"Letter not found! Lives = {lives}")
if lives == 0:
print(f"YOU LOST! \n")
hangman_game()
if letter_count >= 1:
letter_set[index] = letter.upper()
print(f'Your word is: {" ".join(map(str, letter_set))}')
print("YOU WON \n")
hangman_game()
hangman_game() #wrong copied indentation
Related
So I'm working my first project which hangman written in python every works like the visuals and the incorrect letters. However, It is unable to recognise the correct letter guessed.
import random
from hangman_visual import lives_visual_dict
import string
# random word
with open('random.txt', 'r') as f:
All_Text = f.read()
words = list(map(str, All_Text.split()))
WORD2GUESS = random.choice(words).upper()
letters = len(WORD2GUESS)
print("_" * letters)
word_letters = set(WORD2GUESS)
alphabet = set(string.ascii_uppercase)
lives = 7
used_letters = set()
# user input side
while len(word_letters) > 0 and lives > 0:
# letters used
# ' '.join(['a', 'b', 'cd']) --> 'a b cd'
print('You have', lives, 'lives left and you have used these letters: ', ' '.join(used_letters))
# what current word is (ie W - R D)
word_list = [letter if letter in used_letters else '-' for letter in WORD2GUESS]
print(lives_visual_dict[lives])
print('Current word: ', ' '.join(word_list))
user_letter = input('Guess a letter: ').upper()
if user_letter in alphabet - used_letters:
used_letters.add(user_letter)
if user_letter in WORD2GUESS:
used_letters.remove(user_letter)
print('')
else:
lives = lives - 1 # takes away a life if wrong
print('\nYour letter,', user_letter, 'is not in the word.')
elif user_letter in used_letters:
print('\nYou have already used that letter. Guess another letter.')
else:
print('\nThat is not a valid letter.')
if lives == 0:
print(lives_visual_dict[lives])
print('You died, sorry. The word was', WORD2GUESS)
else:
print('YAY! You guessed the word', WORD2GUESS, '!!')
I've tried this, but it still wont recognise the correct guess.
# what current word is (ie W - R D)
word_list = [letter if letter in used_letters else '-' for letter in WORD2GUESS]
print(lives_visual_dict[lives])
print('Current word: ', ' '.join(word_list))
Your error is this: When checking if the user_letter is in the WORD2GUESS, you falsely remove it from used_letters, but it has to stay in the set.
Also you are missing some way of escaping the while loop when fully guessing the word. That could be done at the same spot by checking if used_letters contain all the letters in WORD2GUESS.
Something like this:
import random
from hangman_visual import lives_visual_dict
import string
# random word
with open('random.txt', 'r') as f:
All_Text = f.read()
words = list(map(str, All_Text.split()))
WORD2GUESS = random.choice(words).upper()
letters = len(WORD2GUESS)
print("_" * letters)
word_letters = set(WORD2GUESS)
alphabet = set(string.ascii_uppercase)
lives = 7
used_letters = set()
# user input side
while len(word_letters) > 0 and lives > 0:
# letters used
# ' '.join(['a', 'b', 'cd']) --> 'a b cd'
print('You have', lives, 'lives left and you have used these letters: ', ' '.join(used_letters))
# what current word is (ie W - R D)
word_list = [letter if letter in used_letters else '-' for letter in WORD2GUESS]
print(lives_visual_dict[lives])
print('Current word: ', ' '.join(word_list))
user_letter = input('Guess a letter: ').upper()
if user_letter in alphabet - used_letters:
used_letters.add(user_letter)
if user_letter in WORD2GUESS:
print('\nThat is a correct letter.')
if set(WORD2GUESS).issubset(used_letters):
break
else:
lives = lives - 1 # takes away a life if wrong
print('\nYour letter,', user_letter, 'is not in the word.')
elif user_letter in used_letters:
print('\nYou have already used that letter. Guess another letter.')
else:
print('\nThat is not a valid letter.')
if lives == 0:
print(lives_visual_dict[lives])
print('You died, sorry. The word was', WORD2GUESS)
else:
print('YAY! You guessed the word', WORD2GUESS, '!!')
I am trying to create a hangman game using Python. Though, when the word "sun" is picked, and if the word "tree" is inputted into the console as an answer by me, it says the answer is correct when it is not. I have tried creating a function to fix this situation, though, it does not work for me...
Here is my code:
#hangman mini-project
import random
import string
import time
letters = string.ascii_letters
lettertree = ['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 's', 'u', 'v', 'w', 'x', 'y', 'z']
hangmanwords = ['tree','sun']
sunchoices = ['s _ _', '_ u _', '_ _ n']
treechoices = ['t _ _ _', '_ r _ _', ' _ _ e _', '_ _ _ e']
lettercount = [0]
gameWinTree = False
gameWinSun = False
limbCount = 5
hangmanword = random.choice(hangmanwords)
correct = hangmanword
if hangmanword == "sun":
print (random.choice(sunchoices))
if hangmanword == "tree":
print (random.choice(treechoices))
if letters == "r":
print("Nice! You guessed one letter from the word")
if letters == "e":
print("Wow! You guessed two letters from the word, if you wish, you can guess the word")
while True:
letters = input("Please enter a letter to guess the word")
if letters == "tree":
input("Correct! The word was tree! Press enter to play again.")
time.sleep(1)
break
if letters == "tree":
gameWinTree == true
if gameWinTree == true:
time.sleep(1)
break
print("The letter that you chose was " + letters)
if letters == "r":
print("Nice! You guessed one letter from the word!\n t r _ _")
if letters == "e":
print("Wow! You guessed two letters from the word!\n t _ e e")
if letters == "tree":
print("Correct! The word was tree!")
if letters == lettertree:
print("Sorry, that's not a correct letter, feel free to try again.")
limbCount -=1
if limbCount == 0:
print("Unfortunately, you are out of tries, better luck next time!")
time.sleep(1)
exit()
Basically, if the word "sun" is picked, I want the code for the word tree to not work. Also sorry if my code is sloppy, tried to create this quickly! Thank you
I have no idea about your level of coding tho I would try to use a
if or contain for example
x = input("char player entered")
chr = [sun, tree]
if x.__contains__(x):
chr.remove('sun')
you can use a while loop to restart the game or re-append new words to the list
another way is to create a brand new list that contains the word the person chose
x = input("char player entered")
chr = [sun, tree]
n = []
if x.__contains__(x):
z = chr.index(x)
n.append(chr[z])
I am trying to make a hangman game and I am not fully sure on how to add a specific letter to a variable.
For example, adding a letter that someone chose through the pythons' input prompt to a variable. Here is the code I am working on:
import random
import time
word_list = ['that', 'poop', 'situation', 'coding', 'python', 'turtle', 'random', 'passive', 'neutral', 'factor', 'time']
word_chosen = random.choice(word_list)
your_name = input("What is your name?")
time.sleep(1)
print("Hello " + your_name + ", lets play some hangman!, The amount of letters in the word is below!")
guesses = 7
time.sleep(1)
hidden_word = ""
for i in word_chosen:
hidden_word += "-"
while True:
n = 1
time.sleep(1)
print("Your word is: " + hidden_word)
print("___________")
print("|")
print("|")
print("|")
print("|")
print("|")
print("|")
print("|")
characters = (word_chosen)
time.sleep(1)
letters_correct = ""
characters_guessed = input("Type in the letters you think are in this word!")
for i in characters:
hidden_word == characters_guessed
if characters_guessed == characters:
print(hidden_word + characters)
else:
int(guesses) - int(n)
print("Nope, sorry.")
I have modified your code #Noob and made it work. Instead of using strings I have made lists of chosen_word ,characters and characters_guessed .In this code you can even enter more than one word at a time. It automatically fillsup the repitive words and will tell the user if he or she has won or lost the game.
import random
import time
word_list = ['that', 'poop', 'situation', 'coding', 'python', 'turtle', 'random', 'passive', 'neutral', 'factor', 'time']
word_chosen = random.choice(word_list)
your_name = input("What is your name?")
time.sleep(1)
print("Hello " + your_name + ", lets play some hangman!, The amount of letters in the word is below!")
guesses = 7
time.sleep(1)
hidden_word = [" - " for i in range(len(word_chosen))]
while guesses>0:
time.sleep(1)
print("Your word is: "+ "".join(hidden_word))
print("___________")
for i in range(7):
print("|")
characters = list(word_chosen)
time.sleep(1)
letters_correct = ""
characters_guessed = input("Type in the letters you think are in this word!").split()
for j in characters_guessed:
if j not in characters:
guesses-=1
print(f"Wrong guess, {j} is not in the word")
else:
for i in characters:
if i==j:
find_position=0
for k in range(characters.count(i)):
hidden_word[characters.index(i,find_position)]=j
find_position+=characters.index(i,find_position)+1
if " - " not in hidden_word:
print("Congratulations, you have won the game.The word was {chosen_word}")
break
elif guesses==0:
print("Opps!! out of guesses. You have lost the game.")
Python strings do not support item assignment, so I would use an array of strings and then use "".join(hidden_word) when you want to print the word out. You can loop over the chosen word and then when that letter matches the input letter, fill in that position in your hidden_word array.
Here's how I would adapt your code to get the game to run:
import random
import time
word_list = ['that', 'poop', 'situation', 'coding', 'python', 'turtle', 'random', 'passive', 'neutral', 'factor', 'time']
word_chosen = random.choice(word_list)
your_name = input("What is your name?")
time.sleep(1)
print("Hello " + your_name + ", lets play some hangman!, The amount of letters in the word is below!")
guesses = 7
won = False
hidden_word = ["|"] * len(word_chosen)
while guesses > 0:
print("Your word is: " + "".join(hidden_word))
print("___________")
for _ in range(5):
print("|")
guessed = input("Type in the letters you think are in this word!")
for c in guessed:
for i in range(0, len(word_chosen)):
if word_chosen[i] == c:
hidden_word[i] = c
if "|" not in hidden_word:
won = True
break
guesses -= 1
if won:
print(f'Word found: {"".join(hidden_word)}')
else:
print(f'Nope, sorry - word was {word_chosen}')
So to answer your original question, I assign the string that is input to guessed. I then loop over each letter in guessed, and check it against each position in chosen_word. If the letter at that position is a match, I change the placeholder | to the chosen letter. Once no placeholders are left, the game is won.
If you wanted to limit the user to only inputting one character at a time, I would take a look at this thread for example on how to adapt input() to handle this.
Good evening everyone..... i wrote a vowel eater program with the code below
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
userWord = userWord.upper()
for letter in userWord:
if letter == 'A':
continue
elif letter == 'E':
continue
elif letter == 'I':
continue
elif letter == 'O':
continue
elif letter == 'U':
continue
else:
print(letter)
It run fine but i want to use concatenation operation to ask python to combine selected letters into a longer string during subsequent loop turns, and assign it to the wordWithoutVowels variable.....
I really appreciate any help or suggestions thanks in advance
is this what you need?
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
userWord = userWord.upper()
for letter in userWord:
if letter == 'A':
word = letter
continue
elif letter == 'E':
continue
elif letter == 'I':
continue
elif letter == 'O':
continue
elif letter == 'U':
continue
else:
wordWithoutVowels+=letter
print(wordWithoutVowels)
Another approach. You can prepare a set of vowels you want to filter-out before-hand and then use str.join() to obtain you string:
userWord = input("Please Enter a word: ")
vowels = set('aeiou')
wordWithoutVowels = ''.join(character for character in userWord if not character.lower() in vowels)
print(wordWithoutVowels)
Prints (for example):
Please Enter a word: Hello World
Hll Wrld
I'm sorry I didn't read the original post (OP) more carefully. Poster clearly asked for a way to do this by concatenation in a loop. So instead of excluding vowels, we want to include the good characters. Or instead of looking for membership, we can look for not in membership.
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
vowels = 'aAeEiIoOuU'
wordWithoutVowels = '' # initialize to empty string
for letter in userWord:
if letter not in vowels:
wordWithoutVowels += letter # equivalent to wordWithoutVowels = wordWithoutVowels + letter
print(wordWithoutVowels)
Please Enter a word: Hello World
Hll Wrld
or you can try this:
wordWithoutVowels = ""
user = input("Enter a word: ")
userWord = user.upper()
for letter in userWord:
if letter == "A":
continue
elif letter == "E":
continue
elif letter == "O":
continue
elif letter == "I":
continue
elif letter == "U":
continue
else:
wordWithoutVowels += letter
print(wordWithoutVowels)
Using str.replace() seems like a natural way to go for a problem like this
Brute Force
Just go through all of the vowels. And if they exist in input string, replace them
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
userWord = userWord.upper()
# make a copy of userWord
output = userWord
# replace vowels
output = output.replace('A', '') # replace A with empty string
output = output.replace('E', '') # replace E with empty string
output = output.replace('I', '') # replace I with empty string
output = output.replace('O', '') # replace O with empty string
output = output.replace('U', '') # replace U with empty string
print(output)
Please Enter a word: Hello World
HLL WRLD
Use a loop
This is a little more elegant. And you won't have to convert the input to uppercase.
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
# make a copy of userWord
output = userWord
# replace vowels
vowels = 'aAeEiIoOuU'
for letter in vowels:
output = output.replace(letter, '') # replace letter with empty string
print(output)
Please Enter a word: Hello World
Hll Wrld
Try this. I think it's the easiest way:
word_without_vowels = ""
user_word = input("Enter a word")
user_word = user_word.upper()
for letter in user_word:
# Complete the body of the loop.
if letter in ("A","E","I","O","U"):
continue
word_without_vowels+=letter
print(word_without_vowels)
user_word =str(input("Enter a Word"))
# and assign it to the user_word variable.
user_word = user_word.upper()
vowels = ('A','E','E','I','O','U')
for letter in user_word:
if letter in vowels:
continue
elif letter == vowels:
letter = letter - vowels
else:
print(letter)
A one liner that does what you need is:
wordWithoutVowels = ''.join([ x for x in userWord if x not in 'aeiou'])
or the equivalent:
wordWithoutVowels = ''.join(filter(lambda x : x not in 'aeiou', userWord))
The code is creating a list containing the letters in the string that are not vowels and then joining them into a new string.
You just need to figure out how to handle the lower/capital cases. You could do x.lower() not in 'aeiou', check if x is in 'aeiouAEIOU', ... you have plenty of choices.
user_word = input('enter a word:')
user_word = user_word.upper()
for letter in user_word:
if letter in ('A','E','I','O','U'):
continue
print(letter)
word_without_vowels = ""
vowels = 'A', 'E', 'I', 'O', 'U'
user_word = input('enter a word:')
user_word = user_word.upper()
for letter in user_word:
if letter in vowels:
continue
word_without_vowels += letter
print(word_without_vowels)
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