Persist action queues for Technology Trade and replacement settlers
This commit is contained in:
parent
4bdfc1e01a
commit
65fa7d8eed
42 changed files with 767 additions and 129 deletions
|
|
@ -37,6 +37,7 @@ pub enum Action {
|
|||
Playing(PlayingAction),
|
||||
Movement(MovementAction),
|
||||
Response(EventResponse),
|
||||
QueueMoves { key: String, actions: Vec<Action>, waiting: bool },
|
||||
QueueChoice { key: String, response: Option<EventResponse> },
|
||||
Undo,
|
||||
Redo,
|
||||
|
|
@ -75,6 +76,10 @@ pub fn try_execute_action(
|
|||
player_index: usize,
|
||||
) -> Result<Game, String> {
|
||||
game.early_choice_update = false;
|
||||
if let Action::QueueMoves { key, actions, waiting } = &action {
|
||||
crate::action_queue::save(&mut game, player_index, key, actions.clone(), *waiting)?;
|
||||
return Ok(game);
|
||||
}
|
||||
if let Action::QueueChoice { key, response } = &action {
|
||||
crate::early_choices::save(&mut game, player_index, key, response.clone())?;
|
||||
return Ok(game);
|
||||
|
|
|
|||
214
server/src/action_queue.rs
Normal file
214
server/src/action_queue.rs
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
//! Private plans around narrowly identified off-turn reactions. The real event
|
||||
//! stays in place until its owner responds; plans execute only afterwards.
|
||||
use crate::{
|
||||
action::{Action, try_execute_action},
|
||||
content::persistent_events::{PersistentEventRequest, PersistentEventType},
|
||||
events::EventOrigin,
|
||||
game::Game,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Plan {
|
||||
pub player: usize,
|
||||
pub key: String,
|
||||
pub actions: Vec<Action>,
|
||||
pub waiting: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
pub fn offer(game: &Game, player: usize) -> Option<(String, String)> {
|
||||
if player != game.current_player_index
|
||||
|| player == game.active_player()
|
||||
|| game.round > 3
|
||||
|| game.events.len() != 1
|
||||
|| game.civilization_draft.is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let event = game.events.last()?;
|
||||
let handler = event.player.handler.as_ref()?;
|
||||
let label = match (&event.event_type, &handler.origin, &handler.request) {
|
||||
(
|
||||
PersistentEventType::CombatEnd(_),
|
||||
EventOrigin::Ability(name),
|
||||
PersistentEventRequest::SelectPositions(_),
|
||||
) if name == "Place Settler" => "Placing a settler",
|
||||
(PersistentEventType::ActionCard(card), _, PersistentEventRequest::SelectAdvance(_))
|
||||
if card.active_player == Some(player)
|
||||
&& card.selected_player == Some(game.active_player())
|
||||
&& game.cache.get_action_card(card.id).civil_card.name == "Technology Trade" =>
|
||||
{
|
||||
"Choosing an advance"
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let key = format!(
|
||||
"{:x}",
|
||||
Sha256::digest(
|
||||
serde_json::to_vec(&(
|
||||
game.age,
|
||||
game.round,
|
||||
crate::game_api::log_length(game),
|
||||
&game.events
|
||||
))
|
||||
.ok()?
|
||||
)
|
||||
);
|
||||
Some((key, label.into()))
|
||||
}
|
||||
|
||||
fn safe_step(game: Game, action: Action, player: usize) -> Result<Game, String> {
|
||||
if !matches!(
|
||||
action,
|
||||
Action::Playing(_) | Action::Movement(_) | Action::Response(_)
|
||||
) {
|
||||
return Err("This action cannot be queued".into());
|
||||
}
|
||||
// Spy can reveal a hand without consuming randomness or a draw pile.
|
||||
if game.events.iter().any(|event| match &event.event_type {
|
||||
PersistentEventType::ActionCard(card) => [7, 8].contains(&card.id),
|
||||
PersistentEventType::PayAction(pay) => serde_json::to_value(pay)
|
||||
.ok()
|
||||
.is_some_and(|v| matches!(v["action"]["ActionCard"].as_u64(), Some(7 | 8))),
|
||||
_ => false,
|
||||
}) {
|
||||
return Err("Wait for the earlier choice before revealing a hand".into());
|
||||
}
|
||||
// A battle must not be sampled, even if its first step only asks for tactics.
|
||||
if let Action::Movement(crate::movement::MovementAction::Move(ref movement)) = action {
|
||||
if game.players.iter().any(|p| {
|
||||
p.index != player
|
||||
&& p.units.iter().any(|u| {
|
||||
u.position == movement.destination
|
||||
&& u.unit_type != crate::unit::UnitType::Settler
|
||||
})
|
||||
}) {
|
||||
return Err("Wait for the earlier choice before attacking".into());
|
||||
}
|
||||
}
|
||||
let before = serde_json::to_value(game.cloned_data()).map_err(|e| e.to_string())?;
|
||||
let result = try_execute_action(game, action, player)?;
|
||||
let after = serde_json::to_value(result.cloned_data()).map_err(|e| e.to_string())?;
|
||||
if before["rng"] != after["rng"]
|
||||
|| before["dice_roll_log"] != after["dice_roll_log"]
|
||||
|| [
|
||||
"incidents_left",
|
||||
"wonders_left",
|
||||
"action_cards_left",
|
||||
"objective_cards_left",
|
||||
]
|
||||
.iter()
|
||||
.any(|key| {
|
||||
after[*key].as_array().map_or(0, Vec::len) < before[*key].as_array().map_or(0, Vec::len)
|
||||
})
|
||||
|| after["map"]["unexplored_blocks"]
|
||||
.as_array()
|
||||
.map_or(0, Vec::len)
|
||||
< before["map"]["unexplored_blocks"]
|
||||
.as_array()
|
||||
.map_or(0, Vec::len)
|
||||
|| result.active_player() != player
|
||||
{
|
||||
return Err(
|
||||
"Wait for the earlier choice: this action reveals information or needs another player"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn project(game: &Game, player: usize, actions: &[Action]) -> Result<Game, String> {
|
||||
if offer(game, player).is_none() {
|
||||
return Err("Planning is no longer available".into());
|
||||
}
|
||||
let mut projected = game.clone();
|
||||
projected.events.clear();
|
||||
projected.action_plan = None;
|
||||
for (index, action) in actions.iter().enumerate() {
|
||||
if matches!(
|
||||
action,
|
||||
Action::Playing(crate::playing_actions::PlayingAction::EndTurn)
|
||||
) {
|
||||
if index + 1 != actions.len() || !projected.events.is_empty() {
|
||||
return Err("End turn must be last, after your choices".into());
|
||||
}
|
||||
break;
|
||||
}
|
||||
projected = safe_step(projected, action.clone(), player)?;
|
||||
}
|
||||
Ok(projected)
|
||||
}
|
||||
|
||||
pub fn save(
|
||||
game: &mut Game,
|
||||
player: usize,
|
||||
key: &str,
|
||||
actions: Vec<Action>,
|
||||
waiting: bool,
|
||||
) -> Result<(), String> {
|
||||
if actions.is_empty()
|
||||
&& game
|
||||
.action_plan
|
||||
.as_ref()
|
||||
.is_some_and(|p| p.player == player && p.key == key && p.error.is_some())
|
||||
{
|
||||
game.action_plan = None;
|
||||
game.early_choice_update = true;
|
||||
return Ok(());
|
||||
}
|
||||
if actions.len() > 100 {
|
||||
return Err("Too many queued actions".into());
|
||||
}
|
||||
if !offer(game, player).is_some_and(|(current, _)| current == key) {
|
||||
return Err("The earlier choice has changed; review your plan".into());
|
||||
}
|
||||
project(game, player, &actions)?;
|
||||
game.early_choice_update = true;
|
||||
game.action_plan = Some(Plan {
|
||||
player,
|
||||
key: key.into(),
|
||||
actions,
|
||||
waiting,
|
||||
error: None,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Called after ordinary resolution. Keep the failed suffix private for review.
|
||||
pub fn resume(mut game: Game) -> Game {
|
||||
let Some(mut plan) = game.action_plan.take() else {
|
||||
return game;
|
||||
};
|
||||
if plan.error.is_some() || !game.events.is_empty() || game.active_player() != plan.player {
|
||||
game.action_plan = Some(plan);
|
||||
return game;
|
||||
}
|
||||
while !plan.actions.is_empty() {
|
||||
let action = plan.actions[0].clone();
|
||||
if !matches!(
|
||||
action,
|
||||
Action::Playing(crate::playing_actions::PlayingAction::EndTurn)
|
||||
) {
|
||||
if let Err(error) = safe_step(game.clone(), action.clone(), plan.player) {
|
||||
plan.error = Some(error);
|
||||
game.action_plan = Some(plan);
|
||||
return game;
|
||||
}
|
||||
}
|
||||
match crate::board_history::execute(game.clone(), action, plan.player) {
|
||||
Ok(next) => {
|
||||
game = next;
|
||||
plan.actions.remove(0);
|
||||
}
|
||||
Err(error) => {
|
||||
plan.error = Some(error);
|
||||
game.action_plan = Some(plan);
|
||||
return game;
|
||||
}
|
||||
}
|
||||
}
|
||||
game
|
||||
}
|
||||
|
|
@ -158,7 +158,7 @@ fn title(action: &Action) -> String {
|
|||
}
|
||||
|
||||
pub fn execute(game: Game, action: Action, player: usize) -> Result<Game, String> {
|
||||
if matches!(action, Action::QueueChoice { .. }) {
|
||||
if matches!(action, Action::QueueChoice { .. } | Action::QueueMoves { .. }) {
|
||||
return try_execute_action(game, action, player);
|
||||
}
|
||||
let undo = matches!(action, Action::Undo);
|
||||
|
|
@ -188,7 +188,7 @@ pub fn execute(game: Game, action: Action, player: usize) -> Result<Game, String
|
|||
player,
|
||||
)?;
|
||||
}
|
||||
Ok(game)
|
||||
Ok(crate::action_queue::resume(game))
|
||||
}
|
||||
|
||||
fn auto_keep_government(game: &Game) -> bool {
|
||||
|
|
|
|||
|
|
@ -136,6 +136,7 @@ pub struct Game {
|
|||
pub events: Vec<PersistentEventState>,
|
||||
pub early_choices: Vec<crate::early_choices::SavedChoice>,
|
||||
pub early_choice_update: bool,
|
||||
pub action_plan: Option<crate::action_queue::Plan>,
|
||||
// in turn order starting from starting_player_index and wrapping around
|
||||
pub players: Vec<Player>,
|
||||
pub map: Map,
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
if game.action_plan.as_ref().is_some_and(|p| Some(p.player) != player_index) {game.action_plan=None;}
|
||||
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() {
|
||||
|
|
|
|||
|
|
@ -178,6 +178,12 @@ 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::QueueMoves { key, .. }) = serde_json::from_str(&raw)
|
||||
{
|
||||
return crate::action_queue::offer(&game, player).is_some_and(|(current,_)| current == key)
|
||||
|| game.action_plan.as_ref().is_some_and(|p|p.player==player && p.key==key && p.error.is_some());
|
||||
}
|
||||
if let Some(raw) = move_data.as_string()
|
||||
&& let Ok(crate::action::Action::QueueChoice { key, response }) = serde_json::from_str(&raw)
|
||||
{
|
||||
|
|
@ -358,3 +364,19 @@ pub fn web_query(data: String, player: usize, query: String) -> Result<String, J
|
|||
.map_err(|e| JsValue::from_str(&e))?;
|
||||
serde_json::to_string(&result).map_err(|e| JsValue::from_str(&e.to_string()))
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = "webPlanning")]
|
||||
pub fn web_planning(data: String, player: usize) -> Result<String, JsValue> {
|
||||
with_view_game(data, |game| -> Result<String,String> {
|
||||
let Some((key,label))=crate::action_queue::offer(game,player) else {return Ok("null".into());};
|
||||
let plan=game.action_plan.as_ref().filter(|p|p.player==player && p.key==key);
|
||||
let actions=plan.map(|p|p.actions.clone()).unwrap_or_default();
|
||||
let waiting=plan.is_some_and(|p|p.waiting);
|
||||
let base=crate::action_queue::project(game,player,&[])?;
|
||||
let projected=crate::action_queue::project(game,player,&actions)?;
|
||||
serde_json::to_string(&serde_json::json!({"key":key,"label":label,"other":game.player(game.active_player()).civilization.name,
|
||||
"pendingPlayer":game.active_player(),"actions":actions,"waiting":waiting,
|
||||
"base":from_game(crate::game_api::strip_secret(base,Some(player))),
|
||||
"projected":from_game(crate::game_api::strip_secret(projected,Some(player)))})).map_err(|e|e.to_string())
|
||||
}).map_err(|e|JsValue::from_str(&e))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,6 +48,8 @@ pub struct GameData {
|
|||
early_choices: Vec<crate::early_choices::SavedChoice>,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
early_choice_update: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
action_plan: Option<crate::action_queue::Plan>,
|
||||
players: Vec<PlayerData>,
|
||||
map: MapData,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
|
|
@ -117,6 +119,7 @@ pub struct GameData {
|
|||
#[must_use]
|
||||
pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
|
||||
let mut game = Game {
|
||||
action_plan: data.action_plan,
|
||||
early_choices: data.early_choices,
|
||||
early_choice_update: data.early_choice_update,
|
||||
context,
|
||||
|
|
@ -179,6 +182,7 @@ pub fn data(game: Game) -> GameData {
|
|||
version: game.version,
|
||||
state: game.state,
|
||||
events: game.events,
|
||||
action_plan: game.action_plan,
|
||||
early_choices: game.early_choices,
|
||||
early_choice_update: game.early_choice_update,
|
||||
players: game.players.into_iter().map(player_data).collect(),
|
||||
|
|
@ -218,6 +222,7 @@ pub fn cloned_data(game: &Game) -> GameData {
|
|||
version: game.version,
|
||||
state: game.state.clone(),
|
||||
events: game.events.clone(),
|
||||
action_plan: game.action_plan.clone(),
|
||||
early_choices: game.early_choices.clone(),
|
||||
early_choice_update: game.early_choice_update,
|
||||
players: game.players.iter().map(cloned_player_data).collect(),
|
||||
|
|
|
|||
|
|
@ -186,6 +186,7 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game {
|
|||
.shuffled(&mut rng);
|
||||
let all = &cache.get_abilities().clone();
|
||||
let mut game = Game {
|
||||
action_plan: None,
|
||||
early_choices: vec![],
|
||||
early_choice_update: false,
|
||||
seed: setup.seed.clone(),
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ extern crate core;
|
|||
pub mod ability_initializer;
|
||||
pub mod action;
|
||||
pub mod early_choices;
|
||||
pub mod action_queue;
|
||||
pub mod action_card;
|
||||
mod action_cost;
|
||||
pub mod advance;
|
||||
|
|
|
|||
|
|
@ -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::QueueChoice { .. } | Action::StartTurn | Action::Response(_) | Action::ChooseCivilization(_) => None,
|
||||
Action::QueueMoves { .. } | Action::QueueChoice { .. } | Action::StartTurn | Action::Response(_) | Action::ChooseCivilization(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -171,6 +171,7 @@ fn fallback(game: &Game, entry: &ActionLogAction) -> String {
|
|||
},
|
||||
Action::Movement(_) => "Moved units".into(),
|
||||
Action::ChooseCivilization(name) => format!("Chose {name}"),
|
||||
Action::QueueMoves { .. } => "Updated queued actions".into(),
|
||||
Action::QueueChoice { .. } => "Queued a choice".into(),
|
||||
Action::StartTurn => "Started turn".into(),
|
||||
Action::Response(_) => "Completed a decision".into(),
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ use crate::movement::execute_movement_action;
|
|||
use json_patch::{PatchOperation, patch};
|
||||
use serde_json::Value;
|
||||
|
||||
const IGNORE_PATHS: [&str; 4] = ["/log/", "/log_index", "/early_choices", "/early_choice_update"];
|
||||
const IGNORE_PATHS: [&str; 5] = ["/log/", "/log_index", "/early_choices", "/early_choice_update", "/action_plan"];
|
||||
|
||||
pub(crate) fn clean_patch(mut patch: Vec<PatchOperation>) -> Vec<PatchOperation> {
|
||||
patch.retain(|op| {
|
||||
|
|
|
|||
|
|
@ -837,7 +837,7 @@ mod tests {
|
|||
.map
|
||||
.tiles
|
||||
.keys()
|
||||
.find(|pos| pos.distance(site) == 2)
|
||||
.find(|pos| pos.distance(site) == 2 && game.map.within_revealed_distance(**pos, site, 2))
|
||||
.expect("tile 2 spaces away");
|
||||
game.players[seat]
|
||||
.units
|
||||
|
|
|
|||
146
server/tests/action_queue_tests.rs
Normal file
146
server/tests/action_queue_tests.rs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
use server::{
|
||||
action::Action,
|
||||
action_queue, board_history,
|
||||
cache::Cache,
|
||||
game::{Game, GameContext},
|
||||
game_data::GameData,
|
||||
};
|
||||
fn action(value: serde_json::Value) -> Action {
|
||||
serde_json::from_value(value).unwrap()
|
||||
}
|
||||
fn setup() -> Game {
|
||||
let mut data: serde_json::Value =
|
||||
serde_json::from_str(include_str!("test_games/action_cards/tech_trade.json")).unwrap();
|
||||
data["round"] = serde_json::json!(2);
|
||||
data["players"][0]["advances"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(serde_json::json!("Irrigation"));
|
||||
let data: GameData = serde_json::from_value(data).unwrap();
|
||||
let cache = Cache::new(&data.options);
|
||||
let game = Game::from_data(data, cache, GameContext::Play);
|
||||
board_history::execute(
|
||||
game,
|
||||
action(serde_json::json!({"Playing":{"ActionCard":39}})),
|
||||
0,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn tech_trade_plan_is_private_and_replays_after_response() {
|
||||
let mut game = setup();
|
||||
let (key, _) = action_queue::offer(&game, 0).expect("trade recipient still choosing");
|
||||
let original = game.player(0).resources.clone();
|
||||
action_queue::save(
|
||||
&mut game,
|
||||
0,
|
||||
&key,
|
||||
vec![action(serde_json::json!({"Playing":"EndTurn"}))],
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(game.player(0).resources, original);
|
||||
assert_eq!(game.active_player(), 1);
|
||||
assert!(
|
||||
server::game_api::strip_secret(game.clone(), Some(1))
|
||||
.action_plan
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
server::game_api::strip_secret(game.clone(), Some(0))
|
||||
.action_plan
|
||||
.is_some()
|
||||
);
|
||||
// Persist/reload: execution does not require the planning player's browser.
|
||||
let data: GameData =
|
||||
serde_json::from_str(&serde_json::to_string(&game.cloned_data()).unwrap()).unwrap();
|
||||
game = Game::from_data(data, game.cache.clone(), GameContext::Play);
|
||||
game = board_history::execute(
|
||||
game,
|
||||
action(serde_json::json!({"Response":{"SelectAdvance":"Fishing"}})),
|
||||
1,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(game.action_plan.is_none());
|
||||
assert!(game.events.is_empty());
|
||||
assert_eq!(game.current_player_index, 1);
|
||||
}
|
||||
#[test]
|
||||
fn queue_rejects_wrong_player_stale_key_and_nonterminal_end_turn() {
|
||||
let mut game = setup();
|
||||
let (key, _) = action_queue::offer(&game, 0).unwrap();
|
||||
assert!(action_queue::save(&mut game, 1, &key, vec![], false).is_err());
|
||||
assert!(action_queue::save(&mut game, 0, "stale", vec![], false).is_err());
|
||||
let end = action(serde_json::json!({"Playing":"EndTurn"}));
|
||||
assert!(action_queue::save(&mut game, 0, &key, vec![end.clone(), end], false).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn waiting_and_clearing_do_not_advance_the_game() {
|
||||
let mut game = setup();
|
||||
let (key, _) = action_queue::offer(&game, 0).unwrap();
|
||||
action_queue::save(&mut game, 0, &key, vec![], true).unwrap();
|
||||
assert!(game.action_plan.as_ref().unwrap().waiting);
|
||||
assert_eq!(game.active_player(), 1);
|
||||
assert_eq!(game.current_player_index, 0);
|
||||
action_queue::save(&mut game, 0, &key, vec![], false).unwrap();
|
||||
assert!(!game.action_plan.as_ref().unwrap().waiting);
|
||||
}
|
||||
#[test]
|
||||
fn replacement_settler_resolves_before_queued_collection() {
|
||||
let mut value: serde_json::Value = serde_json::from_str(include_str!(
|
||||
"../../web-client/scripts/async-preview-fixture.json"
|
||||
))
|
||||
.unwrap();
|
||||
value["state"] = serde_json::json!("Playing");
|
||||
value["actions_left"] = serde_json::json!(3);
|
||||
value["players"][0]["cities"][0]["activations"] = serde_json::json!(0);
|
||||
value["players"][0]["resources"]["food"] = serde_json::json!(1);
|
||||
let data: GameData = serde_json::from_value(value).unwrap();
|
||||
let cache = Cache::new(&data.options);
|
||||
let mut game = Game::from_data(data, cache, GameContext::Play);
|
||||
let (key, _) = action_queue::offer(&game, 0).unwrap();
|
||||
let collect = action(
|
||||
serde_json::json!({"Playing":{"Collect":{"city_position":"A1","collections":[{"position":"A1","pile":{"food":1},"times":1}],"action_type":"Collect"}}}),
|
||||
);
|
||||
action_queue::save(&mut game, 0, &key, vec![collect], false).unwrap();
|
||||
assert_eq!(game.player(0).resources.food, 1);
|
||||
let units = game.player(1).units.len();
|
||||
game = board_history::execute(
|
||||
game,
|
||||
action(serde_json::json!({"Response":{"SelectPositions":["B2"]}})),
|
||||
1,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(game.player(1).units.len(), units + 1);
|
||||
assert_eq!(game.player(0).resources.food, 2);
|
||||
assert!(game.action_plan.is_none());
|
||||
}
|
||||
#[test]
|
||||
fn battles_and_illegal_moves_cannot_enter_the_plan() {
|
||||
let mut game = setup();
|
||||
let (key, _) = action_queue::offer(&game, 0).unwrap();
|
||||
let enemy = game.players[1]
|
||||
.units
|
||||
.iter()
|
||||
.find(|u| u.unit_type != server::unit::UnitType::Settler)
|
||||
.unwrap()
|
||||
.position
|
||||
.to_string();
|
||||
let attack = action(serde_json::json!({"Movement":{"Move":{"units":[0],"destination":enemy}}}));
|
||||
assert!(action_queue::save(&mut game, 0, &key, vec![attack], false).is_err());
|
||||
assert!(game.action_plan.is_none());
|
||||
assert!(action_queue::save(&mut game, 0, &key, vec![Action::Undo], false).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn event_triggering_research_is_not_queued() {
|
||||
let mut game = setup();
|
||||
game.player_mut(0).incident_tokens = 1;
|
||||
let (key, _) = action_queue::offer(&game, 0).unwrap();
|
||||
let research = action(
|
||||
serde_json::json!({"Playing":{"Advance":{"advance":"Husbandry","payment":{"food":2}}}}),
|
||||
);
|
||||
let projected = action_queue::project(&game, 0, &[]).unwrap();
|
||||
assert!(server::action::try_execute_action(projected, research.clone(), 0).is_ok());
|
||||
assert!(action_queue::save(&mut game, 0, &key, vec![research], false).is_err());
|
||||
assert!(game.action_plan.is_none());
|
||||
}
|
||||
|
|
@ -17,11 +17,13 @@ Open http://127.0.0.1:8643. The preview binds to loopback and saves its disposab
|
|||
|
||||
The local preview does not modify production games, catalog records, or chat rooms.
|
||||
|
||||
## Action-queue prototype
|
||||
## Off-turn action queues
|
||||
|
||||
Open `/async-preview.html` on the local dev server. This isolated replacement-settler scenario uses the real board and controls: Maya plans actions while Rome chooses a city. Switch seats with the preview toolbar. The queue reuses `predictMove`, revalidates actions after Rome responds, and stops on an invalid action. End turn can be queued last; the normal Undo button removes a queued action and its payment responses together.
|
||||
After an opponent captures your city, its owner can plan while you place the replacement settler. Technology Trade also lets its owner plan while the recipient chooses their advance. Normal controls show the projected board; Undo removes the latest queued action with its payment responses. Wait for choice pauses planning. End turn may be queued last.
|
||||
|
||||
This is a local, in-memory prototype, not production concurrency. Reloading resets it. It neither saves a server-side queue nor enables planning around other live-game reactions. The production viewer entry point does not import the prototype.
|
||||
Queues are private, stored in the game, and validated by the server. After the earlier response and any nested choices finish, valid queued actions execute in order even if the planning player is offline. Hidden draws, dice, battles and actions requiring another player cannot be queued. An invalid replay stops and reports an error.
|
||||
|
||||
Open `/async-preview.html` on the local dev server to test both scenarios with the production controller and engine, switching seats in the test toolbar. Reloading this isolated fixture resets it.
|
||||
|
||||
## Implemented controls
|
||||
|
||||
|
|
|
|||
|
|
@ -497,3 +497,22 @@ Move action. Claiming a Great Person no longer skips pirate raids on later playe
|
|||
Epic now ends after 8 ages; setup labels, the age track and final-turn warnings agree.
|
||||
Verified regression tests, reported-game local reproductions, locale validation,
|
||||
Svelte checking, status-phase tests and the production build. No live saves edited.
|
||||
|
||||
### 0.1.168 / engine 0.4.115 — Persisted action queues
|
||||
|
||||
The current turn owner can plan while another player places a replacement settler
|
||||
or makes Technology Trade's final advance choice. The real decision stays pending;
|
||||
normal controls display a projected board, the action-bar Undo edits the queue,
|
||||
and Wait for choice pauses planning. Private queues are stored in the game and
|
||||
revalidated/executed by the server after all earlier reactions finish, including
|
||||
when the planner is offline. End turn is a terminal intent. Battles, random draws,
|
||||
exploration and actions requiring another player stop planning. Failed replay
|
||||
retains the suffix and reports an error, with an explicit discard control.
|
||||
|
||||
The local `/async-preview.html` tests both cases through the production controller
|
||||
and engine. The research chooser no longer repeats its advance-selection hint.
|
||||
Validated 886 web tests, 48 engine unit tests, 21 action-card tests, 6 queue tests,
|
||||
17 locales, Svelte checks, build, and engine protocol/replay/undo checks. The broad
|
||||
Rust suite still has an unrelated cultural-influence log snapshot mismatch, also
|
||||
reproduced on the pre-release main revision. The Raiders UI test now selects a
|
||||
revealed two-space path, matching the existing revealed-distance rule.
|
||||
|
|
|
|||
4
web-client/package-lock.json
generated
4
web-client/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "@boardgamers/clash-web-client",
|
||||
"version": "0.1.167",
|
||||
"version": "0.1.168",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@boardgamers/clash-web-client",
|
||||
"version": "0.1.167",
|
||||
"version": "0.1.168",
|
||||
"dependencies": {
|
||||
"@boardgamers/protocol": "0.9.0",
|
||||
"lucide-svelte": "^0.577.0",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@boardgamers/clash-web-client",
|
||||
"version": "0.1.167",
|
||||
"version": "0.1.168",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
|
|
|||
1
web-client/scripts/tech-queue-fixture.json
Normal file
1
web-client/scripts/tech-queue-fixture.json
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -127,9 +127,12 @@
|
|||
import { sinceLastTurn } from './playback';
|
||||
import { ageCount, ageLabel } from './game-length';
|
||||
import { roundProgress, personalRoundLabel } from './round-progress';
|
||||
let { controller, concurrentPreview }: { controller: Controller; concurrentPreview?: { pending: boolean; waiting: boolean; seat: number; other: string; queued: number; ended: boolean; onUndo: () => void; onWait: () => void } } = $props();
|
||||
let { controller, concurrentPreview }: { controller: Controller; concurrentPreview?: { pending: boolean; waiting: boolean; seat: number; other: string; label?: string; pendingPlayer?: number; queued: number; ended: boolean; onUndo: () => void; onWait: () => void } } = $props();
|
||||
const session = $derived(controller.session);
|
||||
const planningQueue = $derived(!!concurrentPreview?.pending && concurrentPreview.seat === 0);
|
||||
const queueControls = $derived(concurrentPreview ?? ($session.planning ? {
|
||||
...$session.planning,pending:true,seat:0,onUndo:()=>controller.undoQueuedAction(),onWait:()=>controller.waitForChoice(),
|
||||
} : undefined));
|
||||
const planningQueue = $derived(!!queueControls?.pending && queueControls.seat === 0);
|
||||
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')));
|
||||
|
|
@ -266,7 +269,7 @@
|
|||
const activePlayers = $derived(
|
||||
$session.game?.state === 'Finished' || $session.playback
|
||||
? []
|
||||
: concurrentPreview?.pending ? (concurrentPreview.waiting ? [1] : [0, 1]) : ($session.view?.activePlayers ?? ($session.view ? [$session.view.activePlayer] : [])),
|
||||
: queueControls?.pending ? (queueControls.waiting ? [queueControls.pendingPlayer ?? 1] : [$session.seat ?? 0, queueControls.pendingPlayer ?? 1]) : ($session.view?.activePlayers ?? ($session.view ? [$session.view.activePlayer] : [])),
|
||||
);
|
||||
const choosingPlayer = $derived(
|
||||
!!$session.view?.civilizationDraft || !!$session.game?.events?.length || ($session.game?.round ?? 0) > 3,
|
||||
|
|
@ -938,7 +941,7 @@
|
|||
<div class="player-list" aria-label="Civilizations in turn order">
|
||||
{#each playerTurns as { player, order, status }}
|
||||
{@const turnLabel = activePlayers.includes(player.index)
|
||||
? (concurrentPreview?.pending ? player.index === 1 : choosingPlayer)
|
||||
? (queueControls?.pending ? player.index === (queueControls.pendingPlayer ?? 1) : choosingPlayer)
|
||||
? 'Choosing'
|
||||
: player.index === $session.seat
|
||||
? 'Your turn'
|
||||
|
|
@ -1293,7 +1296,7 @@
|
|||
class="turn-light"
|
||||
></span>{/if}
|
||||
<div class="turn-copy">
|
||||
<strong>{concurrentPreview?.pending && concurrentPreview.seat === 0 && !concurrentPreview.waiting ? 'Planning ahead' : actionTitle}</strong>
|
||||
<strong>{queueControls?.pending && queueControls.seat === 0 && !queueControls.waiting ? 'Planning ahead' : actionTitle}</strong>
|
||||
{#if waiting}<span class="waiting-action"
|
||||
>{waiting.action}{waiting.source ? ` · ${printedCardName(waiting.source)}` : ''}</span
|
||||
>{/if}
|
||||
|
|
@ -1464,9 +1467,9 @@
|
|||
aria-hidden="true"
|
||||
/>{/if}</button
|
||||
>
|
||||
<UndoControl canUndo={planningQueue ? !!concurrentPreview?.queued : !!$session.view?.canUndo || !!activeInfluence($session)} canRedo={!planningQueue && !!$session.view?.canRedo}
|
||||
<UndoControl canUndo={planningQueue ? !!queueControls?.queued : !!$session.view?.canUndo || !!activeInfluence($session)} canRedo={!planningQueue && !!$session.view?.canRedo}
|
||||
blocked={!!$session.playback || $session.pending} submit={action => {
|
||||
if (planningQueue && action === 'Undo') concurrentPreview!.onUndo();
|
||||
if (planningQueue && action === 'Undo') queueControls!.onUndo();
|
||||
else controller.submit(action);
|
||||
}}/>
|
||||
<button
|
||||
|
|
@ -1484,12 +1487,15 @@
|
|||
}}><Flag size={19} /><span>End turn</span></button
|
||||
>
|
||||
</nav>
|
||||
{#if concurrentPreview?.pending && !concurrentPreview.waiting && concurrentPreview.seat === 0}
|
||||
{#if queueControls?.pending && !queueControls.waiting && queueControls.seat === 0}
|
||||
<div class="concurrent-choice-row">
|
||||
<span>{concurrentPreview.other} · Placing a settler{#if concurrentPreview.queued}<br /><strong>{concurrentPreview.queued} queued{concurrentPreview.ended ? ' · End turn queued' : ''}</strong>{/if}</span>
|
||||
<button onclick={concurrentPreview.onWait}><Hourglass size={14} />Wait for choice</button>
|
||||
<span>{queueControls.other} · {queueControls.label ?? 'Placing a settler'}{#if queueControls.queued}<br /><strong>{queueControls.queued} queued{queueControls.ended ? ' · End turn queued' : ''}</strong>{/if}</span>
|
||||
<button onclick={queueControls.onWait}><Hourglass size={14} />Wait for choice</button>
|
||||
</div>
|
||||
{/if}
|
||||
{#if $session.failedPlan && !$session.playback}
|
||||
<div class="concurrent-choice-row"><span>Queue stopped · {$session.failedPlan.actions.length} remaining</span><button disabled={$session.pending} onclick={()=>controller.discardFailedQueue()}>Discard queue</button></div>
|
||||
{/if}
|
||||
{#if !$session.playback}<ContextualCards {controller} context="after-battle" />{/if}
|
||||
</div>
|
||||
<nav class="table-tools" aria-label="Table controls">
|
||||
|
|
@ -1677,7 +1683,10 @@
|
|||
/>{/if}{#if !variant.free}<Zap size={12} />1{/if}</button
|
||||
>{/each}
|
||||
</div>{/if}
|
||||
{#if !$session.playback}<ContextualCards {controller} context="collect" />{/if}
|
||||
{#if $session.failedPlan && !$session.playback}
|
||||
<div class="concurrent-choice-row"><span>Queue stopped · {$session.failedPlan.actions.length} remaining</span><button disabled={$session.pending} onclick={()=>controller.discardFailedQueue()}>Discard queue</button></div>
|
||||
{/if}
|
||||
{#if !$session.playback}<ContextualCards {controller} context="collect" />{/if}
|
||||
{#if city && !city.reason}<CollectionBonusHints {city} selection={$session.selection} />{/if}
|
||||
{#if city?.ballcourts}<label class="ballcourts-toggle"
|
||||
><input
|
||||
|
|
|
|||
|
|
@ -4,112 +4,50 @@
|
|||
import { Controller } from './controller';
|
||||
import { loadTutorialEngine } from './bridge';
|
||||
import { mountLocalization } from './localization';
|
||||
import fixture from '../scripts/async-preview-fixture.json';
|
||||
import settlerFixture from '../scripts/async-preview-fixture.json';
|
||||
import tradeFixture from '../scripts/tech-queue-fixture.json';
|
||||
import './style.css';
|
||||
import { ActionQueue } from './action-queue';
|
||||
let seat = $state(0);
|
||||
let pending = $state(true);
|
||||
let waiting = $state(false);
|
||||
let error = $state('');
|
||||
let ready = $state(false);
|
||||
let scenario=$state<'settler'|'trade'>('trade');
|
||||
let seat=$state(0), ready=$state(false), error=$state('');
|
||||
let engine: Awaited<ReturnType<typeof loadTutorialEngine>>;
|
||||
let game: any;
|
||||
let queue: ActionQueue;
|
||||
let queued = $state(0);
|
||||
let ended = $state(false);
|
||||
let remaining = $state<unknown[]>([]);
|
||||
function describeAction(action: any): string {
|
||||
if(action?.Playing === 'EndTurn') return 'End turn';
|
||||
const playing=action?.Playing;
|
||||
if(playing?.Collect) return `Collect in ${playing.Collect.city_position}`;
|
||||
if(playing?.Advance) return `Research ${playing.Advance.advance}`;
|
||||
if(action?.Response) return 'Confirm action choice or payment';
|
||||
const key=Object.keys(playing ?? action ?? {})[0] ?? 'Action';
|
||||
return key.replace(/([a-z])([A-Z])/g,'$1 $2');
|
||||
let game:any;
|
||||
let controller=$state<Controller>();
|
||||
let names=$derived((scenario==='settler'?settlerFixture:tradeFixture).players.slice(0,2).map(p=>p.civilization));
|
||||
async function refresh(){controller!.setPlayer(seat);await controller!.load(engine.stripSecret(JSON.stringify(game),seat));}
|
||||
async function move(raw:string){
|
||||
try{game=JSON.parse(engine.tryMove(JSON.stringify(game),raw,seat));error='';await refresh();}
|
||||
catch(e){error=String(e);controller!.moveResult({ok:false,error});}
|
||||
}
|
||||
function syncQueue() {queued=queue.count;ended=queue.ended;}
|
||||
async function undoQueued() {queue.undo();syncQueue();await refresh();}
|
||||
|
||||
let controller = $state<Controller>();
|
||||
const names = fixture.players.slice(0,2).map(p => p.civilization);
|
||||
function snapshot() {
|
||||
if (pending && seat === 0 && !waiting) return JSON.parse(queue.projected);
|
||||
return pending ? {...game, events: structuredClone(fixture.events)} : game;
|
||||
async function restart(next=scenario){
|
||||
scenario=next;game=structuredClone(next==='settler'?settlerFixture:tradeFixture);
|
||||
game.state='Playing';game.actions_left=3;game.board_history??={id:'async-queue-preview',frames:[]};
|
||||
for(const c of game.players[0].cities){c.activations=0;c.mood_state='Happy';}
|
||||
game.players[0].resources.food=1;seat=0;error='';await refresh();ready=true;
|
||||
}
|
||||
async function refresh() {
|
||||
controller!.setPlayer(seat);
|
||||
await controller!.load(engine.stripSecret(JSON.stringify(snapshot()),seat));
|
||||
}
|
||||
async function move(raw: string) {
|
||||
try {
|
||||
error='';
|
||||
if(pending && seat === 0) {
|
||||
if(waiting) throw Error('Waiting for the replacement settler.');
|
||||
const action=JSON.parse(raw);
|
||||
if(action==='Undo') {queue.undo();syncQueue();await refresh();return;}
|
||||
const result=queue.append(action);
|
||||
if(!result.ok) throw Error(result.reason);
|
||||
syncQueue();
|
||||
// End turn has no speculative state change to acknowledge.
|
||||
if(ended) controller!.moveResult({ok:false,error:''});
|
||||
await refresh();
|
||||
controller!.patch({error:''});
|
||||
return;
|
||||
}
|
||||
const result = JSON.parse(engine.tryMove(JSON.stringify(snapshot()),raw,seat));
|
||||
if(pending && seat === 1) {
|
||||
// The fixture's reaction resolves against the untouched authoritative board.
|
||||
game=result;
|
||||
pending=false; waiting=false;
|
||||
const replay=queue.replay(JSON.stringify(game));
|
||||
game=JSON.parse(replay.raw);
|
||||
remaining=replay.remaining;
|
||||
if(replay.error) error=`Queue stopped after ${replay.applied} actions. ${replay.error}`;
|
||||
queued=0;ended=false;
|
||||
} else game=result;
|
||||
await refresh();
|
||||
} catch(e) { error=String(e); controller!.moveResult({ok:false,error}); }
|
||||
}
|
||||
async function restart() {
|
||||
game=structuredClone(fixture);
|
||||
game.events=[]; game.state='Playing'; game.actions_left=3;
|
||||
for(const city of game.players[0].cities) {city.activations=0;city.mood_state='Happy';}
|
||||
game.players[0].resources.food=2;
|
||||
game.board_history={id:'async-queue-preview',frames:[]};
|
||||
queue=new ActionQueue(engine,0,JSON.stringify(game));
|
||||
syncQueue();remaining=[];
|
||||
pending=true; waiting=false; error=''; seat=0;
|
||||
await refresh();
|
||||
ready=true;
|
||||
}
|
||||
async function switchSeat(value:number) {seat=value;await refresh();controller!.patch({mode:'overview',error:''});}
|
||||
async function switchSeat(next:number){seat=next;await refresh();controller!.patch({mode:'overview',error:''});}
|
||||
onMount(()=>{
|
||||
const localization=mountLocalization(document.body);
|
||||
controller=new Controller({
|
||||
move(raw){void move(raw);return true;},
|
||||
fetchState(){void refresh();return true;},
|
||||
controller=new Controller({move(raw){void move(raw);return true;},fetchState(){void refresh();return true;},
|
||||
updatePreference(name,value){controller!.setPreferences({mapView:'3d',[name]:value});return true;},
|
||||
updateSetting(){return true;},openPlayer(){return true;},hoverPlayer(){return true;},leavePlayer(){return true;},openBoardgame(){return true;},fetchLog(){return true;},addLog(){return true;},replaceLog(){return true;},setReplayInfo(){return true;},
|
||||
},new URL('/',location.href),{predict:false});
|
||||
controller.setPreferences({mapView:'3d',locale:'en',sound:false});
|
||||
void (async()=>{await localization.ready;engine=await loadTutorialEngine();await restart();})().catch(e=>error=String(e));
|
||||
return ()=>{controller?.destroy();localization.destroy();};
|
||||
void(async()=>{await localization.ready;engine=await loadTutorialEngine();await restart();})().catch(e=>error=String(e));
|
||||
return()=>{controller?.destroy();localization.destroy();};
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="prototype-tools">
|
||||
<span>Local prototype · Replacement settler</span>
|
||||
<div><button class:chosen={seat===0} onclick={()=>switchSeat(0)}>Play as {names[0]}</button><button class:chosen={seat===1} onclick={()=>switchSeat(1)}>Play as {names[1]}</button><button onclick={restart}>Restart</button></div>
|
||||
</div>
|
||||
{#if error}<div class="prototype-error">{error}<button onclick={()=>error=''} aria-label="Dismiss error">×</button></div>{/if}
|
||||
{#if remaining.length}<aside class="queue-review"><strong>{remaining.length} queued actions need review</strong>{#each remaining as action}<p>{describeAction(action)}</p>{/each}<button onclick={()=>remaining=[]}>Discard remaining queue</button></aside>{/if}
|
||||
<div class="real-game">
|
||||
{#if controller && ready}<App {controller} concurrentPreview={{pending,waiting,seat,other:names[1],queued,ended,onUndo:undoQueued,onWait:async()=>{waiting=true;await refresh();}}}/>{:else}<p>Loading the game…</p>{/if}
|
||||
<span>Local test · Live queue implementation</span>
|
||||
<div><button class:chosen={scenario==='settler'} onclick={()=>restart('settler')}>Replacement settler</button><button class:chosen={scenario==='trade'} onclick={()=>restart('trade')}>Technology Trade</button></div>
|
||||
<div><button class:chosen={seat===0} onclick={()=>switchSeat(0)}>Play as {names[0]}</button><button class:chosen={seat===1} onclick={()=>switchSeat(1)}>Play as {names[1]}</button><button onclick={()=>restart()}>Restart</button></div>
|
||||
</div>
|
||||
{#if error}<div class="prototype-error">{error}<button onclick={()=>error=''}>×</button></div>{/if}
|
||||
<div class="real-game">{#if controller && ready}<App {controller}/>{:else}<p>Loading the game…</p>{/if}</div>
|
||||
<style>
|
||||
:global(html),:global(body),:global(#app){margin:0;width:100%;height:100%;overflow:hidden;}
|
||||
.prototype-tools{height:46px;box-sizing:border-box;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:6px 12px;background:#1c303b;color:#e5edf0;font:12px system-ui;}
|
||||
.prototype-tools div{display:flex;gap:5px;}.prototype-tools button{border:1px solid #708a92;border-radius:4px;padding:6px 10px;background:transparent;color:inherit;cursor:pointer;}.prototype-tools button.chosen{background:#306b75;border-color:#b3d4db;}
|
||||
.queue-review{position:fixed;z-index:10001;left:12px;bottom:60px;max-height:40vh;overflow:auto;background:#f5f8f9;color:#263c48;padding:16px;border-radius:6px;}
|
||||
.real-game :global(.game-shell){height:100%;min-height:0;}
|
||||
.real-game{position:relative;height:calc(100% - 46px);width:100%;}.prototype-error{position:fixed;z-index:10000;bottom:10px;left:10px;background:#642e29;color:white;padding:12px;}
|
||||
@media(max-width:600px){.prototype-tools{height:70px;flex-wrap:wrap;}.real-game{height:calc(100% - 70px);}}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import initWasm, {
|
||||
webView,
|
||||
webPlanning,
|
||||
currentPlayer,
|
||||
webCollectPreview,
|
||||
webRecruitPreview,
|
||||
webQuery,
|
||||
|
|
@ -17,7 +19,7 @@ async function initialize(): Promise<Bridge> {
|
|||
if (!response.ok) throw new Error(`Could not load the game engine (HTTP ${response.status}).`);
|
||||
// The full engine exceeds browsers' synchronous WebAssembly compilation limit.
|
||||
await initWasm({ module_or_path: response });
|
||||
return { webView, webCollectPreview, webRecruitPreview, webQuery, tryMove, stripSecret };
|
||||
return { webView, webPlanning, currentPlayer, webCollectPreview, webRecruitPreview, webQuery, tryMove, stripSecret };
|
||||
}
|
||||
|
||||
/** Tutorials run the same initialized engine in an isolated local state. */
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { ActionQueue } from './action-queue';
|
||||
import { liveActionMessages } from './live-actions';
|
||||
import { eventNotices, liveEventNotices } from './event-notices';
|
||||
import { publicActions } from './replay-actions';
|
||||
|
|
@ -117,6 +118,8 @@ export class Controller {
|
|||
private raw = '';
|
||||
/** The latest state received from the host. */
|
||||
private confirmedRaw = '';
|
||||
private planningInfo: {key: string; base: string; projected: string; actions: Move[]; waiting: boolean; other: string; label: string; pendingPlayer: number} | null = null;
|
||||
private planningQueue: ActionQueue | null = null;
|
||||
private confirmedPrint: string | null = null;
|
||||
/**
|
||||
* Moves awaiting the server, oldest first. Only the head has been sent; the
|
||||
|
|
@ -367,6 +370,20 @@ export class Controller {
|
|||
this.cardContinuation = null;
|
||||
}
|
||||
const old = get(this.session);
|
||||
const failedPlan=(JSON.parse(raw) as {action_plan?: {key: string; actions: Move[]; error: string}}).action_plan;
|
||||
const queuedFailure=failedPlan?.error;
|
||||
this.patch({failedPlan:queuedFailure ? failedPlan : undefined});
|
||||
this.planningInfo = old.seat !== undefined && !old.playback && this.engine.webPlanning
|
||||
? JSON.parse(this.engine.webPlanning(raw, old.seat)) : null;
|
||||
this.planningQueue = null;
|
||||
if (this.planningInfo && old.seat !== undefined && this.engine.tryMove && this.engine.stripSecret && this.engine.currentPlayer) {
|
||||
const info=this.planningInfo;
|
||||
const queue=new ActionQueue({tryMove:this.engine.tryMove,stripSecret:this.engine.stripSecret,currentPlayer:this.engine.currentPlayer},old.seat,info.base);
|
||||
for(const action of info.actions) { const added=queue.append(action); if(!added.ok) break; }
|
||||
this.planningQueue=queue;
|
||||
this.patch({planning:{queued:queue.count,ended:queue.ended,waiting:info.waiting,other:info.other,label:info.label,pendingPlayer:info.pendingPlayer}});
|
||||
if(!info.waiting) raw=info.projected;
|
||||
} else this.patch({planning:undefined});
|
||||
const game = JSON.parse(raw) as Game;
|
||||
if (game.board_history) game.board_history = { ...game.board_history, frames: groupPlaybackFrames(game) };
|
||||
const changed = raw !== this.raw;
|
||||
|
|
@ -504,7 +521,7 @@ export class Controller {
|
|||
focus: old.focus ?? city,
|
||||
pending: false,
|
||||
automaticPayment: !!automaticPayment,
|
||||
error: '',
|
||||
error: queuedFailure ? `Queued actions stopped: ${queuedFailure}` : '',
|
||||
selection: [],
|
||||
preview: null,
|
||||
recruits: {},
|
||||
|
|
@ -1849,6 +1866,18 @@ export class Controller {
|
|||
submit(move: Move, quotedPayment?: Pile) {
|
||||
if (move === 'Undo' && this.backInfluence()) return;
|
||||
const s = get(this.session);
|
||||
if(this.planningInfo && this.planningQueue && !s.playback) {
|
||||
if(s.pending) return;
|
||||
if(move==='Undo') {this.undoQueuedAction();return;}
|
||||
if(this.planningInfo.waiting) return;
|
||||
try {
|
||||
const result=this.planningQueue.append(move);
|
||||
if(!result.ok) {this.patch({error:result.reason});return;}
|
||||
this.quotedActionPayment=quotedPayment ?? null;
|
||||
this.sendPlan(false);
|
||||
} catch(error) {this.patch({error:String(error)});}
|
||||
return;
|
||||
}
|
||||
if (
|
||||
s.pending ||
|
||||
s.playback ||
|
||||
|
|
@ -1878,6 +1907,25 @@ export class Controller {
|
|||
// state; the host still validates every move and its state stays authoritative.
|
||||
if (predicted) this.apply(predicted.raw, { predicted: true });
|
||||
}
|
||||
discardFailedQueue() {
|
||||
const s=get(this.session);
|
||||
if(!s.failedPlan || s.pending) return;
|
||||
const move={QueueMoves:{key:s.failedPlan.key,actions:[],waiting:false}};
|
||||
this.patch({pending:true,error:''});this.outbox.push({move,print:null,announced:false});
|
||||
if(this.outbox.length===1) this.sendHead();
|
||||
}
|
||||
waitForChoice() { this.sendPlan(true); }
|
||||
undoQueuedAction() {
|
||||
if(!this.planningQueue || get(this.session).pending) return;
|
||||
this.planningQueue.undo();this.sendPlan(this.planningInfo?.waiting ?? false);
|
||||
}
|
||||
private sendPlan(waiting: boolean) {
|
||||
if(!this.planningInfo || !this.planningQueue || get(this.session).pending) return;
|
||||
const move={QueueMoves:{key:this.planningInfo.key,actions:this.planningQueue.entries.map(e=>e.move),waiting}};
|
||||
this.patch({pending:true,error:''});
|
||||
this.outbox.push({move,print:null,announced:false});
|
||||
if(this.outbox.length===1) this.sendHead();
|
||||
}
|
||||
/** The visible result of `move`, when it does not depend on hidden information. */
|
||||
private predict(move: Move, s: Session): { raw: string; print: string } | null {
|
||||
const engine = this.engine;
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "Ingen indsamling eller handelsruter på dette havfelt.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "Bevæger sig mod den valgte spillers byer. Kan ingen hær flytte, kan en by opstå i stedet.",
|
||||
"End diplomatic relations": "Afslut diplomatiske forbindelser",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Kassér Den store diplomat og afslut aftalen. Koster 1 handling."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Kassér Den store diplomat og afslut aftalen. Koster 1 handling.",
|
||||
"Planning ahead": "Planlæg fremad",
|
||||
"Wait for choice": "Afvent valg",
|
||||
"{p0} queued": "{p0} i kø",
|
||||
"End turn queued": "Turafslutning i kø",
|
||||
"Choosing an advance": "Vælger et fremskridt",
|
||||
"Placing a settler": "Placerer en nybygger",
|
||||
"Discard queue": "Ryd kø",
|
||||
"Queue stopped · {p0} remaining": "Kø stoppet · {p0} tilbage",
|
||||
"{p0} · Choosing an advance": "{p0} · Vælger et fremskridt",
|
||||
"{p0} · Placing a settler": "{p0} · Placerer en nybygger",
|
||||
"{p0} queued · End turn queued": "{p0} i kø · Turafslutning i kø"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "Auf diesem Seefeld sind weder Sammeln noch Handelsrouten möglich.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "Bewegt sich auf die Städte des gewählten Spielers zu. Kann keine Armee ziehen, kann stattdessen eine Stadt entstehen.",
|
||||
"End diplomatic relations": "Diplomatische Beziehungen beenden",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Lege den Großen Diplomaten ab und beende das Abkommen. Kostet 1 Aktion."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Lege den Großen Diplomaten ab und beende das Abkommen. Kostet 1 Aktion.",
|
||||
"Planning ahead": "Vorausplanen",
|
||||
"Wait for choice": "Auswahl abwarten",
|
||||
"{p0} queued": "{p0} vorgemerkt",
|
||||
"End turn queued": "Zugende vorgemerkt",
|
||||
"Choosing an advance": "Wählt einen Fortschritt",
|
||||
"Placing a settler": "Platziert einen Siedler",
|
||||
"Discard queue": "Plan verwerfen",
|
||||
"Queue stopped · {p0} remaining": "Plan angehalten · {p0} übrig",
|
||||
"{p0} · Choosing an advance": "{p0} · Wählt einen Fortschritt",
|
||||
"{p0} · Placing a settler": "{p0} · Platziert einen Siedler",
|
||||
"{p0} queued · End turn queued": "{p0} vorgemerkt · Zugende vorgemerkt"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "Δεν επιτρέπεται η συλλογή πόρων ή η χρήση Εμπορικών Οδών σε αυτή τη θαλάσσια θέση.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "Κινούνται προς τις πόλεις του επιλεγμένου παίκτη. Αν κανένας στρατός δεν μπορεί να κινηθεί, μπορεί να εμφανιστεί μια πόλη.",
|
||||
"End diplomatic relations": "Τερματισμός διπλωματικών σχέσεων",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Απόρριψε τον Μεγάλο Διπλωμάτη και τερμάτισε τη συμφωνία. Κόστος: 1 ενέργεια."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Απόρριψε τον Μεγάλο Διπλωμάτη και τερμάτισε τη συμφωνία. Κόστος: 1 ενέργεια.",
|
||||
"Planning ahead": "Προγραμματισμός",
|
||||
"Wait for choice": "Αναμονή επιλογής",
|
||||
"{p0} queued": "{p0} στην ουρά",
|
||||
"End turn queued": "Τέλος γύρου στην ουρά",
|
||||
"Choosing an advance": "Επιλέγει πρόοδο",
|
||||
"Placing a settler": "Τοποθετεί άποικο",
|
||||
"Discard queue": "Εκκαθάριση ουράς",
|
||||
"Queue stopped · {p0} remaining": "Η ουρά σταμάτησε · απομένουν {p0}",
|
||||
"{p0} · Choosing an advance": "{p0} · Επιλέγει πρόοδο",
|
||||
"{p0} · Placing a settler": "{p0} · Τοποθετεί άποικο",
|
||||
"{p0} queued · End turn queued": "{p0} στην ουρά · Τέλος γύρου στην ουρά"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "No collection or Trade Routes on this sea tile.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "Moves toward the selected player's cities. If no army can move, a city may spawn instead.",
|
||||
"End diplomatic relations": "End diplomatic relations",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Discard Great Diplomat and end its agreement. Costs 1 action."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Discard Great Diplomat and end its agreement. Costs 1 action.",
|
||||
"Planning ahead": "Planning ahead",
|
||||
"Wait for choice": "Wait for choice",
|
||||
"{p0} queued": "{p0} queued",
|
||||
"End turn queued": "End turn queued",
|
||||
"Choosing an advance": "Choosing an advance",
|
||||
"Placing a settler": "Placing a settler",
|
||||
"Discard queue": "Discard queue",
|
||||
"Queue stopped · {p0} remaining": "Queue stopped · {p0} remaining",
|
||||
"{p0} · Choosing an advance": "{p0} · Choosing an advance",
|
||||
"{p0} · Placing a settler": "{p0} · Placing a settler",
|
||||
"{p0} queued · End turn queued": "{p0} queued · End turn queued"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "در این خانهٔ دریایی نمیتوان منابع جمعآوری کرد یا از مسیرهای تجاری استفاده کرد.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "بهسوی شهرهای بازیکن انتخابشده حرکت میکنند. اگر هیچ ارتشی نتواند حرکت کند، ممکن است بهجای آن شهری ظاهر شود.",
|
||||
"End diplomatic relations": "پایان روابط دیپلماتیک",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "دیپلمات بزرگ را دور بیندازید و توافق را پایان دهید. هزینه: ۱ اقدام."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "دیپلمات بزرگ را دور بیندازید و توافق را پایان دهید. هزینه: ۱ اقدام.",
|
||||
"Planning ahead": "برنامهریزی پیشاپیش",
|
||||
"Wait for choice": "انتظار برای انتخاب",
|
||||
"{p0} queued": "{p0} در صف",
|
||||
"End turn queued": "پایان نوبت در صف",
|
||||
"Choosing an advance": "در حال انتخاب پیشرفت",
|
||||
"Placing a settler": "در حال قرار دادن مهاجر",
|
||||
"Discard queue": "پاک کردن صف",
|
||||
"Queue stopped · {p0} remaining": "صف متوقف شد · {p0} باقیمانده",
|
||||
"{p0} · Choosing an advance": "{p0} · در حال انتخاب پیشرفت",
|
||||
"{p0} · Placing a settler": "{p0} · در حال قرار دادن مهاجر",
|
||||
"{p0} queued · End turn queued": "{p0} در صف · پایان نوبت در صف"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "Aucune collecte ni route commerciale sur cette case de mer.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "Avance vers les villes du joueur choisi. Si aucune armée ne peut bouger, une ville peut apparaître à la place.",
|
||||
"End diplomatic relations": "Rompre les relations diplomatiques",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Défaussez Grand Diplomate pour mettre fin à son accord. Coûte 1 action."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Défaussez Grand Diplomate pour mettre fin à son accord. Coûte 1 action.",
|
||||
"Planning ahead": "Planification",
|
||||
"Wait for choice": "Attendre le choix",
|
||||
"{p0} queued": "{p0} en attente",
|
||||
"End turn queued": "Fin de tour en attente",
|
||||
"Choosing an advance": "Choisit une avancée",
|
||||
"Placing a settler": "Place un colon",
|
||||
"Discard queue": "Vider la file",
|
||||
"Queue stopped · {p0} remaining": "File interrompue · {p0} restants",
|
||||
"{p0} · Choosing an advance": "{p0} · Choisit une avancée",
|
||||
"{p0} · Placing a settler": "{p0} · Place un colon",
|
||||
"{p0} queued · End turn queued": "{p0} en attente · Fin de tour en attente"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "इस समुद्री खाने पर संसाधन एकत्र नहीं कर सकते और व्यापार मार्गों का उपयोग नहीं कर सकते।",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "चुने हुए खिलाड़ी के शहरों की ओर बढ़ते हैं। यदि कोई सेना नहीं चल सकती, तो उसकी जगह एक शहर आ सकता है।",
|
||||
"End diplomatic relations": "राजनयिक संबंध समाप्त करें",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "महान राजनयिक को त्यागकर समझौता समाप्त करें। लागत: 1 कार्रवाई।"
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "महान राजनयिक को त्यागकर समझौता समाप्त करें। लागत: 1 कार्रवाई।",
|
||||
"Planning ahead": "अग्रिम योजना",
|
||||
"Wait for choice": "चयन की प्रतीक्षा",
|
||||
"{p0} queued": "कतार में {p0}",
|
||||
"End turn queued": "बारी समाप्ति कतार में",
|
||||
"Choosing an advance": "उन्नति चुन रहा है",
|
||||
"Placing a settler": "बसने वाला रख रहा है",
|
||||
"Discard queue": "कतार साफ़ करें",
|
||||
"Queue stopped · {p0} remaining": "कतार रुकी · {p0} शेष",
|
||||
"{p0} · Choosing an advance": "{p0} · उन्नति चुन रहा है",
|
||||
"{p0} · Placing a settler": "{p0} · बसने वाला रख रहा है",
|
||||
"{p0} queued · End turn queued": "कतार में {p0} · बारी समाप्ति कतार में"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "Non puoi raccogliere risorse né usare Rotte Commerciali in questo spazio di mare.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "Si muovono verso le città del giocatore scelto. Se nessun esercito può muoversi, può comparire una città.",
|
||||
"End diplomatic relations": "Termina le relazioni diplomatiche",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Scarta il Grande Diplomatico e termina l’accordo. Costa 1 azione."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Scarta il Grande Diplomatico e termina l’accordo. Costa 1 azione.",
|
||||
"Planning ahead": "Pianificazione",
|
||||
"Wait for choice": "Attendi la scelta",
|
||||
"{p0} queued": "{p0} in coda",
|
||||
"End turn queued": "Fine turno in coda",
|
||||
"Choosing an advance": "Sceglie un progresso",
|
||||
"Placing a settler": "Posiziona un colono",
|
||||
"Discard queue": "Svuota coda",
|
||||
"Queue stopped · {p0} remaining": "Coda interrotta · {p0} rimanenti",
|
||||
"{p0} · Choosing an advance": "{p0} · Sceglie un progresso",
|
||||
"{p0} · Placing a settler": "{p0} · Posiziona un colono",
|
||||
"{p0} queued · End turn queued": "{p0} in coda · Fine turno in coda"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "이 바다 칸에서는 자원을 수집하거나 교역로를 이용할 수 없습니다.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "선택한 플레이어의 도시를 향해 이동합니다. 이동할 수 있는 군대가 없으면 대신 도시가 생길 수 있습니다.",
|
||||
"End diplomatic relations": "외교 관계 종료",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "위대한 외교관을 버리고 협정을 종료합니다. 행동 1회를 소모합니다."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "위대한 외교관을 버리고 협정을 종료합니다. 행동 1회를 소모합니다.",
|
||||
"Planning ahead": "미리 계획",
|
||||
"Wait for choice": "선택 기다리기",
|
||||
"{p0} queued": "{p0}개 대기 중",
|
||||
"End turn queued": "턴 종료 대기 중",
|
||||
"Choosing an advance": "발전 선택 중",
|
||||
"Placing a settler": "개척자 배치 중",
|
||||
"Discard queue": "대기열 비우기",
|
||||
"Queue stopped · {p0} remaining": "대기열 중단 · {p0}개 남음",
|
||||
"{p0} · Choosing an advance": "{p0} · 발전 선택 중",
|
||||
"{p0} · Placing a settler": "{p0} · 개척자 배치 중",
|
||||
"{p0} queued · End turn queued": "{p0}개 대기 중 · 턴 종료 대기 중"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "Op dit zeeveld kun je geen grondstoffen verzamelen of handelsroutes gebruiken.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "Bewegen naar de steden van de gekozen speler. Kan geen leger bewegen, dan kan er in plaats daarvan een stad verschijnen.",
|
||||
"End diplomatic relations": "Diplomatieke betrekkingen beëindigen",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Leg de Grote Diplomaat af en beëindig de overeenkomst. Kost 1 actie."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Leg de Grote Diplomaat af en beëindig de overeenkomst. Kost 1 actie.",
|
||||
"Planning ahead": "Vooruitplannen",
|
||||
"Wait for choice": "Wacht op keuze",
|
||||
"{p0} queued": "{p0} in wachtrij",
|
||||
"End turn queued": "Beurteinde in wachtrij",
|
||||
"Choosing an advance": "Kiest een ontwikkeling",
|
||||
"Placing a settler": "Plaatst een kolonist",
|
||||
"Discard queue": "Wachtrij wissen",
|
||||
"Queue stopped · {p0} remaining": "Wachtrij gestopt · {p0} resterend",
|
||||
"{p0} · Choosing an advance": "{p0} · Kiest een ontwikkeling",
|
||||
"{p0} · Placing a settler": "{p0} · Plaatst een kolonist",
|
||||
"{p0} queued · End turn queued": "{p0} in wachtrij · Beurteinde in wachtrij"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "Na tym polu morskim nie można zbierać zasobów ani korzystać ze szlaków handlowych.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "Ruch w stronę miast wybranego gracza. Jeśli żadna armia nie może się ruszyć, zamiast tego może powstać miasto.",
|
||||
"End diplomatic relations": "Zakończ stosunki dyplomatyczne",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Odrzuć Wielkiego Dyplomatę i zakończ porozumienie. Koszt: 1 akcja."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Odrzuć Wielkiego Dyplomatę i zakończ porozumienie. Koszt: 1 akcja.",
|
||||
"Planning ahead": "Planowanie",
|
||||
"Wait for choice": "Czekaj na wybór",
|
||||
"{p0} queued": "{p0} w kolejce",
|
||||
"End turn queued": "Koniec tury w kolejce",
|
||||
"Choosing an advance": "Wybiera postęp",
|
||||
"Placing a settler": "Umieszcza osadnika",
|
||||
"Discard queue": "Wyczyść kolejkę",
|
||||
"Queue stopped · {p0} remaining": "Kolejka zatrzymana · pozostało {p0}",
|
||||
"{p0} · Choosing an advance": "{p0} · Wybiera postęp",
|
||||
"{p0} · Placing a settler": "{p0} · Umieszcza osadnika",
|
||||
"{p0} queued · End turn queued": "{p0} w kolejce · Koniec tury w kolejce"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "Não é possível coletar recursos nem usar Rotas Comerciais neste espaço de mar.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "Move em direção às cidades do jogador selecionado. Se nenhum exército puder mover, uma cidade poderá surgir.",
|
||||
"End diplomatic relations": "Encerrar relações diplomáticas",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Descarte o Grande Diplomata e encerre o acordo. Custa 1 ação."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Descarte o Grande Diplomata e encerre o acordo. Custa 1 ação.",
|
||||
"Planning ahead": "Planejamento",
|
||||
"Wait for choice": "Aguardar escolha",
|
||||
"{p0} queued": "{p0} na fila",
|
||||
"End turn queued": "Fim do turno na fila",
|
||||
"Choosing an advance": "Escolhendo um avanço",
|
||||
"Placing a settler": "Posicionando um colono",
|
||||
"Discard queue": "Limpar fila",
|
||||
"Queue stopped · {p0} remaining": "Fila interrompida · {p0} restantes",
|
||||
"{p0} · Choosing an advance": "{p0} · Escolhendo um avanço",
|
||||
"{p0} · Placing a settler": "{p0} · Posicionando um colono",
|
||||
"{p0} queued · End turn queued": "{p0} na fila · Fim do turno na fila"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "Nu poți colecta resurse sau folosi Rute Comerciale pe acest spațiu de mare.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "Se deplasează spre orașele jucătorului selectat. Dacă nicio armată nu se poate mișca, poate apărea un oraș.",
|
||||
"End diplomatic relations": "Încheie relațiile diplomatice",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Decartează Marele Diplomat și încheie acordul. Costă 1 acțiune."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Decartează Marele Diplomat și încheie acordul. Costă 1 acțiune.",
|
||||
"Planning ahead": "Planificare",
|
||||
"Wait for choice": "Așteaptă alegerea",
|
||||
"{p0} queued": "{p0} în așteptare",
|
||||
"End turn queued": "Sfârșit de tură în așteptare",
|
||||
"Choosing an advance": "Alege un progres",
|
||||
"Placing a settler": "Plasează un colonist",
|
||||
"Discard queue": "Golește coada",
|
||||
"Queue stopped · {p0} remaining": "Coadă oprită · {p0} rămase",
|
||||
"{p0} · Choosing an advance": "{p0} · Alege un progres",
|
||||
"{p0} · Placing a settler": "{p0} · Plasează un colonist",
|
||||
"{p0} queued · End turn queued": "{p0} în așteptare · Sfârșit de tură în așteptare"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "На этой морской клетке нельзя собирать ресурсы или использовать торговые пути.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "Движутся к городам выбранного игрока. Если ни одна армия не может двигаться, вместо этого может появиться город.",
|
||||
"End diplomatic relations": "Прекратить дипломатические отношения",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Сбросьте Великого дипломата и прекратите соглашение. Стоимость: 1 действие."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Сбросьте Великого дипломата и прекратите соглашение. Стоимость: 1 действие.",
|
||||
"Planning ahead": "Планирование",
|
||||
"Wait for choice": "Ждать выбора",
|
||||
"{p0} queued": "В очереди: {p0}",
|
||||
"End turn queued": "Конец хода в очереди",
|
||||
"Choosing an advance": "Выбирает достижение",
|
||||
"Placing a settler": "Размещает поселенца",
|
||||
"Discard queue": "Очистить очередь",
|
||||
"Queue stopped · {p0} remaining": "Очередь остановлена · осталось {p0}",
|
||||
"{p0} · Choosing an advance": "{p0} · Выбирает достижение",
|
||||
"{p0} · Placing a settler": "{p0} · Размещает поселенца",
|
||||
"{p0} queued · End turn queued": "В очереди: {p0} · Конец хода в очереди"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "Không thể thu thập tài nguyên hoặc sử dụng Tuyến Thương Mại trên ô biển này.",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "Di chuyển về các thành phố của người chơi đã chọn. Nếu không đội quân nào có thể di chuyển, một thành phố có thể xuất hiện thay thế.",
|
||||
"End diplomatic relations": "Chấm dứt quan hệ ngoại giao",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Bỏ Nhà ngoại giao vĩ đại và chấm dứt thỏa thuận. Tốn 1 hành động."
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "Bỏ Nhà ngoại giao vĩ đại và chấm dứt thỏa thuận. Tốn 1 hành động.",
|
||||
"Planning ahead": "Lên kế hoạch trước",
|
||||
"Wait for choice": "Chờ lựa chọn",
|
||||
"{p0} queued": "{p0} đang chờ",
|
||||
"End turn queued": "Kết thúc lượt đang chờ",
|
||||
"Choosing an advance": "Đang chọn tiến bộ",
|
||||
"Placing a settler": "Đang đặt người định cư",
|
||||
"Discard queue": "Xóa hàng đợi",
|
||||
"Queue stopped · {p0} remaining": "Hàng đợi dừng · còn {p0}",
|
||||
"{p0} · Choosing an advance": "{p0} · Đang chọn tiến bộ",
|
||||
"{p0} · Placing a settler": "{p0} · Đang đặt người định cư",
|
||||
"{p0} queued · End turn queued": "{p0} đang chờ · Kết thúc lượt đang chờ"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "此海洋板块不能采集或建立贸易路线。",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "朝所选玩家的城市移动。若没有军队能移动,可能改为生成城市。",
|
||||
"End diplomatic relations": "结束外交关系",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "弃掉伟大外交家并终止协议。花费1次行动。"
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "弃掉伟大外交家并终止协议。花费1次行动。",
|
||||
"Planning ahead": "提前规划",
|
||||
"Wait for choice": "等待选择",
|
||||
"{p0} queued": "{p0} 项待执行",
|
||||
"End turn queued": "结束回合待执行",
|
||||
"Choosing an advance": "正在选择进步",
|
||||
"Placing a settler": "正在放置移民",
|
||||
"Discard queue": "清空队列",
|
||||
"Queue stopped · {p0} remaining": "队列已停止 · 剩余 {p0} 项",
|
||||
"{p0} · Choosing an advance": "{p0} · 正在选择进步",
|
||||
"{p0} · Placing a settler": "{p0} · 正在放置移民",
|
||||
"{p0} queued · End turn queued": "{p0} 项待执行 · 结束回合待执行"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4756,5 +4756,16 @@
|
|||
"No collection or Trade Routes on this sea tile.": "此海洋格無法採集資源或使用貿易路線。",
|
||||
"Moves toward the selected player's cities. If no army can move, a city may spawn instead.": "朝所選玩家的城市移動。若沒有軍隊可以移動,則可能改為生成一座城市。",
|
||||
"End diplomatic relations": "結束外交關係",
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "棄掉偉大外交家並終止協議。花費1次行動。"
|
||||
"Discard Great Diplomat and end its agreement. Costs 1 action.": "棄掉偉大外交家並終止協議。花費1次行動。",
|
||||
"Planning ahead": "提前規劃",
|
||||
"Wait for choice": "等待選擇",
|
||||
"{p0} queued": "{p0} 項待執行",
|
||||
"End turn queued": "結束回合待執行",
|
||||
"Choosing an advance": "正在選擇進步",
|
||||
"Placing a settler": "正在放置移民",
|
||||
"Discard queue": "清空佇列",
|
||||
"Queue stopped · {p0} remaining": "佇列已停止 · 剩餘 {p0} 項",
|
||||
"{p0} · Choosing an advance": "{p0} · 正在選擇進步",
|
||||
"{p0} · Placing a settler": "{p0} · 正在放置移民",
|
||||
"{p0} queued · End turn queued": "{p0} 項待執行 · 結束回合待執行"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -608,3 +608,34 @@ test('canonical state comparisons preserve nested keys, arrays and special prope
|
|||
assert.equal(canonicalJson(source), old);
|
||||
assert.deepEqual(JSON.parse(canonicalJson(source)), source);
|
||||
});
|
||||
|
||||
test('Technology Trade plans use persisted queue commands, restore on reconnect, and support Undo and Wait', async () => {
|
||||
const app=harness();
|
||||
let raw=readFileSync(new URL('../scripts/tech-queue-fixture.json',import.meta.url),'utf8');
|
||||
try {
|
||||
app.controller.setPlayer(0);await app.controller.load(strip(raw));
|
||||
assert.equal(app.session().planning?.label,'Choosing an advance');
|
||||
assert.equal(app.session().view?.canPlay,true);
|
||||
app.controller.submit({Playing:'EndTurn'});
|
||||
const queued=JSON.parse(app.sent.at(-1)!);
|
||||
assert.deepEqual(queued.QueueMoves.actions,[{Playing:'EndTurn'}]);
|
||||
raw=engine.tryMove(raw,app.sent.at(-1)!,0);
|
||||
assert.equal(engine.isLiveUpdate(raw),true);
|
||||
await app.controller.load(strip(raw));
|
||||
assert.equal(app.session().planning?.ended,true);
|
||||
const other=harness();
|
||||
try {
|
||||
other.controller.setPlayer(0);await other.controller.load(strip(raw));
|
||||
assert.equal(other.session().planning?.queued,1,'queue survives a new browser/controller');
|
||||
} finally {other.close();}
|
||||
app.controller.undoQueuedAction();raw=engine.tryMove(raw,app.sent.at(-1)!,0);await app.controller.load(strip(raw));
|
||||
assert.equal(app.session().planning?.queued,0);
|
||||
app.controller.waitForChoice();raw=engine.tryMove(raw,app.sent.at(-1)!,0);await app.controller.load(strip(raw));
|
||||
assert.equal(app.session().planning?.waiting,true);
|
||||
assert.equal(app.session().view?.canPlay,false);
|
||||
raw=engine.tryMove(raw,JSON.stringify({Response:{SelectAdvance:'Fishing'}}),1);
|
||||
await app.controller.load(strip(raw));
|
||||
assert.equal(app.session().planning,undefined);
|
||||
assert.equal(app.session().view?.canPlay,true);
|
||||
} finally {app.close();}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -405,6 +405,8 @@ export interface CollectionPreview {
|
|||
moodWillDecrease: boolean;
|
||||
}
|
||||
export interface Bridge {
|
||||
webPlanning?: (state: string, seat: number) => string;
|
||||
currentPlayer?: (state: string) => number;
|
||||
webQuery: (state: string, seat: number, query: string) => string;
|
||||
webView: (state: string, seat?: number) => string;
|
||||
webCollectPreview: (state: string, seat: number, city: string, choices: string) => string;
|
||||
|
|
@ -541,6 +543,8 @@ export interface EventInfo {
|
|||
targets: ('all' | 'active' | 'selected')[];
|
||||
}
|
||||
export interface Session {
|
||||
failedPlan?: {key: string; actions: Move[]; error: string};
|
||||
planning?: { queued: number; ended: boolean; waiting: boolean; other: string; label: string; pendingPlayer: number };
|
||||
earlyRaze?: { key: string; positions: string[]; selected: string | null };
|
||||
eventNotices?: import('./event-notices').EventNotice[];
|
||||
portPlacement?: { city: string; payment: Pile; choices: { position: string; action: Move }[] };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue