File size: 5,567 Bytes
e4dc0c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import streamlit as st
import numpy as np
import time
from dataclasses import dataclass
from typing import Dict, List, Optional

@dataclass
class Building:
    name: str
    cost: Dict[str, int]
    produces: str
    color: str
    icon: str
    description: str

class FactoryGame:
    def __init__(self):
        self.GRID_SIZE = 8
        self.buildings = {
            "solar_panel": Building(
                name="Solar Panel",
                cost={"minerals": 10},
                produces="energy",
                color="#FEF08A",
                icon="β˜€οΈ",
                description="Produces energy from sunlight"
            ),
            "mineral_extractor": Building(
                name="Mineral Extractor",
                cost={"energy": 10},
                produces="minerals",
                color="#D1D5DB",
                icon="⛏️",
                description="Extracts minerals from the ground"
            ),
            "circuit_factory": Building(
                name="Circuit Factory",
                cost={"energy": 15, "minerals": 15},
                produces="circuits",
                color="#BBF7D0",
                icon="πŸ”§",
                description="Produces electronic circuits"
            )
        }

        # Initialize session state if needed
        if "resources" not in st.session_state:
            st.session_state.resources = {
                "energy": 50,
                "minerals": 50,
                "circuits": 0
            }
        if "grid" not in st.session_state:
            st.session_state.grid = [[None for _ in range(self.GRID_SIZE)] 
                                   for _ in range(self.GRID_SIZE)]
        if "last_update" not in st.session_state:
            st.session_state.last_update = time.time()

    def update_resources(self):
        current_time = time.time()
        elapsed = current_time - st.session_state.last_update
        
        if elapsed >= 1.0:  # Update every second
            for row in range(self.GRID_SIZE):
                for col in range(self.GRID_SIZE):
                    building_id = st.session_state.grid[row][col]
                    if building_id:
                        building = self.buildings[building_id]
                        st.session_state.resources[building.produces] += 1
            st.session_state.last_update = current_time

    def can_afford(self, building_id: str) -> bool:
        building = self.buildings[building_id]
        for resource, cost in building.cost.items():
            if st.session_state.resources.get(resource, 0) < cost:
                return False
        return True

    def place_building(self, row: int, col: int, building_id: str) -> bool:
        if not self.can_afford(building_id):
            st.error(f"Cannot afford {self.buildings[building_id].name}!")
            return False

        if st.session_state.grid[row][col] is not None:
            st.error("Space already occupied!")
            return False

        # Deduct costs
        building = self.buildings[building_id]
        for resource, cost in building.cost.items():
            st.session_state.resources[resource] -= cost

        # Place building
        st.session_state.grid[row][col] = building_id
        st.success(f"Placed {building.name}")
        return True

def main():
    st.set_page_config(page_title="Factory Game", layout="wide")
    
    game = FactoryGame()
    
    # Title and description
    st.title("🏭 Factory Game")
    st.markdown("""
    Build your factory empire! Place buildings, manage resources, and optimize production.
    """)
    
    # Layout columns
    col1, col2 = st.columns([3, 1])
    
    with col2:
        # Resources display
        st.subheader("Resources")
        st.metric("⚑ Energy", f"{st.session_state.resources['energy']}")
        st.metric("πŸͺ¨ Minerals", f"{st.session_state.resources['minerals']}")
        st.metric("πŸ”Œ Circuits", f"{st.session_state.resources['circuits']}")
        
        # Building selection
        st.subheader("Buildings")
        selected_building = None
        for building_id, building in game.buildings.items():
            if st.button(
                f"{building.icon} {building.name}\n"
                f"Cost: {', '.join(f'{cost} {res}' for res, cost in building.cost.items())}",
                help=building.description,
                key=f"building_{building_id}"
            ):
                selected_building = building_id

    with col1:
        # Game grid
        st.subheader("Factory Grid")
        
        # Create a grid of buttons
        for row in range(game.GRID_SIZE):
            cols = st.columns(game.GRID_SIZE)
            for col, column in enumerate(cols):
                building_id = st.session_state.grid[row][col]
                building = game.buildings.get(building_id) if building_id else None
                
                # Style the button based on what's there
                label = building.icon if building else "⬜"
                
                if column.button(
                    label,
                    key=f"cell_{row}_{col}",
                    help=building.name if building else "Empty space"
                ):
                    if selected_building:
                        game.place_building(row, col, selected_building)
    
    # Update resources periodically
    game.update_resources()
    
    # Force a rerun every second to update resources
    time.sleep(0.1)
    st.experimental_rerun()

if __name__ == "__main__":
    main()