Python - Hangman Game With Multiple Letters In One Word
I am new to python and have a problem with a hangman game that I was making. So I have a list called 'current' which is filled with hyphens (-) the same amount of times as the leng
Solution 1:
By using the string.find-method, you only get the first occurrence of the character in the word. By defining this method, you get all occurrences:
def find_all(word, guess):
return [i for i, letter in enumerate(word)ifletter== guess]
You should also add a "continue" after checking if you've already guessed the letter before, so that you don't add it to the list again.
This should work:
deffind_all(word, guess):
return [i for i, letter inenumerate(word) if letter == guess]
current = "_" * len(theword)
x = list(current)
print (x)
guessed = []
while current != theword and lives > 0:
print ("You have %d lives left" % lives)
guess = input("Please input one letter or type 'exit' to quit.")
guess = guess.lower()
if guess == "exit":
breakelif guess in guessed:
print ("You have already guessed this letter, please try again.")
continue
guessed.append(guess)
if guess in theword:
indices = find_all(theword, guess)
x = list(current)
for i in indices:
x[i] = guess
current = "".join(x)
print ("Correct! \nYour guesses: %s" % (guessed))
print(x)
else:
print ("Incorrect, try again")
lives = lives -1
Solution 2:
Instead of:
if guess in theword:
index = theword.find(guess)
x = list(current)
x[index] = guess
current = "".join(x)
print ("Correct! \nYour guesses: %s" % (guessed))
print(x)
Try this:
for index,characterin enumerate(theword):
x = list(current)
if character== guess:
x[index] = guess
Post a Comment for "Python - Hangman Game With Multiple Letters In One Word"