import gradio as gr import json GRID_SIZE = 8 class GameState: def __init__(self): self.resources = { "energy": 50, "minerals": 50, "circuits": 0 } self.grid = [[None for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)] self.message = "" def to_json(self): return json.dumps({ "resources": self.resources, "grid": self.grid, "message": self.message }) def process_click(row, col, building_type, state_json): if not state_json: return GameState().to_json() state = json.loads(state_json) game = GameState() game.resources = state["resources"] game.grid = state["grid"] # Building costs costs = { "solarPanel": {"minerals": 10}, "mineralExtractor": {"energy": 10}, "circuitFactory": {"energy": 15, "minerals": 15} } # Check if we can afford the building if building_type in costs: can_afford = True for resource, cost in costs[building_type].items(): if game.resources[resource] < cost: can_afford = False game.message = f"Not enough {resource}!" break if can_afford: # Deduct resources for resource, cost in costs[building_type].items(): game.resources[resource] -= cost # Place building if game.grid[row][col] is None: game.grid[row][col] = building_type game.message = f"Placed {building_type}" else: game.message = "Space already occupied!" # Produce resources from buildings for r in range(GRID_SIZE): for c in range(GRID_SIZE): building = game.grid[r][c] if building == "solarPanel": game.resources["energy"] += 1 elif building == "mineralExtractor": game.resources["minerals"] += 1 elif building == "circuitFactory": game.resources["circuits"] += 1 return game.to_json() def create_ui(): building_colors = { "solarPanel": "#FEF08A", "mineralExtractor": "#D1D5DB", "circuitFactory": "#BBF7D0" } html = f"""
Energy: 50
Minerals: 50
Circuits: 0
{''''.join(f''' ''' for r in range(GRID_SIZE) for c in range(GRID_SIZE))}
""" return gr.HTML(html) with gr.Blocks() as demo: state = gr.State() click_handler = gr.Interface( fn=process_click, inputs=[ gr.Number(label="Row"), gr.Number(label="Col"), gr.Text(label="Building"), gr.Text(label="State") ], outputs=gr.Text(label="New State"), live=True ) ui = create_ui() def update_ui(value): return value click_handler.load(lambda: GameState().to_json()) demo.load(lambda: None, None, _js="() => { window.send_click = (row, col, building, state) => { "+click_handler.jsfn+"(row, col, building, state).then((v) => updateUI(JSON.parse(v))) } }") demo.launch()