- 2nd Jan 2024
- 21:24 pm
Certainly! Below is an example of a Hangman game in Python that incorporates API functionality to fetch a random word from an online dictionary API - api.dictionaryapi.dev
import requests
import string
# Function to get a random word from the API
def get_random_word():
response = requests.get('https://api.dictionaryapi.dev/api/v2/entries/en/random')
if response.status_code == 200:
word = response.json()[0]['word']
return word.upper()
else:
print("Error: Failed to fetch a random word")
return None
# Function to display the masked word
def display_word(word, guessed_letters):
masked_word = ''
for letter in word:
if letter in guessed_letters:
masked_word += letter + ' '
else:
masked_word += '_ '
return masked_word
# Function to play Hangman
def play_hangman():
print("Welcome to Hangman!")
word_to_guess = get_random_word()
if word_to_guess:
guessed_letters = []
attempts = 6
while attempts > 0:
print("\n" + display_word(word_to_guess, guessed_letters))
print(f"Attempts left: {attempts}")
guess = input("Guess a letter: ").upper()
if len(guess) == 1 and guess.isalpha():
if guess in guessed_letters:
print("You've already guessed that letter!")
elif guess in word_to_guess:
guessed_letters.append(guess)
if set(guessed_letters) == set(word_to_guess):
print(f"Congratulations! You guessed the word: {word_to_guess}")
break
else:
attempts -= 1
print("Incorrect guess!")
else:
print("Please enter a single alphabetic character.")
if attempts == 0:
print("Sorry, you're out of attempts. The word was:", word_to_guess)
# Start the game
play_hangman()
This Hangman game utilizes the requests library to interact with the api.dictionaryapi.dev API to fetch a random English word for the game. The player has to guess the word by inputting letters, and they have limited attempts to guess the word correctly.