publicstring commited on
Commit
6af9aa9
Β·
verified Β·
1 Parent(s): 24aed14

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +27 -8
app.js CHANGED
@@ -3,16 +3,19 @@ import express from 'express';
3
  import cors from 'cors';
4
  import { WebSocketServer, WebSocket } from 'ws';
5
  import { v4 as uuidv4 } from 'uuid';
 
6
  import {
7
  resolveCombat, getDerivedStats, breedOffspring, INITIAL_STATE,
8
  attributeCap, featureGateReason, getEvolutionPoints, COMPOSITION_ORDER
9
  } from './mechanics.js';
10
 
11
  const app = express();
 
12
  const PORT = process.env.PORT || 7860;
13
 
 
14
  app.use(cors({
15
- origin: '*',
16
  }));
17
 
18
  const MIN_ROOMS = 5;
@@ -25,23 +28,24 @@ const roomEmptySince = new Map();
25
  const roomChatLogs = new Map();
26
  const CHAT_HISTORY_LIMIT = 50;
27
 
 
28
  const BOT_TEMPLATES = [
29
- {
30
  compositions: { ANIMALIA: 100, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
31
  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 },
32
  features: ['CRUSHING_MANDIBLES'], socialType: 'SOLITARY'
33
  },
34
- {
35
  compositions: { ANIMALIA: 40, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 60, MYCELIUM: 0, MINERALIS: 0 },
36
  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 },
37
  features: ['TOXIN_GLANDS', 'GELATINOUS_BODY'], socialType: 'SOLITARY'
38
  },
39
- {
40
  compositions: { ANIMALIA: 100, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
41
  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 },
42
  features: ['SLASHING_BLADES'], socialType: 'PACK'
43
  },
