Here’s a simple Python implementation of a Hangman game to help you get started:
import random
def get_word():
words = ['python', 'java', 'swift', 'javascript', 'hangman']
return random.choice(words)
def display_progress(word, guesses):
return ' '.join([letter if letter in guesses else '_' for letter in word])
def hangman():
word = get_word()
guesses = []
attempts = 6
print("Let's play Hangman!")
while attempts > 0:
print(f"\nWord: {display_progress(word, guesses)}")
print(f"Guesses: {', '.join(guesses)}")
print(f"Attempts left: {attempts}")
guess = input("Guess a letter: ").lower()
if guess in guesses:
print("You already guessed that letter.")
elif guess in word:
print("Good guess!")
guesses.append(guess)
if all(letter in guesses for letter in word):
print(f"\nCongratulations! You've guessed the word '{word}'.")
break
else:
print("Incorrect guess.")
attempts -= 1
guesses.append(guess)
if attempts == 0:
print(f"\nYou've run out of attempts. The word was '{word}'. Better luck next time!")
hangman()
How it Works:
- get_word: Selects a random word from a list.
- display_progress: Displays the word with underscores for unguessed letters.
- hangman: Main game loop that allows the user to guess letters and track attempts.
You can customize the word list, attempts, and add more features as you improve! Enjoy coding your Hangman game!
Leave a Comment