diff --git a/server/src/web_view.rs b/server/src/web_view.rs index 1ae71f65..59507964 100644 --- a/server/src/web_view.rs +++ b/server/src/web_view.rs @@ -448,7 +448,7 @@ pub fn view(game: &Game, seat: Option) -> Value { "leaders":c.leaders.iter().map(|l|json!({"name":l.name,"abilities":l.abilities.iter().map(|a|json!({"name":a.name,"description":a.description})).collect::>()})).collect::>(), "action":Action::ChooseCivilization(c.name.clone())})).collect::>(), "actionCards":actions::cards(game,seat,can_play), "specialActions":special_actions.iter().filter(|a| a["reason"].is_null()).collect::>(), "influence":actions::influence(game,seat,can_play), - "collectActions":if can_play {crate::collect::available_collect_actions(game,seat).iter().map(|a|{ let cost = a.cost(game,seat); json!({"value":a,"name":a.origin(p).name(game),"free":cost.free,"payment":cost.payment_options(p,a.origin(p)).default_payment()}) }).collect::>()} else {vec![]}, + "collectActions":if can_play {crate::collect::available_collect_actions(game,seat).iter().map(|a|{ let cost = a.cost(game,seat); let options = cost.payment_options(p,a.origin(p)); let payment = options.first_valid_payment(&p.resources).unwrap_or_else(|| options.default_payment()); json!({"value":a,"name":a.origin(p).name(game),"free":cost.free,"payment":payment}) }).collect::>()} else {vec![]}, "happinessActions":if can_play {crate::happiness::available_happiness_actions(game,seat).iter().map(|a|json!({"value":a,"name":a.origin(p).name(game),"free":a.cost(game,seat).free,"surcharge":a.payment_options(game,seat).default})).collect::>()} else {vec![]}, "units":p.units.iter().map(|u|json!({"id":u.id,"type":u.unit_type,"position":u.position,"carrier":u.carrier_id,"pirate":u.pirate,"movementNotes":movement_notes(game,p,u)})).collect::>(), "nomadCities":p.cities.iter().filter(|c|!crate::content::civilizations::huns::city_destinations(game,p,c.position,&[]).is_empty()).map(|c|c.position).collect::>(), @@ -911,6 +911,60 @@ mod tests { .push(Unit::new(seat, site, UnitType::Infantry, 901)); assert_eq!(reason(&game), Value::Null); } + #[test] + fn great_arena_quotes_first_valid_payment_for_free_economy_and_arts() { + use crate::wonder::Wonder; + let mut game = game(); + let seat = game.active_player(); + let enemy = 1 - seat; + let my_city = game.players[seat].cities[0].position; + let near = *game + .map + .tiles + .iter() + .find(|(pos, terrain)| { + pos.distance(my_city) == 1 && crate::city::is_valid_city_terrain(terrain) + }) + .map(|(pos, _)| pos) + .expect("adjacent land tile"); + game.players[seat].cities[0].mood_state = crate::city::MoodState::Happy; + game.players[enemy].cities[0].position = near; + game.players[enemy].cities[0].pieces.temple = Some(enemy); + game.players[seat].advances.insert(Advance::FreeEconomy); + game.players[seat].advances.insert(Advance::Arts); + game.players[seat].cities[0] + .pieces + .wonders + .push(Wonder::Colosseum); + game.players[seat].wonders_owned.insert(Wonder::Colosseum); + let data = game.cloned_data(); + game = Game::from_data(data, game.cache, crate::game::GameContext::Play); + + // Free Economy defaults to mood, but with 0 mood + 1 culture + Great Arena it quotes culture. + game.players[seat].resources = ResourcePile::culture_tokens(1); + let v = view(&game, Some(seat)); + let free_econ = v["collectActions"] + .as_array() + .unwrap() + .iter() + .find(|a| a["free"] == true) + .expect("Free Economy collect action"); + assert_eq!(free_econ["payment"], json!({"culture_tokens": 1})); + + // Arts defaults to culture, but with 0 culture + 7 mood + Great Arena it quotes mood. + game.players[seat].resources = ResourcePile::mood_tokens(7); + let v = view(&game, Some(seat)); + let arts = v["influence"] + .as_array() + .unwrap() + .iter() + .find(|a| a["free"] == true) + .expect("Arts influence offer"); + assert_eq!(arts["actionPayment"], json!({"mood_tokens": 1})); + for origin in arts["origins"].as_array().unwrap() { + assert_eq!(origin["actionPayment"], json!({"mood_tokens": 1})); + } + } } fn research_plan(game: &Game, seat: usize, input: &Value) -> Result { diff --git a/server/src/web_view/actions.rs b/server/src/web_view/actions.rs index bcb4b6d7..143b1ef9 100644 --- a/server/src/web_view/actions.rs +++ b/server/src/web_view/actions.rs @@ -394,12 +394,23 @@ pub fn movement(game: &Game, seat: usize, units: Vec) -> Result crate::resource_pile::ResourcePile { + options + .first_valid_payment(resources) + .unwrap_or_else(|| options.default_payment()) +} + pub fn cards(game: &Game, seat: usize, can_play: bool) -> Vec { - game.player(seat).action_cards.iter().filter(|id|**id!=0 && **id != crate::content::incidents::great_diplomat::DIPLOMAT_ID + crate::content::incidents::great_persons::GREAT_PERSON_OFFSET).map(|id| { + let p = game.player(seat); + p.action_cards.iter().filter(|id|**id!=0 && **id != crate::content::incidents::great_diplomat::DIPLOMAT_ID + crate::content::incidents::great_persons::GREAT_PERSON_OFFSET).map(|id| { let c = game.cache.get_action_card(*id); let reason = action_reason(game,seat,can_play,PlayingActionType::ActionCard(*id)); + let cost = quoted_payment(&PlayingActionType::ActionCard(*id).payment_options(game,seat), &p.resources); json!({"id":id,"name":c.civil_card.name,"description":c.civil_card.description,"free":PlayingActionType::ActionCard(*id).cost(game,seat).free, - "cost":PlayingActionType::ActionCard(*id).payment_options(game,seat).default, + "cost":cost, "researchAdvances":if reason.is_none() {super::research::card_choices(game, seat, *id)} else {vec![]}, "freeResearch":super::research::card_is_free_research(*id), "tactics":c.tactics_card.as_ref().map(|t|json!({"name":t.name,"description":t.description})), @@ -409,7 +420,8 @@ pub fn cards(game: &Game, seat: usize, can_play: bool) -> Vec { pub fn special(game: &Game, seat: usize, can_play: bool) -> Vec { use crate::content::custom_actions::{CustomAction, SpecialActionExecution}; - game.player(seat).special_actions.values().flat_map(|info| { + let p = game.player(seat); + p.special_actions.values().flat_map(|info| { if info.action == crate::content::custom_actions::SpecialAction::Custom( crate::content::custom_actions::CustomActionType::EndDiplomaticRelations ) && !game.permanent_effects.iter().any(|effect| matches!(effect, @@ -425,19 +437,20 @@ pub fn special(game: &Game, seat: usize, can_play: bool) -> Vec { info.action.playing_action_type().is_available(game, seat).err() }; let mut cities: Vec> = if info.city_bound().is_some() { - game.player(seat).cities.iter().filter(|c|info.is_city_available(game,c)).map(|c|Some(c.position)).collect() + p.cities.iter().filter(|c|info.is_city_available(game,c)).map(|c|Some(c.position)).collect() } else { vec![None] }; if cities.is_empty() { reason.get_or_insert_with(|| "Custom action cannot be played".to_string()); cities.push(None); } + let cost = quoted_payment(&info.cost.cost.payment_options(p, info.event_origin.clone()), &p.resources); cities.into_iter().map(|city|json!({"name":info.event_origin.name(game),"description":execution.ability.description,"position":city,"reason":reason, - "cost":info.cost.cost.payment_options(game.player(seat),info.event_origin.clone()).default_payment(), + "cost":cost, "free":info.cost.cost.free, "researchAdvances":if reason.is_none() {super::research::ability_choices(game, seat, info.custom_action_type())} else {vec![]}, "freeResearch":super::research::ability_is_free_research(info.custom_action_type()), "activatesCity":(info.custom_action_type() == crate::content::custom_actions::CustomActionType::GoldenAge) - .then(|| crate::leader::leader_position(game.player(seat))), + .then(|| crate::leader::leader_position(p)), "action":Action::Playing(PlayingAction::Custom(CustomAction::new(info.custom_action_type(),city)))})).collect::>() }).collect() } @@ -457,10 +470,13 @@ pub fn influence(game: &Game, seat: usize, can_play: bool) -> Vec { if !can_play { return vec![]; } + let p = game.player(seat); let mut offers: Vec = available_influence_actions(game,seat).into_iter().flat_map(|kind| { - available_influence_culture(game,seat,&kind).into_iter().filter_map(|(s,r)| { + let action_cost = kind.cost(game, seat); + let action_payment = quoted_payment(&action_cost.payment_options(p, kind.origin(p)), &p.resources); + available_influence_culture(game,seat,&kind).into_iter().filter_map(move |(s,r)| { let info = r.ok()?; - let origins = influence_start_positions(game,game.player(seat)).into_iter().map(|(p,_)|p) + let origins = influence_start_positions(game,p).into_iter().map(|(pos,_)|pos) .chain(std::iter::once(s.position)) .collect::>().into_iter().filter_map(|origin| { let from = influence_culture_boost_cost_from(game,seat,&s,&kind,true,false,game.get_any_city(s.position).player_index,Some(origin)).ok()?; @@ -469,19 +485,21 @@ pub fn influence(game: &Game, seat: usize, can_play: bool) -> Vec { Some(json!({"position":origin,"settlers":game.try_get_any_city(origin).is_none(), "reroll":crate::content::civilizations::india::buddhism_available(game,seat,&from), "successRewards":influence_source_success_rewards(game,seat,from.starting_city_position), - "free":kind.cost(game,seat).free,"actionPayment":kind.cost(game,seat).payment_options(game.player(seat), kind.origin(game.player(seat))).default_payment(),"rollBonus":from.roll_boost,"preventBoost":from.prevent_boost,"payment":from.range_boost_cost.default_payment(), + "free":action_cost.free,"actionPayment":action_payment,"rollBonus":from.roll_boost,"preventBoost":from.prevent_boost,"payment":quoted_payment(&from.range_boost_cost, &p.resources), "action":Action::Playing(PlayingAction::InfluenceCultureAttempt(attempt))})) }).collect::>(); - Some(json!({"name":super::decisions::structure_name(&s.structure),"position":s.position,"origin":info.starting_city_position,"variant":kind.origin(game.player(seat)).name(game),"free":kind.cost(game,seat).free,"actionPayment":kind.cost(game,seat).payment_options(game.player(seat), kind.origin(game.player(seat))).default_payment(),"rollBonus":info.roll_boost,"preventBoost":info.prevent_boost,"payment":info.range_boost_cost.default_payment(), + Some(json!({"name":super::decisions::structure_name(&s.structure),"position":s.position,"origin":info.starting_city_position,"variant":kind.origin(p).name(game),"free":action_cost.free,"actionPayment":action_payment,"rollBonus":info.roll_boost,"preventBoost":info.prevent_boost,"payment":quoted_payment(&info.range_boost_cost, &p.resources), "origins":origins, "action":Action::Playing(PlayingAction::InfluenceCultureAttempt(InfluenceCultureAttempt::new(s,kind.clone())))})) }).collect::>() }).collect(); - if game - .player(seat) - .has_special_advance(crate::special_advance::SpecialAdvance::Zoroastrianism) - { + if p.has_special_advance(crate::special_advance::SpecialAdvance::Zoroastrianism) { for kind in available_influence_actions(game, seat) { + let action_cost = kind.cost(game, seat); + let action_payment = quoted_payment( + &action_cost.payment_options(p, kind.origin(p)), + &p.resources, + ); for owner in &game.players { for unit in &owner.units { let mut attempt = InfluenceCultureAttempt::new( @@ -500,14 +518,14 @@ pub fn influence(game: &Game, seat: usize, can_play: bool) -> Vec { else { continue; }; - let origins=influence_start_positions(game,game.player(seat)).into_iter().filter_map(|(pos,_)| { + let origins=influence_start_positions(game,p).into_iter().filter_map(|(pos,_)| { let mut selected=attempt.clone();selected.starting_position=Some(pos); let from=crate::cultural_influence::unit_influence_cost(game,seat,&selected,true).ok()?; Some(json!({"position":pos,"settlers":false,"reroll":false, "successRewards":influence_source_success_rewards(game,seat,from.starting_city_position), - "free":kind.cost(game,seat).free,"actionPayment":kind.cost(game,seat).payment_options(game.player(seat), kind.origin(game.player(seat))).default_payment(),"rollBonus":from.roll_boost,"preventBoost":from.prevent_boost,"payment":from.range_boost_cost.default_payment(),"action":Action::Playing(PlayingAction::InfluenceCultureAttempt(selected))})) + "free":action_cost.free,"actionPayment":action_payment,"rollBonus":from.roll_boost,"preventBoost":from.prevent_boost,"payment":quoted_payment(&from.range_boost_cost, &p.resources),"action":Action::Playing(PlayingAction::InfluenceCultureAttempt(selected))})) }).collect::>(); - offers.push(json!({"name":format!("{} · {} #{}",owner.civilization.name,unit.unit_type.non_leader_name(),unit.id+1),"position":unit.position,"origin":info.starting_city_position,"variant":"Zoroastrianism","free":kind.cost(game,seat).free,"actionPayment":kind.cost(game,seat).payment_options(game.player(seat), kind.origin(game.player(seat))).default_payment(),"rollBonus":info.roll_boost,"preventBoost":info.prevent_boost,"payment":info.range_boost_cost.default_payment(),"origins":origins,"action":Action::Playing(PlayingAction::InfluenceCultureAttempt(attempt))})); + offers.push(json!({"name":format!("{} · {} #{}",owner.civilization.name,unit.unit_type.non_leader_name(),unit.id+1),"position":unit.position,"origin":info.starting_city_position,"variant":"Zoroastrianism","free":action_cost.free,"actionPayment":action_payment,"rollBonus":info.roll_boost,"preventBoost":info.prevent_boost,"payment":quoted_payment(&info.range_boost_cost, &p.resources),"origins":origins,"action":Action::Playing(PlayingAction::InfluenceCultureAttempt(attempt))})); } } } diff --git a/web-client/docs/viewer-publishing.md b/web-client/docs/viewer-publishing.md index f7904f1e..1e23d8af 100644 --- a/web-client/docs/viewer-publishing.md +++ b/web-client/docs/viewer-publishing.md @@ -1897,3 +1897,21 @@ artwork 4, all 60 named assets, gallery, Standard options, settings and preferences. Only the artwork manifest's lockfile integrity pin changes; no artwork is republished and no production moves, repairs, backfills or historical rewrites are performed. + +# Viewer 0.1.244 / engine 0.4.174 — Auto-continuation and Great Arena payment quotes + +Engine web-view payment quotes for collect actions, action cards, custom +abilities, and cultural influence now select the player's first valid payment +option (falling back to the default payment) so Great Arena substitutions such +as paying culture for Free Economy or mood for Arts quote an affordable payment +automatically. The viewer preserves quoted action-fee, cultural-influence range, +and Free Education continuations across optimistic outbox reconciliation and +passes upfront action payments from `CityPanel` and `ResearchTree`, while +clearing continuations on seat switches or mismatched prompts. + +Require exact-commit Check and Web viewer CI green before publishing the frozen +viewer `0.1.244` and engine `0.4.174` together. Preserve catalog 8 / 46 +definitions, artwork 4, all 60 named assets, gallery, Standard options, +settings, and preferences. Only the artwork manifest's lockfile integrity pin +changes; no artwork is republished and no production moves, repairs, backfills, +or historical rewrites are performed. diff --git a/web-client/package-lock.json b/web-client/package-lock.json index 4cc9b4b1..ac95e970 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.243", + "version": "0.1.244", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@boardgamers/clash-web-client", - "version": "0.1.243", + "version": "0.1.244", "dependencies": { "@boardgamers/protocol": "0.11.0", "lucide-svelte": "^0.577.0", diff --git a/web-client/package.json b/web-client/package.json index 793a78df..eed65742 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -1,6 +1,6 @@ { "name": "@boardgamers/clash-web-client", - "version": "0.1.243", + "version": "0.1.244", "private": true, "type": "module", "scripts": { diff --git a/web-client/release/achievement-assets.json b/web-client/release/achievement-assets.json index b33d5e5f..a7180fd2 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": "991ba032023910ccfb0f0951ddf3a2568f2e9fd80c154d2d55c72ed5a38f3739", + "web-client/package-lock.json": "02c9700cbef1545cc838e876e6317bdf8dae8a9ec95ec3e726c2136bd213ad69", "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 0921161a..995cbe53 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.173", + "version": "0.4.174", "description": "Clash of Cultures: Monumental edition engine for Boardgamers Space", "license": "MIT", "type": "commonjs", diff --git a/web-client/src/CityPanel.svelte b/web-client/src/CityPanel.svelte index 30705ca6..1210d491 100644 --- a/web-client/src/CityPanel.svelte +++ b/web-client/src/CityPanel.svelte @@ -43,7 +43,7 @@ // Card-request builds select the city first; their payment decision follows. const chosen = structuredClone(action) as { Playing?: { Construct: { payment: Pile } } }; if (buildPayment && chosen.Playing) chosen.Playing.Construct.payment = buildPayment; - controller.submit(chosen); + controller.submit(chosen, selected?.actionPayment); } let city = $derived($session.view?.cities.find((c) => c.position === $session.city)); let options = $derived($session.view?.cityActions.find((c) => c.position === $session.city)); diff --git a/web-client/src/ResearchTree.svelte b/web-client/src/ResearchTree.svelte index 0dd6a055..9e8c5fea 100644 --- a/web-client/src/ResearchTree.svelte +++ b/web-client/src/ResearchTree.svelte @@ -629,7 +629,7 @@ class="secondary" disabled={!!selectedAqueduct.reason || $session.pending} title={selectedAqueduct.reason ? actionReason(selectedAqueduct.reason) : undefined} - onclick={() => controller.submit(selectedAqueduct!.action)} + onclick={() => controller.submit(selectedAqueduct!.action, selectedAqueduct!.cost)} >Advance · Sanitation · free action 2 / / · any mix @@ -658,7 +658,7 @@ onclick={() => selectedAction && (!choice - ? controller.submitResearch(selectedAction, buyFreeEducation) + ? controller.submitResearch(selectedAction, buyFreeEducation, selected?.actionPayment) : (controller.submit(selectedAction), early && controller.patch({ mode: 'overview' })))} > {$session.pending diff --git a/web-client/src/controller.test.ts b/web-client/src/controller.test.ts index 5ee247f9..5c5c178b 100644 --- a/web-client/src/controller.test.ts +++ b/web-client/src/controller.test.ts @@ -3082,3 +3082,315 @@ test('full collection blocks a dual-choice tile but allows replacement and map d assert.deepEqual(app.sent, []); } finally { app.close(); } }); + +function mismatchState(raw: string, opponent: number) { + const game = JSON.parse(raw); + game.players[opponent].resources.wood = (game.players[opponent].resources.wood ?? 0) + 1; + return JSON.stringify(game); +} + +test('prediction mismatch preserves Free Education auto-continuation for both opt-in and skip', async () => { + for (const buy of [true, false]) { + const app = paymentController(), + c = app.controller; + try { + const g = JSON.parse(fixture('advances/free_education')); + g.players[0].resources.ideas = 6; + let raw = JSON.stringify(g); + c.setPlayer(0); + await c.load(engine.stripSecret(raw, 0)); + const advance = app.session().view!.advances.find((a) => a.id === 'Irrigation')!; + c.submitResearch(advance.action!, buy); + assert.equal(app.sent.length, 1); + // Authoritative state differs from local prediction (forces head.print !== print). + raw = mismatchState(engine.tryMove(raw, app.sent[0], 0), 1); + await c.load(engine.stripSecret(raw, 0)); + assert.equal(app.sent.length, 2, 'Free Education continuation must auto-submit after mismatch'); + assert.deepEqual(JSON.parse(app.sent[1]), { Response: { Payment: [buy ? { ideas: 1 } : {}] } }); + raw = engine.tryMove(raw, app.sent[1], 0); + await c.load(engine.stripSecret(raw, 0)); + assert.equal(app.session().view!.decision, null); + assert.equal(app.session().pending, false); + assert.equal(app.session().automaticPayment, false); + const p = JSON.parse(raw).players[0]; + assert.equal(p.resources.mood_tokens, 12 + Number(buy)); + } finally { + app.close(); + } + } +}); + +test('prediction mismatch preserves Free Economy auto-payment continuation', async () => { + const app = paymentController(), + c = app.controller; + try { + let raw = await engine.init(2, [], {}, 'free-economy-mismatch', {}); + const game = JSON.parse(raw), + seat = engine.currentPlayer(raw), + opponent = 1 - seat; + game.players[seat].advances.push('FreeEconomy'); + game.players[seat].resources.mood_tokens = 2; + raw = JSON.stringify(game); + c.setPlayer(seat); + await c.load(engine.stripSecret(raw, seat)); + const freeEconomy = app.session().view!.collectActions!.find((a) => a.free)!; + c.beginCollect(game.players[seat].cities[0].position); + c.switchCollectVariant(freeEconomy.value); + c.toggleChoice(app.session().view!.cities[0].choices[0]); + c.collect(); + assert.equal(app.sent.length, 1); + raw = mismatchState(engine.tryMove(raw, app.sent[0], seat), opponent); + await c.load(engine.stripSecret(raw, seat)); + assert.equal(app.sent.length, 2, 'Free Economy payment must auto-submit after mismatch'); + assert.deepEqual(JSON.parse(app.sent[1]), { Response: { Payment: [{ mood_tokens: 1 }] } }); + raw = engine.tryMove(raw, app.sent[1], seat); + await c.load(engine.stripSecret(raw, seat)); + assert.equal(app.session().view!.decision, null); + assert.equal(app.session().pending, false); + assert.equal(JSON.parse(raw).players[seat].resources.mood_tokens, 1); + } finally { + app.close(); + } +}); + +test('prediction mismatch preserves 3-step Arts + range auto-payment continuation on step 1 and step 2', async () => { + for (const mismatchStep of [0, 1]) { + const app = paymentController(), + c = app.controller; + try { + const g = JSON.parse(fixture('base/cultural_influence_instant')); + g.dice_roll_outcomes = [0]; + g.current_player_index = 0; + g.players[1].cities[0].city_pieces = { temple: 1 }; + g.players[0].cities = [{ position: 'A1', mood_state: 'Happy' }]; + g.players[0].civilization = 'Rome'; + g.players[0].resources.culture_tokens = 7; + g.players[0].advances = [...new Set([...g.players[0].advances, 'Arts', 'Theaters'])]; + c.setPlayer(0); + let raw = JSON.stringify(g); + await c.load(engine.stripSecret(raw, 0)); + const target = app + .session() + .view!.influence!.find((t) => t.position === 'C1' && t.name === 'Temple' && !!t.free)!; + const origin = target.origins!.find((o) => o.position === target.origin)!; + c.startInfluence(origin.action, origin.actionPayment!, origin.payment); + for (let i = 0; i < app.sent.length; i++) { + assert.ok(i < 3, 'only Arts initiation, action fee, and range fee auto-submit'); + raw = engine.tryMove(raw, app.sent[i], 0); + if (i === mismatchStep) raw = mismatchState(raw, 1); + await c.load(engine.stripSecret(raw, 0)); + } + assert.equal(app.sent.length, 3); + assert.equal(app.session().view!.influenceContext!.stage, 'boost'); + assert.equal(app.session().pending, false); + assert.equal(app.session().automaticPayment, false); + } finally { + app.close(); + } + } +}); + +test('settleToConfirmed while outbox[0] is in flight still fires continuation on reconcile', async () => { + const app = paymentController(), + c = app.controller; + try { + const g = JSON.parse(fixture('advances/free_education')); + g.players[0].resources.ideas = 6; + let raw = JSON.stringify(g); + c.setPlayer(0); + await c.load(engine.stripSecret(raw, 0)); + const advance = app.session().view!.advances.find((a) => a.id === 'Irrigation')!; + c.submitResearch(advance.action!, true); + assert.equal(app.sent.length, 1); + (c as unknown as { settleToConfirmed(): void }).settleToConfirmed(); + assert.equal(app.session().pending, true); + raw = engine.tryMove(raw, app.sent[0], 0); + await c.load(engine.stripSecret(raw, 0)); + assert.equal(app.sent.length, 2, 'continuation must still auto-submit after settleToConfirmed'); + assert.deepEqual(JSON.parse(app.sent[1]), { Response: { Payment: [{ ideas: 1 }] } }); + raw = engine.tryMove(raw, app.sent[1], 0); + await c.load(engine.stripSecret(raw, 0)); + assert.equal(app.session().view!.decision, null); + assert.equal(app.session().pending, false); + } finally { + app.close(); + } +}); + +test('continuation is discarded cleanly on rejection, unexpected state, or opponent turn', async () => { + for (const mode of ['rejected', 'opponent-turn', 'unexpected-state'] as const) { + const app = paymentController(), + c = app.controller; + try { + const g = JSON.parse(fixture('advances/free_education')); + g.players[0].resources.ideas = 6; + const raw = JSON.stringify(g); + c.setPlayer(0); + await c.load(engine.stripSecret(raw, 0)); + const advance = app.session().view!.advances.find((a) => a.id === 'Irrigation')!; + c.submitResearch(advance.action!, true); + assert.equal(app.sent.length, 1); + if (mode === 'rejected') { + c.moveResult({ move: app.sent[0], ok: false, error: 'Rejected by server' }); + const after = engine.tryMove(raw, app.sent[0], 0); + await c.load(engine.stripSecret(after, 0)); + assert.equal(app.sent.length, 1); + assert.equal(app.session().view!.decision!.origin!.Advance, 'FreeEducation'); + } else if (mode === 'opponent-turn') { + const otherTurn = JSON.parse(raw); + otherTurn.current_player_index = 1; + await c.load(engine.stripSecret(JSON.stringify(otherTurn), 0)); + assert.equal(app.sent.length, 1); + assert.equal(app.session().automaticPayment, false); + } else { + const endTurn = engine.tryMove(raw, JSON.stringify({ Playing: 'EndTurn' }), 0); + await c.load(engine.stripSecret(endTurn, 0)); + assert.equal(app.sent.length, 1); + assert.equal(app.session().automaticPayment, false); + } + } finally { + app.close(); + } + } +}); + +test('Great Arena auto-pays single-option Free Economy and Arts quotes and keeps 2-option choice dialog', async () => { + // 1. Free Economy + Great Arena + 0 mood + 1 culture -> quotes culture & auto-pays. + { + const app = paymentController(), + c = app.controller; + try { + let raw = await engine.init(2, [], {}, 'great-arena-free-econ-single', {}); + const game = JSON.parse(raw), + seat = engine.currentPlayer(raw); + game.players[seat].advances.push('FreeEconomy'); + game.players[seat].cities[0].city_pieces = { ...game.players[seat].cities[0].city_pieces, wonders: ['Colosseum'] }; + game.players[seat].wonders_owned = ['Colosseum']; + game.players[seat].resources.mood_tokens = 0; + game.players[seat].resources.culture_tokens = 1; + raw = JSON.stringify(game); + c.setPlayer(seat); + await c.load(engine.stripSecret(raw, seat)); + const freeEconomy = app.session().view!.collectActions!.find((a) => a.free)!; + assert.deepEqual(freeEconomy.payment, { culture_tokens: 1 }); + c.beginCollect(game.players[seat].cities[0].position); + c.switchCollectVariant(freeEconomy.value); + c.toggleChoice(app.session().view!.cities[0].choices[0]); + c.collect(); + for (let i = 0; i < app.sent.length; i++) { + assert.ok(i < 2); + raw = engine.tryMove(raw, app.sent[i], seat); + await c.load(engine.stripSecret(raw, seat)); + } + assert.equal(app.sent.length, 2); + assert.deepEqual(JSON.parse(app.sent[1]), { Response: { Payment: [{ culture_tokens: 1 }] } }); + assert.equal(app.session().view!.decision, null); + } finally { + app.close(); + } + } + + // 2. Free Economy + Great Arena + BOTH mood and culture -> keeps 2-option choice dialog. + { + const app = paymentController(), + c = app.controller; + try { + let raw = await engine.init(2, [], {}, 'great-arena-free-econ-both', {}); + const game = JSON.parse(raw), + seat = engine.currentPlayer(raw); + game.players[seat].advances.push('FreeEconomy'); + game.players[seat].cities[0].city_pieces = { ...game.players[seat].cities[0].city_pieces, wonders: ['Colosseum'] }; + game.players[seat].wonders_owned = ['Colosseum']; + game.players[seat].resources.mood_tokens = 1; + game.players[seat].resources.culture_tokens = 1; + raw = JSON.stringify(game); + c.setPlayer(seat); + await c.load(engine.stripSecret(raw, seat)); + const freeEconomy = app.session().view!.collectActions!.find((a) => a.free)!; + c.beginCollect(game.players[seat].cities[0].position); + c.switchCollectVariant(freeEconomy.value); + c.toggleChoice(app.session().view!.cities[0].choices[0]); + c.collect(); + raw = engine.tryMove(raw, app.sent[0], seat); + await c.load(engine.stripSecret(raw, seat)); + assert.equal(app.sent.length, 1); + assert.equal(app.session().view!.decision!.name, 'Pay for action'); + assert.equal(app.session().view!.decision!.fields[0].choices!.length, 2); + assert.equal(app.session().automaticPayment, false); + } finally { + app.close(); + } + } + + // 3. Arts + Great Arena + 0 culture + mood -> quotes mood & auto-pays. + { + const app = paymentController(), + c = app.controller; + try { + const g = JSON.parse(fixture('base/cultural_influence_instant')); + g.dice_roll_outcomes = [0]; + g.current_player_index = 0; + g.players[1].cities[0].city_pieces = { temple: 1 }; + g.players[0].cities = [{ position: 'A1', mood_state: 'Happy', city_pieces: { wonders: ['Colosseum'] } }]; + g.players[0].wonders_owned = ['Colosseum']; + g.players[0].civilization = 'Rome'; + g.players[0].resources.culture_tokens = 0; + g.players[0].resources.mood_tokens = 7; + g.players[0].advances = [...new Set([...g.players[0].advances, 'Arts', 'Theaters'])]; + c.setPlayer(0); + let raw = JSON.stringify(g); + await c.load(engine.stripSecret(raw, 0)); + const target = app + .session() + .view!.influence!.find((t) => t.position === 'C1' && t.name === 'Temple' && !!t.free)!; + const origin = target.origins!.find((o) => o.position === target.origin)!; + assert.deepEqual(origin.actionPayment, { mood_tokens: 1 }); + c.startInfluence(origin.action, origin.actionPayment!, origin.payment); + for (let i = 0; i < app.sent.length; i++) { + assert.ok(i < 3); + raw = engine.tryMove(raw, app.sent[i], 0); + await c.load(engine.stripSecret(raw, 0)); + } + const expectedSteps = Object.values(origin.payment).some(Boolean) ? 3 : 2; + assert.equal(app.sent.length, expectedSteps); + assert.deepEqual(JSON.parse(app.sent[1]), { Response: { Payment: [{ mood_tokens: 1 }] } }); + assert.equal(app.session().view!.influenceContext!.stage, 'boost'); + } finally { + app.close(); + } + } + + // 4. Arts + Great Arena + BOTH mood and culture -> keeps 2-option choice dialog. + { + const app = paymentController(), + c = app.controller; + try { + const g = JSON.parse(fixture('base/cultural_influence_instant')); + g.dice_roll_outcomes = [0]; + g.current_player_index = 0; + g.players[1].cities[0].city_pieces = { temple: 1 }; + g.players[0].cities = [{ position: 'A1', mood_state: 'Happy', city_pieces: { wonders: ['Colosseum'] } }]; + g.players[0].wonders_owned = ['Colosseum']; + g.players[0].civilization = 'Rome'; + g.players[0].resources.culture_tokens = 2; + g.players[0].resources.mood_tokens = 2; + g.players[0].advances = [...new Set([...g.players[0].advances, 'Arts', 'Theaters'])]; + c.setPlayer(0); + let raw = JSON.stringify(g); + await c.load(engine.stripSecret(raw, 0)); + const target = app + .session() + .view!.influence!.find((t) => t.position === 'C1' && t.name === 'Temple' && !!t.free)!; + const origin = target.origins!.find((o) => o.position === target.origin)!; + c.startInfluence(origin.action, origin.actionPayment!, origin.payment); + raw = engine.tryMove(raw, app.sent[0], 0); + await c.load(engine.stripSecret(raw, 0)); + assert.equal(app.sent.length, 1); + assert.equal(app.session().view!.decision!.name, 'Pay for action'); + assert.equal(app.session().view!.decision!.fields[0].choices!.length, 2); + assert.equal(app.session().automaticPayment, false); + } finally { + app.close(); + } + } +}); diff --git a/web-client/src/controller.ts b/web-client/src/controller.ts index 8c6cc70e..bb2053c0 100644 --- a/web-client/src/controller.ts +++ b/web-client/src/controller.ts @@ -129,7 +129,12 @@ export class Controller { * `print` is the predicted state's fingerprint, or null when the result * depends on information this seat does not have. */ - private outbox: { move: Move; print: string | null; announced: boolean }[] = []; + private outbox: { + move: Move; + print: string | null; + announced: boolean; + continuation?: { actionPayment?: Pile; influenceRangePayment?: Pile; freeEducation?: Pile }; + }[] = []; private predictions: boolean; private moveAnnounced = false; private undoPreview = new UndoPreview(); @@ -359,7 +364,8 @@ export class Controller { this.outbox = []; this.submittedMove = head.move; this.moveAnnounced = head.announced; - this.apply(raw); + this.restoreContinuation(head.continuation); + this.apply(raw, { continuing: !!head.continuation }); return true; } // The server disagrees with the prediction (or another player moved first). @@ -367,11 +373,27 @@ export class Controller { // as a regular update so new draws, battles and recap effects are reported. this.outbox = []; if (this.raw !== base) this.apply(base, { quiet: true }); - this.apply(raw); - this.notify('Game updated.'); + this.restoreContinuation(head.continuation); + this.apply(raw, { continuing: !!head.continuation }); + if (!get(this.session).automaticPayment && !this.outbox.length) this.notify('Game updated.'); return true; } - private apply(raw: string, { predicted = false, quiet = false, local = false } = {}) { + private restoreContinuation(continuation?: { + actionPayment?: Pile; + influenceRangePayment?: Pile; + freeEducation?: Pile; + }) { + if (!continuation) return; + this.quotedActionPayment = continuation.actionPayment ? { ...continuation.actionPayment } : null; + this.quotedInfluenceRangePayment = continuation.influenceRangePayment + ? { ...continuation.influenceRangePayment } + : null; + this.quotedFreeEducation = continuation.freeEducation ? { ...continuation.freeEducation } : null; + } + private apply( + raw: string, + { predicted = false, quiet = false, local = false, continuing = false } = {}, + ) { if (!this.engine) return; this.localCalendar = null; if (quiet) { @@ -404,6 +426,7 @@ export class Controller { const view = JSON.parse(this.engine.webView(raw, old.seat)) as View; if (!local) this.undoPreview.remember(raw, game, view, old.seat); if (view.influenceContext) this.influenceAttemptPending = true; + const awaitContinuation = old.pending || continuing; const quotedPayment = this.quotedActionPayment; this.quotedActionPayment = null; let automaticPayment: Move | null = null; @@ -412,7 +435,7 @@ export class Controller { // Continue only the exact fee already accepted on the initiating button. // Optional purchases, different prices and alternative payments stay visible. if ( - old.pending && + awaitContinuation && changed && quotedPayment && old.seat === view.activePlayer && @@ -440,7 +463,7 @@ export class Controller { } } if ( - old.pending && + awaitContinuation && changed && old.seat === view.activePlayer && influencePaymentMatches(view, this.quotedInfluenceRangePayment) @@ -455,11 +478,11 @@ export class Controller { /* Keep the range controls when a quote is rejected. */ } this.quotedInfluenceRangePayment = null; - } else if (!view.influenceContext || !['payment', 'range'].includes(view.influenceContext.stage)) { + } else if (old.seat !== view.activePlayer || view.influenceContext?.stage !== 'payment') { this.quotedInfluenceRangePayment = null; } if ( - old.pending && + awaitContinuation && changed && this.quotedFreeEducation && old.seat === view.activePlayer && @@ -479,7 +502,7 @@ export class Controller { /* Show the regular dialog if the agreed purchase is no longer legal. */ } this.quotedFreeEducation = null; - } else if (old.pending && changed && !automaticPayment) this.quotedFreeEducation = null; + } else if (changed && !automaticPayment) this.quotedFreeEducation = null; const researchChoice = researchDecision(view); const newDecision = changed || JSON.stringify(view.decision) !== JSON.stringify(old.view?.decision); const drawn = this.cardDraws.update(old.seat, game, view); @@ -980,6 +1003,7 @@ export class Controller { setPlayer(index?: number) { if (get(this.session).seat === index) return; this.settleToConfirmed(); + if (this.outbox[0]) this.outbox[0] = { ...this.outbox[0], continuation: undefined }; this.undoPreview.clear(); if (get(this.session).seat !== undefined) this.playerSettings = null; this.migratedSkipRaze = false; @@ -1880,14 +1904,16 @@ export class Controller { return { eligible: false, affordable: false }; } } - submitResearch(action: Move, buyFreeEducation: boolean) { + submitResearch(action: Move, buyFreeEducation: boolean, quotedPayment?: Pile) { + const s = get(this.session); + if (s.pending || s.playback) return; const plan = this.researchPlan(action); this.quotedFreeEducation = plan.combined ? buyFreeEducation && plan.affordable ? { ideas: 1 } : {} : null; - this.submit(action); + this.submit(action, quotedPayment); } submit(move: Move, quotedPayment?: Pile) { if (move === 'Undo' && this.backInfluence()) return; @@ -1951,8 +1977,18 @@ export class Controller { this.submittedMove = move; this.quotedActionPayment = quotedPayment && Object.values(quotedPayment).some(Boolean) ? { ...quotedPayment } : null; + const continuation = + this.quotedActionPayment || this.quotedInfluenceRangePayment || this.quotedFreeEducation + ? { + ...(this.quotedActionPayment ? { actionPayment: { ...this.quotedActionPayment } } : {}), + ...(this.quotedInfluenceRangePayment + ? { influenceRangePayment: { ...this.quotedInfluenceRangePayment } } + : {}), + ...(this.quotedFreeEducation ? { freeEducation: { ...this.quotedFreeEducation } } : {}), + } + : undefined; const predicted = this.predict(move, s); - this.outbox.push({ move, print: predicted?.print ?? null, announced: !!predicted }); + this.outbox.push({ move, print: predicted?.print ?? null, announced: !!predicted, continuation }); if (this.outbox.length === 1 && !this.sendHead()) return; // Show the result immediately. Queries and follow-up moves use the predicted // state; the host still validates every move and its state stays authoritative. diff --git a/web-client/src/types.ts b/web-client/src/types.ts index fa260c92..13032328 100644 --- a/web-client/src/types.ts +++ b/web-client/src/types.ts @@ -203,6 +203,7 @@ export interface AdvanceView extends PublicAdvance { owned: boolean; reason: string | null; payment: Pile; + actionPayment?: Pile; costAmount: number; costResources: Resource[]; costGroups?: { amount: number; resources: Resource[] }[]; @@ -463,6 +464,7 @@ export interface CityActions { owned: boolean; required: string; payment: Pile; + actionPayment?: Pile; payments?: Pile[] | null; reason: string | null; free?: boolean;