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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// server.js
|
| 2 |
+
import express from 'express';
|
| 3 |
+
import cors from 'cors';
|
| 4 |
+
import { WebSocketServer, WebSocket } from 'ws';
|
| 5 |
+
import { v4 as uuidv4 } from 'uuid';
|
| 6 |
+
// Make sure this points to the compiled mechanics.js file in your build output,
|
| 7 |
+
// or the JS version of your mechanics file.
|
| 8 |
+
import { resolveCombat, getDerivedStats, breedOffspring, INITIAL_STATE } from './src/lib/mechanics.js';
|
| 9 |
+
|
| 10 |
+
const app = express();
|
| 11 |
+
// Hugging Face Spaces and other cloud PaaS use process.env.PORT (HF uses 7860)
|
| 12 |
+
const PORT = process.env.PORT || 3000;
|
| 13 |
+
|
| 14 |
+
// Enable CORS so your separate frontend can communicate
|
| 15 |
+
app.use(cors({
|
| 16 |
+
origin: '*', // Set to your specific frontend URL in production for security
|
| 17 |
+
}));
|
| 18 |
+
|
| 19 |
+
const rooms = {};
|
| 20 |
+
const roomEmptySince = new Map();
|
| 21 |
+
const roomChatLogs = new Map();
|
| 22 |
+
const CHAT_HISTORY_LIMIT = 50;
|
| 23 |
+
|
| 24 |
+
// ─── BOT TEMPLATES ───────────────────────────────────────────────────────────────
|
| 25 |
+
const BOT_TEMPLATES = [
|
| 26 |
+
{ // The Bruiser
|
| 27 |
+
compositions: { ANIMALIA: 100, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
|
| 28 |
+
attributes: { WATER_RETENTION: 2, INSULATION: 0, MUSCLE_DENSITY: 8, BONE_DENSITY: 5, FAT_RESERVES: 2, METABOLIC_RATE: 2, NEURAL_COMPLEXITY: 2, THERMAL_REGULATION: 0, BUOYANCY: 0, CAMOUFLAGE: 0, REGENERATION: 0, TOXIN_RESISTANCE: 0 },
|
| 29 |
+
features: ['CRUSHING_MANDIBLES'], socialType: 'SOLITARY'
|
| 30 |
+
},
|
| 31 |
+
{ // The Toxic Jelly
|
| 32 |
+
compositions: { ANIMALIA: 40, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 60, MYCELIUM: 0, MINERALIS: 0 },
|
| 33 |
+
attributes: { WATER_RETENTION: 0, INSULATION: 0, MUSCLE_DENSITY: 2, BONE_DENSITY: 0, FAT_RESERVES: 4, METABOLIC_RATE: 2, NEURAL_COMPLEXITY: 3, THERMAL_REGULATION: 0, BUOYANCY: 5, CAMOUFLAGE: 0, REGENERATION: 0, TOXIN_RESISTANCE: 8 },
|
| 34 |
+
features: ['TOXIN_GLANDS', 'GELATINOUS_BODY'], socialType: 'SOLITARY'
|
| 35 |
+
},
|
| 36 |
+
{ // The Sprinter
|
| 37 |
+
compositions: { ANIMALIA: 100, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
|
| 38 |
+
attributes: { WATER_RETENTION: 2, INSULATION: 0, MUSCLE_DENSITY: 4, BONE_DENSITY: 1, FAT_RESERVES: 2, METABOLIC_RATE: 8, NEURAL_COMPLEXITY: 4, THERMAL_REGULATION: 2, BUOYANCY: 0, CAMOUFLAGE: 0, REGENERATION: 0, TOXIN_RESISTANCE: 0 },
|
| 39 |
+
features: ['SLASHING_BLADES'], socialType: 'PACK'
|
| 40 |
+
},
|
| 41 |
+
{ // The Desert Stalker
|
| 42 |
+
compositions: { ANIMALIA: 50, CHITINARIA: 50, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
|
| 43 |
+
attributes: { WATER_RETENTION: 6, INSULATION: 0, MUSCLE_DENSITY: 4, BONE_DENSITY: 4, FAT_RESERVES: 2, METABOLIC_RATE: 3, NEURAL_COMPLEXITY: 4, THERMAL_REGULATION: 4, BUOYANCY: 0, CAMOUFLAGE: 5, REGENERATION: 0, TOXIN_RESISTANCE: 2 },
|
| 44 |
+
features: ['SCORPION_TAIL'], socialType: 'SOLITARY'
|
| 45 |
+
}
|
| 46 |
+
];
|
| 47 |
+
|
| 48 |
+
const BOT_NAMES = ['Alpha', 'Beta', 'Gamma', 'Delta', 'Omega', 'Zeta', 'Sigma', 'Prime'];
|
| 49 |
+
|
| 50 |
+
function populateBots(room, guaranteeBot = false) {
|
| 51 |
+
if (!guaranteeBot && Math.random() > 0.5) return;
|
| 52 |
+
const numBots = Math.floor(Math.random() * 2) + 1;
|
| 53 |
+
for (let i = 0; i < numBots; i++) {
|
| 54 |
+
const botId = `bot-${uuidv4()}`;
|
| 55 |
+
const template = BOT_TEMPLATES[Math.floor(Math.random() * BOT_TEMPLATES.length)];
|
| 56 |
+
const randomName = `Bot ${BOT_NAMES[Math.floor(Math.random() * BOT_NAMES.length)]}`;
|
| 57 |
+
room.players[botId] = {
|
| 58 |
+
id: botId, name: randomName, roomId: room.id,
|
| 59 |
+
state: JSON.parse(JSON.stringify(template)), ready: true,
|
| 60 |
+
score: 0, joinedAt: Date.now(), hasCollectedGift: true, groupId: null
|
| 61 |
+
};
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
function randomBiome() {
|
| 66 |
+
return ['DESERT', 'RAINFOREST', 'UNDERWATER'][Math.floor(Math.random() * 3)];
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
function makeRoom(forceBots = false) {
|
| 70 |
+
roomCounter++;
|
| 71 |
+
const id = `room-${roomCounter}`;
|
| 72 |
+
const room = { id, status: 'LOBBY', players: {}, startTime: 0, biome: randomBiome(), groups: {}, hasRealPlayers: false };
|
| 73 |
+
populateBots(room, forceBots);
|
| 74 |
+
return room;
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
const MIN_ROOMS = 5;
|
| 78 |
+
const ROOM_SAFETY_CAP = 200;
|
| 79 |
+
const ROOM_EMPTY_GRACE_MS = 15000;
|
| 80 |
+
const ARENA_SIZE = 800;
|
| 81 |
+
const SAFE_ZONE_START = 400;
|
| 82 |
+
const FOOD_COUNT = 15;
|
| 83 |
+
const HUNGER_THRESHOLD = 100;
|
| 84 |
+
const MATING_SPAWN_DELAY = 3000;
|
| 85 |
+
const RESULTS_DISPLAY_MS = 12000;
|
| 86 |
+
const MAX_ROUND_DURATION_MS = 5 * 60_000;
|
| 87 |
+
const ZONE_DAMAGE_RATE = 15;
|
| 88 |
+
|
| 89 |
+
const ZONE_PHASES = [
|
| 90 |
+
{ waitMs: 15000, shrinkMs: 20000, targetRadius: 300 },
|
| 91 |
+
{ waitMs: 10000, shrinkMs: 15000, targetRadius: 180 },
|
| 92 |
+
{ waitMs: 10000, shrinkMs: 15000, targetRadius: 80 },
|
| 93 |
+
{ waitMs: 10000, shrinkMs: 20000, targetRadius: 0 },
|
| 94 |
+
];
|
| 95 |
+
|
| 96 |
+
for (let i = 0; i < MIN_ROOMS; i++) {
|
| 97 |
+
const r = makeRoom(i < 3);
|
| 98 |
+
rooms[r.id] = r;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
function isRoomJoinable(room) {
|
| 102 |
+
if (room.status === 'EXTINCTION') return false;
|
| 103 |
+
const elapsed = room.startTime ? Date.now() - room.startTime : 0;
|
| 104 |
+
const pCount = Object.keys(room.players).length;
|
| 105 |
+
return !(pCount >= 2 && elapsed > 60000);
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
const roomStates = new Map();
|
| 109 |
+
|
| 110 |
+
function resetRoomToLobby(room) {
|
| 111 |
+
room.status = 'LOBBY';
|
| 112 |
+
room.startTime = 0;
|
| 113 |
+
room.biome = randomBiome();
|
| 114 |
+
room.groups = {};
|
| 115 |
+
for (const pid of Object.keys(room.players)) {
|
| 116 |
+
if (pid.startsWith('offspring-') || pid.startsWith('bot-')) { delete room.players[pid]; continue; }
|
| 117 |
+
room.players[pid].ready = false;
|
| 118 |
+
room.players[pid].state = JSON.parse(JSON.stringify(INITIAL_STATE));
|
| 119 |
+
}
|
| 120 |
+
populateBots(room, false);
|
| 121 |
+
roomStates.delete(room.id);
|
| 122 |
+
roomChatLogs.delete(room.id);
|
| 123 |
+
roomEmptySince.delete(room.id);
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
function initRoomState(roomId) {
|
| 127 |
+
const room = rooms[roomId];
|
| 128 |
+
const colors = ['#67e8f9', '#fbbf24', '#34d399', '#f472b6', '#a78bfa', '#fb923c'];
|
| 129 |
+
const initial = {};
|
| 130 |
+
let idx = 0;
|
| 131 |
+
|
| 132 |
+
Object.values(room.players).forEach((p) => {
|
| 133 |
+
const angle = Math.random() * Math.PI * 2;
|
| 134 |
+
const dist = Math.random() * 300;
|
| 135 |
+
initial[p.id] = {
|
| 136 |
+
id: p.id, name: p.name,
|
| 137 |
+
x: ARENA_SIZE / 2 + Math.cos(angle) * dist, y: ARENA_SIZE / 2 + Math.sin(angle) * dist,
|
| 138 |
+
targetX: ARENA_SIZE / 2 + Math.cos(angle) * dist, targetY: ARENA_SIZE / 2 + Math.sin(angle) * dist,
|
| 139 |
+
color: colors[idx % colors.length], dead: false,
|
| 140 |
+
hunger: 0, matingCooldown: 0, combatCooldown: 0, offspringCount: 0, envDamage: 0,
|
| 141 |
+
};
|
| 142 |
+
idx++;
|
| 143 |
+
});
|
| 144 |
+
|
| 145 |
+
const food = Array.from({ length: FOOD_COUNT }).map(() => ({
|
| 146 |
+
x: 50 + Math.random() * (ARENA_SIZE - 100), y: 50 + Math.random() * (ARENA_SIZE - 100),
|
| 147 |
+
consumed: false, capacity: 100,
|
| 148 |
+
}));
|
| 149 |
+
|
| 150 |
+
roomStates.set(roomId, {
|
| 151 |
+
lastTick: Date.now(), tickCount: 0, entities: initial, foodNodes: food,
|
| 152 |
+
safeZoneRadius: SAFE_ZONE_START, matingPairs: [], visualEffects: [],
|
| 153 |
+
endingSince: null, winner: null, winnerAt: null,
|
| 154 |
+
});
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
function zoneDeathAttacker(biome) {
|
| 158 |
+
switch (biome) {
|
| 159 |
+
case 'DESERT': return 'The Encroaching Sands';
|
| 160 |
+
case 'RAINFOREST': return 'The Choking Canopy';
|
| 161 |
+
case 'UNDERWATER': return 'The Crushing Depths';
|
| 162 |
+
default: return 'The Shrinking Tide';
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
// REST health checks
|
| 167 |
+
app.get('/api/health', (req, res) => res.json({ status: 'ok', roomsCount: Object.keys(rooms).length }));
|
| 168 |
+
app.get('/', (req, res) => res.send('Level Evolution standalone JS server running.'));
|
| 169 |
+
|
| 170 |
+
// Launch Server
|
| 171 |
+
const server = app.listen(PORT, '0.0.0.0', () => console.log(`Standalone Backend running on port ${PORT}`));
|
| 172 |
+
const wss = new WebSocketServer({ server });
|
| 173 |
+
|
| 174 |
+
const connections = new Map();
|
| 175 |
+
const players = new Map();
|
| 176 |
+
|
| 177 |
+
function broadcastAllRooms() {
|
| 178 |
+
const str = JSON.stringify({ type: 'ALL_ROOMS', rooms });
|
| 179 |
+
for (const ws of Array.from(connections.values())) {
|
| 180 |
+
if (ws.readyState === WebSocket.OPEN) ws.send(str);
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
function broadcastRoom(roomId) {
|
| 185 |
+
const room = rooms[roomId];
|
| 186 |
+
if (!room) return;
|
| 187 |
+
broadcastToRoom(roomId, JSON.stringify({ type: 'ROOM_STATE', room }));
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
function broadcastToRoom(roomId, dataStr) {
|
| 191 |
+
const room = rooms[roomId];
|
| 192 |
+
if (!room) return;
|
| 193 |
+
for (const pid of Object.keys(room.players)) {
|
| 194 |
+
const ws = connections.get(pid);
|
| 195 |
+
if (ws && ws.readyState === WebSocket.OPEN) ws.send(dataStr);
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
function maybeAddRoom() {
|
| 200 |
+
const anyJoinable = Object.values(rooms).some(isRoomJoinable);
|
| 201 |
+
if (!anyJoinable && Object.keys(rooms).length < ROOM_SAFETY_CAP) {
|
| 202 |
+
const r = makeRoom();
|
| 203 |
+
rooms[r.id] = r;
|
| 204 |
+
broadcastAllRooms();
|
| 205 |
+
}
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
function maybeScaleDownRooms() {
|
| 209 |
+
const now = Date.now();
|
| 210 |
+
const ids = Object.keys(rooms);
|
| 211 |
+
if (ids.length <= MIN_ROOMS) return;
|
| 212 |
+
|
| 213 |
+
const removable = ids.filter(id => {
|
| 214 |
+
const room = rooms[id];
|
| 215 |
+
if (room.status !== 'LOBBY' || Object.keys(room.players).length > 0) {
|
| 216 |
+
roomEmptySince.delete(id);
|
| 217 |
+
return false;
|
| 218 |
+
}
|
| 219 |
+
const since = roomEmptySince.get(id);
|
| 220 |
+
if (since === undefined) { roomEmptySince.set(id, now); return false; }
|
| 221 |
+
return now - since > ROOM_EMPTY_GRACE_MS;
|
| 222 |
+
});
|
| 223 |
+
|
| 224 |
+
let toRemove = ids.length - MIN_ROOMS;
|
| 225 |
+
let changed = false;
|
| 226 |
+
for (const id of removable) {
|
| 227 |
+
if (toRemove <= 0) break;
|
| 228 |
+
delete rooms[id];
|
| 229 |
+
roomEmptySince.delete(id);
|
| 230 |
+
toRemove--;
|
| 231 |
+
changed = true;
|
| 232 |
+
}
|
| 233 |
+
if (changed) broadcastAllRooms();
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
function checkRoomExtinction(roomId) {
|
| 237 |
+
const room = rooms[roomId];
|
| 238 |
+
const realPlayers = Object.values(room.players).filter(p => !p.id.startsWith('bot-'));
|
| 239 |
+
if (realPlayers.length > 0 && Object.keys(room.players).length >= 2 && Object.values(room.players).every(p => p.ready)) {
|
| 240 |
+
room.status = 'EXTINCTION';
|
| 241 |
+
room.startTime = Date.now();
|
| 242 |
+
initRoomState(roomId);
|
| 243 |
+
broadcastRoom(roomId);
|
| 244 |
+
broadcastAllRooms();
|
| 245 |
+
}
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
wss.on('connection', (ws) => {
|
| 249 |
+
const playerId = uuidv4();
|
| 250 |
+
connections.set(playerId, ws);
|
| 251 |
+
players.set(playerId, {
|
| 252 |
+
id: playerId, name: `Player ${playerId.substring(0, 4)}`,
|
| 253 |
+
roomId: null, state: null, ready: false, score: 0,
|
| 254 |
+
joinedAt: Date.now(), hasCollectedGift: false, groupId: null,
|
| 255 |
+
});
|
| 256 |
+
|
| 257 |
+
ws.send(JSON.stringify({ type: 'INIT', playerId, rooms }));
|
| 258 |
+
|
| 259 |
+
ws.on('message', (message) => {
|
| 260 |
+
try {
|
| 261 |
+
const data = JSON.parse(message.toString());
|
| 262 |
+
const player = players.get(playerId);
|
| 263 |
+
if (!player) return;
|
| 264 |
+
|
| 265 |
+
switch (data.type) {
|
| 266 |
+
case 'JOIN_ROOM': {
|
| 267 |
+
if (player.roomId && rooms[player.roomId]) {
|
| 268 |
+
delete rooms[player.roomId].players[playerId];
|
| 269 |
+
}
|
| 270 |
+
const target = rooms[data.roomId];
|
| 271 |
+
if (!target) break;
|
| 272 |
+
|
| 273 |
+
if (!isRoomJoinable(target)) {
|
| 274 |
+
maybeAddRoom();
|
| 275 |
+
ws.send(JSON.stringify({ type: 'CHAT_MSG', from: 'System', text: 'Room locked — try the newest room.', timestamp: Date.now() }));
|
| 276 |
+
break;
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
player.roomId = data.roomId;
|
| 280 |
+
player.name = data.name || player.name;
|
| 281 |
+
target.players[playerId] = player;
|
| 282 |
+
roomEmptySince.delete(data.roomId);
|
| 283 |
+
|
| 284 |
+
broadcastRoom(data.roomId);
|
| 285 |
+
broadcastAllRooms();
|
| 286 |
+
|
| 287 |
+
ws.send(JSON.stringify({ type: 'CHAT_HISTORY', messages: roomChatLogs.get(data.roomId) || [] }));
|
| 288 |
+
break;
|
| 289 |
+
}
|
| 290 |
+
case 'UPDATE_STATE': {
|
| 291 |
+
player.state = data.state;
|
| 292 |
+
if (player.roomId) {
|
| 293 |
+
rooms[player.roomId].players[playerId] = player;
|
| 294 |
+
broadcastRoom(player.roomId);
|
| 295 |
+
}
|
| 296 |
+
break;
|
| 297 |
+
}
|
| 298 |
+
case 'SET_READY': {
|
| 299 |
+
player.ready = data.ready;
|
| 300 |
+
if (player.roomId) {
|
| 301 |
+
rooms[player.roomId].players[playerId] = player;
|
| 302 |
+
checkRoomExtinction(player.roomId);
|
| 303 |
+
broadcastRoom(player.roomId);
|
| 304 |
+
}
|
| 305 |
+
break;
|
| 306 |
+
}
|
| 307 |
+
case 'CHAT': {
|
| 308 |
+
if (player.roomId) {
|
| 309 |
+
const entry = { from: player.name, text: data.text, timestamp: Date.now() };
|
| 310 |
+
const log = roomChatLogs.get(player.roomId) || [];
|
| 311 |
+
log.push(entry);
|
| 312 |
+
if (log.length > CHAT_HISTORY_LIMIT) log.splice(0, log.length - CHAT_HISTORY_LIMIT);
|
| 313 |
+
roomChatLogs.set(player.roomId, log);
|
| 314 |
+
broadcastToRoom(player.roomId, JSON.stringify({ type: 'CHAT_MSG', ...entry }));
|
| 315 |
+
}
|
| 316 |
+
break;
|
| 317 |
+
}
|
| 318 |
+
case 'SEND_GIFT': {
|
| 319 |
+
const target = players.get(data.toPlayerId);
|
| 320 |
+
if (!target) break;
|
| 321 |
+
const isNoob = Date.now() - target.joinedAt < 15000 && !target.hasCollectedGift;
|
| 322 |
+
if (isNoob) {
|
| 323 |
+
target.hasCollectedGift = true;
|
| 324 |
+
player.score += 10;
|
| 325 |
+
const result = { type: 'GIFT_RESULT', toPlayerId: target.id, fromId: player.id, accepted: true, giverReward: 10, giverId: player.id };
|
| 326 |
+
ws.send(JSON.stringify(result));
|
| 327 |
+
const targetWs = connections.get(target.id);
|
| 328 |
+
if (targetWs) targetWs.send(JSON.stringify(result));
|
| 329 |
+
} else {
|
| 330 |
+
ws.send(JSON.stringify({ type: 'GIFT_RESULT', toPlayerId: target.id, fromId: player.id, accepted: false, giverReward: 0, giverId: player.id }));
|
| 331 |
+
}
|
| 332 |
+
break;
|
| 333 |
+
}
|
| 334 |
+
}
|
| 335 |
+
} catch (e) {
|
| 336 |
+
console.error('WS parse error', e);
|
| 337 |
+
}
|
| 338 |
+
});
|
| 339 |
+
|
| 340 |
+
ws.on('close', () => {
|
| 341 |
+
const player = players.get(playerId);
|
| 342 |
+
if (player && player.roomId) {
|
| 343 |
+
const roomId = player.roomId;
|
| 344 |
+
const room = rooms[roomId];
|
| 345 |
+
const gs = roomStates.get(roomId);
|
| 346 |
+
|
| 347 |
+
if (gs && gs.entities[playerId] && !gs.entities[playerId].dead) {
|
| 348 |
+
gs.entities[playerId].dead = true;
|
| 349 |
+
gs.entities[playerId].deathTime = Date.now();
|
| 350 |
+
gs.entities[playerId].deathReason = 'Disconnected';
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
if (room) {
|
| 354 |
+
delete room.players[playerId];
|
| 355 |
+
if (player.groupId && room.groups[player.groupId]) {
|
| 356 |
+
room.groups[player.groupId].memberIds = room.groups[player.groupId].memberIds.filter(id => id !== playerId);
|
| 357 |
+
}
|
| 358 |
+
broadcastRoom(roomId);
|
| 359 |
+
broadcastAllRooms();
|
| 360 |
+
}
|
| 361 |
+
}
|
| 362 |
+
connections.delete(playerId);
|
| 363 |
+
players.delete(playerId);
|
| 364 |
+
});
|
| 365 |
+
});
|
| 366 |
+
|
| 367 |
+
// ─── EXTINCTION TICK LOOP (20Hz) ──────────────────────────────────────────────────
|
| 368 |
+
let globalTick = 0;
|
| 369 |
+
setInterval(() => {
|
| 370 |
+
globalTick++;
|
| 371 |
+
let stateChanged = false;
|
| 372 |
+
const now = Date.now();
|
| 373 |
+
|
| 374 |
+
if (globalTick % 40 === 0) maybeScaleDownRooms();
|
| 375 |
+
|
| 376 |
+
for (const roomId in rooms) {
|
| 377 |
+
const room = rooms[roomId];
|
| 378 |
+
const pCount = Object.keys(room.players).length;
|
| 379 |
+
const realPlayers = Object.values(room.players).filter(p => !p.id.startsWith('bot-'));
|
| 380 |
+
|
| 381 |
+
if (room.status === 'LOBBY' && pCount > 0) {
|
| 382 |
+
room.status = 'CRAFTING';
|
| 383 |
+
room.hasRealPlayers = realPlayers.length > 0;
|
| 384 |
+
room.startTime = now;
|
| 385 |
+
stateChanged = true;
|
| 386 |
+
} else if (room.status === 'CRAFTING') {
|
| 387 |
+
if (realPlayers.length > 0 && !room.hasRealPlayers) {
|
| 388 |
+
room.hasRealPlayers = true;
|
| 389 |
+
room.startTime = now - 50000;
|
| 390 |
+
stateChanged = true;
|
| 391 |
+
} else if (realPlayers.length === 0) {
|
| 392 |
+
room.startTime = now;
|
| 393 |
+
room.hasRealPlayers = false;
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
const elapsed = now - room.startTime;
|
| 397 |
+
if ((elapsed >= 120000 || (pCount >= 2 && Object.values(room.players).every(p => p.ready))) && realPlayers.length > 0) {
|
| 398 |
+
room.status = 'EXTINCTION';
|
| 399 |
+
room.startTime = now;
|
| 400 |
+
initRoomState(roomId);
|
| 401 |
+
stateChanged = true;
|
| 402 |
+
maybeAddRoom();
|
| 403 |
+
}
|
| 404 |
+
} else if (room.status === 'EXTINCTION') {
|
| 405 |
+
const gs = roomStates.get(roomId);
|
| 406 |
+
|
| 407 |
+
if (gs?.winner) {
|
| 408 |
+
if (gs.winnerAt === null) gs.winnerAt = now;
|
| 409 |
+
if (realPlayers.length === 0 || now - gs.winnerAt > RESULTS_DISPLAY_MS) {
|
| 410 |
+
resetRoomToLobby(room);
|
| 411 |
+
stateChanged = true;
|
| 412 |
+
}
|
| 413 |
+
continue;
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
if (realPlayers.length === 0 && now - room.startTime > 5000) {
|
| 417 |
+
resetRoomToLobby(room);
|
| 418 |
+
stateChanged = true;
|
| 419 |
+
continue;
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
if (!gs) continue;
|
| 423 |
+
|
| 424 |
+
const dt = Math.min(0.1, (now - gs.lastTick) / 1000);
|
| 425 |
+
gs.lastTick = now;
|
| 426 |
+
gs.tickCount++;
|
| 427 |
+
|
| 428 |
+
const roundElapsed = now - room.startTime;
|
| 429 |
+
let currentRadius = SAFE_ZONE_START;
|
| 430 |
+
let accumTime = 0;
|
| 431 |
+
for (const p of ZONE_PHASES) {
|
| 432 |
+
if (roundElapsed < accumTime + p.waitMs) break;
|
| 433 |
+
accumTime += p.waitMs;
|
| 434 |
+
if (roundElapsed < accumTime + p.shrinkMs) {
|
| 435 |
+
const progress = (roundElapsed - accumTime) / p.shrinkMs;
|
| 436 |
+
currentRadius = currentRadius - (currentRadius - p.targetRadius) * progress;
|
| 437 |
+
break;
|
| 438 |
+
}
|
| 439 |
+
accumTime += p.shrinkMs;
|
| 440 |
+
currentRadius = p.targetRadius;
|
| 441 |
+
}
|
| 442 |
+
gs.safeZoneRadius = currentRadius;
|
| 443 |
+
gs.visualEffects = gs.visualEffects.filter(fx => now - fx.timestamp < 1000);
|
| 444 |
+
|
| 445 |
+
const pendingLogs = [];
|
| 446 |
+
let needsPlayerBroadcast = false;
|
| 447 |
+
|
| 448 |
+
const isPaired = (id) => gs.matingPairs.some(mp => !mp.done && (mp.a === id || mp.b === id));
|
| 449 |
+
|
| 450 |
+
for (const k in gs.entities) {
|
| 451 |
+
if (gs.entities[k].dead && now - (gs.entities[k].deathTime || 0) > 10000) {
|
| 452 |
+
delete gs.entities[k];
|
| 453 |
+
}
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
const activeKeys = Object.keys(gs.entities).filter(k => !gs.entities[k].dead);
|
| 457 |
+
|
| 458 |
+
// Separation
|
| 459 |
+
for (const k of activeKeys) {
|
| 460 |
+
const e = gs.entities[k];
|
| 461 |
+
for (const otherK of activeKeys) {
|
| 462 |
+
if (k === otherK) continue;
|
| 463 |
+
const other = gs.entities[otherK];
|
| 464 |
+
const dx = e.x - other.x, dy = e.y - other.y;
|
| 465 |
+
const dist = Math.hypot(dx, dy);
|
| 466 |
+
if (dist > 0 && dist < 15) {
|
| 467 |
+
const push = ((15 - dist) / 15) * 10 * dt;
|
| 468 |
+
e.x += (dx / dist) * push; e.y += (dy / dist) * push;
|
| 469 |
+
}
|
| 470 |
+
}
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
for (const k of activeKeys) {
|
| 474 |
+
const e = gs.entities[k];
|
| 475 |
+
const stateA = room.players[k]?.state;
|
| 476 |
+
|
| 477 |
+
if (!stateA) {
|
| 478 |
+
if (!e.dead) { e.dead = true; e.deathTime = now; e.deathReason = 'No Blueprint'; }
|
| 479 |
+
continue;
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
const derivedA = getDerivedStats(stateA, room.biome);
|
| 483 |
+
|
| 484 |
+
if (isPaired(k)) {
|
| 485 |
+
const angle = Math.atan2(ARENA_SIZE / 2 - e.y, ARENA_SIZE / 2 - e.x);
|
| 486 |
+
e.x += Math.cos(angle) * derivedA.speed * 0.3 * dt;
|
| 487 |
+
e.y += Math.sin(angle) * derivedA.speed * 0.3 * dt;
|
| 488 |
+
continue;
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
const distToCenter = Math.hypot(e.x - ARENA_SIZE / 2, e.y - ARENA_SIZE / 2);
|
| 492 |
+
const outsideZone = distToCenter > gs.safeZoneRadius;
|
| 493 |
+
|
| 494 |
+
if (outsideZone) {
|
| 495 |
+
e.targetX = ARENA_SIZE / 2; e.targetY = ARENA_SIZE / 2;
|
| 496 |
+
const overshoot = distToCenter - gs.safeZoneRadius;
|
| 497 |
+
const severity = 1 + Math.min(3, overshoot / 100);
|
| 498 |
+
e.envDamage += ZONE_DAMAGE_RATE * severity * dt;
|
| 499 |
+
}
|
| 500 |
+
|
| 501 |
+
let envDmgRate = 0;
|
| 502 |
+
if (room.biome === 'UNDERWATER' && !derivedA.aquatic && stateA.compositions.CNIDARIA < 30 && stateA.attributes.BUOYANCY < 3) {
|
| 503 |
+
envDmgRate = 12;
|
| 504 |
+
} else if (room.biome === 'DESERT') {
|
| 505 |
+
envDmgRate = derivedA.desiccationRate * 4;
|
| 506 |
+
}
|
| 507 |
+
if (envDmgRate > 0) e.envDamage += envDmgRate * dt;
|
| 508 |
+
|
| 509 |
+
if (e.envDamage >= derivedA.hp) {
|
| 510 |
+
e.dead = true; e.deathTime = now;
|
| 511 |
+
e.deathReason = distToCenter > gs.safeZoneRadius ? 'Caught in Zone' : (room.biome === 'UNDERWATER' ? 'Drowned' : 'Desiccated');
|
| 512 |
+
pendingLogs.push({ id: Math.random().toString(), attacker: zoneDeathAttacker(room.biome), defender: e.name, attackerWon: true, notes: [e.deathReason] });
|
| 513 |
+
continue;
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
const PANIC_RETURN_SPEED = 20;
|
| 517 |
+
const baseSpeed = derivedA.speed * 0.8;
|
| 518 |
+
const moveSpeed = Math.max(baseSpeed, outsideZone ? PANIC_RETURN_SPEED : 0);
|
| 519 |
+
|
| 520 |
+
// Bot AI
|
| 521 |
+
const isBot = k.startsWith('bot-');
|
| 522 |
+
let aiTarget = null;
|
| 523 |
+
|
| 524 |
+
if (isBot) {
|
| 525 |
+
const zoneMargin = gs.safeZoneRadius - distToCenter;
|
| 526 |
+
if (zoneMargin < 60) {
|
| 527 |
+
const urgency = 1 - Math.max(0, zoneMargin / 60);
|
| 528 |
+
aiTarget = { x: ARENA_SIZE / 2 + (e.x - ARENA_SIZE / 2) * (1 - urgency * 0.8), y: ARENA_SIZE / 2 + (e.y - ARENA_SIZE / 2) * (1 - urgency * 0.8) };
|
| 529 |
+
}
|
| 530 |
+
if (!aiTarget && e.hunger > 20) {
|
| 531 |
+
const food = gs.foodNodes.find(f => !f.consumed && f.capacity > 0 && Math.hypot(f.x - e.x, f.y - e.y) < derivedA.detection && Math.hypot(f.x - ARENA_SIZE/2, f.y - ARENA_SIZE/2) < gs.safeZoneRadius * 0.85);
|
| 532 |
+
if (food) aiTarget = { x: food.x, y: food.y };
|
| 533 |
+
}
|
| 534 |
+
if (!aiTarget) {
|
| 535 |
+
for (const otherK of activeKeys) {
|
| 536 |
+
if (otherK === k) continue;
|
| 537 |
+
const other = gs.entities[otherK];
|
| 538 |
+
const dist = Math.hypot(e.x - other.x, e.y - other.y);
|
| 539 |
+
if (dist < derivedA.detection * 0.7) {
|
| 540 |
+
const stateB = room.players[otherK]?.state;
|
| 541 |
+
if (stateB && getDerivedStats(stateB, room.biome).hp > derivedA.hp * 1.3) {
|
| 542 |
+
const fleeAngle = Math.atan2(e.y - other.y, e.x - other.x);
|
| 543 |
+
aiTarget = { x: e.x + Math.cos(fleeAngle) * 100, y: e.y + Math.sin(fleeAngle) * 100 };
|
| 544 |
+
break;
|
| 545 |
+
}
|
| 546 |
+
}
|
| 547 |
+
}
|
| 548 |
+
}
|
| 549 |
+
if (aiTarget) { e.targetX = aiTarget.x; e.targetY = aiTarget.y; }
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
if (!outsideZone && !isBot) {
|
| 553 |
+
if (e.hunger > 15) {
|
| 554 |
+
const nearFood = gs.foodNodes.find(f => !f.consumed && f.capacity > 0 && Math.hypot(f.x - e.x, f.y - e.y) < derivedA.detection * 0.8 && Math.hypot(f.x - ARENA_SIZE/2, f.y - ARENA_SIZE/2) < gs.safeZoneRadius * 0.9);
|
| 555 |
+
if (nearFood) { e.targetX = nearFood.x; e.targetY = nearFood.y; }
|
| 556 |
+
} else if (Math.hypot(e.targetX - e.x, e.targetY - e.y) < 12) {
|
| 557 |
+
const a = Math.random() * Math.PI * 2;
|
| 558 |
+
const r = Math.random() * gs.safeZoneRadius * 0.8;
|
| 559 |
+
e.targetX = ARENA_SIZE / 2 + Math.cos(a) * r;
|
| 560 |
+
e.targetY = ARENA_SIZE / 2 + Math.sin(a) * r;
|
| 561 |
+
}
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
const moveAngle = Math.atan2(e.targetY - e.y, e.targetX - e.x);
|
| 565 |
+
e.x = Math.max(10, Math.min(ARENA_SIZE - 10, e.x + Math.cos(moveAngle) * moveSpeed * dt));
|
| 566 |
+
e.y = Math.max(10, Math.min(ARENA_SIZE - 10, e.y + Math.sin(moveAngle) * moveSpeed * dt));
|
| 567 |
+
|
| 568 |
+
if (e.hunger > 15) {
|
| 569 |
+
const nearFood = gs.foodNodes.find(f => !f.consumed && f.capacity > 0 && Math.hypot(f.x - e.x, f.y - e.y) < 25);
|
| 570 |
+
if (nearFood) {
|
| 571 |
+
const eatAmount = Math.min(e.hunger, 40 * dt, nearFood.capacity);
|
| 572 |
+
nearFood.capacity -= eatAmount;
|
| 573 |
+
e.hunger -= eatAmount;
|
| 574 |
+
if (nearFood.capacity <= 0) nearFood.consumed = true;
|
| 575 |
+
}
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
e.hunger += (derivedA.energyDemand / 20) * dt;
|
| 579 |
+
if (e.hunger > HUNGER_THRESHOLD) {
|
| 580 |
+
e.dead = true; e.deathTime = now; e.deathReason = 'Starved';
|
| 581 |
+
pendingLogs.push({ id: Math.random().toString(), attacker: 'Environment', defender: e.name, attackerWon: true, notes: ['Starvation'] });
|
| 582 |
+
continue;
|
| 583 |
+
}
|
| 584 |
+
|
| 585 |
+
if (e.matingCooldown > 0) e.matingCooldown = Math.max(0, e.matingCooldown - dt);
|
| 586 |
+
if (e.combatCooldown > 0) e.combatCooldown = Math.max(0, e.combatCooldown - dt);
|
| 587 |
+
|
| 588 |
+
// Combat
|
| 589 |
+
for (const otherK of activeKeys) {
|
| 590 |
+
if (k === otherK) continue;
|
| 591 |
+
const other = gs.entities[otherK];
|
| 592 |
+
if (other.dead) continue;
|
| 593 |
+
const stateB = room.players[otherK]?.state;
|
| 594 |
+
if (!stateB) continue;
|
| 595 |
+
|
| 596 |
+
const dist = Math.hypot(e.x - other.x, e.y - other.y);
|
| 597 |
+
const combatRange = Math.max(35, moveSpeed * dt * 2 + 20);
|
| 598 |
+
if (dist >= combatRange) continue;
|
| 599 |
+
|
| 600 |
+
const canSee = dist < derivedA.detection * 0.6;
|
| 601 |
+
if (!canSee && dist > 40) continue;
|
| 602 |
+
|
| 603 |
+
if (stateA.socialType !== 'SOLITARY' && stateA.socialType === stateB.socialType && e.matingCooldown <= 0 && other.matingCooldown <= 0) {
|
| 604 |
+
e.matingCooldown = 15; other.matingCooldown = 15;
|
| 605 |
+
const midX = (e.x + other.x) / 2, midY = (e.y + other.y) / 2;
|
| 606 |
+
gs.matingPairs.push({ a: k, b: otherK, gasX: midX, gasY: midY, startTime: now, done: false });
|
| 607 |
+
break;
|
| 608 |
+
}
|
| 609 |
+
|
| 610 |
+
if (e.combatCooldown <= 0 && other.combatCooldown <= 0) {
|
| 611 |
+
const result = resolveCombat(stateA, stateB, room.biome);
|
| 612 |
+
const attackTag = result.breakdown.primaryTag || 'CRUSH';
|
| 613 |
+
const outcome = result.breakdown.isShatter ? 'Shatter' : 'Normal';
|
| 614 |
+
|
| 615 |
+
if (result.breakdown.evaded) {
|
| 616 |
+
e.combatCooldown = 1.2; other.combatCooldown = 1.2;
|
| 617 |
+
pendingLogs.push({ id: Math.random().toString(), attacker: e.name, defender: other.name, attackerWon: false, notes: [...result.breakdown.notes, `${other.name} evaded`] });
|
| 618 |
+
} else {
|
| 619 |
+
gs.visualEffects.push({ id: Math.random().toString(), x: (e.x + other.x) / 2, y: (e.y + other.y) / 2, timestamp: now, attackTag, outcome });
|
| 620 |
+
pendingLogs.push({ id: Math.random().toString(), attacker: e.name, defender: other.name, attackerWon: result.won, notes: result.breakdown.notes });
|
| 621 |
+
if (result.won) {
|
| 622 |
+
other.dead = true; other.deathTime = now; other.deathReason = attackTag;
|
| 623 |
+
} else {
|
| 624 |
+
e.dead = true; e.deathTime = now; e.deathReason = attackTag; break;
|
| 625 |
+
}
|
| 626 |
+
}
|
| 627 |
+
}
|
| 628 |
+
}
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
gs.matingPairs = gs.matingPairs.filter(mp => now - mp.startTime < 4000).map(mp => {
|
| 632 |
+
if (!mp.done && now - mp.startTime > MATING_SPAWN_DELAY) {
|
| 633 |
+
const stateA = room.players[mp.a]?.state;
|
| 634 |
+
const stateB = room.players[mp.b]?.state;
|
| 635 |
+
if (stateA && stateB && gs.entities[mp.a] && !gs.entities[mp.a].dead) {
|
| 636 |
+
const offId = `offspring-${mp.a}-${gs.tickCount}`;
|
| 637 |
+
const offspringState = breedOffspring(stateA, stateB);
|
| 638 |
+
|
| 639 |
+
const distToCenter = Math.hypot(mp.gasX - ARENA_SIZE/2, mp.gasY - ARENA_SIZE/2);
|
| 640 |
+
let spawnX = mp.gasX, spawnY = mp.gasY;
|
| 641 |
+
if (distToCenter > gs.safeZoneRadius - 10) {
|
| 642 |
+
const angle = Math.atan2(mp.gasY - ARENA_SIZE/2, mp.gasX - ARENA_SIZE/2);
|
| 643 |
+
spawnX = ARENA_SIZE/2 + Math.cos(angle) * (gs.safeZoneRadius - 20);
|
| 644 |
+
spawnY = ARENA_SIZE/2 + Math.sin(angle) * (gs.safeZoneRadius - 20);
|
| 645 |
+
}
|
| 646 |
+
|
| 647 |
+
gs.entities[offId] = {
|
| 648 |
+
id: offId, name: `${gs.entities[mp.a].name}'s spawn`,
|
| 649 |
+
x: spawnX + (Math.random() - 0.5) * 40, y: spawnY + (Math.random() - 0.5) * 40,
|
| 650 |
+
targetX: spawnX, targetY: spawnY, color: gs.entities[mp.a].color,
|
| 651 |
+
dead: false, hunger: 0, matingCooldown: 5, combatCooldown: 1, offspringCount: 0, envDamage: 0
|
| 652 |
+
};
|
| 653 |
+
gs.entities[mp.a].offspringCount++;
|
| 654 |
+
if (gs.entities[mp.b]) gs.entities[mp.b].offspringCount++;
|
| 655 |
+
|
| 656 |
+
room.players[offId] = {
|
| 657 |
+
id: offId, name: gs.entities[offId].name, roomId: roomId,
|
| 658 |
+
state: offspringState, ready: true, score: 0,
|
| 659 |
+
joinedAt: Date.now(), hasCollectedGift: true, groupId: null,
|
| 660 |
+
};
|
| 661 |
+
|
| 662 |
+
needsPlayerBroadcast = true;
|
| 663 |
+
}
|
| 664 |
+
return { ...mp, done: true };
|
| 665 |
+
}
|
| 666 |
+
return mp;
|
| 667 |
+
});
|
| 668 |
+
|
| 669 |
+
broadcastToRoom(roomId, JSON.stringify({
|
| 670 |
+
type: 'EXTINCTION_TICK',
|
| 671 |
+
state: {
|
| 672 |
+
entities: gs.entities, foodNodes: gs.foodNodes, safeZoneRadius: gs.safeZoneRadius,
|
| 673 |
+
matingPairs: gs.matingPairs, visualEffects: gs.visualEffects
|
| 674 |
+
},
|
| 675 |
+
logs: pendingLogs
|
| 676 |
+
}));
|
| 677 |
+
|
| 678 |
+
if (needsPlayerBroadcast) broadcastRoom(roomId);
|
| 679 |
+
|
| 680 |
+
// === DELAYED WINNER CHECK ===
|
| 681 |
+
const all = Object.values(gs.entities);
|
| 682 |
+
const alive = all.filter(e => !e.dead);
|
| 683 |
+
|
| 684 |
+
if ((all.length > 1 && alive.length <= 1) || (all.length === 1 && alive.length === 0)) {
|
| 685 |
+
if (!gs.endingSince) gs.endingSince = now;
|
| 686 |
+
} else if (roundElapsed > MAX_ROUND_DURATION_MS) {
|
| 687 |
+
if (!gs.endingSince) gs.endingSince = now;
|
| 688 |
+
} else {
|
| 689 |
+
gs.endingSince = null;
|
| 690 |
+
}
|
| 691 |
+
|
| 692 |
+
if (gs.endingSince && (now - gs.endingSince > 4000) && !gs.winner) {
|
| 693 |
+
if (roundElapsed > MAX_ROUND_DURATION_MS) {
|
| 694 |
+
const ranked = [...alive].sort((a, b) => b.offspringCount - a.offspringCount);
|
| 695 |
+
gs.winner = ranked.length > 0 ? `${ranked[0].name} (sudden death)` : 'No survivors';
|
| 696 |
+
} else {
|
| 697 |
+
gs.winner = alive.length === 1 ? alive[0].name : 'No survivors';
|
| 698 |
+
}
|
| 699 |
+
gs.winnerAt = now;
|
| 700 |
+
broadcastToRoom(roomId, JSON.stringify({ type: 'EXTINCTION_END', winner: gs.winner }));
|
| 701 |
+
}
|
| 702 |
+
}
|
| 703 |
+
}
|
| 704 |
+
if (stateChanged) broadcastAllRooms();
|
| 705 |
+
}, 50);
|