I was need of help and besides helping me, people told me my code was, although working, a complete mess and under the "Spaghetti Code" category.
Can someone please assist me on how to refactor my code for efficiency and readability purposes?
Any help you can give me is much appreciated.
This is my code: The Hangman Game on Python
import random
import time
from theHangmanStages import * # This imports ASCII hangman figure.
from theHangmanIntro import *
intro() # This just imports an ASCII art as an intro.
startGame = input()
game = 'on'
words = ''' In a strange city lying alone
Far down within the dim West
Where the good and the bad and the worst and the best
Have gone to their eternal rest
There shrines and palaces and towers'''.lower().split()
secretWord = random.sample(words, 1)
numberOFLetters = len(secretWord[0])
missedLetters = ''
alreadyGuessed = ''
print('I\'m thinking of a word...')
time.sleep(1)
print(f'\nThe word has {numberOFLetters} letters...')
for char in secretWord[0]:
print('_ ', end='')
wordSpaces = len(secretWord[0]) * '_'
listedWordSpaces = list(wordSpaces)
def char_positioner(word, guessAttempt):
i = word.index(guessAttempt)
if guessAttempt in word:
listedWordSpaces[i] = word[i]
print(listedWordSpaces)
return listedWordSpaces
def converter(list):
# Converts a list of chars into a string.
initialStr = ''
for char in list:
initialStr += char
print(initialStr)
return initialStr
def getGuess(guess):
# Returns the letter the played entered. This function makes sure the
# player entered a single letter and not something else.
while True:
guess = guess.lower()
if len(guess) != 1:
print('Please enter a single letter.')
guess = input()
elif guess in alreadyGuessed:
print('You have already guessed that letter')
guess = input()
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print('Please enter a letter.')
else:
return guess
misses = 0
while game == 'on':
print('\nChoose a letter')
chosenLetter = input()
guess = getGuess(chosenLetter)
if guess in secretWord[0]:
print('\nYour guess is correct!')
alreadyGuessed += guess
position = char_positioner(secretWord[0], guess)
converter(position)
elif guess not in secretWord[0]:
print('\nWrong letter, try again.')
missedLetters += guess
alreadyGuessed += guess
print('\nMissed letters: ', missedLetters, end=' ')
misses += 1
if misses == 1:
hangmanOne()
elif misses == 2:
hangmanTwo()
elif misses == 3:
hangmanThree()
elif misses == 4:
hangmanFour()
elif misses == 5:
hangmanFive()
elif misses == 6:
hangmanSix()
print('You lose! - The word was:' + '"' + secretWord[0] + '"')
break
else:
print('Wrong input.')