import random from typing import TypedDict import gradio as gr from langgraph.graph import StateGraph, END # ---------------------- # LangGraph Game Logic # ---------------------- class GameState(TypedDict): bet: int result: str roll: int def node_roll(state: GameState): roll = random.randint(1, 6) + random.randint(1, 6) state["roll"] = roll return state def node_win(state: GameState): state["result"] = "win" return state def node_loss(state: GameState): state["result"] = "loss" return state def decide(state: GameState): if state["roll"] <= state["bet"]: return "win_node" return "loss_node" # Build LangGraph graph = StateGraph(GameState) graph.add_node("roll_node", node_roll) graph.add_node("win_node", node_win) graph.add_node("loss_node", node_loss) graph.set_entry_point("roll_node") graph.add_conditional_edges("roll_node", decide) graph.add_edge("win_node", END) graph.add_edge("loss_node", END) app = graph.compile() # ---------------------- # Gradio App State # ---------------------- class Dashboard: def __init__(self): self.total = 0 self.history = [] def update(self, result): if result == "win": self.total += 10 else: self.total -= 5 self.history.append(result) dashboard = Dashboard() # ---------------------- # Game Function # ---------------------- def play_game(bet): if bet is None or bet < 2 or bet > 12: return "Enter a valid bet (2-12)", dashboard.total, str(dashboard.history) state = {"bet": int(bet)} result_state = app.invoke(state) roll = result_state["roll"] result = result_state["result"] dashboard.update(result) message = f"🎲 Dice Roll: {roll} → You {result.upper()}" return message, dashboard.total, str(dashboard.history) def stop_game(): return "🛑 Game stopped.", dashboard.total, str(dashboard.history) # ---------------------- # Gradio UI (HF Spaces Ready) # ---------------------- with gr.Blocks(title="Dice Betting Game") as demo: gr.Markdown(""" # 🎲 Dice Betting Game (LangGraph) Place a bet between 2 and 12.\n - Win → +$10 - Loss → -$5 """) with gr.Row(): bet_input = gr.Number(label="Enter your bet (2-12)") with gr.Row(): play_btn = gr.Button("🎯 Place Bet") stop_btn = gr.Button("🛑 Stop") output = gr.Textbox(label="Game Output") total_score = gr.Number(label="💰 Total Winnings ($)") history_box = gr.Textbox(label="📜 Game History") play_btn.click(play_game, inputs=bet_input, outputs=[output, total_score, history_box]) stop_btn.click(stop_game, outputs=[output, total_score, history_box]) # Required for Hugging Face Spaces app = demo # ---------------------- # requirements.txt (create separately in repo) # ---------------------- # gradio # langgraph