I'm making a simple "hangman" game for a course. The game is completed and it works, but I want to overwrite outputs that the while loop prints in the console so that it looks cleaner and like an actual game, not just consecutive print statements.
Here's the while loop itself and some background. At the start of the program, there is a random word picked from a list word_list
, and made into a variable chosen_word. There is a variable display = []
, which is a list that gets populated with "_" for each letter in chosen_word
. Then the player takes guesses until he has made 6 loops and reaches exit()
.
Alternatively, the loop can be exited by guessing all the letters before we reach the exit()
.
while "_" in display:
counter = 0
guess = input(f"Please choose a letter: ").lower()
for letter in chosen_word:
counter += 1
if guess == letter:
display[counter -1] = letter
if guess in letters_used:
print("You already used this letter, please choose a different letter.")
print(" ")
continue
letters_used.append(guess)
if guess not in display:
loops += 1
print(stages[loops - 1])
print(" ".join(display))
print(f"You guessed {guess}, that's not in the word. You lose a life and have {6 - loops} lives left.")
print(f"So far you have used the letters: {letters_used}")
print(" ")
else:
print(" ".join(display))
print(" ")
if loops == 6:
print(f"You lose, as expected haha. The word was {chosen_word}")
exit()
else:
print("You win, finally...")
For example: the word "apple". The player inputs "a", and the console populates a _ _ _ _
. Then they can guess "z", and the console will print that they chose wrong and a corresponding picture with a hangman. I want the console to overwrite the previous picture and a _ _ _ _ _
so that it is just showing the hangman, letters used, lives left and the word he needs to guess.
This seems like a tall order, but I know it's possible to do, just not working with what I tried. So far I tried using a \r \n,
various for loops with time
, sys
, but I could not integrate them. I assume that it would be easier if the whole code is given, so here's a pastebin to the whole thing: https://codefile.io/f/mOJJ0u1vL00HbYfQ2A7O
To sum it up: I want the program to run and on each iteration to overwrite the previous print of the hangman picture, lives left and words used, so that it looks like an actual game, not just some print statements running consecutively.