'How to hide/reveal letters in python game?
I'm new to coding and am currently trying to make a simplified game of Hangman using Python 3. For the most part, I have it down, except for the most important part, how to hide the letters of the random word, and then how to reveal them once guessed. Mainly, I just need a quick answer. Any help would be greatly appreciated. Here's my code so far (sorry if it's long, like I said, I relatively new at this, and thanks again!):
import random
#list of words for game
hangmanWords = ("Halloween","Hockey","Minnesota","Vikings","Twins","Timberwolves","Wild","Playstation","Achievement","Minecraft","Metallica","Portal","Xbox","Guitar")
#randomizes the word chosen for game
index = random.randint(0,len(hangmanWords)-1)
#assigns radomized word to variable
randomWord = hangmanWords[index]
'''
menu function, provides user with choices for game, user chooses via imput
'''
def menu():
print("""
Welcome to Hangman!
Select a difficulty:
1. Easy (9 Misses)
2. Medium (7 Misses)
3. Advanced (5 Misses)
4. Exit Game
""")
selection = int(input("What difficulty do you pick (1-4)?: "))
return selection
'''
the function for easy mode, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets 9 guesses to figure out word, correct guesses don't
count, returns player to main menu when they lose
'''
def easyMode():
wrongGuesses = 0
listOfGuesses = []
print(randomWord)
while(wrongGuesses != 9):
x = input("Enter a letter: ")
if x.lower() in randomWord.lower():
print(x,"is in the word!")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
else:
print(x,"is not in the word.")
wrongGuesses += 1
print(wrongGuesses, "wrong guesses.")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
print("You lost the game!")
return x
'''
the function for medium mode, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets 7 guesses to figure out word, correct guesses don't
count, returns player to main menu when they lose
'''
def medium():
wrongGuesses = 0
listOfGuesses = []
print(randomWord)
while(wrongGuesses != 7):
x = input("Enter a letter: ")
if x.lower() in randomWord.lower():
print(x,"is in the word!")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
else:
print(x,"is not in the word.")
wrongGuesses += 1
print(wrongGuesses, "wrong guesses.")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
print("You lost the game!")
return x
'''
the function for advanced mode, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets 5 guesses to figure out word, correct guesses don't
count, returns player to main menu when they lose
'''
def advanced():
wrongGuesses = 0
listOfGuesses = []
print(randomWord)
while(wrongGuesses != 5):
x = input("Enter a letter: ")
if x.lower() in randomWord.lower():
print(x,"is in the word!")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
else:
print(x,"is not in the word.")
wrongGuesses += 1
print(wrongGuesses, "wrong guesses.")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
print("You lost the game!")
return x
'''
main function, deals with what happens depending on
what the player selected on the menu
'''
def main():
select = menu()
while(select != 4):
if(select == 1):
easyMode()
elif(select == 2):
medium()
elif(select == 3):
advanced()
select = menu()
print("You don't want to play today? :'(")
main()
Solution 1:[1]
If you want to try it out yourself, then please don't see the code yet. Like in hangman, we get to see our progress (partially guessed word), you should create another variable that holds such a string. And, with every correct guess, you should update this string accordingly. The string obviously starts out as ##### or ***** according to the length of the word to be guessed.
With several improvements, I present to you, Hangman!
All credits go to you of course!
import random
#list of words for game
hangmanWords = ("Halloween","Hockey","Minnesota","Vikings","Twins","Timberwolves","Wild","Playstation","Achievement","Minecraft","Metallica","Portal","Xbox","Guitar")
#assigns radomized word to variable
randomWord = random.choice(hangmanWords)
'''
menu function, provides user with choices for game, user chooses via imput
'''
def menu():
print("""
Welcome to Hangman!
Select a difficulty:
1. Easy (9 Misses)
2. Medium (7 Misses)
3. Advanced (5 Misses)
4. Exit Game
""")
selection = int(input("What difficulty do you pick (1-4)?: "))
return selection
def game(mode):
'''
the game function, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets guesses according to value passed as per mode,
to figure out the word, correct guesses don't count,
returns player to main menu when they lose
'''
modes = {1:9, 2:7, 3:5} # Matches mode to guesses
guesses = modes[mode]
wrongGuesses = 0
listOfGuesses = []
# print(randomWord) Dont't print the solution!!
# Get a random word which would be guessed by the user
to_guess = random.choice(hangmanWords)
to_guess = to_guess.lower()
# The correctly guessed part of the word that we print after every guess
guessed = "#"*len(to_guess) # e.g. "Hangman" --> "#######"
while(wrongGuesses != guesses):
x = input("Word - %s . Guess a letter: "%guessed).lower()
if x in to_guess:
print(x,"is in the word!")
listOfGuesses.append(x)
# Now replace the '#' in 'guessed' to 'x' as per our word 'to_guess'
new_guessed = ""
for index, char in enumerate(to_guess):
if char == x:
new_guessed += x
else:
new_guessed += guessed[index]
guessed = new_guessed # Change the guessed word according to new guess
# If user has guessed full word correct, then he has won!
if guessed == to_guess:
print("You have guessed the word! You win!")
print("The word was %s"%to_guess)
return True # return true on winning
else:
print("Letters guessed so far:", listOfGuesses, "\n")
else:
print(x,"is not in the word.")
wrongGuesses += 1
print("Wrong guesses:", wrongGuesses)
listOfGuesses.append(x)
print("Letters guessed so far:", listOfGuesses, "\n")
print("You lost the game!")
print("The word was %s"%to_guess)
return False # return false on loosing
'''
main function, deals with what happens depending on
what the player selected on the menu
'''
def main():
select = menu()
while(select != 4):
game(select)
select = menu()
print("You don't want to play today? :'(")
main()
Wherever you see copy-paste or code repetition, it's not Pythonic! Try to avoid repetition, especially in functions. (like your easy, medium & hard functions)
Solution 2:[2]
The other answer implements it for you, but I'll walk you through the methodology so you can improve as a programmer.
You're going to want two lists, one that has the full word, and one that has the list you want to display. You can either make a binary list that is the same length as the word, or you can make a "display list", that is full of underscores, until the correct letter is guessed.
The display list method should look something like this and is easier to impliment:
To initialize displaylist:
for _ in range(len(randomword)):
displaylist.append("_")
Then within the if statement:
for i in range(len(randomword)):
if x == randomword[i]:
displaylist[i] = x
And then to print, you would need something like this:
print(''.join(displaylist))
Another improvement you could make is making a separate function that checks your word so that you can most effectively use modular programming. This would cut down on code complexity, redundancy, and make it easier to implement changes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jacqlyn |
