Add editable early choices and keep-government preference

This commit is contained in:
coyotte508 2026-10-27 15:42:38 +01:00
commit b6b6bf8550
38 changed files with 1014 additions and 66 deletions

View file

@ -37,6 +37,7 @@ pub enum Action {
Playing(PlayingAction),
Movement(MovementAction),
Response(EventResponse),
QueueChoice { key: String, response: Option<EventResponse> },
Undo,
Redo,
#[serde(alias = "Setup")]
@ -73,6 +74,11 @@ pub fn try_execute_action(
action: Action,
player_index: usize,
) -> Result<Game, String> {
game.early_choice_update = false;
if let Action::QueueChoice { key, response } = &action {
crate::early_choices::save(&mut game, player_index, key, response.clone())?;
return Ok(game);
}
if game.civilization_draft.is_some() {
crate::game_setup::execute_draft_choice(&mut game, player_index, &action)?;
return Ok(game);

View file

@ -158,11 +158,27 @@ fn title(action: &Action) -> String {
}
pub fn execute(game: Game, action: Action, player: usize) -> Result<Game, String> {
if matches!(action, Action::QueueChoice { .. }) {
return try_execute_action(game, action, player);
}
let undo = matches!(action, Action::Undo);
let mut game = execute_one(game, action, player)?;
crate::early_choices::prune_objectives(&mut game);
// Save automatic responses as ordinary actions. Replay then reproduces them
// without needing past settings; undo never immediately replays a skipped choice.
while !undo && game.context == crate::game::GameContext::Play && auto_keep_cities(&game) {
while !undo && game.context == crate::game::GameContext::Play {
if let Some(response) = crate::early_choices::take_ready(&mut game) {
let player = game.active_player();
game = execute_one(game, Action::Response(response), player)?;
crate::early_choices::prune_objectives(&mut game);
continue;
}
if auto_keep_government(&game) {
let player = game.active_player();
game = execute_one(game, Action::Response(crate::content::persistent_events::EventResponse::Payment(vec![crate::resource_pile::ResourcePile::empty()])), player)?;
continue;
}
if !auto_keep_cities(&game) { break; }
let player = game.active_player();
game = execute_one(
game,
@ -175,6 +191,16 @@ pub fn execute(game: Game, action: Action, player: usize) -> Result<Game, String
Ok(game)
}
fn auto_keep_government(game: &Game) -> bool {
use crate::content::persistent_events::{PersistentEventRequest, PersistentEventType};
game.player(game.active_player()).settings.keep_government == Some(true)
&& game.events.last().is_some_and(|event| {
matches!(event.event_type, PersistentEventType::StatusPhase(crate::status_phase::StatusPhaseState::ChangeGovernmentType(_)))
&& event.player.handler.as_ref().is_some_and(|h| matches!(&h.request,
PersistentEventRequest::Payment(rs) if rs.len() == 1 && rs[0].optional && rs[0].name == "Pay to change government"))
})
}
fn auto_keep_cities(game: &Game) -> bool {
use crate::content::persistent_events::{PersistentEventRequest, PersistentEventType};
let Some(event) = game.events.last() else {

View file

@ -452,6 +452,7 @@ where
(params.next_player)(&mut value);
}
}
crate::early_choices::expire_current_event(game);
game.events.pop();
present_instant_objective_cards(game);

214
server/src/early_choices.rs Normal file
View file

@ -0,0 +1,214 @@
//! Private, editable commitments. They never change resolution order or reserve a
//! shared card. Only an ordinary, currently legal response can consume a plan.
use crate::card::HandCard;
use crate::content::persistent_events::{EventResponse, PersistentEventRequest, PersistentEventType};
use crate::game::Game;
use crate::resource_pile::ResourcePile;
use crate::status_phase::StatusPhaseState;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SavedChoice {
pub player: usize,
pub key: String,
pub response: EventResponse,
}
#[derive(Serialize)]
pub struct OptionChoice {
pub label: String,
pub description: String,
pub response: EventResponse,
}
#[derive(Serialize)]
pub struct Offer {
pub key: String,
pub title: String,
pub options: Vec<OptionChoice>,
pub selected: Option<EventResponse>,
}
fn scope(game: &Game, index: usize) -> Option<String> {
let name = match &game.events.get(index)?.event_type {
PersistentEventType::StatusPhase(phase) => format!("status:{phase:?}"),
PersistentEventType::Incident(i) => format!("person:{}:{}", i.incident_id, i.active_player),
_ => return None,
};
Some(format!("{}:{}:{index}:{name}/", game.age, game.round))
}
fn option(label: impl Into<String>, response: EventResponse) -> OptionChoice {
OptionChoice { label: label.into(), description: String::new(), response }
}
fn objective_key(game: &Game, name: &str) -> String {
format!("{}:objective:{name}", game.age)
}
fn objective_offers(game: &Game, player: usize) -> Vec<Offer> {
let p = game.player(player);
let mut names: Vec<_> = p.objective_cards.iter().filter(|id| **id != 0).flat_map(|id|
crate::objective_card::status_phase_completable(game, p, *id)).collect();
names.sort(); names.dedup();
names.into_iter().map(|name| {
let key = objective_key(game, &name);
let mut options = vec![option("Skip", EventResponse::SelectHandCards(vec![]))];
options.extend(p.objective_cards.iter().filter(|id| **id != 0).filter(|id|
crate::objective_card::status_phase_completable(game, p, **id).contains(&name))
.map(|id| option(game.cache.get_objective_card(*id).name(),
EventResponse::SelectHandCards(vec![HandCard::ObjectiveCard(*id)]))));
let selected = game.early_choices.iter().find(|c| c.player == player && c.key == key).map(|c| c.response.clone());
Offer {key, title: name, options, selected}
}).collect()
}
pub fn prune_objectives(game: &mut Game) {
let invalid: Vec<_> = game.early_choices.iter().enumerate().filter_map(|(index, choice)| {
if !choice.key.contains(":objective:") { return None; }
let valid = objective_offers(game, choice.player).iter().any(|o| o.key == choice.key
&& o.options.iter().any(|v| v.response == choice.response));
(!valid).then_some(index)
}).collect();
for index in invalid.into_iter().rev() { game.early_choices.remove(index); }
}
/// Expose only the current step, never future cards, random results, or another
/// player's hand. Earlier players may still change the available options.
pub fn offers(game: &Game, player: usize) -> Vec<Offer> {
if player >= game.players.len() || !game.player(player).is_human()
|| game.dropped_players.contains(&player) || game.civilization_draft.is_some() || matches!(game.state, crate::game::GameState::Finished) {
return vec![];
}
if game.events.is_empty() { return objective_offers(game, player); }
let Some(index) = game.events.iter().rposition(|e| matches!(e.event_type,
PersistentEventType::StatusPhase(_) | PersistentEventType::Incident(_))) else { return vec![]; };
let event = &game.events[index];
let first = if matches!(event.event_type, PersistentEventType::StatusPhase(StatusPhaseState::ChangeGovernmentType(_))) {
let players: Vec<_> = game.human_players_sorted(game.starting_player_index).iter().map(|i| game.player(*i)).collect();
if crate::status_phase::player_that_chooses_next_first_player(&players) == player {
let key = format!("{}:first", game.age);
vec![Offer { selected: game.early_choices.iter().find(|c| c.player == player && c.key == key).map(|c| c.response.clone()), key,
title: "Choose first player".into(), options: game.human_players_sorted(game.starting_player_index).iter().map(|i| option(game.player(*i).civilization.name.clone(), EventResponse::SelectPlayer(*i))).collect() }]
} else { vec![] }
} else { vec![] };
if event.players_used.contains(&player) { return first; }
// Nested research/event reactions must finish before early status choices are
// offered. Objective selection is the only supported nested request.
if game.events[index+1..].iter().any(|e| !matches!(e.event_type, PersistentEventType::SelectObjectives(_))) {
return vec![];
}
let prefix = scope(game, index).expect("supported event");
let p = game.player(player);
let mut result: Vec<Offer> = first;
let mut add = |suffix: &str, title: String, options: Vec<OptionChoice>| {
if options.is_empty() { return; }
let key = format!("{prefix}{suffix}");
let selected = game.early_choices.iter().find(|c| c.player == player && c.key == key).map(|c| c.response.clone());
result.push(Offer { key, title, options, selected });
};
match &event.event_type {
PersistentEventType::StatusPhase(StatusPhaseState::FreeAdvance) => {
let mut options: Vec<_> = game.cache.get_advances().values()
.filter(|a| p.can_advance_free(a.advance, game))
.map(|a| OptionChoice { label: a.name.clone(), description: a.description.clone(), response: EventResponse::SelectAdvance(a.advance) }).collect();
options.sort_by(|a,b| a.label.cmp(&b.label));
add("advance", "Free Advance".into(), options);
}
PersistentEventType::StatusPhase(StatusPhaseState::RazeSize1City) => {
let mut options: Vec<_> = p.cities.iter().filter(|c| c.size() == 1)
.map(|c| option(c.position.to_string(), EventResponse::SelectPositions(vec![c.position]))).collect();
if !options.is_empty() {
options.insert(0, option("Keep all cities", EventResponse::SelectPositions(vec![])));
add("raze", "Raze city".into(), options);
}
}
PersistentEventType::StatusPhase(StatusPhaseState::CompleteObjectives) => {
return objective_offers(game, player);
}
PersistentEventType::Incident(i) if !i.consumed && !i.replaced_by_sacrifice && i.selected_player.is_none()
&& game.cache.get_incident(i.incident_id).action_card.is_some() => {
// Do not ask before event cancellation, placement or other base
// effects. Once an offer is visible, later players may precommit.
if !event.player.handler.as_ref().is_some_and(|h| matches!(&h.request,
PersistentEventRequest::Payment(rs) if rs.iter().any(|r| r.name == "Pay to gain the Action Card"))) {
return vec![];
}
let cost = if player == i.active_player { 1 } else { 2 };
let mut options = vec![option("Pass", EventResponse::Payment(vec![ResourcePile::empty()]))];
// No inferred gold/captive conversion: a queued purchase spends
// precisely the displayed culture payment, or asks again.
if p.resources.culture_tokens >= cost {
options.push(option(format!("Take if offered · {cost} culture"), EventResponse::Payment(vec![ResourcePile::culture_tokens(cost)])));
}
add("offer", game.cache.get_incident(i.incident_id).name.clone(), options);
}
_ => {}
}
result
}
pub fn can_save(game: &Game, player: usize, key: &str, response: Option<&EventResponse>) -> bool {
(player != game.active_player() || (game.events.is_empty() && key.contains(":objective:"))) && offers(game, player).iter().any(|offer| offer.key == key
&& response.is_none_or(|r| offer.options.iter().any(|o| &o.response == r)))
}
pub fn save(game: &mut Game, player: usize, key: &str, response: Option<EventResponse>) -> Result<(), String> {
if !can_save(game, player, key, response.as_ref()) { return Err("This early choice is no longer available".into()); }
game.early_choices.retain(|c| c.player != player || (c.key != key && !matches!((&c.response, &response),
(EventResponse::SelectHandCards(a), Some(EventResponse::SelectHandCards(b))) if !a.is_empty() && a == b && key.contains(":objective:"))));
if let Some(response) = response { game.early_choices.push(SavedChoice { player, key: key.into(), response }); }
// Metadata-only platform update; not a turn, journal entry or undo boundary.
game.early_choice_update = true;
Ok(())
}
pub fn expire_current_event(game: &mut Game) {
if game.events.last().is_some_and(|e| matches!(e.event_type, PersistentEventType::StatusPhase(StatusPhaseState::CompleteObjectives))) {
let prefix = format!("{}:objective:", game.age);
game.early_choices.retain(|c| !c.key.starts_with(&prefix));
}
if game.events.last().is_some_and(|e| matches!(e.event_type, PersistentEventType::StatusPhase(StatusPhaseState::DetermineFirstPlayer(_)))) {
game.early_choices.retain(|c| c.key != format!("{}:first", game.age));
}
if let Some(prefix) = scope(game, game.events.len().saturating_sub(1)) {
game.early_choices.retain(|c| !c.key.starts_with(&prefix));
}
}
/// Validate against the *real* request, including costs and prerequisites after
/// intervening events. Invalid plans are removed and the normal prompt remains.
pub fn take_ready(game: &mut Game) -> Option<EventResponse> {
let player = game.active_player();
let event = game.events.last()?;
let handler = event.player.handler.as_ref()?;
let (index, suffix) = match &event.event_type {
PersistentEventType::StatusPhase(StatusPhaseState::DetermineFirstPlayer(_)) => (game.events.len()-1, "first".into()),
PersistentEventType::StatusPhase(StatusPhaseState::FreeAdvance) => (game.events.len()-1, "advance".into()),
PersistentEventType::StatusPhase(StatusPhaseState::RazeSize1City) => (game.events.len()-1, "raze".into()),
PersistentEventType::SelectObjectives(i) => {
let index = game.events.iter().rposition(|e| matches!(e.event_type, PersistentEventType::StatusPhase(StatusPhaseState::CompleteObjectives)))?;
(index, format!("objective:{}", i.shown_objective.as_ref()?))
}
PersistentEventType::Incident(_) if matches!(&handler.request, PersistentEventRequest::Payment(rs)
if rs.iter().any(|r| r.name == "Pay to gain the Action Card")) => (game.events.len()-1, "offer".into()),
_ => return None,
};
let key = if suffix == "first" { format!("{}:first", game.age) } else if let Some(name) = suffix.strip_prefix("objective:") {
objective_key(game, name)
} else { format!("{}{suffix}", scope(game, index)?) };
let at = game.early_choices.iter().position(|c| c.player == player && c.key == key)?;
let response = &game.early_choices[at].response;
let valid = match (&handler.request, response) {
(PersistentEventRequest::SelectPlayer(r), EventResponse::SelectPlayer(p)) => r.choices.contains(p),
(PersistentEventRequest::SelectAdvance(r), EventResponse::SelectAdvance(a)) => r.choices.contains(a),
(PersistentEventRequest::SelectPositions(r), EventResponse::SelectPositions(v)) => r.needed.contains(&(v.len() as u8)) && v.iter().all(|p| r.choices.contains(p)),
(PersistentEventRequest::SelectHandCards(r), EventResponse::SelectHandCards(v)) => r.needed.contains(&(v.len() as u8)) && v.iter().all(|c| r.choices.contains(c)),
(PersistentEventRequest::Payment(rs), EventResponse::Payment(v)) => rs.len() == 1 && v.len() == 1
&& game.player(player).resources.has_at_least(&v[0])
&& ((rs[0].optional && v[0].is_empty()) || rs[0].cost.is_valid_payment(&v[0])),
_ => false,
};
let choice = game.early_choices.remove(at);
valid.then_some(choice.response)
}

View file

@ -134,6 +134,8 @@ pub struct Game {
pub version: u16, // JSON schema version
pub state: GameState,
pub events: Vec<PersistentEventState>,
pub early_choices: Vec<crate::early_choices::SavedChoice>,
pub early_choice_update: bool,
// in turn order starting from starting_player_index and wrapping around
pub players: Vec<Player>,
pub map: Map,

View file

@ -146,6 +146,7 @@ pub fn civilizations(game: Game) -> Vec<String> {
#[must_use]
pub fn strip_secret(mut game: Game, player_index: Option<usize>) -> Game {
game.early_choices.retain(|c| Some(c.player) == player_index);
if let Some(draft) = &mut game.civilization_draft {
for i in 0..draft.offers.len() {
if player_index != Some(i) {

View file

@ -62,6 +62,7 @@ pub fn set_player_settings(
if settings.skip_raze_city.is_some() {
p.settings.skip_raze_city = settings.skip_raze_city;
}
if settings.keep_government.is_some() { p.settings.keep_government = settings.keep_government; }
Ok(from_game(game))
}
@ -177,6 +178,11 @@ pub fn current_player(game: String) -> JsValue {
#[wasm_bindgen(js_name = "canMoveOutOfTurn")]
pub fn can_move_out_of_turn(data: String, move_data: JsValue, player: usize) -> bool {
let game = get_game(data);
if let Some(raw) = move_data.as_string()
&& let Ok(crate::action::Action::QueueChoice { key, response }) = serde_json::from_str(&raw)
{
return crate::early_choices::can_save(&game, player, &key, response.as_ref());
}
let Some(draft) = &game.civilization_draft else {
return false;
};
@ -195,7 +201,8 @@ pub fn can_move_out_of_turn(data: String, move_data: JsValue, player: usize) ->
#[wasm_bindgen(js_name = "isLiveUpdate")]
pub fn is_live_update(data: String) -> bool {
get_game(data)
let game = get_game(data);
game.early_choice_update || game
.civilization_draft
.is_some_and(|draft| draft.live_update)
}

View file

@ -44,6 +44,10 @@ pub struct GameData {
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
events: Vec<PersistentEventState>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
early_choices: Vec<crate::early_choices::SavedChoice>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
early_choice_update: bool,
players: Vec<PlayerData>,
map: MapData,
#[serde(default, skip_serializing_if = "Option::is_none")]
@ -113,6 +117,8 @@ pub struct GameData {
#[must_use]
pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
let mut game = Game {
early_choices: data.early_choices,
early_choice_update: data.early_choice_update,
context,
cache,
options: data.options,
@ -173,6 +179,8 @@ pub fn data(game: Game) -> GameData {
version: game.version,
state: game.state,
events: game.events,
early_choices: game.early_choices,
early_choice_update: game.early_choice_update,
players: game.players.into_iter().map(player_data).collect(),
map: game.map.data(),
civilization_draft: game.civilization_draft,
@ -210,6 +218,8 @@ pub fn cloned_data(game: &Game) -> GameData {
version: game.version,
state: game.state.clone(),
events: game.events.clone(),
early_choices: game.early_choices.clone(),
early_choice_update: game.early_choice_update,
players: game.players.iter().map(cloned_player_data).collect(),
map: game.map.cloned_data(),
civilization_draft: game.civilization_draft.clone(),

View file

@ -186,6 +186,8 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game {
.shuffled(&mut rng);
let all = &cache.get_abilities().clone();
let mut game = Game {
early_choices: vec![],
early_choice_update: false,
seed: setup.seed.clone(),
context: GameContext::Play,
version: JSON_SCHEMA_VERSION,

View file

@ -13,6 +13,7 @@ extern crate core;
pub mod ability_initializer;
pub mod action;
pub mod early_choices;
pub mod action_card;
mod action_cost;
pub mod advance;

View file

@ -457,7 +457,7 @@ fn action_origin(a: &Action, player: &Player) -> Option<EventOrigin> {
Action::Movement(_) => Some(move_event_origin()),
Action::Undo => panic!("Unexpected undo in log"),
Action::Redo => panic!("Unexpected redo in log"),
Action::StartTurn | Action::Response(_) | Action::ChooseCivilization(_) => None,
Action::QueueChoice { .. } | Action::StartTurn | Action::Response(_) | Action::ChooseCivilization(_) => None,
}
}

View file

@ -171,6 +171,7 @@ fn fallback(game: &Game, entry: &ActionLogAction) -> String {
},
Action::Movement(_) => "Moved units".into(),
Action::ChooseCivilization(name) => format!("Chose {name}"),
Action::QueueChoice { .. } => "Queued a choice".into(),
Action::StartTurn => "Started turn".into(),
Action::Response(_) => "Completed a decision".into(),
Action::Undo => "Undid a move".into(),

View file

@ -49,11 +49,13 @@ pub struct PlayerSettings {
// None distinguishes an old save from an explicit opt-out.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skip_raze_city: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub keep_government: Option<bool>,
}
impl PlayerSettings {
pub fn is_empty(&self) -> bool {
self.skip_raze_city.is_none()
self.skip_raze_city.is_none() && self.keep_government.is_none()
}
}

View file

@ -505,7 +505,7 @@ pub(crate) fn determine_first_player() -> Ability {
.build()
}
fn player_that_chooses_next_first_player(players: &[&Player]) -> usize {
pub(crate) fn player_that_chooses_next_first_player(players: &[&Player]) -> usize {
players
.iter()
.find(|p| p.wonders_owned.contains(Wonder::GreatLighthouse))

View file

@ -5,7 +5,7 @@ use crate::movement::execute_movement_action;
use json_patch::{PatchOperation, patch};
use serde_json::Value;
const IGNORE_PATHS: [&str; 2] = ["/log/", "/log_index"];
const IGNORE_PATHS: [&str; 4] = ["/log/", "/log_index", "/early_choices", "/early_choice_update"];
pub(crate) fn clean_patch(mut patch: Vec<PatchOperation>) -> Vec<PatchOperation> {
patch.retain(|op| {

View file

@ -323,6 +323,11 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
"shogunateDraft":p.has_special_advance(crate::special_advance::SpecialAdvance::Shogunate)&&p.can_use_advance(Advance::Draft)&&!p.event_info.contains_key("Shogunate Draft"),
"canActivate":city.can_activate(), "activationMood":after_activation.mood_state,"activationCapacity":after_activation.mood_modified_size(p)})
}).collect::<Vec<_>>();
let early_offers = if seat != active || game.events.is_empty() { crate::early_choices::offers(game, seat) } else { vec![] };
let early_advance = early_offers.iter().find(|o| o.key.ends_with("/advance"));
let early_advance_choices: Vec<_> = early_advance.into_iter().flat_map(|o| &o.options).filter_map(|o| {
if let EventResponse::SelectAdvance(a) = o.response { Some(a) } else { None }
}).collect();
let advance_choice = if seat == active {
game.current_event_handler()
.and_then(|handler| match &handler.request {
@ -331,10 +336,12 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
}
_ => None,
})
} else if early_advance.is_some() {
Some((&early_advance_choices, "free"))
} else {
None
};
let research_uses_event_marker = advance_choice.is_none()
let research_uses_event_marker = early_advance.is_some() || advance_choice.is_none()
|| game
.current_event_handler()
.is_some_and(|handler| decisions::advance_uses_event_marker(game, handler));
@ -357,6 +364,7 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
else if !p.can_advance_free(*advance, game) { Some("Conflicts with your current advances".to_string()) }
else if payment.is_none() { Some("Not enough resources".to_string()) } else { None };
let action = if reason.is_some() { None }
else if let Some(offer) = early_advance { Some(Action::QueueChoice { key: offer.key.clone(), response: Some(EventResponse::SelectAdvance(*advance)) }) }
else if advance_choice.is_some() { Some(Action::Response(EventResponse::SelectAdvance(*advance))) }
else { payment.clone().map(|payment| Action::Playing(PlayingAction::Advance(AdvanceAction::new(*advance, payment)))) };
let mut item = advance_description(game, *advance);
@ -414,6 +422,7 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
result["regions"] = json!(regions);
result["unavailableSpecialActions"] = json!(special_actions.iter().filter(|a| !a["reason"].is_null()).collect::<Vec<_>>());
result["activeEffects"] = json!(active_effects);
result["earlyChoices"] = json!(early_offers);
result
}

View file

@ -4,5 +4,11 @@
"label": "Skip end-of-age razing (keep all cities)",
"type": "checkbox",
"default": false
},
{
"name": "keepGovernment",
"label": "Always keep current government",
"type": "checkbox",
"default": false
}
]

View file

@ -11,8 +11,10 @@
height: 100%;
background: #f7f3e8;
}
body { display: flex; flex-direction: column; }
#preview-bar {
height: 35px;
min-height: 35px;
flex-wrap: wrap;
background: #233d35;
color: #d8decb;
font: 10px system-ui;
@ -56,7 +58,8 @@
iframe {
display: block;
width: 100%;
height: calc(100% - 35px);
flex: 1;
min-height: 0;
border: 0;
}
#host-error {
@ -100,8 +103,10 @@
><button id="reset">New game</button><button id="theme">Theme</button
>
<a href="/sounds.html" target="_blank" rel="noopener">Test sounds</a>
<select id="scenario" aria-label="Test scenario"><option value="">Test a choice…</option></select><button id="restart-scenario" disabled>Restart test</button>
<span id="status">Connecting to local game…</span>
</div>
<div id="scenario-note" style="display:none;position:absolute;bottom:0;left:0;z-index:20;background:#233d35;color:#e4e8d9;padding:5px 10px;font:11px system-ui;max-width:100%;box-sizing:border-box"></div>
<div id="host-error" role="alert"></div>
<iframe title="Clash of Cultures" src="/viewer.html"></iframe>
<script type="module" src="/src/local-host.ts"></script>

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.166",
"version": "0.1.167",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.166",
"version": "0.1.167",
"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.166",
"version": "0.1.167",
"private": true,
"type": "module",
"scripts": {

View file

@ -2,6 +2,7 @@ import { createRequire } from 'node:module';
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import type { Plugin } from 'vite';
import { createPreviewScenario, previewScenarios } from './preview-scenarios';
const require = createRequire(import.meta.url);
export function previewApi(): Plugin {
return {
@ -93,10 +94,19 @@ export function previewApi(): Plugin {
}
body = JSON.parse(text || '{}');
}
if (url.pathname === '/api/scenarios') {
if (req.method !== 'POST') { res.end(JSON.stringify(previewScenarios)); return; }
const scenario = await createPreviewScenario(engine, body.id);
state = scenario.state;
revision++;
messages = []; readAt = {};
persist();
res.end(JSON.stringify({ seat: scenario.seat })); return;
}
if (url.pathname === '/api/reset' && req.method === 'POST') await reset();
if (url.pathname === '/api/settings' && req.method === 'POST') {
if (body.seat !== 0 && body.seat !== 1) throw Error('Choose a player.');
if (body.name !== 'skipRazeCity' || typeof body.value !== 'boolean')
if (!['skipRazeCity', 'keepGovernment'].includes(body.name) || typeof body.value !== 'boolean')
throw Error('Invalid setting.');
state = engine.setPlayerSettings(state, body.seat, { [body.name]: body.value });
persist();
@ -105,7 +115,10 @@ export function previewApi(): Plugin {
}
if (url.pathname === '/api/move' && req.method === 'POST') {
if (body.revision !== revision) throw Error('The game changed. Please choose your action again.');
if (!Number.isInteger(body.seat) || body.seat !== engine.currentPlayer(state))
const move = typeof body.move === 'string' ? body.move : JSON.stringify(body.move);
const current = engine.currentPlayer(state);
const active = Array.isArray(current) ? current.includes(body.seat) : current === body.seat;
if (!Number.isInteger(body.seat) || (!active && !engine.canMoveOutOfTurn(state, move, body.seat)))
throw Error('It is not your turn.');
state = engine.tryMove(
state,

View file

@ -0,0 +1,40 @@
import { readFileSync } from 'node:fs';
export const previewScenarios = [
{ id: 'advance', label: 'Free advance', note: 'Research lets you save an early choice.' },
{ id: 'raze', label: 'Raze city', note: 'Cities lets you save an early choice.' },
{ id: 'objectives-before', label: 'Objectives · during turn', note: 'Queue in Objectives now; conditions are checked again before scoring.' },
{ id: 'objectives', label: 'Objectives', note: 'Objectives lets you queue beside each condition.' },
{ id: 'person', label: 'Great Person', note: 'Cards lets you take or pass conditionally; earlier players have priority.' },
{ id: 'government', label: 'Keep government preference', note: 'Research has Always keep current government. Changing governments is handled on your turn.' },
{ id: 'first', label: 'Choose first player', note: 'Use Choose first player beside your civilization while Rome finishes its government choice.' },
];
export async function createPreviewScenario(engine: any, id: string) {
if (!previewScenarios.some(s => s.id === id)) throw Error('Unknown preview scenario');
const names: Record<string, string> = {
advance: 'status_phase/free_advance', raze: 'status_phase/raze_city_decline',
'objectives-before': 'objective_cards/status_phase/standing_army', objectives: 'objective_cards/status_phase/standing_army', person: 'incidents/pirates_spawn',
government: 'status_phase/change_government', first: 'status_phase/change_government',
};
const game = JSON.parse(readFileSync(new URL(`../../server/tests/test_games/${names[id]}.json`, import.meta.url), 'utf8'));
const fresh = JSON.parse(await engine.init(2, [], {}, 'early-preview', {}));
game.players = [...game.players.slice(0, 2), ...fresh.players.slice(2)];
if (id === 'objectives' || id === 'objectives-before') { game.players[1].objective_cards = [13]; game.players[1].resources.wood = 7; }
if (id === 'person') {
game.incidents_left = [55];
game.players[1].resources = { food: 2, culture_tokens: 4 };
game.players[1].action_cards = [7, 9, 17];
game.action_cards_left = game.action_cards_left?.filter((card: number) => ![7, 9, 17].includes(card));
}
if (id === 'government' || id === 'first') { game.players[1].advances = [...game.players[0].advances]; game.players[0].resources.mood_tokens = 6; }
let state = JSON.stringify(game);
const apply = (action: unknown) => { state = engine.tryMove(state, JSON.stringify(action), engine.currentPlayer(state)); };
if (id === 'advance' || id === 'objectives') apply({ Playing: 'EndTurn' });
if (id === 'government' || id === 'first') apply({ Response: { SelectPositions: [] } });
if (id === 'person') for (const response of [{ SelectAdvance: 'Storage' }, { SelectPositions: ['A2'] }, { SelectPositions: ['D1'] }, { Payment: [{ food: 1 }] }]) apply({ Response: response });
const seat = id === 'objectives-before' ? 1 : 1 - engine.currentPlayer(state);
// Check the fixture can be rendered from both seats before replacing the preview.
for (const player of [0, 1]) engine.webView(engine.stripSecret(state, player), player);
return { state, seat };
}

View file

@ -1,6 +1,7 @@
<script lang="ts">
import { printedCardName, printedCardText } from './card-names';
import { X, Layers, Zap, Swords, Archive, ScrollText, ChevronDown } from 'lucide-svelte';
import { X, Layers, Zap, Swords, Archive, ScrollText, ChevronDown, BookOpen } from 'lucide-svelte';
import GreatPersonEffect from './GreatPersonEffect.svelte';
import ResourceText from './ResourceText.svelte';
import ResourceAmount from './ResourceAmount.svelte';
import type { Controller } from './controller';
@ -8,6 +9,7 @@
import { handCardDescription } from './card-text';
let { controller }: { controller: Controller } = $props();
const session = $derived(controller.session);
const offers = $derived(!$session.playback ? $session.view?.earlyChoices?.filter(o => o.key.endsWith('/offer')) ?? [] : []);
let tab = $state<'hand' | 'actions' | 'events'>('hand');
const actions = $derived([...($session.game?.action_cards_discarded ?? [])].reverse().map(id => ({ id, card: $session.view?.cardCatalog?.find(card => card.id === id) })));
const events = $derived([...($session.game?.incidents_discarded ?? [])].reverse().map(id => ({ id, card: $session.view?.eventCatalog?.find(card => card.id === id) })));
@ -40,6 +42,35 @@
<button class:chosen={tab === 'events'} aria-pressed={tab === 'events'} onclick={() => tab = 'events'}><ScrollText size={16} />Discarded events <span>{events.length}</span></button>
</nav>
{#if tab === 'hand'}
{#each offers as offer (offer.key)}
{@const card = $session.view?.cardCatalog?.find(c => c.name === offer.title)}
{@const event = $session.view?.eventCatalog?.find(c => c.name === offer.title)}
<article class="play-card" aria-label={`Offer: ${printedCardName(offer.title)}`}>
<header class="play-card-header"><h3>{printedCardName(offer.title)}</h3></header>
{#if card}<GreatPersonEffect {card} />{/if}
<details class="event-rules">
<summary><BookOpen size={13} /> Event rules</summary>
{#if event?.baseEffect}<p><ResourceText text={event.baseEffect} /></p>{/if}
<p>The player who triggered the event may take the card for <ResourceAmount pile={{culture_tokens:1}} />. If they pass, other players may take it in turn order for <ResourceAmount pile={{culture_tokens:2}} />.</p>
</details>
<div class="queued-person-actions">
{#each offer.options as option}
{@const payment = (option.response as {Payment: Record<string, number>[]}).Payment[0]}
{@const take = Object.values(payment).some(Boolean)}
<button class={take ? 'primary' : 'secondary'} disabled={$session.pending}
onclick={() => controller.submit({QueueChoice:{key:offer.key,response:option.response}})}>
{take ? 'Queue take if offered' : 'Queue pass'}{#if take}<ResourceAmount pile={payment} />{/if}
</button>
{/each}
</div>
{#if offer.selected}
<div class="queued-person-status">
<span>Queued: {Object.values((offer.selected as {Payment: Record<string, number>[]}).Payment[0]).some(Boolean) ? 'take if offered' : 'pass'}</span>
<button disabled={$session.pending} onclick={() => controller.submit({QueueChoice:{key:offer.key,response:null}})}>Cancel queued choice</button>
</div>
{/if}
</article>
{/each}
{#if $session.view?.actionCards?.some((card) => card.tactics)}
<p class="card-use-rule">
Choose one use, then discard. Battle uses require Tactics: one card per combat round.
@ -76,7 +107,7 @@
<p><ResourceText text={card.tactics.description} /></p>
</section>{/if}
</article>
{:else}<p>No action cards in hand.</p>{/each}
{:else}{#if !offers.length}<p>No action cards in hand.</p>{/if}{/each}
{:else}
<p class="pile-hint">Top of the pile first. Select a card to read its rules.</p>
<div class="discard-list">
@ -133,4 +164,9 @@
.discard-id { color: var(--muted); font-size: 11px; }
.discard-rules .card-battle-use { margin-bottom: 0; }
@media (max-width: 600px) { .card-tabs { gap: 0.15rem; } .card-tabs button { padding: 0.5rem 0.35rem; font-size: 11px; gap: 0.25rem; } }
.queued-person-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 16px; }
.queued-person-actions button { display: flex; align-items: center; justify-content: center; gap: 8px; padding: 10px 14px; border: 1px solid var(--line); border-radius: 4px; }
.queued-person-status { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 8px; margin-top: 12px; font-size: .8rem; color: var(--muted); }
.queued-person-status button { border: 1px solid var(--line); border-radius: 4px; padding: 5px 8px; }
</style>

View file

@ -102,6 +102,8 @@
import CollectionCapacity from './CollectionCapacity.svelte';
import ContextualCards from './ContextualCards.svelte';
import DecisionPanel from './DecisionPanel.svelte';
import EarlyChoices from './EarlyChoices.svelte';
import EarlyChoiceBadge from './EarlyChoiceBadge.svelte';
import CombatJournal from './CombatJournal.svelte';
import { combatJournal } from './combat-journal';
import ActionCardsDialog from './ActionCardsDialog.svelte';
@ -127,6 +129,26 @@
import { roundProgress, personalRoundLabel } from './round-progress';
let { controller }: { controller: Controller } = $props();
const session = $derived(controller.session);
let earlyPanel = $state<'cities' | 'abilities' | 'first' | null>(null);
const earlyOffers = $derived(!$session.playback ? $session.view?.earlyChoices ?? [] : []);
const earlyAdvance = $derived(earlyOffers.find(o => o.key.endsWith('/advance')));
const earlyFirst = $derived(earlyOffers.filter(o => o.key.endsWith(':first')));
const earlyCities = $derived(earlyOffers.filter(o => o.key.endsWith('/raze')));
const earlyObjectives = $derived(earlyOffers.filter(o => o.key.includes(':objective:')));
const earlyPeople = $derived(earlyOffers.filter(o => o.key.endsWith('/offer')));
const earlyAbilities = $derived(earlyOffers.filter(o => !o.key.endsWith('/advance') && !o.key.endsWith('/raze') && !o.key.includes(':objective:') && !o.key.endsWith('/offer') && !o.key.endsWith('/government') && !o.key.endsWith(':first')));
const panelOffers = $derived(earlyPanel === 'cities' ? earlyCities : earlyPanel === 'abilities' ? earlyAbilities : earlyPanel === 'first' ? earlyFirst : []);
function openEarly(panel: 'cities' | 'abilities' | 'first') {
earlyPanel = earlyPanel === panel ? null : panel;
controller.closeActivity();
const offer = earlyPanel === 'cities' ? earlyCities[0] : undefined;
controller.patch({ mode: 'overview', tilePanel: false, abilitiesOpen: false, earlyRaze: offer ? {
key: offer.key,
positions: offer.options.flatMap(o => (o.response as {SelectPositions?: string[]}).SelectPositions ?? []),
selected: (offer.selected as {SelectPositions?: string[]} | null)?.SelectPositions?.[0] ?? null,
} : undefined });
}
// Preserve reference boundaries: opening panels or changing a selection does
// not require parsing the whole journal or recalculating recap history.
const game = $derived($session.game);
@ -494,6 +516,14 @@
},
};
}
function measureActionBar(node: HTMLElement) {
const layout = node.parentElement!;
const update = () => layout.style.setProperty('--action-bar-bottom', `${node.offsetTop + node.offsetHeight + 12}px`);
const observer = new ResizeObserver(update);
observer.observe(node);
update();
return { destroy: () => observer.disconnect() };
}
function showDialog(node: HTMLDialogElement) {
node.showModal();
return { destroy: () => node.close() };
@ -502,8 +532,10 @@
controller.patch({ help: false });
}
function closeAction() {
earlyPanel = null;
confirmEnd = false;
controller.patch({
earlyRaze: undefined,
mode: 'overview',
tilePanel: false,
collectionTile: null,
@ -522,12 +554,15 @@
closeAction();
}
function openResearch() {
earlyPanel = null;
controller.patch({earlyRaze: undefined});
confirmEnd = false;
controller.closeActivity();
controller.patch({
mode: 'research',
tilePanel: false,
selectedAdvance: null,
selectedAdvance: (earlyAdvance?.selected as {SelectAdvance?: string} | null)?.SelectAdvance ?? null,
availableOnly: !!earlyAdvance,
error: '',
abilitiesOpen: false,
});
@ -833,6 +868,9 @@
{#if $session.seat !== undefined}
<button
class="text-button cards-button"
class:queue-available={earlyPeople.length > 0}
class:queue-saved={earlyPeople.some(o => o.selected != null)}
title={earlyPeople.length ? 'Great Person offer · Choose ahead' : 'Cards'}
data-tutorial="cards"
aria-label={`Action cards: ${$session.view?.actionCards?.length ?? 0}`}
onclick={() => controller.patch({ cardsOpen: true })}
@ -849,6 +887,9 @@
>
<button
class="text-button objectives-button"
class:queue-available={earlyObjectives.length > 0}
class:queue-saved={earlyObjectives.some(o => o.selected != null)}
title={earlyObjectives.some(o => o.selected != null) ? 'Objective queued · Click to edit' : earlyObjectives.length ? 'Objective available to queue' : 'Objectives'}
aria-label={`Objectives: ${$session.view?.objectiveCards?.length ?? 0} ${$session.view?.objectiveCards?.length === 1 ? 'card' : 'cards'}`}
onclick={() => controller.patch({ objectivesOpen: true })}
><Target size={17} /> Objectives
@ -975,7 +1016,12 @@
><Swords size={13} />{forces.army}<Ship size={13} />{forces.ships}</span
>{/if}</span
><span class="player-score">{formatPoints(player.score)}<Trophy size={10} /></span>
</button>{/each}
</button>
{#if player.index === $session.seat && earlyFirst.length}
<button class="queue-first-player" class:saved={earlyFirst[0].selected != null} onclick={() => openEarly('first')}>
<EarlyChoiceBadge saved={earlyFirst[0].selected != null} inline />Choose first player
</button>
{/if}{/each}
</div>
{#if !$session.game}<div class="map-loading">
<Compass size={30} />
@ -1233,7 +1279,7 @@
>{/each}
</div>
</section>
<div class="board-toolbar" aria-label="Game controls">
<div class="board-toolbar" aria-label="Game controls" use:measureActionBar>
<div
class="turn-banner"
class:waiting={!!waiting}
@ -1296,12 +1342,13 @@
<button
class:active={$session.mode === 'research'}
class:inspect-only={!researchAvailable}
title={researchAvailable ? 'Research tree' : 'View research · Browse advances and costs'}
class:early-available={!!earlyAdvance}
title={earlyAdvance ? (earlyAdvance.selected ? 'Free advance saved · Click to edit' : 'Choose your free advance ahead of your turn') : researchAvailable ? 'Research tree' : 'View research · Browse advances and costs'}
data-tutorial="research"
aria-label="Research tree"
disabled={$session.seat === undefined}
onclick={openResearch}
><GraduationCap size={21} /><span>Research</span>{#if !researchAvailable}<Eye
><GraduationCap size={21} /><span>Research</span>{#if earlyAdvance}<EarlyChoiceBadge saved={earlyAdvance.selected != null} />{:else if !researchAvailable}<Eye
class="action-inspect"
size={10}
aria-hidden="true"
@ -1309,17 +1356,20 @@
>
<button
class:active={$session.mode === 'city' && $session.cityTab === 'build'}
class:inspect-only={!cityActionsAvailable}
class:inspect-only={!cityActionsAvailable && !earlyCities.length}
class:early-available={!!earlyCities.length}
aria-label="Manage cities"
title={cityActionsAvailable
title={earlyCities.length ? 'Choose city razing ahead of your turn' : cityActionsAvailable
? 'Build, recruit and improve happiness'
: 'View cities · Browse buildings, units and costs'}
disabled={!city}
disabled={!city && !earlyCities.length}
onclick={() => {
if (earlyCities.length) { openEarly('cities'); return; }
earlyPanel = null;
confirmEnd = false;
controller.openCities();
}}
><Hammer size={21} /><span>Cities</span>{#if !cityActionsAvailable}<Eye
><Hammer size={21} /><span>Cities</span>{#if earlyCities.length}<EarlyChoiceBadge saved={earlyCities.every(o => o.selected != null)} />{:else if !cityActionsAvailable}<Eye
class="action-inspect"
size={10}
aria-hidden="true"
@ -1393,18 +1443,21 @@
><Drama size={21} /><span>Influence</span></button>
<button
title={abilitiesAvailable
title={earlyAbilities.length ? 'Choose ahead · Events and objectives' : abilitiesAvailable
? 'Abilities'
: 'No abilities available'}
aria-label="Abilities"
class:active={$session.abilitiesOpen && !$session.influenceMode}
class:inspect-only={!abilitiesAvailable}
class:inspect-only={!abilitiesAvailable && !earlyAbilities.length}
class:early-available={!!earlyAbilities.length}
disabled={!$session.view}
onclick={() => {
if (earlyAbilities.length) { openEarly('abilities'); return; }
earlyPanel = null;
controller.closeActivity();
controller.patch({ mode: 'overview', tilePanel: false, abilitiesOpen: !$session.abilitiesOpen });
}}
><Sparkles size={21} /><span>Abilities</span>{#if !abilitiesAvailable}<Eye
><Sparkles size={21} /><span>Abilities</span>{#if earlyAbilities.length}<EarlyChoiceBadge saved={earlyAbilities.every(o => o.selected != null)} />{:else if !abilitiesAvailable}<Eye
class="action-inspect"
size={10}
aria-hidden="true"
@ -1481,6 +1534,9 @@
<ResourceAmount pile={$session.portPlacement.payment} />
</section>
{/if}
{#if panelOffers.length && $session.mode === 'overview' && !$session.abilitiesOpen}
<EarlyChoices {controller} offers={panelOffers} onclose={() => { earlyPanel = null; controller.patch({earlyRaze: undefined}); }} />
{/if}
{#if choiceDecision || objectiveDecision || (!$session.playback && $session.game && !$session.view?.supportedPhase && $session.seat === $session.view?.activePlayer) || $session.mode === 'collect' || confirmEnd || ($session.error && $session.mode === 'overview')}
<section
class="action-panel floating-panel"
@ -1953,6 +2009,18 @@
{#each card.objectives as objective, index}
{#if index > 0}<div class="objective-divider">or</div>{/if}
<ObjectiveCondition {objective} />
{@const offer = earlyObjectives.find(o => o.title === objective.name)}
{@const response = { SelectHandCards: [{ ObjectiveCard: card.id }] }}
{@const canQueue = offer?.options.some(o => JSON.stringify(o.response) === JSON.stringify(response))}
{@const queued = offer && JSON.stringify(offer.selected) === JSON.stringify(response)}
{#if canQueue && offer}
<div class="objective-queue-action">
<button class={queued ? 'secondary' : 'primary'} disabled={$session.pending}
onclick={() => controller.submit({QueueChoice:{key:offer.key,response:queued ? null : response}})}>
{#if queued}<Check size={15} />Cancel queued choice{:else}Queue choice{/if}
</button>
</div>
{/if}
{/each}
</article>
{:else}

View file

@ -1,5 +1,7 @@
<script lang="ts">
import { handCardDescription } from './card-text';
import GreatPersonEffect from './GreatPersonEffect.svelte';
import RazeActions from './RazeActions.svelte';
import CombatEstimate from './CombatEstimate.svelte';
import { printedCardName } from './card-names';
import { onDestroy } from 'svelte';
@ -31,6 +33,8 @@
const session = $derived(controller.session);
const panelId = $props.id();
const selected = $derived($session.decisionSelection);
const razeChoice = $derived(decision.name === 'Raze city');
const firstPlayerChoice = $derived(decision.name === 'Determine First Player');
const mapChoice = $derived(mapDecisionOptions(decision).length > 0);
const combatBenefit = $derived(
decision.name === 'Steel Weapons'
@ -41,7 +45,7 @@
&& decision.fields.some((field) => field.name === 'Pay to gain the Action Card')
? decision.eventContext.card : null);
const description = $derived(
combatBenefit ??
razeChoice ? 'Select a highlighted city on the map.' : combatBenefit ??
(decision.tacticsSelection && decision.name === 'Tactics'
? 'Play one battle effect or skip.'
: decision.name === 'Place Settler'
@ -185,7 +189,7 @@
onmouseleave={() => onHighlight(null)}
onfocus={() => onHighlight(option.position)}
onblur={() => onHighlight(null)}
onclick={() => toggle(i)}
onclick={() => { if (!firstPlayerChoice || !selected.includes(i)) toggle(i); }}
>
{#if option.terrain}<TerrainIcon terrain={option.terrain} />{:else if Icon}<Icon size={19} />{/if}
<DecisionOptionContent option={presented} id={`${panelId}-option-${i}`} />
@ -194,9 +198,10 @@
{foodRecipient.resources?.food ?? 0}/{foodRecipient.resource_limit?.food ?? 0}<Wheat size={15} />
</span>
{/if}
<span class="decision-selection" aria-hidden="true"
>{#if selected.includes(i)}<Check size={13} />{/if}</span
>
{#if firstPlayerChoice}
{#if selected.includes(i)}<Check size={18} aria-hidden="true" />{/if}
{:else}<span class="decision-selection" aria-hidden="true"
>{#if selected.includes(i)}<Check size={13} />{/if}</span>{/if}
</button>
{/each}
{/each}
@ -206,6 +211,7 @@
<section
class="action-panel floating-panel decision-panel"
data-tutorial="decision"
class:raze-prompt={razeChoice}
class:board-decision={mapChoice}
class:selection-tray={mapChoice}
class:unit-decision={unitChoice}
@ -213,7 +219,7 @@
class:tactics-decision={decision.tacticsSelection}
aria-label={printedCardName(decision.name)}
>
{#if decision.endOfAge}<span class="tiny-label">END OF AGE</span>{/if}
{#if decision.endOfAge && !razeChoice}<span class="tiny-label">END OF AGE</span>{/if}
<header class="decision-heading">
{#if canCancelAbility($session.game, $session.view)}
<button disabled={$session.pending} onclick={() => controller.submit('Undo')}>Cancel</button>
@ -273,10 +279,7 @@
{/if}
</header>
{#if cardOffer}
<div class="great-person-effect">
<span class="event-card-use">{#if cardOffer.description.startsWith("You make place")}Active when taken{:else}Play <span aria-label={`${cardOffer.free ? 0 : 1} actions`}>{cardOffer.free ? 0 : 1} <Zap size={13} /></span>{/if}</span>
<ResourceText text={handCardDescription(cardOffer.description)} />
</div>
<GreatPersonEffect card={cardOffer} />
{/if}
{#if description && !cardOffer && !$session.view?.influenceContext}<p class="decision-description">
<ResourceText
@ -451,14 +454,18 @@
disabled={$session.pending}
onchange={(event) => controller.setSkipRazeCity(event.currentTarget.checked)}
/>
Keep all cities; skip this step in future ages
Always keep cities in future ages
</label>
{/if}
{#if (decision.tacticsSelection || decision.name === 'Siegecraft') && preview.action}
<CombatEstimate {controller} action={preview.action} />
{/if}
<div class="decision-footer" class:map-decision-footer={mapChoice}>
{#if decision.tacticsSelection}
{#if razeChoice}
<RazeActions selected={selected.length ? decision.options[selected[0]].position : null} pending={$session.pending}
onkeep={() => { const response = controller.query<{action: Move}>({kind:'decision', values:[], payments:[]}); controller.submit(response.action); }}
onraze={() => preview.action && controller.submit(preview.action)} />
{:else if decision.tacticsSelection}
{#if selected.length}<small class="tactics-discard">Discards the selected card</small>{/if}
<button
class="secondary"
@ -479,10 +486,10 @@
>Play tactics<Check size={16} /></button
>{/if}
{:else}
{#if decision.options.length && !mapChoice}<div class="decision-count">
{#if decision.options.length && !mapChoice && !firstPlayerChoice}<div class="decision-count">
{count}<span>{selected.length}/{decision.max}</span>
</div>{/if}
{#if mapChoice && !unitChoice}<span
{#if mapChoice && !unitChoice && decision.max > 1}<span
class="map-selection-count"
aria-label={`${selected.length} of ${decision.max} selected`}
>{selected.length}/{decision.max}</span
@ -490,7 +497,7 @@
<button
class="primary"
class:wide={!mapChoice}
aria-label={mapChoice && selected.length
aria-label={mapChoice && decision.max > 1 && selected.length
? `Confirm · ${selected.length}/${decision.max}`
: undefined}
disabled={!preview.action || $session.pending}

View file

@ -0,0 +1,14 @@
<script lang="ts">
import { Clock, Check } from 'lucide-svelte';
let { saved, inline = false }: { saved: boolean; inline?: boolean } = $props();
</script>
<i class="early-badge" class:saved class:inline title={saved ? 'Choice saved · Click to edit' : 'Choose ahead'}>
{#if saved}<Check size={11} style="width:11px;height:11px" aria-label="Choice saved" />{:else}<Clock size={11} style="width:11px;height:11px" aria-label="Choose ahead" />{/if}
</i>
<style>
.early-badge { position: absolute; top: 3px; right: 3px; display: grid; place-items: center; width: 11px; height: 11px; color: #b87523; }
.inline { position: static; flex: 0 0 11px; }
.saved { color: var(--green); }
</style>

View file

@ -0,0 +1,79 @@
<script lang="ts">
import { Clock, Check, X, Sparkles } from 'lucide-svelte';
import type { View } from './types';
import type { Controller } from './controller';
import RazeActions from './RazeActions.svelte';
import ResourceText from './ResourceText.svelte';
let { controller, offers, onclose }: { controller: Controller; offers: NonNullable<View['earlyChoices']>; onclose: () => void } = $props();
const session = $derived(controller.session);
let selections = $state<Record<string, string>>({});
const raze = $derived(offers.length === 1 && offers[0].key.endsWith('/raze'));
const first = $derived(offers.length === 1 && offers[0].key.endsWith(':first'));
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
</script>
<section class="action-panel floating-panel early-choices" class:raze-prompt={raze} aria-label={raze ? 'Raze city' : first ? 'Choose first player' : 'Choose ahead'}>
<header>
<h2>{#if raze}<Sparkles size={21} />Raze city{:else}<Clock size={18} />{first ? 'Choose first player' : 'Choose ahead'}{/if}</h2>
<button class="icon-button" aria-label="Close early choices" onclick={onclose}><X size={18} /></button>
</header>
{#each offers as offer (offer.key)}
{@const saved = offer.options.findIndex((o) => same(o.response, offer.selected))}
{@const value = selections[offer.key] ?? (saved >= 0 ? JSON.stringify(offer.selected) : '')}
{@const selected = offer.options.findIndex((o) => JSON.stringify(o.response) === value)}
<div class="early-choice">
{#if !raze && !first}<label for={'early-' + offer.key}>{offer.title}</label>{/if}
{#if offer.key.endsWith('/advance')}
<div class="choice-row">
<button class="primary" disabled={$session.pending} onclick={() => controller.patch({mode: 'research', selectedAdvance: (offer.selected as {SelectAdvance?: string} | null)?.SelectAdvance ?? null, availableOnly: true})}>
{saved >= 0 ? offer.options[saved].label : 'Choose an advance'}
</button>
{#if saved >= 0}<button disabled={$session.pending} onclick={() => controller.submit({QueueChoice:{key:offer.key,response:null}})}>Clear</button>{/if}
</div>
{#if saved >= 0}<p class="hint"><Check size={13} /> Saved</p>{/if}
{:else if offer.key.endsWith('/raze')}
<p class="hint">Select a highlighted city on the map.</p>
<RazeActions queued selected={$session.earlyRaze?.selected ?? null} pending={$session.pending}
onkeep={() => { controller.submit({QueueChoice:{key:offer.key,response:{SelectPositions:[]}}}); onclose(); }}
onraze={() => { controller.submit({QueueChoice:{key:offer.key,response:{SelectPositions:[$session.earlyRaze!.selected]}}}); onclose(); }} />
{#if saved >= 0}
<div class="queued-choice">
<span>Queued: {(offer.selected as {SelectPositions: string[]}).SelectPositions.length ? `raze ${(offer.selected as {SelectPositions: string[]}).SelectPositions[0]}` : 'keep all cities'}</span>
<button disabled={$session.pending} onclick={() => { controller.submit({QueueChoice:{key:offer.key,response:null}}); onclose(); }}>Cancel queued choice</button>
</div>
{/if}
{:else}
<div class="option-list">
{#each offer.options as option}
<button class:chosen={same(option.response, offer.selected)} disabled={$session.pending}
onclick={() => { controller.submit({QueueChoice:{key:offer.key,response:option.response}}); onclose(); }}>
{first ? 'Queue ' : ''}{option.label}{#if same(option.response, offer.selected)}<Check size={15} />{/if}
</button>
{/each}
{#if saved >= 0}<button disabled={$session.pending} onclick={() => { controller.submit({QueueChoice:{key:offer.key,response:null}}); onclose(); }}>Cancel queued choice</button>{/if}
</div>
{/if}
{#if !offer.key.endsWith('/advance') && selected >= 0 && offer.options[selected]?.description}
<p class="hint"><ResourceText text={offer.options[selected].description} /></p>
{/if}
</div>
{/each}
</section>
<style>
.early-choices { max-height: min(60vh, 32rem); overflow-y: auto; }
header { display: flex; align-items: center; justify-content: space-between; gap: .75rem; }
h2 { display: flex; align-items: center; gap: .5rem; margin: 0; }
.hint { font-size: .8rem; color: var(--muted); line-height: 1.45; }
.early-choice { margin-top: 1rem; }
.raze-prompt .early-choice { margin-top: 0; }
label { display: block; font-weight: 600; margin-bottom: .4rem; }
.choice-row { display: flex; gap: .5rem; align-items: stretch; }
.queued-choice { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 12px; padding-top: 10px; border-top: 1px solid var(--line); font-size: .75rem; color: var(--muted); }
.queued-choice button { padding: 6px 8px; border: 1px solid var(--line); border-radius: 4px; color: var(--ink); font-size: inherit; }
.option-list { display: grid; gap: .5rem; }
.option-list button { display: flex; align-items: center; justify-content: space-between; text-align: left; padding: .7rem; border: 1px solid var(--line); border-radius: 4px; }
.option-list button.chosen { border-color: var(--green); }
.choice-row button { display: flex; align-items: center; gap: .3rem; white-space: nowrap; }
</style>

View file

@ -0,0 +1,10 @@
<script lang="ts">
import { Zap } from 'lucide-svelte';
import ResourceText from './ResourceText.svelte';
import { handCardDescription } from './card-text';
let { card }: {card: {description: string; free?: boolean}} = $props();
</script>
<div class="great-person-effect">
<span class="event-card-use">{#if card.description.startsWith('You make place')}Active when taken{:else}Play <span aria-label={`${card.free ? 0 : 1} actions`}>{card.free ? 0 : 1} <Zap size={13} /></span>{/if}</span>
<ResourceText text={handCardDescription(card.description)} />
</div>

View file

@ -0,0 +1,14 @@
<script lang="ts">
let { selected, pending, onkeep, onraze, queued = false }: {
selected: string | null; pending: boolean; queued?: boolean; onkeep: () => void; onraze: () => void;
} = $props();
</script>
<div class="raze-actions">
<button class="secondary" disabled={pending} onclick={onkeep}>{queued ? 'Queue keep all' : 'Keep all cities'}</button>
<button class="primary" disabled={pending || !selected} onclick={onraze}>{queued ? 'Queue raze' : 'Raze'}{selected ? ` ${selected}` : ''}</button>
</div>
<style>
.raze-actions { display: flex; gap: 8px; width: 100%; }
button { flex: 1; min-height: 40px; border-radius: 4px; padding: 8px 12px; }
.secondary { border: 1px solid var(--line); background: var(--paper2); }
</style>

View file

@ -57,7 +57,8 @@
} = $props();
const session = $derived(controller.session);
const view = $derived(reference?.view ?? $session.view);
const choice = $derived(!reference && !$session.playback && researchDecision(view) ? view!.decision : null);
const early = $derived(!reference && !$session.playback ? view?.earlyChoices?.find((o) => o.key.endsWith('/advance')) : undefined);
const choice = $derived(early ? { name: 'Free advance', description: '', advanceMode: 'free', endOfAge: true } : !reference && !$session.playback && researchDecision(view) ? view!.decision : null);
const freeResearch = $derived(!!choice && choice.advanceMode === 'free');
const borrowing = $derived(choice?.advanceMode === 'borrow');
let query = $state('');
@ -266,12 +267,12 @@
{#if reference && player}<span>· {player.civilization}</span>{/if}
{#if player}<EventMarkers remaining={player.eventTokens} />{/if}
</h2>
<p>
{#if !early}<p>
{choice
? choice.description
: 'Each advance scores ½ point. Branches unlock from their first advance.'}
</p>
{#if choice}<p class="research-choice-hint">Choose a highlighted advance.</p>{/if}
{#if choice}<p class="research-choice-hint">Choose a highlighted advance.</p>{/if}{/if}
{#if eventImminent}<p
class="research-event-notice"
id="research-event-notice"
@ -332,6 +333,7 @@
>
{:else if lockedGovernment}<LockKeyhole size={13} aria-label="Government unavailable" />{/if}
</h3>
{#if group === currentGovernment && !reference && !$session.playback}<label class="keep-government"><input type="checkbox" checked={$session.keepGovernment} disabled={$session.pending} onchange={e => controller.setKeepGovernment(e.currentTarget.checked)} />Always keep this government</label>{/if}
{#each (view?.actionCards ?? []).filter(card => card.name === 'Synergies' && advances.some(a => a.group === group && cardHints(a).includes(card))) as card}
<div class="research-card-hint">
<button class="research-advance-link" disabled={$session.pending}
@ -343,11 +345,10 @@
{/each}
{#if governmentGroups.includes(group)}<p class="government-rule">
{#if lockedGovernment}
<span>Only one government at a time.</span>
<span class="government-switch"
>Switch at end of age · <ResourceAmount pile={{ mood_tokens: 1, culture_tokens: 1 }} /></span
>
{:else if !currentGovernment}Only one government at a time. You can switch at the end of an age.{/if}
{:else if !currentGovernment}You can switch at the end of an age.{/if}
</p>{/if}
{#if lockedGovernment && statusFilter === 'available'}<button
class="show-all-options"
@ -416,8 +417,8 @@
+<ResourceAmount pile={bonus.pile} compact /> · {bonus.source}
</span>{/each}
</div>
{#if !advance.owned && (!choice || advance.action)}<div class="research-node-cost">
<span
{#if !advance.owned && (!choice || advance.action) && (!early || warnsEvent)}<div class="research-node-cost">
{#if !early}<span
class="research-flexible-cost"
title={borrowing
? 'Borrow until end of turn'
@ -440,14 +441,14 @@
{#if group.resources.length > 1}<span>any mix</span>{/if}
{/each}
{/if}
</span><span class="research-availability"
</span>{/if}<span class="research-availability"
>{#if researchAvailable(advance)}
{#if warnsEvent}<span
id={`research-${advance.id}-event`}
class="research-event-warning"
title="Uses your last event marker. The event resolves after research bonuses and choices."
><ScrollText size={12} aria-hidden="true" />Triggers an event</span
>{:else}Available{/if}
>{:else if !early}Available{/if}
{:else if !choice && parent && !parent.owned}
<button
class="research-advance-link"
@ -541,7 +542,10 @@
{#if unavailableReason(selected) && !selected.owned}<small>{unavailableReason(selected)}</small>{/if}
{#if $session.error && !reference}<p class="inline-error" role="alert">{$session.error}</p>{/if}
</div>
{#if !reference && !$session.playback}<div class="research-payment">
{#if !reference && !$session.playback}<div class="research-payment" class:early-payment={!!early}>
{#if early?.selected}
<button class="clear-choice" disabled={$session.pending} onclick={() => { controller.submit({QueueChoice: {key: early!.key, response: null}}); controller.patch({mode: 'overview'}); }}>Clear</button>
{/if}
{#if !choice && !selected.owned && selected.payments.length > 1}
<PaymentPicker
options={selected.payments.map((option) => ({
@ -591,14 +595,14 @@
selectedAction &&
(!choice
? controller.submitResearch(selectedAction, buyFreeEducation)
: controller.submit(selectedAction))}
: (controller.submit(selectedAction), early && controller.patch({ mode: 'overview' })))}
>
{$session.pending
? 'Confirming…'
: selected.owned
? 'Researched'
: `${borrowing ? 'Use' : choice?.advanceMode === 'paid' ? 'Choose' : 'Research'} ${selected.name}`}
{#if !selected.owned}<span
: early ? 'Queue choice' : `${borrowing ? 'Use' : choice?.advanceMode === 'paid' ? 'Choose' : 'Research'} ${selected.name}`}
{#if !selected.owned && !early}<span
>{#if eventImminent}<ScrollText size={13} aria-hidden="true" />{/if}{#if borrowing}Until end
of turn{:else if freeResearch}Free{:else if choice}{selected.costAmount === 0
? 'Free'
@ -613,9 +617,9 @@
>{/if}
</button>
</div>{/if}
<button class="icon-button" aria-label="Close research details" onclick={() => selectAdvance(null)}
{#if !early}<button class="icon-button" aria-label="Close research details" onclick={() => selectAdvance(null)}
><X size={18} /></button
>
>{/if}
</section>
{:else}<div class="research-legend">
<span><Check size={14} /> Researched</span><span class="available-key">Available</span><span

View file

@ -1047,7 +1047,8 @@ export class World {
};
}
if (!s.game) return;
const mapChoices = mapDecisionOptions(s.view?.decision);
const earlyRaze = s.mode === 'overview' && s.earlyRaze && s.view?.earlyChoices?.some(o => o.key === s.earlyRaze!.key) ? s.earlyRaze : undefined;
const mapChoices = earlyRaze ? earlyRaze.positions.map(position => ({position, name: position, description: '', value: position, mapTarget: undefined})) : mapDecisionOptions(s.view?.decision);
this.tileTooltip.update(s);
const decisionPositions = [...new Set(mapChoices.map((o) => o.position!))];
const pieceDecision = mapChoices.some((o) => o.mapTarget);
@ -1103,13 +1104,13 @@ export class World {
: [];
this.labelHost.classList.toggle('collecting', s.mode === 'collect');
this.labelHost.classList.toggle('choosing-happiness', s.mode === 'happiness');
const decisionSelected = s.decisionSelection.flatMap((i) => mapChoices[i]?.position ?? []);
const decisionSelected = earlyRaze ? (earlyRaze.selected ? [earlyRaze.selected] : []) : s.decisionSelection.flatMap((i) => mapChoices[i]?.position ?? []);
const interacting =
s.mode === 'collect' ||
s.mode === 'happiness' ||
s.mode === 'settlers' ||
s.tilePanel ||
mapChoices.length > 0 ||
(mapChoices.length > 0 && !earlyRaze) ||
choosingCity ||
!!exploration ||
!!s.view?.decision?.tacticsSelection;
@ -2178,7 +2179,8 @@ export class World {
if (interactionSignature !== this.interactionSignature) {
this.interactionSignature = interactionSignature;
this.updateViewport();
this.centerInteraction();
// Queued choices highlight the existing view without moving the player’s camera.
if (!earlyRaze) this.centerInteraction();
if (exploration) this.locateExploration();
}
this.updateStructureMarkers(s, influence);

View file

@ -87,6 +87,7 @@ export class Controller {
replayAutoplay: true,
availableOnly: false,
skipRazeCity: false,
keepGovernment: false,
});
readonly chat = new ChatController();
readonly audio = new GameAudio();
@ -193,7 +194,7 @@ export class Controller {
}
setSettings(settings: Record<string, unknown> | null) {
this.playerSettings = settings;
this.patch({ skipRazeCity: settings?.skipRazeCity === true });
this.patch({ skipRazeCity: settings?.skipRazeCity === true, keepGovernment: settings?.keepGovernment === true });
const request = this.keepCitiesRequest;
this.keepCitiesRequest = null;
const s = get(this.session);
@ -240,6 +241,11 @@ export class Controller {
this.migratedSkipRaze = true;
this.commands.updateSetting('skipRazeCity', true);
}
setKeepGovernment(enabled: boolean) {
const s = get(this.session);
if (s.analysis || s.playback || s.pending || s.seat === undefined) return;
if (!this.commands.updateSetting('keepGovernment', enabled)) this.patch({error: 'Could not save the government setting. Please try again.'});
}
setSkipRazeCity(enabled: boolean) {
const s = get(this.session);
if (s.analysis || s.playback || s.pending || s.seat === undefined) return;
@ -948,7 +954,7 @@ export class Controller {
if (get(this.session).seat !== undefined) this.playerSettings = null;
this.migratedSkipRaze = false;
this.keepCitiesRequest = null;
this.patch({ skipRazeCity: this.playerSettings?.skipRazeCity === true });
this.patch({ skipRazeCity: this.playerSettings?.skipRazeCity === true, keepGovernment: this.playerSettings?.keepGovernment === true });
this.cardContinuation = null;
this.endPlayback();
this.dismissEffects(true);
@ -1049,6 +1055,11 @@ export class Controller {
this.inspectTile(position);
return;
}
if (s.earlyRaze && s.mode === 'overview' && s.view?.earlyChoices?.some(o => o.key === s.earlyRaze!.key)) {
if (!s.pending && s.earlyRaze.positions.includes(position))
this.patch({earlyRaze: {...s.earlyRaze, selected: s.earlyRaze.selected === position ? null : position}});
return;
}
if (s.mode === 'port') {
if (s.pending) return;
const choice = s.portPlacement?.choices.find(c => c.position === position);
@ -1843,6 +1854,10 @@ export class Controller {
s.playback ||
s.seat === undefined ||
(!(s.view?.activePlayers ?? [s.view?.activePlayer]).includes(s.seat) &&
!(
typeof move === 'object' && 'QueueChoice' in move &&
s.view?.earlyChoices?.some((c) => c.key === (move.QueueChoice as { key?: string })?.key)
) &&
!(
s.view?.civilizationDraft &&
typeof move === 'object' &&

View file

@ -150,7 +150,20 @@ test('free research exposes exactly the legal choices without paid actions or re
assert.equal(next.players[seat].resources.food ?? 0, 0);
assert.equal(next.players[seat].resources.gold ?? 0, 0);
assert.ok(!researchDecision(view(state, 1 - seat)));
assert.ok(view(state, 1 - seat).advances.every((a) => !a.action));
const waiting = view(state, 1 - seat);
const queuedAdvances = waiting.advances.filter((a) => a.action);
assert.ok(queuedAdvances.length > 0);
for (const advance of queuedAdvances) {
assert.ok('QueueChoice' in (advance.action as object));
assert.equal(advance.costAmount, 0);
assert.deepEqual(advance.payments, []);
}
const queued = JSON.parse(engine.tryMove(state, JSON.stringify(queuedAdvances[0].action), 1 - seat));
for (let player = 0; player < raw.players.length; player++) {
assert.deepEqual(queued.players[player].advances, raw.players[player].advances);
assert.deepEqual(queued.players[player].resources ?? {}, raw.players[player].resources ?? {});
}
assert.equal(engine.currentPlayer(JSON.stringify(queued)), seat);
assert.ok(!researchDecision(JSON.parse(engine.webView(engine.stripSecret(state)))));
});

View file

@ -0,0 +1,233 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const npcs = JSON.parse(await engine.init(2, [], {}, 'early-choices', {})).players.slice(2);
function fixture(name: string) {
const g = JSON.parse(readFileSync(new URL(`../../server/tests/test_games/${name}.json`, import.meta.url), 'utf8'));
g.players = [...g.players.slice(0, 2), ...structuredClone(npcs)];
return JSON.stringify(g);
}
const apply = (raw: string, move: unknown, player = engine.currentPlayer(raw)) => engine.tryMove(raw, JSON.stringify(move), player);
const view = (raw: string, player: number) => JSON.parse(engine.webView(engine.stripSecret(raw, player), player));
const queue = (raw: string, player: number, key: string, response: unknown) => apply(raw, { QueueChoice: { key, response } }, player);
const actions = (raw: string) => JSON.parse(raw).log.flatMap((a: any) => a.rounds.flatMap((r: any) => r.turns.flatMap((t: any) => t.actions ?? [])));
function research() { return apply(fixture('status_phase/free_advance'), { Playing: 'EndTurn' }); }
test('early research is private, editable and persisted without spending or advancing play', () => {
const before = research();
assert.equal(engine.currentPlayer(before), 1);
const offer = view(before, 0).earlyChoices[0];
const selected = offer.options.find((o: any) => o.response.SelectAdvance === 'Philosophy');
assert.ok(selected);
const command = JSON.stringify({ QueueChoice: { key: offer.key, response: selected.response } });
assert.equal(engine.canMoveOutOfTurn(before, command, 0), true);
const queued = queue(before, 0, offer.key, selected.response);
assert.equal(engine.isLiveUpdate(queued), true);
assert.equal(engine.currentPlayer(queued), 1);
assert.deepEqual(JSON.parse(queued).players, JSON.parse(before).players);
assert.equal(actions(queued).length, actions(before).length);
assert.equal(JSON.parse(engine.stripSecret(queued, 1)).early_choices, undefined);
assert.equal(JSON.parse(engine.stripSecret(queued, undefined)).early_choices, undefined);
assert.deepEqual(view(queued, 0).earlyChoices[0].selected, selected.response);
const cancelled = queue(queued, 0, offer.key, null);
assert.equal(JSON.parse(cancelled).early_choices, undefined);
const edited = queue(queued, 0, offer.key, offer.options[0].response);
assert.equal(JSON.parse(edited).early_choices.length, 1);
});
test('queued research resolves in order as a normal journal response and replays', () => {
const before = research();
const offer = view(before, 0).earlyChoices[0];
const queued = queue(before, 0, offer.key, { SelectAdvance: 'Philosophy' });
const after = apply(queued, { Response: { SelectAdvance: 'Storage' } }, 1);
assert.ok(JSON.parse(after).players[0].advances.includes('Philosophy'));
assert.ok(JSON.parse(after).players[1].advances.includes('Storage'));
assert.equal(JSON.parse(after).early_choices, undefined);
assert.equal(engine.isLiveUpdate(after), false);
const added = actions(after).slice(actions(before).length).map((a: any) => a.action);
assert.deepEqual(added.slice(0, 2), [{ Response: { SelectAdvance: 'Storage' } }, { Response: { SelectAdvance: 'Philosophy' } }]);
let replay = before;
for (const action of added) if (action !== 'StartTurn') replay = apply(replay, action);
assert.deepEqual(JSON.parse(replay).players, JSON.parse(after).players);
});
test('forged, stale, active-player and spectator queues are rejected', () => {
const raw = research();
const offer = view(raw, 0).earlyChoices[0];
for (const [player, key, response] of [
[0, offer.key, { SelectAdvance: 'SteelWeapons' }],
[0, 'old-window', offer.options[0].response],
[1, offer.key, offer.options[0].response],
[99, offer.key, offer.options[0].response],
] as const) assert.throws(() => queue(raw, player, key, response));
});
test('a queued raze invalidated by a board change asks again instead of choosing another city', () => {
let raw = fixture('status_phase/raze_city');
const offer = view(raw, 1).earlyChoices[0];
const pick = offer.options.find((o: any) => o.response.SelectPositions.length);
assert.ok(pick);
raw = queue(raw, 1, offer.key, pick.response);
const changed = JSON.parse(raw);
const city = changed.players[1].cities.find((c: any) => c.position === pick.response.SelectPositions[0]);
city.city_pieces = { temple: 1 };
raw = apply(JSON.stringify(changed), { Response: { SelectPositions: [] } }, 0);
assert.ok(JSON.parse(raw).players[1].cities.some((c: any) => c.position === city.position));
assert.equal(JSON.parse(raw).early_choices, undefined);
});
function person() {
const g = JSON.parse(fixture('incidents/pirates_spawn'));
g.incidents_left = [55];
g.players[1].resources = { food: 2, culture_tokens: 4 };
let raw = JSON.stringify(g);
for (const response of [{ SelectAdvance: 'Storage' }, { SelectPositions: ['A2'] }, { SelectPositions: ['D1'] }, { Payment: [{ food: 1 }] }]) raw = apply(raw, { Response: response });
return raw;
}
test('Great Person preacceptance respects priority and waits through the recipient pirate payment', () => {
const raw = person();
const offer = view(raw, 1).earlyChoices[0];
assert.ok(offer);
const queued = queue(raw, 1, offer.key, { Payment: [{ culture_tokens: 2 }] });
const passed = apply(queued, { Response: { Payment: [{}] } }, 0);
assert.equal(engine.currentPlayer(passed), 1);
assert.ok(JSON.parse(passed).events.at(-1).handler.request.Payment[0].name.includes('pirates'));
assert.ok(!(JSON.parse(passed).players[1].action_cards ?? []).includes(155));
const after = apply(passed, { Response: { Payment: [{ food: 1 }] } }, 1);
assert.ok(JSON.parse(after).players[1].action_cards.includes(155));
assert.equal(JSON.parse(after).players[1].resources.culture_tokens, 2);
});
test('Great Person claimed by earlier player expires conditional offers without charging others', () => {
const raw = person();
const offer = view(raw, 1).earlyChoices[0];
const queued = queue(raw, 1, offer.key, { Payment: [{ culture_tokens: 2 }] });
let after = apply(queued, { Response: { Payment: [{ culture_tokens: 1 }] } }, 0);
after = apply(after, { Response: { Payment: [{ food: 1 }] } }, 1);
assert.equal(JSON.parse(after).players[1].resources.culture_tokens, 4);
assert.ok(JSON.parse(after).players[0].action_cards.includes(155));
assert.equal(JSON.parse(after).early_choices, undefined);
});
test('early objective choices stay private and complete only when that player is reached', () => {
const g = JSON.parse(fixture('objective_cards/status_phase/standing_army'));
g.players[1].objective_cards = [13];
g.players[1].resources.wood = 7;
let raw = apply(JSON.stringify(g), { Playing: 'EndTurn' }, 1);
const offer = view(raw, 1).earlyChoices.find((o: any) => o.title === 'Wood Supplies');
assert.ok(offer, 'other player can queue a qualifying status objective');
const pick = offer.options.find((o: any) => o.response.SelectHandCards.length);
for (const other of view(raw, 1).earlyChoices) {
raw = queue(raw, 1, other.key, other.key === offer.key ? pick.response : { SelectHandCards: [] });
}
assert.ok(!JSON.parse(raw).players[1].completed_objectives?.length);
for (let i = 0; i < 3 && engine.currentPlayer(raw) === 0; i++) {
if (!JSON.parse(raw).events.at(-1)?.handler?.request.SelectHandCards) break;
raw = apply(raw, { Response: { SelectHandCards: [] } }, 0);
}
assert.ok(JSON.parse(raw).players[1].completed_objectives.some((o: any) => o.name === 'Wood Supplies'));
});
test('objectives can be queued before status, replace the other side, and expire when no longer met', () => {
const g = JSON.parse(fixture('objective_cards/status_phase/standing_army'));
g.players[1].objective_cards = [13];
g.players[1].resources.wood = 7;
const before = JSON.stringify(g);
const offers = view(before, 1).earlyChoices;
const wood = offers.find((o: any) => o.title === 'Wood Supplies');
assert.ok(wood, 'objective is available before ending the turn');
const response = { SelectHandCards: [{ ObjectiveCard: 13 }] };
const queued = queue(before, 1, wood.key, response);
assert.equal(JSON.parse(queued).early_choices.length, 1);
const other = offers.find((o: any) => o.key !== wood.key && o.options.some((v: any) => JSON.stringify(v.response) === JSON.stringify(response)));
if (other) {
const replaced = queue(queued, 1, other.key, response);
assert.equal(JSON.parse(replaced).early_choices.length, 1);
assert.equal(JSON.parse(replaced).early_choices[0].key, other.key);
}
const changed = JSON.parse(queued);
changed.players[1].resources.wood = 0;
const after = apply(JSON.stringify(changed), { Playing: 'EndTurn' }, 1);
assert.ok(!(JSON.parse(after).early_choices ?? []).some((c: any) => c.key === wood.key));
});
test('a pre-status objective queue resolves only at that player’s objective check', () => {
const g = JSON.parse(fixture('objective_cards/status_phase/standing_army'));
g.players[1].objective_cards = [13];
g.players[1].resources.wood = 7;
let raw = JSON.stringify(g);
for (const offer of view(raw, 1).earlyChoices) {
raw = queue(raw, 1, offer.key, offer.title === 'Wood Supplies'
? { SelectHandCards: [{ ObjectiveCard: 13 }] } : { SelectHandCards: [] });
}
raw = apply(raw, { Playing: 'EndTurn' }, 1);
assert.ok(!JSON.parse(raw).players[1].completed_objectives?.length);
for (let i = 0; i < 3 && engine.currentPlayer(raw) === 0; i++) {
if (!JSON.parse(raw).events.at(-1)?.handler?.request.SelectHandCards) break;
raw = apply(raw, { Response: { SelectHandCards: [] } }, 0);
}
assert.ok(JSON.parse(raw).players[1].completed_objectives.some((o: any) => o.name === 'Wood Supplies'));
});
function governmentQueueSetup() {
const g = JSON.parse(fixture('status_phase/change_government'));
g.players[1].advances = [...g.players[0].advances];
g.players[0].resources.mood_tokens = 6;
return apply(JSON.stringify(g), {Response:{SelectPositions:[]}});
}
test('first player can be queued during government choices and resolves only for the actual chooser', () => {
const before = governmentQueueSetup();
const offer = view(before, 1).earlyChoices.find((o: any) => o.key.endsWith(':first'));
assert.ok(offer);
let state = queue(before, 1, offer.key, {SelectPlayer:1});
state = engine.setPlayerSettings(state, 1, {keepGovernment:true});
state = apply(state, {Response:{Payment:[{}]}});
assert.equal(JSON.parse(state).starting_player_index, 1);
assert.equal(JSON.parse(state).early_choices, undefined);
});
test('a changed first-player chooser does not consume another player’s queued selection', () => {
const before = governmentQueueSetup();
const offer = view(before, 1).earlyChoices.find((o:any) => o.key.endsWith(':first'));
let state = queue(before,1,offer.key,{SelectPlayer:1});
const g = JSON.parse(state);
g.players[1].resources.mood_tokens = 5;
state = engine.setPlayerSettings(JSON.stringify(g), 1, {keepGovernment:true});
state = apply(state,{Response:{Payment:[{}]}});
assert.equal(engine.currentPlayer(state),0);
assert.deepEqual(JSON.parse(state).events.at(-1).handler.request.SelectPlayer.choices, [0,1]);
assert.equal(JSON.parse(state).starting_player_index, 0);
});
test('first-player queue is visible only to the current eligible chooser, including ties', () => {
const g = JSON.parse(governmentQueueSetup());
const hasOffer = () => view(JSON.stringify(g), 1).earlyChoices.some((o: any) => o.key.endsWith(':first'));
assert.equal(hasOffer(), true); // Greece: 14 tokens, Rome: 13.
g.players[1].resources.mood_tokens = 6;
assert.equal(hasOffer(), false); // Tie goes to Rome, first in turn order.
g.players[1].resources.mood_tokens = 5;
assert.equal(hasOffer(), false);
});
test('keep-government preference skips the optional payment without changing advances or resources', () => {
const before = governmentQueueSetup();
const queued = engine.setPlayerSettings(before, 1, {keepGovernment:true});
const after = apply(queued, {Response:{Payment:[{}]}});
const p = JSON.parse(after).players[1];
assert.deepEqual(p.advances, JSON.parse(before).players[1].advances);
assert.deepEqual(p.resources, JSON.parse(before).players[1].resources);
assert.ok(JSON.parse(after).events.at(-1).handler.request.SelectPlayer);
assert.ok(!view(before,1).earlyChoices.some((o:any) => o.key.endsWith('/government')));
});
test('disabling keep-government restores the normal payment prompt', () => {
let state = engine.setPlayerSettings(governmentQueueSetup(),1,{keepGovernment:true});
state = engine.setPlayerSettings(state,1,{keepGovernment:false});
state = apply(state,{Response:{Payment:[{}]}});
assert.equal(engine.currentPlayer(state),1);
assert.equal(JSON.parse(state).events.at(-1).handler.request.Payment[0].name,'Pay to change government');
});

View file

@ -1,6 +1,7 @@
const frame = document.querySelector('iframe')!;
if (new URLSearchParams(location.search).has('built')) frame.src = '/built-viewer.html';
const seatSelect = document.querySelector<HTMLSelectElement>('#seat')!;
seatSelect.value = sessionStorage.getItem('clash-preview-seat') ?? 'auto';
let revision = -1;
let seat: number | undefined;
let ready = false;
@ -31,6 +32,7 @@ try {
'availableOnly',
'replayAutoplay',
'skipRazeCity',
'keepGovernment',
])
if (typeof saved[key] === 'boolean') preferences[key] = saved[key];
if (['2d', 'strategy'].includes(saved.mapView)) preferences.mapView = 'strategy';
@ -171,11 +173,16 @@ addEventListener('message', async (event) => {
`Player ${payload.index + 1} · ${payload.index === 0 ? 'Leif' : 'Aurelia'}`;
});
seatSelect.onchange = () => {
sessionStorage.setItem('clash-preview-seat', seatSelect.value);
lastMessages = '';
void refresh(true);
};
document.querySelector('#reset')!.addEventListener('click', async () => {
await post('/api/reset', {});
sessionStorage.removeItem('clash-preview-scenario');
scenarioSelect.value = '';
scenarioNote.style.display = 'none';
restartScenario.disabled = true;
lastMessages = '';
showError('');
await refresh(true);
@ -187,3 +194,33 @@ document.querySelector('#theme')!.addEventListener('click', () => {
setInterval(() => {
if (ready) void refresh();
}, 2000);
const scenarioSelect = document.querySelector<HTMLSelectElement>('#scenario')!;
const restartScenario = document.querySelector<HTMLButtonElement>('#restart-scenario')!;
const scenarioNote = document.querySelector<HTMLElement>('#scenario-note')!;
let scenarios: {id: string; label: string; note: string}[] = [];
fetch('/api/scenarios').then(r => r.json()).then(data => {
scenarios = data;
for (const item of scenarios) scenarioSelect.add(new Option(item.label, item.id));
const remembered = sessionStorage.getItem('clash-preview-scenario');
const scenario = scenarios.find(s => s.id === remembered);
if (scenario) { scenarioSelect.value = scenario.id; restartScenario.disabled = false; scenarioNote.textContent = scenario.note; scenarioNote.style.display = 'block'; }
});
async function loadScenario() {
if (!scenarioSelect.value) return;
try {
restartScenario.disabled = true;
showError('');
const result = await post('/api/scenarios', {id: scenarioSelect.value});
seatSelect.value = String(result.seat);
sessionStorage.setItem('clash-preview-seat', seatSelect.value);
sessionStorage.setItem('clash-preview-scenario', scenarioSelect.value);
lastMessages = '';
scenarioNote.textContent = scenarios.find(s => s.id === scenarioSelect.value)?.note ?? '';
scenarioNote.style.display = 'block';
frame.src = frame.src;
} catch (error) { showError(String(error)); }
finally { restartScenario.disabled = false; }
}
scenarioSelect.onchange = () => { void loadScenario(); };
restartScenario.onclick = () => { void loadScenario(); };

View file

@ -645,3 +645,19 @@
.score-dialog .civilization-advances {
margin: 20px 0;
}
.research-payment.early-payment {
display: flex;
align-items: stretch;
gap: 8px;
}
.early-payment .clear-choice {
padding: 10px 16px;
border: 1px solid var(--line);
border-radius: 4px;
background: var(--paper);
}
.early-payment .primary { flex: 1; width: auto; }
.keep-government { display:flex; gap:8px; align-items:center; font-size:12px; margin:0 0 12px; color:var(--muted); cursor:pointer; }

View file

@ -6317,3 +6317,54 @@ small {
white-space: nowrap;
}
}
.board-toolbar .board-actions button.early-available {
background: var(--paper2);
box-shadow: inset 0 -2px var(--gold, #b59255);
color: var(--ink);
}
@media (min-width: 761px) and (min-height: 501px) {
.play-layout .action-panel.floating-panel.early-choices {
top: var(--action-bar-bottom, 154px);
max-height: calc(100% - var(--action-bar-bottom, 154px) - 20px);
}
}
/* Both immediate and queued razing use the same desktop map prompt. */
@media (min-width: 761px) and (min-height: 501px) {
.game-shell .play-layout .action-panel.floating-panel.raze-prompt {
left: auto;
right: 20px;
top: var(--action-bar-bottom, 154px);
bottom: auto;
width: 354px;
max-height: calc(100% - var(--action-bar-bottom, 154px) - 20px);
padding: 16px;
gap: 8px;
}
.game-shell .raze-prompt h2 { font-size: 24px; margin: 0; }
}
.objective-queue-action { display: flex; justify-content: flex-end; margin: 8px 0 12px; }
.objective-queue-action button { display: flex; gap: 6px; align-items: center; padding: 8px 12px; border: 1px solid var(--line); border-radius: 4px; }
.header-actions .cards-button.queue-available > svg,
.header-actions .objectives-button.queue-available > svg {
color: #b87523;
}
.header-actions .cards-button.queue-saved > svg,
.header-actions .objectives-button.queue-saved > svg {
color: var(--green);
}
@media (min-width: 761px) and (min-height: 501px) {
.header-actions .text-button {
padding-block: 10px;
margin-block: -10px;
border-radius: 6px;
}
}
.queue-first-player { display: flex; align-items: center; gap: 6px; padding: 7px 10px; border-radius: 5px; background: var(--paper); color: var(--ink); font-size: 11px; }
.queue-first-player.saved { color: var(--green); }

View file

@ -18,7 +18,7 @@ export interface City {
}
export interface Player {
id: number;
settings?: { skipRazeCity?: boolean };
settings?: { skipRazeCity?: boolean; keepGovernment?: boolean };
name?: string;
civilization: string;
resources?: Pile;
@ -279,6 +279,7 @@ export interface ActiveEffect {
rules: string[];
}
export interface View {
earlyChoices?: { key: string; title: string; options: { label: string; description: string; response: unknown }[]; selected: unknown | null }[];
activeEffects?: ActiveEffect[];
cardCatalog?: Pick<ActionCard, 'id' | 'name' | 'description' | 'free' | 'tactics'>[];
influenceContext?: InfluenceContext | null;
@ -540,6 +541,7 @@ export interface EventInfo {
targets: ('all' | 'active' | 'selected')[];
}
export interface Session {
earlyRaze?: { key: string; positions: string[]; selected: string | null };
eventNotices?: import('./event-notices').EventNotice[];
portPlacement?: { city: string; payment: Pile; choices: { position: string; action: Move }[] };
landingTargets?: string[];
@ -636,6 +638,7 @@ export interface Session {
replayAutoplay: boolean;
availableOnly: boolean;
skipRazeCity: boolean;
keepGovernment: boolean;
}
export interface MapPick {
kind: 'tile' | 'city' | 'unit' | 'units' | 'decision';