import openai import random import os import gradio as gr # Retrieve the OpenAI API key from Hugging Face Secrets openai.api_key = os.getenv('OPENAI_API_KEY') # Define the words and their clues for each difficulty level with at least 10 words word_list = { 'Beginner': { 'apple': ['fruit', 'red', 'tree'], 'book': ['read', 'pages', 'story'], 'car': ['drive', 'vehicle', 'wheels'], 'dog': ['pet', 'bark', 'tail'], 'house': ['home', 'building', 'roof'], 'rain': ['wet', 'cloud', 'storm'], 'tree': ['leaves', 'wood', 'tall'], 'chair': ['sit', 'furniture', 'legs'], 'phone': ['call', 'device', 'ring'], 'shirt': ['clothing', 'wear', 'sleeve'] }, 'Intermediate': { 'planet': ['orbit', 'solar', 'space'], 'bridge': ['cross', 'river', 'connect'], 'computer': ['device', 'keyboard', 'screen'], 'ocean': ['water', 'sea', 'waves'], 'mountain': ['tall', 'peak', 'climb'], 'school': ['learn', 'students', 'teacher'], 'market': ['buy', 'sell', 'goods'], 'train': ['rails', 'transport', 'station'], 'forest': ['trees', 'wild', 'nature'], 'painting': ['art', 'canvas', 'brush'] }, 'Advanced': { 'philosophy': ['thought', 'ethics', 'reason'], 'courage': ['bravery', 'fear', 'bold'], 'innovation': ['new', 'ideas', 'progress'], 'gravity': ['force', 'pull', 'earth'], 'liberty': ['freedom', 'rights', 'society'], 'education': ['knowledge', 'teach', 'learn'], 'architecture': ['buildings', 'design', 'structure'], 'diplomacy': ['negotiation', 'peace', 'agreement'], 'agriculture': ['farming', 'crops', 'soil'], 'democracy': ['government', 'voting', 'people'] }, 'Expert': { 'ephemeral': ['short-lived', 'fleeting', 'temporary'], 'labyrinth': ['maze', 'complex', 'twist'], 'serendipity': ['chance', 'happy', 'unexpected'], 'obfuscate': ['confuse', 'unclear', 'hide'], 'obstreperous': ['noisy', 'unruly', 'disruptive'], 'quintessential': ['perfect', 'ideal', 'example'], 'perspicacious': ['observant', 'insightful', 'sharp'], 'antediluvian': ['ancient', 'prehistoric', 'old'], 'ineffable': ['indescribable', 'beyond words', 'inexpressible'], 'magnanimous': ['generous', 'noble', 'big-hearted'] } } # Function to get 5 random words and clues for the chosen difficulty def get_five_words(difficulty): return random.sample(list(word_list[difficulty].items()), 5) # Function to interact with OpenAI for additional clues (if requested by the player) def generate_hint(word): response = openai.ChatCompletion.create( model="gpt-4-0613", messages=[ {"role": "system", "content": "You are a helpful assistant that gives hints for words."}, {"role": "user", "content": f"Give me a hint for the word '{word}' without saying the word directly."} ], max_tokens=30 ) return response.choices[0].message['content'].strip() # Game state variables game_state = { "word_list": [], "current_word_index": 0, "attempts": 3, "score": 0, "clue_index": 0, "difficulty": "Beginner", "max_words": 5 # The game will consist of 5 words } # Scoring system based on difficulty scoring = { 'Beginner': [30, 20, 10], 'Intermediate': [40, 30, 20], 'Advanced': [50, 40, 30], 'Expert': [60, 50, 40] } # Function to reset the game state for a new round def reset_game(difficulty): words = get_five_words(difficulty) game_state.update({ "word_list": words, "current_word_index": 0, "attempts": 3, "clue_index": 0, "difficulty": difficulty, "score": 0 }) word, clues = words[0] return f"New game started with {game_state['max_words']} words at {difficulty} level. Here's your first clue: {clues[0]}" # Function to move to the next word after a guess def next_word(): game_state["current_word_index"] += 1 if game_state["current_word_index"] >= game_state["max_words"]: return f"Game over! You've completed {game_state['max_words']} words. Your total score is {game_state['score']}." game_state["attempts"] = 3 game_state["clue_index"] = 0 word, clues = game_state["word_list"][game_state["current_word_index"]] return f"Let's now go to the next word! Here's your first clue: {clues[0]}" # Function to check the user's guess def guess_word(guess): guess = guess.lower() word, clues = game_state["word_list"][game_state["current_word_index"]] if guess == word: difficulty = game_state["difficulty"] attempts = game_state["attempts"] points = scoring[difficulty][3 - attempts] # Points for 3rd, 2nd, or 1st attempt game_state["score"] += points message = f"Correct! You've earned {points} points. The word was '{word}'. Your total score is {game_state['score']}." # Move to the next word or end the game if max words reached message += f"\n\n{next_word()}" return message, next_word() # Two outputs: guess feedback and next word clue else: game_state["attempts"] -= 1 game_state["clue_index"] += 1 if game_state["attempts"] == 0: message = f"Sorry, you're out of guesses! The correct word was '{word}'." # Move to the next word or end the game if max words reached message += f"\n\n{next_word()}" return message, next_word() return f"Incorrect! Try again. Here's your next clue: {clues[game_state['clue_index']]}", f"Next clue: {clues[game_state['clue_index']]}" # Function to give an extra hint using OpenAI (no points awarded) def get_extra_hint(): word, _ = game_state["word_list"][game_state["current_word_index"]] hint = generate_hint(word) return f"Extra hint: {hint}. No points will be awarded for guessing this word now." # Gradio Interface with gr.Blocks(css=""" #feedback { position: absolute; top: 20px; right: 20px; background-color: #f8f9fa; border: 1px solid #e0e0e0; padding: 10px; border-radius: 5px; font-weight: bold; font-size: 14px; } #instructions { background-color: #f8f9fa; padding: 10px; border: 1px solid #e0e0e0; border-radius: 5px; } #guess-section { margin-top: 50px; /* Add vertical space before the "Your Guess" section */ } /* Add responsive behavior for mobile devices */ @media only screen and (max-width: 768px) { .gr-blocks { padding: 10px; } .gr-row { flex-direction: column; } #feedback { position: relative; top: auto; right: auto; margin-top: 10px; } #guess-section { margin-top: 20px; } button, input { font-size: 16px; } } """) as game_interface: # Layout with two columns with gr.Row(): with gr.Column(scale=2): # Left side (main game interface) # Game feedback (top-right corner on desktop, below on mobile) guess_output = gr.Markdown("", elem_id="feedback") # Game output (clues and game messages) game_info = gr.Markdown("") # Section for guessing (with space above) with gr.Column(elem_id="guess-section"): guess_input = gr.Textbox(label="Your Guess", placeholder="Type your guess here.") guess_button = gr.Button("Submit Guess") # Section for extra hint hint_button = gr.Button("Get Extra Hint (No Points)") hint_output = gr.Markdown("") with gr.Column(scale=1): # Right side (instructions) # Instructions block gr.Markdown(""" ### Instructions: - Choose a difficulty level and click 'Start New Game'. - You will be given 5 words to guess. - You earn points based on how quickly you guess the word. - If you need an extra hint, click 'Get Extra Hint', but no points will be awarded for the word. - Good luck! """, elem_id="instructions") # Section for Game Setup (below instructions and game) with gr.Row(): difficulty = gr.Dropdown(choices=['Beginner', 'Intermediate', 'Advanced', 'Expert'], label="Select Difficulty Level", value="Beginner") start_button = gr.Button("Start New Game / Reset Game") # Action Connections start_button.click(fn=reset_game, inputs=difficulty, outputs=game_info) guess_button.click(fn=guess_word, inputs=guess_input, outputs=[guess_output, game_info]) hint_button.click(fn=get_extra_hint, outputs=hint_output) # Launch the Gradio interface game_interface.launch()