I am writing a hangman game in python and I have variable called userguess and the user will type in what letter they want to use to guess. However, when the while loop begins it's second repeat, the if statement no longer recognizes the userguess and immediately concludes it to be an incorrect guess. I hope you don't mind the amount of code I am using as an example.
movieletters contains the hiddenword split into letters
defaultletters represents the blanks that have to be filled in by the user
I have tried using exception handlers by creating boolean variables but this hasn't done what I needed it to do.
userguess = input("Guess a letter: ")
while True:
for letter in movieletters:
for defaultletter in defaultletters:
if userguess == letter:
print("You guessed correctly")
score += 1
guessedletters.append(userguess)
print(score, "/", totalletters)
print(guessedletters)
print(movie)
if score == totalletters:
print("\n")
print("*************************************************************************************************")
print(movie)
print("*************************************************************************************************")
print("\n")
print("You guessed all the letters correctly and uncovered the word!")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
elif userguess != letter:
incorrectlyguessed += 1
print("INCORRECT!")
print(str(incorrectlyguessed) + "/" + str(tally))
if incorrectlyguessed == 1:
print("""
__________""")
elif incorrectlyguessed == 2:
print("""
|
|
|
|
|__________ """)
elif incorrectlyguessed == 3:
print("""
-----------
|
|
|
|
|__________ """)
elif incorrectlyguessed == 4:
print("""
-----------
| |
|
|
|
|__________ """)
elif incorrectlyguessed == 5:
print("""
-----------
| |
| 0
|
|
|__________ """)
elif incorrectlyguessed == 6:
print("""
-----------
| |
| 0
| |
|
|__________ """)
elif incorrectlyguessed == 7:
print("""
-----------
| |
| 0
| \|/
|
|__________ """)
elif incorrectlyguessed == 8:
print("""
-----------
| |
| 0
| \|/
| |
|__________ """)
elif incorrectlyguessed == 9:
print("""
-----------
| |
| 0
| \|/
| |
|________/_\ """)
if incorrectlyguessed == tally:
print("GAME OVER!")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print(movie)
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
I expect the output to show that the character is recognized as one of the letters in the hidden word in the while loop's second phase. This also effects all of the while loop's phases except for the first one.
Here's an example of the current output:
Output
if the movie was cars then movieletters would be ['c', 'a', 'r', 's']
defaultletters would be _ _ _ _
The problem is that it always matches with the first letter in the list of movieletters.
use if userguess in movieletters to check whether it matches or not
userguess = input("Guess a letter: ")
if userguess in movieletters:
print("You guessed correctly")
score += 1
guessedletters.append(userguess)
print(score, "/", totalletters)
print(guessedletters)
print(movie)
if score == totalletters:
print("\n")
print("*************************************************************************************************")
print(movie)
print("*************************************************************************************************")
print("\n")
print("You guessed all the letters correctly and uncovered the word!")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
else :
incorrectlyguessed += 1
print("INCORRECT!")
print(str(incorrectlyguessed) + "/" + str(tally))
if incorrectlyguessed == 1:
print("""
__________""")
elif incorrectlyguessed == 2:
print("""
|
|
|
|
|__________ """)
elif incorrectlyguessed == 3:
print("""
-----------
|
|
|
|
|__________ """)
elif incorrectlyguessed == 4:
print("""
-----------
| |
|
|
|
|__________ """)
elif incorrectlyguessed == 5:
print("""
-----------
| |
| 0
|
|
|__________ """)
elif incorrectlyguessed == 6:
print("""
-----------
| |
| 0
| |
|
|__________ """)
elif incorrectlyguessed == 7:
print("""
-----------
| |
| 0
| \|/
|
|__________ """)
elif incorrectlyguessed == 8:
print("""
-----------
| |
| 0
| \|/
| |
|__________ """)
elif incorrectlyguessed == 9:
print("""
-----------
| |
| 0
| \|/
| |
|________/_\ """)
if incorrectlyguessed == tally:
print("GAME OVER!")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print(movie)
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
Related
I'm trying to do a practice assignment to help learn python yet am stuck on this. It says to create a simple Die game which asks for user input to keep playing, along with displaying results. I also need to use classes. I have been able to create it without the classes yet become stuck when transferring it to classes.
import random
def RollDice():
die = random.randint(1,6)
die2 = random.randint(1,6)
faceValue = die + die2
if die == 1:
RollOne()
elif die == 2:
RollTwo()
elif die == 3:
RollThree()
elif die == 4:
RollFour()
elif die == 5:
RollFive()
elif die == 6:
RollSix()
if die2 == 1:
RollOne()
elif die2 == 2:
RollTwo()
elif die2 == 3:
RollThree()
elif die2 == 4:
RollFour()
elif die2 == 5:
RollFive()
elif die2 == 6:
RollSix()
return faceValue
def RollOne():
print(''' ------
| |
| o |
| |
------ ''')
return
def RollTwo():
print(''' ------
| o |
| |
| o |
------ ''')
return
def RollThree():
print(''' ------
| o |
| o |
| o |
------ ''')
return
def RollFour():
print(''' ------
| o o |
| |
| o o |
------ ''')
return
def RollFive():
print(''' ------
| o o |
| o |
| o o |
------ ''')
return
def RollSix():
print(''' ------
| o o |
| o o |
| o o |
------ ''')
return
x = 1
OverallRoll = RollDice()
print("Face value:", OverallRoll)
while x == 1:
play_again = input("Would you like to play again? Respond with 'Yes' to continue and anything else to quit.")
if play_again == 'Yes':
OverallRoll = RollDice()
print("Face value:", OverallRoll)
else:
quit()
Any tips on how to make it into classes with methods? Thank you!
import random
class Game:
DIE_ASCII_ART = {1: ''' ------
| |
| o |
| |
------ ''', 2: ''' ------
| o |
| |
| o |
------ '''} # Do this for all values from 1-6
#staticmethod
def _roll_dice() -> int:
die = random.randint(1, 6)
die2 = random.randint(1, 6)
print(Game.DIE_ASCII_ART[die])
print(Game.DIE_ASCII_ART[die2])
return die + die2
#staticmethod
def run() -> None:
running = True
while running:
play_again = input("Would you like to play again? Respond with 'Yes' to continue and anything else to quit.")
if play_again == 'Yes':
overall_roll = Game._roll_dice()
print("Face value:", overall_roll)
else:
running = False
if __name__ == '__main__':
Game.run()
A few other notes about your code:
You use PascalCase in your code while the convention for Python is snake_case.
You defined alot of functions and wrote alot of if statements when a simple dictonary was enough to solve the problem.
A few notes about my code:
The methods in the Game class are static because there isn't a need for instance variables in the code.
I added typing annotations for improved code quality.
I changed the game loop for using a number to a boolean because that is more readble in my opinion.
Refrences:
PEP8 style guide
type annotations
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.
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.
I was trying to make a basic RNG combat, so people could just copy and paste it and use for their games at our school but I need help on one part.
import random
print("Your Weapon's Stats")
print(" /^\\ ")
print(" | | ")
print(" | | ")
print(" | | ")
print(" | | ")
print(" | | ")
print(" \\\=*=// ")
print(" | ")
print(" (+) ")
print("(+)~~~~~~~~~~~~~~~(+)")
print(" | Damage: | ")
print(" | 1-9 | ")
print(" | Attack Speed: | ")
print(" | 6/10 | ")
print(" | Critical Chance:| ")
print(" | 64% | ")
print("(+)~~~~~~~~~~~~~~~(+)")
your_damage = random.choice("12345789")
enemy_health = 20
enemy_health - your_damage <---it says that not right so what do I do?
print(enemy_health)
You need to use the -= operator to subtract your_damage from enemy_health:
enemy_health -= your_damage
This is equivalent to writing enemy_health = enemy_health - your_damage.
You also want to change random.choice("12345789") to random.randint(1, 9). This selects a random integer between 1 and 9 inclusive, thus ensuring that your_damage is a number instead of a string.
Your code should be:
import random
print("Your Weapon's Stats")
print(" /^\\ ")
print(" | | ")
print(" | | ")
print(" | | ")
print(" | | ")
print(" | | ")
print(" \\\=*=// ")
print(" | ")
print(" (+) ")
print("(+)~~~~~~~~~~~~~~~(+)")
print(" | Damage: | ")
print(" | 1-9 | ")
print(" | Attack Speed: | ")
print(" | 6/10 | ")
print(" | Critical Chance:| ")
print(" | 64% | ")
print("(+)~~~~~~~~~~~~~~~(+)")
your_damage = random.randint(1, 9)
enemy_health = 20
enemy_health -= your_damage
print(enemy_health)
You aren't actually assigning your new value to enemy_health, so you want to do this:
enemy_health = enemy_health - your_damage
Which can be simplified using the -= operator.
So:
enemy_health -= your_damage
To comment about your usage of random.choice. You are almost correct in what you are trying to do, however, you want to use a list of integers instead of a string of numbers. So you can do this instead:
random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Even nicer:
random.choice(range(1, 10))