ewebspace commited on
Commit
3cb409b
·
verified ·
1 Parent(s): 5bd8fac

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +263 -0
app.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ from matplotlib.colors import LinearSegmentedColormap
5
+ import plotly.graph_objects as go
6
+ import random
7
+ import time
8
+
9
+ # Генератор процедурной вселенной
10
+ class UniverseGenerator:
11
+ def __init__(self):
12
+ self.galaxy_map = {}
13
+ self.planet_types = ['Lava', 'Ocean', 'Desert', 'Ice', 'Jungle', 'Toxic', 'Radioactive']
14
+ self.star_classes = ['O', 'B', 'A', 'F', 'G', 'K', 'M']
15
+ self.resources = ['Titanium', 'Quartz', 'Hydrogen', 'Neutronium', 'Exotic Matter']
16
+
17
+ def generate_system(self, seed):
18
+ random.seed(seed)
19
+ system = {
20
+ 'name': f"{random.choice(self.star_classes)}-{random.randint(1000,9999)}",
21
+ 'planets': [],
22
+ 'position': (random.uniform(-100,100), random.uniform(-100,100), random.uniform(-100,100))
23
+ }
24
+
25
+ num_planets = random.randint(3, 8)
26
+ for i in range(num_planets):
27
+ planet_type = random.choice(self.planet_types)
28
+ planet = {
29
+ 'name': f"{system['name']}-{chr(97+i)}",
30
+ 'type': planet_type,
31
+ 'resources': random.sample(self.resources, random.randint(1, 3)),
32
+ 'fauna': random.randint(0, 15),
33
+ 'flora': random.randint(0, 15),
34
+ 'temperature': random.uniform(-200, 500),
35
+ 'gravity': random.uniform(0.2, 2.5),
36
+ 'size': random.uniform(0.5, 2.0)
37
+ }
38
+ system['planets'].append(planet)
39
+
40
+ return system
41
+
42
+ def generate_galaxy(self, num_systems=100):
43
+ for i in range(num_systems):
44
+ self.galaxy_map[f"System-{i}"] = self.generate_system(i)
45
+ return self.galaxy_map
46
+
47
+ # Игровой движок
48
+ class WebspaceEngine:
49
+ def __init__(self):
50
+ self.universe = UniverseGenerator()
51
+ self.galaxy = self.universe.generate_galaxy()
52
+ self.player = {
53
+ 'position': (0, 0, 0),
54
+ 'current_system': 'System-0',
55
+ 'resources': {'Titanium': 10, 'Quartz': 5},
56
+ 'ship': 'Explorer-class',
57
+ 'credits': 1000
58
+ }
59
+ self.discovered_systems = ['System-0']
60
+
61
+ def travel_to_system(self, system_name):
62
+ if system_name in self.galaxy:
63
+ self.player['current_system'] = system_name
64
+ if system_name not in self.discovered_systems:
65
+ self.discovered_systems.append(system_name)
66
+ return self.galaxy[system_name]
67
+ return None
68
+
69
+ def scan_planet(self, planet_index):
70
+ system = self.galaxy[self.player['current_system']]
71
+ if 0 <= planet_index < len(system['planets']):
72
+ return system['planets'][planet_index]
73
+ return None
74
+
75
+ def mine_resources(self, planet_index, resource):
76
+ planet = self.scan_planet(planet_index)
77
+ if planet and resource in planet['resources']:
78
+ amount = random.randint(1, 5)
79
+ self.player['resources'][resource] = self.player['resources'].get(resource, 0) + amount
80
+ return f"Mined {amount} units of {resource}"
81
+ return "Resource not found"
82
+
83
+ # Графические функции
84
+ def create_galaxy_map(discovered_systems, galaxy_map):
85
+ fig = go.Figure()
86
+
87
+ for sys_name in discovered_systems:
88
+ system = galaxy_map[sys_name]
89
+ x, y, z = system['position']
90
+
91
+ # Звезда
92
+ fig.add_trace(go.Scatter3d(
93
+ x=[x], y=[y], z=[z],
94
+ mode='markers',
95
+ marker=dict(size=8, color='yellow'),
96
+ name=sys_name
97
+ ))
98
+
99
+ # Планеты
100
+ for planet in system['planets']:
101
+ px = x + random.uniform(-3, 3)
102
+ py = y + random.uniform(-3, 3)
103
+ pz = z + random.uniform(-3, 3)
104
+
105
+ colors = {
106
+ 'Lava': 'red',
107
+ 'Ocean': 'blue',
108
+ 'Desert': 'orange',
109
+ 'Ice': 'lightblue',
110
+ 'Jungle': 'green',
111
+ 'Toxic': 'purple',
112
+ 'Radioactive': 'greenyellow'
113
+ }
114
+
115
+ fig.add_trace(go.Scatter3d(
116
+ x=[px], y=[py], z=[pz],
117
+ mode='markers',
118
+ marker=dict(size=4, color=colors.get(planet['type'], 'gray')),
119
+ name=planet['name']
120
+ ))
121
+
122
+ fig.update_layout(
123
+ scene=dict(
124
+ xaxis=dict(title='X'),
125
+ yaxis=dict(title='Y'),
126
+ zaxis=dict(title='Z')
127
+ ),
128
+ margin=dict(l=0, r=0, b=0, t=0),
129
+ height=500
130
+ )
131
+ return fig
132
+
133
+ def create_planet_surface(planet_type):
134
+ size = 100
135
+ terrain = np.zeros((size, size))
136
+
137
+ # Генерация процедурного ландшафта
138
+ for i in range(size):
139
+ for j in range(size):
140
+ terrain[i][j] = (np.sin(i/5) + np.cos(j/7) +
141
+ np.sin(np.sqrt((i-size/2)**2 + (j-size/2)**2)/3)
142
+
143
+ # Цветовые схемы для разных планет
144
+ colormaps = {
145
+ 'Lava': ['black', 'darkred', 'red', 'orange'],
146
+ 'Ocean': ['darkblue', 'blue', 'cyan', 'white'],
147
+ 'Desert': ['saddlebrown', 'sandybrown', 'wheat', 'white'],
148
+ 'Ice': ['darkblue', 'lightblue', 'cyan', 'white'],
149
+ 'Jungle': ['darkgreen', 'green', 'lightgreen', 'yellow'],
150
+ 'Toxic': ['darkgreen', 'purple', 'fuchsia', 'pink'],
151
+ 'Radioactive': ['darkgreen', 'green', 'greenyellow', 'yellow']
152
+ }
153
+
154
+ cmap = LinearSegmentedColormap.from_list("custom", colormaps.get(planet_type, ['gray']), N=256)
155
+
156
+ fig, ax = plt.subplots(figsize=(8, 8))
157
+ ax.imshow(terrain, cmap=cmap)
158
+ ax.axis('off')
159
+ plt.tight_layout()
160
+ return fig
161
+
162
+ # Инициализация движка
163
+ engine = WebspaceEngine()
164
+
165
+ # Gradio интерфейс
166
+ with gr.Blocks(title="Webspace Network") as demo:
167
+ gr.Markdown("# 🚀 Webspace Network")
168
+ gr.Markdown("### Cosmic Exploration Simulator (No Man's Sky inspired)")
169
+
170
+ with gr.Row():
171
+ with gr.Column(scale=1):
172
+ current_system = gr.Textbox(label="Current System", value=engine.player['current_system'])
173
+ system_info = gr.JSON(label="System Data")
174
+
175
+ planet_index = gr.Slider(0, 7, step=1, label="Planet Index")
176
+ scan_btn = gr.Button("🛰️ Scan Planet")
177
+ planet_info = gr.JSON(label="Planet Data")
178
+
179
+ resource_select = gr.Dropdown(engine.universe.resources, label="Resource to Mine")
180
+ mine_btn = gr.Button("⛏️ Mine Resource")
181
+ mine_result = gr.Textbox(label="Mining Result")
182
+
183
+ travel_target = gr.Dropdown(list(engine.galaxy.keys()), label="Select System")
184
+ travel_btn = gr.Button("🌌 Hyperjump")
185
+
186
+ player_resources = gr.JSON(label="Your Resources", value=engine.player['resources'])
187
+
188
+ with gr.Column(scale=2):
189
+ galaxy_map = gr.Plot(label="Galaxy Map")
190
+ planet_view = gr.Plot(label="Planet Surface")
191
+
192
+ # Обновление карты галактики
193
+ def update_galaxy_map():
194
+ return create_galaxy_map(engine.discovered_systems, engine.galaxy)
195
+
196
+ # Обновление информации о системе
197
+ def update_system_info():
198
+ system = engine.galaxy[engine.player['current_system']]
199
+ return {
200
+ "Name": system['name'],
201
+ "Position": [round(x, 2) for x in system['position']],
202
+ "Planets": len(system['planets'])
203
+ }
204
+
205
+ # Сканирование планеты
206
+ def scan_planet(idx):
207
+ planet = engine.scan_planet(int(idx))
208
+ if planet:
209
+ fig = create_planet_surface(planet['type'])
210
+ return planet, fig
211
+ return {}, None
212
+
213
+ # Добыча ресурсов
214
+ def mine_resource(resource, idx):
215
+ result = engine.mine_resources(int(idx), resource)
216
+ return result, engine.player['resources']
217
+
218
+ # Путешествие между системами
219
+ def travel_to_system(system):
220
+ engine.travel_to_system(system)
221
+ return {
222
+ "current_system": system,
223
+ "system_info": update_system_info(),
224
+ "galaxy_map": update_galaxy_map()
225
+ }
226
+
227
+ # Привязка событий
228
+ demo.load(
229
+ fn=update_galaxy_map,
230
+ outputs=galaxy_map
231
+ )
232
+
233
+ demo.load(
234
+ fn=update_system_info,
235
+ outputs=system_info
236
+ )
237
+
238
+ scan_btn.click(
239
+ fn=scan_planet,
240
+ inputs=planet_index,
241
+ outputs=[planet_info, planet_view]
242
+ )
243
+
244
+ mine_btn.click(
245
+ fn=mine_resource,
246
+ inputs=[resource_select, planet_index],
247
+ outputs=[mine_result, player_resources]
248
+ )
249
+
250
+ travel_btn.click(
251
+ fn=travel_to_system,
252
+ inputs=travel_target,
253
+ outputs=[current_system, system_info, galaxy_map]
254
+ )
255
+
256
+ current_system.change(
257
+ fn=update_system_info,
258
+ outputs=system_info
259
+ )
260
+
261
+ # Запуск приложения
262
+ if __name__ == "__main__":
263
+ demo.launch()