I made a simple Hangman game in Python:
import random
class Hangman:
def __init__(self):
self.words = ["bike", "monkey", "planet"]
self.random_word = random.choice(self.words)
self.lenght = len(self.random_word)
self.no_of_try = int(self.lenght) + 3
self.empty_word = ["_"] * self.lenght
@staticmethod
def user_input():
print("Enter a guess: ")
user_input = input()
return user_input
def find_index(self):
letter = self.user_input()
possition = self.random_word.index(letter)
return (letter, possition)
def substitue(self):
try:
guess_letter, guess_index = self.find_index()
self.empty_word[guess_index] = guess_letter
print(self.empty_word)
return True
except ValueError as e:
return False
def play_game(self):
while self.no_of_try > 0:
print("no: " + str(self.no_of_try))
game = self.substitue()
if game:
print("Bravo")
self.no_of_try -= 1
else:
self.no_of_try -= 1
print("Wrong")
if "_" not in self.empty_word:
print("You win")
break
if self.no_of_try == 0:
print("Game over")
break
if __name__ == "__main__":
h = Hangman()
h.play_game()