Python Hangman Graphics - python

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.

Related

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

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

Hangman game letter guessing

that plays hangman game.
I guess a have an error in my guessWord(word) function, because its not working properly, and I'm not getting why?
the file for readDictionary contains rows of words for the game. but in the main code words can also be used.
current output:
Welcome to the hangman game.
You will be guessing words, one letter at a time
Guess a letter
a
Would you like to guess a new word? Y/N: y
Guess a letter
h
Would you like to guess a new word? Y/N: g
You guessed 2 words out of 2
desired output:
Your guess so far: -------
Guess a letter from the secret word: a
Good guess;
Your guess so far: -A----A
Guess a letter from the secret word: e
Wrong guess
--------
|
Your guess so far: -A----A
Guess a letter from the secret word: s
Wrong guess
--------
|
O
#and so on…
here are the parameters to do:
readDictionary() which reads the accompanying file “dictionary.txt” and returns a list of all the words appearing in the file.
• guessWord(word) which runs the user interface for guessing the word passed as argument, as described above. guessWord() calls hangmanSketch() with the appropriate argument, whenever a wrong guess is entered by the player.
Note that, even though all the words in the are in all-capital letters, the player should be able to enter the guesses in lower case.
The function returns True, if the player manages to guess the whole word before making 8 wrong guesses. The function returns False, if the player makes 8 wrong guesses and does not guess the whole word.
Below is an extract of a sample run of the whole application, showing the interface for successfully and unsuccessfully guessing words.
code:
from random import choice
def readDictionary():
file = open("dictionary.txt", "r")
lines = file.readlines()
return list(lines)
def hangmanSketch(n):
if n <= 0:
pic = ''' --------\n'''
return pic
pic = hangmanSketch(n-1)
if n == 1:
pic += ''' |\n'''
elif n == 2:
pic += ''' O\n'''
elif n == 3:
pic += '''_/'''
elif n == 4:
pic += '''|'''
elif n == 5:
pic += '''\_ \n'''
elif n == 6:
pic += ''' |\n'''
elif n == 7:
pic += '''_/'''
elif n == 8:
pic += ''' \_ \n'''
return pic
def guessWord(word):
while True:
print("Guess a letter")
userGuess = input()
userGuess = userGuess.lower()
if len(userGuess) != 1:
print("Please enter a single letter")
elif userGuess in word:
print("letter already guessed, try another")
else:
return userGuess
def main():
print("Welcome to the hangman game.")
print("You will be guessing words, one letter at a time")
words = readDictionary()
words = ['ABANDON', 'INQUIRING', 'LACROSSE', 'REINITIALISED'] # use this list if you don't manage to implement readDictionary()
nAttemptedWords = 0
nGuessedWords = 0
play = "Y"
while play == "Y":
secretWord = choice(words) # random choice of one word from the list of words
nAttemptedWords += 1
if guessWord(secretWord):
nGuessedWords += 1
play = input("Would you like to guess a new word? Y/N: ")
play = play.upper()
print("You guessed", nGuessedWords, "words out of", nAttemptedWords)
if __name__ == "__main__":
main()
I suggest you having one while for iterating between words and inner while for iterating through player's guesses:
import random
WORDS = ['abandon', 'inquiring', 'lacrosse', 'reinitialised']
def guessed_word(word, guessed_letters):
""" Build guessed word. E.g.: "--c--r" """
result = ''
for letter in word:
if letter in guessed_letters:
result += letter
else:
result += '-'
return result
print('Welcome to the hangman game.')
print('You will be guessing words, one letter at a time')
play = 'y'
while play == 'y':
word = random.choice(WORDS)
guessed_letters = []
hp = 8
while True:
print(f'Your guess so far: {guessed_word(word, guessed_letters)}')
letter = input('Guess a letter from the secret word: ')
if letter in list(word):
print('Good guess')
guessed_letters.append(letter)
else:
print('Wrong guess')
hp -= 1
if hp == 0:
print('You loose!')
break
elif len(guessed_letters) == len(set(word)):
print(f'You win! The word is: {word}')
break
play = input('Would you like to guess a new word? y/n: ')
Output:
Welcome to the hangman game.
You will be guessing words, one letter at a time
Your guess so far: --------
Guess a letter from the secret word: a
Good guess
Your guess so far: -a------
Guess a letter from the secret word: b
Wrong guess
Your guess so far: -a------
Guess a letter from the secret word: c
Good guess
Your guess so far: -ac-----

Loop breaks without executing the last print statement

I've written a hangman program in python. The program is finished, but I have a problem with my main function. If I set a win or loss, it no longer execute my print statements from before. This means that if I have to guess a word, for example, it doesn't fill in the last letter in the placeholder, it just breaks out the loop without filling in the last letter. The same goes with my hangman. If I don't have any more attempts left, it won't finish drawing my hangman (just leave out the last part). Who knows why that is? Please help
Here is my code:
##### HANGMAN IN PYTHON #####
count_attempts = 0
guess_word = []
def guidance():
print('Welcome to Hangman in Python!')
print('''The point here is to guess a word by trying out letter combinations and
defining them with ENTER.''')
print('''For each word, you have 10 tries! If you can not solve the word,
the game is over.''')
print('You have 9 attempts to guess the word.')
print('Have fun!')
print('')
def user_word():
userinput = str(input("Type in the word you want to be guessed: "))
for character in userinput:
if character.isdigit():
print('There is a number in your word!')
userinput = str(input('Please try again: '))
return userinput.upper()
def change(userinput):
global guess_word
list_WordToBeGuessed = list(userinput)
for characters in list_WordToBeGuessed:
guess_word.append(' _')
def play_game(userinput):
global count_attempts
length_word = len(userinput)
user_guessed = []
print('Word to guess: ', *guess_word)
print("")
list_WordToBeGuessed = list(userinput)
guess = str(input('Guess a letter: ')).upper()
for number in guess:
if number.isdigit():
guess = str(input('Input not valid. Guess a letter: ')).upper()
if guess in user_guessed:
print('You have already given this letter. ')
elif guess in list_WordToBeGuessed:
user_guessed.append(guess)
print("You've guessed a letter correctly!")
for i in range(0, length_word):
if list_WordToBeGuessed[i] == guess:
guess_word[i] = guess
else:
count_attempts += 1
user_guessed.append(guess)
print('Sry your given letter is not in the word!')
print("You have failed", count_attempts, "of 5 attempts")
def draw_hangman(count_attempts):
print('-------' )
print(' | ' + ('|' if count_attempts > 0 else ''))
print(' | ' + ('O' if count_attempts > 1 else ''))
print(' | ' + ('/ \\' if count_attempts > 2 else ''))
print(' | ' + ('|' if count_attempts > 3 else ''))
print('--- ' + ('/ \\' if count_attempts > 4 else ''))
print("")
def main():
guidance()
userinput = user_word()
change(userinput)
while True:
draw_hangman(count_attempts)
play_game(userinput)
if count_attempts >= 5:
print("You haven't any attempts left. Bad luck")
break
elif ' _' not in guess_word:
print("")
print('You won, congratulation!')
break
main()
you are breaking out of a loop before it can draw the hangman and word.
in the endgame conditions, you can simply call draw_hangman(count_atttempts) before each print statement and change(userinput) as well.
Edit:
You will have to redraw the word as well. Since this is built into your play_game() function it is difficult, but you can use
for i in guess_word:
guess = guess + i + " "
print(guess)
before the print statements along with the draw_hangman(count_attempts) change you made before. Please note you will need to create a new variable called guess in your main() function prior to adding this code.
Since you have a "break" in your endgame condition, the loop stops and last "draw_hangman(count_attempts)" is not called. You can simply add "draw_hangman(count_attempts)" before "print("You haven't any attempts left. Bad luck")"

How to compare user inputted string to a character(single letter) of a word in a list?

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)

Python Hangman code

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

Categories

Resources