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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, shoot buildings, pass gates, dodge enemies, and chat!")
|
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, '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 start_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 |
+
st.session_state['server'] = server
|
130 |
+
await asyncio.Future()
|
131 |
+
|
132 |
+
# Chat Functions
|
133 |
+
async def save_chat_entry(username, message):
|
134 |
+
central = pytz.timezone('US/Central')
|
135 |
+
timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
|
136 |
+
entry = f"[{timestamp}] {username}: {message}"
|
137 |
+
with open(CHAT_FILE, 'a') as f:
|
138 |
+
f.write(f"{entry}\n")
|
139 |
+
audio_file = await async_edge_tts_generate(message, FUN_USERNAMES.get(username, "en-US-AriaNeural"), username)
|
140 |
+
if audio_file:
|
141 |
+
play_and_download_audio(audio_file)
|
142 |
+
await broadcast_message(f"{username}|{message}", "snake_chat")
|
143 |
+
st.session_state.chat_history.append(entry)
|
144 |
+
st.session_state.last_chat_update = time.time()
|
145 |
+
|
146 |
+
async def load_chat():
|
147 |
+
with open(CHAT_FILE, 'r') as f:
|
148 |
+
content = f.read().strip()
|
149 |
+
return content.split('\n')
|
150 |
+
|
151 |
+
# Game HTML
|
152 |
+
html_code = f"""
|
153 |
+
<!DOCTYPE html>
|
154 |
+
<html lang="en">
|
155 |
+
<head>
|
156 |
+
<meta charset="UTF-8">
|
157 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
158 |
+
<title>Galaxian Snake 3D Multiplayer</title>
|
159 |
+
<style>
|
160 |
+
body {{ margin: 0; overflow: hidden; font-family: Arial, sans-serif; background: #000; }}
|
161 |
+
#gameContainer {{ width: {container_width}px; height: {container_height}px; position: relative; }}
|
162 |
+
canvas {{ width: 100%; height: 100%; display: block; }}
|
163 |
+
.ui-container {{
|
164 |
+
position: absolute; top: 10px; left: 10px; color: white;
|
165 |
+
background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 5px;
|
166 |
+
user-select: none;
|
167 |
+
}}
|
168 |
+
.controls {{
|
169 |
+
position: absolute; bottom: 10px; left: 10px; color: white;
|
170 |
+
background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 5px;
|
171 |
+
}}
|
172 |
+
#chatBox {{
|
173 |
+
position: absolute; bottom: 60px; left: 10px; width: 300px; height: 200px;
|
174 |
+
background: rgba(0, 0, 0, 0.7); color: white; padding: 10px;
|
175 |
+
border-radius: 5px; overflow-y: auto;
|
176 |
+
}}
|
177 |
+
#debug {{ position: absolute; top: 10px; right: 10px; color: white; }}
|
178 |
+
</style>
|
179 |
+
</head>
|
180 |
+
<body>
|
181 |
+
<div id="gameContainer">
|
182 |
+
<div class="ui-container">
|
183 |
+
<h2>Galaxian Snake 3D</h2>
|
184 |
+
<div id="players">Players: 1</div>
|
185 |
+
<div id="score">Score: 0</div>
|
186 |
+
<div id="length">Length: 1</div>
|
187 |
+
<div id="survival">Survival: 0s</div>
|
188 |
+
<div id="shield">Shield: Off</div>
|
189 |
+
</div>
|
190 |
+
<div id="chatBox"></div>
|
191 |
+
<div class="controls">
|
192 |
+
<p>Controls: W/A/S/D or Arrows to steer, Space to shoot, Shift for shield</p>
|
193 |
+
<p>Eat food, shoot buildings, pass gates, dodge enemies!</p>
|
194 |
+
</div>
|
195 |
+
<div id="debug"></div>
|
196 |
+
</div>
|
197 |
+
|
198 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
|
199 |
+
<script>
|
200 |
+
try {{
|
201 |
+
console.log('Starting game initialization...');
|
202 |
+
let score = 0, players = {{}}, foodItems = [], buildings = [], bullets = [], debris = [], gates = [], enemies = [], enemyBullets = [];
|
203 |
+
let snake, moveLeft = false, moveRight = false, moveUp = false, moveDown = false, shoot = false, shield = false;
|
204 |
+
const playerName = "{st.session_state.username}";
|
205 |
+
let ws = new WebSocket('ws://localhost:8765');
|
206 |
+
const debug = document.getElementById('debug');
|
207 |
+
let survivalTime = 0, lastCollisionTime = performance.now(), shieldTimer = 0;
|
208 |
+
|
209 |
+
// Scene setup
|
210 |
+
const scene = new THREE.Scene();
|
211 |
+
const camera = new THREE.PerspectiveCamera(75, {container_width} / {container_height}, 0.1, 1000);
|
212 |
+
camera.position.set(0, 15, 20);
|
213 |
+
console.log('Camera initialized at:', camera.position);
|
214 |
+
|
215 |
+
const renderer = new THREE.WebGLRenderer({{ antialias: true }});
|
216 |
+
renderer.setSize({container_width}, {container_height});
|
217 |
+
renderer.shadowMap.enabled = true;
|
218 |
+
document.getElementById('gameContainer').appendChild(renderer.domElement);
|
219 |
+
console.log('Renderer initialized');
|
220 |
+
|
221 |
+
// Lighting
|
222 |
+
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
|
223 |
+
scene.add(ambientLight);
|
224 |
+
const sunLight = new THREE.DirectionalLight(0xffddaa, 1);
|
225 |
+
sunLight.position.set(50, 50, 50);
|
226 |
+
sunLight.castShadow = true;
|
227 |
+
scene.add(sunLight);
|
228 |
+
console.log('Lights added');
|
229 |
+
|
230 |
+
// Ground
|
231 |
+
const textureLoader = new THREE.TextureLoader();
|
232 |
+
const groundGeometry = new THREE.PlaneGeometry(200, 1000);
|
233 |
+
const groundMaterial = new THREE.MeshStandardMaterial({{
|
234 |
+
color: 0x1a5e1a,
|
235 |
+
bumpMap: textureLoader.load('https://threejs.org/examples/textures/terrain/grasslight-big-nm.jpg'),
|
236 |
+
bumpScale: 0.1
|
237 |
+
}});
|
238 |
+
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
|
239 |
+
ground.rotation.x = -Math.PI / 2;
|
240 |
+
ground.receiveShadow = true;
|
241 |
+
ground.position.z = -500;
|
242 |
+
scene.add(ground);
|
243 |
+
console.log('Ground added');
|
244 |
+
|
245 |
+
// Player (Snake Head)
|
246 |
+
const snakeGeometry = new THREE.BoxGeometry(1, 1, 1);
|
247 |
+
const snakeMaterial = new THREE.MeshPhongMaterial({{ color: 0x00ff00 }});
|
248 |
+
snake = new THREE.Mesh(snakeGeometry, snakeMaterial);
|
249 |
+
snake.position.set(0, 0.5, 0);
|
250 |
+
snake.castShadow = true;
|
251 |
+
scene.add(snake);
|
252 |
+
players[playerName] = {{ snake: snake, score: 0, length: 1 }};
|
253 |
+
console.log('Snake initialized at:', snake.position);
|
254 |
+
|
255 |
+
// Building rules
|
256 |
+
const buildingColors = [0x888888, 0x666666, 0x999999];
|
257 |
+
const buildingRules = [
|
258 |
+
{{name: "Simple", axiom: "F", rules: {{"F": "F[+F][-F]"}}, iterations: 1, baseHeight: 10, baseWidth: 5, baseDepth: 5, angle: Math.PI/4, probability: 1}}
|
259 |
+
];
|
260 |
+
|
261 |
+
function interpretLSystem(rule, position, rotation) {{
|
262 |
+
let currentString = rule.axiom;
|
263 |
+
for (let i = 0; i < rule.iterations; i++) {{
|
264 |
+
let newString = "";
|
265 |
+
for (let j = 0; j < currentString.length; j++) {{
|
266 |
+
newString += rule.rules[currentString[j]] || currentString[j];
|
267 |
+
}}
|
268 |
+
currentString = newString;
|
269 |
+
}}
|
270 |
+
|
271 |
+
let buildingGroup = new THREE.Group();
|
272 |
+
buildingGroup.position.copy(position);
|
273 |
+
const stack = [];
|
274 |
+
let currentPosition = new THREE.Vector3(0, 0, 0);
|
275 |
+
let currentRotation = rotation || new THREE.Euler();
|
276 |
+
let scale = new THREE.Vector3(1, 1, 1);
|
277 |
+
const color = buildingColors[Math.floor(Math.random() * buildingColors.length)];
|
278 |
+
const material = new THREE.MeshStandardMaterial({{color: color}});
|
279 |
+
|
280 |
+
for (let i = 0; i < currentString.length; i++) {{
|
281 |
+
const char = currentString[i];
|
282 |
+
switch (char) {{
|
283 |
+
case 'F':
|
284 |
+
const width = rule.baseWidth * scale.x;
|
285 |
+
const height = rule.baseHeight * scale.y;
|
286 |
+
const depth = rule.baseDepth * scale.z;
|
287 |
+
const geometry = new THREE.BoxGeometry(width, height, depth);
|
288 |
+
const buildingPart = new THREE.Mesh(geometry, material);
|
289 |
+
buildingPart.position.copy(currentPosition);
|
290 |
+
buildingPart.position.y += height / 2;
|
291 |
+
buildingPart.rotation.copy(currentRotation);
|
292 |
+
buildingPart.castShadow = true;
|
293 |
+
buildingPart.receiveShadow = true;
|
294 |
+
buildingGroup.add(buildingPart);
|
295 |
+
const direction = new THREE.Vector3(0, height, 0);
|
296 |
+
direction.applyEuler(currentRotation);
|
297 |
+
currentPosition.add(direction);
|
298 |
+
break;
|
299 |
+
case '+': currentRotation.y += rule.angle; break;
|
300 |
+
case '-': currentRotation.y -= rule.angle; break;
|
301 |
+
case '[': stack.push({{position: currentPosition.clone(), rotation: currentRotation.clone(), scale: scale.clone()}}); break;
|
302 |
+
case ']': if (stack.length > 0) {{ const state = stack.pop(); currentPosition = state.position; currentRotation = state.rotation; scale = state.scale; }} break;
|
303 |
+
}}
|
304 |
+
}}
|
305 |
+
return buildingGroup;
|
306 |
+
}}
|
307 |
+
|
308 |
+
function spawnBuildings() {{
|
309 |
+
const cityWidth = 40, cityDepth = -1000;
|
310 |
+
for (let i = buildings.length; i < 20; i++) {{
|
311 |
+
const position = new THREE.Vector3(
|
312 |
+
Math.random() * cityWidth - cityWidth / 2,
|
313 |
+
0,
|
314 |
+
cityDepth + Math.random() * 1000
|
315 |
+
);
|
316 |
+
const building = interpretLSystem(buildingRules[0], position, new THREE.Euler());
|
317 |
+
buildings.push(building);
|
318 |
+
scene.add(building);
|
319 |
+
console.log('Building at:', position);
|
320 |
+
}}
|
321 |
+
}}
|
322 |
+
|
323 |
+
function spawnFood() {{
|
324 |
+
if (foodItems.length < 10) {{
|
325 |
+
const food = new THREE.Mesh(
|
326 |
+
new THREE.BoxGeometry(1, 1, 1),
|
327 |
+
new THREE.MeshStandardMaterial({{color: 0xffff00}})
|
328 |
+
);
|
329 |
+
food.position.set(
|
330 |
+
Math.random() * 40 - 20,
|
331 |
+
Math.random() * 10,
|
332 |
+
-1000
|
333 |
+
);
|
334 |
+
foodItems.push(food);
|
335 |
+
scene.add(food);
|
336 |
+
console.log('Food at:', food.position);
|
337 |
+
}}
|
338 |
+
}}
|
339 |
+
|
340 |
+
function spawnGates() {{
|
341 |
+
if (gates.length < 5) {{
|
342 |
+
const gate = new THREE.Group();
|
343 |
+
const postGeometry = new THREE.CylinderGeometry(0.5, 0.5, 10, 8);
|
344 |
+
const postMaterial = new THREE.MeshPhongMaterial({{ color: 0xaaaaaa }});
|
345 |
+
const leftPost = new THREE.Mesh(postGeometry, postMaterial);
|
346 |
+
leftPost.position.set(-5, 5, 0);
|
347 |
+
const rightPost = new THREE.Mesh(postGeometry, postMaterial);
|
348 |
+
rightPost.position.set(5, 5, 0);
|
349 |
+
const fieldGeometry = new THREE.PlaneGeometry(10, 10);
|
350 |
+
const fieldMaterial = new THREE.MeshBasicMaterial({{ color: 0x00ffff, transparent: true, opacity: 0.5, side: THREE.DoubleSide }});
|
351 |
+
const field = new THREE.Mesh(fieldGeometry, fieldMaterial);
|
352 |
+
field.position.set(0, 5, 0);
|
353 |
+
gate.add(leftPost);
|
354 |
+
gate.add(rightPost);
|
355 |
+
gate.add(field);
|
356 |
+
gate.position.set(Math.random() * 40 - 20, 0, -1000 + Math.random() * 1000);
|
357 |
+
gates.push(gate);
|
358 |
+
scene.add(gate);
|
359 |
+
console.log('Gate at:', gate.position);
|
360 |
+
}}
|
361 |
+
}}
|
362 |
+
|
363 |
+
function spawnEnemyCluster() {{
|
364 |
+
const clusterCenter = new THREE.Vector3(
|
365 |
+
Math.random() * 40 - 20,
|
366 |
+
Math.random() * 10 + 5,
|
367 |
+
-1000
|
368 |
+
);
|
369 |
+
const enemyGeometry = new THREE.BoxGeometry(0.8, 0.8, 0.8);
|
370 |
+
const enemyMaterial = new THREE.MeshPhongMaterial({{ color: 0xff0000 }});
|
371 |
+
const pattern = [[-2, 1], [0, 1], [2, 1], [-1, 2], [1, 2]]; // Galaxian V-shape
|
372 |
+
pattern.forEach(pos => {{
|
373 |
+
const enemy = new THREE.Mesh(enemyGeometry, enemyMaterial);
|
374 |
+
enemy.position.set(
|
375 |
+
clusterCenter.x + pos[0],
|
376 |
+
clusterCenter.y + pos[1],
|
377 |
+
clusterCenter.z
|
378 |
+
);
|
379 |
+
enemy.shootTimer = Math.random();
|
380 |
+
enemies.push(enemy);
|
381 |
+
scene.add(enemy);
|
382 |
+
}});
|
383 |
+
console.log('Enemy cluster at:', clusterCenter);
|
384 |
+
}}
|
385 |
+
|
386 |
+
function shootBullet() {{
|
387 |
+
const bulletGeometry = new THREE.SphereGeometry(0.3, 8, 8);
|
388 |
+
const bulletMaterial = new THREE.MeshPhongMaterial({{ color: 0xff0000 }});
|
389 |
+
const bullet = new THREE.Mesh(bulletGeometry, bulletMaterial);
|
390 |
+
bullet.position.copy(snake.position);
|
391 |
+
bullet.velocity = new THREE.Vector3(0, 0, -20);
|
392 |
+
bullet.timer = 5;
|
393 |
+
bullets.push(bullet);
|
394 |
+
scene.add(bullet);
|
395 |
+
}}
|
396 |
+
|
397 |
+
function shootEnemyBullet(enemy) {{
|
398 |
+
const bulletGeometry = new THREE.SphereGeometry(0.3, 8, 8);
|
399 |
+
const bulletMaterial = new THREE.MeshPhongMaterial({{ color: 0x00ff00 }});
|
400 |
+
const bullet = new THREE.Mesh(bulletGeometry, bulletMaterial);
|
401 |
+
bullet.position.copy(enemy.position);
|
402 |
+
const direction = snake.position.clone().sub(enemy.position).normalize();
|
403 |
+
bullet.velocity = direction.multiplyScalar(15);
|
404 |
+
bullet.timer = 5;
|
405 |
+
enemyBullets.push(bullet);
|
406 |
+
scene.add(bullet);
|
407 |
+
}}
|
408 |
+
|
409 |
+
function destroyBuilding(building, index) {{
|
410 |
+
building.children.forEach(child => {{
|
411 |
+
const debrisPiece = new THREE.Mesh(child.geometry, child.material);
|
412 |
+
debrisPiece.position.copy(child.getWorldPosition(new THREE.Vector3()));
|
413 |
+
debrisPiece.velocity = new THREE.Vector3(
|
414 |
+
Math.random() - 0.5,
|
415 |
+
Math.random() * 2,
|
416 |
+
Math.random() - 0.5
|
417 |
+
).multiplyScalar(5);
|
418 |
+
debrisPiece.timer = 3;
|
419 |
+
debris.push(debrisPiece);
|
420 |
+
scene.add(debrisPiece);
|
421 |
+
}});
|
422 |
+
scene.remove(building);
|
423 |
+
buildings.splice(index, 1);
|
424 |
+
score += 100;
|
425 |
+
spawnBuildings();
|
426 |
+
}}
|
427 |
+
|
428 |
+
// Controls
|
429 |
+
document.addEventListener('keydown', (event) => {{
|
430 |
+
switch (event.code) {{
|
431 |
+
case 'ArrowLeft': case 'KeyA': moveLeft = true; break;
|
432 |
+
case 'ArrowRight': case 'KeyD': moveRight = true; break;
|
433 |
+
case 'ArrowUp': case 'KeyW': moveUp = true; break;
|
434 |
+
case 'ArrowDown': case 'KeyS': moveDown = true; break;
|
435 |
+
case 'Space': shoot = true; break;
|
436 |
+
case 'ShiftLeft': case 'ShiftRight': shield = true; shieldTimer = 4; break;
|
437 |
+
}}
|
438 |
+
}});
|
439 |
+
document.addEventListener('keyup', (event) => {{
|
440 |
+
switch (event.code) {{
|
441 |
+
case 'ArrowLeft': case 'KeyA': moveLeft = false; break;
|
442 |
+
case 'ArrowRight': case 'KeyD': moveRight = false; break;
|
443 |
+
case 'ArrowUp': case 'KeyW': moveUp = false; break;
|
444 |
+
case 'ArrowDown': case 'KeyS': moveDown = false; break;
|
445 |
+
case 'Space': shoot = false; break;
|
446 |
+
}}
|
447 |
+
}});
|
448 |
+
|
449 |
+
function updatePlayer(delta) {{
|
450 |
+
const speed = 10;
|
451 |
+
if (moveLeft && snake.position.x > -20) snake.position.x -= speed * delta;
|
452 |
+
if (moveRight && snake.position.x < 20) snake.position.x += speed * delta;
|
453 |
+
if (moveUp && snake.position.y < 15) snake.position.y += speed * delta;
|
454 |
+
if (moveDown && snake.position.y > 0.5) snake.position.y -= speed * delta;
|
455 |
+
|
456 |
+
if (shoot && !bullets.some(b => b.timer > 4.8)) shootBullet();
|
457 |
+
if (shieldTimer > 0) {{
|
458 |
+
shieldTimer -= delta;
|
459 |
+
snake.material.color.setHex(0x0000ff); // Blue when shielded
|
460 |
+
}} else {{
|
461 |
+
snake.material.color.setHex(0x00ff00); // Green when not shielded
|
462 |
+
}}
|
463 |
+
|
464 |
+
const forwardSpeed = 20;
|
465 |
+
buildings.forEach((building, i) => {{
|
466 |
+
building.position.z += forwardSpeed * delta;
|
467 |
+
if (building.position.z > 20) {{
|
468 |
+
building.position.z = -1000;
|
469 |
+
building.position.x = Math.random() * 40 - 20;
|
470 |
+
}}
|
471 |
+
if (snake.position.distanceTo(building.position) < 5) {{
|
472 |
+
snake.position.set(0, 0.5, 0);
|
473 |
+
lastCollisionTime = performance.now();
|
474 |
+
}}
|
475 |
+
}});
|
476 |
+
foodItems.forEach((food, i) => {{
|
477 |
+
food.position.z += forwardSpeed * delta;
|
478 |
+
if (food.position.z > 20) {{
|
479 |
+
scene.remove(food);
|
480 |
+
foodItems.splice(i, 1);
|
481 |
+
spawnFood();
|
482 |
+
}}
|
483 |
+
if (snake.position.distanceTo(food.position) < 1) {{
|
484 |
+
scene.remove(food);
|
485 |
+
foodItems.splice(i, 1);
|
486 |
+
score += 10;
|
487 |
+
players[playerName].length += 1;
|
488 |
+
spawnFood();
|
489 |
+
}}
|
490 |
+
}});
|
491 |
+
gates.forEach((gate, i) => {{
|
492 |
+
gate.position.z += forwardSpeed * delta;
|
493 |
+
if (gate.position.z > 20) {{
|
494 |
+
scene.remove(gate);
|
495 |
+
gates.splice(i, 1);
|
496 |
+
spawnGates();
|
497 |
+
}}
|
498 |
+
const fieldPos = gate.children[2].getWorldPosition(new THREE.Vector3());
|
499 |
+
if (snake.position.distanceTo(fieldPos) < 5) {{
|
500 |
+
score += 100;
|
501 |
+
scene.remove(gate);
|
502 |
+
gates.splice(i, 1);
|
503 |
+
spawnGates();
|
504 |
+
}}
|
505 |
+
}});
|
506 |
+
|
507 |
+
camera.position.set(snake.position.x, snake.position.y + 15, snake.position.z + 20);
|
508 |
+
camera.lookAt(snake.position);
|
509 |
+
}}
|
510 |
+
|
511 |
+
function updateBullets(delta) {{
|
512 |
+
for (let i = bullets.length - 1; i >= 0; i--) {{
|
513 |
+
const bullet = bullets[i];
|
514 |
+
bullet.position.add(bullet.velocity.clone().multiplyScalar(delta));
|
515 |
+
bullet.timer -= delta;
|
516 |
+
|
517 |
+
if (bullet.timer <= 0) {{
|
518 |
+
scene.remove(bullet);
|
519 |
+
bullets.splice(i, 1);
|
520 |
+
continue;
|
521 |
+
}}
|
522 |
+
|
523 |
+
for (let j = buildings.length - 1; j >= 0; j--) {{
|
524 |
+
if (bullet.position.distanceTo(buildings[j].position) < 5) {{
|
525 |
+
destroyBuilding(buildings[j], j);
|
526 |
+
scene.remove(bullet);
|
527 |
+
bullets.splice(i, 1);
|
528 |
+
break;
|
529 |
+
}}
|
530 |
+
}}
|
531 |
+
}}
|
532 |
+
}}
|
533 |
+
|
534 |
+
function updateDebris(delta) {{
|
535 |
+
for (let i = debris.length - 1; i >= 0; i--) {{
|
536 |
+
const piece = debris[i];
|
537 |
+
piece.position.add(piece.velocity.clone().multiplyScalar(delta));
|
538 |
+
piece.velocity.y -= 9.8 * delta;
|
539 |
+
piece.timer -= delta;
|
540 |
+
|
541 |
+
if (piece.position.y <= 0) {{
|
542 |
+
piece.velocity.y *= -0.7;
|
543 |
+
piece.position.y = 0;
|
544 |
+
}}
|
545 |
+
if (piece.timer <= 0) {{
|
546 |
+
scene.remove(piece);
|
547 |
+
debris.splice(i, 1);
|
548 |
+
}}
|
549 |
+
}}
|
550 |
+
}}
|
551 |
+
|
552 |
+
function updateEnemies(delta) {{
|
553 |
+
enemies.forEach((enemy, i) => {{
|
554 |
+
enemy.position.z += 10 * delta; // Slower than world
|
555 |
+
enemy.shootTimer -= delta;
|
556 |
+
if (enemy.shootTimer <= 0) {{
|
557 |
+
shootEnemyBullet(enemy);
|
558 |
+
enemy.shootTimer = 1; // Once per second
|
559 |
+
}}
|
560 |
+
if (enemy.position.z > 20) {{
|
561 |
+
scene.remove(enemy);
|
562 |
+
enemies.splice(i, 1);
|
563 |
+
}}
|
564 |
+
}});
|
565 |
+
if (enemies.length < 10) spawnEnemyCluster();
|
566 |
+
}}
|
567 |
+
|
568 |
+
function updateEnemyBullets(delta) {{
|
569 |
+
for (let i = enemyBullets.length - 1; i >= 0; i--) {{
|
570 |
+
const bullet = enemyBullets[i];
|
571 |
+
const direction = snake.position.clone().sub(bullet.position).normalize();
|
572 |
+
bullet.velocity.lerp(direction.multiplyScalar(15), delta * 2); // Heat-seeking
|
573 |
+
bullet.position.add(bullet.velocity.clone().multiplyScalar(delta));
|
574 |
+
bullet.timer -= delta;
|
575 |
+
|
576 |
+
if (bullet.timer <= 0 || bullet.position.z > 20) {{
|
577 |
+
scene.remove(bullet);
|
578 |
+
enemyBullets.splice(i, 1);
|
579 |
+
continue;
|
580 |
+
}}
|
581 |
+
|
582 |
+
if (bullet.position.distanceTo(snake.position) < 1 && shieldTimer <= 0) {{
|
583 |
+
snake.position.set(0, 0.5, 0);
|
584 |
+
lastCollisionTime = performance.now();
|
585 |
+
scene.remove(bullet);
|
586 |
+
enemyBullets.splice(i, 1);
|
587 |
+
}} else if (bullet.position.distanceTo(snake.position) < 1 && shieldTimer > 0) {{
|
588 |
+
scene.remove(bullet);
|
589 |
+
enemyBullets.splice(i, 1);
|
590 |
+
}}
|
591 |
+
}}
|
592 |
+
}}
|
593 |
+
|
594 |
+
function updateUI() {{
|
595 |
+
survivalTime = (performance.now() - lastCollisionTime) / 1000;
|
596 |
+
score += Math.floor(survivalTime / 10);
|
597 |
+
document.getElementById('players').textContent = `Players: ${{Object.keys(players).length}}`;
|
598 |
+
document.getElementById('score').textContent = `Score: ${{score}}`;
|
599 |
+
document.getElementById('length').textContent = `Length: ${{players[playerName].length}}`;
|
600 |
+
document.getElementById('survival').textContent = `Survival: ${{survivalTime.toFixed(1)}}s`;
|
601 |
+
document.getElementById('shield').textContent = `Shield: ${{shieldTimer > 0 ? 'On' : 'Off'}}`;
|
602 |
+
debug.innerHTML = `Scene: ${{scene.children.length}}<br>Buildings: ${{buildings.length}}<br>Food: ${{foodItems.length}}<br>Bullets: ${{bullets.length}}<br>Gates: ${{gates.length}}<br>Enemies: ${{enemies.length}}`;
|
603 |
+
}}
|
604 |
+
|
605 |
+
// WebSocket chat
|
606 |
+
ws.onmessage = function(event) {{
|
607 |
+
const [sender, message] = event.data.split('|');
|
608 |
+
const chatBox = document.getElementById('chatBox');
|
609 |
+
chatBox.innerHTML += `<p>${{sender}}: ${{message}}</p>`;
|
610 |
+
chatBox.scrollTop = chatBox.scrollHeight;
|
611 |
+
}};
|
612 |
+
|
613 |
+
ws.onopen = function() {{ console.log('Connected to WebSocket server'); }};
|
614 |
+
ws.onerror = function(error) {{ console.error('WebSocket error:', error); }};
|
615 |
+
ws.onclose = function() {{ console.log('Disconnected from WebSocket server'); }};
|
616 |
+
|
617 |
+
// Game loop
|
618 |
+
let lastTime = performance.now();
|
619 |
+
function animate() {{
|
620 |
+
requestAnimationFrame(animate);
|
621 |
+
const currentTime = performance.now();
|
622 |
+
const delta = (currentTime - lastTime) / 1000;
|
623 |
+
lastTime = currentTime;
|
624 |
+
|
625 |
+
updatePlayer(delta);
|
626 |
+
updateBullets(delta);
|
627 |
+
updateDebris(delta);
|
628 |
+
updateEnemies(delta);
|
629 |
+
updateEnemyBullets(delta);
|
630 |
+
spawnFood();
|
631 |
+
spawnGates();
|
632 |
+
updateUI();
|
633 |
+
|
634 |
+
renderer.render(scene, camera);
|
635 |
+
}}
|
636 |
+
|
637 |
+
// Initialize
|
638 |
+
spawnBuildings();
|
639 |
+
spawnFood();
|
640 |
+
spawnGates();
|
641 |
+
spawnEnemyCluster();
|
642 |
+
animate();
|
643 |
+
console.log('Game initialized');
|
644 |
+
}} catch (e) {{
|
645 |
+
console.error('Error in game initialization:', e);
|
646 |
+
document.getElementById('debug').innerHTML = 'Error: ' + e.message;
|
647 |
+
}}
|
648 |
+
</script>
|
649 |
+
</body>
|
650 |
+
</html>
|
651 |
+
"""
|
652 |
+
|
653 |
+
# Render the HTML component
|
654 |
+
components.html(html_code, width=container_width, height=container_height)
|
655 |
+
|
656 |
+
# Chat Interface
|
657 |
+
st.sidebar.title(f"Chat as {st.session_state.username}")
|
658 |
+
chat_content = asyncio.run(load_chat())
|
659 |
+
chat_container = st.sidebar.container()
|
660 |
+
with chat_container:
|
661 |
+
st.code("\n".join(chat_content), language="python")
|
662 |
+
|
663 |
+
message = st.sidebar.text_input("Message", key="chat_input")
|
664 |
+
if message and st.sidebar.button("Send 🚀"):
|
665 |
+
asyncio.run(save_chat_entry(st.session_state.username, message))
|
666 |
+
|
667 |
+
audio_bytes = audio_recorder()
|
668 |
+
if audio_bytes:
|
669 |
+
with open("temp_audio.wav", "wb") as f:
|
670 |
+
f.write(audio_bytes)
|
671 |
+
message = "Voice message received"
|
672 |
+
asyncio.run(save_chat_entry(st.session_state.username, message))
|
673 |
+
|
674 |
+
# Start WebSocket Server in Main Event Loop
|
675 |
+
async def main_async():
|
676 |
+
if not st.session_state.get('server_running', False):
|
677 |
+
await start_websocket_server()
|
678 |
+
|
679 |
+
loop = asyncio.get_event_loop()
|
680 |
+
if not st.session_state.get('server_running', False):
|
681 |
+
loop.run_until_complete(main_async())
|
682 |
+
|
683 |
+
st.sidebar.write("""
|
684 |
+
### How to Play
|
685 |
+
- **W/A/S/D or Arrow Keys**: Steer the snake (up/down/left/right)
|
686 |
+
- **Space**: Shoot bullets to destroy buildings
|
687 |
+
- **Shift**: Activate 4s shield to block enemy bullets
|
688 |
+
- Eat yellow cubes for 10 points
|
689 |
+
- Destroy buildings for 100 points each
|
690 |
+
- Pass through gates for 100 points
|
691 |
+
- Survive longer for bonus points (1 per 10s)
|
692 |
+
- Dodge heat-seeking enemy bullets
|
693 |
+
- Chat with other players in real-time
|
694 |
+
""")
|