I created a basic Hangman game that uses a text file to select a secret word. Are there any areas for improvement?
import random
secret_word = ['']
user_list = []
number_of_tries = 5
guessed_letters = []
user_tries = 0
user_guess = ''
def select_word():
global secret_word, user_list
with open('secret_words.txt', 'r') as f:
word = f.read()
word_list = word.split('\n')
secret_word = word_list[random.randint(1, len(word_list))]
user_list = ['-'] * len(secret_word)
def game_over():
if user_tries == number_of_tries or user_list == list(secret_word):
return True
else:
return False
def user_input():
global user_guess
user_guess = input('Guess a letter\n')
check_guess(user_guess)
def repeated(guess):
global guessed_letters
if guess in guessed_letters:
print('You already guessed that letter!\n')
return True
else:
guessed_letters.append(user_guess)
return False
def check_guess(guess):
correct_guess = False
for x in range(len(secret_word)):
if guess == secret_word[x]:
user_list[x] = guess
correct_guess = True
elif not correct_guess and x == len(secret_word)-1:
global user_tries
user_tries += 1
print('Wrong guess, you lose one try\n'
'Remaining tries : {}\n'.format(number_of_tries - user_tries))
if correct_guess:
print('Correct guess!')
def valid_input(user_letter):
valid_letters = 'qwertyuiopasdfghjklzxcvbnm'
if user_letter.lower() in list(valid_letters):
return True
else:
print('Invalid input')
return False
# main code:
print('----HANG MAN----')
print('*Welcome, guess the word\n*you have 5 tries.')
select_word()
while not game_over():
for x in user_list:
print(x, end='')
user_guess = input('\nGuess a letter : ')
if valid_input(user_guess):
if repeated(user_guess):
continue
else:
check_guess(user_guess)
if user_list != list(secret_word):
print('Game over, you died!\ncorrect word was {}'.format(secret_word))
else:
print('Congratulations! you guessed the correct word\n')