-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspectatorServer.js
More file actions
772 lines (686 loc) · 25.5 KB
/
Copy pathspectatorServer.js
File metadata and controls
772 lines (686 loc) · 25.5 KB
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
import http from "node:http";
import path from "node:path";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
import { WebSocketServer } from "ws";
import { createAgent } from "./Agent.js";
import { createGameState, addHeroToGame, getFullGameStatus } from "./GameState.js";
import { processTick } from "./CombatEngine.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const PORT = Number(process.env.PORT || 3000);
const TICK_RATE = Number(process.env.TICK_RATE || 10);
const BROADCAST_RATE = Number(process.env.BROADCAST_RATE || 10);
const DATA_DIR = path.join(__dirname, "data");
const REWARD_LEDGER_FILE = path.join(DATA_DIR, "reward-ledger.json");
const PLAYER_BALANCES_FILE = path.join(DATA_DIR, "player-balances.json");
const WOA_PER_GOLD = 1 / 20;
const WOA_PER_ROUND_CAP = 120;
const DAILY_SOFT_CAP = 900;
const DAILY_HARD_CAP = 1500;
const CLAIM_THRESHOLD = 100;
const CLAIM_COOLDOWN_MS = 10 * 60 * 1000; // 10 minutes
const PARTICIPATION_GATE = 0.35;
const FIGHT_CLUB_ROUNDS = [
{
id: "humans-vs-orcs",
title: "Round 1: Human Legion vs Orc Horde",
subtitle: "Footmen, Archers & Knights charge into battle",
durationTicks: 800,
spawnConfig: {
mid: { spawnEvery: 1, maxPerSide: 120, burst: 6, allianceType: ["FOOTMAN", "ARCHER", "KNIGHT"], hordeType: ["GRUNT", "TROLL", "OGRE"] },
},
allianceHero: {
name: "Lord Commander Uther",
classType: "WARRIOR",
lane: "mid",
hpScale: 2.0,
damageScale: 1.5,
manaScale: 1.0,
},
hordeHero: {
name: "Warchief Thrall",
classType: "WARRIOR",
lane: "mid",
hpScale: 2.2,
damageScale: 1.4,
manaScale: 1.2,
},
},
{
id: "elves-vs-trolls",
title: "Round 2: High Elves vs Forest Trolls",
subtitle: "Arcane archers and mages against feral warriors",
durationTicks: 800,
spawnConfig: {
mid: { spawnEvery: 1, maxPerSide: 140, burst: 8, allianceType: ["RIFLEMAN", "ARCHER", "BATTLE_MAGE"], hordeType: ["TROLL", "TROLL_AXER", "WOLF_RIDER"] },
},
allianceHero: {
name: "Archmage Antonidas",
classType: "MAGE",
lane: "mid",
hpScale: 1.2,
damageScale: 2.0,
manaScale: 2.0,
},
hordeHero: {
name: "Shadow Hunter Vol'jin",
classType: "HEALER",
lane: "mid",
hpScale: 1.4,
damageScale: 1.2,
manaScale: 1.8,
},
},
{
id: "knights-vs-ogres",
title: "Round 3: Death Knights vs Ogre Warlords",
subtitle: "Dark cavalry and siege engines clash",
durationTicks: 900,
spawnConfig: {
mid: { spawnEvery: 1, maxPerSide: 100, burst: 5, allianceType: ["DEATH_KNIGHT", "KNIGHT", "BALLISTA"], hordeType: ["OGRE", "OGRE_LORD", "CATAPULT"] },
},
allianceHero: {
name: "Death Knight Arthas",
classType: "WARRIOR",
lane: "mid",
hpScale: 2.5,
damageScale: 1.8,
manaScale: 0.8,
},
hordeHero: {
name: "Ogre Chief Grom",
classType: "WARRIOR",
lane: "mid",
hpScale: 3.0,
damageScale: 2.2,
manaScale: 0.5,
},
},
{
id: "siege_legions",
title: "Round 4: Grand Siege",
subtitle: "All units - Knights, Ballistas, Giants",
durationTicks: 1000,
spawnConfig: {
mid: { spawnEvery: 1, maxPerSide: 160, burst: 10, allianceType: ["KNIGHT", "FOOTMAN", "BALLISTA", "DEATH_KNIGHT"], hordeType: ["OGRE_LORD", "GRUNT", "CATAPULT", "OGRE"] },
},
allianceHero: {
name: "Paladin Prophet",
classType: "HEALER",
lane: "mid",
hpScale: 1.8,
damageScale: 1.2,
manaScale: 2.2,
},
hordeHero: {
name: "Chaos Warlord",
classType: "MAGE",
lane: "mid",
hpScale: 1.5,
damageScale: 2.5,
manaScale: 1.5,
},
},
];
const SERIES_LENGTH = FIGHT_CLUB_ROUNDS.length; // Best-of-4
const SERIES_WIN_THRESHOLD = 3; // First to 3 wins takes the series
// --- AI Commander system ---
// Each faction gets a commander personality that influences strategy
const AI_COMMANDERS = {
alliance: [
{ name: "High Marshal Lothar", style: "aggressive", trait: "Relentless Push", desc: "Favors all-out offense. Units press forward constantly." },
{ name: "Lady Jaina Proudmoore", style: "balanced", trait: "Arcane Precision", desc: "Calculated moves. Balanced attack and defense." },
{ name: "General Turalyon", style: "defensive", trait: "Holy Bulwark", desc: "Fortifies positions. Towers and stronghold are priority." },
{ name: "Sky-Admiral Rogers", style: "siege", trait: "Siege Doctrine", desc: "Focuses on structure damage. Ballistas and siege units favored." },
],
horde: [
{ name: "Warlord Garrosh", style: "aggressive", trait: "Blood Fury", desc: "Pure aggression. No retreat, no surrender." },
{ name: "Sylvanas Windrunner", style: "balanced", trait: "Dark Tactics", desc: "Cunning strategy. Strike where they're weakest." },
{ name: "Saurfang the Elder", style: "defensive", trait: "Honor Guard", desc: "Protects the stronghold. Counterattacks when advantage appears." },
{ name: "Gul'dan", style: "siege", trait: "Fel Bombardment", desc: "Sacrifices units for devastating siege damage." },
],
};
function pickRandomCommander(faction) {
const pool = AI_COMMANDERS[faction];
return pool[Math.floor(Math.random() * pool.length)];
}
// Active commanders for current series
let commanders = {
alliance: pickRandomCommander("alliance"),
horde: pickRandomCommander("horde"),
};
const fightClub = {
roundIndex: 0,
wins: { alliance: 0, horde: 0 },
seriesNumber: 1,
seriesActive: true,
seriesWinner: null,
history: [],
predictions: Object.fromEntries(FIGHT_CLUB_ROUNDS.map((r) => [r.id, { alliance: 0, horde: 0 }])),
// Round-level stats
roundStats: { kills: { alliance: 0, horde: 0 }, towersDestroyed: { alliance: 0, horde: 0 }, mvp: null },
// All-time stats
allTime: { seriesPlayed: 0, allianceSeriesWins: 0, hordeSeriesWins: 0, totalRounds: 0 },
};
const rewardLedger = loadRewardLedger();
const playerBalances = loadPlayerBalances();
const sessions = new Map(); // ws -> { sessionId, connectedAt, ticksPresent }
const sessionIndex = new Map(); // sessionId -> Set<ws>
function loadPlayerBalances() {
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
if (!fs.existsSync(PLAYER_BALANCES_FILE)) {
const initial = { players: {}, updatedAt: new Date().toISOString() };
fs.writeFileSync(PLAYER_BALANCES_FILE, JSON.stringify(initial, null, 2), "utf8");
return initial;
}
try {
return JSON.parse(fs.readFileSync(PLAYER_BALANCES_FILE, "utf8"));
} catch {
return { players: {}, updatedAt: new Date().toISOString() };
}
}
function persistPlayerBalances() {
playerBalances.updatedAt = new Date().toISOString();
fs.writeFileSync(PLAYER_BALANCES_FILE, JSON.stringify(playerBalances, null, 2), "utf8");
}
function ensurePlayer(sessionId) {
if (!playerBalances.players[sessionId]) {
playerBalances.players[sessionId] = {
pending: 0,
totalEarned: 0,
totalClaimed: 0,
dailyEarned: 0,
dailyDate: new Date().toISOString().slice(0, 10),
lastClaimAt: null,
};
}
const p = playerBalances.players[sessionId];
const today = new Date().toISOString().slice(0, 10);
if (p.dailyDate !== today) {
p.dailyEarned = 0;
p.dailyDate = today;
}
return p;
}
function applyDailyCap(player, rawWoa) {
if (player.dailyEarned >= DAILY_HARD_CAP) return 0;
let amount = rawWoa;
if (player.dailyEarned >= DAILY_SOFT_CAP) {
const degradation = Math.max(0, 1 - (player.dailyEarned - DAILY_SOFT_CAP) / (DAILY_HARD_CAP - DAILY_SOFT_CAP));
amount = Math.floor(rawWoa * degradation);
}
const capped = Math.min(amount, DAILY_HARD_CAP - player.dailyEarned);
return Math.max(0, capped);
}
function generateSessionId() {
return `s_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
}
function loadRewardLedger() {
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
}
if (!fs.existsSync(REWARD_LEDGER_FILE)) {
const initial = {
factions: { alliance: 0, horde: 0 },
rounds: [],
updatedAt: new Date().toISOString(),
};
fs.writeFileSync(REWARD_LEDGER_FILE, JSON.stringify(initial, null, 2), "utf8");
return initial;
}
try {
const raw = fs.readFileSync(REWARD_LEDGER_FILE, "utf8");
const parsed = JSON.parse(raw);
return {
factions: parsed.factions || { alliance: 0, horde: 0 },
rounds: Array.isArray(parsed.rounds) ? parsed.rounds : [],
updatedAt: parsed.updatedAt || new Date().toISOString(),
};
} catch {
return {
factions: { alliance: 0, horde: 0 },
rounds: [],
updatedAt: new Date().toISOString(),
};
}
}
function persistRewardLedger() {
rewardLedger.updatedAt = new Date().toISOString();
fs.writeFileSync(REWARD_LEDGER_FILE, JSON.stringify(rewardLedger, null, 2), "utf8");
}
function estimateRoundWoa(state, winner) {
const allianceGold = state.heroes.alliance.reduce((acc, h) => acc + h.gold, 0);
const hordeGold = state.heroes.horde.reduce((acc, h) => acc + h.gold, 0);
const aw = winner === "alliance" ? 1.1 : winner === "draw" ? 1.0 : 0.9;
const hw = winner === "horde" ? 1.1 : winner === "draw" ? 1.0 : 0.9;
const allianceWoa = Math.min(WOA_PER_ROUND_CAP, Math.floor(allianceGold * aw * WOA_PER_GOLD));
const hordeWoa = Math.min(WOA_PER_ROUND_CAP, Math.floor(hordeGold * hw * WOA_PER_GOLD));
return {
allianceGold,
hordeGold,
allianceWoa,
hordeWoa,
};
}
let gameState = initRoundState(fightClub.roundIndex);
function initRoundState(index) {
const round = FIGHT_CLUB_ROUNDS[index];
const state = createGameState(`fightclub_${round.id}_${Date.now()}`);
state.spawnConfig = round.spawnConfig;
const allianceHero = createScaledHero(round.allianceHero);
const hordeHero = createScaledHero(round.hordeHero);
addHeroToGame(state, allianceHero, "alliance", round.allianceHero.lane || "mid");
addHeroToGame(state, hordeHero, "horde", round.hordeHero.lane || "mid");
return state;
}
function createScaledHero(def) {
const hero = createAgent(def.name, def.classType);
hero.maxHp = Math.floor(hero.maxHp * (def.hpScale || 1));
hero.hp = hero.maxHp;
hero.damage = Math.max(1, Math.floor(hero.damage * (def.damageScale || 1)));
hero.maxMana = Math.floor(hero.maxMana * (def.manaScale || 1));
hero.mana = hero.maxMana;
return hero;
}
function computeRoundStats(state) {
// Determine MVP (hero with most kills + gold)
const allHeroes = [...state.heroes.alliance, ...state.heroes.horde];
let mvp = null;
let bestScore = -1;
for (const h of allHeroes) {
const score = (h.kills || 0) * 100 + (h.gold || 0);
if (score > bestScore) {
bestScore = score;
mvp = { name: h.name, class: h.class, faction: h.faction, kills: h.kills || 0, gold: h.gold || 0 };
}
}
// Count kills per faction
const aKills = state.heroes.alliance.reduce((s, h) => s + (h.kills || 0), 0);
const hKills = state.heroes.horde.reduce((s, h) => s + (h.kills || 0), 0);
return { kills: { alliance: aKills, horde: hKills }, mvp };
}
function finalizeRoundAndAdvance() {
const round = FIGHT_CLUB_ROUNDS[fightClub.roundIndex];
const winner = resolveRoundWinner(gameState);
const rewards = estimateRoundWoa(gameState, winner);
const stats = computeRoundStats(gameState);
if (winner === "alliance" || winner === "horde") {
fightClub.wins[winner]++;
}
fightClub.roundStats = stats;
fightClub.allTime.totalRounds++;
fightClub.history.push({
roundId: round.id,
title: round.title,
winner,
tick: gameState.tick,
endedAt: new Date().toISOString(),
rewards,
mvp: stats.mvp,
kills: stats.kills,
});
if (fightClub.history.length > 20) {
fightClub.history = fightClub.history.slice(-20);
}
rewardLedger.factions.alliance += rewards.allianceWoa;
rewardLedger.factions.horde += rewards.hordeWoa;
rewardLedger.rounds.push({
roundId: round.id,
winner,
tick: gameState.tick,
rewards,
endedAt: new Date().toISOString(),
});
if (rewardLedger.rounds.length > 400) {
rewardLedger.rounds = rewardLedger.rounds.slice(-400);
}
persistRewardLedger();
// Per-player reward distribution with participation gate + daily caps
const qualifiedSessions = [];
for (const [ws, info] of sessions) {
const presence = round.durationTicks > 0 ? info.ticksPresent / round.durationTicks : 0;
if (presence >= PARTICIPATION_GATE) {
qualifiedSessions.push(info.sessionId);
}
info.ticksPresent = 0;
}
if (qualifiedSessions.length > 0) {
const perPlayerWoa = Math.floor(Math.max(rewards.allianceWoa, rewards.hordeWoa) / qualifiedSessions.length);
for (const sid of qualifiedSessions) {
const player = ensurePlayer(sid);
const capped = applyDailyCap(player, Math.min(perPlayerWoa, WOA_PER_ROUND_CAP));
if (capped > 0) {
player.pending += capped;
player.totalEarned += capped;
player.dailyEarned += capped;
}
}
persistPlayerBalances();
}
// --- Series progression ---
// Check if a faction won the series (first to SERIES_WIN_THRESHOLD)
if (fightClub.wins.alliance >= SERIES_WIN_THRESHOLD || fightClub.wins.horde >= SERIES_WIN_THRESHOLD) {
fightClub.seriesWinner = fightClub.wins.alliance >= SERIES_WIN_THRESHOLD ? "alliance" : "horde";
fightClub.allTime.seriesPlayed++;
if (fightClub.seriesWinner === "alliance") fightClub.allTime.allianceSeriesWins++;
else fightClub.allTime.hordeSeriesWins++;
console.log(`[SERIES] Series #${fightClub.seriesNumber} won by ${fightClub.seriesWinner.toUpperCase()} (${fightClub.wins.alliance}-${fightClub.wins.horde})`);
// Start new series after a brief pause — new commanders each series
setTimeout(() => {
fightClub.seriesNumber++;
fightClub.wins = { alliance: 0, horde: 0 };
fightClub.seriesWinner = null;
fightClub.roundIndex = 0;
fightClub.predictions = Object.fromEntries(FIGHT_CLUB_ROUNDS.map((r) => [r.id, { alliance: 0, horde: 0 }]));
commanders = { alliance: pickRandomCommander("alliance"), horde: pickRandomCommander("horde") };
gameState = initRoundState(0);
console.log(`[SERIES] Series #${fightClub.seriesNumber} started! Commanders: ${commanders.alliance.name} vs ${commanders.horde.name}`);
}, 8000);
return;
}
fightClub.roundIndex = (fightClub.roundIndex + 1) % FIGHT_CLUB_ROUNDS.length;
gameState = initRoundState(fightClub.roundIndex);
}
function resolveRoundWinner(state) {
if (state.winner) return state.winner;
const aBase = state.strongholds.alliance.hp;
const hBase = state.strongholds.horde.hp;
if (aBase > hBase) return "alliance";
if (hBase > aBase) return "horde";
const aTower = aliveTowers(state, "alliance");
const hTower = aliveTowers(state, "horde");
if (aTower > hTower) return "alliance";
if (hTower > aTower) return "horde";
const aArmy = totalArmyPower(state, "alliance");
const hArmy = totalArmyPower(state, "horde");
if (aArmy > hArmy) return "alliance";
if (hArmy > aArmy) return "horde";
return "draw";
}
function aliveTowers(state, faction) {
let count = 0;
for (const laneName of ["top", "mid", "bot"]) {
for (const tower of state.towers[laneName][faction]) {
if (tower.alive) count++;
}
}
return count;
}
function totalArmyPower(state, faction) {
let unitCount = 0;
for (const laneName of ["top", "mid", "bot"]) {
unitCount += state.lanes[laneName].units[faction].length;
}
let heroHp = 0;
for (const hero of state.heroes[faction]) {
heroHp += hero.hp;
}
return unitCount * 10 + heroHp;
}
function getFightClubSummary() {
const round = FIGHT_CLUB_ROUNDS[fightClub.roundIndex];
const prediction = fightClub.predictions[round.id] || { alliance: 0, horde: 0 };
const totalPredictions = prediction.alliance + prediction.horde;
return {
round,
roundTick: gameState.tick,
rounds: FIGHT_CLUB_ROUNDS,
wins: fightClub.wins,
history: fightClub.history,
prediction: {
...prediction,
total: totalPredictions,
alliancePct: totalPredictions ? Math.round((prediction.alliance / totalPredictions) * 100) : 50,
hordePct: totalPredictions ? Math.round((prediction.horde / totalPredictions) * 100) : 50,
},
rewards: {
totalAlliance: rewardLedger.factions.alliance,
totalHorde: rewardLedger.factions.horde,
roundsTracked: rewardLedger.rounds.length,
woaPerGold: WOA_PER_GOLD,
perRoundCap: WOA_PER_ROUND_CAP,
},
series: {
number: fightClub.seriesNumber,
winner: fightClub.seriesWinner,
winsNeeded: SERIES_WIN_THRESHOLD,
},
roundStats: fightClub.roundStats,
allTime: fightClub.allTime,
commanders: {
alliance: commanders.alliance,
horde: commanders.horde,
},
};
}
function getSpectatorState() {
return {
...getFullGameStatus(gameState),
fightClub: getFightClubSummary(),
};
}
setInterval(() => {
processTick(gameState);
// Track presence for every connected session this tick
for (const [, info] of sessions) {
info.ticksPresent++;
}
const round = FIGHT_CLUB_ROUNDS[fightClub.roundIndex];
if (gameState.winner || gameState.tick >= round.durationTicks) {
finalizeRoundAndAdvance();
}
}, Math.floor(1000 / TICK_RATE));
const publicDir = path.join(__dirname, "public");
function sendJson(res, statusCode, obj) {
const body = JSON.stringify(obj);
res.writeHead(statusCode, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
});
res.end(body);
}
function sendText(res, statusCode, text) {
res.writeHead(statusCode, {
"Content-Type": "text/plain; charset=utf-8",
"Cache-Control": "no-store",
});
res.end(text);
}
function safeResolvePublicPath(urlPath) {
const decoded = decodeURIComponent(urlPath);
const cleaned = decoded.replace(/\0/g, "");
const joined = path.join(publicDir, cleaned);
if (!joined.startsWith(publicDir)) return null;
return joined;
}
function readJsonBody(req) {
return new Promise((resolve, reject) => {
let body = "";
req.on("data", (chunk) => {
body += chunk;
if (body.length > 8 * 1024) {
reject(new Error("Payload too large"));
}
});
req.on("end", () => {
if (!body) return resolve({});
try {
resolve(JSON.parse(body));
} catch {
reject(new Error("Invalid JSON"));
}
});
req.on("error", reject);
});
}
const server = http.createServer(async (req, res) => {
if (!req.url) return sendText(res, 400, "Bad Request");
const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
const pathname = url.pathname;
if (req.method === "GET" && pathname === "/api/state") {
return sendJson(res, 200, getSpectatorState());
}
if (req.method === "GET" && pathname === "/api/fightclub") {
return sendJson(res, 200, getFightClubSummary());
}
if (req.method === "GET" && pathname === "/api/rewards") {
const limit = Math.max(1, Math.min(100, Number(url.searchParams.get("limit") || 20)));
return sendJson(res, 200, {
totals: rewardLedger.factions,
woaPerGold: WOA_PER_GOLD,
perRoundCap: WOA_PER_ROUND_CAP,
recentRounds: rewardLedger.rounds.slice(-limit).reverse(),
updatedAt: rewardLedger.updatedAt,
});
}
if (req.method === "GET" && pathname === "/api/balance") {
const sessionId = url.searchParams.get("sessionId");
if (!sessionId) return sendJson(res, 400, { error: "sessionId required" });
const player = playerBalances.players[sessionId];
if (!player) return sendJson(res, 200, { pending: 0, totalEarned: 0, totalClaimed: 0, dailyEarned: 0 });
return sendJson(res, 200, {
pending: player.pending,
totalEarned: player.totalEarned,
totalClaimed: player.totalClaimed,
dailyEarned: player.dailyEarned,
dailyDate: player.dailyDate,
nextClaimAt: player.lastClaimAt ? new Date(new Date(player.lastClaimAt).getTime() + CLAIM_COOLDOWN_MS).toISOString() : null,
});
}
if (req.method === "POST" && pathname === "/api/claim") {
try {
const body = await readJsonBody(req);
const sessionId = String(body.sessionId || "");
if (!sessionId) return sendJson(res, 400, { error: "sessionId required" });
const player = playerBalances.players[sessionId];
if (!player) return sendJson(res, 404, { error: "Session not found" });
if (player.pending < CLAIM_THRESHOLD) {
return sendJson(res, 400, { error: `Minimum ${CLAIM_THRESHOLD} WOA required to claim` });
}
if (player.lastClaimAt) {
const elapsed = Date.now() - new Date(player.lastClaimAt).getTime();
if (elapsed < CLAIM_COOLDOWN_MS) {
const waitSec = Math.ceil((CLAIM_COOLDOWN_MS - elapsed) / 1000);
return sendJson(res, 429, { error: `Claim cooldown: wait ${waitSec}s` });
}
}
const claimed = player.pending;
player.totalClaimed += claimed;
player.pending = 0;
player.lastClaimAt = new Date().toISOString();
persistPlayerBalances();
return sendJson(res, 200, { ok: true, claimed, remaining: 0 });
} catch (err) {
return sendJson(res, 400, { error: err.message });
}
}
if (req.method === "POST" && pathname === "/api/predict") {
try {
const body = await readJsonBody(req);
const pick = String(body.pick || "").toLowerCase();
if (pick !== "alliance" && pick !== "horde") {
return sendJson(res, 400, { error: "pick must be 'alliance' or 'horde'" });
}
const round = FIGHT_CLUB_ROUNDS[fightClub.roundIndex];
fightClub.predictions[round.id][pick]++;
return sendJson(res, 200, { ok: true, fightClub: getFightClubSummary() });
} catch (err) {
return sendJson(res, 400, { error: err.message });
}
}
if (req.method !== "GET") {
return sendText(res, 405, "Method Not Allowed");
}
// Serve docs as static markdown via a simple HTML wrapper
if (pathname === "/docs" || pathname === "/docs/") {
const docsIndex = path.join(__dirname, "docs", "README.md");
try {
const md = fs.readFileSync(docsIndex, "utf8");
const html = `<!doctype html><html><head><meta charset="utf-8"><title>War of Agents - Docs</title>
<link rel="stylesheet" href="/styles.css">
<style>body{padding:40px;max-width:800px;margin:0 auto}.doc-content{background:rgba(11,11,16,0.9);border:1px solid rgba(240,201,106,0.25);border-radius:14px;padding:32px}
.doc-content h1,.doc-content h2,.doc-content h3{font-family:Cinzel,Georgia,serif;color:var(--brass)}
.doc-content pre{background:rgba(0,0,0,0.4);padding:12px;border-radius:8px;overflow-x:auto}
.doc-content a{color:var(--alliance)}
.doc-back{display:inline-block;margin-bottom:16px;color:var(--brass);font-size:13px}</style></head>
<body><a class="doc-back" href="/">← Back to Arena</a><div class="doc-content"><pre style="white-space:pre-wrap;font-size:13px;line-height:1.6">${md.replace(/</g,"<").replace(/>/g,">")}</pre></div></body></html>`;
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
return res.end(html);
} catch {
return sendText(res, 404, "Docs not found");
}
}
const targetPath = pathname === "/" ? "/index.html" : pathname === "/pvp" ? "/pvp.html" : pathname;
const resolved = safeResolvePublicPath(targetPath);
if (!resolved) return sendText(res, 403, "Forbidden");
fs.readFile(resolved, (err, data) => {
if (err) return sendText(res, 404, "Not Found");
const ext = path.extname(resolved).toLowerCase();
const type =
ext === ".html"
? "text/html; charset=utf-8"
: ext === ".js"
? "text/javascript; charset=utf-8"
: ext === ".css"
? "text/css; charset=utf-8"
: ext === ".svg"
? "image/svg+xml"
: "application/octet-stream";
res.writeHead(200, {
"Content-Type": type,
"Cache-Control": "no-store",
});
res.end(data);
});
});
const wss = new WebSocketServer({ noServer: true });
server.on("upgrade", (req, socket, head) => {
try {
const url = new URL(req.url || "", `http://${req.headers.host || "localhost"}`);
if (url.pathname !== "/ws") {
socket.destroy();
return;
}
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit("connection", ws, req);
});
} catch {
socket.destroy();
}
});
wss.on("connection", (ws, req) => {
// Extract or generate session ID
const wsUrl = new URL(req.url || "/ws", `http://${req.headers.host || "localhost"}`);
let sessionId = wsUrl.searchParams.get("sessionId") || generateSessionId();
ensurePlayer(sessionId);
const info = { sessionId, connectedAt: Date.now(), ticksPresent: 0 };
sessions.set(ws, info);
if (!sessionIndex.has(sessionId)) sessionIndex.set(sessionId, new Set());
sessionIndex.get(sessionId).add(ws);
const initPayload = getSpectatorState();
initPayload.sessionId = sessionId;
ws.send(JSON.stringify({ type: "state", data: initPayload }));
ws.on("close", () => {
sessions.delete(ws);
const subs = sessionIndex.get(sessionId);
if (subs) {
subs.delete(ws);
if (subs.size === 0) sessionIndex.delete(sessionId);
}
});
});
setInterval(() => {
const payload = JSON.stringify({ type: "state", data: getSpectatorState() });
for (const ws of wss.clients) {
if (ws.readyState === ws.OPEN) ws.send(payload);
}
}, Math.floor(1000 / BROADCAST_RATE));
server.listen(PORT, () => {
console.log("World of Agents Fight Club server running:");
console.log(` http://localhost:${PORT}`);
console.log(` http://localhost:${PORT}/api/state`);
console.log(` http://localhost:${PORT}/api/fightclub`);
console.log(` http://localhost:${PORT}/api/rewards`);
console.log(` ws://localhost:${PORT}/ws`);
});