import gradio as gr import random # Function to handle the guessing logic def guess_number(guess, secret_number, attempts): if secret_number is None: # Initialize the secret number and reset attempts secret_number = random.randint(1, 100) attempts = 0 # Validate input if not isinstance(guess, (int, float)) or not (1 <= guess <= 100): result = "⚠️ Please enter an integer between 1 and 100." return result, secret_number, attempts attempts += 1 # Increment the number of attempts if attempts > 8: # Game over if the number of attempts exceeds 8 result = f"💥 Game Over! You couldn't guess the number within 8 attempts. The number was {secret_number}. Starting a new game." secret_number = None # Reset the game attempts = 0 elif guess == secret_number: result = f"🎉 Congratulations! You guessed the number {secret_number} in {attempts} attempt(s). Starting a new game." secret_number = None # Reset the game attempts = 0 elif guess < secret_number: result = f"📉 Too low! Attempt {attempts}/8." else: result = f"📈 Too high! Attempt {attempts}/8." return result, secret_number, attempts # Function to restart the game def restart_game(secret_number, attempts): secret_number = random.randint(1, 100) attempts = 0 result = "🔄 Game has been restarted! Try to guess the new number between 1 and 100." return result, secret_number, attempts # Function to reveal the answer def reveal_answer(secret_number, attempts): if secret_number is None: # If no game is active, start a new one first secret_number = random.randint(1, 100) attempts = 0 result = f"🔍 The secret number was {secret_number}. Starting a new game." secret_number = None # Reset the game attempts = 0 return result, secret_number, attempts with gr.Blocks() as iface: gr.Markdown("# 🕵️‍♂️ Number Guessing Game") gr.Markdown("Try to guess the secret number between 1 and 100 in less than 8 attempts.") guess_input = gr.Number(label="Enter your guess", precision=0, interactive=True) # Main output display for results output = gr.Textbox(label="Result", lines=2, interactive=False) # Button row for Guess, Restart, and Reveal actions with gr.Row(): submit_button = gr.Button("Guess") restart_button = gr.Button("🔄 Restart Game") reveal_button = gr.Button("🔍 Reveal Answer") # Initialize state for secret number and attempts count secret_number_state = gr.State() attempts_state = gr.State() # Define what happens when the Guess button is clicked submit_button.click( fn=guess_number, inputs=[guess_input, secret_number_state, attempts_state], outputs=[output, secret_number_state, attempts_state] ) # Define what happens when the Restart button is clicked restart_button.click( fn=restart_game, inputs=[secret_number_state, attempts_state], outputs=[output, secret_number_state, attempts_state] ) # Define what happens when the Reveal Answer button is clicked reveal_button.click( fn=reveal_answer, inputs=[secret_number_state, attempts_state], outputs=[output, secret_number_state, attempts_state] ) iface.launch()