Skip to content

Instantly share code, notes, and snippets.

@alekxeyuk
Last active August 8, 2021 10:23
Show Gist options
  • Save alekxeyuk/8ea7c6578ebdf7ea7d1706414d36ea81 to your computer and use it in GitHub Desktop.
Save alekxeyuk/8ea7c6578ebdf7ea7d1706414d36ea81 to your computer and use it in GitHub Desktop.
Hangman game
import random
import string
word_list = ['python', 'java', 'kotlin', 'javascript']
class GameState:
def __init__(self):
self.turns = 8
self.alive = True
self.state_msg = ''
self.word = random.choice(word_list)
self.guessed_letters = set()
self.tryed_letters = set()
def render_word(self) -> str:
letters_to_hide = set(self.word).difference(self.guessed_letters)
return self.word.translate(str.maketrans(''.join(letters_to_hide), '-' * len(letters_to_hide)))
def sanitize(self, input_string: str) -> None:
if len(input_string) != 1:
print('You should input a single letter')
elif input_string not in string.ascii_lowercase:
print('Please enter a lowercase English letter')
elif input_string in self.tryed_letters:
print("You've already guessed this letter")
else:
self.guess_letter(input_string)
def guess_letter(self, letter: str) -> None:
if letter not in self.word:
self.update("That letter doesn't appear in the word")
else:
self.guessed_letters.add(letter)
if not self.render_word().count('-'):
self.state_msg = 'You guessed the word!\nYou survived!'
self.alive = False
self.tryed_letters.add(letter)
def update(self, msg: str = '') -> None:
self.turns -= 1
self.alive = self.turns != 0
if msg:
print(msg)
if not self.alive:
self.state_msg = 'You lost!'
def game_loop() -> None:
state = GameState()
while state.alive:
print()
print(state.render_word())
state.sanitize(input('Input a letter:'))
print(state.state_msg)
print()
def menu_loop() -> None:
while True:
user_input = input('Type "play" to play the game, "exit" to quit:')
if user_input == 'play':
game_loop()
elif user_input == 'exit':
break
print('H A N G M A N')
menu_loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment