publicstring commited on
Commit
b903329
·
verified ·
1 Parent(s): 14b67cf

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +100 -31
app.js CHANGED
@@ -4,7 +4,10 @@ import cors from 'cors';
4
  import { WebSocketServer, WebSocket } from 'ws';
5
  import { v4 as uuidv4 } from 'uuid';
6
  // Make sure this points to your JS mechanics file
7
- import { resolveCombat, getDerivedStats, breedOffspring, INITIAL_STATE } from './mechanics.js';
 
 
 
8
 
9
  const app = express();
10
  // Hugging Face Spaces and other cloud PaaS use process.env.PORT (HF uses 7860)
@@ -18,7 +21,7 @@ app.use(cors({
18
  const MIN_ROOMS = 5;
19
  const ROOM_SAFETY_CAP = 200;
20
  const ROOM_EMPTY_GRACE_MS = 15000;
21
- let roomCounter = 0; // RESTORED
22
 
23
  const rooms = {};
24
  const roomEmptySince = new Map();
@@ -53,14 +56,14 @@ const BOT_NAMES = ['Alpha', 'Beta', 'Gamma', 'Delta', 'Omega', 'Zeta', 'Sigma',
53
 
54
  function populateBots(room, guaranteeBot = false) {
55
  if (!guaranteeBot && Math.random() > 0.5) return;
56
- const numBots = Math.floor(Math.random() * 2) + 1;
57
  for (let i = 0; i < numBots; i++) {
58
  const botId = `bot-${uuidv4()}`;
59
  const template = BOT_TEMPLATES[Math.floor(Math.random() * BOT_TEMPLATES.length)];
60
  const randomName = `Bot ${BOT_NAMES[Math.floor(Math.random() * BOT_NAMES.length)]}`;
61
  room.players[botId] = {
62
  id: botId, name: randomName, roomId: room.id,
63
- state: JSON.parse(JSON.stringify(template)), ready: true,
64
  score: 0, joinedAt: Date.now(), hasCollectedGift: true, groupId: null
65
  };
66
  }
@@ -116,7 +119,7 @@ function resetRoomToLobby(room) {
116
  for (const pid of Object.keys(room.players)) {
117
  if (pid.startsWith('offspring-') || pid.startsWith('bot-')) { delete room.players[pid]; continue; }
118
  room.players[pid].ready = false;
119
- room.players[pid].state = JSON.parse(JSON.stringify(INITIAL_STATE));
120
  }
121
  populateBots(room, false);
122
  roomStates.delete(room.id);
@@ -144,7 +147,7 @@ function initRoomState(roomId) {
144
  });
145
 
146
  const food = Array.from({ length: FOOD_COUNT }).map(() => ({
147
- x: 50 + Math.random() * (ARENA_SIZE - 100), y: 50 + Math.random() * (ARENA_SIZE - 100),
148
  consumed: false, capacity: 100,
149
  }));
150
 
@@ -164,6 +167,38 @@ function zoneDeathAttacker(biome) {
164
  }
165
  }
166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  // REST health checks
168
  app.get('/api/health', (req, res) => res.json({ status: 'ok', roomsCount: Object.keys(rooms).length }));
169
  app.get('/', (req, res) => res.send('Level Evolution standalone JS server running.'));
@@ -281,7 +316,7 @@ wss.on('connection', (ws) => {
281
  player.name = data.name || player.name;
282
  target.players[playerId] = player;
283
  roomEmptySince.delete(data.roomId);
284
-
285
  broadcastRoom(data.roomId);
286
  broadcastAllRooms();
287
 
@@ -289,11 +324,16 @@ wss.on('connection', (ws) => {
289
  break;
290
  }
291
  case 'UPDATE_STATE': {
292
- player.state = data.state;
293
- if (player.roomId) {
294
- rooms[player.roomId].players[playerId] = player;
295
- broadcastRoom(player.roomId);
 
 
 
296
  }
 
 
297
  break;
298
  }
299
  case 'SET_READY': {
@@ -332,6 +372,30 @@ wss.on('connection', (ws) => {
332
  }
333
  break;
334
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
  }
336
  } catch (e) {
337
  console.error('WS parse error', e);
@@ -344,7 +408,7 @@ wss.on('connection', (ws) => {
344
  const roomId = player.roomId;
345
  const room = rooms[roomId];
346
  const gs = roomStates.get(roomId);
347
-
348
  if (gs && gs.entities[playerId] && !gs.entities[playerId].dead) {
349
  gs.entities[playerId].dead = true;
350
  gs.entities[playerId].deathTime = Date.now();
@@ -387,10 +451,10 @@ setInterval(() => {
387
  } else if (room.status === 'CRAFTING') {
388
  if (realPlayers.length > 0 && !room.hasRealPlayers) {
389
  room.hasRealPlayers = true;
390
- room.startTime = now - 50000;
391
  stateChanged = true;
392
  } else if (realPlayers.length === 0) {
393
- room.startTime = now;
394
  room.hasRealPlayers = false;
395
  }
396
 
@@ -447,7 +511,7 @@ setInterval(() => {
447
  let needsPlayerBroadcast = false;
448
 
449
  const isPaired = (id) => gs.matingPairs.some(mp => !mp.done && (mp.a === id || mp.b === id));
450
-
451
  for (const k in gs.entities) {
452
  if (gs.entities[k].dead && now - (gs.entities[k].deathTime || 0) > 10000) {
453
  delete gs.entities[k];
@@ -474,7 +538,7 @@ setInterval(() => {
474
  for (const k of activeKeys) {
475
  const e = gs.entities[k];
476
  const stateA = room.players[k]?.state;
477
-
478
  if (!stateA) {
479
  if (!e.dead) { e.dead = true; e.deathTime = now; e.deathReason = 'No Blueprint'; }
480
  continue;
@@ -486,12 +550,12 @@ setInterval(() => {
486
  const angle = Math.atan2(ARENA_SIZE / 2 - e.y, ARENA_SIZE / 2 - e.x);
487
  e.x += Math.cos(angle) * derivedA.speed * 0.3 * dt;
488
  e.y += Math.sin(angle) * derivedA.speed * 0.3 * dt;
489
- continue;
490
  }
491
 
492
  const distToCenter = Math.hypot(e.x - ARENA_SIZE / 2, e.y - ARENA_SIZE / 2);
493
  const outsideZone = distToCenter > gs.safeZoneRadius;
494
-
495
  if (outsideZone) {
496
  e.targetX = ARENA_SIZE / 2; e.targetY = ARENA_SIZE / 2;
497
  const overshoot = distToCenter - gs.safeZoneRadius;
@@ -501,12 +565,17 @@ setInterval(() => {
501
 
502
  let envDmgRate = 0;
503
  if (room.biome === 'UNDERWATER' && !derivedA.aquatic && stateA.compositions.CNIDARIA < 30 && stateA.attributes.BUOYANCY < 3) {
504
- envDmgRate = 12;
505
  } else if (room.biome === 'DESERT') {
506
- envDmgRate = derivedA.desiccationRate * 4;
507
  }
508
  if (envDmgRate > 0) e.envDamage += envDmgRate * dt;
509
 
 
 
 
 
 
510
  if (e.envDamage >= derivedA.hp) {
511
  e.dead = true; e.deathTime = now;
512
  e.deathReason = distToCenter > gs.safeZoneRadius ? 'Caught in Zone' : (room.biome === 'UNDERWATER' ? 'Drowned' : 'Desiccated');
@@ -514,7 +583,7 @@ setInterval(() => {
514
  continue;
515
  }
516
 
517
- const PANIC_RETURN_SPEED = 20;
518
  const baseSpeed = derivedA.speed * 0.8;
519
  const moveSpeed = Math.max(baseSpeed, outsideZone ? PANIC_RETURN_SPEED : 0);
520
 
@@ -576,7 +645,7 @@ setInterval(() => {
576
  }
577
  }
578
 
579
- e.hunger += (derivedA.energyDemand / 20) * dt;
580
  if (e.hunger > HUNGER_THRESHOLD) {
581
  e.dead = true; e.deathTime = now; e.deathReason = 'Starved';
582
  pendingLogs.push({ id: Math.random().toString(), attacker: 'Environment', defender: e.name, attackerWon: true, notes: ['Starvation'] });
@@ -595,7 +664,7 @@ setInterval(() => {
595
  if (!stateB) continue;
596
 
597
  const dist = Math.hypot(e.x - other.x, e.y - other.y);
598
- const combatRange = Math.max(35, moveSpeed * dt * 2 + 20);
599
  if (dist >= combatRange) continue;
600
 
601
  const canSee = dist < derivedA.detection * 0.6;
@@ -619,10 +688,10 @@ setInterval(() => {
619
  } else {
620
  gs.visualEffects.push({ id: Math.random().toString(), x: (e.x + other.x) / 2, y: (e.y + other.y) / 2, timestamp: now, attackTag, outcome });
621
  pendingLogs.push({ id: Math.random().toString(), attacker: e.name, defender: other.name, attackerWon: result.won, notes: result.breakdown.notes });
622
- if (result.won) {
623
  other.dead = true; other.deathTime = now; other.deathReason = attackTag;
624
- } else {
625
- e.dead = true; e.deathTime = now; e.deathReason = attackTag; break;
626
  }
627
  }
628
  }
@@ -636,7 +705,7 @@ setInterval(() => {
636
  if (stateA && stateB && gs.entities[mp.a] && !gs.entities[mp.a].dead) {
637
  const offId = `offspring-${mp.a}-${gs.tickCount}`;
638
  const offspringState = breedOffspring(stateA, stateB);
639
-
640
  const distToCenter = Math.hypot(mp.gasX - ARENA_SIZE/2, mp.gasY - ARENA_SIZE/2);
641
  let spawnX = mp.gasX, spawnY = mp.gasY;
642
  if (distToCenter > gs.safeZoneRadius - 10) {
@@ -681,13 +750,13 @@ setInterval(() => {
681
  // === DELAYED WINNER CHECK ===
682
  const all = Object.values(gs.entities);
683
  const alive = all.filter(e => !e.dead);
684
-
685
  if ((all.length > 1 && alive.length <= 1) || (all.length === 1 && alive.length === 0)) {
686
- if (!gs.endingSince) gs.endingSince = now;
687
  } else if (roundElapsed > MAX_ROUND_DURATION_MS) {
688
- if (!gs.endingSince) gs.endingSince = now;
689
  } else {
690
- gs.endingSince = null;
691
  }
692
 
693
  if (gs.endingSince && (now - gs.endingSince > 4000) && !gs.winner) {
 
4
  import { WebSocketServer, WebSocket } from 'ws';
5
  import { v4 as uuidv4 } from 'uuid';
6
  // Make sure this points to your JS mechanics file
7
+ import {
8
+ resolveCombat, getDerivedStats, breedOffspring, INITIAL_STATE,
9
+ attributeCap, featureGateReason, getEvolutionPoints, COMPOSITION_ORDER
10
+ } from './mechanics.js';
11
 
12
  const app = express();
13
  // Hugging Face Spaces and other cloud PaaS use process.env.PORT (HF uses 7860)
 
21
  const MIN_ROOMS = 5;
22
  const ROOM_SAFETY_CAP = 200;
23
  const ROOM_EMPTY_GRACE_MS = 15000;
24
+ let roomCounter = 0;
25
 
26
  const rooms = {};
27
  const roomEmptySince = new Map();
 
56
 
57
  function populateBots(room, guaranteeBot = false) {
58
  if (!guaranteeBot && Math.random() > 0.5) return;
59
+ const numBots = Math.floor(Math.random() * 2) + 1;
60
  for (let i = 0; i < numBots; i++) {
61
  const botId = `bot-${uuidv4()}`;
62
  const template = BOT_TEMPLATES[Math.floor(Math.random() * BOT_TEMPLATES.length)];
63
  const randomName = `Bot ${BOT_NAMES[Math.floor(Math.random() * BOT_NAMES.length)]}`;
64
  room.players[botId] = {
65
  id: botId, name: randomName, roomId: room.id,
66
+ state: JSON.parse(JSON.stringify(template)), ready: true,
67
  score: 0, joinedAt: Date.now(), hasCollectedGift: true, groupId: null
68
  };
69
  }
 
119
  for (const pid of Object.keys(room.players)) {
120
  if (pid.startsWith('offspring-') || pid.startsWith('bot-')) { delete room.players[pid]; continue; }
121
  room.players[pid].ready = false;
122
+ room.players[pid].state = JSON.parse(JSON.stringify(INITIAL_STATE));
123
  }
124
  populateBots(room, false);
125
  roomStates.delete(room.id);
 
147
  });
148
 
149
  const food = Array.from({ length: FOOD_COUNT }).map(() => ({
150
+ x: 50 + Math.random() * (ARENA_SIZE - 100), y: 50 + Math.random() * (ARENA_SIZE - 100),
151
  consumed: false, capacity: 100,
152
  }));
153
 
 
167
  }
168
  }
169
 
170
+ // ─── STATE SANITIZATION ───────────────────────────────────────────────────────────
171
+ // The server is authoritative for combat, so a client-submitted CreatureState must
172
+ // never be trusted verbatim — clamp caps, drop ungated features, reject over-budget builds.
173
+ function sanitizeState(raw) {
174
+ try {
175
+ const s = {
176
+ compositions: { ...INITIAL_STATE.compositions, ...(raw?.compositions || {}) },
177
+ attributes: { ...INITIAL_STATE.attributes, ...(raw?.attributes || {}) },
178
+ features: Array.isArray(raw?.features) ? raw.features.slice(0, 5) : [],
179
+ socialType: ['SOLITARY', 'PACK', 'HIVE'].includes(raw?.socialType) ? raw.socialType : 'SOLITARY',
180
+ };
181
+
182
+ const compSum = COMPOSITION_ORDER.reduce((sum, k) => sum + (Number(s.compositions[k]) || 0), 0);
183
+ if (Math.abs(compSum - 100) > 2) return JSON.parse(JSON.stringify(INITIAL_STATE));
184
+
185
+ for (const k of Object.keys(s.attributes)) {
186
+ const cap = attributeCap(k, s.compositions);
187
+ const val = Number(s.attributes[k]) || 0;
188
+ s.attributes[k] = Math.max(0, Math.min(val, cap));
189
+ }
190
+
191
+ s.features = s.features.filter(f => !featureGateReason(f, s.compositions));
192
+
193
+ const ep = getEvolutionPoints(s);
194
+ if (ep.used > ep.max) return null; // over budget — reject, caller keeps last valid state
195
+
196
+ return s;
197
+ } catch {
198
+ return null;
199
+ }
200
+ }
201
+
202
  // REST health checks
203
  app.get('/api/health', (req, res) => res.json({ status: 'ok', roomsCount: Object.keys(rooms).length }));
204
  app.get('/', (req, res) => res.send('Level Evolution standalone JS server running.'));
 
316
  player.name = data.name || player.name;
317
  target.players[playerId] = player;
318
  roomEmptySince.delete(data.roomId);
319
+
320
  broadcastRoom(data.roomId);
321
  broadcastAllRooms();
322
 
 
324
  break;
325
  }
326
  case 'UPDATE_STATE': {
327
+ const clean = sanitizeState(data.state);
328
+ if (clean) {
329
+ player.state = clean;
330
+ if (player.roomId) {
331
+ rooms[player.roomId].players[playerId] = player;
332
+ broadcastRoom(player.roomId);
333
+ }
334
  }
335
+ // if sanitization rejected the payload (over EP budget / malformed), we
336
+ // silently keep the last valid state — the client resends on every change anyway
337
  break;
338
  }
339
  case 'SET_READY': {
 
372
  }
373
  break;
374
  }
375
+ case 'CREATE_GROUP':
376
+ case 'JOIN_GROUP': {
377
+ if (!player.roomId) break;
378
+ const room = rooms[player.roomId];
379
+ if (!room) break;
380
+
381
+ if (data.type === 'CREATE_GROUP') {
382
+ const gid = uuidv4();
383
+ room.groups[gid] = { id: gid, name: data.name, memberIds: [playerId] };
384
+ player.groupId = gid;
385
+ } else {
386
+ const g = room.groups[data.groupId];
387
+ if (g && !g.memberIds.includes(playerId)) {
388
+ if (player.groupId && room.groups[player.groupId]) {
389
+ room.groups[player.groupId].memberIds =
390
+ room.groups[player.groupId].memberIds.filter(id => id !== playerId);
391
+ }
392
+ g.memberIds.push(playerId);
393
+ player.groupId = data.groupId;
394
+ }
395
+ }
396
+ broadcastRoom(player.roomId);
397
+ break;
398
+ }
399
  }
400
  } catch (e) {
401
  console.error('WS parse error', e);
 
408
  const roomId = player.roomId;
409
  const room = rooms[roomId];
410
  const gs = roomStates.get(roomId);
411
+
412
  if (gs && gs.entities[playerId] && !gs.entities[playerId].dead) {
413
  gs.entities[playerId].dead = true;
414
  gs.entities[playerId].deathTime = Date.now();
 
451
  } else if (room.status === 'CRAFTING') {
452
  if (realPlayers.length > 0 && !room.hasRealPlayers) {
453
  room.hasRealPlayers = true;
454
+ room.startTime = now - 50000;
455
  stateChanged = true;
456
  } else if (realPlayers.length === 0) {
457
+ room.startTime = now;
458
  room.hasRealPlayers = false;
459
  }
460
 
 
511
  let needsPlayerBroadcast = false;
512
 
513
  const isPaired = (id) => gs.matingPairs.some(mp => !mp.done && (mp.a === id || mp.b === id));
514
+
515
  for (const k in gs.entities) {
516
  if (gs.entities[k].dead && now - (gs.entities[k].deathTime || 0) > 10000) {
517
  delete gs.entities[k];
 
538
  for (const k of activeKeys) {
539
  const e = gs.entities[k];
540
  const stateA = room.players[k]?.state;
541
+
542
  if (!stateA) {
543
  if (!e.dead) { e.dead = true; e.deathTime = now; e.deathReason = 'No Blueprint'; }
544
  continue;
 
550
  const angle = Math.atan2(ARENA_SIZE / 2 - e.y, ARENA_SIZE / 2 - e.x);
551
  e.x += Math.cos(angle) * derivedA.speed * 0.3 * dt;
552
  e.y += Math.sin(angle) * derivedA.speed * 0.3 * dt;
553
+ continue;
554
  }
555
 
556
  const distToCenter = Math.hypot(e.x - ARENA_SIZE / 2, e.y - ARENA_SIZE / 2);
557
  const outsideZone = distToCenter > gs.safeZoneRadius;
558
+
559
  if (outsideZone) {
560
  e.targetX = ARENA_SIZE / 2; e.targetY = ARENA_SIZE / 2;
561
  const overshoot = distToCenter - gs.safeZoneRadius;
 
565
 
566
  let envDmgRate = 0;
567
  if (room.biome === 'UNDERWATER' && !derivedA.aquatic && stateA.compositions.CNIDARIA < 30 && stateA.attributes.BUOYANCY < 3) {
568
+ envDmgRate = 12;
569
  } else if (room.biome === 'DESERT') {
570
+ envDmgRate = derivedA.desiccationRate * 4;
571
  }
572
  if (envDmgRate > 0) e.envDamage += envDmgRate * dt;
573
 
574
+ // Plantae passive regen in Rainforest — the composition's "free energy in light" bonus
575
+ if (room.biome === 'RAINFOREST' && stateA.compositions.PLANTAE >= 30) {
576
+ e.hunger = Math.max(0, e.hunger - dt * 0.5);
577
+ }
578
+
579
  if (e.envDamage >= derivedA.hp) {
580
  e.dead = true; e.deathTime = now;
581
  e.deathReason = distToCenter > gs.safeZoneRadius ? 'Caught in Zone' : (room.biome === 'UNDERWATER' ? 'Drowned' : 'Desiccated');
 
583
  continue;
584
  }
585
 
586
+ const PANIC_RETURN_SPEED = 20;
587
  const baseSpeed = derivedA.speed * 0.8;
588
  const moveSpeed = Math.max(baseSpeed, outsideZone ? PANIC_RETURN_SPEED : 0);
589
 
 
645
  }
646
  }
647
 
648
+ e.hunger += (derivedA.energyDemand / 20) * dt;
649
  if (e.hunger > HUNGER_THRESHOLD) {
650
  e.dead = true; e.deathTime = now; e.deathReason = 'Starved';
651
  pendingLogs.push({ id: Math.random().toString(), attacker: 'Environment', defender: e.name, attackerWon: true, notes: ['Starvation'] });
 
664
  if (!stateB) continue;
665
 
666
  const dist = Math.hypot(e.x - other.x, e.y - other.y);
667
+ const combatRange = Math.max(35, moveSpeed * dt * 2 + 20);
668
  if (dist >= combatRange) continue;
669
 
670
  const canSee = dist < derivedA.detection * 0.6;
 
688
  } else {
689
  gs.visualEffects.push({ id: Math.random().toString(), x: (e.x + other.x) / 2, y: (e.y + other.y) / 2, timestamp: now, attackTag, outcome });
690
  pendingLogs.push({ id: Math.random().toString(), attacker: e.name, defender: other.name, attackerWon: result.won, notes: result.breakdown.notes });
691
+ if (result.won) {
692
  other.dead = true; other.deathTime = now; other.deathReason = attackTag;
693
+ } else {
694
+ e.dead = true; e.deathTime = now; e.deathReason = attackTag; break;
695
  }
696
  }
697
  }
 
705
  if (stateA && stateB && gs.entities[mp.a] && !gs.entities[mp.a].dead) {
706
  const offId = `offspring-${mp.a}-${gs.tickCount}`;
707
  const offspringState = breedOffspring(stateA, stateB);
708
+
709
  const distToCenter = Math.hypot(mp.gasX - ARENA_SIZE/2, mp.gasY - ARENA_SIZE/2);
710
  let spawnX = mp.gasX, spawnY = mp.gasY;
711
  if (distToCenter > gs.safeZoneRadius - 10) {
 
750
  // === DELAYED WINNER CHECK ===
751
  const all = Object.values(gs.entities);
752
  const alive = all.filter(e => !e.dead);
753
+
754
  if ((all.length > 1 && alive.length <= 1) || (all.length === 1 && alive.length === 0)) {
755
+ if (!gs.endingSince) gs.endingSince = now;
756
  } else if (roundElapsed > MAX_ROUND_DURATION_MS) {
757
+ if (!gs.endingSince) gs.endingSince = now;
758
  } else {
759
+ gs.endingSince = null;
760
  }
761
 
762
  if (gs.endingSince && (now - gs.endingSince > 4000) && !gs.winner) {