File size: 30,473 Bytes
53d127f
 
 
 
 
b903329
 
 
 
53d127f
 
d8ee931
53d127f
 
11151e6
53d127f
 
8dd027d
 
 
b903329
8dd027d
53d127f
 
 
 
 
 
11151e6
53d127f
 
 
 
11151e6
53d127f
 
 
 
11151e6
53d127f
 
 
 
11151e6
53d127f
 
 
 
 
 
cee13f8
 
 
 
 
 
 
 
53d127f
cee13f8
 
 
6af9aa9
53d127f
 
 
6af9aa9
53d127f
 
b903329
53d127f
 
 
 
 
 
 
 
 
cee13f8
53d127f
 
 
cee13f8
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cee13f8
53d127f
 
 
 
 
11151e6
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b903329
53d127f
cee13f8
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b903329
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b903329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11151e6
b903329
 
 
 
 
 
 
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11151e6
53d127f
 
 
 
 
 
 
b903329
53d127f
 
 
 
 
 
24aed14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53d127f
b903329
 
 
 
 
 
 
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b903329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53d127f
 
 
 
 
 
 
 
 
 
 
 
b903329
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b903329
53d127f
 
b903329
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b903329
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b903329
53d127f
 
 
 
 
 
 
 
 
 
 
b903329
53d127f
 
 
 
b903329
53d127f
 
 
 
 
 
 
 
 
b903329
53d127f
b903329
53d127f
 
 
b903329
 
 
 
53d127f
 
 
 
 
 
 
b903329
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b903329
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b903329
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b903329
53d127f
b903329
 
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
b903329
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b903329
53d127f
b903329
53d127f
b903329
53d127f
b903329
53d127f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
// server.js
import express from 'express';
import cors from 'cors';
import { WebSocketServer, WebSocket } from 'ws';
import { v4 as uuidv4 } from 'uuid';
import {
  resolveCombat, getDerivedStats, breedOffspring, INITIAL_STATE,
  attributeCap, featureGateReason, getEvolutionPoints, COMPOSITION_ORDER
} from './mechanics.js';

const app = express();
const PORT = process.env.PORT || 7860;

app.use(cors({
  origin: '*',
}));

const MIN_ROOMS = 5;
const ROOM_SAFETY_CAP = 200;
const ROOM_EMPTY_GRACE_MS = 15000;
let roomCounter = 0;

const rooms = {};
const roomEmptySince = new Map();
const roomChatLogs = new Map();
const CHAT_HISTORY_LIMIT = 50;

const BOT_TEMPLATES = [
  {
    compositions: { ANIMALIA: 100, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
    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 },
    features: ['CRUSHING_MANDIBLES'], socialType: 'SOLITARY'
  },
  {
    compositions: { ANIMALIA: 40, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 60, MYCELIUM: 0, MINERALIS: 0 },
    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 },
    features: ['TOXIN_GLANDS', 'GELATINOUS_BODY'], socialType: 'SOLITARY'
  },
  {
    compositions: { ANIMALIA: 100, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
    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 },
    features: ['SLASHING_BLADES'], socialType: 'PACK'
  },
  {
    compositions: { ANIMALIA: 50, CHITINARIA: 50, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
    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 },
    features: ['SCORPION_TAIL'], socialType: 'SOLITARY'
  }
];

// Expanded to 25 unique variants!
const BOT_NAMES = [
  'Alpha', 'Beta', 'Gamma', 'Delta', 'Omega', 
  'Zeta', 'Sigma', 'Prime', 'Apex', 'Titan', 
  'Leviathan', 'Chimera', 'Vertex', 'Nebula', 'Pulsar', 
  'Quasar', 'Zenith', 'Onyx', 'Kestrel', 'Raptor', 
  'Vortex', 'Echo', 'Talon', 'Nova', 'Orion'
];

function populateBots(room) {
  // Always add between 8 and 12 bots (0-4 + 8)
  const numBots = Math.floor(Math.random() * 5) + 8;

  for (let i = 0; i < numBots; i++) {
    const botId = `bot-${uuidv4()}`;
    const template = BOT_TEMPLATES[Math.floor(Math.random() * BOT_TEMPLATES.length)];
    const randomName = `${BOT_NAMES[Math.floor(Math.random() * BOT_NAMES.length)]}`;
    room.players[botId] = {
      id: botId, name: randomName, roomId: room.id,
      state: JSON.parse(JSON.stringify(template)), ready: true,
      score: 0, joinedAt: Date.now(), hasCollectedGift: true, groupId: null
    };
  }
}