44
- {
45
  compositions: { ANIMALIA: 50, CHITINARIA: 50, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
46
  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 },
47
  features: ['SCORPION_TAIL'], socialType: 'SOLITARY'
@@ -52,11 +56,13 @@ const BOT_NAMES = ['Alpha', 'Beta', 'Gamma', 'Delta', 'Omega', 'Zeta', 'Sigma',
52
 
53
  function populateBots(room, guaranteeBot = false) {
54
  if (!guaranteeBot && Math.random() > 0.5) return;
55
- const numBots = Math.floor(Math.random() * 2) + 1;
 
 
56
  for (let i = 0; i < numBots; i++) {
57
  const botId = `bot-${uuidv4()}`;
58
  const template = BOT_TEMPLATES[Math.floor(Math.random() * BOT_TEMPLATES.length)];
59
- const randomName = `Bot ${BOT_NAMES[Math.floor(Math.random() * BOT_NAMES.length)]}`;
60
  room.players[botId] = {
61
  id: botId, name: randomName, roomId: room.id,
62
  state: JSON.parse(JSON.stringify(template)), ready: true,
@@ -163,6 +169,9 @@ function zoneDeathAttacker(biome) {
163
  }
164
  }
165
 
 
 
 
166
  function sanitizeState(raw) {
167
  try {
168
  const s = {
@@ -184,7 +193,7 @@ function sanitizeState(raw) {
184
  s.features = s.features.filter(f => !featureGateReason(f, s.compositions));
185
 
186
  const ep = getEvolutionPoints(s);
187
- if (ep.used > ep.max) return null;
188
 
189
  return s;
190
  } catch {
@@ -192,9 +201,11 @@ function sanitizeState(raw) {
192
  }
193
  }
194
 
 
195
  app.get('/api/health', (req, res) => res.json({ status: 'ok', roomsCount: Object.keys(rooms).length }));
196
  app.get('/', (req, res) => res.send('Level Evolution standalone JS server running.'));
197
 
 
198
  const server = app.listen(PORT, '0.0.0.0', () => console.log(`Standalone Backend running on port ${PORT}`));
199
  const wss = new WebSocketServer({ server });
200
 
@@ -344,6 +355,8 @@ wss.on('connection', (ws) => {
344
  broadcastRoom(player.roomId);
345
  }
346
  }
 
 
347
  break;
348
  }
349
  case 'SET_READY': {
@@ -439,6 +452,7 @@ wss.on('connection', (ws) => {
439
  });
440
  });
441
 
 
442
  let globalTick = 0;
443
  setInterval(() => {
444
  globalTick++;
@@ -529,6 +543,7 @@ setInterval(() => {
529
 
530
  const activeKeys = Object.keys(gs.entities).filter(k => !gs.entities[k].dead);
531
 
 
532
  for (const k of activeKeys) {
533
  const e = gs.entities[k];
534
  for (const otherK of activeKeys) {
@@ -579,6 +594,7 @@ setInterval(() => {
579
  }
580
  if (envDmgRate > 0) e.envDamage += envDmgRate * dt;
581
 
 
582
  if (room.biome === 'RAINFOREST' && stateA.compositions.PLANTAE >= 30) {
583
  e.hunger = Math.max(0, e.hunger - dt * 0.5);
584
  }
@@ -594,6 +610,7 @@ setInterval(() => {
594
  const baseSpeed = derivedA.speed * 0.8;
595
  const moveSpeed = Math.max(baseSpeed, outsideZone ? PANIC_RETURN_SPEED : 0);
596
 
 
597
  const isBot = k.startsWith('bot-');
598
  let aiTarget = null;
599
 
@@ -661,6 +678,7 @@ setInterval(() => {
661
  if (e.matingCooldown > 0) e.matingCooldown = Math.max(0, e.matingCooldown - dt);
662
  if (e.combatCooldown > 0) e.combatCooldown = Math.max(0, e.combatCooldown - dt);
663
 
 
664
  for (const otherK of activeKeys) {
665
  if (k === otherK) continue;
666
  const other = gs.entities[otherK];
@@ -752,6 +770,7 @@ setInterval(() => {
752
 
753
  if (needsPlayerBroadcast) broadcastRoom(roomId);
754
 
 
755
  const all = Object.values(gs.entities);
756
  const alive = all.filter(e => !e.dead);
757
 
 
3
  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 {
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)
14
  const PORT = process.env.PORT || 7860;
15
 
16
+ // Enable CORS so your separate frontend can communicate
17
  app.use(cors({
18
+ origin: '*', // Set to your specific frontend URL in production for security
19
  }));
20
 
21
  const MIN_ROOMS = 5;
 
28
  const roomChatLogs = new Map();
29
  const CHAT_HISTORY_LIMIT = 50;
30
 
31
+ // ─── BOT TEMPLATES ───────────────────────────────────────────────────────────────
32
  const BOT_TEMPLATES = [
33
+ { // The Bruiser
34
  compositions: { ANIMALIA: 100, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
35
  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 },
36
  features: ['CRUSHING_MANDIBLES'], socialType: 'SOLITARY'
37
  },
38
+ { // The Toxic Jelly
39
  compositions: { ANIMALIA: 40, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 60, MYCELIUM: 0, MINERALIS: 0 },
40
  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 },
41
  features: ['TOXIN_GLANDS', 'GELATINOUS_BODY'], socialType: 'SOLITARY'
42
  },
43
+ { // The Sprinter
44
  compositions: { ANIMALIA: 100, CHITINARIA: 0, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
45
  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 },
46
  features: ['SLASHING_BLADES'], socialType: 'PACK'
47
  },
48
+ { // The Desert Stalker
49
  compositions: { ANIMALIA: 50, CHITINARIA: 50, PLANTAE: 0, CNIDARIA: 0, MYCELIUM: 0, MINERALIS: 0 },
50
  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 },
51
  features: ['SCORPION_TAIL'], socialType: 'SOLITARY'
 
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
+ const numBots = Math.floor(Math.random() * 6) + 8;
61
+
62
  for (let i = 0; i < numBots; i++) {
63
  const botId = `bot-${uuidv4()}`;
64
  const template = BOT_TEMPLATES[Math.floor(Math.random() * BOT_TEMPLATES.length)];
65
+ const randomName = `${BOT_NAMES[Math.floor(Math.random() * BOT_NAMES.length)]}`;
66
  room.players[botId] = {
67
  id: botId, name: randomName, roomId: room.id,
68
  state: JSON.parse(JSON.stringify(template)), ready: true,
 
169
  }
170
  }
171
 
172
+ // ─── STATE SANITIZATION ───────────────────────────────────────────────────────────
173
+ // The server is authoritative for combat, so a client-submitted CreatureState must
174
+ // never be trusted verbatim β€” clamp caps, drop ungated features, reject over-budget builds.
175
  function sanitizeState(raw) {
176
  try {
177
  const s = {
 
193
  s.features = s.features.filter(f => !featureGateReason(f, s.compositions));
194
 
195
  const ep = getEvolutionPoints(s);
196
+ if (ep.used > ep.max) return null; // over budget β€” reject, caller keeps last valid state
197
 
198
  return s;
199
  } catch {
 
201
  }
202
  }
203
 
204
+ // REST health checks
205
  app.get('/api/health', (req, res) => res.json({ status: 'ok', roomsCount: Object.keys(rooms).length }));
206
  app.get('/', (req, res) => res.send('Level Evolution standalone JS server running.'));
207
 
208
+ // Launch Server
209
  const server = app.listen(PORT, '0.0.0.0', () => console.log(`Standalone Backend running on port ${PORT}`));
210
  const wss = new WebSocketServer({ server });
211
 
 
355
  broadcastRoom(player.roomId);
356
  }
357
  }
358
+ // if sanitization rejected the payload (over EP budget / malformed), we
359
+ // silently keep the last valid state β€” the client resends on every change anyway
360
  break;
361
  }
362
  case 'SET_READY': {
 
452
  });
453
  });
454
 
455
+ // ─── EXTINCTION TICK LOOP (20Hz) ──────────────────────────────────────────────────
456
  let globalTick = 0;
457
  setInterval(() => {
458
  globalTick++;
 
543
 
544
  const activeKeys = Object.keys(gs.entities).filter(k => !gs.entities[k].dead);
545
 
546
+ // Separation
547
  for (const k of activeKeys) {
548
  const e = gs.entities[k];
549
  for (const otherK of activeKeys) {
 
594
  }
595
  if (envDmgRate > 0) e.envDamage += envDmgRate * dt;
596
 
597
+ // Plantae passive regen in Rainforest β€” the composition's "free energy in light" bonus
598
  if (room.biome === 'RAINFOREST' && stateA.compositions.PLANTAE >= 30) {
599
  e.hunger = Math.max(0, e.hunger - dt * 0.5);
600
  }
 
610
  const baseSpeed = derivedA.speed * 0.8;
611
  const moveSpeed = Math.max(baseSpeed, outsideZone ? PANIC_RETURN_SPEED : 0);
612
 
613
+ // Bot AI
614
  const isBot = k.startsWith('bot-');
615
  let aiTarget = null;
616
 
 
678
  if (e.matingCooldown > 0) e.matingCooldown = Math.max(0, e.matingCooldown - dt);
679
  if (e.combatCooldown > 0) e.combatCooldown = Math.max(0, e.combatCooldown - dt);
680
 
681
+ // Combat
682
  for (const otherK of activeKeys) {
683
  if (k === otherK) continue;
684
  const other = gs.entities[otherK];
 
770
 
771
  if (needsPlayerBroadcast) broadcastRoom(roomId);
772
 
773
+ // === DELAYED WINNER CHECK ===
774
  const all = Object.values(gs.entities);
775
  const alive = all.filter(e => !e.dead);
776