diff --git a/viewer/scripts/powering-preview.mjs b/viewer/scripts/powering-preview.mjs
new file mode 100644
index 0000000..b2bfaba
--- /dev/null
+++ b/viewer/scripts/powering-preview.mjs
@@ -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 = `
Powergrid · Plant activation previewPlant activation Local preview · not published`;
+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))
+ );
diff --git a/viewer/scripts/protocol-smoke.mjs b/viewer/scripts/protocol-smoke.mjs
index 77685e3..dfcb83b 100644
--- a/viewer/scripts/protocol-smoke.mjs
+++ b/viewer/scripts/protocol-smoke.mjs
@@ -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`);
diff --git a/viewer/scripts/replay-smoke.mjs b/viewer/scripts/replay-smoke.mjs
new file mode 100644
index 0000000..70c6d16
--- /dev/null
+++ b/viewer/scripts/replay-smoke.mjs
@@ -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`);
+}
diff --git a/viewer/src/components/Game.vue b/viewer/src/components/Game.vue
index 94e9f8b..ef04763 100644
--- a/viewer/src/components/Game.vue
+++ b/viewer/src/components/Game.vue
@@ -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 @@
Player |
- {{ player.name }}
+
+ {{ player.name }}
+
|
@@ -615,7 +625,14 @@
Player |
- {{ player.name }}
+
+ {{ player.name }}
+
|
@@ -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%;
diff --git a/viewer/src/components/PlayerBoard.vue b/viewer/src/components/PlayerBoard.vue
index 90e8013..149aee8 100644
--- a/viewer/src/components/PlayerBoard.vue
+++ b/viewer/src/components/PlayerBoard.vue
@@ -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) {
diff --git a/viewer/src/components/boards/CityCount.vue b/viewer/src/components/boards/CityCount.vue
index ed54af2..e30bc3c 100644
--- a/viewer/src/components/boards/CityCount.vue
+++ b/viewer/src/components/boards/CityCount.vue
@@ -9,6 +9,8 @@
:key="count"
:transform="`translate(${cellX(count)}, ${cellY(count)})`"
>
+
+
{{
`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 }}
@@ -63,9 +66,10 @@
- $
+ {{ poweredCities !== undefined ? 'ϟ' : '$' }}
- Total income for powered cities
+ {{ poweredCities }} / {{ ownedCities }} cities powered · ${{ poweringIncome }}
+ Total income for powered cities
@@ -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 })[] = [];
diff --git a/viewer/src/components/pieces/Card.vue b/viewer/src/components/pieces/Card.vue
index b8119c2..d1bfaa1 100644
--- a/viewer/src/components/pieces/Card.vue
+++ b/viewer/src/components/pieces/Card.vue
@@ -6,10 +6,12 @@
+ {{ activationLabel }}
+
+
+
+
@@ -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) {
}