I'd like to know how to improve this code because I think that the main_func
is too big and I can not split it into other functions or classes.
Also, I want to know if I can or should use classes to make it cleaner.
import random
import string
def starting():
print('HANGMAN')
print('Set game mode:')
print('0. To exit')
print('1. Easy')
print('2. Medium')
print('3. Hard')
difficult = int(input('Your choice: '))
if difficult == 1:
difficult_easy()
elif difficult == 2:
difficult_medium()
elif difficult == 3:
difficult_hard()
else:
exit('Exiting...')
def main_func(word_lst, guesses_given):
secret_word = random.choice(word_lst)
output = []
guessed_letters = []
alphabet = string.ascii_letters
length = len(secret_word)
print(f'Your word has {len(secret_word)} characters ')
for i in range(len(secret_word)):
output.append('_')
while '_' in output:
letter = input('Enter a letter: ')
if letter not in alphabet:
print('You should enter only one letter!\n ')
elif len(letter) != 1:
print('You can only display 1 letter at a time\n')
else:
if letter not in guessed_letters:
guessed_letters.append(letter)
if letter in secret_word:
for n in range(length):
if secret_word[n] == letter:
output[n] = letter.upper()
print(*output, sep=' ')
if '_' not in output:
print('You won!')
if letter not in secret_word:
guesses_given -= 1
print(f"This letter is not in the secret word. REMAINING TRIES: {guesses_given}\n")
if guesses_given == 0:
print(f"You lost. The secret word was '{secret_word.upper()}'")
break
else:
print('You have already guessed this letter!\n\n')
print('GAMEOVER')
play_again()
def play_again():
again = input('Play again? (y/n)\n')
if again.lower() == 'yes' or again.lower() == 'y':
starting()
else:
exit('Exiting...')
def difficult_easy():
main_func(['hall', 'exam', 'road', 'gate', 'debt', 'poet', 'sir', 'girl', 'food'], 14)
def difficult_medium():
main_func(['customer', 'baseball', 'language', 'stranger', 'quantity',
'judgment', 'republic', 'proposal', 'magazine'], 12)
def difficult_hard():
main_func(['assumption', 'impression', 'restaurant', 'indication', 'excitement',
'depression', 'government', 'inspection', 'protection', 'investment'], 10)
if __name__ == '__main__':
starting()
For me, it looks garbage, but I did my best to make it simple and short at the same time. I want to use classes to make it more simple, but I still hadn't figured out... The last thing I want to ask is about the if __name__ == '__main__':
, am I using it correctly?
I posted it on Stack Overflow but people said that the site is only for specific problems in your code, so they told me to go here.
if __name__ == '__main__':
correctly, I have some doubts. \$\endgroup\$