Spaces:
Sleeping
Sleeping
File size: 1,856 Bytes
55de2f1 1534762 6ed0cce 1534762 6ed0cce 1534762 55de2f1 6ed0cce 1534762 55de2f1 6ed0cce 1534762 6ed0cce 1534762 6ed0cce 1534762 6ed0cce 1534762 55de2f1 1534762 55de2f1 6ed0cce |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import gradio as gr
import random
def start_game():
secret_number = random.randint(1, 100)
attempts = 0
message = "๐ฎ New Game Started! Guess a number between 1 and 100."
return message, secret_number, attempts
def check_guess(user_guess, secret_number, attempts):
if user_guess is None:
return "โ ๏ธ Please enter a number!", secret_number, attempts
attempts += 1
if user_guess < secret_number:
message = f"๐ป Too low! Attempts: {attempts}"
elif user_guess > secret_number:
message = f"๐บ Too high! Attempts: {attempts}"
else:
message = (
f"๐ Correct! The number was {secret_number}. You guessed it in {attempts} tries.\n"
f"๐ Starting a new game..."
)
# Reset game
secret_number = random.randint(1, 100)
attempts = 0
return message, secret_number, attempts
with gr.Blocks() as demo:
gr.Markdown("## ๐ฏ Guess the Number Game\nTry to guess the secret number between 1 and 100.")
with gr.Row():
guess_input = gr.Number(label="Your Guess", precision=0)
guess_button = gr.Button("Submit Guess")
new_game_button = gr.Button("๐ New Game")
result_output = gr.Textbox(label="Result", interactive=False)
# Session state variables
secret_state = gr.State()
attempts_state = gr.State()
# Button click logic
guess_button.click(
check_guess,
inputs=[guess_input, secret_state, attempts_state],
outputs=[result_output, secret_state, attempts_state]
)
new_game_button.click(
start_game,
inputs=[],
outputs=[result_output, secret_state, attempts_state]
)
# Auto-start game when app loads
demo.load(start_game, inputs=[], outputs=[result_output, secret_state, attempts_state])
demo.launch() |