File size: 23,380 Bytes
3a99762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61368a5
3a99762
61368a5
 
3a99762
 
 
 
 
 
 
 
 
 
 
 
 
 
a03d3b9
3a99762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a03d3b9
3a99762
 
 
d5d2a63
a03d3b9
3a99762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61368a5
3a99762
 
 
 
 
 
61368a5
3a99762
 
d5d2a63
3a99762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5d2a63
3a99762
 
 
 
 
61368a5
3a99762
 
 
 
 
 
 
 
 
 
d5d2a63
3a99762
 
 
 
d5d2a63
 
 
 
61368a5
d5d2a63
 
 
 
 
 
 
 
61368a5
d5d2a63
 
 
 
 
 
61368a5
d5d2a63
 
61368a5
d5d2a63
61368a5
 
 
 
 
d5d2a63
 
 
61368a5
d5d2a63
61368a5
d5d2a63
 
 
 
 
 
 
61368a5
d5d2a63
 
 
 
61368a5
d5d2a63
 
 
 
 
 
 
 
 
 
3a99762
d5d2a63
 
 
 
 
 
 
 
61368a5
d5d2a63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a99762
d5d2a63
3a99762
 
d5d2a63
61368a5
d5d2a63
 
61368a5
d5d2a63
 
 
 
61368a5
3a99762
 
61368a5
d5d2a63
 
 
 
 
 
 
 
 
81bd88c
d5d2a63
 
 
 
 
 
 
 
3a99762
 
d5d2a63
61368a5
d5d2a63
 
 
 
61368a5
 
d5d2a63
 
 
61368a5
d5d2a63
3a99762
 
d5d2a63
 
 
 
 
 
 
 
 
 
3a99762
d5d2a63
 
 
3a99762
 
d5d2a63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a99762
d5d2a63
 
 
 
3a99762
d5d2a63
 
 
 
 
 
 
61368a5
d5d2a63
3a99762
61368a5
3a99762
 
 
 
d5d2a63
 
 
 
3a99762
d5d2a63
3a99762
d5d2a63
 
 
 
 
 
 
 
 
 
 
 
3a99762
 
d5d2a63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a99762
 
61368a5
 
 
3a99762
 
d5d2a63
 
 
 
61368a5
d5d2a63
3a99762
d5d2a63
 
 
 
 
 
 
3a99762
d5d2a63
 
 
3a99762
d5d2a63
 
 
 
 
 
 
 
 
 
 
 
 
 
3a99762
d5d2a63
 
 
 
 
 
 
 
 
 
3a99762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a03d3b9
 
 
 
 
 
 
 
3a99762
 
 
 
 
61368a5
3a99762
 
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
import streamlit as st
import streamlit.components.v1 as components
import asyncio
import websockets
import uuid
import os
import random
import time
import hashlib
from datetime import datetime
import pytz
import nest_asyncio
import edge_tts
from audio_recorder_streamlit import audio_recorder

# Patch asyncio for nesting
nest_asyncio.apply()

# Page Config
st.set_page_config(page_title="Galaxian Snake 3D Multiplayer", layout="wide")

st.title("Galaxian Snake 3D Multiplayer")
st.write("Navigate a 3D city with others, eat food, and chat in real-time!")

# Sliders for container size
max_width = min(1200, st.session_state.get('window_width', 1200))
max_height = min(1600, st.session_state.get('window_height', 1600))

col1, col2 = st.columns(2)
with col1:
    container_width = st.slider("Container Width (px)", 300, max_width, 768, step=50)
with col2:
    container_height = st.slider("Container Height (px)", 400, max_height, 1024, step=50)

# Session State Initialization
def init_session_state():
    defaults = {
        'server_running': False, 'active_connections': {},
        'chat_history': [], 'last_chat_update': 0, 'username': None,
        'tts_voice': "en-US-AriaNeural", 'audio_cache': {}
    }
    for k, v in defaults.items():
        if k not in st.session_state:
            st.session_state[k] = v

init_session_state()

# Usernames and Voices
FUN_USERNAMES = {
    "CosmicJester 🌌": "en-US-AriaNeural",
    "PixelPanda 🐼": "en-US-JennyNeural",
    "QuantumQuack πŸ¦†": "en-GB-SoniaNeural",
    "StellarSquirrel 🐿️": "en-AU-NatashaNeural",
    "GizmoGuru βš™οΈ": "en-CA-ClaraNeural",
    "NebulaNinja 🌠": "en-US-GuyNeural",
}

if not st.session_state.username:
    st.session_state.username = random.choice(list(FUN_USERNAMES.keys()))
    st.session_state.tts_voice = FUN_USERNAMES[st.session_state.username]

