Develop a snowman game similar to the Hangman game but draws a snowman
figure standing on the snow instead of a hangman. It also downloads (or
uses library) the complete English dictionary to select words for three
levels of difficulty. Think step-by-step, take a deep breath and choose
a higher quality code for each step.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a comprehensive implementation of the Snowman game in Python, incorporating a dictionary lookup for word selection and a visually appealing snowman representation:
python
import random
from typing import List, Tuple
import nltk # For word corpus (download 'words' package if not installed)
nltk.download('words', quiet=True)
from nltk.corpus import words
# Snowman ASCII art components
SNOWMAN_BASE = '___'
SNOWMAN_BODY = '( o.o )'
SNOWMAN_HEAD = '( ^ - ^ )'
SNOWMAN_HAT = '______'
class SnowmanGame:
def __init__(self, difficulty: str = 'medium'):
"""
Initialize the game with a random word from the English dictionary,
tailored to the specified difficulty level.
:param difficulty: One of 'easy', 'medium', or 'hard', defaulting to 'medium'.
"""
self.difficulty_levels = {
'easy': lambda w: 4 <= len(w) <= 6,
'medium': lambda w: 7 <= len(w) <= 9,
'hard': lambda w: len(w) >= 10,
}
assert difficulty in self.difficulty_levels, f"Invalid difficulty: {difficulty}"
self.difficulty = difficulty
self.word_list: List[str] = [w for w in words.words() if self.difficulty_levels[difficulty](w)]
self.word: str = random.choice(self.word_list)
self.guessed: List[bool] = [False] * len(self.word)
self.mistakes: int = 0
def _draw_snowman(self) -> str:
"""Generate the snowman ASCII art based on the number of mistakes."""
parts = [SNOWMAN_HAT, SNOWMAN_HEAD, SNOWMAN_BODY, SNOWMAN_BASE]
for i in range(self.mistakes):
parts[i] = ' ' * len(parts[i]) # Erase snowman parts as mistakes accumulate
return '\n'.join(parts)
def _format_word(self) -> str:
"""Display the word with guessed letters revealed and underscores for unknowns."""
return ' '.join(c if guessed else '_' for c, guessed in zip(self.word, self.guessed))
def play(self) -> None:
"""Main game loop."""
while True:
print(f'\n{self._draw_snowman()}\n')
print(self._format_word())
guess = input(f"Guess a letter (or 'quit' to exit): ").lower()
if guess == 'quit':
print(f"The correct answer was {self.word}.")
return
if len(guess) != 1:
print("Please enter a single letter.")
continue
if guess in self.word:
for i, c in enumerate(self.word):
if c == guess:
self.guessed[i] = True
if all(self.guessed):
print(f"\nCongratulations! You won with the correct answer: {self.word}")
return
else:
self.mistakes += 1
if self.mistakes == 4:
print(f"\nGame over! The correct answer was {self.word}.")
return
print(f"Incorrect! {4 - self.mistakes} chances remaining.")
if __name__ == '__main__':
difficulty = input("Choose a difficulty (easy, medium, hard): ").lower() or 'medium'
game = SnowmanGame(difficulty)
game.play()
Key features and design decisions:
Word selection:
Uses the comprehensive nltk corpus (words) for English words.
Filters words based on length to accommodate three difficulty levels.
Snowman representation:
ASCII art components are modular, allowing easy customization or extension.
The draw_snowman method dynamically generates the snowman based on the number of mistakes.
Gameplay and feedback:
Clear, concise output for the snowman, word, and guess prompts.
Immediate feedback for correct/incorrect guesses, with remaining chances displayed.
Quit option and revealing the correct answer upon game completion.
Robust input handling:
Validates guess length and ignores non-single-character inputs.
Case-insensitive guessing for user convenience.
Modularity and extensibility:
The SnowmanGame class encapsulates game logic, making it easy to modify or replace components (e.g., word selection, snowman art).
Difficulty levels are decoupled from the game logic, allowing effortless addition of new levels or customization.
Tips and variations:
To improve performance, consider caching the filtered word lists for each difficulty level.
Enhance the user experience by adding animations or sounds for correct/incorrect guesses.
Introduce thematic variations, such as seasonal snowman designs or word categories (e.g., countries, animals).
Create a high-score tracking system or leaderboards for competitive play.