Release alpha 13 balance and mission tests

This commit is contained in:
Emporex committed 2026-10-11 13:05:34 +02:00
1 parent fc4fcd40a4
commit 026d0bad58
9 files changed
+219 -13

No files matched your search

+149
View File
@@ -0,0 +1,149 @@
const fs = require("fs");
const vm = require("vm");
const path = require("path");
const assert = require("assert");
const source = fs.readFileSync(path.join(__dirname, "..", "runtime", "build", "index.js"), "utf8");
const context = { console, Math, Date, JSON, isFinite };
vm.createContext(context);
vm.runInContext(source, context);
function seedRandom(seed) {
let value = seed >>> 0;
return function () {
value = (value * 1664525 + 1013904223) >>> 0;
return value / 0x100000000;
};
}
function samplePath(route) {
const samples = [];
for (let i = 0; i < route.length - 1; i++) {
const [ax, ay] = route[i], [bx, by] = route[i + 1];
const length = Math.hypot(bx - ax, by - ay);
const steps = Math.max(1, Math.ceil(length / 40));
for (let step = 0; step < steps; step++) {
const ratio = step / steps;
samples.push([ax + (bx - ax) * ratio, ay + (by - ay) * ratio, length / steps]);
}
}
return samples;
}
const pathSamples = [samplePath(context.PATHS[0]), samplePath(context.PATHS[1])];
const areaFactor = [1, 1, 1.65, 1.6, 1.9, 1.35, 1];
function nextWaveComposition(state, wave) {
const schedule = context.buildWaveSchedule(state, wave, context.wavePopulation(state, wave));
const counts = Array(context.ENEMIES.length).fill(0);
for (const entry of schedule) counts[entry.type] += 1;
return { schedule, counts };
}
function chooseTowerType(state, composition, fixedType) {
if (fixedType !== null) return fixedType;
let bestType = 1, bestScore = -1;
for (let towerType = 0; towerType < context.TOWERS.length; towerType++) {
const tower = context.TOWERS[towerType];
let score = 0;
for (let enemyType = 0; enemyType < context.ENEMIES.length; enemyType++) {
const count = composition.counts[enemyType];
if (!count) continue;
const enemy = context.ENEMIES[enemyType];
if (tower.targetClass !== "both" && tower.targetClass !== enemy.category) continue;
const damage = tower.damage * (tower.targetClass === "both" ? tower.bothScale || 1 : 1);
const exposedDps = damage / tower.cooldown;
const shieldChance = enemyType === 4 ? 1 : 0.25;
const shieldMultiplier = towerType === 1 || towerType === 5 ? 1 : 1 - shieldChance * (1 - (enemy.shieldResistance || 0.28));
const bossWeight = composition.schedule.some(entry => entry.type === enemyType && entry.boss) ? 1.2 : 1;
score += count * Math.sqrt(enemy.hp) * exposedDps * shieldMultiplier * areaFactor[towerType] * bossWeight;
}
score /= Math.max(1, tower.cost);
if (score > bestScore) { bestScore = score; bestType = towerType; }
}
return bestType;
}
function choosePosition(state, owner, range) {
const xMin = owner === 0 ? 120 : 1520;
const xMax = owner === 0 ? 1440 : 2840;
let best = null, bestScore = -1;
for (let y = 120; y <= 680; y += 80) for (let x = xMin; x <= xMax; x += 80) {
if (!context.validBuildPosition(state, owner, x, y)) continue;
const rangeSq = range * range;
let score = 0;
for (const [px, py, weight] of pathSamples[owner]) {
const covered = state.towers.some(tower => tower.owner === owner &&
context.distanceSquared(tower.x, tower.y, px, py) <= context.towerRange(state, tower) ** 2);
if (!covered && context.distanceSquared(x, y, px, py) <= rangeSq) score += weight;
}
if (score > bestScore) { bestScore = score; best = [x, y]; }
}
return best;
}
function runMission(difficulty, fixedType = null) {
let random = seedRandom(0xB45710 + difficulty * 7919 + (fixedType === null ? 0 : fixedType * 97));
context.Math = Object.create(Math);
context.Math.random = () => random();
const state = context.initialState({ difficulty, mode: "balance_test" });
state.started = true;
let wavesCompleted = 0, totalSpawned = 0, totalBreached = 0;
const trace = [];
const maxTicksPerWave = 24000;
for (let wave = 1; wave <= 15 && !state.gameOver; wave++) {
const composition = nextWaveComposition(state, wave);
for (let owner = 0; owner < 2; owner++) {
let guard = 32;
while (guard-- > 0) {
const towerType = chooseTowerType(state, composition, fixedType);
const tower = context.TOWERS[towerType];
if (state.credits[owner] < tower.cost) break;
const position = choosePosition(state, owner, tower.range);
if (!position) break;
state.credits[owner] -= tower.cost;
state.towers.push({ id: state.nextTowerId++, type: towerType, x: position[0], y: position[1], owner, level: 1, cooldown: 0.15, angle: owner === 0 ? 0 : Math.PI });
}
}
if (!context.startWave(state)) break;
const beforeSpawn = state.nextEnemyId;
let tick = 0;
while (state.waveActive && !state.gameOver && tick++ < maxTicksPerWave) {
context.updateWave(state, 0.1, { broadcastMessage() {} });
context.updateEnemies(state, 0.1);
context.updateTowers(state, 0.1);
}
totalSpawned += state.nextEnemyId - beforeSpawn;
totalBreached += Math.max(0, 30 - state.reactorLives);
trace.push({wave, lives: state.reactorLives, spawned: state.nextEnemyId - beforeSpawn, towers: state.towers.length, credits: [...state.credits], enemyLeft: state.enemies.length, towerTypes: state.towers.map(t => t.type)});
if (tick >= maxTicksPerWave) break;
if (!state.gameOver) wavesCompleted++;
}
return { difficulty, fixedType, wavesCompleted, reactorLives: state.reactorLives, trace,
towers: state.towers.length, spawned: totalSpawned, remainingEnemies: state.enemies.length,
credits: state.credits.reduce((sum, value) => sum + value, 0) };
}
const baseline = [];
for (let difficulty = 0; difficulty < context.DIFFICULTIES.length; difficulty++) {
baseline.push(runMission(difficulty));
}
const towerRuns = [];
for (let tower = 0; tower < context.TOWERS.length; tower++) {
for (let difficulty = 0; difficulty < context.DIFFICULTIES.length; difficulty++) {
towerRuns.push(runMission(difficulty, tower));
}
}
assert.strictEqual(baseline.length, 3);
assert.ok(towerRuns.length === context.TOWERS.length * 3);
assert.ok(baseline.every(result => result.spawned > 0), "mission simulations must use the real wave scheduler");
console.log("BALANCE MISSION RESULTS (Nakama wave/combat code, fixed-seed greedy build planner, level-1 towers)");
console.log("planner: " + baseline.map(r => `D${r.difficulty} ${r.wavesCompleted}/15 waves, reactor ${r.reactorLives}, ${r.towers} towers`).join(" | "));
for (let tower = 0; tower < context.TOWERS.length; tower++) {
const values = towerRuns.filter(result => result.fixedType === tower)
.map(r => `D${r.difficulty} ${r.wavesCompleted}/15, R${r.reactorLives}, ${r.towers}T`).join(" | ");
console.log(`tower ${tower} (${context.TOWERS[tower].targetClass}): ${values}`);
}
console.log(`BALANCE_MISSION_TEST_OK scenarios=${baseline.length + towerRuns.length}`);
+23
View File
@@ -22,6 +22,10 @@ assert.ok(context.TOWERS[3].bothScale < 1, "Universal towers should trade damage
assert.strictEqual(context.TOWERS[4].damage, 20, "EMP damage should be tuned down to about 20.");
assert.strictEqual(context.TOWERS[4].targetClass, "both", "EMP should cover both air and ground units.");
assert.strictEqual(context.TOWERS[6].targetClass, "air", "The Flak tower must only target air units.");
assert.strictEqual(context.TOWERS[6].damage, 22, "The air-only Flak tower should receive its focused damage tuning.");
assert.strictEqual(context.ENEMIES[5].hp, 620, "The first aerial boss base hull should use the reduced balance value.");
assert.strictEqual(context.initialState({ difficulty: 0 }).difficulty, 0, "Easy must not be coerced to the default difficulty.");
assert.strictEqual(context.initialState({ difficulty: 0 }).credits[0], context.DIFFICULTIES[0].startCredits);
const balanceStorage = new Map();
let balanceVersion = 0;
const balanceNk = {
@@ -44,6 +48,25 @@ assert.strictEqual(JSON.parse(context.rpcSetGameBalance({}, {}, balanceNk, JSON.
assert.strictEqual(JSON.parse(context.rpcGetGameBalance({ userId: "pilot-b" }, {}, balanceNk, "{}")).config.towers[0].damage, 31);
assert.strictEqual(context.matchInit({}, {}, balanceNk, { difficulty: 1 }).state.balance.enemies[0].hp, 90);
assert.throws(() => context.rpcSetGameBalance({}, {}, balanceNk, JSON.stringify({ config: { towers: [], enemies: [] } })), /invalid balance schema/);
const legacyStorage = new Map();
const legacyKey = `game_balance:${context.SYSTEM_USER_ID}:global`;
const legacyConfig = JSON.parse(JSON.stringify(context.defaultBalanceConfig()));
legacyConfig.schema = 1;
legacyConfig.towers[0].damage = 31;
legacyConfig.towers[6].damage = 20;
legacyConfig.enemies[5].hp = 740;
legacyStorage.set(legacyKey, { collection: "game_balance", key: "global", userId: context.SYSTEM_USER_ID,
value: { config: legacyConfig, updated_at: 1 }, permissionRead: 0, permissionWrite: 0, version: "7" });
const migrationNk = {
storageRead(ops) { return ops.map(op => legacyStorage.get(`${op.collection}:${op.userId}:${op.key}`)).filter(Boolean); },
storageWrite(ops) { for (const op of ops) legacyStorage.set(`${op.collection}:${op.userId}:${op.key}`, { ...op, version: "8" }); }
};
const migratedBalance = context.readBalanceConfig(migrationNk);
assert.strictEqual(migratedBalance.config.schema, 2);
assert.strictEqual(migratedBalance.config.towers[0].damage, 31, "Balance migrations must preserve unrelated admin tuning.");
assert.strictEqual(migratedBalance.config.towers[6].damage, 22, "Unchanged legacy Flak defaults should migrate to the new value.");
assert.strictEqual(migratedBalance.config.enemies[5].hp, 620, "Unchanged legacy boss HP should migrate to the new value.");
assert.strictEqual(legacyStorage.get(legacyKey).value.config.schema, 2, "Migrated balance should persist for future matches.");
const hostId = "11111111-1111-1111-1111-111111111111";
const friendId = "22222222-2222-2222-2222-222222222222";
const sentInvites = [];