Add city management, settler expansion, and BGS viewer publishing
This commit is contained in:
parent
8df84ba228
commit
e7f257f39b
23 changed files with 1346 additions and 42 deletions
28
.github/workflows/web-viewer.yml
vendored
Normal file
28
.github/workflows/web-viewer.yml
vendored
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
name: Web viewer
|
||||
on:
|
||||
pull_request:
|
||||
paths: ['web-client/**', 'server/**', 'Cargo.*', '.github/workflows/web-viewer.yml']
|
||||
push:
|
||||
branches: [feat/3d-web-viewer]
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: jdx/mise-action@v3
|
||||
with:
|
||||
version: 2025.7.3
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
cache-dependency-path: web-client/package-lock.json
|
||||
- run: rustup target add wasm32-unknown-unknown
|
||||
- run: npm ci
|
||||
working-directory: web-client
|
||||
- run: npm run build:bridge && npm run check && npm test && npm run build
|
||||
working-directory: web-client
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: clash-viewer
|
||||
path: web-client/dist/viewer.js
|
||||
|
|
@ -215,3 +215,18 @@ pub fn try_move(data: String, action: String, player: usize) -> Result<String, J
|
|||
.map(from_game)
|
||||
.map_err(|e| JsValue::from_str(&e))
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = "webRecruitPreview")]
|
||||
pub fn web_recruit_preview(
|
||||
data: String,
|
||||
player: usize,
|
||||
city: String,
|
||||
units: String,
|
||||
) -> Result<String, JsValue> {
|
||||
let units = serde_json::from_str(&units).map_err(|e| JsValue::from_str(&e.to_string()))?;
|
||||
let city = serde_json::from_value(serde_json::Value::String(city))
|
||||
.map_err(|e| JsValue::from_str(&e.to_string()))?;
|
||||
let result = crate::web_view::recruit_preview(&get_game(data), player, city, units)
|
||||
.map_err(|e| JsValue::from_str(&e))?;
|
||||
serde_json::to_string(&result).map_err(|e| JsValue::from_str(&e.to_string()))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -662,7 +662,7 @@ fn save_carried_units(game: &mut Game, player: usize, pos: Position) {
|
|||
u.carrier_id
|
||||
.is_some_and(|id| game.player(player).try_get_unit(id).is_none())
|
||||
})
|
||||
.map(|u| (u.id))
|
||||
.map(|u| u.id)
|
||||
.collect_vec();
|
||||
|
||||
if survivors.is_empty() {
|
||||
|
|
|
|||
|
|
@ -15,6 +15,8 @@ use crate::player::CostTrigger;
|
|||
use crate::playing_actions::{PlayingAction, PlayingActionType};
|
||||
use crate::position::Position;
|
||||
use serde_json::{Value, json};
|
||||
mod actions;
|
||||
pub use actions::recruit_preview;
|
||||
|
||||
pub fn view(game: &Game, seat: Option<usize>) -> Value {
|
||||
let seat = seat.filter(|i| *i < game.players.len() && game.player(*i).is_human());
|
||||
|
|
@ -27,7 +29,9 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
|
|||
Some(PersistentEventRequest::SelectHandCards(_))
|
||||
)
|
||||
});
|
||||
let supported_phase = playing || objective_phase;
|
||||
let moving = matches!(game.state, GameState::Movement(_)) && game.events.is_empty();
|
||||
let choice = seat.and_then(|seat| choice_decision(game, seat));
|
||||
let supported_phase = playing || objective_phase || moving || choice.is_some();
|
||||
let can_play = seat == Some(active) && playing;
|
||||
let players = game.players.iter().filter(|p| p.is_human()).map(|p| json!({
|
||||
"index": p.index, "name": game.player_name(p.index), "civilization": p.civilization.name,
|
||||
|
|
@ -35,7 +39,7 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
|
|||
"cities": p.cities.iter().map(|c| json!({"position": c.position, "size": c.size(), "capacity": c.mood_modified_size(p), "mood": c.mood_state, "activations": c.activations})).collect::<Vec<_>>()
|
||||
})).collect::<Vec<_>>();
|
||||
let Some(seat) = seat else {
|
||||
return json!({"activePlayer": active, "canPlay": false, "supportedPhase": supported_phase, "players": players, "cities": [], "advances": [], "objectiveCards": [], "objectiveDecision": null, "canUndo": false, "canEndTurn": false});
|
||||
return json!({"activePlayer": active, "canPlay": false, "supportedPhase": supported_phase, "players": players, "cities": [], "advances": [], "objectiveCards": [], "objectiveDecision": null, "cityActions": [], "settlers": [], "stopMovement": null, "canUndo": false, "canEndTurn": false});
|
||||
};
|
||||
let p = game.player(seat);
|
||||
// Hidden cards use ID zero in the player-filtered state; never resolve them.
|
||||
|
|
@ -84,7 +88,38 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
|
|||
"bonus":info.bonus.as_ref().map(|bonus| bonus.resources()),"unlocks":info.unlocked_building.map(|building| building.to_string())})
|
||||
}).collect::<Vec<_>>();
|
||||
advances.sort_by_key(|a| a["name"].as_str().unwrap_or_default().to_string());
|
||||
json!({"activePlayer":active,"canPlay":can_play,"supportedPhase":supported_phase,"players":players,"cities":cities,"advances":advances,"objectiveCards":objective_cards,"objectiveDecision":objective_decision(game, seat),"canUndo":seat == active && game.can_undo(),"canEndTurn":can_play && PlayingActionType::EndTurn.is_available(game, seat).is_ok()})
|
||||
json!({"activePlayer":active,"canPlay":can_play,"supportedPhase":supported_phase,"players":players,"cities":cities,"advances":advances,"objectiveCards":objective_cards,"objectiveDecision":objective_decision(game, seat),
|
||||
"choiceDecision":choice,
|
||||
"cityActions":actions::cities(game, seat, can_play), "settlers":actions::settlers(game, seat, (can_play && PlayingActionType::MoveUnits.is_available(game,seat).is_ok()) || (moving && seat == active)),
|
||||
"stopMovement":if moving && seat == active {Some(Action::Movement(crate::movement::MovementAction::Stop))} else {None},
|
||||
"canUndo":seat == active && game.can_undo(),"canEndTurn":can_play && PlayingActionType::EndTurn.is_available(game, seat).is_ok()})
|
||||
}
|
||||
|
||||
fn choice_decision(game: &Game, seat: usize) -> Option<Value> {
|
||||
use crate::resource::ResourceType;
|
||||
use crate::resource_pile::ResourcePile;
|
||||
let event = game.events.last()?;
|
||||
if event.player.index != seat {
|
||||
return None;
|
||||
}
|
||||
let handler = game.current_event_handler()?;
|
||||
if handler.response.is_some() {
|
||||
return None;
|
||||
}
|
||||
match &handler.request {
|
||||
PersistentEventRequest::ResourceReward(request)
|
||||
if request.reward.payment_options.default.amount() == 1 =>
|
||||
{
|
||||
let choices = ResourceType::all().into_iter().map(|r| ResourcePile::of(r,1))
|
||||
.filter(|pile|request.reward.payment_options.is_valid_payment(pile))
|
||||
.map(|pile|json!({"name":pile.to_string(),"pile":pile,"action":Action::Response(EventResponse::ResourceReward(pile.clone()))})).collect::<Vec<_>>();
|
||||
Some(json!({"name":request.name,"choices":choices}))
|
||||
}
|
||||
PersistentEventRequest::BoolRequest(name) => Some(json!({"name":name,"choices":[
|
||||
{"name":"Yes","action":Action::Response(EventResponse::Bool(true))},
|
||||
{"name":"No","action":Action::Response(EventResponse::Bool(false))}]})),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn objective_decision(game: &Game, seat: usize) -> Option<Value> {
|
||||
|
|
|
|||
106
server/src/web_view/actions.rs
Normal file
106
server/src/web_view/actions.rs
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
use crate::action::Action;
|
||||
use crate::city::MoodState;
|
||||
use crate::city_pieces::BUILDINGS;
|
||||
use crate::construct::{Construct, can_construct, new_building_positions};
|
||||
use crate::game::{Game, GameState};
|
||||
use crate::happiness::{IncreaseHappiness, happiness_base_event_origin, happiness_cost};
|
||||
use crate::map::Terrain;
|
||||
use crate::movement::{MoveUnits, MovementAction, possible_move_routes};
|
||||
use crate::player::CostTrigger;
|
||||
use crate::playing_actions::{PlayingAction, PlayingActionType};
|
||||
use crate::position::Position;
|
||||
use crate::recruit::{Recruit, recruit_cost};
|
||||
use crate::unit::{UnitType, Units};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn action_reason(
|
||||
game: &Game,
|
||||
seat: usize,
|
||||
can_play: bool,
|
||||
kind: PlayingActionType,
|
||||
) -> Option<String> {
|
||||
if !can_play {
|
||||
Some("Wait for your turn or finish the current decision".into())
|
||||
} else {
|
||||
kind.is_available(game, seat).err()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cities(game: &Game, seat: usize, can_play: bool) -> Vec<Value> {
|
||||
let p = game.player(seat);
|
||||
p.cities.iter().map(|city| {
|
||||
let buildings = BUILDINGS.into_iter().map(|building| {
|
||||
let cost = p.building_cost(game, building, CostTrigger::NoModifiers);
|
||||
let payment = cost.cost.first_valid_payment(&p.resources).unwrap_or_else(|| cost.cost.default_payment());
|
||||
let positions = new_building_positions(game, building, city);
|
||||
let reason = action_reason(game, seat, can_play, PlayingActionType::Construct)
|
||||
.or_else(|| can_construct(city, building, p, game, CostTrigger::NoModifiers, &[]).err())
|
||||
.or_else(|| positions.is_empty().then(|| "Needs an adjacent sea tile".to_string()));
|
||||
let choices = if reason.is_none() {positions.into_iter().map(|port| json!({"position":port,
|
||||
"action":Action::Playing(PlayingAction::Construct(Construct::new(city.position, building, payment.clone()).with_port_position(port)))})).collect::<Vec<_>>()} else {vec![]};
|
||||
json!({"name":building.to_string(),"owned":!city.pieces.can_add_building(building),
|
||||
"required":game.cache.get_building_advance(building).name(game),"payment":payment,"reason":reason,"choices":choices,
|
||||
"moodWillDecrease":cost.activate_city && city.is_activated()})
|
||||
}).collect::<Vec<_>>();
|
||||
let recruits = [UnitType::Settler,UnitType::Infantry,UnitType::Cavalry,UnitType::Elephant,UnitType::Ship].into_iter().map(|unit| {
|
||||
let mut units = Units::empty(); units += &unit;
|
||||
let result = recruit_cost(game,p,&units,city.position,&[],CostTrigger::NoModifiers);
|
||||
let reason = action_reason(game,seat,can_play,PlayingActionType::Recruit).or_else(||result.as_ref().err().cloned());
|
||||
let payment = result.map(|c|c.cost.first_valid_payment(&p.resources).unwrap_or_else(||c.cost.default_payment())).unwrap_or_else(|_|unit.cost());
|
||||
json!({"type":unit,"payment":payment,"reason":reason,"available":p.available_units().get_amount(&unit)})
|
||||
}).collect::<Vec<_>>();
|
||||
let max_steps = match city.mood_state {MoodState::Happy=>0, MoodState::Neutral=>1, MoodState::Angry=>2};
|
||||
let happiness = (1..=max_steps).map(|steps| {
|
||||
let kind = PlayingActionType::IncreaseHappiness;
|
||||
let cost = happiness_cost(seat,city.size() as u8 * steps,CostTrigger::NoModifiers,&kind,game,&happiness_base_event_origin());
|
||||
let payment = cost.cost.first_valid_payment(&p.resources);
|
||||
let reason = action_reason(game,seat,can_play,kind.clone()).or_else(||payment.is_none().then(||"Not enough resources".into()));
|
||||
let payment = payment.unwrap_or_else(||cost.cost.default_payment());
|
||||
let action = reason.is_none().then(||Action::Playing(PlayingAction::IncreaseHappiness(IncreaseHappiness::new(vec![(city.position,steps)],payment.clone(),kind))));
|
||||
json!({"steps":steps,"mood":if steps==max_steps {"Happy"} else {"Neutral"},"payment":payment,"reason":reason,"action":action})
|
||||
}).collect::<Vec<_>>();
|
||||
json!({"position":city.position,"buildings":buildings,"recruits":recruits,"happiness":happiness})
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub fn recruit_preview(
|
||||
game: &Game,
|
||||
seat: usize,
|
||||
city: Position,
|
||||
units: Units,
|
||||
) -> Result<Value, String> {
|
||||
if seat >= game.players.len() || seat != game.active_player() || !game.player(seat).is_human() {
|
||||
return Err("Wait for your turn".into());
|
||||
}
|
||||
PlayingActionType::Recruit.is_available(game, seat)?;
|
||||
if units.is_empty() {
|
||||
return Err("Choose at least one unit".into());
|
||||
}
|
||||
let p = game.player(seat);
|
||||
let city_data = p.try_get_city(city).ok_or("Choose one of your cities")?;
|
||||
let cost = recruit_cost(game, p, &units, city, &[], CostTrigger::NoModifiers)?;
|
||||
let payment = cost
|
||||
.cost
|
||||
.first_valid_payment(&p.resources)
|
||||
.ok_or("Not enough resources")?;
|
||||
Ok(
|
||||
json!({"payment":payment,"moodWillDecrease":city_data.is_activated(),
|
||||
"action":Action::Playing(PlayingAction::Recruit(Recruit::new(&units,city,payment.clone())))}),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn settlers(game: &Game, seat: usize, can_move: bool) -> Vec<Value> {
|
||||
let p = game.player(seat);
|
||||
p.units.iter().filter(|u|u.is_settler() && !u.is_transported()).map(|unit| {
|
||||
let mut destinations = if can_move {possible_move_routes(p,game,&[unit.id],unit.position,None).unwrap_or_default().into_iter()
|
||||
.filter(|route|game.map.is_land(route.destination) && game.map.get(route.destination)!=Some(&Terrain::Unexplored) && game.enemy_player(seat,route.destination).is_none())
|
||||
.filter_map(|route|route.cost.first_valid_payment(&p.resources).map(|payment|json!({
|
||||
"position":route.destination,"terrain":game.map.get(route.destination),"payment":payment,
|
||||
"action":Action::Movement(MovementAction::Move(MoveUnits::new(vec![unit.id],route.destination,None,payment.clone())))}))).collect::<Vec<_>>() } else {vec![]};
|
||||
destinations.sort_by_key(|d|d["position"].as_str().unwrap_or_default().to_string());
|
||||
let found_reason = action_reason(game,seat,game.state==GameState::Playing && seat==game.active_player(),PlayingActionType::FoundCity)
|
||||
.or_else(||(!unit.can_found_city(game)).then(||"Move to an empty land tile to found a city".into()));
|
||||
json!({"id":unit.id,"position":unit.position,"destinations":destinations,"foundReason":found_reason,
|
||||
"foundAction":found_reason.is_none().then(||Action::Playing(PlayingAction::FoundCity{settler:unit.id}))})
|
||||
}).collect()
|
||||
}
|
||||
1
web-client/.gitignore
vendored
1
web-client/.gitignore
vendored
|
|
@ -1,2 +1,3 @@
|
|||
.engine/
|
||||
public/engine/
|
||||
.bridge/
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Clash of Cultures — web viewer
|
||||
|
||||
First playable slice of a Svelte/TypeScript interface with a Three.js board. The Rust engine remains the rule authority. The existing Macroquad client is unchanged.
|
||||
First playable slice of a Svelte/TypeScript interface with a Three.js board. The Rust engine remains the rule authority.
|
||||
|
||||
## Run locally
|
||||
|
||||
|
|
@ -25,6 +25,10 @@ No production games, catalog records, or chat rooms are modified. Remaining acti
|
|||
- Collect resources: Rust supplies legal tiles, resource alternatives, capacity, total gain, waste, and an activation warning. Confirming submits the original Rust action format.
|
||||
- Research: a searchable tree with pictograms, short effect summaries, prerequisite branches, costs, bonuses, and unlocked buildings. Rust supplies the graph, full rules, payments, and action payloads; selecting an advance opens its full rule text before confirmation.
|
||||
- End turn and undo, with state and journal reconciliation.
|
||||
- City management: buildings with visible effects and requirements, Port placement, combined recruitment of standard units, and one-city happiness actions. Payments and legal actions come from Rust; repeat activations warn about mood loss.
|
||||
- Settler movement on revealed land without enemies, movement completion, and founding cities. Destination rings and map clicks work alongside accessible destination buttons.
|
||||
- One-resource bonus choices (including Temples) and yes/no decisions. These remain private to the player who must answer.
|
||||
- Buildings appear around city centers; recruited units have separate positions and basic type markers.
|
||||
- BGS registration/lifecycle, player/spectator handling, theme, avatars, and the shared chat controller/panel. Chat sends, failed-send drafts, updates/deletions, mentions, read reports, editing and translation handlers are supplied by the protocol package; the host decides which features are enabled.
|
||||
- Journal entries use action and resource pictograms. Setup is summarized as player, civilization, and original starting tile. Text equivalents are published with `replaceLog` so undo cannot leave stale entries.
|
||||
- Full-width board with floating action controls and dismissible journal/chat panels. The layout stays within the viewport on desktop and mobile; panels scroll internally. City/action controls are keyboard accessible, and the board renders only when changed.
|
||||
|
|
@ -43,18 +47,29 @@ cargo test -p server --lib web_view
|
|||
|
||||
After building, `http://127.0.0.1:8643/?built` loads the production IIFE bundle inside the preview host.
|
||||
|
||||
Upload the contents of `dist/` together, preserving `engine/` alongside `viewer.js`. The viewer resolves its WASM bridge relative to its own script URL. It exports `window.clash3d.launch(selector)` and uses string state/move payloads, matching the existing engine. Configure `topLevelVariable: "clash3d"`, `fullScreen: true`, `chat: true`, and `replayable: false`. No extra runtime scripts or stylesheets are needed. Fonts currently load from Google Fonts; system fonts remain available if blocked.
|
||||
`dist/viewer.js` contains the interface, styles, and Rust WASM bridge in one uploadable file. It exports `window.clash3d.launch(selector)` and uses string state/move payloads, matching the existing engine. Configure `topLevelVariable: "clash3d"`, `fullScreen: true`, `chat: true`, and `replayable: false`. No extra runtime scripts or stylesheets are needed. Fonts currently load from Google Fonts; system fonts remain available if blocked.
|
||||
|
||||
## Publish to BGS
|
||||
|
||||
After building and verifying, use the admin API token from `BGS_ADMIN_TOKEN` or `~/.bgs`:
|
||||
|
||||
```sh
|
||||
npm run publish:bgs -- --version=1 --dry-run
|
||||
npm run publish:bgs -- --version=1
|
||||
```
|
||||
|
||||
The script uploads the viewer, verifies the hosted bytes, then updates only the version's viewer configuration. It preserves the engine and visibility settings, checks for concurrent viewer changes, and saves the previous version document under `.engine/releases/` for rollback. Publishing is separate from pushing Git commits. The GitHub workflow builds and tests the viewer and retains the bundle as an artifact; it does not publish automatically.
|
||||
|
||||
## Next slices
|
||||
|
||||
The new controls do not yet cover movement/exploration, construction, recruitment, action cards, cultural influence, happiness actions, combat, civilization selection, or status/event choices other than objective claims. City buildings beyond the center and unit types beyond settlers still need distinct models. Full replay and analysis controls are not advertised. The interface text is currently English; existing game translations need to be wired into the new presentation layer. Audio and advanced accessibility preferences need a separate pass.
|
||||
The controls do not yet cover army/fleet movement, exploration, unit replacement/leader recruitment, wonders, action cards, cultural influence, combat, civilization selection, or most status/event choices. Free/custom-action variants and multi-city happiness selection are also pending. Models for buildings and units are preliminary. Full replay and analysis controls are not advertised. The interface text is currently English; existing game translations need to be wired into the new presentation layer. Audio and advanced accessibility preferences need a separate pass.
|
||||
|
||||
Before making this the default viewer: complete action/phase coverage, verify against an actual BGS staging game (including reconnects, moderation, translation, and read-state persistence), and test larger multiplayer boards on mobile hardware.
|
||||
Before public release: complete action/phase coverage, verify against an actual BGS staging game (including reconnects, moderation, translation, and read-state persistence), and test larger multiplayer boards on mobile hardware.
|
||||
|
||||
## Architecture
|
||||
|
||||
`server/src/web_view.rs` exposes read-only rule queries; `game_api_wrapper.rs` exports them to WASM. Queries consume the same player-filtered state BGS sends to the viewer. They neither mutate the game nor send moves. The server always validates actual moves.
|
||||
`server/src/web_view.rs` and `web_view/actions.rs` expose read-only rule queries; `game_api_wrapper.rs` exports them to WASM. Queries consume the same player-filtered state BGS sends to the viewer. They neither mutate the game nor send moves. The server always validates actual moves. `src/bridge.ts` initializes the embedded WASM; `.bridge/` and `.engine/` are generated by `build:bridge`.
|
||||
|
||||
`src/controller.ts` coordinates state, choices, and the BGS commands. `src/App.svelte` owns the HTML interface. `src/board.ts` owns and disposes the Three.js scene. `src/viewer.ts` is the production entry. `src/local-host.ts` and `scripts/preview-api.ts` are development-only.
|
||||
|
||||
The protocol dependency is AGPL-3.0-only. The existing engine and classic viewer retain their respective licensing.
|
||||
The protocol dependency is AGPL-3.0-only. The engine retains its existing licensing.
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@
|
|||
"build": "vite build",
|
||||
"check": "svelte-check --tsconfig ./tsconfig.json",
|
||||
"test": "node --experimental-strip-types --test src/*.test.ts",
|
||||
"build:bridge": "bash scripts/build-bridge.sh"
|
||||
"build:bridge": "bash scripts/build-bridge.sh",
|
||||
"publish:bgs": "node scripts/publish.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@boardgamers/protocol": "0.6.1",
|
||||
|
|
|
|||
|
|
@ -2,6 +2,6 @@
|
|||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
cargo build -p server --lib --target wasm32-unknown-unknown --release
|
||||
wasm-bindgen target/wasm32-unknown-unknown/release/server.wasm --target web --out-dir web-client/public/engine
|
||||
wasm-bindgen target/wasm32-unknown-unknown/release/server.wasm --target web --out-dir web-client/.bridge
|
||||
wasm-bindgen target/wasm32-unknown-unknown/release/server.wasm --target nodejs --out-dir web-client/.engine
|
||||
printf '{"type":"commonjs"}\n' > web-client/.engine/package.json
|
||||
|
|
|
|||
86
web-client/scripts/publish.mjs
Normal file
86
web-client/scripts/publish.mjs
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
const version = process.argv.find((a) => a.startsWith('--version='))?.split('=')[1] ?? '1';
|
||||
if (!/^\d+$/.test(version)) throw new Error('Use --version=<integer>');
|
||||
const token =
|
||||
process.env.BGS_ADMIN_TOKEN ?? (await fs.readFile(path.join(os.homedir(), '.bgs'), 'utf8')).trim();
|
||||
const endpoint = `https://admin.boardgamers.space/api/admin/gameinfo/clash/${version}`;
|
||||
async function api(url, options = {}) {
|
||||
const res = await fetch(url, {
|
||||
...options,
|
||||
signal: AbortSignal.timeout(60000),
|
||||
redirect: 'error',
|
||||
headers: { Authorization: `Bearer ${token}`, ...options.headers },
|
||||
});
|
||||
if (!res.ok) throw new Error(`BGS API ${res.status}: ${await res.text()}`);
|
||||
return res.json();
|
||||
}
|
||||
const previous = await api(endpoint);
|
||||
const bytes = await fs.readFile(path.join(root, 'dist/viewer.js'));
|
||||
if (bytes.length > 25 * 1024 * 1024) throw new Error('Viewer exceeds the BGS upload limit');
|
||||
const hash = createHash('sha256').update(bytes).digest('hex');
|
||||
const filename = `viewer-${hash.slice(0, 16)}.js`;
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
game: 'clash',
|
||||
version: Number(version),
|
||||
bytes: bytes.length,
|
||||
sha256: hash,
|
||||
previousViewer: previous.viewer.url,
|
||||
dryRun: process.argv.includes('--dry-run'),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
if (!process.argv.includes('--dry-run')) {
|
||||
const backupDir = path.join(root, '.engine/releases');
|
||||
await fs.mkdir(backupDir, { recursive: true });
|
||||
const backup = path.join(backupDir, `version-${version}-${Date.now()}.json`);
|
||||
await fs.writeFile(backup, JSON.stringify(previous, null, 2));
|
||||
const uploaded = await api(`${endpoint}/viewer/file?filename=${filename}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/octet-stream' },
|
||||
body: bytes,
|
||||
});
|
||||
const asset = await fetch(uploaded.url, { redirect: 'error', signal: AbortSignal.timeout(60000) });
|
||||
if (
|
||||
!asset.ok ||
|
||||
createHash('sha256')
|
||||
.update(new Uint8Array(await asset.arrayBuffer()))
|
||||
.digest('hex') !== hash
|
||||
)
|
||||
throw new Error('Uploaded asset verification failed; version metadata was not changed');
|
||||
const viewer = {
|
||||
...previous.viewer,
|
||||
url: uploaded.url,
|
||||
topLevelVariable: 'clash3d',
|
||||
dependencies: { scripts: [], stylesheets: [] },
|
||||
fullScreen: true,
|
||||
fullScreenMobile: true,
|
||||
replayable: false,
|
||||
chat: true,
|
||||
};
|
||||
const current = await api(endpoint);
|
||||
if (JSON.stringify(current.viewer) !== JSON.stringify(previous.viewer))
|
||||
throw new Error('The viewer changed during upload; version metadata was not changed');
|
||||
await api(endpoint, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ viewer }),
|
||||
});
|
||||
const saved = await api(endpoint);
|
||||
if (
|
||||
saved.viewer.url !== uploaded.url ||
|
||||
saved.viewer.topLevelVariable !== 'clash3d' ||
|
||||
JSON.stringify(saved.engine) !== JSON.stringify(previous.engine)
|
||||
)
|
||||
throw new Error('Published version verification failed; inspect the saved backup');
|
||||
console.log(JSON.stringify({ published: uploaded.url, backup, engineUnchanged: true }, null, 2));
|
||||
}
|
||||
|
|
@ -37,6 +37,9 @@
|
|||
import { mountChat } from '@boardgamers/protocol/chat/dom';
|
||||
import { World } from './board';
|
||||
import ResearchTree from './ResearchTree.svelte';
|
||||
import CityPanel from './CityPanel.svelte';
|
||||
import SettlerPanel from './SettlerPanel.svelte';
|
||||
import ResourceAmount from './ResourceAmount.svelte';
|
||||
import type { Controller } from './controller';
|
||||
import type { Resource } from './types';
|
||||
import { resources, resourceNames, playerColors } from './types';
|
||||
|
|
@ -75,15 +78,20 @@
|
|||
let log = $derived($session.game ? journal($session.game) : []);
|
||||
let totalActions = $derived($session.game?.actions_left ?? 0);
|
||||
let objectiveDecision = $derived($session.view?.objectiveDecision);
|
||||
let choiceDecision = $derived($session.view?.choiceDecision);
|
||||
let focusTerrain = $derived($session.game?.map.tiles.find(([p]) => p === $session.focus)?.[1]);
|
||||
let actionTitle = $derived(
|
||||
$session.seat === undefined
|
||||
? 'Spectating'
|
||||
: objectiveDecision
|
||||
? 'Objective available'
|
||||
: $session.view?.canPlay
|
||||
? 'Your turn'
|
||||
: `${$session.view?.players.find((p) => p.index === $session.view?.activePlayer)?.civilization ?? 'Opponent'}’s turn`,
|
||||
: choiceDecision
|
||||
? 'Choose a bonus'
|
||||
: objectiveDecision
|
||||
? 'Objective available'
|
||||
: $session.view?.stopMovement
|
||||
? 'Moving settlers'
|
||||
: $session.view?.canPlay
|
||||
? 'Your turn'
|
||||
: `${$session.view?.players.find((p) => p.index === $session.view?.activePlayer)?.civilization ?? 'Opponent'}’s turn`,
|
||||
);
|
||||
onMount(() => {
|
||||
try {
|
||||
|
|
@ -285,7 +293,7 @@
|
|||
<div class="dock-intro"><Landmark size={19} /><span class="tiny-label">YOUR CITIES</span></div>
|
||||
{#each $session.view?.cities ?? [] as c}<button
|
||||
class:selected={c.position === $session.city}
|
||||
onclick={() => controller.selectCity(c.position)}
|
||||
onclick={() => controller.openCities(c.position)}
|
||||
><span class="city-thumb"><Landmark size={25} /></span><span
|
||||
><strong
|
||||
>{identity?.civilization}
|
||||
|
|
@ -320,6 +328,26 @@
|
|||
disabled={$session.seat === undefined}
|
||||
onclick={openResearch}><GraduationCap size={21} /><span>Research</span></button
|
||||
>
|
||||
<button
|
||||
class:active={$session.mode === 'city'}
|
||||
aria-label="Manage cities"
|
||||
title="Build, recruit and improve happiness"
|
||||
disabled={!city}
|
||||
onclick={() => {
|
||||
confirmEnd = false;
|
||||
controller.openCities();
|
||||
}}><Hammer size={21} /><span>Cities</span></button
|
||||
>
|
||||
<button
|
||||
class:active={$session.mode === 'settlers'}
|
||||
aria-label="Move settlers and found cities"
|
||||
title="Move settlers and found cities"
|
||||
disabled={$session.seat === undefined}
|
||||
onclick={() => {
|
||||
confirmEnd = false;
|
||||
controller.openSettlers();
|
||||
}}><Footprints size={21} /><span>Settlers</span></button
|
||||
>
|
||||
<button
|
||||
title="Undo last action"
|
||||
aria-label="Undo last action"
|
||||
|
|
@ -359,14 +387,26 @@
|
|||
>{/if}</button
|
||||
>
|
||||
</nav>
|
||||
{#if objectiveDecision || ($session.game && !$session.view?.supportedPhase && $session.seat === $session.view?.activePlayer) || $session.mode === 'collect' || confirmEnd || $session.error}
|
||||
{#if choiceDecision || objectiveDecision || ($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" aria-label="Current action">
|
||||
{#if !objectiveDecision && $session.view?.supportedPhase}<button
|
||||
{#if !choiceDecision && !objectiveDecision && $session.view?.supportedPhase}<button
|
||||
class="icon-button close-action"
|
||||
aria-label="Close action"
|
||||
onclick={closeAction}><X size={18} /></button
|
||||
>{/if}
|
||||
{#if objectiveDecision}
|
||||
{#if choiceDecision}
|
||||
<h2>{choiceDecision.name}</h2>
|
||||
<div class="collection-choices">
|
||||
{#each choiceDecision.choices as choice}<button
|
||||
class="secondary wide"
|
||||
disabled={$session.pending}
|
||||
onclick={() => controller.submit(choice.action)}
|
||||
>{#if choice.pile}<ResourceAmount pile={choice.pile} />{:else}{choice.name}{/if}<ArrowRight
|
||||
size={17}
|
||||
/></button
|
||||
>{/each}
|
||||
</div>
|
||||
{:else if objectiveDecision}
|
||||
<h2>{objectiveDecision.name}</h2>
|
||||
<p>{objectiveDecision.description}</p>
|
||||
{#each objectiveDecision.cards as card (card.id)}
|
||||
|
|
@ -449,6 +489,7 @@
|
|||
{#if $session.error}<p class="inline-error" role="alert">{$session.error}</p>{/if}
|
||||
</section>
|
||||
{/if}
|
||||
{#if $session.mode === 'settlers'}<SettlerPanel {controller} />{/if}
|
||||
<section
|
||||
class="activity floating-panel"
|
||||
hidden={!$session.activityOpen}
|
||||
|
|
@ -507,6 +548,7 @@
|
|||
</section>
|
||||
</main>
|
||||
{#if $session.mode === 'research'}<ResearchTree {controller} />{/if}
|
||||
{#if $session.mode === 'city'}<CityPanel {controller} />{/if}
|
||||
{#if $session.toast}<div class="toast" role="status"><Check size={16} />{$session.toast}</div>{/if}
|
||||
{#if $session.objectivesOpen && $session.seat !== undefined}
|
||||
<dialog
|
||||
|
|
|
|||
173
web-client/src/CityPanel.svelte
Normal file
173
web-client/src/CityPanel.svelte
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
<script lang="ts">
|
||||
import { X, Landmark, Hammer, Users, Smile, Plus, Minus, Check } from 'lucide-svelte';
|
||||
import type { Controller } from './controller';
|
||||
import { buildingInfo, unitInfo, cityReason } from './city';
|
||||
import ResourceAmount from './ResourceAmount.svelte';
|
||||
let { controller }: { controller: Controller } = $props();
|
||||
const session = $derived(controller.session);
|
||||
let tab = $state('build');
|
||||
let building = $state<string | null>(null);
|
||||
let city = $derived($session.view?.cities.find((c) => c.position === $session.city));
|
||||
let options = $derived($session.view?.cityActions.find((c) => c.position === $session.city));
|
||||
let selected = $derived(options?.buildings.find((b) => b.name === building));
|
||||
let count = $derived(Object.values($session.recruits).reduce((a, b) => a + (b ?? 0), 0));
|
||||
function close() {
|
||||
controller.patch({ mode: 'overview', error: '' });
|
||||
}
|
||||
function open(node: HTMLDialogElement) {
|
||||
node.showModal();
|
||||
return { destroy: () => node.close() };
|
||||
}
|
||||
</script>
|
||||
|
||||
<dialog
|
||||
class="city-dialog"
|
||||
use:open
|
||||
onclose={close}
|
||||
onclick={(e) => {
|
||||
if (e.target === e.currentTarget) close();
|
||||
}}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Escape') close();
|
||||
}}
|
||||
aria-labelledby="city-title"
|
||||
>
|
||||
<header class="city-dialog-header">
|
||||
<div>
|
||||
<h2 id="city-title"><Landmark size={26} /> City {$session.city}</h2>
|
||||
<p>Size {city?.size} · {city?.mood} · Collect or recruit up to {city?.capacity}</p>
|
||||
</div>
|
||||
<button class="icon-button" aria-label="Close city management" onclick={close}><X /></button>
|
||||
</header>
|
||||
<nav class="city-picker" aria-label="Choose city">
|
||||
{#each $session.view?.cities ?? [] as c}<button
|
||||
class:active={c.position === $session.city}
|
||||
onclick={() => {
|
||||
building = null;
|
||||
controller.openCities(c.position);
|
||||
}}><Landmark size={14} />{c.position} <span>{c.mood}</span></button
|
||||
>{/each}
|
||||
</nav>
|
||||
<nav class="city-tabs" aria-label="City actions">
|
||||
{#each [{ id: 'build', label: 'Buildings', icon: Hammer }, { id: 'recruit', label: 'Recruit', icon: Users }, { id: 'happiness', label: 'Happiness', icon: Smile }] as item}<button
|
||||
class:active={tab === item.id}
|
||||
onclick={() => {
|
||||
tab = item.id;
|
||||
controller.patch({ error: '' });
|
||||
}}><item.icon size={17} />{item.label}</button
|
||||
>{/each}
|
||||
</nav>
|
||||
<div class="city-content">
|
||||
{#if tab === 'build'}
|
||||
<p class="city-rule">
|
||||
Each building adds 1 city size and 1 point. A city’s size cannot exceed your number of cities.
|
||||
</p>
|
||||
<div class="building-grid">
|
||||
{#each options?.buildings ?? [] as item}{@const info = buildingInfo[item.name]}<button
|
||||
class="building-option"
|
||||
class:owned={item.owned}
|
||||
class:selected={building === item.name}
|
||||
onclick={() => (building = item.name)}
|
||||
aria-pressed={building === item.name}
|
||||
><strong
|
||||
><info.icon size={21} />{item.name}{#if item.owned}<Check size={16} />{/if}</strong
|
||||
><span>{info.effect}</span>{#if item.owned}<small>Built</small>{:else}<ResourceAmount
|
||||
pile={item.payment}
|
||||
/><small>{cityReason(item.reason, city?.size) || 'Available'}</small>{/if}</button
|
||||
>{/each}
|
||||
</div>
|
||||
{:else if tab === 'recruit'}
|
||||
<p class="city-rule">
|
||||
Recruit up to {city?.capacity} units together for 1 action. Activates this city.
|
||||
</p>
|
||||
<div class="recruit-list">
|
||||
{#each options?.recruits ?? [] as item}{@const info = unitInfo[item.type]}{@const amount =
|
||||
$session.recruits[info.key] ?? 0}
|
||||
<article class="recruit-row">
|
||||
<info.icon size={24} />
|
||||
<div>
|
||||
<strong>{item.type}</strong>
|
||||
<p>{info.effect}</p>
|
||||
<ResourceAmount pile={item.payment} /><small
|
||||
>{cityReason(item.reason) || `${item.available} in supply`}</small
|
||||
>
|
||||
</div>
|
||||
<div class="quantity">
|
||||
<button
|
||||
aria-label={`Remove ${item.type}`}
|
||||
disabled={!amount || $session.pending}
|
||||
onclick={() => controller.setRecruits({ ...$session.recruits, [info.key]: amount - 1 })}
|
||||
><Minus size={15} /></button
|
||||
><output aria-label={`${item.type} selected`}>{amount}</output><button
|
||||
aria-label={`Add ${item.type}`}
|
||||
disabled={!!item.reason ||
|
||||
amount >= item.available ||
|
||||
count >= (city?.capacity ?? 0) ||
|
||||
$session.pending}
|
||||
onclick={() => controller.setRecruits({ ...$session.recruits, [info.key]: amount + 1 })}
|
||||
><Plus size={15} /></button
|
||||
>
|
||||
</div>
|
||||
</article>{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="city-rule">
|
||||
Happier cities collect more and recruit more. Improving mood uses 1 action without activating the
|
||||
city.
|
||||
</p>
|
||||
{#if !options?.happiness.length}<div class="happy-message">
|
||||
<Smile size={32} />
|
||||
<h3>This city is already happy</h3>
|
||||
<p>Its capacity is {city?.capacity}, one more than its size.</p>
|
||||
</div>{/if}
|
||||
<div class="happiness-options">
|
||||
{#each options?.happiness ?? [] as item}<article>
|
||||
<Smile size={26} />
|
||||
<h3>{item.mood}</h3>
|
||||
<p>Raise mood by {item.steps} {item.steps === 1 ? 'step' : 'steps'}.</p>
|
||||
<ResourceAmount pile={item.payment} /><small>{item.reason ?? 'Costs 1 action'}</small><button
|
||||
class="primary"
|
||||
disabled={!item.action || $session.pending}
|
||||
onclick={() => item.action && controller.submit(item.action)}>Raise to {item.mood}</button
|
||||
>
|
||||
</article>{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{#if tab === 'build' && selected && !selected.owned}<footer class="city-confirm">
|
||||
<div>
|
||||
<strong>{selected.name}</strong><ResourceAmount pile={selected.payment} /><small
|
||||
>{cityReason(selected.reason, city?.size) || 'Costs 1 action · Activates this city'}</small
|
||||
>{#if selected.moodWillDecrease}<small class="warning"
|
||||
>Activating this city again lowers its mood.</small
|
||||
>{/if}
|
||||
</div>
|
||||
<div class="port-choices">
|
||||
{#each selected.choices as choice}<button
|
||||
class="primary"
|
||||
disabled={$session.pending}
|
||||
onclick={() => controller.submit(choice.action)}
|
||||
>Build {selected.name}{choice.position ? ` at ${choice.position}` : ''}</button
|
||||
>{/each}
|
||||
</div>
|
||||
</footer>{/if}
|
||||
{#if tab === 'recruit'}<footer class="city-confirm">
|
||||
<div>
|
||||
<strong>{count} {count === 1 ? 'unit' : 'units'} selected</strong
|
||||
>{#if $session.recruitPreview}<ResourceAmount
|
||||
pile={$session.recruitPreview.payment}
|
||||
/>{#if $session.recruitPreview.moodWillDecrease}<small class="warning"
|
||||
>Activating this city again lowers its mood.</small
|
||||
>{/if}{/if}
|
||||
</div>
|
||||
<button
|
||||
class="primary"
|
||||
disabled={!$session.recruitPreview || $session.pending}
|
||||
onclick={() => $session.recruitPreview && controller.submit($session.recruitPreview.action)}
|
||||
>{$session.pending
|
||||
? 'Confirming…'
|
||||
: `Recruit ${count || ''} ${count === 1 ? 'unit' : 'units'}`}</button
|
||||
>
|
||||
</footer>{/if}
|
||||
{#if $session.error}<p class="city-error" role="alert">{cityReason($session.error, city?.size)}</p>{/if}
|
||||
</dialog>
|
||||
20
web-client/src/ResourceAmount.svelte
Normal file
20
web-client/src/ResourceAmount.svelte
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<script lang="ts">
|
||||
import { Wheat, Trees, Mountain, Lightbulb, Coins, Smile, Drama } from 'lucide-svelte';
|
||||
import { resourceNames, type Pile, type Resource } from './types';
|
||||
let { pile }: { pile: Pile } = $props();
|
||||
const icons = {
|
||||
food: Wheat,
|
||||
wood: Trees,
|
||||
ore: Mountain,
|
||||
ideas: Lightbulb,
|
||||
gold: Coins,
|
||||
mood_tokens: Smile,
|
||||
culture_tokens: Drama,
|
||||
};
|
||||
</script>
|
||||
|
||||
<span class="resource-amount"
|
||||
>{#each Object.entries(pile).filter(([, n]) => n) as [key, amount]}{@const Icon =
|
||||
icons[key as Resource]}<span><Icon size={14} />{amount} {resourceNames[key as Resource]}</span
|
||||
>{:else}<span>No resources</span>{/each}</span
|
||||
>
|
||||
69
web-client/src/SettlerPanel.svelte
Normal file
69
web-client/src/SettlerPanel.svelte
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
<script lang="ts">
|
||||
import { Footprints, Landmark, MapPin, X, ArrowRight, Check } from 'lucide-svelte';
|
||||
import type { Controller } from './controller';
|
||||
import ResourceAmount from './ResourceAmount.svelte';
|
||||
let { controller }: { controller: Controller } = $props();
|
||||
const session = $derived(controller.session);
|
||||
let unit = $derived($session.view?.settlers.find((u) => u.id === $session.selectedSettler));
|
||||
let destination = $derived(unit?.destinations.find((d) => d.position === $session.destination));
|
||||
</script>
|
||||
|
||||
<section class="action-panel floating-panel settler-panel" aria-label="Settler movement">
|
||||
<button
|
||||
class="icon-button close-action"
|
||||
aria-label="Close settler controls"
|
||||
onclick={() => controller.patch({ mode: 'overview', error: '' })}><X size={18} /></button
|
||||
>
|
||||
<h2><Footprints size={22} /> Settlers</h2>
|
||||
<p>
|
||||
{$session.view?.stopMovement
|
||||
? 'Movement in progress. Move another eligible settler, or finish moving.'
|
||||
: 'Move settlers, then spend another action to found a city.'}
|
||||
</p>
|
||||
<div class="settler-picker">
|
||||
{#each $session.view?.settlers ?? [] as u}<button
|
||||
class:selected={u.id === unit?.id}
|
||||
onclick={() => controller.patch({ selectedSettler: u.id, destination: null, error: '' })}
|
||||
><Footprints size={15} />#{u.id + 1} · {u.position}</button
|
||||
>{/each}
|
||||
</div>
|
||||
{#if unit}<div class="settler-destinations">
|
||||
<strong><MapPin size={14} /> From {unit.position}</strong>
|
||||
<p>Choose a highlighted tile or a destination below.</p>
|
||||
{#each unit.destinations as d}<button
|
||||
class:selected={destination?.position === d.position}
|
||||
onclick={() => controller.patch({ destination: d.position, error: '' })}
|
||||
><span>{d.position} · {typeof d.terrain === 'string' ? d.terrain : 'Exhausted'}</span
|
||||
>{#if destination?.position === d.position}<Check size={15} />{/if}</button
|
||||
>{:else}<p>No available destinations for this settler.</p>{/each}
|
||||
</div>
|
||||
{#if destination}<div class="settler-confirm">
|
||||
<ResourceAmount pile={destination.payment} /><button
|
||||
class="primary wide"
|
||||
disabled={$session.pending}
|
||||
onclick={() => controller.submit(destination.action)}
|
||||
>Move to {destination.position}<ArrowRight size={16} /></button
|
||||
><small
|
||||
>{$session.view?.stopMovement
|
||||
? 'Part of the current movement action'
|
||||
: 'Costs 1 action · Up to 3 group moves'}</small
|
||||
>
|
||||
</div>{/if}
|
||||
{#if !$session.view?.stopMovement}<div class="settler-found">
|
||||
<button
|
||||
class="secondary wide"
|
||||
disabled={!unit.foundAction || $session.pending}
|
||||
onclick={() => unit.foundAction && controller.submit(unit.foundAction)}
|
||||
><Landmark size={17} /> Found city at {unit.position}</button
|
||||
><small>{unit.foundReason ?? 'Costs 1 action · Replaces this settler with a city'}</small>
|
||||
</div>{/if}
|
||||
{:else}<p>Recruit a settler in one of your cities to expand.</p>{/if}
|
||||
{#if $session.view?.stopMovement}<button
|
||||
class="primary wide"
|
||||
disabled={$session.pending}
|
||||
onclick={() => $session.view?.stopMovement && controller.submit($session.view.stopMovement)}
|
||||
>Finish moving <Check size={16} /></button
|
||||
>{/if}
|
||||
<p class="feature-note">Settler movement currently covers revealed land without enemy units.</p>
|
||||
{#if $session.error}<p class="inline-error" role="alert">{$session.error}</p>{/if}
|
||||
</section>
|
||||
|
|
@ -190,9 +190,7 @@ export class World {
|
|||
this.topDown ? 0 : 12.5,
|
||||
this.topDown ? 27 : 22,
|
||||
this.topDown ? 0.01 : 17,
|
||||
).multiplyScalar(
|
||||
Math.max(1, 0.92 / this.camera.aspect) * (this.camera.aspect > 1.4 ? 0.85 : 1),
|
||||
),
|
||||
).multiplyScalar(Math.max(1, 0.92 / this.camera.aspect) * (this.camera.aspect > 1.4 ? 0.85 : 1)),
|
||||
);
|
||||
this.controls.update();
|
||||
this.invalidate();
|
||||
|
|
@ -375,6 +373,30 @@ export class World {
|
|||
const cityModel = this.building(playerColors[player.id] ?? '#bfa986');
|
||||
cityModel.position.set(x, 0.38, z);
|
||||
cityModel.rotation.y = 0.25;
|
||||
const additions = Object.keys(city.city_pieces ?? {}).filter((k) => k !== 'wonders');
|
||||
for (const [j, name] of additions.entries()) {
|
||||
const annex = new THREE.Group();
|
||||
const stone = this.material('#d5c6a0');
|
||||
const angle = j * 2.4;
|
||||
const tower = this.mesh(
|
||||
name === 'obelisk'
|
||||
? new THREE.ConeGeometry(0.1, 0.85, 4)
|
||||
: new THREE.BoxGeometry(0.22, name === 'fortress' ? 0.55 : 0.27, 0.26),
|
||||
stone,
|
||||
);
|
||||
tower.position.y = name === 'obelisk' ? 0.42 : name === 'fortress' ? 0.27 : 0.14;
|
||||
annex.add(tower);
|
||||
if (name !== 'obelisk' && name !== 'fortress') {
|
||||
const roof = this.mesh(
|
||||
new THREE.ConeGeometry(0.23, 0.18, name === 'observatory' ? 12 : 4),
|
||||
this.material(name === 'observatory' ? '#62887b' : '#a86042'),
|
||||
);
|
||||
roof.position.y = 0.35;
|
||||
annex.add(roof);
|
||||
}
|
||||
annex.position.set(Math.cos(angle) * 0.66, 0, Math.sin(angle) * 0.64);
|
||||
cityModel.add(annex);
|
||||
}
|
||||
this.board.add(cityModel);
|
||||
const label = document.createElement('button');
|
||||
label.className = 'city-map-label';
|
||||
|
|
@ -389,7 +411,7 @@ export class World {
|
|||
node: label,
|
||||
});
|
||||
}
|
||||
for (const unit of player.units ?? []) {
|
||||
for (const [unitIndex, unit] of (player.units ?? []).entries()) {
|
||||
const [x, z] = positionXY(unit.position);
|
||||
const pawn = new THREE.Group();
|
||||
const color = this.material(playerColors[player.id] ?? '#bfa986');
|
||||
|
|
@ -401,17 +423,56 @@ export class World {
|
|||
pawn.add(head);
|
||||
const base = this.mesh(new THREE.CylinderGeometry(0.14, 0.14, 0.04, 14), this.material('#e5d19e'));
|
||||
pawn.add(base);
|
||||
pawn.position.set(x - 0.58, 0.4, z + 0.25);
|
||||
if (unit.unit_type === 'Infantry') {
|
||||
const spear = this.mesh(
|
||||
new THREE.CylinderGeometry(0.013, 0.013, 0.56, 5),
|
||||
this.material('#6b6042'),
|
||||
);
|
||||
spear.position.set(0.13, 0.28, 0);
|
||||
pawn.add(spear);
|
||||
} else if (unit.unit_type === 'Ship') {
|
||||
const hull = this.mesh(new THREE.BoxGeometry(0.23, 0.13, 0.5), color);
|
||||
hull.position.y = 0.07;
|
||||
pawn.add(hull);
|
||||
const sail = this.mesh(new THREE.BoxGeometry(0.25, 0.27, 0.018), this.material('#f4e8cc'));
|
||||
sail.position.y = 0.4;
|
||||
pawn.add(sail);
|
||||
} else if (unit.unit_type === 'Cavalry' || unit.unit_type === 'Elephant') {
|
||||
const mount = this.mesh(
|
||||
new THREE.BoxGeometry(0.19, 0.2, 0.35),
|
||||
this.material(unit.unit_type === 'Elephant' ? '#859187' : '#887258'),
|
||||
);
|
||||
mount.position.y = 0.13;
|
||||
pawn.add(mount);
|
||||
}
|
||||
const stackIndex = (player.units ?? [])
|
||||
.slice(0, unitIndex)
|
||||
.filter((u) => u.position === unit.position).length;
|
||||
pawn.position.set(
|
||||
x - 0.58 + (stackIndex % 3) * 0.23,
|
||||
0.4,
|
||||
z + 0.25 + Math.floor(stackIndex / 3) * 0.23,
|
||||
);
|
||||
this.board.add(pawn);
|
||||
}
|
||||
}
|
||||
if (this.selectionSignature === '') this.reset();
|
||||
}
|
||||
const selected = s.mode === 'collect' ? s.selection.map((c) => c.position) : s.city ? [s.city] : [];
|
||||
const settler = s.view?.settlers.find((u) => u.id === s.selectedSettler);
|
||||
const selected =
|
||||
s.mode === 'settlers'
|
||||
? [settler?.position, s.destination].filter((p): p is string => !!p)
|
||||
: s.mode === 'collect'
|
||||
? s.selection.map((c) => c.position)
|
||||
: s.city
|
||||
? [s.city]
|
||||
: [];
|
||||
const available =
|
||||
s.mode === 'collect'
|
||||
? (s.view?.cities.find((c) => c.position === s.city)?.choices.map((c) => c.position) ?? [])
|
||||
: [];
|
||||
s.mode === 'settlers'
|
||||
? (settler?.destinations.map((d) => d.position) ?? [])
|
||||
: s.mode === 'collect'
|
||||
? (s.view?.cities.find((c) => c.position === s.city)?.choices.map((c) => c.position) ?? [])
|
||||
: [];
|
||||
const selectionSig = JSON.stringify([selected, available]);
|
||||
if (selectionSig !== this.selectionSignature) {
|
||||
this.selectionSignature = selectionSig;
|
||||
|
|
|
|||
14
web-client/src/bridge.ts
Normal file
14
web-client/src/bridge.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { initSync, webView, webCollectPreview, webRecruitPreview } from '../.bridge/server.js';
|
||||
import wasm from '../.bridge/server_bg.wasm?url';
|
||||
import type { Bridge } from './types';
|
||||
let ready: Promise<Bridge> | undefined;
|
||||
export function loadBridge(): Promise<Bridge> {
|
||||
return (ready ??= initialize());
|
||||
}
|
||||
async function initialize(): Promise<Bridge> {
|
||||
const bytes = wasm.startsWith('data:')
|
||||
? Uint8Array.from(atob(wasm.split(',')[1]), (c) => c.charCodeAt(0))
|
||||
: new Uint8Array(await (await fetch(wasm)).arrayBuffer());
|
||||
initSync({ module: bytes });
|
||||
return { webView, webCollectPreview, webRecruitPreview };
|
||||
}
|
||||
415
web-client/src/city.css
Normal file
415
web-client/src/city.css
Normal file
|
|
@ -0,0 +1,415 @@
|
|||
.resource-amount {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 13px;
|
||||
font-size: 12px;
|
||||
align-items: center;
|
||||
}
|
||||
.resource-amount > span {
|
||||
display: inline-flex;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
}
|
||||
.city-dialog {
|
||||
width: min(960px, calc(100vw - 50px));
|
||||
height: min(830px, calc(100dvh - 40px));
|
||||
max-height: calc(100dvh - 40px);
|
||||
padding: 0;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-shadow: 0 25px 90px #203c3d40;
|
||||
overflow: hidden;
|
||||
}
|
||||
.city-dialog::backdrop {
|
||||
background: #1b352c55;
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
.city-dialog-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
padding: 24px 26px 14px;
|
||||
}
|
||||
.city-dialog-header h2 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
font-size: 31px;
|
||||
}
|
||||
.city-dialog-header p {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
.city-picker,
|
||||
.city-tabs {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 10px 26px;
|
||||
flex-shrink: 0;
|
||||
overflow-x: auto;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.city-picker button,
|
||||
.city-tabs button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
padding: 9px 12px;
|
||||
white-space: nowrap;
|
||||
border-radius: 5px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.city-picker button > span {
|
||||
font-size: 10px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.city-picker button.active,
|
||||
.city-tabs button.active {
|
||||
background: var(--paper2);
|
||||
color: var(--green);
|
||||
box-shadow: inset 0 0 0 1px var(--line);
|
||||
}
|
||||
.city-content {
|
||||
padding: 20px 26px;
|
||||
overflow: auto;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.city-rule {
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
color: var(--muted);
|
||||
margin-bottom: 19px;
|
||||
}
|
||||
.building-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
|
||||
gap: 13px;
|
||||
}
|
||||
.building-option {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
text-align: left;
|
||||
padding: 17px;
|
||||
gap: 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 7px;
|
||||
}
|
||||
.building-option > strong {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
font-size: 14px;
|
||||
}
|
||||
.building-option > strong svg:last-child:not(:first-child) {
|
||||
margin-left: auto;
|
||||
}
|
||||
.building-option > span:not(.resource-amount) {
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
min-height: 36px;
|
||||
}
|
||||
.building-option small {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.building-option.selected {
|
||||
outline: 2px solid #ad8a4e;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.building-option.owned {
|
||||
background: #8eae7220;
|
||||
}
|
||||
.city-confirm {
|
||||
border-top: 1px solid var(--line);
|
||||
padding: 17px 26px;
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-shrink: 0;
|
||||
max-height: 35%;
|
||||
overflow: auto;
|
||||
}
|
||||
.city-confirm > div:first-child {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
}
|
||||
.city-confirm strong {
|
||||
font-size: 14px;
|
||||
}
|
||||
.city-confirm small,
|
||||
.happiness-options small {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
color: var(--muted);
|
||||
}
|
||||
.city-confirm .primary {
|
||||
white-space: nowrap;
|
||||
min-width: 170px;
|
||||
}
|
||||
.port-choices {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.recruit-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
.recruit-row {
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
align-items: center;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 7px;
|
||||
padding: 17px;
|
||||
}
|
||||
.recruit-row > svg {
|
||||
flex-shrink: 0;
|
||||
color: var(--gold);
|
||||
}
|
||||
.recruit-row > div:not(.quantity) {
|
||||
flex: 1;
|
||||
}
|
||||
.recruit-row strong {
|
||||
font-size: 14px;
|
||||
}
|
||||
.recruit-row p {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
margin: 6px 0 9px;
|
||||
}
|
||||
.recruit-row small {
|
||||
display: block;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
margin-top: 7px;
|
||||
}
|
||||
.quantity {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.quantity button {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 4px;
|
||||
width: 29px;
|
||||
height: 31px;
|
||||
}
|
||||
.quantity output {
|
||||
min-width: 15px;
|
||||
text-align: center;
|
||||
}
|
||||
.happiness-options {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
}
|
||||
.happiness-options article {
|
||||
flex: 1;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 22px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 13px;
|
||||
}
|
||||
.happiness-options article p {
|
||||
font-size: 12px;
|
||||
}
|
||||
.happiness-options h3,
|
||||
.happy-message h3 {
|
||||
font-size: 24px;
|
||||
}
|
||||
.happy-message {
|
||||
text-align: center;
|
||||
padding: 45px 0;
|
||||
}
|
||||
.happy-message > svg {
|
||||
color: var(--green);
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
.happy-message p {
|
||||
margin-top: 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.city-error {
|
||||
padding: 10px 26px;
|
||||
color: #9b4d33;
|
||||
font-size: 12px;
|
||||
border-top: 1px solid var(--line);
|
||||
max-height: 15%;
|
||||
overflow: auto;
|
||||
}
|
||||
.settler-panel h2 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.settler-picker {
|
||||
display: flex;
|
||||
gap: 7px;
|
||||
flex-wrap: wrap;
|
||||
margin: 15px 0;
|
||||
}
|
||||
.settler-picker button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
border: 1px solid var(--line);
|
||||
padding: 8px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.settler-picker button.selected,
|
||||
.settler-destinations button.selected {
|
||||
background: var(--paper2);
|
||||
border-color: var(--gold);
|
||||
}
|
||||
.settler-destinations > strong {
|
||||
font-size: 13px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.settler-destinations p,
|
||||
.settler-panel .feature-note {
|
||||
font-size: 11px;
|
||||
line-height: 1.6;
|
||||
color: var(--muted);
|
||||
margin: 10px 0;
|
||||
}
|
||||
.settler-destinations > button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 5px;
|
||||
font-size: 12px;
|
||||
margin: 6px 0;
|
||||
}
|
||||
.settler-confirm,
|
||||
.settler-found {
|
||||
padding: 14px 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 9px;
|
||||
}
|
||||
.settler-confirm small,
|
||||
.settler-found small {
|
||||
font-size: 10px;
|
||||
color: var(--muted);
|
||||
line-height: 1.5;
|
||||
}
|
||||
.play-layout .board-toolbar {
|
||||
width: 354px;
|
||||
}
|
||||
.board-toolbar .board-actions {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(6, minmax(0, 1fr));
|
||||
}
|
||||
.board-toolbar .board-actions button {
|
||||
min-width: 0;
|
||||
}
|
||||
.dark .city-tabs button.active,
|
||||
.dark .city-picker button.active {
|
||||
color: var(--ink);
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.play-layout .board-toolbar {
|
||||
width: 208px;
|
||||
max-width: calc(100% - 150px);
|
||||
}
|
||||
.board-toolbar .board-actions {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
padding: 4px;
|
||||
gap: 0;
|
||||
}
|
||||
.board-toolbar .board-actions button {
|
||||
padding: 5px 3px;
|
||||
gap: 2px;
|
||||
font-size: 9px;
|
||||
}
|
||||
.board-toolbar .board-actions button svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
.play-layout .action-panel.floating-panel {
|
||||
top: 136px;
|
||||
max-height: calc(100% - 150px);
|
||||
}
|
||||
.city-dialog {
|
||||
width: calc(100vw - 16px);
|
||||
height: calc(100dvh - 16px);
|
||||
max-height: calc(100dvh - 16px);
|
||||
}
|
||||
.city-dialog-header {
|
||||
padding: 20px 17px 10px;
|
||||
}
|
||||
.city-dialog-header h2 {
|
||||
font-size: 27px;
|
||||
}
|
||||
.city-picker,
|
||||
.city-tabs {
|
||||
padding: 9px 17px;
|
||||
}
|
||||
.city-tabs {
|
||||
gap: 3px;
|
||||
}
|
||||
.city-tabs button {
|
||||
padding: 8px 9px;
|
||||
}
|
||||
.city-content {
|
||||
padding: 17px;
|
||||
}
|
||||
.building-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.city-confirm {
|
||||
padding: 14px 17px;
|
||||
gap: 12px;
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
.city-confirm .primary {
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.recruit-row {
|
||||
padding: 13px 10px;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.recruit-row > div:not(.quantity) {
|
||||
min-width: 170px;
|
||||
}
|
||||
.quantity {
|
||||
margin-left: auto;
|
||||
}
|
||||
.happiness-options {
|
||||
flex-direction: column;
|
||||
}
|
||||
.happiness-options article {
|
||||
padding: 18px;
|
||||
}
|
||||
.city-error {
|
||||
padding: 10px 17px;
|
||||
}
|
||||
}
|
||||
40
web-client/src/city.ts
Normal file
40
web-client/src/city.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import {
|
||||
BookOpen,
|
||||
Store,
|
||||
Landmark,
|
||||
Telescope,
|
||||
Castle,
|
||||
Anchor,
|
||||
Church,
|
||||
Footprints,
|
||||
Swords,
|
||||
Flag,
|
||||
Shield,
|
||||
Ship,
|
||||
} from 'lucide-svelte';
|
||||
import type { RecruitSelection, UnitKind } from './types';
|
||||
export const buildingInfo: Record<string, { icon: typeof Landmark; effect: string }> = {
|
||||
Academy: { icon: BookOpen, effect: 'Gain 2 ideas when built.' },
|
||||
Market: { icon: Store, effect: 'Recruit cavalry and elephants here.' },
|
||||
Obelisk: { icon: Landmark, effect: 'This building cannot be culturally influenced.' },
|
||||
Observatory: { icon: Telescope, effect: 'Draw an action card when built.' },
|
||||
Fortress: { icon: Castle, effect: 'Defending: +1 die and cancel 1 hit in round 1.' },
|
||||
Port: { icon: Anchor, effect: 'Recruit ships. Collect gold or mood from the port tile.' },
|
||||
Temple: { icon: Church, effect: 'Gain 1 mood or culture when built.' },
|
||||
};
|
||||
export const unitInfo: Record<
|
||||
UnitKind,
|
||||
{ icon: typeof Footprints; key: keyof RecruitSelection; effect: string }
|
||||
> = {
|
||||
Settler: { icon: Footprints, key: 'settlers', effect: 'Explore and found new cities.' },
|
||||
Infantry: { icon: Swords, key: 'infantry', effect: 'Fight on land. Needs Tactics to move.' },
|
||||
Cavalry: { icon: Flag, key: 'cavalry', effect: 'Army unit; requires a Market.' },
|
||||
Elephant: { icon: Shield, key: 'elephants', effect: 'Army unit; requires a Market.' },
|
||||
Ship: { icon: Ship, key: 'ships', effect: 'Sail and transport units; requires a Port.' },
|
||||
};
|
||||
export function cityReason(reason: string | null, size = 1) {
|
||||
if (reason === 'Need more cities') return `You need ${size + 1} cities before this city can grow.`;
|
||||
if (reason === 'Invalid replacement') return 'No pieces left in your supply.';
|
||||
if (reason === 'Too many units') return 'The selection exceeds this city’s recruitment capacity.';
|
||||
return reason?.replace('Mising building:', 'Requires a') ?? '';
|
||||
}
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import { get, writable } from 'svelte/store';
|
||||
import { ChatController } from '@boardgamers/protocol/chat';
|
||||
import type { ViewerCommands } from '@boardgamers/protocol/viewer';
|
||||
import type { Bridge, Choice, Game, Move, Session, View } from './types';
|
||||
import type { Bridge, Choice, Game, Move, RecruitSelection, Session, View } from './types';
|
||||
import { journal } from './model';
|
||||
import { loadBridge } from './bridge';
|
||||
export class Controller {
|
||||
readonly session = writable<Session>({
|
||||
game: null,
|
||||
|
|
@ -10,6 +11,10 @@ export class Controller {
|
|||
city: null,
|
||||
focus: null,
|
||||
mode: 'overview',
|
||||
selectedSettler: null,
|
||||
destination: null,
|
||||
recruits: {},
|
||||
recruitPreview: null,
|
||||
selection: [],
|
||||
preview: null,
|
||||
error: '',
|
||||
|
|
@ -48,11 +53,7 @@ export class Controller {
|
|||
async load(raw: unknown) {
|
||||
if (typeof raw !== 'string') throw new Error('Clash expects a serialized game state.');
|
||||
if (!this.engine) {
|
||||
const engine = (await import(
|
||||
/* @vite-ignore */ new URL('engine/server.js', this.assetBase).href
|
||||
)) as Bridge;
|
||||
await engine.default();
|
||||
this.engine = engine;
|
||||
this.engine = await loadBridge();
|
||||
}
|
||||
if (this.destroyed) return;
|
||||
const old = get(this.session);
|
||||
|
|
@ -72,10 +73,21 @@ export class Controller {
|
|||
error: '',
|
||||
selection: [],
|
||||
preview: null,
|
||||
mode: old.pending || view.objectiveDecision ? 'overview' : old.mode,
|
||||
objectivesOpen: view.objectiveDecision ? false : old.objectivesOpen,
|
||||
recruits: {},
|
||||
recruitPreview: null,
|
||||
destination: null,
|
||||
selectedSettler: view.settlers.some((u) => u.id === old.selectedSettler)
|
||||
? old.selectedSettler
|
||||
: (view.settlers[0]?.id ?? null),
|
||||
mode: view.stopMovement
|
||||
? 'settlers'
|
||||
: old.pending || view.objectiveDecision || view.choiceDecision
|
||||
? 'overview'
|
||||
: old.mode,
|
||||
objectivesOpen: view.objectiveDecision || view.choiceDecision ? false : old.objectivesOpen,
|
||||
});
|
||||
this.commands.replaceLog(journal(game).map((entry) => entry.text));
|
||||
if (view.objectiveDecision || view.choiceDecision) this.closeActivity();
|
||||
if (old.pending) this.notify('Game updated.');
|
||||
}
|
||||
setPlayer(index?: number) {
|
||||
|
|
@ -86,6 +98,10 @@ export class Controller {
|
|||
preview: null,
|
||||
selectedAdvance: null,
|
||||
objectivesOpen: false,
|
||||
recruits: {},
|
||||
recruitPreview: null,
|
||||
selectedSettler: null,
|
||||
destination: null,
|
||||
});
|
||||
if (this.engine && this.raw) {
|
||||
const view = JSON.parse(this.engine.webView(this.raw, index)) as View;
|
||||
|
|
@ -100,12 +116,21 @@ export class Controller {
|
|||
preview: null,
|
||||
error: '',
|
||||
mode: 'overview',
|
||||
recruits: {},
|
||||
recruitPreview: null,
|
||||
});
|
||||
}
|
||||
selectTile(position: string) {
|
||||
const s = get(this.session);
|
||||
const city = s.view?.cities.find((c) => c.position === position);
|
||||
if (s.mode === 'collect') {
|
||||
if (s.mode === 'settlers') {
|
||||
const unit = s.view?.settlers.find((u) => u.id === s.selectedSettler);
|
||||
if (unit?.destinations.some((d) => d.position === position)) this.patch({ destination: position });
|
||||
else {
|
||||
const selected = s.view?.settlers.find((u) => u.position === position);
|
||||
if (selected) this.patch({ selectedSettler: selected.id, destination: null });
|
||||
}
|
||||
} else if (s.mode === 'collect') {
|
||||
const choice = s.view?.cities
|
||||
.find((c) => c.position === s.city)
|
||||
?.choices.find((c) => c.position === position);
|
||||
|
|
@ -117,6 +142,41 @@ export class Controller {
|
|||
this.closeActivity();
|
||||
this.patch({ mode: 'collect', selection: [], preview: null, error: '', selectedAdvance: null });
|
||||
}
|
||||
openCities(position?: string) {
|
||||
this.closeActivity();
|
||||
this.patch({
|
||||
mode: 'city',
|
||||
city: position ?? get(this.session).city,
|
||||
recruits: {},
|
||||
recruitPreview: null,
|
||||
error: '',
|
||||
});
|
||||
}
|
||||
openSettlers() {
|
||||
this.closeActivity();
|
||||
const s = get(this.session);
|
||||
this.patch({
|
||||
mode: 'settlers',
|
||||
selectedSettler: s.selectedSettler ?? s.view?.settlers[0]?.id ?? null,
|
||||
destination: null,
|
||||
error: '',
|
||||
});
|
||||
}
|
||||
setRecruits(recruits: RecruitSelection) {
|
||||
const s = get(this.session);
|
||||
if (s.pending || s.seat === undefined || !s.city || !this.engine) return;
|
||||
this.patch({ recruits, recruitPreview: null, error: '' });
|
||||
if (!Object.values(recruits).some(Boolean)) return;
|
||||
try {
|
||||
this.patch({
|
||||
recruitPreview: JSON.parse(
|
||||
this.engine.webRecruitPreview(this.raw, s.seat, s.city, JSON.stringify(recruits)),
|
||||
),
|
||||
});
|
||||
} catch (error) {
|
||||
this.patch({ error: String(error) });
|
||||
}
|
||||
}
|
||||
toggleChoice(choice: Choice) {
|
||||
const s = get(this.session);
|
||||
if (s.pending || !s.view?.canPlay || s.seat === undefined || !s.city || !this.engine) return;
|
||||
|
|
|
|||
|
|
@ -66,6 +66,12 @@ test('viewer queries respect spectator and opponent seats and reject illegal cho
|
|||
),
|
||||
);
|
||||
const full = JSON.parse(state);
|
||||
const exhausted = { ...full, actions_left: 0 };
|
||||
const exhaustedView: View = JSON.parse(
|
||||
engine.webView(engine.stripSecret(JSON.stringify(exhausted), seat), seat),
|
||||
);
|
||||
assert.ok(exhaustedView.settlers.length > 0);
|
||||
assert.ok(exhaustedView.settlers.every((u) => !u.foundAction && u.destinations.length === 0));
|
||||
const limited = JSON.parse(visible);
|
||||
assert.ok(full.players[1 - seat].action_cards.some((id: number) => id !== 0));
|
||||
assert.ok(limited.players[1 - seat].action_cards.every((id: number) => id === 0));
|
||||
|
|
@ -235,6 +241,78 @@ test('BGS lifecycle, chat acknowledgements, journal, and cleanup', async () => {
|
|||
assert.equal(client.emitter.emit('state', '{}'), false);
|
||||
});
|
||||
|
||||
test('settlers move, found a second city, and unlock construction without exceeding the turn budget', async () => {
|
||||
const setup = JSON.parse(await initial());
|
||||
const seat = engine.currentPlayer(JSON.stringify(setup));
|
||||
const p = setup.players[seat];
|
||||
p.resources = { food: 2, wood: 4, ore: 4, ideas: 4, mood_tokens: 4 };
|
||||
p.advances.push('Writing');
|
||||
let state = JSON.stringify(setup);
|
||||
const view = () => JSON.parse(engine.webView(engine.stripSecret(state, seat), seat)) as View;
|
||||
const city = view().cities[0].position;
|
||||
assert.equal(view().cityActions[0].buildings.find((b) => b.name === 'Academy')!.reason, 'Need more cities');
|
||||
const destination = view().settlers[0].destinations.find((d) => d.terrain === 'Forest')!;
|
||||
assert.ok(destination);
|
||||
state = engine.tryMove(state, JSON.stringify(destination.action), seat);
|
||||
assert.equal(JSON.parse(state).actions_left, 2);
|
||||
if (view().stopMovement) state = engine.tryMove(state, JSON.stringify(view().stopMovement), seat);
|
||||
const found = view().settlers[0].foundAction;
|
||||
assert.ok(found);
|
||||
state = engine.tryMove(state, JSON.stringify(found), seat);
|
||||
assert.equal(view().cities.length, 2);
|
||||
assert.equal(view().settlers.length, 0);
|
||||
const academy = view()
|
||||
.cityActions.find((c) => c.position === city)!
|
||||
.buildings.find((b) => b.name === 'Academy')!;
|
||||
assert.equal(academy.reason, null);
|
||||
state = engine.tryMove(state, JSON.stringify(academy.choices[0].action), seat);
|
||||
assert.equal(view().cities.find((c) => c.position === city)!.size, 2);
|
||||
assert.equal(JSON.parse(state).actions_left, 0);
|
||||
assert.ok(view().cityActions.every((c) => c.buildings.every((b) => b.choices.length === 0)));
|
||||
assert.ok(view().settlers.every((u) => u.destinations.length === 0));
|
||||
});
|
||||
|
||||
test('recruitment validates the whole selection, happiness uses mood, and temple bonuses can be chosen', async () => {
|
||||
const setup = JSON.parse(await initial());
|
||||
const seat = engine.currentPlayer(JSON.stringify(setup));
|
||||
const p = setup.players[seat];
|
||||
p.resources = { food: 2, wood: 4, ore: 4, mood_tokens: 4 };
|
||||
p.advances.push('Myths');
|
||||
const city = p.cities[0].position;
|
||||
const expansion: View = JSON.parse(engine.webView(engine.stripSecret(JSON.stringify(setup), seat), seat));
|
||||
p.cities.push({ ...p.cities[0], position: expansion.settlers[0].destinations[0].position });
|
||||
let state = JSON.stringify(setup);
|
||||
let visible = engine.stripSecret(state, seat);
|
||||
const recruit = JSON.parse(engine.webRecruitPreview(visible, seat, city, JSON.stringify({ infantry: 2 })));
|
||||
assert.deepEqual(recruit.payment, { food: 2, ore: 2 });
|
||||
assert.throws(() => engine.webRecruitPreview(visible, seat, city, JSON.stringify({ settlers: 3 })));
|
||||
assert.throws(() => engine.webRecruitPreview(visible, 1 - seat, city, JSON.stringify({ infantry: 1 })));
|
||||
assert.throws(() => engine.webRecruitPreview(visible, seat, 'Z99', JSON.stringify({ infantry: 1 })));
|
||||
const recruited = JSON.parse(engine.tryMove(state, JSON.stringify(recruit.action), seat));
|
||||
assert.equal(recruited.players[seat].units.filter((u: any) => u.unit_type === 'Infantry').length, 2);
|
||||
assert.equal(recruited.actions_left, 2);
|
||||
p.cities[0].mood_state = 'Neutral';
|
||||
state = JSON.stringify(setup);
|
||||
let view: View = JSON.parse(engine.webView(engine.stripSecret(state, seat), seat));
|
||||
const happy = view.cityActions[0].happiness[0];
|
||||
assert.deepEqual(happy.payment, { mood_tokens: 1 });
|
||||
state = engine.tryMove(state, JSON.stringify(happy.action), seat);
|
||||
assert.equal(JSON.parse(state).players[seat].cities[0].mood_state, 'Happy');
|
||||
view = JSON.parse(engine.webView(engine.stripSecret(state, seat), seat));
|
||||
const temple = view.cityActions[0].buildings.find((b) => b.name === 'Temple')!;
|
||||
state = engine.tryMove(state, JSON.stringify(temple.choices[0].action), seat);
|
||||
view = JSON.parse(engine.webView(engine.stripSecret(state, seat), seat));
|
||||
assert.equal(view.choiceDecision?.choices.length, 2);
|
||||
assert.equal(
|
||||
JSON.parse(engine.webView(engine.stripSecret(state, 1 - seat), 1 - seat)).choiceDecision,
|
||||
null,
|
||||
);
|
||||
const bonus = view.choiceDecision!.choices.find((c) => c.pile?.culture_tokens)!;
|
||||
state = engine.tryMove(state, JSON.stringify(bonus.action), seat);
|
||||
assert.equal(JSON.parse(state).players[seat].resources.culture_tokens, 1);
|
||||
assert.equal(JSON.parse(engine.webView(engine.stripSecret(state, seat), seat)).choiceDecision, null);
|
||||
});
|
||||
|
||||
test('offset hex coordinates preserve the odd-column layout', () => {
|
||||
assert.deepEqual(positionXY('A1'), [0, 0]);
|
||||
assert.deepEqual(positionXY('B1'), [1.5, Math.sqrt(3) / 2]);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;450;500;550;600;650;700&family=Libre+Caslon+Display&display=swap');
|
||||
@import './research.css';
|
||||
@import './city.css';
|
||||
:root {
|
||||
font-family: 'DM Sans', sans-serif;
|
||||
color: #343c32;
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ export type Terrain =
|
|||
export interface City {
|
||||
position: string;
|
||||
mood_state: string;
|
||||
pieces?: Record<string, unknown>;
|
||||
city_pieces?: Record<string, unknown>;
|
||||
activations?: number;
|
||||
}
|
||||
export interface Player {
|
||||
|
|
@ -92,6 +92,10 @@ export interface View {
|
|||
supportedPhase: boolean;
|
||||
players: PlayerView[];
|
||||
cities: CityView[];
|
||||
cityActions: CityActions[];
|
||||
settlers: SettlerView[];
|
||||
stopMovement: Move | null;
|
||||
choiceDecision?: { name: string; choices: { name: string; pile?: Pile; action: Move }[] } | null;
|
||||
advances: AdvanceView[];
|
||||
objectiveCards: {
|
||||
id: number;
|
||||
|
|
@ -115,9 +119,44 @@ export interface CollectionPreview {
|
|||
moodWillDecrease: boolean;
|
||||
}
|
||||
export interface Bridge {
|
||||
default: (input?: unknown) => Promise<unknown>;
|
||||
webView: (state: string, seat?: number) => string;
|
||||
webCollectPreview: (state: string, seat: number, city: string, choices: string) => string;
|
||||
webRecruitPreview: (state: string, seat: number, city: string, units: string) => string;
|
||||
}
|
||||
export type UnitKind = 'Settler' | 'Infantry' | 'Cavalry' | 'Elephant' | 'Ship';
|
||||
export type RecruitSelection = Partial<
|
||||
Record<'settlers' | 'infantry' | 'cavalry' | 'elephants' | 'ships', number>
|
||||
>;
|
||||
export interface ActionOffer {
|
||||
action: Move | null;
|
||||
payment: Pile;
|
||||
reason: string | null;
|
||||
}
|
||||
export interface CityActions {
|
||||
position: string;
|
||||
buildings: {
|
||||
name: string;
|
||||
owned: boolean;
|
||||
required: string;
|
||||
payment: Pile;
|
||||
reason: string | null;
|
||||
moodWillDecrease: boolean;
|
||||
choices: { position: string | null; action: Move }[];
|
||||
}[];
|
||||
recruits: { type: UnitKind; payment: Pile; reason: string | null; available: number }[];
|
||||
happiness: (ActionOffer & { steps: number; mood: string })[];
|
||||
}
|
||||
export interface SettlerView {
|
||||
id: number;
|
||||
position: string;
|
||||
foundReason: string | null;
|
||||
foundAction: Move | null;
|
||||
destinations: { position: string; terrain: Terrain; payment: Pile; action: Move }[];
|
||||
}
|
||||
export interface RecruitPreview {
|
||||
payment: Pile;
|
||||
action: Move;
|
||||
moodWillDecrease: boolean;
|
||||
}
|
||||
export interface JournalEntry {
|
||||
id: string;
|
||||
|
|
@ -144,7 +183,11 @@ export interface Session {
|
|||
seat?: number;
|
||||
city: string | null;
|
||||
focus: string | null;
|
||||
mode: 'overview' | 'collect' | 'research';
|
||||
mode: 'overview' | 'collect' | 'research' | 'city' | 'settlers';
|
||||
selectedSettler: number | null;
|
||||
destination: string | null;
|
||||
recruits: RecruitSelection;
|
||||
recruitPreview: RecruitPreview | null;
|
||||
selection: Selection[];
|
||||
preview: CollectionPreview | null;
|
||||
error: string;
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { defineConfig } from 'vite';
|
|||
import { svelte } from '@sveltejs/vite-plugin-svelte';
|
||||
import { previewApi } from './scripts/preview-api';
|
||||
export default defineConfig({
|
||||
publicDir: false,
|
||||
plugins: [svelte(), previewApi()],
|
||||
build: {
|
||||
lib: { entry: 'src/viewer.ts', name: 'Clash3DBundle', formats: ['iife'], fileName: () => 'viewer.js' },
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue