awacke1 commited on
Commit
3a99762
·
verified ·
1 Parent(s): 2c98932

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +661 -0
app.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import streamlit.components.v1 as components
3
+ import asyncio
4
+ import websockets
5
+ import uuid
6
+ import os
7
+ import random
8
+ import time
9
+ import hashlib
10
+ from datetime import datetime
11
+ import pytz
12
+ import nest_asyncio
13
+ import edge_tts
14
+ from audio_recorder_streamlit import audio_recorder
15
+
16
+ # Patch asyncio for nesting
17
+ nest_asyncio.apply()
18
+
19
+ # Page Config
20
+ st.set_page_config(page_title="Galaxian Snake 3D Multiplayer", layout="wide")
21
+
22
+ st.title("Galaxian Snake 3D Multiplayer")
23
+ st.write("Navigate a 3D city with others, eat food, and chat in real-time!")
24
+
25
+ # Sliders for container size
26
+ max_width = min(1200, st.session_state.get('window_width', 1200))
27
+ max_height = min(1600, st.session_state.get('window_height', 1600))
28
+
29
+ col1, col2 = st.columns(2)
30
+ with col1:
31
+ container_width = st.slider("Container Width (px)", 300, max_width, 768, step=50)
32
+ with col2:
33
+ container_height = st.slider("Container Height (px)", 400, max_height, 1024, step=50)
34
+
35
+ # Session State Initialization
36
+ def init_session_state():
37
+ defaults = {
38
+ 'server_running': False, 'server_task': None, 'active_connections': {},
39
+ 'chat_history': [], 'last_chat_update': 0, 'username': None,
40
+ 'tts_voice': "en-US-AriaNeural", 'audio_cache': {}
41
+ }
42
+ for k, v in defaults.items():
43
+ if k not in st.session_state:
44
+ st.session_state[k] = v
45
+
46
+ init_session_state()
47
+
48
+ # Usernames and Voices
49
+ FUN_USERNAMES = {
50
+ "CosmicJester 🌌": "en-US-AriaNeural",
51
+ "PixelPanda 🐼": "en-US-JennyNeural",
52
+ "QuantumQuack 🦆": "en-GB-SoniaNeural",
53
+ "StellarSquirrel 🐿️": "en-AU-NatashaNeural",
54
+ "GizmoGuru ⚙️": "en-CA-ClaraNeural",
55
+ "NebulaNinja 🌠": "en-US-GuyNeural",
56
+ }
57
+
58
+ if not st.session_state.username:
59
+ st.session_state.username = random.choice(list(FUN_USERNAMES.keys()))
60
+ st.session_state.tts_voice = FUN_USERNAMES[st.session_state.username]
61
+
62
+ # Chat File
63
+ CHAT_FILE = "chat_logs/global_chat.md"
64
+ os.makedirs("chat_logs", exist_ok=True)
65
+ if not os.path.exists(CHAT_FILE):
66
+ with open(CHAT_FILE, 'a') as f:
67
+ f.write("# Multiplayer Snake Chat\n\nWelcome to the cosmic city! 🎤\n")
68
+
69
+ # Audio Processing
70
+ async def async_edge_tts_generate(text, voice, username):
71
+ cache_key = f"{text[:100]}_{voice}"
72
+ if cache_key in st.session_state['audio_cache']:
73
+ return st.session_state['audio_cache'][cache_key]
74
+ filename = f"audio_logs/{datetime.now().strftime('%Y%m%d_%H%M%S')}-by-{username}-{hashlib.md5(text.encode()).hexdigest()[:8]}.mp3"
75
+ os.makedirs("audio_logs", exist_ok=True)
76
+ communicate = edge_tts.Communicate(text, voice)
77
+ await communicate.save(filename)
78
+ if os.path.exists(filename) and os.path.getsize(filename) > 0:
79
+ st.session_state['audio_cache'][cache_key] = filename
80
+ return filename
81
+ return None
82
+
83
+ def play_and_download_audio(file_path):
84
+ if file_path and os.path.exists(file_path):
85
+ with open(file_path, "rb") as f:
86
+ audio_bytes = f.read()
87
+ st.audio(audio_bytes, format="audio/mp3")
88
+ b64 = base64.b64encode(audio_bytes).decode()
89
+ st.markdown(f'<a href="data:audio/mpeg;base64,{b64}" download="{os.path.basename(file_path)}">🎵 Download {os.path.basename(file_path)}</a>', unsafe_allow_html=True)
90
+
91
+ # WebSocket Handling
92
+ async def websocket_handler(websocket, path):
93
+ client_id = str(uuid.uuid4())
94
+ room_id = "snake_chat"
95
+ if room_id not in st.session_state.active_connections:
96
+ st.session_state.active_connections[room_id] = {}
97
+ st.session_state.active_connections[room_id][client_id] = websocket
98
+ username = st.session_state.username
99
+ await broadcast_message(f"System|{username} has joined the game!", room_id)
100
+ try:
101
+ async for message in websocket:
102
+ if '|' in message:
103
+ sender, content = message.split('|', 1)
104
+ await save_chat_entry(sender, content)
105
+ else:
106
+ await websocket.send("ERROR|Message format: username|content")
107
+ except websockets.ConnectionClosed:
108
+ await broadcast_message(f"System|{username} has left the game!", room_id)
109
+ finally:
110
+ if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
111
+ del st.session_state.active_connections[room_id][client_id]
112
+
113
+ async def broadcast_message(message, room_id):
114
+ if room_id in st.session_state.active_connections:
115
+ disconnected = []
116
+ for client_id, ws in st.session_state.active_connections[room_id].items():
117
+ try:
118
+ await ws.send(message)
119
+ except websockets.ConnectionClosed:
120
+ disconnected.append(client_id)
121
+ for client_id in disconnected:
122
+ if client_id in st.session_state.active_connections[room_id]:
123
+ del st.session_state.active_connections[room_id][client_id]
124
+
125
+ async def run_websocket_server():
126
+ if not st.session_state.get('server_running', False):
127
+ server = await websockets.serve(websocket_handler, '0.0.0.0', 8765)
128
+ st.session_state['server_running'] = True
129
+ await server.wait_closed()
130
+
131
+ def start_websocket_server():
132
+ loop = asyncio.new_event_loop()
133
+ asyncio.set_event_loop(loop)
134
+ loop.run_until_complete(run_websocket_server())
135
+
136
+ # Chat Functions
137
+ async def save_chat_entry(username, message):
138
+ central = pytz.timezone('US/Central')
139
+ timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
140
+ entry = f"[{timestamp}] {username}: {message}"
141
+ with open(CHAT_FILE, 'a') as f:
142
+ f.write(f"{entry}\n")
143
+ audio_file = await async_edge_tts_generate(message, FUN_USERNAMES.get(username, "en-US-AriaNeural"), username)
144
+ if audio_file:
145
+ play_and_download_audio(audio_file)
146
+ await broadcast_message(f"{username}|{message}", "snake_chat")
147
+ st.session_state.chat_history.append(entry)
148
+ st.session_state.last_chat_update = time.time()
149
+
150
+ async def load_chat():
151
+ with open(CHAT_FILE, 'r') as f:
152
+ content = f.read().strip()
153
+ return content.split('\n')
154
+
155
+ # Game HTML
156
+ html_code = f"""
157
+ <!DOCTYPE html>
158
+ <html lang="en">
159
+ <head>
160
+ <meta charset="UTF-8">
161
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
162
+ <title>Galaxian Snake 3D Multiplayer</title>
163
+ <style>
164
+ body {{ margin: 0; overflow: hidden; font-family: Arial, sans-serif; }}
165
+ #gameContainer {{ width: {container_width}px; height: {container_height}px; position: relative; }}
166
+ canvas {{ width: 100%; height: 100%; display: block; }}
167
+ .ui-container {{
168
+ position: absolute; top: 10px; left: 10px; color: white;
169
+ background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 5px;
170
+ user-select: none;
171
+ }}
172
+ .controls {{
173
+ position: absolute; bottom: 10px; left: 10px; color: white;
174
+ background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 5px;
175
+ }}
176
+ #chatBox {{
177
+ position: absolute; bottom: 60px; left: 10px; width: 300px; height: 200px;
178
+ background: rgba(0, 0, 0, 0.7); color: white; padding: 10px;
179
+ border-radius: 5px; overflow-y: auto;
180
+ }}
181
+ </style>
182
+ </head>
183
+ <body>
184
+ <div id="gameContainer">
185
+ <div class="ui-container">
186
+ <h2>Galaxian Snake 3D</h2>
187
+ <div id="players">Players: 1</div>
188
+ <div id="score">Score: 0</div>
189
+ <div id="length">Length: 3</div>
190
+ <div id="leaderboard"></div>
191
+ </div>
192
+ <div id="chatBox"></div>
193
+ <div class="controls">
194
+ <p>Controls: W/A/S/D or Arrow Keys to move</p>
195
+ <p>Eat yellow cubes to grow and score!</p>
196
+ </div>
197
+ </div>
198
+
199
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
200
+ <script>
201
+ // Game variables
202
+ let score = 0, players = {{}}, foodItems = [], lSysCreatures = [], quineAgents = [], buildings = [];
203
+ let snake = [], moveDir = new THREE.Vector3(1, 0, 0), moveCounter = 0, moveInterval = 0.1;
204
+ const initialLength = 3, playerName = "{st.session_state.username}";
205
+ const highScores = JSON.parse(localStorage.getItem('highScores')) || [];
206
+ let ws = new WebSocket('ws://localhost:8765');
207
+
208
+ // Scene setup
209
+ const scene = new THREE.Scene();
210
+ const camera = new THREE.PerspectiveCamera(75, {container_width} / {container_height}, 0.1, 1000);
211
+ camera.position.set(0, 20, 30);
212
+ const renderer = new THREE.WebGLRenderer({{ antialias: true }});
213
+ renderer.setSize({container_width}, {container_height});
214
+ renderer.shadowMap.enabled = true;
215
+ document.getElementById('gameContainer').appendChild(renderer.domElement);
216
+
217
+ // Lighting
218
+ const ambientLight = new THREE.AmbientLight(0xffffff, 0.2);
219
+ scene.add(ambientLight);
220
+ const sunLight = new THREE.DirectionalLight(0xffddaa, 0.8);
221
+ sunLight.castShadow = true;
222
+ sunLight.shadow.mapSize.width = 2048;
223
+ sunLight.shadow.mapSize.height = 2048;
224
+ sunLight.shadow.camera.near = 1;
225
+ sunLight.shadow.camera.far = 500;
226
+ sunLight.shadow.camera.left = -100;
227
+ sunLight.shadow.camera.right = 100;
228
+ sunLight.shadow.camera.top = 100;
229
+ sunLight.shadow.camera.bottom = -100;
230
+ scene.add(sunLight);
231
+
232
+ // Ground
233
+ const textureLoader = new THREE.TextureLoader();
234
+ const groundGeometry = new THREE.PlaneGeometry(200, 200);
235
+ const groundMaterial = new THREE.MeshStandardMaterial({{
236
+ color: 0x1a5e1a, roughness: 0.8, metalness: 0.2,
237
+ bumpMap: textureLoader.load('https://threejs.org/examples/textures/terrain/grasslight-big-nm.jpg'),
238
+ bumpScale: 0.1
239
+ }});
240
+ const ground = new THREE.Mesh(groundGeometry, groundMaterial);
241
+ ground.rotation.x = -Math.PI / 2;
242
+ ground.receiveShadow = true;
243
+ scene.add(ground);
244
+
245
+ // Building rules
246
+ const buildingColors = [0x888888, 0x666666, 0x999999, 0xaaaaaa, 0x555555, 0x334455, 0x445566, 0x223344, 0x556677, 0x667788, 0x993333, 0x884422, 0x553333, 0x772222, 0x664433];
247
+ const buildingRules = [
248
+ {{name: "Colonial", axiom: "A", rules: {{"A": "B[+F][-F]", "B": "F[-C][+C]F", "C": "D[-E][+E]", "D": "F[+F][-F]F", "E": "F[-F][+F]"}}, iterations: 2, baseHeight: 10, baseWidth: 6, baseDepth: 6, angle: Math.PI/6, probability: 0.2}},
249
+ {{name: "Victorian", axiom: "A", rules: {{"A": "B[+C][-C][/D][\\\\D]", "B": "F[+F][-F][/F][\\\\F]", "C": "F[++F][--F]", "D": "F[+\\\\F][-\\\\F]"}}, iterations: 3, baseHeight: 15, baseWidth: 5, baseDepth: 5, angle: Math.PI/5, probability: 0.15}},
250
+ {{name: "Modern", axiom: "A", rules: {{"A": "B[+B][-B]", "B": "F[/C][\\\\C]", "C": "F"}}, iterations: 2, baseHeight: 20, baseWidth: 8, baseDepth: 8, angle: Math.PI/2, probability: 0.25}},
251
+ {{name: "Skyscraper", axiom: "A", rules: {{"A": "FB[+C][-C]", "B": "FB", "C": "F[+F][-F]"}}, iterations: 4, baseHeight: 30, baseWidth: 10, baseDepth: 10, angle: Math.PI/8, probability: 0.15}},
252
+ {{name: "Simple", axiom: "F", rules: {{"F": "F[+F][-F]"}}, iterations: 1, baseHeight: 8, baseWidth: 6, baseDepth: 6, angle: Math.PI/4, probability: 0.25}}
253
+ ];
254
+
255
+ function interpretLSystem(rule, position, rotation) {{
256
+ let currentString = rule.axiom;
257
+ for (let i = 0; i < rule.iterations; i++) {{
258
+ let newString = "";
259
+ for (let j = 0; j < currentString.length; j++) {{
260
+ newString += rule.rules[currentString[j]] || currentString[j];
261
+ }}
262
+ currentString = newString;
263
+ }}
264
+
265
+ let buildingGroup = new THREE.Group();
266
+ buildingGroup.position.copy(position);
267
+ const stack = [];
268
+ let currentPosition = new THREE.Vector3(0, 0, 0);
269
+ let currentRotation = rotation || new THREE.Euler();
270
+ let scale = new THREE.Vector3(1, 1, 1);
271
+ const color = buildingColors[Math.floor(Math.random() * buildingColors.length)];
272
+ const material = new THREE.MeshStandardMaterial({{color: color, roughness: 0.7, metalness: 0.2}});
273
+
274
+ for (let i = 0; i < currentString.length; i++) {{
275
+ const char = currentString[i];
276
+ switch (char) {{
277
+ case 'F':
278
+ const width = rule.baseWidth * (0.5 + Math.random() * 0.5) * scale.x;
279
+ const height = rule.baseHeight * (0.5 + Math.random() * 0.5) * scale.y;
280
+ const depth = rule.baseDepth * (0.5 + Math.random() * 0.5) * scale.z;
281
+ const geometry = new THREE.BoxGeometry(width, height, depth);
282
+ const buildingPart = new THREE.Mesh(geometry, material);
283
+ buildingPart.position.copy(currentPosition);
284
+ buildingPart.position.y += height / 2;
285
+ buildingPart.rotation.copy(currentRotation);
286
+ buildingPart.castShadow = true;
287
+ buildingPart.receiveShadow = true;
288
+ buildingGroup.add(buildingPart);
289
+ const direction = new THREE.Vector3(0, height, 0);
290
+ direction.applyEuler(currentRotation);
291
+ currentPosition.add(direction);
292
+ break;
293
+ case '+': currentRotation.y += rule.angle; break;
294
+ case '-': currentRotation.y -= rule.angle; break;
295
+ case '/': currentRotation.x += rule.angle; break;
296
+ case '\\\\': currentRotation.x -= rule.angle; break;
297
+ case '^': currentRotation.z += rule.angle; break;
298
+ case '&': currentRotation.z -= rule.angle; break;
299
+ case '[': stack.push({{position: currentPosition.clone(), rotation: currentRotation.clone(), scale: scale.clone()}}); break;
300
+ case ']': if (stack.length > 0) {{ const state = stack.pop(); currentPosition = state.position; currentRotation = state.rotation; scale = state.scale; }} break;
301
+ case '>': scale.multiplyScalar(1.2); break;
302
+ case '<': scale.multiplyScalar(0.8); break;
303
+ }}
304
+ }}
305
+ return buildingGroup;
306
+ }}
307
+
308
+ function createCity() {{
309
+ const citySize = 5, spacing = 15;
310
+ for (let x = -citySize; x <= citySize; x++) {{
311
+ for (let z = -citySize; z <= citySize; z++) {{
312
+ if (Math.random() < 0.2) continue;
313
+ const position = new THREE.Vector3(x * spacing + (Math.random() * 2 - 1), 0, z * spacing + (Math.random() * 2 - 1));
314
+ let selectedRule, random = Math.random(), cumulativeProbability = 0;
315
+ for (const rule of buildingRules) {{
316
+ cumulativeProbability += rule.probability;
317
+ if (random <= cumulativeProbability) {{ selectedRule = rule; break; }}
318
+ }}
319
+ if (!selectedRule) selectedRule = buildingRules[0];
320
+ const building = interpretLSystem(selectedRule, position, new THREE.Euler());
321
+ scene.add(building);
322
+ buildings.push(building);
323
+ if (Math.random() > 0.7) spawnLSysCreature(building.position);
324
+ }}
325
+ }}
326
+ const roadWidth = 8, roadColor = 0x333333;
327
+ for (let x = -citySize; x <= citySize; x++) {{
328
+ const road = new THREE.Mesh(
329
+ new THREE.PlaneGeometry(roadWidth, citySize * 2 * spacing + roadWidth),
330
+ new THREE.MeshStandardMaterial({{color: roadColor, roughness: 0.9, metalness: 0.1}})
331
+ );
332
+ road.rotation.x = -Math.PI / 2;
333
+ road.position.set(x * spacing, 0.01, 0);
334
+ scene.add(road);
335
+ }}
336
+ for (let z = -citySize; z <= citySize; z++) {{
337
+ const road = new THREE.Mesh(
338
+ new THREE.PlaneGeometry(citySize * 2 * spacing + roadWidth, roadWidth),
339
+ new THREE.MeshStandardMaterial({{color: roadColor, roughness: 0.9, metalness: 0.1}})
340
+ );
341
+ road.rotation.x = -Math.PI / 2;
342
+ road.position.set(0, 0.01, z * spacing);
343
+ scene.add(road);
344
+ }}
345
+ }}
346
+
347
+ function evolveCity() {{
348
+ if (Math.random() < 0.1) {{ // 10% chance to evolve per frame
349
+ const citySize = 5, spacing = 15;
350
+ const x = (Math.random() * 2 - 1) * citySize * spacing;
351
+ const z = (Math.random() * 2 - 1) * citySize * spacing;
352
+ const position = new THREE.Vector3(x, 0, z);
353
+ let selectedRule = buildingRules[Math.floor(Math.random() * buildingRules.length)];
354
+ const building = interpretLSystem(selectedRule, position, new THREE.Euler());
355
+ scene.add(building);
356
+ buildings.push(building);
357
+ }}
358
+ }}
359
+
360
+ function spawnFood() {{
361
+ const citySize = 5, spacing = 15;
362
+ if (foodItems.length < 10) {{
363
+ const food = new THREE.Mesh(
364
+ new THREE.BoxGeometry(1, 1, 1),
365
+ new THREE.MeshStandardMaterial({{color: 0xffff00, emissive: 0xffff00, emissiveIntensity: 0.5, transparent: true, opacity: 0.8}})
366
+ );
367
+ const x = (Math.random() * 2 - 1) * citySize * spacing;
368
+ const z = (Math.random() * 2 - 1) * citySize * spacing;
369
+ food.position.set(x, 0.5, z);
370
+ foodItems.push(food);
371
+ scene.add(food);
372
+ }}
373
+ }}
374
+
375
+ function spawnLSysCreature(position) {{
376
+ const lSys = {{
377
+ axiom: "F",
378
+ rules: {{"F": "F[+F]F[-F]F"}},
379
+ angle: 25 * Math.PI / 180,
380
+ length: 2,
381
+ iterations: 2
382
+ }};
383
+ let turtleString = lSys.axiom;
384
+ for (let j = 0; j < lSys.iterations; j++) {{
385
+ turtleString = turtleString.split('').map(c => lSys.rules[c] || c).join('');
386
+ }}
387
+ const creature = new THREE.Group();
388
+ let stack = [], pos = position.clone(), dir = new THREE.Vector3(0, lSys.length, 0);
389
+ const material = new THREE.MeshStandardMaterial({{color: 0x0000ff}});
390
+
391
+ for (let char of turtleString) {{
392
+ if (char === 'F') {{
393
+ const segment = new THREE.Mesh(new THREE.CylinderGeometry(0.1, 0.1, lSys.length, 8), material);
394
+ segment.position.copy(pos).add(dir.clone().multiplyScalar(0.5));
395
+ segment.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), dir.clone().normalize());
396
+ creature.add(segment);
397
+ pos.add(dir);
398
+ }} else if (char === '+') {{
399
+ dir.applyAxisAngle(new THREE.Vector3(0, 0, 1), lSys.angle);
400
+ }} else if (char === '-') {{
401
+ dir.applyAxisAngle(new THREE.Vector3(0, 0, 1), -lSys.angle);
402
+ }} else if (char === '[') {{
403
+ stack.push({{ pos: pos.clone(), dir: dir.clone() }});
404
+ }} else if (char === ']') {{
405
+ const state = stack.pop();
406
+ pos = state.pos;
407
+ dir = state.dir;
408
+ }}
409
+ }}
410
+ creature.position.copy(position);
411
+ lSysCreatures.push(creature);
412
+ scene.add(creature);
413
+ sendQuineAgent(creature);
414
+ }}
415
+
416
+ function sendQuineAgent(sender) {{
417
+ const agent = new THREE.Mesh(
418
+ new THREE.SphereGeometry(0.3, 16, 16),
419
+ new THREE.MeshStandardMaterial({{color: 0x00ffff, emissive: 0x00ffff, emissiveIntensity: 0.5}})
420
+ );
421
+ agent.position.copy(sender.position).add(new THREE.Vector3(0, 5, 0));
422
+ agent.userData = {{
423
+ origin: sender.position.clone(),
424
+ angle: Math.random() * Math.PI * 2,
425
+ speed: 0.5 + Math.random() * 0.5,
426
+ radius: 3 + Math.random() * 2,
427
+ ttl: 5
428
+ }};
429
+ quineAgents.push(agent);
430
+ scene.add(agent);
431
+ }}
432
+
433
+ function resetSnake() {{
434
+ snake.forEach(seg => scene.remove(seg));
435
+ snake = [];
436
+ const snakeMaterial = new THREE.MeshStandardMaterial({{color: 0x00ff00}});
437
+ for (let i = 0; i < initialLength; i++) {{
438
+ const segment = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 16), snakeMaterial);
439
+ segment.position.set(-i * 1.2, 0.5, 0);
440
+ segment.castShadow = true;
441
+ snake.push(segment);
442
+ scene.add(segment);
443
+ }}
444
+ moveDir.set(1, 0, 0);
445
+ players[playerName] = {{ snake: snake, score: 0, length: initialLength }};
446
+ }}
447
+
448
+ // Controls
449
+ const keys = {{w: false, a: false, s: false, d: false}};
450
+ document.addEventListener('keydown', (event) => {{
451
+ switch (event.key.toLowerCase()) {{
452
+ case 'w': case 'arrowup': keys.w = true; break;
453
+ case 'a': case 'arrowleft': keys.a = true; break;
454
+ case 's': case 'arrowdown': keys.s = true; break;
455
+ case 'd': case 'arrowright': keys.d = true; break;
456
+ }}
457
+ }});
458
+ document.addEventListener('keyup', (event) => {{
459
+ switch (event.key.toLowerCase()) {{
460
+ case 'w': case 'arrowup': keys.w = false; break;
461
+ case 'a': case 'arrowleft': keys.a = false; break;
462
+ case 's': case 'arrowdown': keys.s = false; break;
463
+ case 'd': case 'arrowright': keys.d = false; break;
464
+ }}
465
+ }});
466
+
467
+ function updateSnake(delta) {{
468
+ moveCounter += delta;
469
+ if (moveCounter < moveInterval) return;
470
+ moveCounter = 0;
471
+
472
+ if (keys.w && moveDir.z !== 1) moveDir.set(0, 0, -1);
473
+ else if (keys.s && moveDir.z !== -1) moveDir.set(0, 0, 1);
474
+ else if (keys.a && moveDir.x !== 1) moveDir.set(-1, 0, 0);
475
+ else if (keys.d && moveDir.x !== -1) moveDir.set(1, 0, 0);
476
+
477
+ const head = snake[0];
478
+ const newHead = new THREE.Mesh(head.geometry, head.material);
479
+ newHead.position.copy(head.position).add(moveDir.clone().multiplyScalar(1));
480
+ newHead.castShadow = true;
481
+
482
+ if (Math.abs(newHead.position.x) > 75 || Math.abs(newHead.position.z) > 75) {{
483
+ resetSnake();
484
+ return;
485
+ }}
486
+
487
+ for (let i = 1; i < snake.length; i++) {{
488
+ if (newHead.position.distanceTo(snake[i].position) < 0.9) {{
489
+ resetSnake();
490
+ return;
491
+ }}
492
+ }}
493
+
494
+ for (const building of buildings) {{
495
+ building.traverse((child) => {{
496
+ if (child.isMesh) {{
497
+ const buildingBox = new THREE.Box3().setFromObject(child);
498
+ const headPos = newHead.position.clone();
499
+ if (headPos.x + 0.5 > buildingBox.min.x && headPos.x - 0.5 < buildingBox.max.x &&
500
+ headPos.z + 0.5 > buildingBox.min.z && headPos.z - 0.5 < buildingBox.max.z) {{
501
+ resetSnake();
502
+ return;
503
+ }}
504
+ }}
505
+ }});
506
+ }}
507
+
508
+ snake.unshift(newHead);
509
+ scene.add(newHead);
510
+
511
+ for (let i = foodItems.length - 1; i >= 0; i--) {{
512
+ if (newHead.position.distanceTo(foodItems[i].position) < 1) {{
513
+ scene.remove(foodItems[i]);
514
+ foodItems.splice(i, 1);
515
+ spawnFood();
516
+ if (Math.random() > 0.8) spawnLSysCreature(newHead.position.clone());
517
+ score += 2;
518
+ players[playerName].score = score;
519
+ players[playerName].length = snake.length;
520
+ updateUI();
521
+ break;
522
+ }} else {{
523
+ const tail = snake.pop();
524
+ scene.remove(tail);
525
+ }}
526
+ }}
527
+
528
+ for (let creature of lSysCreatures) {{
529
+ if (newHead.position.distanceTo(creature.position) < 2) {{
530
+ resetSnake();
531
+ return;
532
+ }}
533
+ }}
534
+
535
+ const headPos = newHead.position;
536
+ camera.position.set(headPos.x, headPos.y + 20, headPos.z + 30);
537
+ camera.lookAt(headPos);
538
+ }}
539
+
540
+ function updateQuineAgents(delta) {{
541
+ for (let i = quineAgents.length - 1; i >= 0; i--) {{
542
+ const agent = quineAgents[i];
543
+ agent.userData.ttl -= delta;
544
+ if (agent.userData.ttl <= 0) {{
545
+ scene.remove(agent);
546
+ quineAgents.splice(i, 1);
547
+ continue;
548
+ }}
549
+ agent.userData.angle += agent.userData.speed * delta;
550
+ const offsetX = Math.cos(agent.userData.angle) * agent.userData.radius;
551
+ const offsetZ = Math.sin(agent.userData.angle) * agent.userData.radius;
552
+ agent.position.set(
553
+ agent.userData.origin.x + offsetX,
554
+ agent.userData.origin.y + 5 + Math.sin(Date.now() * 0.001 * agent.userData.speed) * 0.5,
555
+ agent.userData.origin.z + offsetZ
556
+ );
557
+ }}
558
+ }}
559
+
560
+ // Sun cycle
561
+ let cycleTime = 0;
562
+ function updateLighting(delta) {{
563
+ cycleTime += delta;
564
+ const cycleDuration = 120;
565
+ const angle = (cycleTime / cycleDuration) * Math.PI * 2;
566
+ sunLight.position.set(Math.cos(angle) * 100, Math.sin(angle) * 100, Math.sin(angle) * 50);
567
+ sunLight.intensity = Math.max(0, Math.sin(angle)) * 0.8;
568
+ const dayColor = new THREE.Color(0x87CEEB);
569
+ const nightColor = new THREE.Color(0x001133);
570
+ scene.background = dayColor.clone().lerp(nightColor, Math.max(0, -Math.sin(angle)));
571
+ }}
572
+
573
+ function updateUI() {{
574
+ document.getElementById('players').textContent = `Players: ${{Object.keys(players).length}}`;
575
+ document.getElementById('score').textContent = `Score: ${{score}}`;
576
+ document.getElementById('length').textContent = `Length: ${{snake.length}}`;
577
+ document.getElementById('leaderboard').innerHTML = highScores.map(s => `<p>${{s.name}}: ${{s.score}}</p>`).join('');
578
+ }}
579
+
580
+ // WebSocket chat
581
+ ws.onmessage = function(event) {{
582
+ const [sender, message] = event.data.split('|');
583
+ const chatBox = document.getElementById('chatBox');
584
+ chatBox.innerHTML += `<p>${{sender}}: ${{message}}</p>`;
585
+ chatBox.scrollTop = chatBox.scrollHeight;
586
+ }};
587
+
588
+ ws.onopen = function() {{
589
+ console.log('Connected to WebSocket server');
590
+ }};
591
+
592
+ ws.onerror = function(error) {{
593
+ console.error('WebSocket error:', error);
594
+ }};
595
+
596
+ ws.onclose = function() {{
597
+ console.log('Disconnected from WebSocket server');
598
+ }};
599
+
600
+ // Game loop
601
+ let lastTime = performance.now();
602
+ function animate() {{
603
+ requestAnimationFrame(animate);
604
+ const currentTime = performance.now();
605
+ const delta = (currentTime - lastTime) / 1000;
606
+ lastTime = currentTime;
607
+
608
+ updateSnake(delta);
609
+ updateQuineAgents(delta);
610
+ updateLighting(delta);
611
+ evolveCity();
612
+ spawnFood();
613
+ updateUI();
614
+
615
+ renderer.render(scene, camera);
616
+ }}
617
+
618
+ // Initialize
619
+ resetSnake();
620
+ createCity();
621
+ spawnFood();
622
+ animate();
623
+ </script>
624
+ </body>
625
+ </html>
626
+ """
627
+
628
+ # Render the HTML component
629
+ components.html(html_code, width=container_width, height=container_height)
630
+
631
+ # Chat Interface
632
+ st.sidebar.title(f"Chat as {st.session_state.username}")
633
+ chat_content = asyncio.run(load_chat())
634
+ chat_container = st.sidebar.container()
635
+ with chat_container:
636
+ st.code("\n".join(chat_content), language="python")
637
+
638
+ message = st.sidebar.text_input("Message", key="chat_input")
639
+ if message and st.sidebar.button("Send 🚀"):
640
+ asyncio.run(save_chat_entry(st.session_state.username, message))
641
+
642
+ audio_bytes = audio_recorder()
643
+ if audio_bytes:
644
+ with open("temp_audio.wav", "wb") as f:
645
+ f.write(audio_bytes)
646
+ # Here you would typically transcribe the audio, but for simplicity, we'll simulate a message
647
+ message = "Voice message received"
648
+ asyncio.run(save_chat_entry(st.session_state.username, message))
649
+
650
+ # Start WebSocket Server
651
+ if not st.session_state.get('server_task'):
652
+ st.session_state.server_task = threading.Thread(target=start_websocket_server, daemon=True)
653
+ st.session_state.server_task.start()
654
+
655
+ st.sidebar.write("""
656
+ ### How to Play
657
+ - **W/A/S/D or Arrow Keys**: Move your snake
658
+ - Eat yellow cubes to grow and score
659
+ - City evolves with new buildings over time
660
+ - Chat with other players in real-time
661
+ """)