Assignment Criteria
Create another version of the Hangman game, this time using Lists. The program should ask for the word to guess and the number of chances to be given.
It should then split the characters in the word into individual items in a list. The other player should then be allowed to guess characters in the word. The program should display correctly guessed characters and unknown characters in the same way as the previous Hangman game.
This a simple Hangman game in Python and I was just wondering if there was any code improvements that could be done with this. I can definitely see a few, but they're very minor changes (e.g. spaces can be removed as it's redundant and never really gets used.)
# ========== Variables ============ #
letter_bank = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
guessed = False # Word has been guessed. (boolean)
spaces = "" # Blanks
word_guess = [] # Placeholder
word_chars = [] # Characters in Word.
word = "" # Word being guessed.
max_guess = None # Maximum amount of Guess.
cur_guess = 0 # Current count of Guesses.
# ================================= #
def findOccurences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
print('''
Welcome to Hangman! Simplified version of the original Hangman.
''')
word = input("Please enter a word: ").lower()
max_guess = int(input("Maximum Guess: "))
for character in word:
word_chars.append(character)
if (character != " "):
spaces += "_ "
word_guess.append("-")
else:
spaces += (" ")
word_guess.append(" ")
print("\n" * 50)
print('''
You are now ready to play.
''')
print("Word: %s. " % (spaces))
while (cur_guess < max_guess) and guessed == False:
if (word.split() == (''.join(word_guess)).split()):
guessed = True
print('''
You have successfully guessed the word!
''')
break;
letter_guess = input("Please enter your guess: ").lower()
if (len(letter_guess) == 1):
if (letter_guess not in letter_bank):
print("You have already used that letter!") # Prints if the character is invalid or already used.
else:
if (letter_guess in word_chars):
print("%s is in the word!" % letter_guess)
letter_bank.remove(letter_guess)
for each in findOccurences(word, letter_guess):
word_guess[each] = letter_guess
print(''.join(word_guess))
else:
print(''.join(word_guess))
print("%s is not in the word!" % letter_guess)
letter_bank.remove(letter_guess)
cur_guess += 1
else:
if (letter_guess == word):
print('''
You have successfully guessed the word!
''')
else:
print('''
You have lost the game! :(
''')
break;