From 60484d3d4cf97f0d2a16ec755b9ef7e43b2fedb7 Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Sun, 22 Nov 2026 12:34:15 +0000 Subject: [PATCH] Add atomic local multi-carrier boarding and release regression coverage --- .github/workflows/web-viewer.yml | 2 + docs/fleet-boarding.md | 39 ++++++ server/src/movement.rs | 110 +++++++++++++++++ server/src/web_view/actions.rs | 4 +- server/tests/movement_tests.rs | 136 +++++++++++++++++++++ web-client/docs/viewer-publishing.md | 23 ++++ web-client/package-lock.json | 4 +- web-client/package.json | 5 +- web-client/release/achievement-assets.json | 2 +- web-client/release/engine-package.json | 2 +- web-client/scripts/boarding-fixture.mjs | 22 ++++ web-client/scripts/boarding-smoke.mjs | 84 +++++++++++++ web-client/scripts/boarding.test.mjs | 112 +++++++++++++++++ web-client/scripts/civilizations-smoke.mjs | 2 +- web-client/scripts/embark-smoke.mjs | 4 +- web-client/scripts/undo-smoke.mjs | 22 +++- web-client/src/SettlerPanel.svelte | 30 ++++- web-client/src/boarding.test.ts | 14 +++ web-client/src/boarding.ts | 13 +- web-client/src/controller.test.ts | 13 +- web-client/src/controller.ts | 46 ++++--- web-client/src/localization/da.json | 4 +- web-client/src/localization/de.json | 4 +- web-client/src/localization/el.json | 4 +- web-client/src/localization/en.json | 4 +- web-client/src/localization/fa.json | 4 +- web-client/src/localization/fr.json | 4 +- web-client/src/localization/hi.json | 4 +- web-client/src/localization/it.json | 4 +- web-client/src/localization/ko.json | 4 +- web-client/src/localization/nl.json | 4 +- web-client/src/localization/pl.json | 4 +- web-client/src/localization/pt-BR.json | 4 +- web-client/src/localization/ro.json | 4 +- web-client/src/localization/ru.json | 4 +- web-client/src/localization/vi.json | 4 +- web-client/src/localization/zh-CN.json | 4 +- web-client/src/localization/zh-TW.json | 4 +- web-client/src/prediction.ts | 5 + web-client/src/types.ts | 1 + 40 files changed, 693 insertions(+), 70 deletions(-) create mode 100644 docs/fleet-boarding.md create mode 100644 web-client/scripts/boarding-fixture.mjs create mode 100644 web-client/scripts/boarding-smoke.mjs create mode 100644 web-client/scripts/boarding.test.mjs diff --git a/.github/workflows/web-viewer.yml b/.github/workflows/web-viewer.yml index 79d44a6f..7abbf386 100644 --- a/.github/workflows/web-viewer.yml +++ b/.github/workflows/web-viewer.yml @@ -26,6 +26,8 @@ jobs: working-directory: web-client - run: node scripts/resource-journal-smoke.mjs && node scripts/famine-journal-smoke.mjs && node scripts/construction-smoke.mjs && node scripts/research-card-smoke.mjs working-directory: web-client + - run: npm run test:boarding && node scripts/embark-smoke.mjs && node scripts/ship-landing-smoke.mjs + working-directory: web-client - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: clash-viewer diff --git a/docs/fleet-boarding.md b/docs/fleet-boarding.md new file mode 100644 index 00000000..dec661d0 --- /dev/null +++ b/docs/fleet-boarding.md @@ -0,0 +1,39 @@ +# Local multi-carrier boarding + +A land group can board multiple ships in the **same adjacent sea space** through +one confirmed movement action. Selecting the destination opens the normal movement +panel's passenger assignments; it does not submit a move. Carrier labels identify +the ship and account for existing cargo. Confirm with **Board ship**. + +`Movement.Move.boarding` is an optional array of assignments. The outer `units` +list must match the assignment union exactly, without duplicates. Each assignment +has its own owned `embark_carrier_id` or neutral `embark_pirate`; the namespaces are +separate. Nested assignments, payments, attacks, different destinations, already +transported passengers and transfers within a sea space are rejected. Execution +uses a disposable game clone, so a rejected later assignment cannot leave an +earlier load or pirate claim behind. Valid assignments use the existing embark +movement group and therefore share one movement allocation. + +Carthage's Pirate Allies claims all neutral ships at the destination, mapping each +neutral ID to a newly owned ID. These claims must respect the four-ship space limit +and eight-ship total limit. The normal movement validation still applies, including +Tactics, moved-unit restrictions, Navigator and civilization-specific capacity +(Viking Longships carry three passengers). + +Old movement payloads omit `boarding` when empty, preserving their serialization. +There is no save migration or production-history repair. + +## Regression checks + +- `npm test` includes durable WASM assignment, invalid-later-assignment, + deterministic retry, log/action count, undo/redo/branch, queue projection, + Tactics, Navigator, Longships, namespace and pirate limit checks. +- `npm run test:boarding` rebuilds the bridge and viewer and exercises physical + clicks on a normal-size map at desktop and mobile widths, for owned and neutral + fleets with two and four passengers. It uses the supported Strategy map account + preference, not forced or synthetic click events. +- Web viewer CI also runs the existing embark and ship-landing browser regressions. + +The separate old-history replay and hidden-state prediction suites remain required +release checks; the edited local boarding fixtures do not purport to be generated +production histories. diff --git a/server/src/movement.rs b/server/src/movement.rs index fd72b817..41cb809a 100644 --- a/server/src/movement.rs +++ b/server/src/movement.rs @@ -29,6 +29,8 @@ use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] pub struct MoveUnits { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub boarding: Vec, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub attack_pirates: bool, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -54,6 +56,7 @@ impl MoveUnits { payment: ResourcePile, ) -> Self { Self { + boarding: vec![], city: None, attack_pirates: false, embark_pirate: None, @@ -345,6 +348,11 @@ pub(crate) fn execute_movement_action( action: MovementAction, player_index: usize, ) -> Result<(), String> { + if let Move(m) = &action { + if !m.boarding.is_empty() { + return execute_boarding(game, player_index, m); + } + } let player = EventPlayer::new(player_index, move_event_origin()); match &action { Move(m) if m.city.is_some() => player.log( @@ -413,6 +421,108 @@ fn has_any_moves_left(game: &mut Game) -> bool { } } +// Validate and execute on a disposable state: no payment, claims or partial loads +// survive a rejected fleet assignment. Carrier namespaces remain distinct. +fn execute_boarding(game: &mut Game, player: usize, m: &MoveUnits) -> Result<(), String> { + let invalid = || "Invalid fleet boarding assignment".to_string(); + if m.city.is_some() + || m.attack_pirates + || m.embark_pirate.is_some() + || m.embark_carrier_id.is_some() + || !m.payment.is_empty() + || m.units.is_empty() + { + return Err(invalid()); + } + let p = game.player(player); + let start = p.try_get_unit(m.units[0]).ok_or_else(invalid)?.position; + if !game.map.is_land(start) + || !game.map.is_sea(m.destination) + || !start.is_neighbor(m.destination) + { + return Err(invalid()); + } + let mut seen = HashSet::new(); + for group in &m.boarding { + if !group.boarding.is_empty() + || group.city.is_some() + || group.attack_pirates + || !group.payment.is_empty() + || group.destination != m.destination + || group.units.is_empty() + || (group.embark_carrier_id.is_some() == group.embark_pirate.is_some()) + { + return Err(invalid()); + } + for id in &group.units { + let u = p.try_get_unit(*id).ok_or_else(invalid)?; + if !seen.insert(*id) + || !u.is_land_based() + || u.carrier_id.is_some() + || u.position != start + { + return Err(invalid()); + } + } + if let Some(id) = group.embark_carrier_id { + let ship = p.try_get_unit(id).ok_or_else(invalid)?; + if !ship.is_ship() || ship.position != m.destination { + return Err(invalid()); + } + } + } + if seen.len() != m.units.len() || m.units.iter().any(|id| !seen.remove(id)) { + return Err(invalid()); + } + let mut preview = game.clone(); + let mut claimed = std::collections::HashMap::new(); + if m.boarding.iter().any(|g| g.embark_pirate.is_some()) { + if !p.has_special_advance(SpecialAdvance::PirateAllies) { + return Err(invalid()); + } + let pirates = crate::content::civilizations::carthage::pirate_player(game); + let ships: Vec<_> = game + .player(pirates) + .units + .iter() + .filter(|u| u.is_ship() && u.position == m.destination) + .map(|u| u.id) + .collect(); + if m.boarding + .iter() + .filter_map(|g| g.embark_pirate) + .any(|id| !ships.contains(&id)) + { + return Err(invalid()); + } + if p.units.iter().filter(|u| u.is_ship()).count() + ships.len() > 8 + || p.units + .iter() + .filter(|u| u.is_ship() && u.position == m.destination) + .count() + + ships.len() + > 4 + { + return Err(invalid()); + } + for id in ships { + claimed.insert( + id, + crate::content::civilizations::carthage::claim_pirate(&mut preview, player, id), + ); + } + } + for group in &m.boarding { + let mut group = group.clone(); + if let Some(id) = group.embark_pirate.take() { + group.embark_carrier_id = Some(claimed[&id]); + } + execute_movement_action(&mut preview, Move(group), player)?; + } + *game = preview; + Ok(()) +} + fn execute_move_action(game: &mut Game, player: &EventPlayer, m: &MoveUnits) -> Result<(), String> { let p = player.get(game); let starting_position = diff --git a/server/src/web_view/actions.rs b/server/src/web_view/actions.rs index 98e85e91..bcb4b6d7 100644 --- a/server/src/web_view/actions.rs +++ b/server/src/web_view/actions.rs @@ -297,7 +297,7 @@ pub fn movement(game: &Game, seat: usize, units: Vec) -> Result) -> Result = (0..count).filter(|id| !first.contains(id)).collect(); + m.boarding.push(MoveUnits::new( + first.clone(), + sea, + Some(10), + ResourcePile::empty(), + )); + if !second.is_empty() { + m.boarding.push(MoveUnits::new( + second.clone(), + sea, + Some(11), + ResourcePile::empty(), + )); + } + if pirates { + for group in &mut m.boarding { + group.embark_pirate = group.embark_carrier_id.take().map(|id| id - 8); + } + } + let before = serde_json::to_value(game.clone().data()).unwrap(); + let result = try_execute_action(game.clone(), Action::Movement(Move(m.clone())), 0); + if count == 4 && split { + assert!(result.is_err()); + assert_eq!(serde_json::to_value(game.clone().data()).unwrap(), before); + continue; + } + game = result.unwrap(); + assert_eq!(game.actions_left, 2); + for id in first { + assert_eq!( + game.player(0).get_unit(id).carrier_id, + Some(if pirates { 22 } else { 10 }) + ); + } + for id in second { + assert_eq!( + game.player(0).get_unit(id).carrier_id, + Some(if pirates { 23 } else { 11 }) + ); + } + if let GameState::Movement(state) = &game.state { + assert_eq!(state.movement_actions_left, 2); + } else { + panic!("expected movement"); + } + // A repeated assignment cannot transfer passengers at sea or charge again. + let before = serde_json::to_value(game.clone().data()).unwrap(); + assert!(try_execute_action(game.clone(), Action::Movement(Move(m)), 0).is_err()); + assert_eq!(serde_json::to_value(game.clone().data()).unwrap(), before); + } + } + } +} + +#[test] +fn legacy_move_payload_omits_optional_fleet_assignment() { + let legacy = serde_json::json!({"units":[1],"destination":"D8","embark_carrier_id":10}); + let action: MoveUnits = serde_json::from_value(legacy.clone()).unwrap(); + assert!(action.boarding.is_empty()); + assert_eq!(serde_json::to_value(action).unwrap(), legacy); +} diff --git a/web-client/docs/viewer-publishing.md b/web-client/docs/viewer-publishing.md index d071e567..348ed6f2 100644 --- a/web-client/docs/viewer-publishing.md +++ b/web-client/docs/viewer-publishing.md @@ -1740,3 +1740,26 @@ Preserve catalog revision 8 (46 definitions), artwork revision 4, all 60 named asset bytes, gallery, preferences/settings and Standard options. The faction artwork manifest's lockfile integrity hash changes only for the viewer version bump; no artwork is republished. No production moves, history edits or rewinds. + +# Viewer 0.1.234 / engine 0.4.165 — local multi-carrier boarding + +Adds an optional, backward-compatible `MoveUnits.boarding` assignment list. A +single confirmed move boards one land group onto multiple adjacent co-located +ships, validating atomically on a cloned game before committing. Pirate IDs map +into the owned namespace only during successful all-space claims. Existing cargo, +Longships, Tactics, Navigator, movement allocations and pirate ship limits remain +validated. The old sequential client queue is removed; the normal movement panel +shows passenger selectors and requires **Board ship** confirmation. + +See [fleet boarding](../../docs/fleet-boarding.md) for payload constraints and +regression coverage. Web viewer CI runs the durable WASM suite and desktop/mobile +physical-click boarding, existing embark and landing smokes. The civilization +smoke uses the current `Abilities` control label rather than its obsolete name. + +Release gate: push matching source to main and require green Check and Web viewer +CI **before** BGS publication. Verify all hosted viewer files and downloaded engine +bytes, run boarding on those actual artifacts, and preserve catalog revision 8 / +46 definitions, artwork revision 4, all 60 named assets and gallery/settings/ +preferences/Standard options. Only the frozen artwork manifest's lockfile integrity +pin changes for the viewer version bump; no artwork or catalog is republished. +No production moves, migrations, history edits or rewinds are involved. diff --git a/web-client/package-lock.json b/web-client/package-lock.json index 2e6b05d5..f7990c09 100644 --- a/web-client/package-lock.json +++ b/web-client/package-lock.json @@ -1,12 +1,12 @@ { "name": "@boardgamers/clash-web-client", - "version": "0.1.233", + "version": "0.1.234", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@boardgamers/clash-web-client", - "version": "0.1.233", + "version": "0.1.234", "dependencies": { "@boardgamers/protocol": "0.11.0", "lucide-svelte": "^0.577.0", diff --git a/web-client/package.json b/web-client/package.json index 17f0fd10..653eb485 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -1,13 +1,14 @@ { "name": "@boardgamers/clash-web-client", - "version": "0.1.233", + "version": "0.1.234", "private": true, "type": "module", "scripts": { "dev": "vite --host 127.0.0.1 --port 8643", "build": "vite build", "check": "svelte-check --tsconfig ./tsconfig.json", - "test": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs && npm run test:achievement-assets && npm run test:locales && node scripts/exhausted-movement-check.mjs && CLASH_WASM=\"$PWD/.engine/server.js\" node --test ../scripts/status-phase-battle.test.cjs ../scripts/postcombat-queue.test.cjs ../scripts/tributes.test.cjs", + "test": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs scripts/boarding.test.mjs && npm run test:achievement-assets && npm run test:locales && node scripts/exhausted-movement-check.mjs && CLASH_WASM=\"$PWD/.engine/server.js\" node --test ../scripts/status-phase-battle.test.cjs ../scripts/postcombat-queue.test.cjs ../scripts/tributes.test.cjs", + "test:boarding": "npm run build:bridge && npm run build && node --test scripts/boarding.test.mjs && node scripts/boarding-smoke.mjs", "test:home-orientation": "npm run build && node scripts/home-orientation-smoke.mjs", "build:achievement-assets": "node scripts/build-achievement-assets.mjs", "test:achievement-assets": "node --test scripts/achievement-assets.test.mjs scripts/publish-achievement-assets.test.mjs scripts/publish-achievement-backups.test.mjs", diff --git a/web-client/release/achievement-assets.json b/web-client/release/achievement-assets.json index 7853771a..641e78d4 100644 --- a/web-client/release/achievement-assets.json +++ b/web-client/release/achievement-assets.json @@ -13,7 +13,7 @@ "web-client/src/civilization-emblems.ts": "01b0cbf3fa77a8466532ccd73d63c1a3ddc9bbc79fc06ce7224b425322a9c9f0", "web-client/src/civilization-flags.ts": "cd176076bfe05b3059093b80c88596b7ae46b77898695c6c7406cbe1a3a0f78b", "server/src/content/civilizations.rs": "73602f3db506f3dc2dbc6de43d01179440fd3bb034c997ff209336faaef2a332", - "web-client/package-lock.json": "38bdad294151ea0429b09c241e112014a445b77918914886e5a431d268739df5", + "web-client/package-lock.json": "e13672f16b16cb39d284f0ba017084769a75fbb4e2ddcc3bc37aefc0e98811d8", "web-client/node_modules/lucide-svelte/dist/Icon.svelte": "f7b49ab842c143fa680fa8bd9a54a9efdc48c2e2d49fa574bd5ccf8f6cfca5be", "web-client/node_modules/lucide-svelte/dist/defaultAttributes.js": "5b8981c6e3434ae6538716af9e0403554e7708c4087f18d060950a7bef00d96a", "web-client/node_modules/lucide-svelte/LICENSE": "668dcc52803480e0a026b31140a4cae668772663cd764e5991d252eef03f98db" diff --git a/web-client/release/engine-package.json b/web-client/release/engine-package.json index f8546ee7..195fc8f0 100644 --- a/web-client/release/engine-package.json +++ b/web-client/release/engine-package.json @@ -1,6 +1,6 @@ { "name": "@boardgamers/clash-server", - "version": "0.4.164", + "version": "0.4.165", "description": "Clash of Cultures: Monumental edition engine for Boardgamers Space", "license": "MIT", "type": "commonjs", diff --git a/web-client/scripts/boarding-fixture.mjs b/web-client/scripts/boarding-fixture.mjs new file mode 100644 index 00000000..09b734c7 --- /dev/null +++ b/web-client/scripts/boarding-fixture.mjs @@ -0,0 +1,22 @@ +import { readFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +export const engine = createRequire(import.meta.url)('../.engine/server.js'); +const base = JSON.parse(await readFile(new URL('../../server/tests/test_games/movement/movement.json', import.meta.url), 'utf8')); +const fullMap = JSON.parse(await readFile(new URL('../../server/tests/test_games/movement/ship_navigation_unit_test.json', import.meta.url), 'utf8')).map; +const npcs = JSON.parse(await engine.init(2, [], {}, 'boarding', {})).players.slice(2); +export function fixture(pirates, count) { + const state = structuredClone(base); + state.state = 'Playing'; state.actions_left = 3; + state.players.push(...structuredClone(npcs)); + for (const p of state.players) { p.units = []; p.cities = []; } + const p = state.players[0]; + p.civilization = pirates ? 'Carthage' : 'Rome'; + p.advances = ['Farming','Mining','Tactics','Navigation']; + p.next_unit_id = 22; + p.units = Array.from({length:count}, (_,id) => ({id,position:'F7',unit_type:id < 2 ? 'Infantry' : 'Elephant'})); + const owner = pirates ? state.players.find(p => p.civilization === 'Pirates') : p; + owner.units.push(...(pirates ? [2,3] : [10,11]).map(id => ({id,position:'F6',unit_type:'Ship'}))); + state.map = structuredClone(fullMap); + state.map.tiles = state.map.tiles.map(([position]) => [position, ['F6','G7'].includes(position) ? 'Water' : 'Fertile']); + return state; +} diff --git a/web-client/scripts/boarding-smoke.mjs b/web-client/scripts/boarding-smoke.mjs new file mode 100644 index 00000000..4bd2e11b --- /dev/null +++ b/web-client/scripts/boarding-smoke.mjs @@ -0,0 +1,84 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { chromium } from 'playwright'; +import { engine, fixture } from './boarding-fixture.mjs'; +// Existing cargo must count, even when the client forges an oversized load. +{ + const state = fixture(false, 3); + state.players[0].units.find(u => u.id === 10).carried_units = [{id:9,unit_type:'Infantry'}]; + const action = {Movement:{Move:{units:[0,1,2],destination:'F6',boarding:[ + {units:[0],destination:'F6',embark_carrier_id:10}, + {units:[1,2],destination:'F6',embark_carrier_id:11}, + ]}}}; + const after = JSON.parse(engine.tryMove(JSON.stringify(state),JSON.stringify(action),0)); + assert.deepEqual(after.players[0].units.filter(u => u.unit_type === 'Ship').map(u => u.carried_units.length),[2,2]); + action.Movement.Move.boarding[0].units = [0,1]; + action.Movement.Move.boarding[1].units = [2]; + assert.throws(() => engine.tryMove(JSON.stringify(state),JSON.stringify(action),0)); + state.players[0].units.find(u => u.id === 10).carried_units.push({id:8,unit_type:'Infantry'}); + assert.throws(() => engine.tryMove(JSON.stringify(state),JSON.stringify(action),0)); +} +const browser = await chromium.launch({headless:true,args:['--use-gl=angle','--use-angle=swiftshader']}); +try { + for (const width of [1400,390]) for (const pirates of [false,true]) for (const count of [2,4]) { + const state = fixture(pirates,count), sent = [], errors = []; + const page = await browser.newPage({viewport:{width,height:900}}); + page.on('pageerror', e => { errors.push(e.message); console.error(e.message); }); + await page.exposeFunction('captureMove', move => sent.push(JSON.parse(move))); + await page.route('**/*', async route => { + const path = new URL(route.request().url()).pathname; + if (path === '/') return route.fulfill({contentType:'text/html',body:'
'}); + if (!['/viewer.js','/server_bg.wasm'].includes(path)) return route.abort(); + return route.fulfill({contentType:path.endsWith('.wasm') ? 'application/wasm':'text/javascript',body:await readFile(new URL('../dist'+path,import.meta.url))}); + }); + await page.goto('http://clash.test/'); + await page.evaluate(raw => { + window.host = clash3d.launch('#app'); + host.on('move', m => window.captureMove(m)); + host.emit('player',{index:0}); host.emit('preferences',{sound:false,mapView:'strategy',homeAtBottom:false}); host.emit('state',raw); + },engine.stripSecret(JSON.stringify(state),0)); + await page.waitForTimeout(800); + await page.getByRole('button',{name:'Move units and found cities',exact:true}).click(); + + async function tap(position) { + await page.locator(`.strategy-map-tile[data-position="${position}"]`).click(); + await page.waitForTimeout(200); + } + await tap('F7'); + + await tap('F6'); + const assignments = page.locator('.boarding-assignment select'); + await assignments.first().waitFor(); + assert.equal(await assignments.count(),count); + assert.equal(sent.length,0,'destination opens cargo choices without submitting'); + if (count === 2) { + await assignments.nth(1).selectOption(String(pirates ? -4 : 11)); + assert.notEqual(await assignments.nth(0).inputValue(),await assignments.nth(1).inputValue()); + } + await page.getByRole('region',{name:'Unit movement',exact:true}).getByRole('button',{name:/^Board ship/}).click(); + assert.equal(sent.length,1); + const invalid = structuredClone(sent[0]); + invalid.Movement.Move.boarding[0].units.push(invalid.Movement.Move.boarding[0].units[0]); + assert.throws(() => engine.tryMove(JSON.stringify(state),JSON.stringify(invalid),0)); + const unknown = structuredClone(sent[0]); + unknown.Movement.Move.boarding[0].embark_carrier_id = 9999; + delete unknown.Movement.Move.boarding[0].embark_pirate; + assert.throws(() => engine.tryMove(JSON.stringify(state),JSON.stringify(unknown),0)); + if (pirates) { + const ordinary = structuredClone(state); ordinary.players[0].civilization = 'Rome'; + assert.throws(() => engine.tryMove(JSON.stringify(ordinary),JSON.stringify(sent[0]),0)); + } + let after = JSON.parse(engine.tryMove(JSON.stringify(state),JSON.stringify(sent[0]),0)); + const ships = after.players[0].units.filter(u => u.unit_type === 'Ship'); + assert.deepEqual(ships.map(u => u.carried_units.length), count === 2 ? [1,1] : [2,2]); + assert.equal(after.actions_left,2); + assert.equal(after.state.Movement.movement_actions_left,2); + assert.throws(() => engine.tryMove(JSON.stringify(after),JSON.stringify(sent[0]),0), 'no same-sea reassignment'); + after = JSON.parse(engine.tryMove(JSON.stringify(after),JSON.stringify({Movement:{Move:{units:ships.map(u=>u.id),destination:'G7'}}}),0)); + assert(after.players[0].units.every(u => u.position === 'G7')); + assert.deepEqual(errors,[]); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + console.log('Fleet boarding browser/WASM passed',{width,pirates,count}); + await page.close(); + } +} finally { await browser.close(); } diff --git a/web-client/scripts/boarding.test.mjs b/web-client/scripts/boarding.test.mjs new file mode 100644 index 00000000..4196559a --- /dev/null +++ b/web-client/scripts/boarding.test.mjs @@ -0,0 +1,112 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { engine, fixture } from './boarding-fixture.mjs'; +const move = (raw, action) => engine.tryMove(raw, JSON.stringify(action), 0); +const assignment = (pirates) => ({Movement:{Move:{units:[0,1,2,3],destination:'F6',boarding:[ + {units:[0,1],destination:'F6',[pirates?'embark_pirate':'embark_carrier_id']:pirates?2:10}, + {units:[2,3],destination:'F6',[pirates?'embark_pirate':'embark_carrier_id']:pirates?3:11}, +]}}}); +for (const pirates of [false,true]) { + test(`compound boarding ${pirates?'pirates':'owned'}: invalid later load leaves all state and subsequent execution unchanged`, () => { + const state = fixture(pirates,4), action = assignment(pirates), raw = JSON.stringify(state); + const expected = move(raw, action); + for (const change of [ + a => { a.boarding[1].units.push(0); }, + a => { a.boarding[1][pirates?'embark_pirate':'embark_carrier_id'] = 9999; }, + a => { a.boarding[0].units = [0]; a.boarding[1].units = [1,2,3]; }, + a => { a.boarding[1].destination = 'G7'; }, + a => { a.boarding[1].payment = {gold:1}; }, + ]) { + const bad = structuredClone(action); change(bad.Movement.Move); + assert.throws(() => move(raw,bad)); + assert.equal(JSON.stringify(state),raw); + // Includes RNG state, claims, logs, action count, history and all private hands. + assert.equal(move(raw,action),expected); + for (const seat of [0,1,undefined]) assert.equal(engine.stripSecret(raw,seat),engine.stripSecret(JSON.stringify(state),seat)); + } + const after = JSON.parse(expected); + assert.equal(after.actions_left,2); + assert.equal(after.state.Movement.movement_actions_left,2); + assert.deepEqual(after.players[0].units.filter(u=>u.unit_type==='Ship').map(u=>u.carried_units.length),[2,2]); + assert.equal(engine.logLength(expected),engine.logLength(raw)+1); + const undone = move(expected,'Undo'); + assert.deepEqual(JSON.parse(undone).players,JSON.parse(engine.setPlayerSettings(raw,0,state.players[0].settings ?? {})).players); + const redone = move(undone,'Redo'); + assert.deepEqual(JSON.parse(redone).players,after.players); + assert.equal(JSON.parse(redone).actions_left,after.actions_left); + const branched = move(undone,action); + assert.deepEqual(JSON.parse(branched).players,after.players); + assert.throws(()=>move(expected,action),'no same-space transfers'); + }); + test(`compound boarding ${pirates?'pirates':'owned'}: Tactics and per-passenger restrictions are not bypassed`, () => { + const state = fixture(pirates,4); + state.players[0].advances = state.players[0].advances.filter(a=>a!=='Tactics'); + assert.throws(()=>move(JSON.stringify(state),assignment(pirates))); + const moved = fixture(pirates,4); + moved.state = {Movement:{movement_actions_left:2,moved_units:[2]}}; + assert.throws(()=>move(JSON.stringify(moved),assignment(pirates))); + }); +} + +test('Viking Longships retain three-passenger capacity in a compound assignment', () => { + const state = fixture(false,4); + state.players[0].civilization = 'Vikings'; + state.players[0].advances.push('WarShips'); + const action = assignment(false); + action.Movement.Move.boarding[0].units = [0]; + action.Movement.Move.boarding[1].units = [1,2,3]; + const after = JSON.parse(move(JSON.stringify(state),action)); + assert.deepEqual(after.players[0].units.filter(u=>u.unit_type==='Ship').map(u=>u.carried_units.length),[1,3]); +}); + +for (const pirates of [false,true]) test(`compound boarding projects as one undoable queue entry (${pirates})`, async () => { + const { ActionQueue } = await import('../src/action-queue.ts'); + const raw = JSON.stringify(fixture(pirates,4)); + const queue = new ActionQueue(engine,0,raw); + const before = queue.projected; + assert.deepEqual(queue.append(assignment(pirates)),{ok:true}); + assert.equal(queue.count,1); + assert.equal(JSON.parse(queue.projected).actions_left,2); + const result = queue.replay(raw); + assert.equal(result.applied,1); + assert.deepEqual(result.remaining,[]); + assert.deepEqual(JSON.parse(result.raw).players,JSON.parse(move(raw,assignment(pirates))).players); + queue.undo(); + assert.equal(queue.count,0); + assert.equal(queue.projected,before); +}); + +test('pirate boarding claims the whole space, maps IDs separately, and enforces 4 per space / 8 total', () => { + const state = fixture(true,4); + const neutral = state.players.find(p=>p.civilization==='Pirates'); + // A colored carrier with a numerically colliding ID is never mistaken for a pirate. + // Free passenger ID 2 before giving that same numeric ID to an owned ship. + state.players[0].units[2].id = 4; + state.players[0].units.push({id:2,position:'G7',unit_type:'Ship'}); + neutral.units.push({id:5,position:'F6',unit_type:'Ship'},{id:6,position:'F6',unit_type:'Ship'}); + const action = assignment(true); + action.Movement.Move.units = [0,1,4,3]; + action.Movement.Move.boarding[1].units = [4,3]; + for(let id=30;id<33;id++)state.players[0].units.push({id,position:'G7',unit_type:'Ship'}); + state.players[0].next_unit_id=40; + const after = JSON.parse(move(JSON.stringify(state),action)); + assert.equal(after.players[0].units.filter(u=>u.unit_type==='Ship').length,8); + assert.equal(after.players.find(p=>p.civilization==='Pirates').units?.length??0,0); + assert.equal(after.players[0].units.find(u=>u.id===2).position,'G7'); + assert.deepEqual(after.players[0].units.filter(u=>u.position==='F6').map(u=>u.id),[40,41,42,43]); + const ninth = structuredClone(state); + ninth.players[0].units.push({id:34,position:'G7',unit_type:'Ship'}); + assert.throws(()=>move(JSON.stringify(ninth),action)); + const fifth = structuredClone(state); + fifth.players.find(p=>p.civilization==='Pirates').units.push({id:7,position:'F6',unit_type:'Ship'}); + fifth.players[0].units = fifth.players[0].units.filter(u=>u.id!==32); + assert.throws(()=>move(JSON.stringify(fifth),action)); +}); + +test('Navigator cannot be used to embark fresh land passengers', () => { + const state = fixture(false,4); + state.players[0].civilization = 'Carthage'; + state.players[0].event_info = {'Navigator active':'yes'}; + state.state = {Movement:{movement_actions_left:1,unit_only:true}}; + assert.throws(()=>move(JSON.stringify(state),assignment(false))); +}); diff --git a/web-client/scripts/civilizations-smoke.mjs b/web-client/scripts/civilizations-smoke.mjs index dd5ce383..f5386c21 100644 --- a/web-client/scripts/civilizations-smoke.mjs +++ b/web-client/scripts/civilizations-smoke.mjs @@ -125,7 +125,7 @@ try { az.players[enemy].held_units = { infantry: 2 }; app = await load(width, dark, az); page = app.page; - await page.getByRole('button', { name: 'Abilities and cultural influence', exact: true }).click(); + await page.getByRole('button', { name: 'Abilities', exact: true }).click(); await page.getByRole('button', { name: /Use Human Sacrifice/ }).click(); const decision = page.getByRole('region', { name: 'Human Sacrifice', exact: true }); await decision.waitFor(); diff --git a/web-client/scripts/embark-smoke.mjs b/web-client/scripts/embark-smoke.mjs index c94ba583..cc77b48e 100644 --- a/web-client/scripts/embark-smoke.mjs +++ b/web-client/scripts/embark-smoke.mjs @@ -48,8 +48,10 @@ try { assert.match(await panel.innerText(), /3 selected/); await tap('C3'); assert.equal(await panel.getByRole('button',{name:/Board all/}).count(),0); + assert.equal(await page.evaluate(() => sent.length),0,'destination only opens passenger assignments'); + await panel.getByRole('button',{name:/^Board ship/}).click(); let raw=JSON.stringify(state); - for(let i=0;i<2;i++) { + for(let i=0;i<1;i++) { await page.waitForFunction(i=>sent.length>i,i); const action=await page.evaluate(i=>sent[i],i); raw=engine.tryMove(raw,typeof action==='string'?action:JSON.stringify(action),0); diff --git a/web-client/scripts/undo-smoke.mjs b/web-client/scripts/undo-smoke.mjs index e4087f12..25ac6771 100644 --- a/web-client/scripts/undo-smoke.mjs +++ b/web-client/scripts/undo-smoke.mjs @@ -12,11 +12,18 @@ const input = JSON.parse( 'utf8', ), ); +// Old native fixture predates the always-present NPC seats. Do not rewrite +// optional exported saves: only complete this local test fixture. +if (!process.argv[2]) { + const npcs = JSON.parse(await engine.init(2, [], {}, 'undo-smoke', {})).players.slice(2); + for (const npc of npcs) if (!input.players.some(p => p.civilization === npc.civilization)) + input.players.push({ ...npc, id: input.players.length }); +} const initial = input.data ?? JSON.stringify(input); const seat = engine.currentPlayer(initial); const view = (state) => JSON.parse(engine.webView(state, seat)); const freeEconomy = (state) => - view(state).collectActions.some((a) => a.value?.Custom === 'FreeEconomyCollect'); + view(state).collectActions.some((a) => a.value?.Special?.Modifier === 'FreeEconomyCollect'); assert(freeEconomy(initial), 'Free Economy must be available after undo'); const city = view(initial).cities.find((c) => c.canActivate && c.choices.length); const choice = city.choices[0]; @@ -41,7 +48,12 @@ const redone = advance(undone, 'Redo'); assert.equal(engine.logLength(redone), engine.logLength(collected)); assert.deepEqual(engine.logSlice(redone, { start: 0 }), engine.logSlice(collected, { start: 0 })); const rewound = advance(redone, 'Undo'); -let free = advance(rewound, collect({ Custom: 'FreeEconomyCollect' })); +const freeVariant = view(rewound).collectActions.find(a => a.free); +const freeAction = JSON.parse(engine.webQuery(engine.stripSecret(rewound,seat),seat,JSON.stringify({ + kind:'collect',city:city.position,variant:freeVariant.value, + selections:[{position:choice.position,pile:choice.pile,times:1}], +}))).action; +let free = advance(rewound, freeAction); free = advance(free, { Response: { Payment: [{ mood_tokens: 1 }] } }); assert.equal(JSON.parse(free).actions_left, JSON.parse(initial).actions_left); assert.equal( @@ -119,9 +131,11 @@ try { (before) => document.querySelector('[aria-label="Journal"]').innerText === before, baseline, ); - await page.getByRole('button', { name: 'Close table activity', exact: true }).click(); + const closeActivity = page.getByRole('button', { name: 'Close table activity', exact: true }); + if (width < 600) { await closeActivity.focus(); await closeActivity.press('Enter'); } + else await closeActivity.click(); await page.getByRole('button', { name: 'Collect resources', exact: true }).click(); - const freeButton = page.getByRole('button', { name: 'Free Economy', exact: true }); + const freeButton = page.locator('.variant-picker button').filter({ hasText: 'Free Economy' }); await freeButton.click(); assert.equal(await freeButton.getAttribute('aria-pressed'), 'true'); await page.screenshot({ path: '/tmp/clash-undo-free-economy-' + width + '.png' }); diff --git a/web-client/src/SettlerPanel.svelte b/web-client/src/SettlerPanel.svelte index 255af5ae..c81e360c 100644 --- a/web-client/src/SettlerPanel.svelte +++ b/web-client/src/SettlerPanel.svelte @@ -1,4 +1,5 @@