# Install dependencies # pip install gradio langgraph import gradio as gr import random from typing import Literal from typing_extensions import TypedDict from langgraph.graph import StateGraph, START, END # Define the game state global_score = {"total": 0} game_history = [] # Track game rounds class State(TypedDict): bet: int result: str score: int roll: int # Nodes for LangGraph def roll_node(state): state["roll"] = random.randint(1, 6) + random.randint(1, 6) return state def input_node(state): return state def success_node(state): global_score["total"] += 10 state["result"] = f"🎉 You win! +$10 (Roll: {state['roll']})" state["score"] = global_score["total"] return state def failure_node(state): global_score["total"] -= 5 state["result"] = f"😞 You lose! -$5 (Roll: {state['roll']})" state["score"] = global_score["total"] return state def determine_outcome(state) -> Literal["node_2", "node_3"]: return "node_2" if state["roll"] <= state["bet"] else "node_3" # Build LangGraph builder = StateGraph(State) builder.add_node("roll_node", roll_node) builder.add_node("node_1", input_node) builder.add_node("node_2", success_node) builder.add_node("node_3", failure_node) builder.add_edge(START, "roll_node") builder.add_edge("roll_node", "node_1") builder.add_conditional_edges("node_1", determine_outcome) builder.add_edge("node_2", END) builder.add_edge("node_3", END) graph = builder.compile() # Gradio UI function def play_game(bet: int): if bet < 1 or bet > 12: return "Please enter a value between 1 and 12.", global_score["total"], [] result = graph.invoke({"bet": bet, "result": "", "score": global_score["total"]}) game_history.append({"Bet": bet, "Roll": result["roll"], "Result": result["result"], "Score": result["score"]}) history_table_data = [[g["Bet"], g["Roll"], g["Result"], g["Score"]] for g in game_history[::-1]] return result["result"], result["score"], history_table_data # Gradio Interface with gr.Blocks() as demo: gr.Markdown("## 🎲 Dice Bet Game with LangGraph") with gr.Row(): bet_input = gr.Number(label="Your Bet (1-12)", value=7, precision=0) play_button = gr.Button("🎲 Roll Dice") with gr.Row(): result_output = gr.Textbox(label="Result") score_output = gr.Number(label="Total Winnings", value=0, precision=0, interactive=False) history_table = gr.Dataframe(headers=["Bet", "Roll", "Result", "Score"], label="Game History", interactive=False) play_button.click(play_game, inputs=[bet_input], outputs=[result_output, score_output, history_table]) if __name__ == "__main__": demo.launch()