# Chat File
CHAT_FILE = "chat_logs/global_chat.md"
os.makedirs("chat_logs", exist_ok=True)
if not os.path.exists(CHAT_FILE):
    with open(CHAT_FILE, 'a') as f:
        f.write("# Multiplayer Snake Chat\n\nWelcome to the cosmic city! 🎀\n")

# Audio Processing
async def async_edge_tts_generate(text, voice, username):
    cache_key = f"{text[:100]}_{voice}"
    if cache_key in st.session_state['audio_cache']:
        return st.session_state['audio_cache'][cache_key]
    filename = f"audio_logs/{datetime.now().strftime('%Y%m%d_%H%M%S')}-by-{username}-{hashlib.md5(text.encode()).hexdigest()[:8]}.mp3"
    os.makedirs("audio_logs", exist_ok=True)
    communicate = edge_tts.Communicate(text, voice)
    await communicate.save(filename)
    if os.path.exists(filename) and os.path.getsize(filename) > 0:
        st.session_state['audio_cache'][cache_key] = filename
        return filename
    return None

def play_and_download_audio(file_path):
    if file_path and os.path.exists(file_path):
        with open(file_path, "rb") as f:
            audio_bytes = f.read()
        st.audio(audio_bytes, format="audio/mp3")
        b64 = base64.b64encode(audio_bytes).decode()
        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)

# WebSocket Handling
async def websocket_handler(websocket, path):
    client_id = str(uuid.uuid4())
    room_id = "snake_chat"
    if room_id not in st.session_state.active_connections:
        st.session_state.active_connections[room_id] = {}
    st.session_state.active_connections[room_id][client_id] = websocket
    username = st.session_state.username
    await broadcast_message(f"System|{username} has joined the game!", room_id)
    try:
        async for message in websocket:
            if '|' in message:
                sender, content = message.split('|', 1)
                await save_chat_entry(sender, content)
            else:
                await websocket.send("ERROR|Message format: username|content")
    except websockets.ConnectionClosed:
        await broadcast_message(f"System|{username} has left the game!", room_id)
    finally:
        if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
            del st.session_state.active_connections[room_id][client_id]

async def broadcast_message(message, room_id):
    if room_id in st.session_state.active_connections:
        disconnected = []
        for client_id, ws in st.session_state.active_connections[room_id].items():
            try:
                await ws.send(message)
            except websockets.ConnectionClosed:
                disconnected.append(client_id)
        for client_id in disconnected:
            if client_id in st.session_state.active_connections[room_id]:
                del st.session_state.active_connections[room_id][client_id]

async def start_websocket_server():
    if not st.session_state.get('server_running', False):
        server = await websockets.serve(websocket_handler, '0.0.0.0', 8765)
        st.session_state['server_running'] = True
        st.session_state['server'] = server
        await asyncio.Future()  # Run forever until cancelled

# Chat Functions
async def save_chat_entry(username, message):
    central = pytz.timezone('US/Central')
    timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
    entry = f"[{timestamp}] {username}: {message}"
    with open(CHAT_FILE, 'a') as f:
        f.write(f"{entry}\n")
    audio_file = await async_edge_tts_generate(message, FUN_USERNAMES.get(username, "en-US-AriaNeural"), username)
    if audio_file:
        play_and_download_audio(audio_file)
    await broadcast_message(f"{username}|{message}", "snake_chat")
    st.session_state.chat_history.append(entry)
    st.session_state.last_chat_update = time.time()

async def load_chat():
    with open(CHAT_FILE, 'r') as f:
        content = f.read().strip()
    return content.split('\n')

# Game HTML
html_code = f"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Galaxian Snake 3D Multiplayer</title>
    <style>
        body {{ margin: 0; overflow: hidden; font-family: Arial, sans-serif; }}
        #gameContainer {{ width: {container_width}px; height: {container_height}px; position: relative; background: #000; }}
        canvas {{ width: 100%; height: 100%; display: block; }}
        .ui-container {{
            position: absolute; top: 10px; left: 10px; color: white;
            background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 5px;
            user-select: none;
        }}
        .controls {{
            position: absolute; bottom: 10px; left: 10px; color: white;
            background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 5px;
        }}
        #chatBox {{ 
            position: absolute; bottom: 60px; left: 10px; width: 300px; height: 200px; 
            background: rgba(0, 0, 0, 0.7); color: white; padding: 10px; 
            border-radius: 5px; overflow-y: auto; 
        }}
        #debug {{ position: absolute; top: 10px; right: 10px; color: white; }}
    </style>