function randomBiome() {
  return ['DESERT', 'RAINFOREST', 'UNDERWATER'][Math.floor(Math.random() * 3)];
}

function makeRoom() {
  roomCounter++;
  const id = `room-${roomCounter}`;
  const room = { id, status: 'LOBBY', players: {}, startTime: 0, biome: randomBiome(), groups: {}, hasRealPlayers: false };
  populateBots(room);
  return room;
}

const ARENA_SIZE = 800;
const SAFE_ZONE_START = 400;
const FOOD_COUNT = 15;
const HUNGER_THRESHOLD = 100;
const MATING_SPAWN_DELAY = 3000;
const RESULTS_DISPLAY_MS = 12000;
const MAX_ROUND_DURATION_MS = 5 * 60_000;
const ZONE_DAMAGE_RATE = 15;

const ZONE_PHASES = [
  { waitMs: 15000, shrinkMs: 20000, targetRadius: 300 },
  { waitMs: 10000, shrinkMs: 15000, targetRadius: 180 },
  { waitMs: 10000, shrinkMs: 15000, targetRadius: 80 },
  { waitMs: 10000, shrinkMs: 20000, targetRadius: 0 },
];

for (let i = 0; i < MIN_ROOMS; i++) {
  const r = makeRoom();
  rooms[r.id] = r;
}

function isRoomJoinable(room) {
  if (room.status === 'EXTINCTION') return false;
  if (!room.hasRealPlayers) return true;
  const elapsed = room.startTime ? Date.now() - room.startTime : 0;
  const pCount = Object.keys(room.players).length;
  return !(pCount >= 2 && elapsed > 60000);
}

const roomStates = new Map();

function resetRoomToLobby(room) {
  room.status = 'LOBBY';
  room.startTime = 0;
  room.biome = randomBiome();
  room.groups = {};
  for (const pid of Object.keys(room.players)) {
    if (pid.startsWith('offspring-') || pid.startsWith('bot-')) { delete room.players[pid]; continue; }
    room.players[pid].ready = false;
    room.players[pid].state = JSON.parse(JSON.stringify(INITIAL_STATE));
  }
  populateBots(room);
  roomStates.delete(room.id);
  roomChatLogs.delete(room.id);
  roomEmptySince.delete(room.id);
}

function initRoomState(roomId) {
  const room = rooms[roomId];
  const colors = ['#67e8f9', '#fbbf24', '#34d399', '#f472b6', '#a78bfa', '#fb923c'];
  const initial = {};
  let idx = 0;

  Object.values(room.players).forEach((p) => {
    const angle = Math.random() * Math.PI * 2;
    const dist = Math.random() * 300;
    initial[p.id] = {
      id: p.id, name: p.name,
      x: ARENA_SIZE / 2 + Math.cos(angle) * dist, y: ARENA_SIZE / 2 + Math.sin(angle) * dist,
      targetX: ARENA_SIZE / 2 + Math.cos(angle) * dist, targetY: ARENA_SIZE / 2 + Math.sin(angle) * dist,
      color: colors[idx % colors.length], dead: false,
      hunger: 0, matingCooldown: 0, combatCooldown: 0, offspringCount: 0, envDamage: 0,
    };
    idx++;
  });

  const food = Array.from({ length: FOOD_COUNT }).map(() => ({
    x: 50 + Math.random() * (ARENA_SIZE - 100), y: 50 + Math.random() * (ARENA_SIZE - 100),
    consumed: false, capacity: 100,
  }));

  roomStates.set(roomId, {
    lastTick: Date.now(), tickCount: 0, entities: initial, foodNodes: food,
    safeZoneRadius: SAFE_ZONE_START, matingPairs: [], visualEffects: [],
    endingSince: null, winner: null, winnerAt: null,
  });
}

