import random
# List of words to choose from
word_list = ["python", "hangman", "programming", "computer", "keyboard", "developer", "password"]
# Select a random word from the list
chosen_word = random.choice(word_list)
# Create a list to store the guessed letters
guessed_letters = []
# Maximum number of allowed incorrect guesses
max_attempts = 6
attempts = 0
# Display the initial state of the game
display_word = ["_"] * len(chosen_word)
while True:
# Print the current state of the game
print(" ".join(display_word))
print(f"Guessed Letters: {' '.join(guessed_letters)}")
# Ask the player for a letter guess
guess = input("Guess a letter: ").lower()
# Check if the guess is a single letter
if len(guess) != 1 or not guess.isalpha():
print("Please enter a single letter.")
continue
# Check if the letter has already been guessed
if guess in guessed_letters:
print("You've already guessed that letter.")
continue
guessed_letters.append(guess)
# Check if the guess is correct
if guess in chosen_word:
for i in range(len(chosen_word)):
if chosen_word[i] == guess:
display_word[i] = guess
else:
attempts += 1
print(f"Wrong guess! You have {max_attempts - attempts} attempts left.")
# Check if the player has won or lost
if "_" not in display_word:
print(f"Congratulations! You've won. The word was {chosen_word}")
break
elif attempts == max_attempts:
print(f"You've run out of attempts. The word was '{chosen_word}'. Game over!")
break
_ _ _ _ _ _ _ _
Guessed Letters:
_ a _ _ _ _ _ _
Guessed Letters: a
Wrong guess! You have 5 attempts left.
_ a _ _ _ _ _ _
Guessed Letters: a e
Wrong guess! You have 4 attempts left.
_ a _ _ _ _ _ _
Guessed Letters: a e f
Wrong guess! You have 3 attempts left.
_ a _ _ _ _ _ _
Guessed Letters: a e f l
p a _ _ _ _ _ _
Guessed Letters: a e f l p
p a s s _ _ _ _
Guessed Letters: a e f l p s
p a s s w _ _ _
Guessed Letters: a e f l p s w
p a s s w o _ _
Guessed Letters: a e f l p s w o
p a s s w o r _
Guessed Letters: a e f l p s w o r
Congratulations! You've won. The word was password