Recently I was given homework to make a hangman homework test andgame, where I wrote something likethe below (python3)..
How can I refactor this to use classes?
import secrets
def guess_the_word():
tries_left = 9
output = ["_"] * len(secret_word)
print(str(' '.join([letter for letter in output])).strip())
while tries_left >= 0 and not secret_word == str(''.join([letter for letter in output])):
# print tries left
print("\nYou have {} tries left".format(tries_left))
# display the _ which is length of the secret_word and fill in _ as and when the user
# types correct word
guessed_letter = input("Guess a letter from secret word:")
if guessed_letter in secret_word:
print("You guessed correct")
for i, x in enumerate(secret_word):
if x is guessed_letter:
output[i] = guessed_letter
else:
tries_left -= 1
print("You guessed incorrect")
print(str(' '.join([letter for letter in output])).strip())
print("\nWelcome to Hangman Game!\n")
# open words.txt file to read words
with open("words.txt") as words_file:
words_list = words_file.read().split()
# choose a random word from words_list
secret_word = secrets.choice(words_list)
guess_the_word()
How do I refactor this to use Classes?