Skip to content

Instantly share code, notes, and snippets.

@Diapolo10
Forked from sheebydeeby/hangman.py
Last active September 15, 2024 17:35
Show Gist options
  • Save Diapolo10/be55bceb8cc61e353c7f397c55d3a193 to your computer and use it in GitHub Desktop.
Save Diapolo10/be55bceb8cc61e353c7f397c55d3a193 to your computer and use it in GitHub Desktop.
from getpass import getpass
def print_line(line_count: int = 1) -> None:
"""Print a number of newlines."""
print('\n' * line_count, end='')
def ask_guess(used: list[str], answer: list[str]) -> str:
while True:
guess = input("Guess: ").strip().lower()
if not guess.isalpha():
print("Must only contain letters.")
elif len(guess) != 1:
print("One letter at a time.")
elif guess in used or guess in answer:
print("You've already guessed this.")
else:
break
print_line()
return guess
def ask_password(prompt: str) -> str:
while not (pw := getpass(prompt).lower()).isalpha():
print("Must only contain letters.")
return pw
def hangman(lives_lost: int) -> None:
"""Print hangman based on how many lives are left."""
print_line(3)
print(f" ======= Incorrect: {' '.join(used)}")
if lives_lost >= 1:
print(" [ O")
else:
print(" [")
if lives_lost >= 2:
if lives_lost == 2:
print(" | |")
elif lives_lost == 3:
print(" | /|")
elif lives_lost >= 4:
print(" | /|\\")
print(" | |")
else:
print(" |")
print(" |")
if lives_lost >= 5:
if x == 5:
print(" [ /")
elif lives_lost == 6:
print(" [ /\\")
else:
print(" [")
print("_==_")
print_line()
print(" ".join(answer))
print_line()
def main() -> None:
word = ask_password("What's the word?: ")
used = []
answer = ['_' for _ in word]
lives_lost = 0
hangman(lives_lost)
while ''.join(answer) != word:
correct_guess = False
guess = ask_guess(used, answer)
for idx, char in enumerate(word):
if char == guess:
answer[idx] = guess
correct_guess = True
if not correct_guess:
lives_lost += 1
used.append(guess)
hangman(lives_lost)
if lives_lost == 6:
break
else:
print("You win!")
return
print("Game over.")
print_line()
print(f"The word was {word}.")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment