|
import gradio as gr |
|
from RockPaperScissor.models import RandomAI |
|
|
|
|
|
ai_model = RandomAI() |
|
|
|
|
|
def _determine_winner(player_move, ai_move): |
|
"""Determines the winner and returns a result code and message.""" |
|
if player_move == ai_move: |
|
return "draw", f"It's a draw! (Both chose {player_move})" |
|
elif (player_move == "rock" and ai_move == "scissors") or \ |
|
(player_move == "paper" and ai_move == "rock") or \ |
|
(player_move == "scissors" and ai_move == "paper"): |
|
return "player_win", f"You win! ({player_move} beats {ai_move})" |
|
else: |
|
return "ai_win", f"AI wins! ({ai_move} beats {player_move})" |
|
|
|
|
|
def play_round(player_choice, current_stats): |
|
""" |
|
Handles one round of the game. |
|
Updates stats stored in the Gradio state. |
|
""" |
|
print(f"Player chose: {player_choice}") |
|
print(f"Current stats before round: {current_stats}") |
|
|
|
|
|
ai_choice, _ = ai_model.make_move() |
|
print(f"AI chose: {ai_choice}") |
|
|
|
|
|
result_code, result_message = _determine_winner(player_choice, ai_choice) |
|
|
|
|
|
if result_code == "player_win": |
|
current_stats["wins"] += 1 |
|
elif result_code == "ai_win": |
|
current_stats["losses"] += 1 |
|
else: |
|
current_stats["draws"] += 1 |
|
|
|
print(f"Current stats after round: {current_stats}") |
|
|
|
|
|
full_result_message = f"You chose: {player_choice}\nAI chose: {ai_choice}\n\n{result_message}" |
|
stats_string = f"Wins: {current_stats['wins']} | Losses: {current_stats['losses']} | Draws: {current_stats['draws']}" |
|
|
|
|
|
return full_result_message, stats_string, current_stats |
|
|
|
|
|
with gr.Blocks(title="Rock Paper Scissors Demo") as demo: |
|
gr.Markdown("# Rock Paper Scissors - Simple Demo") |
|
gr.Markdown("Play against a Random AI. Choose your move:") |
|
|
|
|
|
session_state = gr.State(value={"wins": 0, "losses": 0, "draws": 0}) |
|
|
|
with gr.Row(): |
|
rock_btn = gr.Button("πͺ¨ Rock") |
|
paper_btn = gr.Button("π Paper") |
|
scissors_btn = gr.Button("βοΈ Scissors") |
|
|
|
result_output = gr.Textbox(label="Round Result", lines=3) |
|
stats_output = gr.Label(label="Session Score") |
|
|
|
|
|
|
|
rock_btn.click( |
|
fn=play_round, |
|
inputs=[gr.Textbox("rock", visible=False), session_state], |
|
outputs=[result_output, stats_output, session_state] |
|
) |
|
paper_btn.click( |
|
fn=play_round, |
|
inputs=[gr.Textbox("paper", visible=False), session_state], |
|
outputs=[result_output, stats_output, session_state] |
|
) |
|
scissors_btn.click( |
|
fn=play_round, |
|
inputs=[gr.Textbox("scissors", visible=False), session_state], |
|
outputs=[result_output, stats_output, session_state] |
|
) |
|
|
|
|
|
demo.launch() |