Issue
I'm trying to make this hangman game but it won't work. Does anyone have any suggestions to fix it?
import random, os
print("^^^^^^^^^^THIS IS HANGMAN^^^^^^^^^^")
print("1. Play Game ")
print("2. Quit Game ")
choice = input("Please enter option 1 or 2")
if choice == "1":
words = ["handkerchief", "accommodate", "indict", "impetuous"]
word = random.choice(words)
guess = ['_'] * len(word)
guesses = 7
while '_' in guess and guesses > 0:
print(' '.join(guess))
character = input('Enter character: ')
if len(character) > 1:
print('Only enter one character.')
continue
if character not in word:
guesses -= 1
if guesses == 0:
print('You LOST!')
break
else:
print('You have only', guesses, 'chances left to win.')
else:
print(''.join(guess))
print('You WON, well done')
Solution
I assume, when you say the game doesn't work - you mean that the correctly guessed characters don't appear? That's because you don't change your guess
variable. It will always only contain _
characters if you don't update it every time:
for i, c in enumerate(word):
if c == character:
guess[i] = character
So if you add that to your code (nothing else changed), the complete game looks like this:
import random, os
print("^^^^^^^^^^THIS IS HANGMAN^^^^^^^^^^")
print("1. Play Game ")
print("2. Quit Game ")
choice = input("Please enter option 1 or 2")
if choice == "1":
words = ["handkerchief", "accommodate", "indict", "impetuous"]
word = random.choice(words)
guess = ['_'] * len(word)
guesses = 7
while '_' in guess and guesses > 0:
print(' '.join(guess))
character = input('Enter character: ')
if len(character) > 1:
print('Only enter one character.')
continue
if character not in word:
guesses -= 1
for i, c in enumerate(word):
if c == character:
guess[i] = character
if guesses == 0:
print('You LOST!')
break
else:
print('You have only', guesses, 'chances left to win.')
else:
print(''.join(guess))
print('You WON, well done')
I have changed the structure a little bit to make the code more intuitive in my eyes:
import random
WORDS = ["handkerchief", "accommodate", "indict", "impetuous"]
MAX_GUESSES = 7
print("^^^^^^^^^^THIS IS HANGMAN^^^^^^^^^^")
while True:
input('Press <ENTER> to start a new game or <CTRL>+<C> to quit.')
word = random.choice(WORDS)
guess = ['_'] * len(word)
guesses = set()
n = MAX_GUESSES
while True:
print('\nYour word:', ' '.join(guess))
print('You have {} chances left.'.format(n))
if '_' not in guess:
print('Congratulations, you win!\n')
break
if n < 1:
print('Sorry, no guesses left. You lose!\n')
break
character = input('Guess a new character: ')
if len(character) != 1:
print('You must enter exactly one character!')
continue
if character in guesses:
print('You have already guessed that character!')
continue
guesses.add(character)
if character not in word:
n -= 1
continue
for i, c in enumerate(word):
if c == character:
guess[i] = character
Answered By - finefoot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.