I have recently made a hangman game using python. This is the main bulk of the code, however, there are other files that I have writen that get the words from a dictionary, or see if a word repeats any letters.
import Pick_Word, Unique_Chars
word = (Pick_Word.get_word()).upper()
wordlist = list(word)
dict = dict(enumerate(wordlist))
slots = list('_' * len(word))
print(' '.join(slots))
def game(word):
guess_num = 12
already = []
while '_' in slots:
x = input("Guess the letter: ")
while x in already:
x = input("Guess the letter: ")
for i in range(len(x)):
if x[i] not in already:
already.append(x[i])
turns = True
for a,b in dict.items():
if x.upper() == word:
return 'Win\nOnly {} more turns left over'.format(guess_word.title())
elif len(x) > 1:
single = Unique_Chars.unique(x)
length = len(single)
for idx in single:
if b == idx.upper():
slots[a] = idx.upper()
new_word = ' '.join(slots)
elif b == x.upper():
slots[a] = x.upper()
new_word = ' '.join(slots)
new_word = ' '.join(slots)
if len(x) > 1:
for i in range(length):
if single[i].upper() not in word:
guess_num -= 1
elif x.upper() not in word:
guess_num -= 1
print(new_word, '\n{} turns left'.format(guess_num))
if guess_num == 0:
return 'Lose\nActual Word was: {}'.format(word.title())
elif word == str(slots):
return 'Win\nOnly {} more turns left over'.format(guess_word.title())
print(game(word))
Is there anyway that I could shorten this code down, or make it run better, without completly rewirting the entire thing? Any feedback is much appreciated. Thanks
Pick_Word
&Unique_Chars
to help people reviewing your code understand as well as provide a better more meaningful review. \$\endgroup\$