function zoneDeathAttacker(biome) {
  switch (biome) {
    case 'DESERT': return 'The Encroaching Sands';
    case 'RAINFOREST': return 'The Choking Canopy';
    case 'UNDERWATER': return 'The Crushing Depths';
    default: return 'The Shrinking Tide';
  }
}

function sanitizeState(raw) {
  try {
    const s = {
      compositions: { ...INITIAL_STATE.compositions, ...(raw?.compositions || {}) },
      attributes: { ...INITIAL_STATE.attributes, ...(raw?.attributes || {}) },
      features: Array.isArray(raw?.features) ? raw.features.slice(0, 5) : [],
      socialType: ['SOLITARY', 'PACK', 'HIVE'].includes(raw?.socialType) ? raw.socialType : 'SOLITARY',
    };

    const compSum = COMPOSITION_ORDER.reduce((sum, k) => sum + (Number(s.compositions[k]) || 0), 0);
    if (Math.abs(compSum - 100) > 2) return JSON.parse(JSON.stringify(INITIAL_STATE));

    for (const k of Object.keys(s.attributes)) {
      const cap = attributeCap(k, s.compositions);
      const val = Number(s.attributes[k]) || 0;
      s.attributes[k] = Math.max(0, Math.min(val, cap));
    }

    s.features = s.features.filter(f => !featureGateReason(f, s.compositions));

    const ep = getEvolutionPoints(s);
    if (ep.used > ep.max) return null;

    return s;
  } catch {
    return null;
  }
}

app.get('/api/health', (req, res) => res.json({ status: 'ok', roomsCount: Object.keys(rooms).length }));
app.get('/', (req, res) => res.send('Level Evolution standalone JS server running.'));

const server = app.listen(PORT, '0.0.0.0', () => console.log(`Standalone Backend running on port ${PORT}`));
const wss = new WebSocketServer({ server });

const connections = new Map();
const players = new Map();

function broadcastAllRooms() {
  const str = JSON.stringify({ type: 'ALL_ROOMS', rooms });
  for (const ws of Array.from(connections.values())) {
    if (ws.readyState === WebSocket.OPEN) ws.send(str);
  }
}

function broadcastRoom(roomId) {
  const room = rooms[roomId];
  if (!room) return;
  broadcastToRoom(roomId, JSON.stringify({ type: 'ROOM_STATE', room }));
}

function broadcastToRoom(roomId, dataStr) {
  const room = rooms[roomId];
  if (!room) return;
  for (const pid of Object.keys(room.players)) {
    const ws = connections.get(pid);
    if (ws && ws.readyState === WebSocket.OPEN) ws.send(dataStr);
  }
}

function maybeAddRoom() {
  const anyJoinable = Object.values(rooms).some(isRoomJoinable);
  if (!anyJoinable && Object.keys(rooms).length < ROOM_SAFETY_CAP) {
    const r = makeRoom();
    rooms[r.id] = r;
    broadcastAllRooms();
  }
}

function maybeScaleDownRooms() {
  const now = Date.now();
  const ids = Object.keys(rooms);
  if (ids.length <= MIN_ROOMS) return;

  const removable = ids.filter(id => {
    const room = rooms[id];
    if (room.status !== 'LOBBY' || Object.keys(room.players).length > 0) {
      roomEmptySince.delete(id);
      return false;
    }
    const since = roomEmptySince.get(id);
    if (since === undefined) { roomEmptySince.set(id, now); return false; }
    return now - since > ROOM_EMPTY_GRACE_MS;
  });

  let toRemove = ids.length - MIN_ROOMS;
  let changed = false;
  for (const id of removable) {
    if (toRemove <= 0) break;
    delete rooms[id];
    roomEmptySince.delete(id);
    toRemove--;
    changed = true;
  }
  if (changed) broadcastAllRooms();
}

function checkRoomExtinction(roomId) {
  const room = rooms[roomId];
  const realPlayers = Object.values(room.players).filter(p => !p.id.startsWith('bot-'));
  if (realPlayers.length > 0 && Object.keys(room.players).length >= 2 && Object.values(room.players).every(p => p.ready)) {
    room.status = 'EXTINCTION';
    room.startTime = Date.now();
    initRoomState(roomId);
    broadcastRoom(roomId);
    broadcastAllRooms();
  }
}

