Add automatic powering with activation UI and replay support

This commit is contained in:
coyotte508 2026-10-04 11:12:43 +02:00
commit 7b1ea78987
11 changed files with 9628 additions and 50 deletions

View file

@ -0,0 +1,133 @@
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const engine = require('../../engine/dist/index.js');
const wrapper = require('../../engine/dist/wrapper.js');
const { powerPlants } = require('../../engine/dist/src/powerPlants.js');
const clone = (value) => JSON.parse(JSON.stringify(value));
const plant = (number) => clone(powerPlants.find((p) => p.number === number));
export function poweringPosition(scenario = 'choice') {
const G = engine.setup(
3,
{
map: scenario === 'australia' ? 'Australia' : scenario === 'india' ? 'India' : 'Germany',
variant: 'original',
showMoney: true,
},
'powering-preview'
);
G.round = 6;
G.step = 2;
G.phase = engine.Phase.Bureaucracy;
G.currentPlayers = [0, 1, 2];
G.playerOrder = [0, 1, 2];
G.players.forEach((p, i) => {
p.name = ['You', 'Nora', 'Leo'][i];
p.money = 42 + i * 11;
p.powerPlants = [
[27, 20, 26],
[18, 24, 25],
[22, 28, 30],
][i].map(plant);
p.coalLeft = 3;
p.oilLeft = 0;
p.garbageLeft = i === 1 ? 2 : 0;
p.uraniumLeft = 0;
p.coalCapacity = p.oilCapacity = p.garbageCapacity = p.uraniumCapacity = 12;
p.resourcesUsed = [];
p.citiesPowered = 0;
p.passed = p.skipAuction = false;
p.cities = G.map.cities.slice(i * 8, i * 8 + 8).map((city) => ({ name: city.name, position: 0 }));
});
const p = G.players[0];
if (scenario === 'covered') p.cities = p.cities.slice(0, 3);
if (scenario === 'only-free') p.powerPlants = [18, 27, 33].map(plant);
if (scenario === 'no-fuel') p.coalLeft = 0;
if (scenario === 'empty') {
p.powerPlants = [20, 24, 26].map(plant);
p.coalLeft = 0;
}
if (scenario === 'hybrid') {
p.powerPlants = [27, 29, 26].map(plant);
p.coalLeft = p.oilLeft = 2;
}
if (scenario === 'australia') p.powerPlants = [27, 20, 11].map(plant);
if (scenario === 'india') {
G.citiesBuiltInCurrentRound = 0;
p.targetCitiesPowered = 8;
}
for (const player of G.players) {
player.powerPlantsNotUsed = player.powerPlants.map((plant) => plant.number);
player.availableMoves = engine.availableMoves(G, player);
}
const held = new Set(G.players.flatMap((p) => p.powerPlants.map((p) => p.number)));
G.powerPlantsDeck = G.powerPlantsDeck.filter((p) => !held.has(p.number));
G.log.push({ type: 'event', event: 'Round 6: power your cities and collect income.' });
G.newTurn = true;
return G;
}
const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Powergrid · Plant activation preview</title><link rel="stylesheet" href="/powergrid-viewer.css"><style>.preview{display:flex;gap:12px;align-items:center;flex-wrap:wrap;background:#101d27;color:#eff5f8;padding:12px 16px;font:13px/1.4 system-ui}.preview strong{margin-right:auto}.preview small{color:#b7c8cf}.preview select,.preview button{font:inherit;padding:7px 9px;border:1px solid #6d858b;border-radius:5px;background:#253943;color:#fff}.preview label{display:flex;gap:6px;align-items:center}#error:empty{display:none}#error{background:#fee;color:#900;padding:12px}</style></head><body><header class="preview"><strong>Plant activation <small>Local preview · not published</small></strong><label>Scenario <select id="scenario"><option value="choice">Choose fuel</option><option value="covered">Free plants cover every city</option><option value="only-free">Only free plants</option><option value="no-fuel">No fuel for other plants</option><option value="empty">No usable plants</option><option value="hybrid">Hybrid fuel choice</option><option value="australia">Australia + uranium mine</option><option value="india">India · must power the maximum</option></select></label><button id="reset">Reset</button><button id="theme">Light mode</button><button id="opponent">Finish next opponent</button></header><div id="error" role="alert"></div><div id="app"></div><script src="/vue.js"></script><script src="/powergrid-viewer.umd.min.js"></script><script>
const params=new URLSearchParams(location.search), scenario=params.get('scenario')||'choice', session=crypto.randomUUID();
const host=window.host=powergrid.launch('#app');let dark=true,pending=Promise.resolve();window.sentMoves=[];
const suffix='?scenario='+scenario+'&session='+session;
async function send(path,body){const response=await fetch(path+suffix,{method:body?'POST':'GET',headers:{'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined});const data=await response.json();if(data.error){document.querySelector('#error').textContent=data.error;throw Error(data.error);}document.querySelector('#error').textContent='';window.previewState=data.state;host.emit('state',data.state);}
host.on('fetchState',()=>{pending=pending.then(()=>send('/state'));});host.on('move',moves=>{sentMoves.push(moves);pending=pending.then(()=>send('/move',{moves}));});
host.emit('player',{index:0});host.emit('theme',{dark});host.emit('preferences',{sound:false,locale:params.get('locale')||'en',fitToScreen:false});host.emit('chat:state',{canSend:false,mentions:[]});
host.emit('avatars',Array(3).fill('data:image/svg+xml,'+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30"><circle cx="15" cy="15" r="15" fill="#bccbc4"/></svg>')));
document.querySelector('#scenario').value=scenario;document.querySelector('#scenario').onchange=e=>location.search='?scenario='+e.target.value+'&locale='+(params.get('locale')||'en');
document.querySelector('#reset').onclick=()=>location.reload();document.querySelector('#opponent').onclick=()=>{pending=pending.then(()=>send('/opponent',{}));};document.querySelector('#theme').onclick=e=>{dark=!dark;host.emit('theme',{dark});e.target.textContent=dark?'Light mode':'Dark mode';};
pending=pending.then(()=>send('/state'));
</script></body></html>`;
export function poweringPreviewServer() {
const states = new Map();
return createServer(async (req, res) => {
try {
const url = new URL(req.url, 'http://localhost');
res.setHeader('Cache-Control', 'no-store');
if (url.pathname === '/') {
res.setHeader('Content-Type', 'text/html');
res.end(html);
return;
}
if (url.pathname === '/vue.js' || /^\/powergrid-viewer[\w.-]*\.(css|js)$/.test(url.pathname)) {
res.setHeader('Content-Type', url.pathname.endsWith('.css') ? 'text/css' : 'text/javascript');
res.end(
await readFile(
url.pathname === '/vue.js'
? require.resolve('vue/dist/vue.min.js')
: fileURLToPath(new URL('../dist' + url.pathname, import.meta.url))
)
);
return;
}
const key = url.searchParams.get('session');
if (!key || !['/state', '/move', '/opponent'].includes(url.pathname)) {
res.writeHead(404);
res.end();
return;
}
if (!states.has(key)) states.set(key, poweringPosition(url.searchParams.get('scenario')));
let state = states.get(key);
if (req.method === 'POST') {
let raw = '';
for await (const chunk of req) raw += chunk;
const seat = url.pathname === '/opponent' ? state.currentPlayers.find((i) => i !== 0) : 0;
if (seat === undefined) throw Error('No opponent is waiting.');
const moves = url.pathname === '/opponent' ? [{ name: 'Pass', data: true }] : JSON.parse(raw).moves;
state = await wrapper.move(clone(state), moves, seat);
if (wrapper.toSave(state)) states.set(key, state);
}
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ state: wrapper.stripSecret(state, 0) }));
} catch (error) {
res.writeHead(422, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: error.message }));
}
});
}
if (process.argv[1] === fileURLToPath(import.meta.url))
poweringPreviewServer().listen(Number(process.env.PORT || 5207), '127.0.0.1', () =>
console.log('Powergrid activation preview: http://127.0.0.1:' + (process.env.PORT || 5207))
);

View file

@ -1,4 +1,5 @@
import { checkHostPresentation } from './host-presentation-smoke.mjs';
import { checkMiddleEastReplay } from './replay-smoke.mjs';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
@ -392,6 +393,7 @@ try {
assert.doesNotMatch(await page.locator('.player-board [data-bgs-player="1"]').textContent(), /2 ·/);
assert.deepEqual(await page.evaluate(() => preferenceUpdates), [{ name: 'colorBlind', value: false }]);
await checkHostPresentation(page, 'host', `/tmp/powergrid-board-thumbnail-${width}.png`);
if (width === 1400) await checkMiddleEastReplay(page);
assert.deepEqual(errors, []);
await page.close();
console.log(`${game} ${width}px: protocol/chat smoke passed`);

View file

@ -0,0 +1,52 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
// Public spectator snapshot of MHABKH0215, with player names anonymized.
// Move 331 draws the Step 3 card during Middle East's Step 1 -> Step 2 transition.
export async function checkMiddleEastReplay(page) {
const state = JSON.parse(await readFile(new URL('../tests/fixtures/middle-east-replay.json', import.meta.url)));
const end = state.log.filter((item) => item.type === 'move').length;
await page.evaluate((state) => {
window.host = window.powergrid.launch('#app');
window.replayInfo = null;
window.replayMoves = [];
window.replayReady = false;
window.replaySource = state;
window.replaySourceBefore = JSON.stringify(state);
host.on('ready', () => { window.replayReady = true; });
host.on('replay:info', (info) => { window.replayInfo = info; });
host.on('move', (move) => { window.replayMoves.push(move); });
host.emit('preferences', { sound: false, locale: 'en' });
host.emit('player', {});
host.emit('state', state);
}, state);
await page.waitForFunction(() => window.replayReady);
await page.evaluate(() => host.emit('replay:start'));
assert.deepEqual(await page.evaluate(() => replayInfo), { start: 1, current: end, end });
// Exercise the bundled viewer handler at every position, including sealed
// bids which are temporarily stored in hiddenLog during reconstruction.
const failures = await page.evaluate((end) => {
const failures = [];
for (let current = 1; current <= end; current++) {
host.emit('replay:to', current);
if (replayInfo.current !== current || replayInfo.end !== end) failures.push(current);
}
return failures;
}, end);
assert.deepEqual(failures, [], 'every replay position is reachable');
// Scrub across the boundary more than once: no recorded draw may be consumed
// from the saved source state by an earlier reconstruction.
for (const [current, round, step] of [[330, 6, 1], [331, 7, 2], [end, 9, 2], [1, 1, 1], [331, 7, 2], [end, 9, 2]]) {
await page.evaluate((current) => host.emit('replay:to', current), current);
assert.deepEqual(await page.evaluate(() => replayInfo), { start: 1, current, end });
await page.waitForFunction(({ round, step }) => {
const text = document.querySelector('#scene')?.textContent;
return text?.includes(`Round: ${round}`) && text.includes(`Step: ${step}`);
}, { round, step });
}
assert.deepEqual(await page.evaluate(() => replayMoves), [], 'replay never submits game moves');
assert.equal(await page.evaluate(() => JSON.stringify(replaySource) === replaySourceBefore), true);
console.log(`powergrid Middle East replay: all ${end} positions and repeated Step 2 crossings passed`);
}

View file

@ -42,6 +42,9 @@
:transform="`translate(${G.map.cityCountPosition[0]}, ${G.map.cityCountPosition[1]})`"
:playerColors="playerColors"
:paymentTable="G.paymentTable"
:poweredCities="poweringCount"
:ownedCities="poweringPlayer ? poweringPlayer.cities.length : undefined"
:poweringIncome="poweringIncome"
:compact="stacked"
:citiesToEndGame="G.citiesToEndGame"
:citiesToStep2="G.map.name === 'Manhattan' ? undefined : G.citiesToStep2"
@ -451,7 +454,7 @@
:color="playerColors[playerIndex]"
:avatar="avatars[playerIndex]"
:owner="playerIndex"
:isCurrentPlayer="isCurrentPlayer(playerIndex)"
:isCurrentPlayer="isCurrentPlayer(playerIndex) && !poweringSubmitting"
:ended="gameEnded(G)"
:isPlayer="player == playerIndex"
:ranking="sortedPlayers.findIndex((x) => x.id == G.players[playerIndex].id) + 1"
@ -590,7 +593,14 @@
<tr>
<th><div>Player</div></th>
<th v-for="player in sortedPlayers" :key="'FS' + player.id">
<div :style="{ backgroundColor: playerColors[player.id], color: colorText(playerColors[player.id]) }">{{ player.name }}</div>
<div
:style="{
backgroundColor: playerColors[player.id],
color: colorText(playerColors[player.id]),
}"
>
{{ player.name }}
</div>
</th>
</tr>
<tr v-for="(cat, i) in ['Cities Powered', 'Money', 'Total Cities']" :key="'FC_' + cat">
@ -615,7 +625,14 @@
<tr>
<th><div>Player</div></th>
<th v-for="player in sortedPlayers" :key="'FS' + player.id">
<div :style="{ backgroundColor: playerColors[player.id], color: colorText(playerColors[player.id]) }">{{ player.name }}</div>
<div
:style="{
backgroundColor: playerColors[player.id],
color: colorText(playerColors[player.id]),
}"
>
{{ player.name }}
</div>
</th>
</tr>
<tr v-for="row in spendingRows" :key="'FC_' + row.label">
@ -827,6 +844,8 @@ import { isUraniumMine, Phase, playerTimeUsed, PowerPlant, PowerPlantType, Resou
import { City } from 'powergrid-engine/src/maps';
import { formatDuration } from '../util/time';
import { playerOrderForDisplay } from '../util/player-order';
import { freePlantMoves, canAutoFinishPowering, poweredCities } from '../util/powering';
import { powerIncome } from 'powergrid-engine/src/engine';
// Portrait layout: the rows the scene is broken into, top to bottom. Slots on
// the same row sit side by side and share one scale. Names map to the `slotX`
@ -930,7 +949,10 @@ const round = (n: number, digits = 2) => Number(n.toFixed(digits));
const log = this._futureState!.log.map((l, i) => ({ index: i, ...l })).filter((l) => l.type == 'move');
to = log[to - 1].index;
this.replaceState(reconstructState(this._futureState!, to + 1), false);
// Middle East reshuffles at Step 2: replay the recorded draws so the
// Step 3 card cannot be drawn repeatedly from a reconstructed deck.
const recordedDraws = this._futureState!.map.name === 'Middle East';
this.replaceState(reconstructState(this._futureState!, to + 1, recordedDraws), false);
this.emitter.emit('replay:info', {
start: 1,
@ -1052,6 +1074,47 @@ export default class Game extends Vue {
soleBuyerPlant: PowerPlant | null = null;
disablePass: boolean = false;
private automaticPoweringRound = '';
get poweringPlayer() {
return this.G?.phase === Phase.Bureaucracy && this.player !== undefined && !this.paused &&
!this.tutorialMove && !this.preferences.analysis && !this.roundPlan
? this.G.players[this.player]
: null;
}
get poweringCount() {
return this.poweringPlayer ? poweredCities(this.G!, this.poweringPlayer) : undefined;
}
get poweringIncome() {
return this.poweringPlayer
? powerIncome(this.G!, { ...this.poweringPlayer, citiesPowered: this.poweringCount! })
: undefined;
}
get poweringSubmitting() {
return this.G?.phase === Phase.Bureaucracy && this.turnMoves.some((move) => move.name === MoveName.Pass);
}
get automaticPoweringKey() {
return this.poweringPlayer && this.canMove() && !this.paused && !this.tutorialMove &&
!this.preferences.analysis && !this.roundPlan && this.committedState && !this.poweringSubmitting
? `${this.G!.round}:${this.player}` : '';
}
@Watch('automaticPoweringKey')
startAutomaticPowering(key: string) {
if (!key || key === this.automaticPoweringRound) return;
this.automaticPoweringRound = key;
const activated = this.activateFreePlants(false);
if (canAutoFinishPowering(this.G!, this.player!)) this.pass();
else if (activated) this.emitter.emit('move', [...this.turnMoves]);
}
activateFreePlants(submit = true) {
if (!this.G || this.player === undefined || this.paused || this.tutorialMove || this.preferences.analysis || this.roundPlan) return;
const before = this.turnMoves.length;
for (const move of freePlantMoves(this.G, this.player)) this.sendMove(move, false);
const activated = this.turnMoves.length > before;
if (activated && submit) this.emitter.emit('move', [...this.turnMoves]);
return activated;
}
@Ref() powerPlantMarket!: PowerPlantMarket;
@Ref() playerOrder!: PlayerOrder;
@ -1487,6 +1550,7 @@ export default class Game extends Vue {
// turn, so the last committed state IS the turn start.
this.replaceState(this.committedState, false);
}
this.activateFreePlants();
}
choosePowerPlant(powerPlant: PowerPlant) {
@ -1874,7 +1938,7 @@ export default class Game extends Vue {
});
}
sendMove(move) {
sendMove(move, submit = true) {
if (this.paused || this.interactionDisabled) {
return;
}
@ -1957,7 +2021,7 @@ export default class Game extends Vue {
// Send the WHOLE turn so far: the platform is stateless between calls and
// replays the buffer from the last committed (saved) state.
this.emitter.emit('move', [...this.turnMoves]);
if (submit) this.emitter.emit('move', [...this.turnMoves]);
// Only adopt a preview that is still TENTATIVE. A committing move (Pass, a bid
// that ends an auction) replays hidden outcomes — deck draws, upkeep — on a
@ -2009,7 +2073,7 @@ export default class Game extends Vue {
canPass() {
if (!this.canMove()) return false;
if (this.disablePass) return false;
if (this.disablePass || this.poweringSubmitting) return false;
const currentPlayer = this.G!.players[this.player!];
const availableMoves = currentPlayer.availableMoves!;
@ -2021,7 +2085,11 @@ export default class Game extends Vue {
if (this.roundPlan) return this.roundPlan.entries.length > 0;
if (!this.canMove()) return false;
// Undo scope = the current tentative turn: anything still in the buffer
if (this.poweringSubmitting) return false;
// Free activations are restored by Undo; only fuel choices are undoable here.
if (this.G?.phase === Phase.Bureaucracy && !this.tutorialMove && !this.preferences.analysis) {
return this.turnMoves.some((move) => move.name === MoveName.UsePowerPlant && move.data.resourcesSpent.length > 0);
}
return this.turnMoves.length > 0;
}
@ -2883,9 +2951,23 @@ ul {
}
}
html {
--powergrid-page-background: #e7ebda;
}
html[data-powergrid-theme='dark'] {
--powergrid-page-background: #171717;
}
@media (prefers-color-scheme: dark) {
html:not([data-powergrid-theme]) {
--powergrid-page-background: #171717;
}
}
body,
html {
background: #e7ebda;
background: var(--powergrid-page-background);
color: #263521;
height: 100%;
width: 100%;

View file

@ -43,6 +43,8 @@
:owner="owner"
:powerPlant="powerPlant"
:canClick="canUse(powerPlant)"
:activationState="activationState(powerPlant)"
:data-plant-number="powerPlant.number"
@click="powerPlantClick(powerPlant)"
/>
@ -249,44 +251,21 @@ export default class PlayerBoard extends Vue {
return name;
}
canUse(powerPlant) {
activationState(plant: PowerPlant) {
if (!this.isPlayer || this.phase !== Phase.Bureaucracy || this.isMine(plant)) return undefined;
if (!this.player.powerPlantsNotUsed.includes(plant.number)) return 'used';
const fuel = [this.player.coalLeft, this.player.oilLeft, this.player.garbageLeft,
this.player.uraniumLeft, this.player.coalLeft + this.player.oilLeft];
if (plant.cost > 0 && fuel[plant.type] < plant.cost) return 'unavailable';
return this.canUse(plant) ? 'ready' : 'idle';
}
canUse(powerPlant: PowerPlant) {
if (!this.isCurrentPlayer) return false;
if (this.player.availableMoves?.[MoveName.DiscardPowerPlant]) {
return powerPlant.number !== this.player.powerPlants[this.player.powerPlants.length - 1].number;
} else {
if (!this.player.availableMoves?.[MoveName.UsePowerPlant]) return false;
if (!this.player.powerPlantsNotUsed.includes(powerPlant.number) || this.player.resourcesUsed.length > 0) {
return false;
}
switch (powerPlant.type) {
case PowerPlantType.Coal: {
return this.player.coalLeft >= powerPlant.cost;
}
case PowerPlantType.Oil: {
return this.player.oilLeft >= powerPlant.cost;
}
case PowerPlantType.Garbage: {
return this.player.garbageLeft >= powerPlant.cost;
}
case PowerPlantType.Uranium: {
return this.player.uraniumLeft >= powerPlant.cost;
}
case PowerPlantType.Hybrid: {
return this.player.coalLeft + this.player.oilLeft >= powerPlant.cost;
}
case PowerPlantType.Wind:
case PowerPlantType.Nuclear:
return this.player.coalLeft + this.player.oilLeft >= powerPlant.cost;
}
}
const moves = this.player.availableMoves;
if (moves?.DiscardPowerPlant) return moves.DiscardPowerPlant.includes(powerPlant.number);
return this.player.resourcesUsed.length === 0 &&
!!moves?.UsePowerPlant?.some((move) => move.powerPlant === powerPlant.number);
}
powerPlantClick(powerPlant: PowerPlant) {

View file

@ -9,6 +9,8 @@
:key="count"
:transform="`translate(${cellX(count)}, ${cellY(count)})`"
>
<rect v-if="count === poweredCities" class="powered-city-marker" x="11" y="12" width="32" height="64" rx="3" fill="none" stroke="#183b32" stroke-width="3" />
<rect v-if="count === poweredCities" x="13" y="57" width="28" height="17" rx="2" fill="#d6ed87" />
<title>
{{
`Cities supplied: ${count}. Income: $${income} before map penalties. Houses show connected cities.`
@ -41,7 +43,8 @@
y="66"
text-anchor="middle"
style="font-size: 15px; dominant-baseline: central"
fill="#fff3cf"
:fill="count === poweredCities ? '#183b32' : '#fff3cf'"
:font-weight="count === poweredCities ? 'bold' : 'normal'"
>
{{ income }}
</text>
@ -63,9 +66,10 @@
</g>
<g class="city-income-legend" :transform="`translate(0, ${compact ? 157 : 87})`">
<circle cx="21" cy="0" r="7" fill="#365343" />
<text x="21" text-anchor="middle" font-size="11" fill="#fff3cf">$</text>
<text x="21" text-anchor="middle" font-size="11" fill="#fff3cf">{{ poweredCities !== undefined ? 'ϟ' : '$' }}</text>
<text x="33" y="0" style="font-size: 13px; dominant-baseline: central" fill="#29432e">
Total income for powered cities
<template v-if="poweredCities !== undefined">{{ poweredCities }} / {{ ownedCities }} cities powered · ${{ poweringIncome }}</template>
<template v-else>Total income for powered cities</template>
</text>
</g>
</g>
@ -97,6 +101,9 @@ export default class CityCount extends Vue {
@Prop() playerColors?: string[];
@Prop({ required: true }) paymentTable!: number[];
@Prop({ default: false }) compact!: boolean;
@Prop() poweredCities?: number;
@Prop() ownedCities?: number;
@Prop() poweringIncome?: number;
houses: (Piece & { cityCount: number })[] = [];

View file

@ -6,10 +6,12 @@
<g
v-else
:id="elId"
:class="[{ canClick: canClick }]"
:class="[{ canClick: canClick }, activationState && 'plant-' + activationState]"
:data-activation="activationState"
:transform="`translate(${currentX}, ${currentY})`"
@click="canClick && $emit('click')"
>
<title v-if="activationState">{{ activationLabel }}</title>
<rect
width="60"
height="40"
@ -65,6 +67,17 @@
<path d="M0,3 L8,3 L8,0 L14,6 L8,12 L8,9 L0,9Z" fill="white" />
</g>
<g v-if="activationState === 'used'" class="plant-activation-badge" pointer-events="none">
<circle cx="56" cy="3" r="8" fill="#183b32" stroke="#e0f2b9" stroke-width="1.5" />
<path
d="M52 3 L55 6 L60 0"
fill="none"
stroke="#e0f2b9"
stroke-width="2.2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</g>
<defs>
<linearGradient id="hybrid" x1="0" y1="0" x2="100%" y2="100%">
<stop offset="50%" stop-color="#8b4513" />
@ -97,6 +110,15 @@ export default class Card extends Mixins(Piece) {
@Prop({ default: false })
hasDiscount?: boolean;
@Prop()
activationState?: 'used' | 'unavailable' | 'ready' | 'idle';
get activationLabel() {
return this.activationState === 'used' ? 'Activated' :
this.activationState === 'unavailable' ? 'Not enough fuel' :
this.activationState === 'ready' ? 'Ready to activate' : 'Not activated';
}
getColor() {
switch (this.powerPlant?.type) {
case PowerPlantType.Coal: return '#8b4513';
@ -125,6 +147,10 @@ export default class Card extends Mixins(Piece) {
}
</script>
<style lang="scss">
.plant-used > rect:first-of-type {
stroke: #183b32;
stroke-width: 3px;
}
.canClick {
cursor: pointer;
}

View file

@ -84,6 +84,9 @@ function launch(selector: string) {
params.avatars = data;
app.$forceUpdate();
},
onTheme({ dark }) {
target.ownerDocument.documentElement.dataset.powergridTheme = dark ? 'dark' : 'light';
},
onUpdate() {
if (!replaying) viewer.fetchState();
},
@ -127,6 +130,7 @@ function launch(selector: string) {
thumbnail.destroy();
removeChat();
viewer.destroy();
delete target.ownerDocument.documentElement.dataset.powergridTheme;
params.emitter.removeAllListeners();
});
dispose = () => {

View file

@ -0,0 +1,28 @@
import type { GameState, Move, Player } from 'powergrid-engine';
import { MoveName } from 'powergrid-engine';
import { isUraniumMine, Phase } from 'powergrid-engine/src/gamestate';
export function freePlantMoves(state: GameState, seat: number): Move[] {
if (state.phase !== Phase.Bureaucracy || !state.currentPlayers.includes(seat)) return [];
const player = state.players[seat];
return (player.availableMoves?.UsePowerPlant || [])
.filter((move) => move.resourcesSpent.length === 0)
.map((data) => ({ name: MoveName.UsePowerPlant, data }));
}
export function poweredCities(state: GameState, player: Player): number {
// Pass resets citiesPowered; the used cards keep the result visible until the next round.
const output = player.powerPlants
.filter((plant) => !isUraniumMine(state, plant) && !player.powerPlantsNotUsed.includes(plant.number))
.reduce((total, plant) => total + plant.citiesPowered, 0);
return Math.min(player.cities.length, output);
}
export function canAutoFinishPowering(state: GameState, seat: number): boolean {
if (state.phase !== Phase.Bureaucracy || !state.currentPlayers.includes(seat)) return false;
const player = state.players[seat];
return (
!!player.availableMoves?.Pass &&
(player.citiesPowered >= player.cities.length || !player.availableMoves.UsePowerPlant?.length)
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,89 @@
import { expect } from 'chai';
import { availableMoves, move, MoveName, Phase, setup } from 'powergrid-engine';
import { powerPlants } from 'powergrid-engine/src/powerPlants';
import { canAutoFinishPowering, freePlantMoves, poweredCities } from '../../src/util/powering';
function position(map: 'Germany' | 'Australia' | 'India' = 'Germany') {
const state = setup(3, { map, variant: 'original' }, 'powering');
state.phase = Phase.Bureaucracy;
state.currentPlayers = [0, 1, 2];
const player = state.players[0];
player.powerPlants = [27, 20, 26].map((number) => ({ ...powerPlants.find((plant) => plant.number === number)! }));
player.powerPlantsNotUsed = [27, 20, 26];
player.cities = state.map.cities.slice(0, 8).map((city) => ({ name: city.name, position: 0 }));
player.coalLeft = 3;
player.oilLeft = 0;
player.passed = false;
player.availableMoves = availableMoves(state, player);
return state;
}
function runFree(state: ReturnType<typeof position>) {
return freePlantMoves(state, 0).reduce((current, action) => move(current, action, 0), state);
}
describe('automatic free plants', () => {
it('uses only legal zero-fuel activations and keeps a real fuel choice open', () => {
const initial = position();
expect(freePlantMoves(initial, 0).map((action) => action.data)).to.deep.equal([
{ powerPlant: 27, resourcesSpent: [], citiesPowered: 3 },
]);
const state = runFree(initial);
expect(state.players[0].coalLeft).to.equal(3);
expect(poweredCities(state, state.players[0])).to.equal(3);
expect(canAutoFinishPowering(state, 0)).to.equal(false);
expect(freePlantMoves(state, 0)).to.deep.equal([]);
});
it('finishes when free output covers all cities without burning stored fuel', () => {
const initial = position();
initial.players[0].cities = initial.players[0].cities.slice(0, 2);
const state = runFree(initial);
expect(poweredCities(state, state.players[0])).to.equal(2);
expect(canAutoFinishPowering(state, 0)).to.equal(true);
expect(state.players[0].coalLeft).to.equal(3);
});
it('finishes after free plants when the other plants lack fuel', () => {
const state = position();
state.players[0].coalLeft = 0;
state.players[0].availableMoves = availableMoves(state, state.players[0]);
expect(canAutoFinishPowering(runFree(state), 0)).to.equal(true);
});
it('keeps the powered count after income is collected', () => {
let state = runFree(position());
state = move(state, { name: MoveName.Pass, data: true }, 0);
expect(state.players[0].citiesPowered).to.equal(0);
expect(poweredCities(state, state.players[0])).to.equal(3);
expect(freePlantMoves(state, 0)).to.deep.equal([]);
expect(canAutoFinishPowering(state, 0)).to.equal(false);
});
it('handles multiple free plants including fusion without consuming fuel', () => {
const state = position();
state.players[0].powerPlants = [27, 50].map((number) => ({
...powerPlants.find((plant) => plant.number === number)!,
}));
state.players[0].powerPlantsNotUsed = [27, 50];
state.players[0].availableMoves = availableMoves(state, state.players[0]);
expect(freePlantMoves(state, 0)).to.have.length(2);
expect(canAutoFinishPowering(runFree(state), 0)).to.equal(true);
});
it('never treats an Australian uranium mine as a city-powering plant', () => {
const state = position('Australia');
state.players[0].powerPlants.push({ ...powerPlants.find((plant) => plant.number === 11)! });
state.players[0].availableMoves = availableMoves(state, state.players[0]);
expect(poweredCities(state, state.players[0])).to.equal(0);
expect(freePlantMoves(state, 0)).to.have.length(1);
});
it('respects India’s required output and legal Pass', () => {
const state = position('India');
state.players[0].targetCitiesPowered = 8;
state.players[0].availableMoves = availableMoves(state, state.players[0]);
const after = runFree(state);
expect(after.players[0].availableMoves!.Pass).to.equal(undefined);
expect(canAutoFinishPowering(after, 0)).to.equal(false);
});
it('does nothing outside the powering phase', () => {
const state = position();
state.phase = Phase.Building;
expect(freePlantMoves(state, 0)).to.deep.equal([]);
expect(canAutoFinishPowering(state, 0)).to.equal(false);
});
});