</head>
<body>
    <div id="gameContainer">
        <div class="ui-container">
            <h2>Galaxian Snake 3D</h2>
            <div id="players">Players: 1</div>
            <div id="score">Score: 0</div>
            <div id="length">Length: 3</div>
            <div id="leaderboard"></div>
        </div>
        <div id="chatBox"></div>
        <div class="controls">
            <p>Controls: W/A/S/D or Arrow Keys to move</p>
            <p>Eat yellow cubes to grow and score!</p>
        </div>
        <div id="debug"></div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <script>
        try {{
            console.log('Starting game initialization...');
            // Game variables
            let score = 0, players = {{}}, foodItems = [], lSysCreatures = [], quineAgents = [], buildings = [], lights = [];
            let snake = [], moveDir = new THREE.Vector3(1, 0, 0), moveCounter = 0, moveInterval = 0.05; // Faster movement
            const initialLength = 3, playerName = "{st.session_state.username}";
            const highScores = JSON.parse(localStorage.getItem('highScores')) || [];
            let ws = new WebSocket('ws://localhost:8765');
            const debug = document.getElementById('debug');

            // Scene setup
            const scene = new THREE.Scene();
            const camera = new THREE.PerspectiveCamera(75, {container_width} / {container_height}, 0.1, 1000);
            camera.position.set(0, 15, 20); // Lower, closer camera
            console.log('Camera initialized at:', camera.position);

            const renderer = new THREE.WebGLRenderer({{ antialias: true }});
            renderer.setSize({container_width}, {container_height});
            renderer.shadowMap.enabled = true;
            document.getElementById('gameContainer').appendChild(renderer.domElement);
            console.log('Renderer initialized');

            // Lighting
            const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
            scene.add(ambientLight);
            const sunLight = new THREE.DirectionalLight(0xffddaa, 1);
            sunLight.position.set(50, 50, 50);
            sunLight.castShadow = true;
            scene.add(sunLight);
            console.log('Lights added');

            // Ground
            const textureLoader = new THREE.TextureLoader();
            const groundGeometry = new THREE.PlaneGeometry(200, 200);
            const groundMaterial = new THREE.MeshStandardMaterial({{ 
                color: 0x1a5e1a,
                bumpMap: textureLoader.load('https://threejs.org/examples/textures/terrain/grasslight-big-nm.jpg'),
                bumpScale: 0.1
            }});
            const ground = new THREE.Mesh(groundGeometry, groundMaterial);
            ground.rotation.x = -Math.PI / 2;
            ground.receiveShadow = true;
            scene.add(ground);
            console.log('Ground added');

            // Building rules
            const buildingColors = [0x888888, 0x666666, 0x999999];
            const buildingRules = [
                {{name: "Simple", axiom: "F", rules: {{"F": "F[+F][-F]"}}, iterations: 1, baseHeight: 10, baseWidth: 5, baseDepth: 5, angle: Math.PI/4, probability: 1}}
            ];

            function interpretLSystem(rule, position, rotation) {{
                let currentString = rule.axiom;
                for (let i = 0; i < rule.iterations; i++) {{
                    let newString = "";
                    for (let j = 0; j < currentString.length; j++) {{
                        newString += rule.rules[currentString[j]] || currentString[j];
                    }}
                    currentString = newString;
                }}
                
                let buildingGroup = new THREE.Group();
                buildingGroup.position.copy(position);
                const stack = [];
                let currentPosition = new THREE.Vector3(0, 0, 0);
                let currentRotation = rotation || new THREE.Euler();
                let scale = new THREE.Vector3(1, 1, 1);
                const color = buildingColors[Math.floor(Math.random() * buildingColors.length)];
                const material = new THREE.MeshStandardMaterial({{color: color}});
                
                for (let i = 0; i < currentString.length; i++) {{
                    const char = currentString[i];
                    switch (char) {{
                        case 'F':
                            const width = rule.baseWidth * scale.x;
                            const height = rule.baseHeight * scale.y;
                            const depth = rule.baseDepth * scale.z;
                            const geometry = new THREE.BoxGeometry(width, height, depth);
                            const buildingPart = new THREE.Mesh(geometry, material);
                            buildingPart.position.copy(currentPosition);
                            buildingPart.position.y += height / 2;
                            buildingPart.rotation.copy(currentRotation);
                            buildingPart.castShadow = true;
                            buildingPart.receiveShadow = true;
                            buildingGroup.add(buildingPart);
                            const direction = new THREE.Vector3(0, height, 0);
                            direction.applyEuler(currentRotation);
                            currentPosition.add(direction);
                            break;
                        case '+': currentRotation.y += rule.angle; break;
                        case '-': currentRotation.y -= rule.angle; break;
                        case '[': stack.push({{position: currentPosition.clone(), rotation: currentRotation.clone(), scale: scale.clone()}}); break;
                        case ']': if (stack.length > 0) {{ const state = stack.pop(); currentPosition = state.position; currentRotation = state.rotation; scale = state.scale; }} break;
                    }}
                }}
                return buildingGroup;
            }}

            function createCity() {{
                const citySize = 3, spacing = 20; // Wider spacing
                for (let x = -citySize; x <= citySize; x++) {{
                    for (let z = -citySize; z <= citySize; z++) {{
                        if (Math.random() < 0.7) continue; // Fewer buildings
                        const position = new THREE.Vector3(x * spacing, 0, z * spacing);
                        const building = interpretLSystem(buildingRules[0], position, new THREE.Euler());
                        scene.add(building);
                        buildings.push(building);
                        console.log('Building at:', position);
                    }}
                }}
                const roadWidth = 12; // Wider roads
                for (let x = -citySize; x <= citySize; x++) {{
                    const road = new THREE.Mesh(
                        new THREE.PlaneGeometry(roadWidth, citySize * 2 * spacing + roadWidth),
                        new THREE.MeshStandardMaterial({{color: 0x333333}})
                    );
                    road.rotation.x = -Math.PI / 2;
                    road.position.set(x * spacing, 0.01, 0);
                    scene.add(road);
                }}
                for (let z = -citySize; z <= citySize; z++) {{
                    const road = new THREE.Mesh(
                        new THREE.PlaneGeometry(citySize * 2 * spacing + roadWidth, roadWidth),
                        new THREE.MeshStandardMaterial({{color: 0x333333}})
                    );
                    road.rotation.x = -Math.PI / 2;
                    road.position.set(0, 0.01, z * spacing);
                    scene.add(road);
                }}
            }}

            function spawnFood() {{
                if (foodItems.length < 10) {{
                    const food = new THREE.Mesh(
                        new THREE.BoxGeometry(1, 1, 1),
                        new THREE.MeshStandardMaterial({{color: 0xffff00}})
                    );
                    const x = (Math.random() * 60) - 30;
                    const z = (Math.random() * 60) - 30;
                    food.position.set(x, 0.5, z);
                    foodItems.push(food);
                    scene.add(food);
                    console.log('Food at:', food.position);
                }}
            }}

            function resetSnake() {{
                snake.forEach(seg => scene.remove(seg));
                snake = [];
                const snakeMaterial = new THREE.MeshStandardMaterial({{color: 0x00ff00}});
                for (let i = 0; i < initialLength; i++) {{
                    const segment = new THREE.Mesh(new THREE.SphereGeometry(0.5, 16, 16), snakeMaterial);
                    segment.position.set(-i * 1.2, 0.5, 0);
                    segment.castShadow = true;
                    snake.push(segment);
                    scene.add(segment);
                }}
                moveDir.set(1, 0, 0);
                players[playerName] = {{ snake: snake, score: 0, length: initialLength }};
                console.log('Snake reset at:', snake[0].position);
            }}

            // Controls
            const keys = {{w: false, a: false, s: false, d: false}};
            document.addEventListener('keydown', (event) => {{
                switch (event.key.toLowerCase()) {{
                    case 'w': case 'arrowup': keys.w = true; break;
                    case 'a': case 'arrowleft': keys.a = true; break;
                    case 's': case 'arrowdown': keys.s = true; break;
                    case 'd': case 'arrowright': keys.d = true; break;
                }}
            }});
            document.addEventListener('keyup', (event) => {{
                switch (event.key.toLowerCase()) {{
                    case 'w': case 'arrowup': keys.w = false; break;
                    case 'a': case 'arrowleft': keys.a = false; break;
                    case 's': case 'arrowdown': keys.s = false; break;
                    case 'd': case 'arrowright': keys.d = false; break;
                }}
            }});

            function updateSnake(delta) {{
                moveCounter += delta;
                if (moveCounter < moveInterval) return;
                moveCounter = 0;

                if (keys.w && moveDir.z !== 1) moveDir.set(0, 0, -1);
                else if (keys.s && moveDir.z !== -1) moveDir.set(0, 0, 1);
                else if (keys.a && moveDir.x !== 1) moveDir.set(-1, 0, 0);
                else if (keys.d && moveDir.x !== -1) moveDir.set(1, 0, 0);

                const head = snake[0];
                const newHead = new THREE.Mesh(head.geometry, head.material);
                newHead.position.copy(head.position).add(moveDir.clone().multiplyScalar(2)); // Faster step
                newHead.castShadow = true;

                if (Math.abs(newHead.position.x) > 100 || Math.abs(newHead.position.z) > 100) {{
                    resetSnake();
                    return;
                }}

                for (let i = 1; i < snake.length; i++) {{
                    if (newHead.position.distanceTo(snake[i].position) < 0.9) {{
                        resetSnake();
                        return;
                    }}
                }}

                for (const building of buildings) {{
                    building.traverse((child) => {{
                        if (child.isMesh) {{
                            const buildingBox = new THREE.Box3().setFromObject(child);
                            const headPos = newHead.position.clone();
                            if (headPos.x + 0.5 > buildingBox.min.x && headPos.x - 0.5 < buildingBox.max.x &&
                                headPos.z + 0.5 > buildingBox.min.z && headPos.z - 0.5 < buildingBox.max.z) {{
                                resetSnake();
                                return;
                            }}
                        }}
                    }});
                }}

                snake.unshift(newHead);
                scene.add(newHead);

                for (let i = foodItems.length - 1; i >= 0; i--) {{
                    if (newHead.position.distanceTo(foodItems[i].position) < 1) {{
                        scene.remove(foodItems[i]);
                        foodItems.splice(i, 1);
                        spawnFood();
                        score += 2;
                        players[playerName].score = score;
                        players[playerName].length = snake.length;
                        updateUI();
                        break;
                    }} else {{
                        const tail = snake.pop();
                        scene.remove(tail);
                    }}
                }}

                const headPos = newHead.position;
                camera.position.set(headPos.x, 15, headPos.z + 20); // Closer chase cam
                camera.lookAt(headPos);
            }}

            function updateUI() {{
                document.getElementById('players').textContent = `Players: ${{Object.keys(players).length}}`;
                document.getElementById('score').textContent = `Score: ${{score}}`;
                document.getElementById('length').textContent = `Length: ${{snake.length}}`;
                debug.innerHTML = `Scene: ${{scene.children.length}}<br>Buildings: ${{buildings.length}}<br>Snake: ${{snake.length}}`;
            }}

            // WebSocket chat
            ws.onmessage = function(event) {{
                const [sender, message] = event.data.split('|');
                const chatBox = document.getElementById('chatBox');
                chatBox.innerHTML += `<p>${{sender}}: ${{message}}</p>`;
                chatBox.scrollTop = chatBox.scrollHeight;
            }};

            ws.onopen = function() {{ console.log('Connected to WebSocket server'); }};
            ws.onerror = function(error) {{ console.error('WebSocket error:', error); }};
            ws.onclose = function() {{ console.log('Disconnected from WebSocket server'); }};

            // Game loop
            let lastTime = performance.now();
            function animate() {{
                requestAnimationFrame(animate);
                const currentTime = performance.now();
                const delta = (currentTime - lastTime) / 1000;
                lastTime = currentTime;

                updateSnake(delta);
                spawnFood();
                updateUI();

                renderer.render(scene, camera);
            }}

            // Initialize
            resetSnake();
            createCity();
            spawnFood();
            animate();
            console.log('Game initialized');
        }} catch (e) {{
            console.error('Error in game initialization:', e);
            document.getElementById('debug').innerHTML = 'Error: ' + e.message;
        }}
    </script>
</body>
</html>
"""

# Render the HTML component
components.html(html_code, width=container_width, height=container_height)

# Chat Interface
st.sidebar.title(f"Chat as {st.session_state.username}")
chat_content = asyncio.run(load_chat())
chat_container = st.sidebar.container()
with chat_container:
    st.code("\n".join(chat_content), language="python")

message = st.sidebar.text_input("Message", key="chat_input")
if message and st.sidebar.button("Send πŸš€"):
    asyncio.run(save_chat_entry(st.session_state.username, message))

audio_bytes = audio_recorder()
if audio_bytes:
    with open("temp_audio.wav", "wb") as f:
        f.write(audio_bytes)
    message = "Voice message received"
    asyncio.run(save_chat_entry(st.session_state.username, message))

# Start WebSocket Server in Main Event Loop
async def main_async():
    if not st.session_state.get('server_running', False):
        await start_websocket_server()

loop = asyncio.get_event_loop()
if not st.session_state.get('server_running', False):
    loop.run_until_complete(main_async())

st.sidebar.write("""
### How to Play
- **W/A/S/D or Arrow Keys**: Move your snake
- Eat yellow cubes to grow and score
- Wider roads and fewer buildings for easier movement
- Chat with other players in real-time
""")