ewebspace/lineages
0
1import gradio as gr2import json3import random4import math5import numpy as np6 7# ================== ГЛОБАЛЬНЫЕ НАСТРОЙКИ ==================8UNIVERSE_SEED = 429RESOURCE_TYPES = ['Iron', 'Copper', 'Gold', 'Water', 'Oxygen', 'Hydrogen', 'Silicon', 'Titanium']10CIVILIZATION_STAGES = [11 {"title": "I. Биологический", "color": "#00cc44", "desc": "Углеродно-водные формы жизни..."},12 {"title": "II. Техногенный", "color": "#00aaff", "desc": "Промышленная и цифровая революция..."},13 {"title": "III. Постбиологический", "color": "#ff7700", "desc": "Переход к цифровому существованию..."},14 {"title": "IV. Космический", "color": "#aa55ff", "desc": "Межзвездные путешествия..."},15 {"title": "V. Универсальный", "color": "#ffff00", "desc": "Слияние с космическим разумом..."}16]17 18# ================== ГЕНЕРАТОР ВСЕЛЕННОЙ ==================19class UniverseGenerator:20 def __init__(self, seed=UNIVERSE_SEED):21 self.rng = random.Random(seed)22 self.planet_types = ['Lava', 'Ocean', 'Desert', 'Ice', 'Jungle']23 24 def generate_planet(self, index):25 return {26 'name': f"Planet-{chr(65 + index)}",27 'type': self.rng.choice(self.planet_types),28 'resources': self.rng.sample(RESOURCE_TYPES, self.rng.randint(2, 5)),29 'size': self.rng.uniform(0.8, 1.5),30 'habitability': round(self.rng.uniform(0.1, 0.9), 2)31 }32 33 def generate_system(self, index):34 return {35 'name': f"System-{index}",36 'planets': [self.generate_planet(i) for i in range(self.rng.randint(3, 6))]37 }38 39 def generate_universe(self):40 return {41 'systems': [self.generate_system(i) for i in range(3)],42 'civilization_stages': CIVILIZATION_STAGES43 }44 45# ================== THREE.JS ШАБЛОНЫ ==================46CIVILIZATION_TEMPLATE = """47<!DOCTYPE html>48<html>49<head>50 <title>Эволюция Цивилизаций</title>51 <style>52 body {{ 53 margin: 0; 54 overflow: hidden; 55 background: #001133; 56 color: white; 57 font-family: Arial, sans-serif; 58 }}59 #infoBox {{60 position: absolute; 61 top: 20px; 62 left: 20px; 63 max-width: 350px;64 background: rgba(0, 0, 20, 0.85); 65 padding: 20px; 66 border-radius: 15px;67 border: 1px solid #4a6fff;68 display: none;69 }}70 #title {{71 position: absolute;72 top: 20px;73 width: 100%;74 text-align: center;75 font-size: 24px;76 color: #4fc3f7;77 text-shadow: 0 0 15px rgba(79, 195, 247, 0.8);78 pointer-events: none;79 }}80 </style>81</head>82<body>83 <div id="title">ЭВОЛЮЦИЯ ЦИВИЛИЗАЦИЙ ВО ВСЕЛЕННОЙ</div>84 <div id="infoBox">85 <h2 id="stageTitle"></h2>86 <p id="stageDesc"></p>87 </div>88 89 <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>90 <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.min.js"></script>91 92 <script>93 // Инициализация сцены94 const scene = new THREE.Scene();95 scene.background = new THREE.Color(0x001122);96 const camera = new THREE.PerspectiveCamera(60, window.innerWidth/window.innerHeight, 0.1, 2000);97 const renderer = new THREE.WebGLRenderer({{ antialias: true }});98 renderer.setSize(window.innerWidth, window.innerHeight);99 document.body.appendChild(renderer.domElement);100 101 // Настройка камеры и освещения102 camera.position.set(0, 15, 50);103 const controls = new THREE.OrbitControls(camera, renderer.domElement);104 controls.enableDamping = true;105 106 // Создание звездного поля107 const starGeometry = new THREE.BufferGeometry();108 const starPositions = new Float32Array(5000 * 3);109 for (let i = 0; i < 5000; i++) {{110 starPositions[i*3] = (Math.random() - 0.5) * 2000;111 starPositions[i*3+1] = (Math.random() - 0.5) * 2000;112 starPositions[i*3+2] = (Math.random() - 0.5) * 2000;113 }}114 starGeometry.setAttribute('position', new THREE.BufferAttribute(starPositions, 3));115 const stars = new THREE.Points(starGeometry, new THREE.PointsMaterial({{ color: 0xffffff, size: 1.5 }}));116 scene.add(stars);117 118 // Создание сфер цивилизаций119 const stages = {civilization_stages};120 const spheres = [];121 122 stages.forEach((stage, i) => {{123 const geometry = new THREE.SphereGeometry(4, 32, 32);124 const material = new THREE.MeshStandardMaterial({{125 color: new THREE.Color(stage.color),126 emissive: new THREE.Color(stage.color),127 metalness: 0.7,128 roughness: 0.2129 }});130 131 const sphere = new THREE.Mesh(geometry, material);132 sphere.position.x = (i - stages.length/2) * 15;133 sphere.userData = stage;134 scene.add(sphere);135 spheres.push(sphere);136 }});137 138 // Интерактивность139 const raycaster = new THREE.Raycaster();140 const mouse = new THREE.Vector2();141 const infoBox = document.getElementById("infoBox");142 143 window.addEventListener("click", (event) => {{144 mouse.x = (event.clientX / window.innerWidth) * 2 - 1;145 mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;146 147 raycaster.setFromCamera(mouse, camera);148 const intersects = raycaster.intersectObjects(spheres);149 150 if (intersects.length > 0) {{151 const stage = intersects[0].object.userData;152 document.getElementById("stageTitle").textContent = stage.title;153 document.getElementById("stageDesc").textContent = stage.desc;154 infoBox.style.display = "block";155 }}156 }});157 158 // Анимация159 function animate() {{160 requestAnimationFrame(animate);161 spheres.forEach((sphere, i) => {{162 sphere.rotation.y += 0.01;163 sphere.rotation.x += 0.005;164 }});165 controls.update();166 renderer.render(scene, camera);167 }}168 animate();169 170 // Адаптация под размер окна171 window.addEventListener("resize", () => {{172 camera.aspect = window.innerWidth / window.innerHeight;173 camera.updateProjectionMatrix();174 renderer.setSize(window.innerWidth, window.innerHeight);175 }});176 </script>177</body>178</html>179"""180 181SPACE_EXPLORER_TEMPLATE = """182<!DOCTYPE html>183<html>184<head>185 <title>Космический Исследователь</title>186 <style>187 body {{ 188 margin: 0; 189 overflow: hidden; 190 background: #000; 191 font-family: Arial, sans-serif; 192 }}193 #ui {{194 position: absolute;195 top: 20px;196 left: 20px;197 color: white;198 background: rgba(0, 0, 0, 0.7);199 padding: 15px;200 border-radius: 10px;201 width: 300px;202 }}203 .bar-container {{ width: 100%; background: #333; border-radius: 5px; margin: 5px 0; }}204 .bar {{ height: 20px; border-radius: 5px; text-align: center; color: white; }}205 .health-bar {{ background: linear-gradient(to right, #ff0000, #00ff00); }}206 .fuel-bar {{ background: linear-gradient(to right, #0000ff, #00ffff); }}207 #planet-info {{208 position: absolute;209 top: 20px;210 right: 20px;211 background: rgba(0, 0, 0, 0.7);212 padding: 15px;213 border-radius: 10px;214 color: white;215 display: none;216 }}217 </style>218</head>219<body>220 <div id="ui">221 <h3>Космический Корабль</h3>222 <div>Здоровье: <span id="health-value">100</span>/100</div>223 <div class="bar-container"><div id="health-bar" class="bar health-bar" style="width: 100%"></div></div>224 <div>Топливо: <span id="fuel-value">100</span>/100</div>225 <div class="bar-container"><div id="fuel-bar" class="bar fuel-bar" style="width: 100%"></div></div>226 </div>227 228 <div id="planet-info">229 <h3 id="planet-name"></h3>230 <div>Тип: <span id="planet-type"></span></div>231 <div>Ресурсы: <span id="planet-resources"></span></div>232 </div>233 234 <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>235 <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.min.js"></script>236 237 <script>238 // Инициализация сцены239 const scene = new THREE.Scene();240 scene.background = new THREE.Color(0x000010);241 const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);242 const renderer = new THREE.WebGLRenderer({{ antialias: true }});243 renderer.setSize(window.innerWidth, window.innerHeight);244 document.body.appendChild(renderer.domElement);245 246 // Освещение247 const ambientLight = new THREE.AmbientLight(0x404040);248 scene.add(ambientLight);249 const directionalLight = new THREE.DirectionalLight(0xffffff, 1);250 directionalLight.position.set(1, 1, 1);251 scene.add(directionalLight);252 253 // Корабль игрока254 const shipGeometry = new THREE.ConeGeometry(1, 3, 8);255 const shipMaterial = new THREE.MeshPhongMaterial({{ color: 0x00aaff }});256 const ship = new THREE.Mesh(shipGeometry, shipMaterial);257 ship.rotation.x = Math.PI / 2;258 scene.add(ship);259 260 // Планеты261 const planets = [];262 const universeData = {universe_data};263 264 universeData.systems[0].planets.forEach((planet, i) => {{265 const geometry = new THREE.SphereGeometry(planet.size, 32, 32);266 const material = new THREE.MeshStandardMaterial({{267 color: new THREE.Color(268 planet.type === 'Lava' ? 0xff3300 :269 planet.type === 'Ocean' ? 0x0066ff :270 planet.type === 'Desert' ? 0xffcc00 :271 0x888888272 ),273 roughness: 0.8,274 metalness: 0.2275 }});276 277 const planetMesh = new THREE.Mesh(geometry, material);278 planetMesh.position.x = i * 15 - 30;279 planetMesh.userData = planet;280 scene.add(planetMesh);281 planets.push(planetMesh);282 }});283 284 // Управление кораблем285 const keys = {{}};286 window.addEventListener('keydown', (e) => keys[e.key.toLowerCase()] = true);287 window.addEventListener('keyup', (e) => keys[e.key.toLowerCase()] = false);288 289 // Анимация290 function animate() {{291 requestAnimationFrame(animate);292 293 // Движение корабля294 if (keys['w']) ship.position.z -= 0.1;295 if (keys['s']) ship.position.z += 0.1;296 if (keys['a']) ship.position.x -= 0.1;297 if (keys['d']) ship.position.x += 0.1;298 299 // Обновление камеры300 camera.position.x = ship.position.x;301 camera.position.y = ship.position.y + 5;302 camera.position.z = ship.position.z + 15;303 camera.lookAt(ship.position);304 305 renderer.render(scene, camera);306 }}307 animate();308 309 // Адаптация под размер окна310 window.addEventListener('resize', () => {{311 camera.aspect = window.innerWidth / window.innerHeight;312 camera.updateProjectionMatrix();313 renderer.setSize(window.innerWidth, window.innerHeight);314 }});315 </script>316</body>317</html>318"""319 320# ================== GRADIO ИНТЕРФЕЙС ==================321def create_civilization_demo():322 universe = UniverseGenerator().generate_universe()323 template = CIVILIZATION_TEMPLATE.replace("{civilization_stages}", json.dumps(universe["civilization_stages"]))324 return template325 326def create_space_explorer_demo():327 universe = UniverseGenerator().generate_universe()328 template = SPACE_EXPLORER_TEMPLATE.replace("{universe_data}", json.dumps(universe))329 return template330 331with gr.Blocks(title="Космические Игры", css=".gradio-container {background: #000033;}") as demo:332 gr.Markdown("# 🌌 Две Космические Игры")333 gr.Markdown("### Исследуйте эволюцию цивилизаций и космические просторы")334 335 with gr.Tabs():336 with gr.TabItem("Эволюция Цивилизаций"):337 civ_html = gr.HTML(create_civilization_demo())338 gr.Markdown("""339 **Инструкции:**340 - Кликните на сферы, чтобы узнать о стадиях развития цивилизаций341 - Используйте мышь для вращения камеры342 """)343 344 with gr.TabItem("Космический Исследователь"):345 space_html = gr.HTML(create_space_explorer_demo())346 gr.Markdown("""347 **Управление:**348 - W/S: Движение вперед/назад349 - A/D: Движение влево/вправо350 - Мышь: Управление камерой351 """)352 353 gr.Markdown("### Общие игровые системы:")354 with gr.Accordion("Технические детали", open=False):355 gr.Markdown("""356 **Общие компоненты:**357 1. **Генерация вселенной**: Процедурное создание планет и систем358 2. **Three.js рендеринг**: Реалистичное 3D отображение космоса359 3. **Интерактивные элементы**: Взаимодействие с объектами через UI360 4. **Физика движения**: Реалистичное управление космическим кораблем361 """)362 363if __name__ == "__main__":364 demo.launch()