Basically, I am making a hangman game and I have the lines with hidden letters but the problem is when I enter a new letter it re-hides the last.
I want it so I can keep showing more letters if I get it right until the entire word is shown and if a letter that isnt in the word is inputed, nothing should happen at all.
Btw Im using python 3 and no imports so far
Code:
#word is selected from a word list so just imagine it is "stuff"
#letter is the letter that the user guesses to see if its in the word or not
def line1():
try:
if letter != "a":
b1 = word.replace("a", "_ ")
else:
b1 = word
if letter != "b":
b2 = b1.replace("b", "_ ")
else:
b2 = b1
if letter != "c":
b3 = b2.replace("c", "_ ")
else:
b3 = b2
if letter != "d":
b4 = b3.replace("d", "_ ")
else:
b4 = b3
if letter != "e":
b5 = b4.replace("e", "_ ")
else:
b5 = b4
if letter != "f":
b6 = b5.replace("f", "_ ")
else:
b6 = b5
if letter != "g":
b7 = b6.replace("g", "_ ")
else:
b7 = b6
if letter != "h":
b8 = b7.replace("h", "_ ")
else:
b8 = b7
if letter != "i":
b9 = b8.replace("i", "_ ")
else:
b9 = b8
if letter != "j":
b10 = b9.replace("j", "_ ")
else:
b10 = b9
if letter != "k":
b11 = b10.replace("k", "_ ")
else:
b11 = b10
if letter != "l":
b12 = b11.replace("l", "_ ")
else:
b12 = b11
if letter != "m":
b13 = b12.replace("m", "_ ")
else:
b13 = b12
if letter != "n":
b14 = b13.replace("n", "_ ")
else:
b14 = b13
if letter != "o":
b15 = b14.replace("o", "_ ")
else:
b15 = b14
if letter != "p":
b16 = b15.replace("p", "_ ")
else:
b16 = b15
if letter != "q":
b17 = b16.replace("q", "_ ")
else:
b17 = b16
if letter != "r":
b18 = b17.replace("r", "_ ")
else:
b18 = b17
if letter != "s":
b19 = b18.replace("s", "_ ")
else:
b19 = b18
if letter != "t":
b20 = b19.replace("t", "_ ")
else:
b20 = b19
if letter != "u":
b21 = b20.replace("u", "_ ")
else:
b21 = b20
if letter != "v":
b22 = b21.replace("v", "_ ")
else:
b22 = b21
if letter != "w":
b23 = b22.replace("w", "_ ")
else:
b23 = b22
if letter != "x":
b24 = b23.replace("x", "_ ")
else:
b24 = b23
if letter != "y":
b25 = b24.replace("y", "_ ")
else:
b25 = b24
if letter != "z":
b26 = b25.replace("z", "_ ")
else:
b26 = b25
print(b26)
except ValueError:
nothing = 1
CodePudding user response:
simplify it first
def mask_word(word,guessed_letters=None):
guessed_letters = guessed_letters or set()
return ''.join(ltr if ltr in guessed_letters else '_' for ltr in word)
print(mask_word("PIG",set(["I"])) # '_I_'
then keep track of guessed letters in a set
guessed_letters = set()
word = "PIG"
num_tries = 5
for i in range(num_tries):
guessed_letters.add(input("Enter A Letter")[0].upper())
print(mask_word(word,guessed_letters))
# once you have guessed all the letters
if set(word).issubset(guessed_letters):
print("You WIN!")
break
else:
print(f"You Are Out Of Tries!!!! You Lose the word was {word}")