Expose public move summaries through BGS engine log protocol
This commit is contained in:
parent
3a3c027487
commit
73303472f7
10 changed files with 390 additions and 9 deletions
|
|
@ -72,6 +72,38 @@ pub fn log_slice(game: &Game, options: &LogSliceOptions) -> Vec<Action> {
|
|||
log.get(options.start..end).unwrap_or_default().to_vec()
|
||||
}
|
||||
|
||||
/// BGS consumes `text` for its ongoing-game list; replay keeps using saved actions.
|
||||
#[derive(serde::Serialize)]
|
||||
pub struct PlatformLogEntry<'a> {
|
||||
pub action: &'a Action,
|
||||
pub player: usize,
|
||||
pub text: String,
|
||||
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
|
||||
pub kind: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn platform_log_slice<'a>(
|
||||
game: &'a Game,
|
||||
options: &LogSliceOptions,
|
||||
) -> Vec<PlatformLogEntry<'a>> {
|
||||
let log = crate::log::linear_action_entries(game);
|
||||
let end = options
|
||||
.end
|
||||
.map_or(log.len(), |end| end.saturating_add(1).min(log.len()));
|
||||
log.get(options.start..end)
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|entry| PlatformLogEntry {
|
||||
action: &entry.action,
|
||||
player: entry.player,
|
||||
kind: (matches!(entry.action, Action::StartTurn) && entry.items.is_empty())
|
||||
.then_some("phase"),
|
||||
text: crate::move_summary::summary(game, entry),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn set_player_name(mut game: Game, player_index: usize, name: String) -> Game {
|
||||
game.players[player_index].set_name(name);
|
||||
|
|
|
|||
|
|
@ -194,7 +194,7 @@ pub fn log_length(game: String) -> JsValue {
|
|||
pub fn log_slice(game: String, options: JsValue) -> JsValue {
|
||||
let game = get_game(game);
|
||||
let options = serde_wasm_bindgen::from_value(options).expect("options should be serializable");
|
||||
let log = game_api::log_slice(&game, &options);
|
||||
let log = game_api::platform_log_slice(&game, &options);
|
||||
serde_wasm_bindgen::to_value(&log).expect("log should be serializable")
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -45,6 +45,7 @@ pub mod events;
|
|||
mod explore;
|
||||
pub mod game;
|
||||
pub mod game_api;
|
||||
mod move_summary;
|
||||
pub mod game_api_wrapper;
|
||||
pub mod game_data;
|
||||
pub mod game_setup;
|
||||
|
|
|
|||
|
|
@ -413,7 +413,7 @@ pub struct LogSliceOptions {
|
|||
pub end: Option<usize>,
|
||||
}
|
||||
|
||||
pub(crate) fn linear_action_log(game: &Game) -> Vec<Action> {
|
||||
pub(crate) fn linear_action_entries(game: &Game) -> Vec<&ActionLogAction> {
|
||||
let turns: Vec<_> = game
|
||||
.log
|
||||
.iter()
|
||||
|
|
@ -428,14 +428,18 @@ pub(crate) fn linear_action_log(game: &Game) -> Vec<Action> {
|
|||
} else {
|
||||
turn.actions.len()
|
||||
};
|
||||
turn.actions
|
||||
.iter()
|
||||
.take(limit)
|
||||
.map(|item| item.action.clone())
|
||||
turn.actions.iter().take(limit)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn linear_action_log(game: &Game) -> Vec<Action> {
|
||||
linear_action_entries(game)
|
||||
.into_iter()
|
||||
.map(|item| item.action.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn add_log_action(game: &mut Game, item: Action) {
|
||||
let active_events = game.events.len();
|
||||
let player = game.active_player();
|
||||
|
|
|
|||
174
server/src/move_summary.rs
Normal file
174
server/src/move_summary.rs
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
//! Short public outcomes for the platform's last-move chip, independent of viewer state.
|
||||
use crate::action::Action;
|
||||
use crate::card::HandCardLocation;
|
||||
use crate::game::Game;
|
||||
use crate::log::{ActionLogAction, ActionLogBalance, ActionLogEntry};
|
||||
use crate::playing_actions::PlayingAction;
|
||||
use crate::structure::Structure;
|
||||
|
||||
pub(crate) fn summary(game: &Game, entry: &ActionLogAction) -> String {
|
||||
let mut details = Vec::new();
|
||||
for item in &entry.items {
|
||||
let text = match &item.entry {
|
||||
ActionLogEntry::Move(m) => Some(format!(
|
||||
"Moved {} from {} to {}",
|
||||
m.units.to_string(Some(game)),
|
||||
m.start,
|
||||
m.destination
|
||||
)),
|
||||
ActionLogEntry::Advance(a) => Some(format!(
|
||||
"{} {}",
|
||||
if item.entry.balance() == Some(&ActionLogBalance::Gain) {
|
||||
"Researched"
|
||||
} else {
|
||||
"Lost"
|
||||
},
|
||||
a.advance.name(game)
|
||||
)),
|
||||
ActionLogEntry::Structure(s) => {
|
||||
let name = match &s.structure {
|
||||
Structure::CityCenter => "city".to_owned(),
|
||||
Structure::Building(b) => b.name().to_owned(),
|
||||
Structure::Wonder(w) => w.name(),
|
||||
};
|
||||
Some(format!(
|
||||
"{} {name} at {}",
|
||||
if s.balance == ActionLogBalance::Gain {
|
||||
match (&entry.action, &s.structure) {
|
||||
(
|
||||
Action::Playing(PlayingAction::FoundCity { .. }),
|
||||
Structure::CityCenter,
|
||||
) => "Founded",
|
||||
(
|
||||
Action::Playing(
|
||||
PlayingAction::Construct(_) | PlayingAction::WonderCard(_),
|
||||
),
|
||||
_,
|
||||
) => "Built",
|
||||
_ => "Gained",
|
||||
}
|
||||
} else {
|
||||
"Lost"
|
||||
},
|
||||
s.position
|
||||
))
|
||||
}
|
||||
ActionLogEntry::Units {
|
||||
balance: ActionLogBalance::Loss | ActionLogBalance::Pay,
|
||||
..
|
||||
} if matches!(
|
||||
entry.action,
|
||||
Action::Playing(PlayingAction::FoundCity { .. })
|
||||
) =>
|
||||
{
|
||||
None
|
||||
}
|
||||
ActionLogEntry::Units {
|
||||
units,
|
||||
balance,
|
||||
position,
|
||||
} => Some(format!(
|
||||
"{} {}{}",
|
||||
if *balance == ActionLogBalance::Gain {
|
||||
"Gained"
|
||||
} else {
|
||||
"Lost"
|
||||
},
|
||||
units.to_string(Some(game)),
|
||||
position.map_or(String::new(), |p| format!(" at {p}"))
|
||||
)),
|
||||
ActionLogEntry::Resources { resources, balance } if !resources.is_empty() => {
|
||||
Some(format!(
|
||||
"{} {resources}",
|
||||
match balance {
|
||||
ActionLogBalance::Gain => "Gained",
|
||||
ActionLogBalance::Pay => "Paid",
|
||||
ActionLogBalance::Loss => "Lost",
|
||||
}
|
||||
))
|
||||
}
|
||||
ActionLogEntry::MoodChange { city, mood } => Some(format!(
|
||||
"{city}: {}",
|
||||
match mood {
|
||||
crate::city::MoodState::Happy => "happy",
|
||||
crate::city::MoodState::Neutral => "neutral",
|
||||
crate::city::MoodState::Angry => "angry",
|
||||
}
|
||||
)),
|
||||
// The game-list summary is public even when the caller requests a private slice.
|
||||
// Never include identities of drawn, peeked, discarded or face-down cards.
|
||||
ActionLogEntry::HandCard { card, to, .. } => match to {
|
||||
HandCardLocation::Hand(_) | HandCardLocation::RevealedHand(_) => {
|
||||
Some(format!("Drew {}", card.card_type()))
|
||||
}
|
||||
HandCardLocation::CompleteObjective(name) => {
|
||||
Some(format!("Completed objective {name}"))
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
ActionLogEntry::Explore { .. } => Some("Explored a region".into()),
|
||||
ActionLogEntry::InfluenceCultureAttempt(i) => Some(format!(
|
||||
"Cultural influence from {} to {}",
|
||||
i.starting_city_position, i.position
|
||||
)),
|
||||
ActionLogEntry::CombatRoll(r) => Some(format!(
|
||||
"Rolled {} combat value, {} hits",
|
||||
r.combat_value, r.hits
|
||||
)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(text) = text {
|
||||
let text = if item.player == entry.player {
|
||||
text
|
||||
} else {
|
||||
format!(
|
||||
"{}: {text}",
|
||||
game.players
|
||||
.get(item.player)
|
||||
.map_or("Player", |p| p.civilization.name.as_str())
|
||||
)
|
||||
};
|
||||
if !details.contains(&text) {
|
||||
details.push(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
let outcome = if details.is_empty() {
|
||||
fallback(game, entry)
|
||||
} else {
|
||||
details.join(" · ")
|
||||
};
|
||||
// Keep the platform chip compact without cutting a Unicode character in half.
|
||||
if outcome.chars().count() > 240 {
|
||||
format!("{}…", outcome.chars().take(239).collect::<String>())
|
||||
} else {
|
||||
outcome
|
||||
}
|
||||
}
|
||||
|
||||
fn fallback(game: &Game, entry: &ActionLogAction) -> String {
|
||||
match &entry.action {
|
||||
Action::Playing(action) => match action {
|
||||
PlayingAction::EndTurn => "Ended turn".into(),
|
||||
PlayingAction::Advance(_) => "Research".into(),
|
||||
PlayingAction::FoundCity { .. } => "Found a city".into(),
|
||||
PlayingAction::Construct(_) => "Construct a building".into(),
|
||||
PlayingAction::Collect(_) => "Collect resources".into(),
|
||||
PlayingAction::Recruit(_) => "Recruit units".into(),
|
||||
PlayingAction::IncreaseHappiness(_) => "Increase happiness".into(),
|
||||
PlayingAction::InfluenceCultureAttempt(_) => "Cultural influence".into(),
|
||||
PlayingAction::ActionCard(_) => "Played an action card".into(),
|
||||
PlayingAction::WonderCard(_) => "Construct a wonder".into(),
|
||||
PlayingAction::Custom(_) => entry
|
||||
.origin
|
||||
.as_ref()
|
||||
.map_or_else(|| "Used an ability".into(), |origin| origin.name(game)),
|
||||
},
|
||||
Action::Movement(_) => "Moved units".into(),
|
||||
Action::ChooseCivilization(name) => format!("Chose {name}"),
|
||||
Action::StartTurn => "Started turn".into(),
|
||||
Action::Response(_) => "Completed a decision".into(),
|
||||
Action::Undo => "Undid a move".into(),
|
||||
Action::Redo => "Redid a move".into(),
|
||||
}
|
||||
}
|
||||
126
server/tests/platform_log_tests.rs
Normal file
126
server/tests/platform_log_tests.rs
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
use server::action::{Action, execute_action};
|
||||
use server::collect::{Collect, PositionCollection};
|
||||
use server::game::Game;
|
||||
use server::game_api::{log_length, log_slice, platform_log_slice};
|
||||
use server::log::{LogSliceOptions, current_turn_log_mut};
|
||||
use server::playing_actions::{PlayingAction, PlayingActionType};
|
||||
use server::position::Position;
|
||||
use server::resource_pile::ResourcePile;
|
||||
mod common;
|
||||
|
||||
fn options(start: usize, end: Option<usize>) -> LogSliceOptions {
|
||||
LogSliceOptions {
|
||||
player: None,
|
||||
start,
|
||||
end,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn platform_delta_has_readable_text_and_preserves_replay_action() {
|
||||
let game = common::JsonTest::new("advances").load_game("collect_free_economy");
|
||||
let before = log_length(&game);
|
||||
let action = Action::Playing(PlayingAction::Collect(Collect::new(
|
||||
Position::from_offset("C2"),
|
||||
vec![PositionCollection::new(
|
||||
Position::from_offset("B1"),
|
||||
ResourcePile::ore(1),
|
||||
)],
|
||||
PlayingActionType::Collect,
|
||||
)));
|
||||
let game = execute_action(game, action.clone(), 0);
|
||||
let entries = platform_log_slice(&game, &options(before, None));
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!(entries[0].action, &action);
|
||||
assert_eq!(entries[0].player, 0);
|
||||
assert!(entries[0].text.contains("1 ore"));
|
||||
assert!(!entries[0].text.starts_with('{'));
|
||||
assert_eq!(log_slice(&game, &options(before, None)), vec![action]);
|
||||
assert_eq!(
|
||||
platform_log_slice(&game, &options(before, Some(before))).len(),
|
||||
1
|
||||
);
|
||||
assert!(platform_log_slice(&game, &options(before + 1, Some(before))).is_empty());
|
||||
let undone = execute_action(game, Action::Undo, 0);
|
||||
assert!(platform_log_slice(&undone, &options(before, None)).is_empty());
|
||||
assert!(platform_log_slice(&undone, &options(usize::MAX, None)).is_empty());
|
||||
}
|
||||
|
||||
fn append(game: &mut Game, entry: serde_json::Value) {
|
||||
let index = game.log_index;
|
||||
let log = current_turn_log_mut(game);
|
||||
log.actions.truncate(index);
|
||||
log.actions.push(serde_json::from_value(entry).unwrap());
|
||||
game.log_index += 1;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_summary_does_not_reveal_drawn_cards_or_private_log_prose() {
|
||||
let mut game = common::JsonTest::new("advances").load_game("collect_free_economy");
|
||||
let start = log_length(&game);
|
||||
append(
|
||||
&mut game,
|
||||
serde_json::json!({"player":0,"action":{"Response":{"Bool":true}},
|
||||
"items":[{"player":0,"origin":{"Ability":"Draw"},"HandCard":{"card":{"ActionCard":1},"from":"DrawPile","to":{"Hand":0}}}],
|
||||
"log":["Private card: Peltasts"]}),
|
||||
);
|
||||
assert_eq!(
|
||||
platform_log_slice(&game, &options(start, None))[0].text,
|
||||
"Drew an action card"
|
||||
);
|
||||
let mut private = options(start, None);
|
||||
private.player = Some(0);
|
||||
assert_eq!(
|
||||
platform_log_slice(&game, &private)[0].text,
|
||||
"Drew an action card"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn latest_response_describes_the_actual_public_outcome() {
|
||||
let mut game = common::JsonTest::new("advances").load_game("collect_free_economy");
|
||||
let start = log_length(&game);
|
||||
append(
|
||||
&mut game,
|
||||
serde_json::json!({"player":0,"action":{"Response":{"SelectAdvance":"SteelWeapons"}},
|
||||
"items":[{"player":0,"origin":{"CivilCard":1},"Advance":{"advance":"SteelWeapons","balance":"Gain"}}]}),
|
||||
);
|
||||
assert_eq!(
|
||||
platform_log_slice(&game, &options(start, None))[0].text,
|
||||
"Researched Steel Weapons"
|
||||
);
|
||||
append(
|
||||
&mut game,
|
||||
serde_json::json!({"player":0,"action":{"Playing":"EndTurn"}}),
|
||||
);
|
||||
assert_eq!(
|
||||
platform_log_slice(&game, &options(start + 1, None))[0].text,
|
||||
"Ended turn"
|
||||
);
|
||||
append(
|
||||
&mut game,
|
||||
serde_json::json!({"player":1,"action":"StartTurn"}),
|
||||
);
|
||||
assert_eq!(
|
||||
platform_log_slice(&game, &options(start + 2, None))[0].kind,
|
||||
Some("phase")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn founding_summary_does_not_describe_spending_the_settler_as_a_casualty() {
|
||||
let mut game = common::JsonTest::new("advances").load_game("collect_free_economy");
|
||||
let start = log_length(&game);
|
||||
append(
|
||||
&mut game,
|
||||
serde_json::json!({"player":0,"action":{"Playing":{"FoundCity":{"settler":1}}},
|
||||
"items":[
|
||||
{"player":0,"origin":{"Ability":"Found City"},"Units":{"units":{"settlers":1},"balance":"Pay","position":"D9"}},
|
||||
{"player":0,"origin":{"Ability":"Found City"},"Structure":{"structure":"CityCenter","balance":"Gain","position":"D9"}}
|
||||
]}),
|
||||
);
|
||||
assert_eq!(
|
||||
platform_log_slice(&game, &options(start, None))[0].text,
|
||||
"Founded city at D9"
|
||||
);
|
||||
}
|
||||
|
|
@ -192,3 +192,7 @@ Separation of Power protects only its owner as defender. Wonders no longer make
|
|||
# Viewer 0.1.67 / engine unchanged (0.4.62)
|
||||
|
||||
Recap captions replace generic choice/payment labels with recorded outcomes: unit placements and losses by player and location, research, gained buildings, payments, happiness changes, and public card-draw effects. Existing saved frames use only their public historical interval, never current hands. Existing action grouping retains follow-up payments without merging different players or combat/event boundaries.
|
||||
|
||||
# Viewer 0.1.68 / engine 0.4.63
|
||||
|
||||
BGS logSlice now returns entries with public readable text and player metadata alongside the original action. Only the requested active-history interval is summarized; log length, inclusive slice bounds, Undo truncation and saved replay actions are unchanged. The ongoing-game list can use the latest summary without a viewer being open. Empty StartTurn bookkeeping is marked as a phase so it cannot displace the preceding real move. Draw summaries expose card types only, never private card names or private log prose. Existing stored list summaries update on the next move.
|
||||
|
|
|
|||
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.67",
|
||||
"version": "0.1.68",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@boardgamers/clash-web-client",
|
||||
"version": "0.1.67",
|
||||
"version": "0.1.68",
|
||||
"dependencies": {
|
||||
"@boardgamers/protocol": "0.9.0",
|
||||
"lucide-svelte": "^0.577.0",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@boardgamers/clash-web-client",
|
||||
"version": "0.1.67",
|
||||
"version": "0.1.68",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
|
|
|||
40
web-client/src/platform-log.test.ts
Normal file
40
web-client/src/platform-log.test.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFileSync } from 'node:fs';
|
||||
const engine = createRequire(import.meta.url)('../.engine/server.js');
|
||||
const npcs = JSON.parse(await engine.init(2, [], {}, 'platform-log', {})).players.slice(2);
|
||||
|
||||
test('BGS receives a plain text field for just the new move, without changing history cursors', () => {
|
||||
const game = JSON.parse(
|
||||
readFileSync(
|
||||
new URL('../../server/tests/test_games/advances/collect_free_economy.json', import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
for (const npc of npcs)
|
||||
if (!game.players.some((p: { civilization: string }) => p.civilization === npc.civilization))
|
||||
game.players.push({ ...npc, id: game.players.length });
|
||||
const before = JSON.stringify(game),
|
||||
start = engine.logLength(before);
|
||||
const action = {
|
||||
Playing: {
|
||||
Collect: {
|
||||
city_position: 'C2',
|
||||
collections: [{ position: 'B1', pile: { ore: 1 }, times: 1 }],
|
||||
action_type: 'Collect',
|
||||
},
|
||||
},
|
||||
};
|
||||
const after = engine.tryMove(before, JSON.stringify(action), 0);
|
||||
const log = engine.logSlice(after, { start });
|
||||
assert.equal(log.length, 1);
|
||||
assert.equal(typeof log[0].text, 'string');
|
||||
assert.match(log[0].text, /Gained 1 ore/);
|
||||
assert.equal(log[0].player, 0);
|
||||
assert.deepEqual(log[0].action, action);
|
||||
assert.equal(engine.logLength(after), start + 1);
|
||||
const undone = engine.tryMove(after, JSON.stringify('Undo'), 0);
|
||||
assert.deepEqual(engine.logSlice(undone, { start }), []);
|
||||
assert.equal(engine.logLength(undone), start);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue