Shniper Shniper - 1 month ago 4
Python Question

Updating missing letters in hangman game

I'm making a hangman game and have found a problem with my methodology for updating the answer. I have a variable that adds underscores equal to the amount of letters in the word the player needs to guess. However I can't figure out how to effectively update that when the player guesses a correct letter.

Here is my code

import random
'''
HANGMAN IMAGE

print(" _________ ")
print("| | ")
print("| 0 ")
print("| /|\\ ")
print("| / \\ ")
print("| ")
print("| ")
'''

def game():
print('''Welcome to hangman, you must guess letters to fill in the word.
Incorrect guesses will use up a turn, you have 7 turns before you lose.''')
lines = open("wordBank.txt").read()
line = lines[0:]

words = line.split()
myword = random.choice(words).lower()
letters = len(myword)
print("Your word has " + str(letters) + " letters.")

underscores = ""
for x in range(0, letters):
underscores += "_ "
print(underscores)
print(myword)
l = set(myword)
turn = 0
guesses = []
def guess():
thisGuess = input("Type a letter and press Enter(Return) to guess: ")
if thisGuess.lower() in l:

else:
print("Boo")

guess()
game()

Answer

Another possible approach (in Python 2.7, see below for 3):

trueword = "shipping"
guesses = ""

def progress():
    for i in range(len(trueword)):
        if trueword[i] in guesses:
            print trueword[i],
        else:
            print "-",
    print ""

This works by checking for each letter if it's been guessed in guesses, and printing that letter. If it hasn't been guessed, it prints -. When you put a comma at the end of a print (as in print "-",) it won't automatically print a newline, so you can continue printing on the same line. print "" prints a null string with a newline, finishing the line.

Then guessing becomes:

guesses += guess

Output is:

guesses = ''

- - - - - - - -

guesses = 'sip'

s - i p p i - -

In Python 3:

trueword = "shipping"
guesses = ""

def progress():
    for i in range(len(trueword)):
        if trueword[i] in guesses:
            print(trueword[i], end='')
        else:
            print("-", end='')
    print('')

you add the end='' parameter to remove the newline, instead of the comma. If you want the spaces between them, you can add sep=' ' as well to specify the separator.


Also, because list comprehensions are awesome (and this works in 2.7 & 3):

def progress():
    ans = [word[x] if word[x] in guesses else '-' for x in range(len(word))]
    print(' '.join(ans))

Does the same thing via list comprehensions... which are a very strong feature in python.