wss.on('connection', (ws) => {
  const playerId = uuidv4();
  connections.set(playerId, ws);
  players.set(playerId, {
    id: playerId, name: `Player ${playerId.substring(0, 4)}`,
    roomId: null, state: null, ready: false, score: 0,
    joinedAt: Date.now(), hasCollectedGift: false, groupId: null,
  });

  ws.send(JSON.stringify({ type: 'INIT', playerId, rooms }));

  ws.on('message', (message) => {
    try {
      const data = JSON.parse(message.toString());
      const player = players.get(playerId);
      if (!player) return;

      switch (data.type) {
        case 'JOIN_ROOM': {
          if (player.roomId && rooms[player.roomId]) {
            delete rooms[player.roomId].players[playerId];
          }
          const target = rooms[data.roomId];
          if (!target) break;

          if (!isRoomJoinable(target)) {
            maybeAddRoom();
            ws.send(JSON.stringify({ type: 'JOIN_ROOM_FAILED', roomId: data.roomId, reason: 'Room locked — try the newest room.' }));
            break;
          }

          player.roomId = data.roomId;
          player.name = data.name || player.name;
          target.players[playerId] = player;
          roomEmptySince.delete(data.roomId);

          broadcastRoom(data.roomId);
          broadcastAllRooms();

          ws.send(JSON.stringify({ type: 'CHAT_HISTORY', messages: roomChatLogs.get(data.roomId) || [] }));
          break;
        }
        case 'LEAVE_ROOM': {
          const roomId = player.roomId;
          if (roomId && rooms[roomId]) {
            const gs = roomStates.get(roomId);
            if (gs && gs.entities[playerId] && !gs.entities[playerId].dead) {
              gs.entities[playerId].dead = true;
              gs.entities[playerId].deathTime = Date.now();
              gs.entities[playerId].deathReason = 'Disconnected';
            }
            delete rooms[roomId].players[playerId];
            if (player.groupId && rooms[roomId].groups[player.groupId]) {
              rooms[roomId].groups[player.groupId].memberIds =
                rooms[roomId].groups[player.groupId].memberIds.filter(id => id !== playerId);
            }
            broadcastRoom(roomId);
          }
          player.roomId = null;
          player.ready = false;
          broadcastAllRooms();
          break;
        }
        case 'UPDATE_STATE': {
          const clean = sanitizeState(data.state);
          if (clean) {
            player.state = clean;
            if (player.roomId) {
              rooms[player.roomId].players[playerId] = player;
              broadcastRoom(player.roomId);
            }
          }
          break;
        }
        case 'SET_READY': {
          player.ready = data.ready;
          if (player.roomId) {
            rooms[player.roomId].players[playerId] = player;
            checkRoomExtinction(player.roomId);
            broadcastRoom(player.roomId);
          }
          break;
        }
        case 'CHAT': {
          if (player.roomId) {
            const entry = { from: player.name, text: data.text, timestamp: Date.now() };
            const log = roomChatLogs.get(player.roomId) || [];
            log.push(entry);
            if (log.length > CHAT_HISTORY_LIMIT) log.splice(0, log.length - CHAT_HISTORY_LIMIT);
            roomChatLogs.set(player.roomId, log);
            broadcastToRoom(player.roomId, JSON.stringify({ type: 'CHAT_MSG', ...entry }));
          }
          break;
        }
        case 'SEND_GIFT': {
          const target = players.get(data.toPlayerId);
          if (!target) break;
          const isNoob = Date.now() - target.joinedAt < 15000 && !target.hasCollectedGift;
          if (isNoob) {
            target.hasCollectedGift = true;
            player.score += 10;
            const result = { type: 'GIFT_RESULT', toPlayerId: target.id, fromId: player.id, accepted: true, giverReward: 10, giverId: player.id };
            ws.send(JSON.stringify(result));
            const targetWs = connections.get(target.id);
            if (targetWs) targetWs.send(JSON.stringify(result));
          } else {
            ws.send(JSON.stringify({ type: 'GIFT_RESULT', toPlayerId: target.id, fromId: player.id, accepted: false, giverReward: 0, giverId: player.id }));
          }
          break;
        }
        case 'CREATE_GROUP':
        case 'JOIN_GROUP': {
          if (!player.roomId) break;
          const room = rooms[player.roomId];
          if (!room) break;

          if (data.type === 'CREATE_GROUP') {
            const gid = uuidv4();
            room.groups[gid] = { id: gid, name: data.name, memberIds: [playerId] };
            player.groupId = gid;
          } else {
            const g = room.groups[data.groupId];
            if (g && !g.memberIds.includes(playerId)) {
              if (player.groupId && room.groups[player.groupId]) {
                room.groups[player.groupId].memberIds =
                  room.groups[player.groupId].memberIds.filter(id => id !== playerId);
              }
              g.memberIds.push(playerId);
              player.groupId = data.groupId;
            }
          }
          broadcastRoom(player.roomId);
          break;
        }
      }
    } catch (e) {
      console.error('WS parse error', e);
    }
  });

  ws.on('close', () => {
    const player = players.get(playerId);
    if (player && player.roomId) {
      const roomId = player.roomId;
      const room = rooms[roomId];
      const gs = roomStates.get(roomId);

      if (gs && gs.entities[playerId] && !gs.entities[playerId].dead) {
        gs.entities[playerId].dead = true;
        gs.entities[playerId].deathTime = Date.now();
        gs.entities[playerId].deathReason = 'Disconnected';
      }

      if (room) {
        delete room.players[playerId];
        if (player.groupId && room.groups[player.groupId]) {
          room.groups[player.groupId].memberIds = room.groups[player.groupId].memberIds.filter(id => id !== playerId);
        }
        broadcastRoom(roomId);
        broadcastAllRooms();
      }
    }
    connections.delete(playerId);
    players.delete(playerId);
  });
});

