Python Forum

Full Version: Hangman Troubleshooting
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Okay so, I created a hangman game, this is the code for the game

import time
name = input("what is your name?: ")
print("Hello, " +name +" , time to play hangman")
time.sleep(2)
print("This word has 4 letters, you will have to guess all 4 letter, \neven repeats, in order to win")
print (" ")
time.sleep(2)

word = 'test'
guesses =" "
turns = 10
correct = 0
while turns > 0:
		guess = input("guess a character: \n")
		guesses += guess
		if guess in word:
			correct += 1
			print("correct")
			print("You have " + str(correct) +  ' out of ' + str(len(word)) + "letters" )
		elif guess not in word: 
			turns -= 1
			print ("wrong") 
			print ("you have", + turns, ' more guesses')
		if correct == 4:  
			print("You win! \nthe word was test.")
			break
		elif turns == 0:
			print ("game over")
			break
and just like hangman the program asks the user for a character, if the letter they guess is in the word they gain a point, and if the letter they use is not in the game then they lose a turn. If you reach as many points as the letters in the word you win, (for example the word I used is test and there are 4 letters in that so when the user guesses the 4 letters correctly they win),

but I have 1 dilemas(actually I have quite a few but I'm only focusing on these one)
I have found that if the user clicks enter without typing in a letter the program still marks that as correct and gives the person a point,
Is there anyway that I can stop this, I'm not sure,if their is but I figured I would ask anyway
Just check the input, here's some simple code for an example. You can turn this into a function to make the code smoother.
import time
letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}

something = input("Type a letter: ")
while something not in letters:
    print("I said type *a letter*")
    time.sleep(1)
    something = input("Type something: ")
I just put the wait in there so that there's space between the print and input. So, the code above as you can see, will check to make sure that they are typing 1 letter, so no multiple letters, no numbers, etc.
you could also:
>>> guess
''
>>> if guess:
	    print('true') #then make a check it's a legal character or already guessed one
    else:
        guess= input('enter a character')
import time
letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}

something = input("Type a letter: ")
while something not in letters:
    print("I said type *a letter*")
    time.sleep(1)
    something = input("Type something: ")
slitherio
Thanks for the information!
Smile