I am fairly new to coding and decided to test my skills and make a program from scratch on my own. I chose to make a Hangman game, it's pretty straight forward. The code reads a file consisting of ~40,000+ words to choose from when generating a word for the user. The user inputs the number of attempts and the minimum length of a word they would prefer. As the player guesses, the word is displayed with only the correct guesses displayed to the user. The incorrect guesses are shown to the user as they are entered. Fairly simple, yet I feel like my code is confusing so I was just curious if anyone had any tips on what I could fix/improve to make my code more readable and run more efficiently. Any feedback is appreciated.
import random
word_file = 'popular.txt'
word_list = open(word_file).read().splitlines()
def get_attempts():
"""
returns # attempts user wants
"""
while True:
try:
attempts = int(input("How many incorrect attempts do you want? [1-25] "))
except:
print('There was a error. Enter an interger between 1 and 25!\n')
continue
else:
return attempts
def get_min_len():
"""
returns minimum word length
"""
while True:
try:
min_len = int(input("What minimum word length do you want[4-16] "))
except:
print('There was a error. Enter an integer between 4 and 16!\n')
continue
else:
if min_len < 4 or min_len > 16:
print("Enter a integer between 4 and 16!\n")
continue
else:
return min_len
def pick_word(minlen):
# pick random word from word list
random_word = random.choice(word_list)
while len(random_word) < minlen:
random_word = random.choice(word_list)
return random_word
def fill_word(main_word, covered_word, user_guess):
"""
fills in hidden word as user guesses correctly
"""
covered_word_list = list(covered_word)
for idx in range(0, len(main_word)):
if main_word[idx] == user_guess:
covered_word_list[idx] = user_guess
covered_word = ''.join(covered_word_list)
return covered_word
def display_info(covered_word, atmps, incorrect):
print("Word: {}".format(covered_word))
print("Attempts Remaining: {}".format(atmps))
print("Previous Guesses: {}".format(incorrect))
def get_guess():
"""
error/exception handling for user input
"""
while True:
try:
user_guess = str(input('Choose a letter: '))
except:
print("There was a Error. Enter a letter!\n")
continue
else:
if not user_guess.isalpha():
print("Guess MUST BE a STRING!\n")
continue
elif len(user_guess) != 1:
print("Enter ONLY ONE letter!\n")
continue
else:
return user_guess
def check_guess(main_word, user_guess):
if guess in main_word:
print("{} is in the word!\n".format(user_guess))
else:
print("{} is not in the word!\n".format(user_guess))
def start_game():
while True:
try:
start = input("Are you ready to play? Enter 'Yes' or 'No': ")
except:
print("There was an error. Try again.\n")
continue
else:
if start.isspace():
print("Enter either 'Yes' or 'No'!")
continue
if start[0].lower() == 'y':
play = True
return play
elif start[0].lower() == 'n':
play = False
return play
else:
print("There was an error, try again.\n")
continue
def replay():
while True:
try:
replay = input("Do you want to play again. Enter 'Yes' or 'No': ")
except:
print("There was an error. Try again.\n")
continue
else:
if replay[0].lower() == 'y':
play = True
return play
elif replay[0].lower() == 'n':
play = False
return play
else:
print("There was an error, try again.\n")
continue
GAMEPLAY
play = start_game() # ask user if they are ready return bool
while play:
attempts = get_attempts() # get # of attempts user wants
min_len = get_min_len() # get min len of word
print("Selecting a word...\n")
word = pick_word(min_len) # choose word <= min_len
final_word = word # store word has another variable
hidden_word = '*' * len(word) # create str of '*' == len(word)
guess_list_w = [] # list of incorrect guesses
guess_list_c = [] # list of correct guesses
while word != hidden_word:
display_info(hidden_word, attempts, guess_list_w) # display information for user
guess = get_guess() # get a guess from user
if guess in word:
if guess not in guess_list_w and guess not in guess_list_c:
print("{} is in the word!\n".format(guess)) # if correct guess
hidden_word = fill_word(final_word, hidden_word, guess)
guess_list_c.append(guess)
continue
elif guess in guess_list_c: # if guess is in word but already guessed try again
print("{} has been guessed already! Try Again!\n".format(guess))
continue
elif guess in guess_list_w: # if guess is not in word but already guessed
print("{} has been guessed already! Try Again!\n".format(guess))
continue
else: # if guess hasnt been guessed and is not in the word
print("{} is not in the word!\n".format(guess)) # if incorrect guess
guess_list_w.append(guess)
if attempts == 1: # check num of attempts left; if 0 break
break
else:
attempts -= 1
# Winning Scenario
if hidden_word == word:
print("You Win! You guesses the correct letters!")
print("The word was {}\n\n".format(final_word))
else:
# Losing Scenario
print("You Lose! You're out of attempts!")
print("The word was {}\n\n".format(final_word))
play = replay() # ask player to play again