o1-preview-2024-09-12· openai
from WildChat-4.8M
Generate Code for a simple game in python like wordle
- User
Generate Code for a simple game in python like wordle
- Assistant
Certainly! Below is a simple implementation of a Wordle-like game in Python. This game allows the user to guess a secret word, and it provides feedback after each guess. The feedback indicates which letters are correct and in the correct position, and which letters are correct but in the wrong position.
pythonimport random # List of possible 5-letter words word_list = ['apple', 'brain', 'chart', 'drink', 'eagle', 'flame', 'grape', 'heart', 'index', 'jelly'] # Select a random word from the list as the secret word secret_word = random.choice(word_list) word_length = len(secret_word) MAX_ATTEMPTS = 6 print("Welcome to the Wordle-like game!") print(f"Guess the {word_length}-letter secret word. You have {MAX_ATTEMPTS} attempts.\n") def get_feedback(guess, secret): feedback = ['_'] * word_length secret_temp = list(secret) # First pass: check for correct letters in the correct position for i in range(word_length): if guess[i] == secret[i]: feedback[i] = guess[i].upper() secret_temp[i] = None # Remove matched letter # Second pass: check for correct letters in the wrong position for i in range(word_length): if feedback[i] == '_' and guess[i] in secret_temp: feedback[i] = guess[i].lower() # Remove the first occurrence of the letter from secret_temp secret_temp[secret_temp.index(guess[i])] = None return ' '.join(feedback) attempts = 0 while attempts < MAX_ATTEMPTS: guess = input(f"Attempt {attempts + 1}: ").lower() if len(guess) != word_length: print(f"Please enter a {word_length}-letter word.\n") continue if guess not in word_list: print("Word not in the list. Please try again.\n") continue feedback = get_feedback(guess, secret_word) print("Feedback:", feedback, "\n") if guess == secret_word: print("Congratulations! You've guessed the secret word!") break attempts += 1 if attempts == MAX_ATTEMPTS and guess != secret_word: print(f"Sorry, you've used all your attempts. The secret word was '{secret_word}'.")