File size: 9,143 Bytes
3cb409b 54aee5d 3cb409b |
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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import plotly.graph_objects as go
import random
import time
# Генератор процедурной вселенной
class UniverseGenerator:
def __init__(self):
self.galaxy_map = {}
self.planet_types = ['Lava', 'Ocean', 'Desert', 'Ice', 'Jungle', 'Toxic', 'Radioactive']
self.star_classes = ['O', 'B', 'A', 'F', 'G', 'K', 'M']
self.resources = ['Titanium', 'Quartz', 'Hydrogen', 'Neutronium', 'Exotic Matter']
def generate_system(self, seed):
random.seed(seed)
system = {
'name': f"{random.choice(self.star_classes)}-{random.randint(1000,9999)}",
'planets': [],
'position': (random.uniform(-100,100), random.uniform(-100,100), random.uniform(-100,100))
}
num_planets = random.randint(3, 8)
for i in range(num_planets):
planet_type = random.choice(self.planet_types)
planet = {
'name': f"{system['name']}-{chr(97+i)}",
'type': planet_type,
'resources': random.sample(self.resources, random.randint(1, 3)),
'fauna': random.randint(0, 15),
'flora': random.randint(0, 15),
'temperature': random.uniform(-200, 500),
'gravity': random.uniform(0.2, 2.5),
'size': random.uniform(0.5, 2.0)
}
system['planets'].append(planet)
return system
def generate_galaxy(self, num_systems=100):
for i in range(num_systems):
self.galaxy_map[f"System-{i}"] = self.generate_system(i)
return self.galaxy_map
# Игровой движок
class WebspaceEngine:
def __init__(self):
self.universe = UniverseGenerator()
self.galaxy = self.universe.generate_galaxy()
self.player = {
'position': (0, 0, 0),
'current_system': 'System-0',
'resources': {'Titanium': 10, 'Quartz': 5},
'ship': 'Explorer-class',
'credits': 1000
}
self.discovered_systems = ['System-0']
def travel_to_system(self, system_name):
if system_name in self.galaxy:
self.player['current_system'] = system_name
if system_name not in self.discovered_systems:
self.discovered_systems.append(system_name)
return self.galaxy[system_name]
return None
def scan_planet(self, planet_index):
system = self.galaxy[self.player['current_system']]
if 0 <= planet_index < len(system['planets']):
return system['planets'][planet_index]
return None
def mine_resources(self, planet_index, resource):
planet = self.scan_planet(planet_index)
if planet and resource in planet['resources']:
amount = random.randint(1, 5)
self.player['resources'][resource] = self.player['resources'].get(resource, 0) + amount
return f"Mined {amount} units of {resource}"
return "Resource not found"
# Графические функции
def create_galaxy_map(discovered_systems, galaxy_map):
fig = go.Figure()
for sys_name in discovered_systems:
system = galaxy_map[sys_name]
x, y, z = system['position']
# Звезда
fig.add_trace(go.Scatter3d(
x=[x], y=[y], z=[z],
mode='markers',
marker=dict(size=8, color='yellow'),
name=sys_name
))
# Планеты
for planet in system['planets']:
px = x + random.uniform(-3, 3)
py = y + random.uniform(-3, 3)
pz = z + random.uniform(-3, 3)
colors = {
'Lava': 'red',
'Ocean': 'blue',
'Desert': 'orange',
'Ice': 'lightblue',
'Jungle': 'green',
'Toxic': 'purple',
'Radioactive': 'greenyellow'
}
fig.add_trace(go.Scatter3d(
x=[px], y=[py], z=[pz],
mode='markers',
marker=dict(size=4, color=colors.get(planet['type'], 'gray')),
name=planet['name']
))
fig.update_layout(
scene=dict(
xaxis=dict(title='X'),
yaxis=dict(title='Y'),
zaxis=dict(title='Z')
),
margin=dict(l=0, r=0, b=0, t=0),
height=500
)
return fig
def create_planet_surface(planet_type):
size = 100
terrain = np.zeros((size, size))
# Генерация процедурного ландшафта
for i in range(size):
for j in range(size):
terrain[i][j] = (
np.sin(i/5) +
np.cos(j/7) +
np.sin(np.sqrt((i - size/2)**2 + (j - size/2)**2)/3)
)
# Цветовые схемы для разных планет
colormaps = {
'Lava': ['black', 'darkred', 'red', 'orange'],
'Ocean': ['darkblue', 'blue', 'cyan', 'white'],
'Desert': ['saddlebrown', 'sandybrown', 'wheat', 'white'],
'Ice': ['darkblue', 'lightblue', 'cyan', 'white'],
'Jungle': ['darkgreen', 'green', 'lightgreen', 'yellow'],
'Toxic': ['darkgreen', 'purple', 'fuchsia', 'pink'],
'Radioactive': ['darkgreen', 'green', 'greenyellow', 'yellow']
}
cmap = LinearSegmentedColormap.from_list("custom", colormaps.get(planet_type, ['gray']), N=256)
fig, ax = plt.subplots(figsize=(8, 8))
ax.imshow(terrain, cmap=cmap)
ax.axis('off')
plt.tight_layout()
return fig
# Инициализация движка
engine = WebspaceEngine()
# Gradio интерфейс
with gr.Blocks(title="Webspace Network") as demo:
gr.Markdown("# 🚀 Webspace Network")
gr.Markdown("### Cosmic Exploration Simulator (No Man's Sky inspired)")
with gr.Row():
with gr.Column(scale=1):
current_system = gr.Textbox(label="Current System", value=engine.player['current_system'])
system_info = gr.JSON(label="System Data")
planet_index = gr.Slider(0, 7, step=1, label="Planet Index")
scan_btn = gr.Button("🛰️ Scan Planet")
planet_info = gr.JSON(label="Planet Data")
resource_select = gr.Dropdown(engine.universe.resources, label="Resource to Mine")
mine_btn = gr.Button("⛏️ Mine Resource")
mine_result = gr.Textbox(label="Mining Result")
travel_target = gr.Dropdown(list(engine.galaxy.keys()), label="Select System")
travel_btn = gr.Button("🌌 Hyperjump")
player_resources = gr.JSON(label="Your Resources", value=engine.player['resources'])
with gr.Column(scale=2):
galaxy_map = gr.Plot(label="Galaxy Map")
planet_view = gr.Plot(label="Planet Surface")
# Обновление карты галактики
def update_galaxy_map():
return create_galaxy_map(engine.discovered_systems, engine.galaxy)
# Обновление информации о системе
def update_system_info():
system = engine.galaxy[engine.player['current_system']]
return {
"Name": system['name'],
"Position": [round(x, 2) for x in system['position']],
"Planets": len(system['planets'])
}
# Сканирование планеты
def scan_planet(idx):
planet = engine.scan_planet(int(idx))
if planet:
fig = create_planet_surface(planet['type'])
return planet, fig
return {}, None
# Добыча ресурсов
def mine_resource(resource, idx):
result = engine.mine_resources(int(idx), resource)
return result, engine.player['resources']
# Путешествие между системами
def travel_to_system(system):
engine.travel_to_system(system)
return {
"current_system": system,
"system_info": update_system_info(),
"galaxy_map": update_galaxy_map()
}
# Привязка событий
demo.load(
fn=update_galaxy_map,
outputs=galaxy_map
)
demo.load(
fn=update_system_info,
outputs=system_info
)
scan_btn.click(
fn=scan_planet,
inputs=planet_index,
outputs=[planet_info, planet_view]
)
mine_btn.click(
fn=mine_resource,
inputs=[resource_select, planet_index],
outputs=[mine_result, player_resources]
)
travel_btn.click(
fn=travel_to_system,
inputs=travel_target,
outputs=[current_system, system_info, galaxy_map]
)
current_system.change(
fn=update_system_info,
outputs=system_info
)
# Запуск приложения
if __name__ == "__main__":
demo.launch() |