Cancel departed Persia Banking turn start and recover stalled legacy saves

This commit is contained in:
coyotte508 2026-11-10 19:22:23 +00:00
commit 20ffdcd9f6
8 changed files with 316 additions and 5 deletions

View file

@ -670,6 +670,65 @@ impl Game {
true
}
/// Cancel only an unsubmitted, standalone Banking reward. Other turn-start
/// handlers include mandatory payments and shared effects; they are not safe
/// to discard generically, nor are nested persistent-event continuations.
fn dropped_banking_player(&self) -> Option<usize> {
use crate::content::persistent_events::PersistentEventRequest;
use crate::special_advance::SpecialAdvance;
let [event] = self.events.as_slice() else {
return None;
};
let handler = event.player.handler.as_ref()?;
(matches!(self.state, GameState::Playing)
&& matches!(event.event_type, PersistentEventType::TurnStart)
&& event.origin_override.is_none()
&& event.players_used.is_empty()
&& handler.priority == 5
&& self.dropped_players.contains(&event.player.index)
&& handler.origin == EventOrigin::SpecialAdvance(SpecialAdvance::Banking)
&& matches!(handler.request, PersistentEventRequest::ResourceReward(_))
&& handler.response.is_none())
.then_some(event.player.index)
}
/// Repair the old withdrawal shape: the seat pointer advanced, but Banking
/// still belongs to the departed seat and the successor has not started.
/// Removing the event before starting the successor makes repeated load/clone
/// idempotent and avoids resuming TurnStart with the wrong seat pointer.
pub(crate) fn reconcile_dropped_banking(&mut self) {
let Some(player) = self.dropped_banking_player() else {
return;
};
if self.human_players_count() <= 1 || self.current_player_index == player {
return;
}
let seats = self.players.iter().filter(|p| p.is_human()).count();
let next = (1..seats)
.map(|offset| (player + offset) % seats)
.find(|p| !self.dropped_players.contains(p));
// The old code entered next_round at the boundary. Do not guess whether
// that round's effects have already run; only repair the confirmed shape.
if next != Some(self.current_player_index)
|| self.current_player_index == self.starting_player_index
|| self.log.is_empty()
|| current_turn_log(self).turn_type != TurnType::Player(player)
{
return;
}
self.events.clear();
self.cleanup_withdrawn_turn(player);
self.start_turn();
}
fn cleanup_withdrawn_turn(&mut self, player: usize) {
end_turn(self, player);
for action in &mut current_turn_log_mut(self).actions {
action.undo.clear();
}
check_for_waste(self);
}
/// Remove a player while keeping surviving seat indices and round order stable.
///
/// # Panics
@ -679,9 +738,12 @@ impl Game {
crate::game_setup::drop_draft_player(self, player_index);
return;
}
if !self.dropped_players.contains(&player_index) {
self.dropped_players.push(player_index);
if self.dropped_players.contains(&player_index) {
self.reconcile_dropped_banking();
self.finish_after_drop();
return;
}
self.dropped_players.push(player_index);
if self.finish_after_drop() {
return;
}
@ -700,6 +762,10 @@ impl Game {
if self.current_player_index != player_index {
return;
}
if self.dropped_banking_player() == Some(player_index) {
self.events.clear();
self.cleanup_withdrawn_turn(player_index);
}
self.skip_dropped_players();
if !dropped_first && self.current_player_index == self.starting_player_index {
self.next_round();

View file

@ -193,6 +193,7 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
for player_index in 0..game.players.len() {
initialize_player(player_index, &mut game, &all);
}
game.reconcile_dropped_banking();
game
}

View file

@ -86,3 +86,6 @@ pub mod wonder;
#[cfg(test)]
mod game_length_tests;
#[cfg(test)]
mod withdrawal_tests;

View file

@ -0,0 +1,159 @@
use crate::content::effects::PermanentEffect;
use crate::content::persistent_events::{PersistentEventState, PersistentEventType};
use crate::game::{Game, GameContext, GameState};
use crate::game_setup::{GameSetupBuilder, setup_game};
use crate::resource_pile::ResourcePile;
fn reload(game: &Game) -> Game {
let data = serde_json::from_str(&serde_json::to_string(&game.cloned_data()).unwrap()).unwrap();
Game::from_data(data, game.cache.clone(), GameContext::Play)
}
fn banking() -> Game {
let mut game = setup_game(
&GameSetupBuilder::new(4)
.seed("withdraw-banking".into())
.assigned_civilizations(vec![
"Greece".into(),
"China".into(),
"Persia".into(),
"Rome".into(),
])
.build(),
);
for player in &mut game.players {
player.objective_cards.clear();
}
game.starting_player_index = 0;
game.current_player_index = 2;
game.age = 4;
game.round = 2;
game.player_mut(2)
.advances
.insert(crate::advance::Advance::Currency);
game.player_mut(2).resources = ResourcePile::gold(1);
game = reload(&game);
game.start_turn();
assert_eq!(game.events.len(), 1);
assert_eq!(game.active_player(), 2);
// A real successor turn-start effect proves that start_turn is not skipped
// or duplicated (including after serialization and a repeated notification).
game.permanent_effects
.push(PermanentEffect::AssassinationLoseAction(3));
game
}
fn snapshot(game: &Game) -> String {
serde_json::to_string(&game.cloned_data()).unwrap()
}
#[test]
fn withdrawal_banking_starts_successor_once_and_preserves_seats() {
let mut game = banking();
let seats = game.players.len();
game.player_mut(2)
.event_info
.insert("personal".into(), "stale".into());
let resources = game.player(2).resources.clone();
game.drop_player(2);
assert_eq!(game.player(2).resources, resources);
assert!(game.player(2).event_info.is_empty());
assert!(game.events.is_empty());
assert_eq!(game.current_player_index, 3);
assert_eq!(game.actions_left, 2);
assert_eq!(game.round, 2);
assert_eq!(game.players.len(), seats);
let saved = snapshot(&game);
game.drop_player(2);
assert_eq!(snapshot(&game), saved);
game = reload(&game);
assert_eq!(snapshot(&game), saved);
game.next_turn();
assert_eq!(game.current_player_index, 0);
assert_eq!(game.round, 3);
}
#[test]
fn withdrawal_banking_legacy_advanced_pointer_recovers_once() {
let mut old = banking();
old.dropped_players.push(2);
old.current_player_index = 3;
let mut game = reload(&old);
assert_eq!(game.current_player_index, 3);
assert!(game.events.is_empty());
assert_eq!(game.actions_left, 2);
assert_eq!(game.player(2).resources, ResourcePile::gold(1));
let saved = snapshot(&game);
assert_eq!(snapshot(&reload(&game)), saved);
game.drop_player(2);
assert_eq!(snapshot(&game), saved);
assert_eq!(snapshot(&reload(&old)), saved);
}
#[test]
fn withdrawal_opponent_leaves_current_banking_intact() {
let mut game = banking();
let events = game.events.clone();
game.drop_player(1);
assert_eq!(game.events, events);
assert_eq!(game.active_player(), 2);
assert_eq!(game.current_player_index, 2);
}
#[test]
fn withdrawal_banking_round_boundary_and_first_seat() {
for first in [2, 3] {
let mut game = banking();
game.starting_player_index = first;
game.drop_player(2);
assert_eq!(game.current_player_index, 3);
assert_eq!(game.starting_player_index, 3);
assert_eq!(game.round, if first == 2 { 2 } else { 3 });
assert_eq!(game.actions_left, 2);
assert!(game.events.is_empty());
}
}
#[test]
fn withdrawal_does_not_discard_nested_or_other_handlers() {
let mut game = banking();
game.events.push(PersistentEventState::new(
2,
PersistentEventType::ChooseActionCard,
None,
));
let events = game.events.clone();
game.drop_player(2);
assert_eq!(game.events, events);
assert_eq!(reload(&game).events, events);
let mut game = banking();
game.events[0].player.handler.as_mut().unwrap().origin =
crate::events::EventOrigin::Ability("Not Banking".into());
let events = game.events.clone();
game.drop_player(2);
assert_eq!(game.events, events);
assert_eq!(reload(&game).events, events);
}
#[test]
fn withdrawal_last_survivor_still_finishes_pending_banking() {
let mut game = banking();
game.drop_player(0);
game.drop_player(1);
game.drop_player(2);
assert!(matches!(game.state, GameState::Finished));
assert!(game.events.is_empty());
assert_eq!(game.current_player_index, 3);
}
#[test]
fn withdrawal_legacy_does_not_restart_an_already_started_successor() {
let mut old = banking();
old.dropped_players.push(2);
old.current_player_index = 3;
crate::log::add_turn_log(&mut old, crate::log::TurnType::Player(3));
let restored = reload(&old);
assert_eq!(restored.events, old.events);
assert_eq!(snapshot(&restored), snapshot(&old));
}

View file

@ -1186,3 +1186,30 @@ supported. Earthquake and cultural-influx coverage includes selection in another
player's city; accessible button names include the foreign civilization. Event rules,
scoring and existing game history are unchanged. Publish the matching viewer and engine
together.
Viewer 0.1.212 / engine 0.4.144 fixes withdrawal while Persia is choosing its
standalone Banking start-of-turn reward. The unresolved personal reward and
remaining start-of-turn sequence are cancelled, the departed turn is cleaned up,
and the next surviving seat starts exactly once. No gold/culture is selected on
behalf of the departed player. Stable seats, first-seat changes, round boundaries,
opponent withdrawals and last-survivor victory retain their existing behavior.
Repeated withdrawal notifications are idempotent.
Loading also deterministically normalizes the confirmed legacy shape: a dropped
Banking owner, a pointer already advanced to the next surviving seat, and a latest
turn log still owned by the departed seat. Recovery is limited to non-boundary
Playing saves with exactly one unsubmitted Banking event. The successor's normal
start effects run once; subsequent loads and moves use that normalized state.
This includes the reported Fossil-cyclone-9455 shape. Engine reads do not persist a
repaired save or update BGS's separately stored currentPlayers/timers; a platform
refresh/recovery action may still be required. No live move or repair is performed
by this release.
This is intentionally not a general withdrawal-decision policy: combat, mandatory
payments (including Viking Raids), shared choices, nested events, draft choices,
and ambiguous legacy round-boundary saves are not automatically resolved. Full
historical replay cannot in general reconstruct unlogged withdrawal timing; this
release does not change that separate limitation. Tests use synthetic setups only;
production saves are not committed. Publish the matching bridge and viewer while
preserving the existing gallery and all unrelated metadata, including game-length
labels/order and Standard as default.

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.211",
"version": "0.1.212",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.211",
"version": "0.1.212",
"dependencies": {
"@boardgamers/protocol": "0.9.0",
"lucide-svelte": "^0.577.0",

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.211",
"version": "0.1.212",
"private": true,
"type": "module",
"scripts": {

View file

@ -3,6 +3,61 @@ import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
const engine = createRequire(import.meta.url)('../.engine/server.js');
async function bankingFixture() {
const g = JSON.parse(await engine.init(4, [], {}, 'withdraw-bank', {}));
assert.equal(g.players[2].civilization, 'Persia');
assert.equal(g.players[3].civilization, 'Rome');
for (const p of g.players) p.objective_cards = [];
g.starting_player_index = 0;
g.current_player_index = 1;
g.age = 4;
g.round = 2;
g.players[2].advances.push('Currency');
g.players[2].resources = { gold: 1 };
g.permanent_effects = [{ AssassinationLoseAction: 3 }];
const pending = JSON.parse(engine.tryMove(JSON.stringify(g), JSON.stringify({ Playing: 'EndTurn' }), 1));
assert.equal(pending.events[0].event_type, 'TurnStart');
assert.deepEqual(pending.events[0].handler.origin, { SpecialAdvance: 'Banking' });
return pending;
}
test('four-seat Banking withdrawal skips the reward and starts Rome exactly once', async () => {
const g = await bankingFixture();
const raw = await engine.dropPlayer(JSON.stringify(g), 2);
const result = JSON.parse(raw);
assert.equal(engine.currentPlayer(raw), 3);
assert.equal(result.actions_left, 2);
assert.equal(result.round, 2);
assert.equal(result.events?.length ?? 0, 0);
assert.deepEqual(result.players[2].resources, { gold: 1 });
assert.equal(result.players.length, 6);
assert.equal(await engine.dropPlayer(raw, 2), raw);
const next = JSON.parse(engine.tryMove(raw, JSON.stringify({ Playing: 'EndTurn' }), 3));
assert.equal(next.current_player_index, 0);
assert.equal(next.round, 3);
});
test('legacy advanced-pointer Banking save normalizes consistently at every engine read', async () => {
const g = await bankingFixture();
g.dropped_players = [2];
g.current_player_index = 3;
const raw = JSON.stringify(g);
assert.equal(engine.currentPlayer(raw), 3);
assert.equal(engine.currentPlayer(raw), 3);
const normalized = await engine.dropPlayer(raw, 2);
assert.equal(JSON.parse(normalized).actions_left, 2);
assert.equal(await engine.dropPlayer(normalized, 2), normalized);
const move = JSON.stringify({ Playing: 'EndTurn' });
assert.equal(engine.tryMove(raw, move, 3), engine.tryMove(normalized, move, 3));
});
test('opponent withdrawal does not cancel Persia Banking', async () => {
const g = await bankingFixture();
const result = JSON.parse(await engine.dropPlayer(JSON.stringify(g), 1));
assert.deepEqual(result.events, g.events);
assert.equal(engine.currentPlayer(JSON.stringify(result)), 2);
});
async function fixture() {
const g = JSON.parse(readFileSync(new URL('../../server/tests/test_games/combat/direct_capture_city_fortress.json', import.meta.url), 'utf8'));
const initial = JSON.parse(await engine.init(2, [], {}, 'drop-player', {}));