let globalTick = 0;
setInterval(() => {
  globalTick++;
  let stateChanged = false;
  const now = Date.now();

  if (globalTick % 40 === 0) maybeScaleDownRooms();

  for (const roomId in rooms) {
    const room = rooms[roomId];
    const pCount = Object.keys(room.players).length;
    const realPlayers = Object.values(room.players).filter(p => !p.id.startsWith('bot-'));

    if (room.status === 'LOBBY' && pCount > 0) {
      room.status = 'CRAFTING';
      room.hasRealPlayers = realPlayers.length > 0;
      room.startTime = now;
      stateChanged = true;
    } else if (room.status === 'CRAFTING') {
      if (realPlayers.length > 0 && !room.hasRealPlayers) {
        room.hasRealPlayers = true;
        room.startTime = now - 50000;
        stateChanged = true;
      } else if (realPlayers.length === 0) {
        room.startTime = now;
        room.hasRealPlayers = false;
      }

      const elapsed = now - room.startTime;
      if ((elapsed >= 120000 || (pCount >= 2 && Object.values(room.players).every(p => p.ready))) && realPlayers.length > 0) {
        room.status = 'EXTINCTION';
        room.startTime = now;
        initRoomState(roomId);
        stateChanged = true;
        maybeAddRoom();
      }
    } else if (room.status === 'EXTINCTION') {
      const gs = roomStates.get(roomId);

      if (gs?.winner) {
        if (gs.winnerAt === null) gs.winnerAt = now;
        if (realPlayers.length === 0 || now - gs.winnerAt > RESULTS_DISPLAY_MS) {
          resetRoomToLobby(room);
          stateChanged = true;
        }
        continue;
      }

      if (realPlayers.length === 0 && now - room.startTime > 5000) {
        resetRoomToLobby(room);
        stateChanged = true;
        continue;
      }

      if (!gs) continue;

      const dt = Math.min(0.1, (now - gs.lastTick) / 1000);
      gs.lastTick = now;
      gs.tickCount++;

      const roundElapsed = now - room.startTime;
      let currentRadius = SAFE_ZONE_START;
      let accumTime = 0;
      for (const p of ZONE_PHASES) {
        if (roundElapsed < accumTime + p.waitMs) break;
        accumTime += p.waitMs;
        if (roundElapsed < accumTime + p.shrinkMs) {
          const progress = (roundElapsed - accumTime) / p.shrinkMs;
          currentRadius = currentRadius - (currentRadius - p.targetRadius) * progress;
          break;
        }
        accumTime += p.shrinkMs;
        currentRadius = p.targetRadius;
      }
      gs.safeZoneRadius = currentRadius;
      gs.visualEffects = gs.visualEffects.filter(fx => now - fx.timestamp < 1000);

      const pendingLogs = [];
      let needsPlayerBroadcast = false;

      const isPaired = (id) => gs.matingPairs.some(mp => !mp.done && (mp.a === id || mp.b === id));

      for (const k in gs.entities) {
        if (gs.entities[k].dead && now - (gs.entities[k].deathTime || 0) > 10000) {
          delete gs.entities[k];
        }
      }

      const activeKeys = Object.keys(gs.entities).filter(k => !gs.entities[k].dead);

      for (const k of activeKeys) {
        const e = gs.entities[k];
        for (const otherK of activeKeys) {
          if (k === otherK) continue;
          const other = gs.entities[otherK];
          const dx = e.x - other.x, dy = e.y - other.y;
          const dist = Math.hypot(dx, dy);
          if (dist > 0 && dist < 15) {
            const push = ((15 - dist) / 15) * 10 * dt;
            e.x += (dx / dist) * push; e.y += (dy / dist) * push;
          }
        }
      }

      for (const k of activeKeys) {
        const e = gs.entities[k];
        const stateA = room.players[k]?.state;

        if (!stateA) {
          if (!e.dead) { e.dead = true; e.deathTime = now; e.deathReason = 'No Blueprint'; }
          continue;
        }

        const derivedA = getDerivedStats(stateA, room.biome);

        if (isPaired(k)) {
          const angle = Math.atan2(ARENA_SIZE / 2 - e.y, ARENA_SIZE / 2 - e.x);
          e.x += Math.cos(angle) * derivedA.speed * 0.3 * dt;
          e.y += Math.sin(angle) * derivedA.speed * 0.3 * dt;
          continue;
        }

        const distToCenter = Math.hypot(e.x - ARENA_SIZE / 2, e.y - ARENA_SIZE / 2);
        const outsideZone = distToCenter > gs.safeZoneRadius;

        if (outsideZone) {
          e.targetX = ARENA_SIZE / 2; e.targetY = ARENA_SIZE / 2;
          const overshoot = distToCenter - gs.safeZoneRadius;
          const severity = 1 + Math.min(3, overshoot / 100);
          e.envDamage += ZONE_DAMAGE_RATE * severity * dt;
        }

        let envDmgRate = 0;
        if (room.biome === 'UNDERWATER' && !derivedA.aquatic && stateA.compositions.CNIDARIA < 30 && stateA.attributes.BUOYANCY < 3) {
          envDmgRate = 12;
        } else if (room.biome === 'DESERT') {
          envDmgRate = derivedA.desiccationRate * 4;
        }
        if (envDmgRate > 0) e.envDamage += envDmgRate * dt;

        if (room.biome === 'RAINFOREST' && stateA.compositions.PLANTAE >= 30) {
          e.hunger = Math.max(0, e.hunger - dt * 0.5);
        }

        if (e.envDamage >= derivedA.hp) {
          e.dead = true; e.deathTime = now;
          e.deathReason = distToCenter > gs.safeZoneRadius ? 'Caught in Zone' : (room.biome === 'UNDERWATER' ? 'Drowned' : 'Desiccated');
          pendingLogs.push({ id: Math.random().toString(), attacker: zoneDeathAttacker(room.biome), defender: e.name, attackerWon: true, notes: [e.deathReason] });
          continue;
        }

        const PANIC_RETURN_SPEED = 20;
        const baseSpeed = derivedA.speed * 0.8;
        const moveSpeed = Math.max(baseSpeed, outsideZone ? PANIC_RETURN_SPEED : 0);

        const isBot = k.startsWith('bot-');
        let aiTarget = null;

        if (isBot) {
          const zoneMargin = gs.safeZoneRadius - distToCenter;
          if (zoneMargin < 60) {
            const urgency = 1 - Math.max(0, zoneMargin / 60);
            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) };
          }
          if (!aiTarget && e.hunger > 20) {
            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);
            if (food) aiTarget = { x: food.x, y: food.y };
          }
          if (!aiTarget) {
            for (const otherK of activeKeys) {
              if (otherK === k) continue;
              const other = gs.entities[otherK];
              const dist = Math.hypot(e.x - other.x, e.y - other.y);
              if (dist < derivedA.detection * 0.7) {
                const stateB = room.players[otherK]?.state;
                if (stateB && getDerivedStats(stateB, room.biome).hp > derivedA.hp * 1.3) {
                  const fleeAngle = Math.atan2(e.y - other.y, e.x - other.x);
                  aiTarget = { x: e.x + Math.cos(fleeAngle) * 100, y: e.y + Math.sin(fleeAngle) * 100 };
                  break;
                }
              }
            }
          }
          if (aiTarget) { e.targetX = aiTarget.x; e.targetY = aiTarget.y; }
        }

        if (!outsideZone && !isBot) {
          if (e.hunger > 15) {
            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);
            if (nearFood) { e.targetX = nearFood.x; e.targetY = nearFood.y; }
          } else if (Math.hypot(e.targetX - e.x, e.targetY - e.y) < 12) {
            const a = Math.random() * Math.PI * 2;
            const r = Math.random() * gs.safeZoneRadius * 0.8;
            e.targetX = ARENA_SIZE / 2 + Math.cos(a) * r;
            e.targetY = ARENA_SIZE / 2 + Math.sin(a) * r;
          }
        }

        const moveAngle = Math.atan2(e.targetY - e.y, e.targetX - e.x);
        e.x = Math.max(10, Math.min(ARENA_SIZE - 10, e.x + Math.cos(moveAngle) * moveSpeed * dt));
        e.y = Math.max(10, Math.min(ARENA_SIZE - 10, e.y + Math.sin(moveAngle) * moveSpeed * dt));

        if (e.hunger > 15) {
          const nearFood = gs.foodNodes.find(f => !f.consumed && f.capacity > 0 && Math.hypot(f.x - e.x, f.y - e.y) < 25);
          if (nearFood) {
            const eatAmount = Math.min(e.hunger, 40 * dt, nearFood.capacity);
            nearFood.capacity -= eatAmount;
            e.hunger -= eatAmount;
            if (nearFood.capacity <= 0) nearFood.consumed = true;
          }
        }

        e.hunger += (derivedA.energyDemand / 20) * dt;
        if (e.hunger > HUNGER_THRESHOLD) {
          e.dead = true; e.deathTime = now; e.deathReason = 'Starved';
          pendingLogs.push({ id: Math.random().toString(), attacker: 'Environment', defender: e.name, attackerWon: true, notes: ['Starvation'] });
          continue;
        }

        if (e.matingCooldown > 0) e.matingCooldown = Math.max(0, e.matingCooldown - dt);
        if (e.combatCooldown > 0) e.combatCooldown = Math.max(0, e.combatCooldown - dt);

        for (const otherK of activeKeys) {
          if (k === otherK) continue;
          const other = gs.entities[otherK];
          if (other.dead) continue;
          const stateB = room.players[otherK]?.state;
          if (!stateB) continue;

          const dist = Math.hypot(e.x - other.x, e.y - other.y);
          const combatRange = Math.max(35, moveSpeed * dt * 2 + 20);
          if (dist >= combatRange) continue;

          const canSee = dist < derivedA.detection * 0.6;
          if (!canSee && dist > 40) continue;

          if (stateA.socialType !== 'SOLITARY' && stateA.socialType === stateB.socialType && e.matingCooldown <= 0 && other.matingCooldown <= 0) {
            e.matingCooldown = 15; other.matingCooldown = 15;
            const midX = (e.x + other.x) / 2, midY = (e.y + other.y) / 2;
            gs.matingPairs.push({ a: k, b: otherK, gasX: midX, gasY: midY, startTime: now, done: false });
            break;
          }

          if (e.combatCooldown <= 0 && other.combatCooldown <= 0) {
            const result = resolveCombat(stateA, stateB, room.biome);
            const attackTag = result.breakdown.primaryTag || 'CRUSH';
            const outcome = result.breakdown.isShatter ? 'Shatter' : 'Normal';

            if (result.breakdown.evaded) {
              e.combatCooldown = 1.2; other.combatCooldown = 1.2;
              pendingLogs.push({ id: Math.random().toString(), attacker: e.name, defender: other.name, attackerWon: false, notes: [...result.breakdown.notes, `${other.name} evaded`] });
            } else {
              gs.visualEffects.push({ id: Math.random().toString(), x: (e.x + other.x) / 2, y: (e.y + other.y) / 2, timestamp: now, attackTag, outcome });
              pendingLogs.push({ id: Math.random().toString(), attacker: e.name, defender: other.name, attackerWon: result.won, notes: result.breakdown.notes });
              if (result.won) {
                other.dead = true; other.deathTime = now; other.deathReason = attackTag;
              } else {
                e.dead = true; e.deathTime = now; e.deathReason = attackTag; break;
              }
            }
          }
        }
      }

      gs.matingPairs = gs.matingPairs.filter(mp => now - mp.startTime < 4000).map(mp => {
        if (!mp.done && now - mp.startTime > MATING_SPAWN_DELAY) {
          const stateA = room.players[mp.a]?.state;
          const stateB = room.players[mp.b]?.state;
          if (stateA && stateB && gs.entities[mp.a] && !gs.entities[mp.a].dead) {
            const offId = `offspring-${mp.a}-${gs.tickCount}`;
            const offspringState = breedOffspring(stateA, stateB);

            const distToCenter = Math.hypot(mp.gasX - ARENA_SIZE/2, mp.gasY - ARENA_SIZE/2);
            let spawnX = mp.gasX, spawnY = mp.gasY;
            if (distToCenter > gs.safeZoneRadius - 10) {
              const angle = Math.atan2(mp.gasY - ARENA_SIZE/2, mp.gasX - ARENA_SIZE/2);
              spawnX = ARENA_SIZE/2 + Math.cos(angle) * (gs.safeZoneRadius - 20);
              spawnY = ARENA_SIZE/2 + Math.sin(angle) * (gs.safeZoneRadius - 20);
            }

            gs.entities[offId] = {
              id: offId, name: `${gs.entities[mp.a].name}'s spawn`,
              x: spawnX + (Math.random() - 0.5) * 40, y: spawnY + (Math.random() - 0.5) * 40,
              targetX: spawnX, targetY: spawnY, color: gs.entities[mp.a].color,
              dead: false, hunger: 0, matingCooldown: 5, combatCooldown: 1, offspringCount: 0, envDamage: 0
            };
            gs.entities[mp.a].offspringCount++;
            if (gs.entities[mp.b]) gs.entities[mp.b].offspringCount++;

            room.players[offId] = {
              id: offId, name: gs.entities[offId].name, roomId: roomId,
              state: offspringState, ready: true, score: 0,
              joinedAt: Date.now(), hasCollectedGift: true, groupId: null,
            };

            needsPlayerBroadcast = true;
          }
          return { ...mp, done: true };
        }
        return mp;
      });

      broadcastToRoom(roomId, JSON.stringify({
        type: 'EXTINCTION_TICK',
        state: {
          entities: gs.entities, foodNodes: gs.foodNodes, safeZoneRadius: gs.safeZoneRadius,
          matingPairs: gs.matingPairs, visualEffects: gs.visualEffects
        },
        logs: pendingLogs
      }));

      if (needsPlayerBroadcast) broadcastRoom(roomId);

      const all = Object.values(gs.entities);
      const alive = all.filter(e => !e.dead);

      if ((all.length > 1 && alive.length <= 1) || (all.length === 1 && alive.length === 0)) {
        if (!gs.endingSince) gs.endingSince = now;
      } else if (roundElapsed > MAX_ROUND_DURATION_MS) {
        if (!gs.endingSince) gs.endingSince = now;
      } else {
        gs.endingSince = null;
      }

      if (gs.endingSince && (now - gs.endingSince > 4000) && !gs.winner) {
        if (roundElapsed > MAX_ROUND_DURATION_MS) {
          const ranked = [...alive].sort((a, b) => b.offspringCount - a.offspringCount);
          gs.winner = ranked.length > 0 ? `${ranked[0].name} (sudden death)` : 'No survivors';
        } else {
          gs.winner = alive.length === 1 ? alive[0].name : 'No survivors';
        }
        gs.winnerAt = now;
        broadcastToRoom(roomId, JSON.stringify({ type: 'EXTINCTION_END', winner: gs.winner }));
      }
    }
  }
  if (stateChanged) broadcastAllRooms();
}, 50);