import gradio as gr
import json
from dataclasses import dataclass
import numpy as np
class GameState:
def __init__(self):
self.resources = {
"energy": 50,
"minerals": 50,
"circuits": 0
}
self.grid = [[None for _ in range(8)] for _ in range(8)]
self.buildings = {
"solarPanel": {
"cost": {"minerals": 10},
"produces": "energy",
"color": "#FEF08A"
},
"mineralExtractor": {
"cost": {"energy": 10},
"produces": "minerals",
"color": "#D1D5DB"
},
"circuitFactory": {
"cost": {"energy": 15, "minerals": 15},
"produces": "circuits",
"color": "#BBF7D0"
}
}
game_state = GameState()
def update_game(action_type, data):
if action_type == "tick":
# Update resources based on buildings
for row in range(8):
for col in range(8):
building_type = game_state.grid[row][col]
if building_type:
produces = game_state.buildings[building_type]["produces"]
game_state.resources[produces] += 1
elif action_type == "build":
row, col, building_type = data
if game_state.grid[row][col] is not None:
return {"error": "Cell already occupied"}
building = game_state.buildings[building_type]
# Check if can afford
for resource, cost in building["cost"].items():
if game_state.resources[resource] < cost:
return {"error": "Not enough resources"}
# Pay costs
for resource, cost in building["cost"].items():
game_state.resources[resource] -= cost
# Place building
game_state.grid[row][col] = building_type
return {
"resources": game_state.resources,
"grid": game_state.grid,
"buildings": game_state.buildings
}
def create_ui():
html = """
"""
return gr.HTML(html)
def handle_action(action_type, data):
return json.dumps(update_game(action_type, data))
with gr.Blocks() as demo:
ui = create_ui()
action = gr.State("tick")
data = gr.State(None)
demo.load(lambda: handle_action("tick", None), None, _js="(o) => { updateUI(JSON.parse(o)) }")
demo.load(None, None, _js="""
function(arg) {
window.syncGameState = function(actionType, actionData) {
gradioApp().querySelector("gradio-app").props.action_type = actionType;
gradioApp().querySelector("gradio-app").props.action_data = actionData;
updateUI(JSON.parse(handle_action(actionType, actionData)));
}
}
""")
demo.launch()
# No additional requirements needed