I am currently learning object oriented programming in Python. I attempted writing an OOP program for hangman, and while the program is functional, I just ended up writing a very long class method. Do you have any suggestions on how to improve the code to make it more pythonic, and some resources that can help me drill-in the concepts?
main.py
import random
from words import word_list
from question import Word
from art import logo
import random
print(logo)
new_word = Word(random.choice(word_list))
#print(new_word.word)
word_length = len(new_word.word)
placeholder = ""
for position in range(word_length):
placeholder += "_"
print("Word to guess: " + placeholder)
while new_word.lives != 0:
new_word.check_word()
print(f"You lose! The correct word was '{new_word.word}'.")
question.py
from art import stages
class Word:
def __init__(self,word):
self.word = word
self.lives = 6
self.correct_letters = []
def check_word(self):
guess = input(f"Guess the letter: ").lower()
if guess in self.correct_letters:
print(f"You've already guessed {guess}")
display = ""
for i in self.word:
if i == guess:
print("That's right")
display += i
self.correct_letters.append(i)
elif i in self.correct_letters:
display += i
else:
display += "_"
print("Word to guess: " + display)
if guess not in self.word:
self.lives -= 1
print(f"You guessed {guess}, that's not in the word. You lose a life.")
print(f"You have {self.lives} left.")
print(stages[self.lives])
Wordclass is to play a game of hangman, then I would expect it to be namedHangman. The class nameWorddoes not match with the intended usage. \$\endgroup\$