Add a 3D web viewer with Rust-backed actions and BGS protocol integration

This commit is contained in:
coyotte508 2026-09-27 23:43:06 +02:00
commit 8df84ba228
29 changed files with 6935 additions and 1 deletions

View file

@ -185,3 +185,33 @@ impl Messages {
Self { messages, data }
}
}
#[wasm_bindgen(js_name = "webView")]
pub fn web_view(data: String, player: Option<usize>) -> Result<String, JsValue> {
serde_json::to_string(&crate::web_view::view(&get_game(data), player))
.map_err(|e| JsValue::from_str(&e.to_string()))
}
#[wasm_bindgen(js_name = "webCollectPreview")]
pub fn web_collect_preview(
data: String,
player: usize,
city: String,
selections: String,
) -> Result<String, JsValue> {
let selections =
serde_json::from_str(&selections).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::collect_preview(&get_game(data), player, city, selections)
.map_err(|e| JsValue::from_str(&e))?;
serde_json::to_string(&result).map_err(|e| JsValue::from_str(&e.to_string()))
}
#[wasm_bindgen(js_name = "tryMove")]
pub fn try_move(data: String, action: String, player: usize) -> Result<String, JsValue> {
let action = serde_json::from_str(&action).map_err(|e| JsValue::from_str(&e.to_string()))?;
crate::action::try_execute_action(get_game(data), action, player)
.map(from_game)
.map_err(|e| JsValue::from_str(&e))
}

View file

@ -13,7 +13,6 @@ extern crate core;
pub mod ability_initializer;
pub mod action;
pub mod analysis;
pub mod action_card;
mod action_cost;
pub mod advance;
@ -25,6 +24,7 @@ pub mod ai_actions;
pub mod ai_collect;
#[cfg(not(target_arch = "wasm32"))]
pub mod ai_missions;
pub mod analysis;
pub mod barbarians;
pub mod cache;
pub mod card;
@ -75,4 +75,5 @@ mod undo;
pub mod unit;
pub mod utils;
pub mod victory_points;
pub mod web_view;
pub mod wonder;

210
server/src/web_view.rs Normal file
View file

@ -0,0 +1,210 @@
use crate::action::Action;
use crate::advance::AdvanceAction;
use crate::card::HandCard;
use crate::collect::{
Collect, PositionCollection, collect_event_origin, get_total_collection,
possible_resource_collections,
};
use crate::consts::OBJECTIVE_VICTORY_POINTS;
use crate::content::persistent_events::{
EventResponse, PersistentEventRequest, PersistentEventType,
};
use crate::game::{Game, GameState};
use crate::objective_card::ObjectiveType;
use crate::player::CostTrigger;
use crate::playing_actions::{PlayingAction, PlayingActionType};
use crate::position::Position;
use serde_json::{Value, json};
pub fn view(game: &Game, seat: Option<usize>) -> Value {
let seat = seat.filter(|i| *i < game.players.len() && game.player(*i).is_human());
let active = game.active_player();
let playing = game.state == GameState::Playing && game.events.is_empty();
let objective_phase = game.events.last().is_some_and(|event| {
matches!(event.event_type, PersistentEventType::SelectObjectives(_))
&& matches!(
game.current_event_handler().map(|h| &h.request),
Some(PersistentEventRequest::SelectHandCards(_))
)
});
let supported_phase = playing || objective_phase;
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,
"score": p.victory_points(game),
"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});
};
let p = game.player(seat);
// Hidden cards use ID zero in the player-filtered state; never resolve them.
let objective_cards = p
.objective_cards
.iter()
.filter(|id| **id != 0)
.map(|id| {
let card = game.cache.get_objective_card(*id);
json!({"id": card.id, "objectives": card.objectives.iter().map(|objective| json!({
"name": objective.name,
"description": objective.description,
"timing": match objective.get_type() {
ObjectiveType::Instant => "Instant",
ObjectiveType::StatusPhase => "Status phase",
}
})).collect::<Vec<_>>()})
})
.collect::<Vec<_>>();
let collect_type = PlayingActionType::Collect;
let collect_reason = collect_type.is_available(game, seat).err();
let origin = collect_event_origin(&collect_type, p);
let cities = p.cities.iter().map(|city| {
let info = possible_resource_collections(game, city.position, seat, &origin, CostTrigger::NoModifiers);
let mut choices = info.choices.iter().flat_map(|(position, piles)| piles.iter().map(move |pile| json!({"position":position,"pile":pile}))).collect::<Vec<_>>();
choices.sort_by_key(Value::to_string);
let reason = if !can_play { Some("Wait for your turn".to_string()) } else if !city.can_activate() { Some("This city has already been activated while angry".to_string()) } else { collect_reason.clone() };
json!({"position":city.position,"size":city.size(),"capacity":info.max_selection,"maxPerTile":info.max_per_tile,"maxRange2":info.max_range2_tiles,"mood":city.mood_state,"activations":city.activations,"reason":reason,"choices":choices})
}).collect::<Vec<_>>();
let mut advances = game.cache.get_advances().iter().map(|(advance, info)| {
let cost = p.advance_cost(*advance, game, CostTrigger::NoModifiers).cost;
let payment = cost.first_valid_payment(&p.resources);
let owned = p.has_advance(*advance);
let reason = if owned { Some("Already researched".to_string()) }
else if !can_play { Some("Wait for your turn".to_string()) }
else if let Err(reason) = PlayingActionType::Advance.is_available(game, seat) { Some(reason) }
else if let Some(required) = info.required.filter(|a| !p.has_advance(*a)) { Some(format!("Requires {}", required.name(game))) }
else if !p.can_advance_free(*advance, game) { Some("Conflicts with your current advances".to_string()) }
else if payment.is_none() { Some("Not enough resources".to_string()) } else { None };
let action = if reason.is_none() { payment.clone().map(|payment| Action::Playing(PlayingAction::Advance(AdvanceAction::new(*advance, payment)))) } else { None };
let group = game.cache.get_advance_groups().iter().enumerate().find_map(|(group_index, group)| {
group.advances.iter().position(|a| a.advance == *advance).map(|index| (group.name.clone(), group_index * 10 + index))
});
json!({"id":advance,"name":info.name,"description":info.description,"owned":owned,"reason":reason,"payment":payment.unwrap_or_else(|| cost.default_payment()),"action":action,
"group":group.as_ref().map(|g| &g.0),"order":group.as_ref().map(|g| g.1),"required":info.required,
"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()})
}
fn objective_decision(game: &Game, seat: usize) -> Option<Value> {
let event = game.events.last()?;
if seat != event.player.index {
return None;
}
let PersistentEventType::SelectObjectives(info) = &event.event_type else {
return None;
};
let name = info.shown_objective.as_ref()?;
let handler = game.current_event_handler()?;
let PersistentEventRequest::SelectHandCards(request) = &handler.request else {
return None;
};
if handler.response.is_some() || !request.needed.contains(&1) {
return None;
}
let cards = request.choices.iter().filter_map(|card| {
let HandCard::ObjectiveCard(id) = card else { return None; };
if *id == 0 || !game.player(seat).objective_cards.contains(id) { return None; }
let info = game.cache.get_objective_card(*id);
Some(json!({"id":id,"name":info.name(),"action":Action::Response(EventResponse::SelectHandCards(vec![card.clone()]))}))
}).collect::<Vec<_>>();
let skip = request
.needed
.contains(&0)
.then(|| Action::Response(EventResponse::SelectHandCards(vec![])));
Some(
json!({"name":name,"description":game.cache.get_objective(name).description,"points":OBJECTIVE_VICTORY_POINTS,"cards":cards,"skip":skip}),
)
}
pub fn collect_preview(
game: &Game,
seat: usize,
city: Position,
selections: Vec<PositionCollection>,
) -> Result<Value, String> {
if seat >= game.players.len() || !game.player(seat).is_human() || seat != game.active_player() {
return Err("Wait for your turn".to_string());
}
PlayingActionType::Collect.is_available(game, seat)?;
let p = game.player(seat);
let city_data = p.try_get_city(city).ok_or("Choose one of your cities")?;
if !city_data.can_activate() {
return Err("This city cannot be activated again this turn".to_string());
}
if selections.iter().any(|c| c.times == 0) {
return Err("Choose at least one resource".to_string());
}
let origin = collect_event_origin(&PlayingActionType::Collect, p);
let total = get_total_collection(
game,
seat,
&origin,
city,
&selections,
CostTrigger::NoModifiers,
)?
.total;
let mut after = p.resources.clone() + total.clone();
let waste = after.apply_resource_limit(&p.resource_limit);
let action = Action::Playing(PlayingAction::Collect(Collect::new(
city,
selections,
PlayingActionType::Collect,
)));
Ok(
json!({"action":action,"total":total,"waste":waste,"after":after,"moodWillDecrease":city_data.is_activated()}),
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{game::GameOptions, game_api, resource_pile::ResourcePile};
fn game() -> Game {
game_api::init(2, "web-view-test".into(), GameOptions::default())
}
#[test]
fn spectators_and_waiting_players_have_no_actions() {
let game = game();
assert_eq!(view(&game, None)["canPlay"], false);
assert_eq!(view(&game, Some(99))["cities"], json!([]));
let waiting = view(&game, Some(1 - game.active_player()));
assert_eq!(waiting["canPlay"], false);
assert!(
waiting["advances"]
.as_array()
.unwrap()
.iter()
.all(|a| a["action"].is_null())
);
}
#[test]
fn collect_preview_uses_rules_and_does_not_mutate_state() {
let game = game();
let before = serde_json::to_string(&game.cloned_data()).unwrap();
let seat = game.active_player();
let city = game.player(seat).cities[0].position;
let preview = collect_preview(
&game,
seat,
city,
vec![PositionCollection::new(city, ResourcePile::food(1))],
)
.unwrap();
let action: Action = serde_json::from_value(preview["action"].clone()).unwrap();
assert!(crate::action::try_execute_action(game.clone(), action, seat).is_ok());
assert_eq!(before, serde_json::to_string(&game.cloned_data()).unwrap());
assert!(collect_preview(&game, 1 - seat, city, vec![]).is_err());
assert!(
collect_preview(
&game,
seat,
city,
vec![PositionCollection::new(city, ResourcePile::gold(7))]
)
.is_err()
);
}
}

2
web-client/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
.engine/
public/engine/

View file

@ -0,0 +1,8 @@
{
"plugins": ["prettier-plugin-svelte"],
"printWidth": 110,
"useTabs": false,
"tabWidth": 2,
"singleQuote": true,
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}

60
web-client/README.md Normal file
View file

@ -0,0 +1,60 @@
# 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.
## Run locally
Requirements: Node 24+, Rust with `wasm32-unknown-unknown`, and `wasm-bindgen-cli` matching Cargo.lock (currently 0.2.100).
```sh
cd web-client
npm ci
npm run build:bridge
npm run dev
```
Open http://127.0.0.1:8643. The preview binds to loopback and saves its disposable game under `.engine/preview-state.json`. **New game** resets that game and its local chat. Hotseat follows the active player; the player selector also supports fixed seats and spectators.
No production games, catalog records, or chat rooms are modified. Remaining actions and phases will be implemented in this interface.
## Implemented slice
- Procedural 3D terrain, cities, settlers, tile selection, orbit/zoom, and a top-down view.
- Named resources, storage limits, player scores, action count, city mood, and a short field guide.
- Private objective hand with both alternative conditions and their completion timing, read from the Rust definitions. When the engine offers an eligible objective, the player can claim points or keep the card directly in the action panel.
- 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.
- 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.
The preview host uses a real iframe and `postMessage` to exchange BGS events. Its chat is local test data, not a connection to a live BGS room. Production BGS integration still needs a staging playtest.
## Build and verify
```sh
npm run check
npm test
npm run build
# From repository root:
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.
## 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.
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.
## 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.
`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.

View file

@ -0,0 +1,29 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Clash 3D · production bundle</title>
</head>
<body>
<div id="app"></div>
<script src="/bundle/viewer.js"></script>
<script type="module">
import { uplinkSchemas } from '/node_modules/@boardgamers/protocol/dist/contracts.js';
const transport = window.clash3d.launch('#app');
for (const event of Object.keys(uplinkSchemas))
transport.on(event, (payload) =>
parent.postMessage({ source: 'clash-viewer', event, payload }, location.origin),
);
addEventListener('message', (event) => {
if (
event.source === parent &&
event.origin === location.origin &&
event.data?.source === 'clash-host'
)
transport.receive(event.data.event, event.data.payload);
});
parent.postMessage({ source: 'clash-viewer', event: 'mounted' }, location.origin);
</script>
</body>
</html>

69
web-client/classic.html Normal file
View file

@ -0,0 +1,69 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Clash · Classic controls</title>
<style>
body {
margin: 0;
font: 12px system-ui;
}
header {
height: 35px;
padding: 0 15px;
display: flex;
align-items: center;
gap: 20px;
background: #233d35;
color: #fff;
}
a {
color: #fff;
}
canvas {
display: block;
width: 100vw;
height: calc(100vh - 35px);
}
#error {
color: #9b241d;
}
</style>
</head>
<body>
<header>
<a href="/">← Return to 3D view</a><span>Classic controls · same local game</span
><span id="status"></span>
</header>
<canvas id="glcanvas"></canvas>
<div id="error"></div>
<script src="https://not-fl3.github.io/miniquad-samples/mq_js_bundle.js"></script>
<script src="/legacy/client-scroll-dacf9577a4c1c430.js"></script>
<script>
const control = clash.launch('#glcanvas');
let seat,
revision = -1;
async function refresh() {
const data = await (await fetch('/api/state')).json();
seat = data.seat;
revision = data.revision;
control.emit('player', { index: seat });
control.emit('state', data.state);
document.getElementById('status').textContent = 'Player ' + (seat + 1);
}
control.on('ready', refresh);
control.on('fetchState', refresh);
control.emit('preferences', { locale: 'en', ui_scale: '0.8' });
control.on('move', async (move) => {
const response = await fetch('/api/move', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ move, seat, revision }),
});
if (!response.ok) document.getElementById('error').textContent = (await response.json()).error;
await refresh();
});
</script>
</body>
</html>

101
web-client/index.html Normal file
View file

@ -0,0 +1,101 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Clash of Cultures</title>
<style>
html,
body {
margin: 0;
height: 100%;
background: #f7f3e8;
}
#preview-bar {
height: 35px;
background: #233d35;
color: #d8decb;
font: 10px system-ui;
display: flex;
align-items: center;
gap: 14px;
padding: 0 16px;
box-sizing: border-box;
}
#preview-bar strong {
font-weight: 500;
letter-spacing: 0.3px;
}
#preview-bar button,
#preview-bar select,
#preview-bar a {
font: 10px system-ui;
background: #ffffff12;
color: #e4e8d9;
border: 1px solid #ffffff20;
padding: 3px 8px;
border-radius: 3px;
cursor: pointer;
text-decoration: none;
}
#preview-bar select option {
color: #222;
background: #eee;
}
#preview-bar #status {
margin-left: auto;
font-size: 9px;
opacity: 0.7;
}
iframe {
display: block;
width: 100%;
height: calc(100% - 35px);
border: 0;
}
#host-error {
position: fixed;
top: 45px;
left: 50%;
transform: translateX(-50%);
background: #fff0de;
color: #a44f2e;
z-index: 10;
padding: 12px;
font: 12px system-ui;
border: 1px solid #ca9d66;
border-radius: 5px;
}
#host-error:empty {
display: none;
}
@media (max-width: 650px) {
#preview-bar {
gap: 7px;
padding: 0 8px;
}
#preview-bar strong {
font-size: 9px;
}
#status {
display: none;
}
}
</style>
</head>
<body>
<div id="preview-bar">
<strong>Design preview</strong
><select id="seat" aria-label="Preview player">
<option value="auto">Hotseat</option>
<option value="0">Player 1</option>
<option value="1">Player 2</option>
<option value="spectator">Spectator</option></select
><button id="reset">New game</button><button id="theme">Theme</button
><span id="status">Connecting to local game…</span>
</div>
<div id="host-error" role="alert"></div>
<iframe title="Clash of Cultures" src="/viewer.html"></iframe>
<script type="module" src="/src/local-host.ts"></script>
</body>
</html>

1643
web-client/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

29
web-client/package.json Normal file
View file

@ -0,0 +1,29 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1 --port 8643",
"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"
},
"dependencies": {
"@boardgamers/protocol": "0.6.1",
"lucide-svelte": "^0.468.0",
"svelte": "^5.0.0",
"three": "^0.180.0"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^6.0.0",
"@types/node": "^24.0.0",
"@types/three": "^0.180.0",
"prettier": "^3.9.9",
"prettier-plugin-svelte": "^4.1.1",
"svelte-check": "^4.0.0",
"typescript": "^5.9.0",
"vite": "^7.0.0"
}
}

View file

@ -0,0 +1,7 @@
#!/usr/bin/env bash
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 nodejs --out-dir web-client/.engine
printf '{"type":"commonjs"}\n' > web-client/.engine/package.json

View file

@ -0,0 +1,144 @@
import { createRequire } from 'node:module';
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import type { Plugin } from 'vite';
const require = createRequire(import.meta.url);
export function previewApi(): Plugin {
return {
name: 'clash-local-preview',
configureServer(server) {
const engine = require(fileURLToPath(new URL('../.engine/server.js', import.meta.url)));
const save = fileURLToPath(new URL('../.engine/preview-state.json', import.meta.url));
let state: string;
let revision = 0;
let messages: any[] = [];
let readAt: Record<string, number> = {};
const persist = () => writeFileSync(save, JSON.stringify({ state, revision, messages, readAt }));
const reset = async () => {
state = await engine.init(
2,
[],
{ undo: 'SamePlayer', civilization: 'Random' },
'clash-preview-20260927',
{},
);
for (let i = 0; i < 2; i++)
state = engine.setPlayerMetaData(state, i, { name: ['Leif', 'Aurelia'][i] });
revision++;
messages = [];
readAt = {};
persist();
};
const ready = (async () => {
if (existsSync(save)) {
const saved = JSON.parse(readFileSync(save, 'utf8'));
state = saved.state;
revision = saved.revision;
messages = saved.messages;
readAt = saved.readAt ?? {};
engine.webView(state, engine.currentPlayer(state));
} else await reset();
})();
server.middlewares.use(async (req, res, next) => {
const url = new URL(req.url ?? '/', 'http://127.0.0.1:8643');
if (url.pathname.startsWith('/bundle/')) {
const asset = url.pathname.slice(8);
if (!['viewer.js', 'engine/server.js', 'engine/server_bg.wasm'].includes(asset)) {
res.statusCode = 404;
res.end();
return;
}
try {
res.setHeader('content-type', asset.endsWith('.wasm') ? 'application/wasm' : 'text/javascript');
res.end(readFileSync(fileURLToPath(new URL('../dist/' + asset, import.meta.url))));
} catch {
res.statusCode = 404;
res.end('Build the viewer first');
}
return;
}
if (!url.pathname.startsWith('/api/') && !url.pathname.startsWith('/legacy/')) return next();
try {
if (url.pathname.startsWith('/legacy/')) {
const base =
'https://s3.fr-par.scw.cloud/bgs-assets/games/clash/1/viewer/locales-b2602be75e79cd1b/';
const response = await fetch(new URL(url.pathname.slice(8), base));
res.writeHead(response.status, {
'content-type': response.headers.get('content-type') ?? 'application/octet-stream',
});
res.end(Buffer.from(await response.arrayBuffer()));
return;
}
await ready;
res.setHeader('content-type', 'application/json');
res.setHeader('cache-control', 'no-store');
let body: any = {};
if (req.method === 'POST') {
if (req.headers.origin && req.headers.origin !== `http://${req.headers.host}`) {
res.writeHead(403).end('{}');
return;
}
let text = '';
for await (const chunk of req) {
text += chunk;
if (text.length > 100000) throw Error('Request too large');
}
body = JSON.parse(text || '{}');
}
if (url.pathname === '/api/reset' && req.method === 'POST') await reset();
if (url.pathname === '/api/move' && req.method === 'POST') {
if (body.revision !== revision) throw Error('The game changed. Please choose your action again.');
if (!Number.isInteger(body.seat) || body.seat !== engine.currentPlayer(state))
throw Error('It is not your turn.');
state = engine.tryMove(
state,
typeof body.move === 'string' ? body.move : JSON.stringify(body.move),
body.seat,
);
revision++;
persist();
}
if (url.pathname === '/api/chat' && req.method === 'POST') {
if (body.seat !== 0 && body.seat !== 1)
throw Error('Spectators cannot send messages in this preview.');
if (typeof body.text !== 'string' || !body.text.trim() || body.text.length > 5000)
throw Error('Enter a message under 5000 characters.');
const createdAt = new Date().toISOString();
messages.push({
_id: crypto.randomUUID().replaceAll('-', '').slice(0, 24),
text: body.text.trim(),
author: ['Leif', 'Aurelia'][body.seat],
authorId: `preview-${body.seat}`,
playerIndex: body.seat,
createdAt,
type: 'text',
});
persist();
}
if (url.pathname === '/api/read' && req.method === 'POST') {
if (body.seat !== 0 && body.seat !== 1) throw Error('Unknown player');
const message = messages.find((m) => m._id === body.messageId);
if (message) readAt[body.seat] = Math.max(readAt[body.seat] ?? 0, Date.parse(message.createdAt));
persist();
}
const active = engine.currentPlayer(state);
const requested = url.searchParams.get('seat');
const seat =
requested === 'spectator' ? undefined : requested === '0' ? 0 : requested === '1' ? 1 : active;
res.end(
JSON.stringify({
state: engine.stripSecret(state, seat),
seat,
revision,
messages,
lastReadAt: readAt[String(seat)] ?? 0,
}),
);
} catch (error) {
res.statusCode = 400;
res.end(JSON.stringify({ error: String(error) }));
}
});
},
};
}

607
web-client/src/App.svelte Normal file
View file

@ -0,0 +1,607 @@
<script lang="ts">
import { onMount } from 'svelte';
import {
Landmark,
Compass,
Wheat,
Trees,
Mountain,
Lightbulb,
Coins,
Smile,
Drama,
BookOpen,
ScrollText,
MessageCircle,
ArrowRight,
ArrowLeft,
Check,
Plus,
Minus,
Maximize,
Layers,
Trophy,
Flag,
X,
ChevronRight,
Hourglass,
Undo2,
GraduationCap,
Target,
MapPin,
Hammer,
Footprints,
Users,
Swords,
} from 'lucide-svelte';
import { mountChat } from '@boardgamers/protocol/chat/dom';
import { World } from './board';
import ResearchTree from './ResearchTree.svelte';
import type { Controller } from './controller';
import type { Resource } from './types';
import { resources, resourceNames, playerColors } from './types';
import { journal, journalParts, pileText } from './model';
let { controller }: { controller: Controller } = $props();
const session = $derived(controller.session);
let boardHost: HTMLDivElement;
let world: World;
let boardError = $state('');
let confirmEnd = $state(false);
const icons = {
food: Wheat,
wood: Trees,
ore: Mountain,
ideas: Lightbulb,
gold: Coins,
mood_tokens: Smile,
culture_tokens: Drama,
};
const journalIcons = {
setup: Landmark,
collect: Wheat,
research: GraduationCap,
objective: Target,
'end-turn': Flag,
move: Footprints,
build: Hammer,
recruit: Users,
combat: Swords,
card: Layers,
event: ScrollText,
};
let current = $derived($session.game?.players.find((p) => p.id === $session.seat));
let city = $derived($session.view?.cities.find((c) => c.position === $session.city));
let identity = $derived($session.view?.players.find((p) => p.index === $session.seat));
let log = $derived($session.game ? journal($session.game) : []);
let totalActions = $derived($session.game?.actions_left ?? 0);
let objectiveDecision = $derived($session.view?.objectiveDecision);
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`,
);
onMount(() => {
try {
world = new World(boardHost, (p) => controller.selectTile(p));
const off = session.subscribe((s) => world.update(s));
return () => {
off();
world.destroy();
};
} catch (e) {
boardError =
'The 3D map could not start on this device. You can still select your city and collect resources with the controls.';
}
});
function chatPanel(node: HTMLElement) {
const panel = mountChat(node, {
chat: controller.chat,
openPlayer: controller.commands.openPlayer,
labels: {
title: 'Chat',
empty: 'No messages yet.',
placeholder: 'Message…',
},
});
controller.chat.setOpen($session.activityOpen && $session.tab === 'chat');
return { destroy: () => panel.destroy() };
}
function showDialog(node: HTMLDialogElement) {
node.showModal();
return { destroy: () => node.close() };
}
function closeHelp() {
controller.patch({ help: false });
}
function closeAction() {
confirmEnd = false;
controller.patch({ mode: 'overview', selection: [], preview: null, error: '' });
}
function openResearch() {
confirmEnd = false;
controller.closeActivity();
controller.patch({ mode: 'research', selectedAdvance: null, error: '' });
}
function toggleActivity(tab: 'journal' | 'chat') {
confirmEnd = false;
if ($session.activityOpen && $session.tab === tab) controller.closeActivity();
else controller.setTab(tab);
}
function closeObjectives() {
controller.patch({ objectivesOpen: false });
}
</script>
<div class:dark={$session.dark} class:colorblind={$session.colorBlind} class="game-shell">
<header class="masthead">
<button
class="brand"
onclick={() => controller.commands.openBoardgame()}
aria-label="About Clash of Cultures"><span class="brand-name">Clash <i>of</i> Cultures</span></button
>
<div class="age-track" aria-label={`Age ${$session.game?.age ?? 1} of 6`}>
<span>THE AGES</span>{#each [1, 2, 3, 4, 5, 6] as age}<span
class:current={age === ($session.game?.age ?? 1)}
class:past={age < ($session.game?.age ?? 1)}>{['I', 'II', 'III', 'IV', 'V', 'VI'][age - 1]}</span
>{/each}
</div>
<nav class="header-actions">
{#if $session.seat !== undefined}
<button
class="text-button objectives-button"
aria-label={`Objectives: ${$session.view?.objectiveCards?.length ?? 0} ${$session.view?.objectiveCards?.length === 1 ? 'card' : 'cards'}`}
onclick={() => controller.patch({ objectivesOpen: true })}
><Target size={17} /> Objectives
<span class="card-count">{$session.view?.objectiveCards?.length ?? 0}</span></button
>
{/if}
<button class="text-button" onclick={() => controller.patch({ help: true })}
><BookOpen size={17} /> How to play</button
>
</nav>
</header>
<section class="resource-bar" aria-label="Your resources">
<div class="civilization-tag">
<span class="tiny-label">{$session.seat === undefined ? 'THE TABLE' : 'YOUR CIVILIZATION'}</span><strong
>{identity?.civilization ?? 'Spectator'}</strong
>
</div>
{#each resources as resource}{@const Icon = icons[resource]}
<div
class="resource"
title={`${resourceNames[resource]}${current?.resource_limit?.[resource] !== undefined ? ` · Storage limit ${current.resource_limit[resource]}` : ''}`}
>
<span class="resource-icon {resource}"><Icon size={21} strokeWidth={1.65} /></span><span
><small>{resourceNames[resource]}</small><strong
>{current
? (current.resources?.[resource] ?? 0)
: '—'}{#if current?.resource_limit?.[resource] !== undefined}<em>
/ {current.resource_limit[resource]}</em
>{/if}</strong
></span
>
</div>{/each}
<div class="round-label">
{#if ($session.game?.round ?? 1) > 3}
<span class="tiny-label">AGE END</span><strong class="status-label">Status</strong>
{:else}
<span class="tiny-label">ROUND</span><strong>{$session.game?.round ?? 1} <span>/ 3</span></strong>
{/if}
</div>
</section>
<main class="play-layout">
<section class="map-section" aria-label="The civilization map">
<div class="map-world" bind:this={boardHost}></div>
<div class="map-vignette"></div>
<div class="player-list" aria-label="Civilizations">
{#each $session.view?.players ?? [] as player}<button
class="player-card"
class:active={player.index === $session.view?.activePlayer}
style={`--player:${playerColors[player.index]}`}
onclick={() => controller.commands.openPlayer(player.index)}
onmouseenter={(e) => {
const r = e.currentTarget.getBoundingClientRect();
controller.commands.hoverPlayer(player.index, {
x: r.x,
y: r.y,
width: r.width,
height: r.height,
});
}}
onmouseleave={() => controller.commands.leavePlayer()}
onfocus={() => {}}
onblur={() => controller.commands.leavePlayer()}
>
<span class="player-emblem"
>{#if $session.avatars[player.index]}<img
src={$session.avatars[player.index]}
alt=""
/>{:else}<Landmark size={18} />{/if}</span
><span class="player-info"
><strong>{player.civilization}</strong><small
>{player.index === $session.seat ? 'You' : player.name}</small
></span
><span class="player-score">{player.score}<Trophy size={10} /></span
>{#if player.index === $session.view?.activePlayer}<span class="active-dot" title="Current player"
></span>{/if}
</button>{/each}
</div>
{#if !$session.game}<div class="map-loading">
<Compass size={30} />
<h2>Loading game…</h2>
</div>{/if}
{#if boardError}<div class="map-warning" role="alert">{boardError}</div>{/if}
{#if $session.focus && $session.focus !== $session.city && typeof focusTerrain === 'string'}<div
class="tile-inspector"
>
<button
aria-label="Close terrain details"
onclick={() => controller.patch({ focus: $session.city })}><X size={12} /></button
><span class="tiny-label">TILE {$session.focus}</span><strong
>{focusTerrain === 'Unexplored'
? 'Unexplored'
: focusTerrain === 'Fertile'
? 'Fertile land'
: focusTerrain}</strong
>
<p>
{focusTerrain === 'Unexplored'
? 'Move a unit here to reveal the terrain.'
: focusTerrain === 'Forest'
? 'Collect wood here from a nearby city.'
: focusTerrain === 'Mountain'
? 'Collect ore here from a nearby city.'
: focusTerrain === 'Fertile'
? 'Collect food here from a nearby city.'
: focusTerrain === 'Water'
? 'Coastal waters. Fishing unlocks food collection.'
: 'Barren terrain. Some advances unlock new ways to use it.'}
</p>
</div>{/if}
<div class="map-controls">
<button title="Zoom in" aria-label="Zoom in" onclick={() => world?.zoom(0.84)}
><Plus size={18} /></button
><button title="Zoom out" aria-label="Zoom out" onclick={() => world?.zoom(1.18)}
><Minus size={18} /></button
><span></span><button
title="Toggle top-down view"
aria-label="Toggle top-down view"
aria-pressed={$session.topDown}
onclick={() => controller.patch({ topDown: !$session.topDown })}><Layers size={18} /></button
><button title="Reset camera" aria-label="Reset camera" onclick={() => world?.reset()}
><Maximize size={17} /></button
>
</div>
{#if $session.mode === 'collect'}<div class="map-instruction">
<Wheat size={17} /><span>Choose up to <strong>{city?.capacity}</strong> highlighted tiles</span
><span class="instruction-count">{$session.selection.length} / {city?.capacity}</span>
</div>{/if}
<div class="city-dock">
<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)}
><span class="city-thumb"><Landmark size={25} /></span><span
><strong
>{identity?.civilization}
{c.position === $session.view?.cities[0]?.position ? 'Capital' : 'City'}</strong
><small>{c.position} <span>·</span> Size {c.size} <span>·</span> {c.mood}</small></span
><ChevronRight size={16} /></button
>{/each}
</div>
</section>
<div class="board-toolbar" aria-label="Game controls">
<div class="turn-banner">
<span class="turn-light"></span><strong>{actionTitle}</strong
>{#if !objectiveDecision && ($session.game?.round ?? 1) <= 3}<small
>{totalActions} {totalActions === 1 ? 'action' : 'actions'} left</small
>{/if}
</div>
<nav class="board-actions" aria-label="Actions">
<button
class:active={$session.mode === 'collect'}
title={city?.reason ?? 'Collect resources · 1 action'}
aria-label="Collect resources"
disabled={!$session.view?.canPlay || !city || !!city.reason || $session.pending}
onclick={() => {
confirmEnd = false;
controller.beginCollect();
}}><Wheat size={21} /><span>Collect</span></button
>
<button
class:active={$session.mode === 'research'}
title="Research tree"
aria-label="Research tree"
disabled={$session.seat === undefined}
onclick={openResearch}><GraduationCap size={21} /><span>Research</span></button
>
<button
title="Undo last action"
aria-label="Undo last action"
disabled={!$session.view?.canUndo || $session.pending}
onclick={() => controller.submit('Undo')}><Undo2 size={19} /><span>Undo</span></button
>
<button
class:active={confirmEnd}
title="End turn"
aria-label="End turn"
disabled={!$session.view?.canEndTurn || $session.pending}
onclick={() => {
controller.closeActivity();
controller.patch({ mode: 'overview' });
if (totalActions) confirmEnd = !confirmEnd;
else controller.submit({ Playing: 'EndTurn' });
}}><Flag size={19} /><span>End turn</span></button
>
</nav>
</div>
<nav class="table-tools" aria-label="Table panels">
<button
class:active={$session.activityOpen && $session.tab === 'journal'}
title="Journal"
aria-label="Open journal"
aria-expanded={$session.activityOpen && $session.tab === 'journal'}
onclick={() => toggleActivity('journal')}><ScrollText size={19} /><span>Journal</span></button
>
<button
class:active={$session.activityOpen && $session.tab === 'chat'}
title="Chat"
aria-label="Open chat"
aria-expanded={$session.activityOpen && $session.tab === 'chat'}
onclick={() => toggleActivity('chat')}
><MessageCircle size={19} /><span>Chat</span>{#if $session.unread}<span class="unread"
>{$session.unread}</span
>{/if}</button
>
</nav>
{#if objectiveDecision || ($session.game && !$session.view?.supportedPhase && $session.seat === $session.view?.activePlayer) || $session.mode === 'collect' || confirmEnd || $session.error}
<section class="action-panel floating-panel" aria-label="Current action">
{#if !objectiveDecision && $session.view?.supportedPhase}<button
class="icon-button close-action"
aria-label="Close action"
onclick={closeAction}><X size={18} /></button
>{/if}
{#if objectiveDecision}
<h2>{objectiveDecision.name}</h2>
<p>{objectiveDecision.description}</p>
{#each objectiveDecision.cards as card (card.id)}
<div class="objective-claim">
<small>Card: {card.name.replaceAll('/', ' / ')}</small>
<button
class="primary wide"
disabled={$session.pending}
onclick={() => controller.submit(card.action)}
>
Claim {objectiveDecision.points} points <Check size={17} />
</button>
</div>
{/each}
<p class="claim-note">Claiming discards the card, including its other objective.</p>
{#if objectiveDecision.skip}
<button
class="secondary wide"
disabled={$session.pending}
onclick={() => objectiveDecision?.skip && controller.submit(objectiveDecision.skip)}
>Keep card</button
>
{/if}
{:else if !$session.view?.supportedPhase && $session.game}
<h2>Decision not available yet</h2>
<p>The controls for this phase are still being built.</p>
{:else if $session.mode === 'collect'}
<h2>Collect resources</h2>
<p>
Your {city?.mood.toLowerCase()} city can gather from up to <b>{city?.capacity} tiles</b>. Choose
on the map or below.
</p>
<div class="collection-choices">
{#each city?.choices ?? [] as choice}{@const resource = Object.keys(
choice.pile,
)[0] as Resource}{@const Icon = icons[resource] ?? Wheat}{@const selected =
$session.selection.some(
(c) =>
c.position === choice.position && JSON.stringify(c.pile) === JSON.stringify(choice.pile),
)}<button
class:selected
onclick={() => controller.toggleChoice(choice)}
disabled={$session.pending}
aria-pressed={selected}
><span class="choice-icon {resource}"><Icon size={21} /></span><span
><strong>{pileText(choice.pile)}</strong><small>Tile {choice.position}</small></span
><span class="choice-check"
>{#if selected}<Check size={14} />{:else}<Plus size={13} />{/if}</span
></button
>{/each}
</div>
{#if $session.preview}<div class="collection-summary">
<span>You will collect</span><strong>{pileText($session.preview.total)}</strong
>{#if Object.values($session.preview.waste).some((n) => n)}<small class="warning"
>Storage is full: {pileText($session.preview.waste)} will be lost.</small
>{/if}{#if $session.preview.moodWillDecrease}<small class="warning"
>Activating this city again lowers its mood.</small
>{/if}
</div>{/if}
<button
class="primary wide"
disabled={!$session.preview || $session.pending}
onclick={() => controller.collect()}
>{$session.pending ? 'Confirming…' : 'Collect resources'}<ArrowRight size={17} /></button
><span class="action-cost">Costs 1 action · Activates your city</span>
{:else if confirmEnd}
<h2>End turn?</h2>
<p>You have {totalActions} unused {totalActions === 1 ? 'action' : 'actions'}.</p>
<div class="end-confirm">
<button class="secondary" onclick={() => (confirmEnd = false)}>Keep playing</button><button
class="primary"
disabled={$session.pending}
onclick={() => {
confirmEnd = false;
controller.submit({ Playing: 'EndTurn' });
}}>End turn <ArrowRight size={16} /></button
>
</div>
{/if}
{#if $session.error}<p class="inline-error" role="alert">{$session.error}</p>{/if}
</section>
{/if}
<section
class="activity floating-panel"
hidden={!$session.activityOpen}
aria-label="Table activity panel"
>
<div class="activity-tabs" role="tablist" aria-label="Table activity">
<button
role="tab"
aria-selected={$session.tab === 'journal'}
class:active={$session.tab === 'journal'}
onclick={() => controller.setTab('journal')}><ScrollText size={16} /> Journal</button
><button
role="tab"
aria-selected={$session.tab === 'chat'}
class:active={$session.tab === 'chat'}
onclick={() => controller.setTab('chat')}
><MessageCircle size={16} /> Chat {#if $session.unread}<span class="unread">{$session.unread}</span
>{/if}</button
><button
class="icon-button close-activity"
aria-label="Close table activity"
onclick={() => controller.closeActivity()}><X size={17} /></button
>
</div>
<div class="journal" hidden={$session.tab !== 'journal'} role="tabpanel" aria-label="Journal">
{#each [...log].reverse() as entry}{@const EntryIcon = journalIcons[entry.kind]}
<article>
<span class="journal-symbol" aria-hidden="true"><EntryIcon size={15} /></span><small
>{entry.age === 0 ? 'SETUP' : `AGE ${entry.age} · ROUND ${entry.round}`}</small
>
{#if entry.setup}
<p class="journal-setup">
<strong>{entry.setup.player}</strong><span>· {entry.setup.civilization}</span
>{#if entry.setup.position}<span class="journal-position" title="Starting location"
><MapPin size={13} aria-hidden="true" /><span class="sr-only">Starts at </span>{entry
.setup.position}</span
>{/if}
</p>
{:else}
<p>
{#each journalParts(entry.text) as part}{#if part.resource}{@const ResourceIcon =
icons[part.resource]}<span class="journal-resource"
><ResourceIcon size={13} aria-hidden="true" />{part.text}</span
>{:else}{part.text}{/if}{/each}
</p>
{/if}
</article>{/each}{#if log.length === 0}<p>No actions yet.</p>{/if}
</div>
<div
class="chat-panel"
hidden={$session.tab !== 'chat'}
role="tabpanel"
aria-label="Chat"
use:chatPanel
></div>
</section>
</main>
{#if $session.mode === 'research'}<ResearchTree {controller} />{/if}
{#if $session.toast}<div class="toast" role="status"><Check size={16} />{$session.toast}</div>{/if}
{#if $session.objectivesOpen && $session.seat !== undefined}
<dialog
class="field-guide objectives-dialog"
aria-labelledby="objectives-title"
use:showDialog
onclose={closeObjectives}
onclick={(e) => {
if (e.target === e.currentTarget) closeObjectives();
}}
onkeydown={(e) => {
if (e.key === 'Escape') closeObjectives();
}}
>
<button class="close-guide icon-button" aria-label="Close objectives" onclick={closeObjectives}
><X size={20} /></button
>
<h2 id="objectives-title">Objectives</h2>
<p class="guide-intro">{identity?.civilization} · Private hand</p>
{#each $session.view?.objectiveCards ?? [] as card (card.id)}
<article
class="objective-card"
aria-label={`Objective card: ${card.objectives.map((o) => o.name).join(' / ')}`}
>
{#each card.objectives as objective, index}
{#if index > 0}<div class="objective-divider">or</div>{/if}
<section>
<div class="objective-title">
<h3>{objective.name}</h3>
<span>{objective.timing}</span>
</div>
<p>{objective.description}</p>
</section>
{/each}
</article>
{:else}
<p class="objectives-empty">No objective cards in your hand.</p>
{/each}
{#if $session.view?.objectiveCards?.length}
<p class="objectives-note">
Complete one objective per card for 2 points. When eligible, choose whether to claim it or keep the
card. Status phase objectives are checked at the end of an age.
</p>
{/if}
</dialog>
{/if}
{#if $session.help}<dialog
class="field-guide"
use:showDialog
onclose={closeHelp}
onclick={(e) => {
if (e.target === e.currentTarget) closeHelp();
}}
onkeydown={(e) => {
if (e.key === 'Escape') closeHelp();
}}
>
<button class="close-guide icon-button" aria-label="Close field guide" onclick={closeHelp}
><X size={20} /></button
>
<h2>How to play</h2>
<p class="guide-intro">Score the most points over six ages.</p>
<div class="guide-grid">
<article>
<Landmark />
<h3>Scoring</h3>
<p>
Each city piece is worth 1 point. Advances add ½ point each. Completed objectives and wonders can
add more.
</p>
</article>
<article>
<Hourglass />
<h3>Actions</h3>
<p>
Each turn gives you three actions. Collect resources, research, grow cities, recruit, move,
improve happiness, or influence another culture.
</p>
</article>
<article>
<Wheat />
<h3>Resources</h3>
<p>
Select your capital, then Collect resources. Fertile land gives food, forests give wood, and
mountains give ore.
</p>
</article>
<article>
<Smile />
<h3>City mood and storage</h3>
<p>
A happy city collects from more tiles. Activating a city again in the same turn lowers its mood.
Storage limits can make excess resources go to waste.
</p>
</article>
</div>
</dialog>{/if}
</div>

View file

@ -0,0 +1,200 @@
<script lang="ts">
import { tick } from 'svelte';
import {
X,
Search,
Check,
LockKeyhole,
ArrowRight,
Wheat,
Trees,
Mountain,
Lightbulb,
Coins,
Smile,
Drama,
Hammer,
BookOpen,
} from 'lucide-svelte';
import type { Controller } from './controller';
import { resourceNames, type Resource, type AdvanceView } from './types';
import { pileText } from './model';
import { groupIcons, researchPresentation } from './research';
let { controller }: { controller: Controller } = $props();
const session = $derived(controller.session);
let query = $state('');
let category = $state('All');
const resourceIcons = {
food: Wheat,
wood: Trees,
ore: Mountain,
ideas: Lightbulb,
gold: Coins,
mood_tokens: Smile,
culture_tokens: Drama,
};
let advances = $derived([...($session.view?.advances ?? [])].sort((a, b) => a.order - b.order));
let groups = $derived([...new Set(advances.map((a) => a.group))]);
let selected = $derived(advances.find((a) => a.id === $session.selectedAdvance));
let visibleGroups = $derived(
groups.filter(
(group) =>
(category === 'All' || group === category) && advances.some((a) => a.group === group && matches(a)),
),
);
function matches(advance: AdvanceView) {
return `${advance.name} ${advance.description} ${researchPresentation(advance).summary}`
.toLowerCase()
.includes(query.trim().toLowerCase());
}
function close() {
controller.patch({ mode: 'overview', selectedAdvance: null });
}
function open(node: HTMLDialogElement) {
node.showModal();
return { destroy: () => node.close() };
}
async function prerequisite(id: string) {
query = '';
category = 'All';
controller.patch({ selectedAdvance: id });
await tick();
document.getElementById(`research-${id}`)?.scrollIntoView({
block: 'nearest',
inline: 'nearest',
behavior: $session.reducedMotion ? 'instant' : 'smooth',
});
}
</script>
<dialog
class="research-dialog"
aria-labelledby="research-title"
use:open
onclose={close}
onclick={(e) => {
if (e.target === e.currentTarget) close();
}}
onkeydown={(e) => {
if (e.key === 'Escape') close();
}}
>
<header class="research-header">
<div>
<h2 id="research-title">Research</h2>
<p>Each advance scores ½ point. Branches unlock from their first advance.</p>
</div>
<label class="research-search"
><Search size={17} /><input
aria-label="Search research"
placeholder="Find an effect or advance…"
bind:value={query}
/></label
>
<button class="icon-button" aria-label="Close research" onclick={close}><X size={21} /></button>
</header>
<nav class="research-filters" aria-label="Research categories">
<button class:active={category === 'All'} onclick={() => (category = 'All')}>All advances</button>
{#each groups as group}{@const Icon = groupIcons[group] ?? BookOpen}<button
class:active={category === group}
onclick={() => (category = group)}><Icon size={15} />{group}</button
>{/each}
</nav>
<div class="research-tree" aria-label="Research tree">
{#each visibleGroups as group}{@const GroupIcon = groupIcons[group] ?? BookOpen}
<section class="research-branch" aria-label={group}>
<h3><GroupIcon size={18} />{group}</h3>
{#each advances.filter((a) => a.group === group) as advance, index}{@const presentation =
researchPresentation(advance)}{@const Icon = presentation.icon}{@const parent = advances.find(
(a) => a.id === advance.required,
)}
<article
id={`research-${advance.id}`}
class="research-node"
class:child={index > 0}
class:owned={advance.owned}
class:available={!!advance.action}
class:selected={selected?.id === advance.id}
class:search-muted={!!query.trim() && !matches(advance)}
>
{#if index === 0 && parent}<button
class="research-prerequisite"
onclick={() => prerequisite(parent.id)}
><ArrowRight size={12} /> Requires {parent.name}</button
>{/if}
<button
class="research-pick"
aria-label={`${advance.name}: ${presentation.summary}`}
aria-pressed={selected?.id === advance.id}
title={advance.description}
onclick={() => controller.patch({ selectedAdvance: advance.id })}
>
<span class="research-node-title"
><span class="advance-pictogram"><Icon size={21} /></span><strong>{advance.name}</strong
>{#if advance.owned}<Check
size={16}
aria-label="Researched"
/>{:else if !advance.action}<LockKeyhole
size={13}
aria-label={advance.reason ?? 'Unavailable'}
/>{/if}</span
>
<span class="research-summary">{presentation.summary}</span>
<span class="research-effects"
>{#if advance.unlocks}<span title={`Unlocks ${advance.unlocks}`}
><Hammer size={12} />{advance.unlocks}</span
>{/if}{#each Object.entries(advance.bonus ?? {}) as [resource, amount]}{@const BonusIcon =
resourceIcons[resource as Resource]}<span
title={`Research bonus: ${amount} ${resourceNames[resource as Resource]}`}
><BonusIcon size={12} />+{amount} {resourceNames[resource as Resource]}</span
>{/each}</span
>
<span class="research-node-cost"
>{#if advance.owned}<span class="researched-label">Researched</span
>{:else}{#each Object.entries(advance.payment) as [resource, amount]}{@const CostIcon =
resourceIcons[resource as Resource]}<span
><CostIcon size={13} />{amount} {resourceNames[resource as Resource]}</span
>{/each}{#if !Object.values(advance.payment).some(Boolean)}<span>No resources</span
>{/if}<span class="research-availability"
>{advance.action
? 'Available'
: parent && !advances.find((a) => a.id === parent.id)?.owned
? `Needs ${parent.name}`
: advance.reason}</span
>{/if}</span
>
</button>
</article>
{/each}
</section>
{:else}<p class="research-empty">No advances match “{query}”.</p>{/each}
</div>
{#if selected}
<section class="research-detail" aria-label="Research details">
<div>
<h3>{selected.name}</h3>
<p>{selected.description}</p>
{#if selected.bonus && Object.values(selected.bonus).some(Boolean)}<small
>Research bonus: {pileText(selected.bonus)}</small
>{/if}{#if selected.reason && !selected.owned}<small>{selected.reason}</small>{/if}
{#if $session.error}<p class="inline-error" role="alert">{$session.error}</p>{/if}
</div>
<button
class="primary"
disabled={!selected.action || $session.pending}
onclick={() => selected?.action && controller.submit(selected.action)}
>{$session.pending ? 'Confirming…' : selected.owned ? 'Researched' : `Research ${selected.name}`}
<span>{selected.owned ? '' : `${pileText(selected.payment)} · 1 action`}</span></button
>
<button
class="icon-button"
aria-label="Close research details"
onclick={() => controller.patch({ selectedAdvance: null })}><X size={18} /></button
>
</section>
{:else}<div class="research-legend">
<span><Check size={14} /> Researched</span><span class="available-key">Available</span><span
><LockKeyhole size={13} /> Unavailable</span
><span>Select an advance for its full rules and confirmation.</span>
</div>{/if}
</dialog>

463
web-client/src/board.ts Normal file
View file

@ -0,0 +1,463 @@
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import type { Session, Terrain } from './types';
import { playerColors } from './types';
import { positionXY } from './model';
const terrainColor: Record<string, string> = {
Forest: '#54755a',
Fertile: '#9aa36b',
Mountain: '#858c87',
Barren: '#b6a27c',
Water: '#438d95',
Unexplored: '#526f77',
};
export class World {
private scene = new THREE.Scene();
private camera = new THREE.PerspectiveCamera(36, 1, 0.1, 120);
private renderer: THREE.WebGLRenderer;
private controls: OrbitControls;
private board = new THREE.Group();
private rings = new THREE.Group();
private tiles = new Map<string, THREE.Mesh>();
private raycaster = new THREE.Raycaster();
private resize: ResizeObserver;
private frame = 0;
private dirty = true;
private lastSignature = '';
private selectionSignature = '';
private start = [0, 0];
private disposed = false;
private topDown = false;
private materials = new Set<THREE.Material>();
private geometries = new Set<THREE.BufferGeometry>();
private textures = new Set<THREE.Texture>();
private labelPositions: { position: string; at: THREE.Vector3; node: HTMLButtonElement }[] = [];
private labelHost: HTMLDivElement;
private center = new THREE.Vector3(4.5, 0, 8);
private material(color: string, roughness = 1) {
const mat = new THREE.MeshStandardMaterial({ color, roughness, flatShading: true });
this.materials.add(mat);
return mat;
}
private mesh(geo: THREE.BufferGeometry, mat: THREE.Material | THREE.Material[]) {
this.geometries.add(geo);
const obj = new THREE.Mesh(geo, mat);
obj.castShadow = true;
obj.receiveShadow = true;
return obj;
}
constructor(
private host: HTMLElement,
private pick: (position: string) => void,
) {
this.scene.background = new THREE.Color('#b1c7c0');
this.scene.fog = new THREE.Fog('#b1c7c0', 55, 105);
this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
this.renderer.setPixelRatio(Math.min(devicePixelRatio, 1.8));
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.05;
this.renderer.domElement.setAttribute(
'aria-label',
'3D civilization map. Select a city or terrain tile. Drag to orbit; scroll to zoom.',
);
this.renderer.domElement.setAttribute('role', 'img');
this.renderer.domElement.tabIndex = 0;
host.append(this.renderer.domElement);
this.labelHost = document.createElement('div');
this.labelHost.className = 'world-labels';
host.append(this.labelHost);
this.scene.add(new THREE.HemisphereLight('#fff4d8', '#386775', 2.2));
const sun = new THREE.DirectionalLight('#ffe0a7', 3.2);
sun.position.set(-9, 18, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 18;
sun.shadow.camera.bottom = -18;
sun.shadow.normalBias = 0.045;
this.scene.add(sun);
const water = this.mesh(new THREE.PlaneGeometry(150, 150), this.material('#679a9d', 0.4));
water.rotation.x = -Math.PI / 2;
water.position.y = -0.56;
water.receiveShadow = true;
this.scene.add(water);
const glintMat = this.material('#a1c1b8');
for (let i = 0; i < 130; i++) {
const x = Math.sin(i * 99.31) * 22 + 4.5,
z = Math.cos(i * 47.79) * 22 + 8;
const glint = this.mesh(new THREE.PlaneGeometry(0.12 + (i % 5) * 0.06, 0.018), glintMat);
glint.rotation.x = -Math.PI / 2;
glint.position.set(x, -0.535, z);
this.scene.add(glint);
}
this.scene.add(this.board, this.rings);
this.camera.position.set(17, 22, 25);
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
this.controls.target.copy(this.center);
this.controls.enableDamping = false;
this.controls.minDistance = 8;
this.controls.maxDistance = 55;
this.controls.maxPolarAngle = Math.PI * 0.43;
this.controls.minPolarAngle = 0.08;
this.controls.enablePan = true;
this.controls.update();
this.controls.addEventListener('change', () => this.invalidate());
this.renderer.domElement.addEventListener('pointerdown', this.down);
this.renderer.domElement.addEventListener('pointerup', this.up);
this.renderer.domElement.addEventListener('keydown', this.key);
this.resize = new ResizeObserver(() => {
const { width, height } = host.getBoundingClientRect();
if (!width || !height) return;
this.renderer.setSize(width, height);
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
this.controls.enableZoom = true;
this.controls.enableRotate = true;
this.controls.touches.ONE = THREE.TOUCH.ROTATE;
this.renderer.domElement.style.touchAction = 'none';
this.reset();
});
this.resize.observe(host);
}
private down = (e: PointerEvent) => {
this.start = [e.clientX, e.clientY];
};
private up = (e: PointerEvent) => {
if (Math.hypot(e.clientX - this.start[0], e.clientY - this.start[1]) > 5) return;
const rect = this.renderer.domElement.getBoundingClientRect();
this.raycaster.setFromCamera(
new THREE.Vector2(
((e.clientX - rect.left) / rect.width) * 2 - 1,
(-(e.clientY - rect.top) / rect.height) * 2 + 1,
),
this.camera,
);
const hit = this.raycaster.intersectObjects([...this.tiles.values()])[0];
if (hit) this.pick(hit.object.userData.position);
};
private key = (e: KeyboardEvent) => {
if (e.key === 'Home') this.reset();
else if (e.key === '+' || e.key === '=') this.zoom(0.85);
else if (e.key === '-') this.zoom(1.15);
else if (e.key.startsWith('Arrow')) {
e.preventDefault();
const offset = this.camera.position.clone().sub(this.controls.target);
offset.applyAxisAngle(
new THREE.Vector3(0, 1, 0),
e.key === 'ArrowLeft' ? 0.12 : e.key === 'ArrowRight' ? -0.12 : 0,
);
this.camera.position.copy(this.controls.target).add(offset);
this.controls.update();
this.invalidate();
}
};
private invalidate() {
if (this.disposed) return;
this.dirty = true;
if (this.frame) return;
this.frame = requestAnimationFrame(() => {
this.frame = 0;
if (!this.dirty) return;
this.dirty = false;
this.renderer.render(this.scene, this.camera);
const w = this.host.clientWidth,
h = this.host.clientHeight;
for (const label of this.labelPositions) {
const v = label.at.clone().project(this.camera);
label.node.style.transform = `translate(-50%, -50%) translate(${((v.x + 1) * w) / 2}px,${((-v.y + 1) * h) / 2}px)`;
label.node.style.display = v.z > 1 ? 'none' : '';
}
});
}
zoom(factor: number) {
const direction = this.camera.position.clone().sub(this.controls.target);
direction.multiplyScalar(factor).clampLength(8, 55);
this.camera.position.copy(this.controls.target).add(direction);
this.controls.update();
this.invalidate();
}
reset() {
this.controls.target.copy(this.center);
this.camera.position
.copy(this.center)
.add(
new THREE.Vector3(
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),
),
);
this.controls.update();
this.invalidate();
}
private building(color: string) {
const group = new THREE.Group();
const stone = this.material('#ead7ad'),
roof = this.material('#a86042');
const base = this.mesh(new THREE.BoxGeometry(0.83, 0.12, 0.66), stone);
base.position.y = 0.06;
group.add(base);
const hall = this.mesh(new THREE.BoxGeometry(0.54, 0.3, 0.4), stone);
hall.position.set(0, 0.26, 0);
group.add(hall);
const ridge = this.mesh(new THREE.CylinderGeometry(0.42, 0.42, 0.66, 3), roof);
ridge.rotation.z = Math.PI / 2;
ridge.rotation.x = Math.PI / 2;
ridge.position.y = 0.51;
group.add(ridge);
for (const x of [-0.25, -0.08, 0.09, 0.26]) {
const column = this.mesh(new THREE.CylinderGeometry(0.033, 0.04, 0.32, 7), stone);
column.position.set(x, 0.28, 0.29);
group.add(column);
}
for (let i = 0; i < 3; i++) {
const step = this.mesh(new THREE.BoxGeometry(0.68 + i * 0.08, 0.04, 0.16), stone);
step.position.set(0, 0.12 - i * 0.025, 0.37 + i * 0.06);
group.add(step);
}
const pole = this.mesh(new THREE.CylinderGeometry(0.015, 0.02, 0.85, 6), this.material('#624d30'));
pole.position.set(0.47, 0.5, -0.2);
group.add(pole);
const flag = this.mesh(new THREE.BoxGeometry(0.28, 0.18, 0.018), this.material(color));
flag.position.set(0.6, 0.84, -0.2);
group.add(flag);
return group;
}
private tree(x: number, z: number, scale: number, seed: number) {
const group = new THREE.Group();
const trunk = this.mesh(new THREE.CylinderGeometry(0.035, 0.055, 0.4, 5), this.material('#6b6042'));
trunk.position.y = 0.2;
group.add(trunk);
const green = this.material(['#355849', '#456d4f', '#637950'][seed % 3]);
for (let k = 0; k < 3; k++) {
const cone = this.mesh(new THREE.ConeGeometry(0.22 - k * 0.035, 0.45, 6), green);
cone.position.y = 0.39 + k * 0.18;
group.add(cone);
}
group.position.set(x, 0.12, z);
group.scale.setScalar(scale);
return group;
}
private addTerrain(group: THREE.Group, kind: string, seed: number) {
if (kind === 'Forest') {
for (let i = 0; i < 9; i++) {
const angle = i * 2.4;
const radius = 0.18 + 0.1 * (i % 5);
group.add(
this.tree(Math.cos(angle) * radius, Math.sin(angle) * radius, 0.75 + (i % 3) * 0.17, i + seed),
);
}
}
if (kind === 'Mountain') {
for (let i = 0; i < 3; i++) {
const height = [1.1, 0.8, 0.6][i];
const rock = this.mesh(
new THREE.ConeGeometry(0.45, height, 5),
this.material(['#82867a', '#999c8c', '#767d77'][i]),
);
rock.position.set((i - 1) * 0.32, height / 2 + 0.08, (i % 2) * 0.24 - 0.1);
rock.rotation.y = i;
group.add(rock);
const cap = this.mesh(new THREE.ConeGeometry(0.14, height * 0.28, 5), this.material('#eee9d7'));
cap.position.copy(rock.position);
cap.position.y = height * 0.87 + 0.08;
cap.rotation.y = i;
group.add(cap);
}
}
if (kind === 'Fertile') {
const fieldMat = this.material('#c6b968');
for (let i = 0; i < 5; i++) {
const furrow = this.mesh(new THREE.BoxGeometry(0.06, 0.035, 0.7), fieldMat);
furrow.position.set(-0.35 + i * 0.14, 0.12, 0.03);
furrow.rotation.y = 0.25;
group.add(furrow);
}
group.add(this.tree(0.55, -0.25, 0.5, seed));
}
if (kind === 'Barren') {
for (let i = 0; i < 7; i++) {
const rock = this.mesh(
new THREE.DodecahedronGeometry(0.09 + (i % 3) * 0.04, 0),
this.material('#c8b18b'),
);
rock.position.set(Math.sin(i * 8) * 0.65, 0.13, Math.cos(i * 5) * 0.6);
rock.scale.y = 0.5;
group.add(rock);
}
}
if (kind === 'Unexplored') {
const mat = this.material('#90aba5');
const circle = this.mesh(new THREE.TorusGeometry(0.22, 0.009, 4, 24), mat);
circle.rotation.x = -Math.PI / 2;
circle.position.y = 0.09;
group.add(circle);
for (let i = 0; i < 4; i++) {
const mark = this.mesh(new THREE.BoxGeometry(0.014, 0.012, 0.14), mat);
mark.position.set(Math.sin((i * Math.PI) / 2) * 0.26, 0.093, Math.cos((i * Math.PI) / 2) * 0.26);
mark.rotation.y = (i * Math.PI) / 2;
group.add(mark);
}
}
if (kind === 'Water') {
for (let i = 0; i < 4; i++) {
const line = this.mesh(new THREE.BoxGeometry(0.5 - i * 0.08, 0.018, 0.025), this.material('#96c9c1'));
line.position.set((i % 2) * 0.16, 0.07, (i - 2) * 0.19);
group.add(line);
}
}
}
private clearBoard() {
this.board.traverse((o) => {
if (o instanceof THREE.Mesh) {
o.geometry.dispose();
this.geometries.delete(o.geometry);
const mats = Array.isArray(o.material) ? o.material : [o.material];
mats.forEach((m) => {
m.dispose();
this.materials.delete(m);
});
}
});
this.board.clear();
this.tiles.clear();
this.labelHost.replaceChildren();
this.labelPositions = [];
}
update(s: Session) {
if (!s.game) return;
const signature = JSON.stringify([
s.game.map.tiles,
s.game.players.map((p) => [p.cities, p.units]),
s.view?.players,
s.seat,
]);
if (signature !== this.lastSignature) {
this.lastSignature = signature;
this.clearBoard();
const coords = s.game.map.tiles.map(([p]) => positionXY(p));
const minX = Math.min(...coords.map((c) => c[0])),
maxX = Math.max(...coords.map((c) => c[0])),
minZ = Math.min(...coords.map((c) => c[1])),
maxZ = Math.max(...coords.map((c) => c[1]));
this.center.set((minX + maxX) / 2, 0, (minZ + maxZ) / 2);
for (const [position, terrain] of s.game.map.tiles) {
const kind = typeof terrain === 'string' ? terrain : 'Barren';
const [x, z] = positionXY(position);
const height = kind === 'Water' ? 0.13 : kind === 'Unexplored' ? 0.27 : 0.43;
const group = new THREE.Group();
group.position.set(x, height / 2 - 0.12, z);
const top = this.material(terrainColor[kind]);
const side = this.material(
kind === 'Unexplored' ? '#4c7378' : kind === 'Water' ? '#4c8a91' : '#837655',
);
const hex = this.mesh(new THREE.CylinderGeometry(0.976, 0.98, height, 6), [side, top, side]);
hex.rotation.y = Math.PI / 6;
hex.userData.position = position;
group.add(hex);
this.tiles.set(position, hex);
const terrainGroup = new THREE.Group();
terrainGroup.position.y = height / 2;
this.addTerrain(terrainGroup, kind, position.charCodeAt(0));
group.add(terrainGroup);
this.board.add(group);
}
for (const player of s.game.players) {
for (const [i, city] of (player.cities ?? []).entries()) {
const [x, z] = positionXY(city.position);
const cityModel = this.building(playerColors[player.id] ?? '#bfa986');
cityModel.position.set(x, 0.38, z);
cityModel.rotation.y = 0.25;
this.board.add(cityModel);
const label = document.createElement('button');
label.className = 'city-map-label';
label.style.setProperty('--player-color', playerColors[player.id] ?? '#bfa986');
label.textContent = `${player.civilization} · ${i === 0 ? 'Capital' : city.position}`;
label.setAttribute('aria-label', `Select ${player.civilization} city ${city.position}`);
label.onclick = () => this.pick(city.position);
this.labelHost.append(label);
this.labelPositions.push({
position: city.position,
at: new THREE.Vector3(x, 1.85, z),
node: label,
});
}
for (const unit of player.units ?? []) {
const [x, z] = positionXY(unit.position);
const pawn = new THREE.Group();
const color = this.material(playerColors[player.id] ?? '#bfa986');
const body = this.mesh(new THREE.ConeGeometry(0.085, 0.27, 7), color);
body.position.y = 0.19;
pawn.add(body);
const head = this.mesh(new THREE.SphereGeometry(0.062, 8, 6), this.material('#e4c7a1'));
head.position.y = 0.39;
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);
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 available =
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;
this.rings.traverse((o) => {
if (o instanceof THREE.Mesh) {
o.geometry.dispose();
this.geometries.delete(o.geometry);
(o.material as THREE.Material).dispose();
this.materials.delete(o.material as THREE.Material);
}
});
this.rings.clear();
for (const pos of new Set([...selected, ...available])) {
const [x, z] = positionXY(pos);
const ring = this.mesh(
new THREE.TorusGeometry(0.99, selected.includes(pos) ? 0.035 : 0.018, 6, 6),
this.material(selected.includes(pos) ? '#ffe0a0' : '#e5cc92'),
);
ring.rotation.x = -Math.PI / 2;
ring.rotation.z = Math.PI / 6;
ring.position.set(x, 0.35, z);
this.rings.add(ring);
}
}
this.labelPositions.forEach((label) =>
label.node.classList.toggle('selected', label.position === s.city),
);
if (s.topDown !== this.topDown) {
this.topDown = s.topDown;
this.reset();
}
this.invalidate();
}
destroy() {
this.disposed = true;
cancelAnimationFrame(this.frame);
this.resize.disconnect();
this.controls.dispose();
this.renderer.domElement.removeEventListener('pointerdown', this.down);
this.renderer.domElement.removeEventListener('pointerup', this.up);
this.renderer.domElement.removeEventListener('keydown', this.key);
for (const geometry of this.geometries) geometry.dispose();
for (const material of this.materials) material.dispose();
for (const texture of this.textures) texture.dispose();
this.renderer.dispose();
this.renderer.domElement.remove();
this.labelHost.remove();
}
}

View file

@ -0,0 +1,179 @@
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 { journal } from './model';
export class Controller {
readonly session = writable<Session>({
game: null,
view: null,
city: null,
focus: null,
mode: 'overview',
selection: [],
preview: null,
error: '',
pending: false,
tab: 'journal',
activityOpen: false,
help: false,
objectivesOpen: false,
dark: false,
unread: 0,
avatars: [],
reducedMotion: false,
colorBlind: false,
locale: 'en',
selectedAdvance: null,
toast: '',
topDown: false,
});
readonly chat = new ChatController();
private raw = '';
private engine: Bridge | null = null;
private timer: ReturnType<typeof setTimeout> | undefined;
private refreshTimer: ReturnType<typeof setTimeout> | undefined;
private destroyed = false;
private chatOff: () => void;
constructor(
readonly commands: ViewerCommands<string>,
readonly assetBase: URL,
) {
this.chat.setOpen(false);
this.chatOff = this.chat.subscribe(() => this.patch({ unread: this.chat.unread }));
}
patch(patch: Partial<Session>) {
this.session.update((s) => ({ ...s, ...patch }));
}
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;
}
if (this.destroyed) return;
const old = get(this.session);
const game = JSON.parse(raw) as Game;
this.raw = raw;
const view = JSON.parse(this.engine.webView(raw, old.seat)) as View;
const city = view.cities.some((c) => c.position === old.city)
? old.city
: (view.cities[0]?.position ?? null);
clearTimeout(this.refreshTimer);
this.patch({
game,
view,
city,
focus: old.focus ?? city,
pending: false,
error: '',
selection: [],
preview: null,
mode: old.pending || view.objectiveDecision ? 'overview' : old.mode,
objectivesOpen: view.objectiveDecision ? false : old.objectivesOpen,
});
this.commands.replaceLog(journal(game).map((entry) => entry.text));
if (old.pending) this.notify('Game updated.');
}
setPlayer(index?: number) {
this.patch({
seat: index,
mode: 'overview',
selection: [],
preview: null,
selectedAdvance: null,
objectivesOpen: false,
});
if (this.engine && this.raw) {
const view = JSON.parse(this.engine.webView(this.raw, index)) as View;
this.patch({ view, city: view.cities[0]?.position ?? null, focus: view.cities[0]?.position ?? null });
}
}
selectCity(position: string) {
this.patch({
city: position,
focus: position,
selection: [],
preview: null,
error: '',
mode: 'overview',
});
}
selectTile(position: string) {
const s = get(this.session);
const city = s.view?.cities.find((c) => c.position === position);
if (s.mode === 'collect') {
const choice = s.view?.cities
.find((c) => c.position === s.city)
?.choices.find((c) => c.position === position);
if (choice) this.toggleChoice(choice);
} else if (city) this.selectCity(position);
else this.patch({ focus: position });
}
beginCollect() {
this.closeActivity();
this.patch({ mode: 'collect', selection: [], preview: null, error: '', selectedAdvance: null });
}
toggleChoice(choice: Choice) {
const s = get(this.session);
if (s.pending || !s.view?.canPlay || s.seat === undefined || !s.city || !this.engine) return;
const selected = s.selection.find(
(c) => c.position === choice.position && JSON.stringify(c.pile) === JSON.stringify(choice.pile),
);
const city = s.view.cities.find((c) => c.position === s.city)!;
const selection = selected
? s.selection.filter((c) => c !== selected)
: [...s.selection, { ...choice, times: 1 }];
if (selection.length > city.capacity) {
this.patch({ error: `This city can collect from ${city.capacity} tiles. Remove a selection first.` });
return;
}
try {
const preview = selection.length
? JSON.parse(this.engine.webCollectPreview(this.raw, s.seat, s.city, JSON.stringify(selection)))
: null;
this.patch({ selection, preview, error: '' });
} catch (error) {
this.patch({ error: String(error) });
}
}
submit(move: Move) {
const s = get(this.session);
if (s.pending || s.seat === undefined || s.view?.activePlayer !== s.seat) return;
this.patch({ pending: true, error: '' });
if (!this.commands.move(JSON.stringify(move))) {
this.patch({ pending: false, error: 'The action could not be sent. Please try again.' });
return;
}
this.refreshTimer = setTimeout(() => {
this.commands.fetchState();
this.patch({ error: 'Waiting for the game to confirm your action…' });
}, 8000);
}
collect() {
const s = get(this.session);
if (s.preview) this.submit(s.preview.action);
}
setTab(tab: 'journal' | 'chat') {
this.chat.setOpen(tab === 'chat');
this.patch({ tab, activityOpen: true, mode: 'overview' });
}
closeActivity() {
this.chat.setOpen(false);
this.patch({ activityOpen: false });
}
notify(toast: string) {
clearTimeout(this.timer);
this.patch({ toast });
this.timer = setTimeout(() => this.patch({ toast: '' }), 4000);
}
destroy() {
this.destroyed = true;
clearTimeout(this.timer);
clearTimeout(this.refreshTimer);
this.chatOff();
}
}

View file

@ -0,0 +1,242 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { createViewer } from '@boardgamers/protocol/viewer';
import { ChatController } from '@boardgamers/protocol/chat';
import { journal, positionXY } from './model.ts';
import type { View, Game } from './types.ts';
const require = createRequire(import.meta.url);
const engine = require('../.engine/server.js');
async function initial() {
return engine.init(2, [], { undo: 'SamePlayer', civilization: 'Random' }, 'clash-preview-20260927', {});
}
test('opening collection, research, undo, and handoff use the Rust engine', async () => {
let state = await initial();
const seat = engine.currentPlayer(state);
const publicState = engine.stripSecret(state, seat);
const view: View = JSON.parse(engine.webView(publicState, seat));
const city = view.cities[0];
const choices = city.choices.filter((c) => c.pile.wood || c.pile.ore).map((c) => ({ ...c, times: 1 }));
const preview = JSON.parse(
engine.webCollectPreview(publicState, seat, city.position, JSON.stringify(choices)),
);
state = engine.tryMove(state, JSON.stringify(preview.action), seat);
let game: Game = JSON.parse(state);
assert.equal(game.actions_left, 2);
assert.equal(game.players[seat].resources?.wood, 1);
assert.equal(game.players[seat].resources?.ore, 1);
const afterCollection = state;
const research = JSON.parse(engine.webView(engine.stripSecret(state, seat), seat)).advances.find(
(a: any) => a.id === 'Storage',
);
assert.ok(research.action);
state = engine.tryMove(state, JSON.stringify(research.action), seat);
game = JSON.parse(state);
assert.equal(game.actions_left, 1);
assert.equal(game.players[seat].resource_limit?.food, 7);
state = engine.tryMove(state, '"Undo"', seat);
game = JSON.parse(state);
assert.equal(game.actions_left, 2);
assert.equal(game.players[seat].resource_limit?.food, 2);
assert.deepEqual(journal(game), journal(JSON.parse(afterCollection)));
state = engine.tryMove(state, JSON.stringify({ Playing: 'EndTurn' }), seat);
assert.notEqual(engine.currentPlayer(state), seat);
});
test('viewer queries respect spectator and opponent seats and reject illegal choices', async () => {
const state = await initial();
const seat = engine.currentPlayer(state);
const visible = engine.stripSecret(state, seat);
for (const index of [undefined, 99, 1 - seat]) {
const view: View = JSON.parse(engine.webView(visible, index));
assert.equal(view.canPlay, false);
assert.equal(view.canUndo, false);
assert.ok(view.advances.every((a) => a.action === null));
}
const view: View = JSON.parse(engine.webView(visible, seat));
const city = view.cities[0];
assert.throws(() => engine.webCollectPreview(visible, 1 - seat, city.position, '[]'));
assert.throws(() =>
engine.webCollectPreview(
visible,
seat,
city.position,
JSON.stringify([{ position: city.position, pile: { gold: 7 }, times: 1 }]),
),
);
const full = JSON.parse(state);
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));
});
test('objective cards show both conditions only from the player-visible hand', async () => {
const state = await initial();
const seat = engine.currentPlayer(state);
const visible = engine.stripSecret(state, seat);
const view: View = JSON.parse(engine.webView(visible, seat));
const hand = JSON.parse(visible).players[seat].objective_cards;
assert.deepEqual(
view.objectiveCards.map((card) => card.id),
hand,
);
assert.ok(view.objectiveCards.length > 0);
for (const card of view.objectiveCards) {
assert.equal(card.objectives.length, 2);
for (const objective of card.objectives) {
assert.ok(objective.name.length > 0);
assert.ok(objective.description.length > 0);
assert.ok(['Instant', 'Status phase'].includes(objective.timing));
}
}
assert.deepEqual(
view.objectiveCards[0].objectives.map((o) => o.name),
['Legacy', 'Ivory Tower'],
);
for (const index of [undefined, 99, 1 - seat]) {
assert.deepEqual(JSON.parse(engine.webView(visible, index)).objectiveCards, []);
}
const spectatorState = engine.stripSecret(state, undefined);
assert.deepEqual(JSON.parse(engine.webView(spectatorState, seat)).objectiveCards, []);
});
test('an eligible status objective can be claimed or kept, with correct points and privacy', async () => {
const setup = JSON.parse(await initial());
const seat = setup.current_player_index;
// A city with an Obelisk makes the existing Legacy objective eligible.
setup.players[seat].cities[0].city_pieces = { obelisk: seat };
let state = JSON.stringify(setup);
for (let turn = 0; turn < 6; turn++) {
assert.equal(JSON.parse(state).events?.length ?? 0, 0);
state = engine.tryMove(state, JSON.stringify({ Playing: 'EndTurn' }), engine.currentPlayer(state));
}
const visible = engine.stripSecret(state, seat);
const view: View = JSON.parse(engine.webView(visible, seat));
const decision = view.objectiveDecision!;
assert.ok(decision);
assert.equal(view.supportedPhase, true);
assert.equal(view.canPlay, false);
assert.equal(decision.name, 'Legacy');
assert.equal(decision.points, 2);
assert.equal(decision.cards.length, 1);
assert.equal(decision.cards[0].id, 36);
for (const index of [undefined, 1 - seat]) {
const limited = engine.stripSecret(state, index);
assert.equal(JSON.parse(engine.webView(limited, index)).objectiveDecision, null);
// Switching a seat never reveals card choices from already-filtered data.
assert.equal(JSON.parse(engine.webView(limited, seat)).objectiveDecision, null);
}
const claimed = engine.tryMove(state, JSON.stringify(decision.cards[0].action), seat);
const claimedPlayer = JSON.parse(claimed).players[seat];
assert.ok(!claimedPlayer.objective_cards?.includes(36));
assert.ok(claimedPlayer.completed_objectives.some((o: any) => o.card === 36 && o.name === 'Legacy'));
const after: View = JSON.parse(engine.webView(engine.stripSecret(claimed, seat), seat));
assert.equal(
after.players.find((p) => p.index === seat)!.score,
view.players.find((p) => p.index === seat)!.score + 2,
);
assert.equal(after.objectiveDecision, null);
assert.ok(journal(JSON.parse(claimed)).some((entry) => entry.text.includes('Legacy')));
assert.ok(decision.skip);
const kept = engine.tryMove(state, JSON.stringify(decision.skip), seat);
assert.ok(JSON.parse(kept).players[seat].objective_cards.includes(36));
const keptView: View = JSON.parse(engine.webView(engine.stripSecret(kept, seat), seat));
assert.equal(keptView.objectiveDecision, null);
assert.equal(
keptView.players.find((p) => p.index === seat)!.score,
view.players.find((p) => p.index === seat)!.score,
);
});
test('research graph has valid prerequisites and setup summaries retain historical locations', async () => {
const state = await initial();
const seat = engine.currentPlayer(state);
const game: Game = JSON.parse(engine.stripSecret(state, seat));
const view: View = JSON.parse(engine.webView(JSON.stringify(game), seat));
assert.equal(new Set(view.advances.map((a) => a.group)).size, 12);
for (const advance of view.advances) {
if (advance.required) assert.ok(view.advances.some((a) => a.id === advance.required));
assert.ok(Number.isInteger(advance.order));
}
const storage = view.advances.find((a) => a.id === 'Storage')!;
assert.equal(storage.required, 'Farming');
assert.equal(storage.group, 'Agriculture');
assert.deepEqual(storage.bonus, { mood_tokens: 1 });
assert.equal(view.advances.find((a) => a.id === 'Voting')!.required, 'Philosophy');
const before = journal(game).filter((entry) => entry.kind === 'setup');
assert.equal(before.length, 2);
assert.ok(
before.every(
(entry) => entry.setup?.position && !entry.text.includes('Gain') && !entry.text.includes('card'),
),
);
game.players.forEach((player) => {
player.cities = [];
});
assert.deepEqual(
journal(game).filter((entry) => entry.kind === 'setup'),
before,
);
});
test('BGS lifecycle, chat acknowledgements, journal, and cleanup', async () => {
const chat = new ChatController({ readDelayMs: 0 });
let renders = 0;
let ready = 0;
let lines: string[] = [];
const client = createViewer<string, string>({
chat,
onPlayer() {},
onState(state) {
renders++;
client.replaceLog(journal(JSON.parse(state)).map((l) => l.text));
},
});
client.emitter.on('ready', () => ready++);
client.emitter.on('replaceLog', (payload) => {
lines = payload;
});
client.emitter.emit('player', { index: 1 });
client.emitter.emit('state', engine.stripSecret(await initial(), 1));
await new Promise((resolve) => setTimeout(resolve, 30));
assert.equal(renders, 1);
assert.equal(ready, 1);
assert.ok(lines.length > 0);
assert.equal(client.diagnostics(['chat']).compatible, true);
client.emitter.emit('chat:state', { canSend: true, readState: { userId: 'me', lastReadAt: 0 } });
client.emitter.on('chat:send', (payload) => {
assert.equal(payload.text, 'hello');
client.emitter.emit('chat:result', { requestId: payload.requestId!, ok: false, error: 'Try again' });
});
chat.setDraft('hello');
chat.submit();
assert.equal(chat.snapshot.draft, 'hello');
assert.equal(chat.snapshot.error, 'Try again');
client.emitter.emit('chat:appended', [
{
_id: '0123456789abcdef01234567',
author: 'Aurelia',
authorId: 'other',
playerIndex: 0,
text: 'Welcome',
createdAt: new Date().toISOString(),
type: 'text',
},
]);
assert.equal(chat.unread, 1);
client.emitter.emit('chat:updated', [
{ _id: '0123456789abcdef01234567', text: 'Welcome back', type: 'text' },
]);
assert.equal(chat.snapshot.messages[0].text, 'Welcome back');
client.emitter.emit('chat:deleted', ['0123456789abcdef01234567']);
assert.equal(chat.snapshot.messages.length, 0);
client.destroy();
assert.equal(client.emitter.emit('state', '{}'), false);
});
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]);
assert.equal(positionXY('D7')[1] - positionXY('D2')[1], 5 * Math.sqrt(3));
});

View file

@ -0,0 +1,13 @@
import { viewer } from './viewer';
import { uplinkSchemas } from '@boardgamers/protocol';
const transport = viewer.launch('#app');
for (const event of Object.keys(uplinkSchemas)) {
transport.on(event as any, (payload: unknown) =>
parent.postMessage({ source: 'clash-viewer', event, payload }, location.origin),
);
}
addEventListener('message', (event) => {
if (event.source === parent && event.origin === location.origin && event.data?.source === 'clash-host')
transport.receive(event.data.event, event.data.payload);
});
parent.postMessage({ source: 'clash-viewer', event: 'mounted' }, location.origin);

View file

@ -0,0 +1,132 @@
const frame = document.querySelector('iframe')!;
if (new URLSearchParams(location.search).has('built')) frame.src = '/built-viewer.html';
const seatSelect = document.querySelector<HTMLSelectElement>('#seat')!;
let revision = -1;
let seat: number | undefined;
let ready = false;
let dark = false;
let lastMessages = '';
let fetching = false;
let queued = false;
let journal: string[] = [];
const send = (event: string, payload?: unknown) =>
frame.contentWindow?.postMessage({ source: 'clash-host', event, payload }, location.origin);
function showError(message: string) {
document.querySelector('#host-error')!.textContent = message;
}
async function refresh(force = false) {
if (fetching) {
queued = true;
return;
}
fetching = true;
try {
const response = await fetch(`/api/state?seat=${seatSelect.value}`);
const data = await response.json();
if (!response.ok) throw Error(data.error);
if (force || data.revision !== revision || data.seat !== seat) {
revision = data.revision;
seat = data.seat;
send('player', { index: seat });
send('state', data.state);
}
send('chat:state', {
canSend: seat !== undefined,
reason: seat === undefined ? 'not-a-player' : undefined,
mentions: [
{ id: '0', name: 'Leif', playerIndex: 0 },
{ id: '1', name: 'Aurelia', playerIndex: 1 },
],
readState: { userId: `preview-${seat}`, lastReadAt: data.lastReadAt ?? 0 },
});
const serialized = JSON.stringify(data.messages);
if (lastMessages !== serialized) {
send('chat:messages', data.messages);
lastMessages = serialized;
}
document.querySelector('#status')!.textContent =
`Local game · Revision ${revision} · BGS protocol connected`;
} catch (error) {
showError(String(error));
} finally {
fetching = false;
if (queued) {
queued = false;
void refresh(true);
}
}
}
async function post(path: string, body: unknown) {
const response = await fetch(path, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
const data = await response.json();
if (!response.ok) throw Error(data.error);
return data;
}
addEventListener('message', async (event) => {
if (
event.source !== frame.contentWindow ||
event.origin !== location.origin ||
event.data?.source !== 'clash-viewer'
)
return;
const { event: kind, payload } = event.data;
if (kind === 'mounted') {
ready = true;
send('preferences', { locale: 'en' });
send('theme', { dark });
await refresh(true);
}
if (kind === 'fetchState') await refresh(true);
if (kind === 'move') {
try {
showError('');
await post('/api/move', { move: payload, seat, revision });
} catch (error) {
showError(String(error));
}
await refresh(true);
}
if (kind === 'replaceLog') journal = payload;
if (kind === 'chat:read') {
try {
await post('/api/read', { messageId: payload.messageId, seat });
} catch (error) {
showError(String(error));
}
}
if (kind === 'chat:send') {
try {
await post('/api/chat', { text: payload.text, seat });
send('chat:result', { requestId: payload.requestId, ok: true });
await refresh();
} catch (error) {
send('chat:result', { requestId: payload.requestId, ok: false, error: String(error) });
}
}
if (kind === 'boardgame:clicked')
window.open('https://boardgamers.space/boardgame/clash', '_blank', 'noopener');
if (kind === 'player:clicked')
document.querySelector('#status')!.textContent =
`Player ${payload.index + 1} · ${payload.index === 0 ? 'Leif' : 'Aurelia'}`;
});
seatSelect.onchange = () => {
lastMessages = '';
void refresh(true);
};
document.querySelector('#reset')!.addEventListener('click', async () => {
await post('/api/reset', {});
lastMessages = '';
showError('');
await refresh(true);
});
document.querySelector('#theme')!.addEventListener('click', () => {
dark = !dark;
send('theme', { dark });
});
setInterval(() => {
if (ready) void refresh();
}, 2000);

120
web-client/src/model.ts Normal file
View file

@ -0,0 +1,120 @@
import type { Game, JournalEntry, LoggedAction, Pile, Resource } from './types.ts';
import { resourceNames } from './types.ts';
export function pileText(pile: Pile): string {
return (
Object.entries(pile)
.filter(([, n]) => n)
.map(([key, n]) => `${n} ${resourceNames[key as Resource].toLowerCase()}`)
.join(' + ') || 'No resources'
);
}
export function journal(game: Game): JournalEntry[] {
return (game.log ?? []).flatMap((age, a) =>
age.rounds.flatMap((round, r) =>
round.turns.flatMap((turn, t) =>
(turn.actions ?? []).flatMap((action, c) => {
if (turn.turn_type === 'Setup' || action.action === 'Setup') {
return setupJournal(game, action).map((setup, i) => ({
id: `${a}-${r}-${t}-${c}-${i}`,
age: age.age,
round: round.round,
kind: 'setup' as const,
setup,
text: `${setup.player} plays as ${setup.civilization}${setup.position ? ` · starts at ${setup.position}` : ''}`,
}));
}
return (action.log ?? []).map((text, i) => ({
id: `${a}-${r}-${t}-${c}-${i}`,
age: age.age,
round: round.round,
kind: journalKind(action),
text,
}));
}),
),
),
);
}
function setupJournal(game: Game, action: LoggedAction): NonNullable<JournalEntry['setup']>[] {
const players = [...new Set((action.items ?? []).map((item) => item.player))];
if (players.length) {
return players.flatMap((id) => {
const player = game.players.find((p) => p.id === id);
if (!player) return [];
// Read the original location from history, even if the city has since moved or been lost.
const position = action.items?.find(
(item) =>
item.player === id &&
item.Structure?.structure === 'CityCenter' &&
item.Structure.balance === 'Gain',
)?.Structure?.position;
return [{ player: player.name ?? `Player ${id + 1}`, civilization: player.civilization, position }];
});
}
// Older saved logs may contain only their rendered text.
return (action.log ?? []).flatMap((text) => {
const match = text.match(/^(.+?): Setup: Play as ([^,]+)/);
if (!match) return [];
return [
{ player: match[1], civilization: match[2], position: text.match(/\bGain city ([A-Z]+\d+)\b/)?.[1] },
];
});
}
function journalKind(action: LoggedAction): JournalEntry['kind'] {
if (action.combat_stats) return 'combat';
if (
action.items?.some(
(item) =>
item.HandCard?.to && typeof item.HandCard.to === 'object' && 'CompleteObjective' in item.HandCard.to,
)
)
return 'objective';
if (!action.action || typeof action.action === 'string') return 'event';
if ('Movement' in action.action) return 'move';
const playing = action.action.Playing;
const name =
typeof playing === 'string'
? playing
: playing && typeof playing === 'object'
? Object.keys(playing)[0]
: '';
const kinds: Record<string, JournalEntry['kind']> = {
Collect: 'collect',
Advance: 'research',
EndTurn: 'end-turn',
Construct: 'build',
FoundCity: 'build',
Recruit: 'recruit',
ActionCard: 'card',
WonderCard: 'card',
};
return kinds[name] ?? 'event';
}
export function journalParts(text: string): { text: string; resource?: Resource }[] {
const names: Record<string, Resource> = {
food: 'food',
wood: 'wood',
ore: 'ore',
ideas: 'ideas',
gold: 'gold',
'mood token': 'mood_tokens',
'mood tokens': 'mood_tokens',
'culture token': 'culture_tokens',
'culture tokens': 'culture_tokens',
};
const pattern = /\b\d+(?:\.\d+)? (food|wood|ore|ideas|gold|mood tokens?|culture tokens?)\b/g;
const parts: { text: string; resource?: Resource }[] = [];
let offset = 0;
for (const match of text.matchAll(pattern)) {
if (match.index > offset) parts.push({ text: text.slice(offset, match.index) });
parts.push({ text: match[0], resource: names[match[1]] });
offset = match.index + match[0].length;
}
if (offset < text.length) parts.push({ text: text.slice(offset) });
return parts;
}
export function positionXY(position: string): [number, number] {
const q = position.charCodeAt(0) - 65;
const row = Number(position.slice(1)) - 1;
return [q * 1.5, (row + (q % 2) * 0.5) * Math.sqrt(3)];
}

385
web-client/src/research.css Normal file
View file

@ -0,0 +1,385 @@
.research-dialog {
width: calc(100% - 36px);
max-width: 1400px;
height: calc(100dvh - 36px);
max-height: 900px;
padding: 0;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--paper);
color: var(--ink);
box-shadow: 0 18px 100px #163c3c66;
display: flex;
flex-direction: column;
overflow: hidden;
}
.research-dialog::backdrop {
background: #153a345b;
backdrop-filter: blur(3px);
}
.research-header {
display: flex;
align-items: center;
gap: 22px;
padding: 20px 25px 15px;
flex-shrink: 0;
}
.research-dialog h2 {
font-size: 34px;
}
.research-header p {
font-size: 12px;
color: var(--muted);
margin-top: 5px;
}
.research-header > .icon-button {
margin-left: auto;
}
.research-search {
display: flex;
align-items: center;
gap: 8px;
margin-left: auto;
border: 1px solid var(--line);
border-radius: 5px;
padding: 9px 11px;
color: var(--muted);
min-width: 245px;
}
.research-search input {
width: 100%;
background: none;
border: 0;
outline: none;
font-size: 12px;
color: var(--ink);
}
.research-search:focus-within {
outline: 2px solid #b58a45;
}
.research-filters {
display: flex;
flex-wrap: wrap;
gap: 5px;
padding: 0 25px 16px;
flex-shrink: 0;
border-bottom: 1px solid var(--line);
}
.research-filters button {
display: flex;
align-items: center;
gap: 6px;
padding: 7px 9px;
font-size: 11px;
border: 1px solid transparent;
border-radius: 5px;
}
.research-filters button:hover {
background: var(--paper2);
}
.research-filters button.active {
color: #f7f3e8;
background: #355948;
}
.research-tree {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: 28px 24px;
padding: 22px 25px 30px;
overflow: auto;
flex: 1;
min-height: 0;
align-content: start;
}
.research-branch {
min-width: 0;
}
.research-branch > h3 {
display: flex;
align-items: center;
gap: 9px;
font-family: inherit;
font-size: 12px;
font-weight: 600;
margin-bottom: 13px;
}
.research-node {
position: relative;
margin-bottom: 12px;
border: 1px solid var(--line);
border-radius: 7px;
background: var(--paper);
scroll-margin: 16px;
}
.research-node.child {
margin-left: 17px;
}
.research-node.child::before {
content: '';
position: absolute;
left: -12px;
top: -14px;
bottom: -12px;
width: 1px;
background: #b6bba6;
}
.research-node.child::after {
content: '';
position: absolute;
left: -12px;
top: 22px;
width: 11px;
height: 1px;
background: #b6bba6;
}
.research-node.child:last-child::before {
bottom: calc(100% - 23px);
}
.research-node.owned {
border-color: #a0b493;
background: #e9eedf;
}
.research-node.available {
border-color: #c2a46e;
box-shadow: 0 1px 4px #86652c12;
}
.research-node.selected {
outline: 2px solid #a67e3d;
outline-offset: 2px;
}
.research-node.search-muted {
opacity: 0.45;
}
.research-pick {
width: 100%;
text-align: left;
padding: 12px;
display: flex;
flex-direction: column;
gap: 9px;
border-radius: 7px;
}
.research-pick:hover {
background: #bba77912;
}
.research-node-title {
display: flex;
align-items: center;
gap: 9px;
width: 100%;
}
.advance-pictogram {
width: 32px;
height: 32px;
background: var(--paper2);
color: #8d7447;
border-radius: 5px;
display: grid;
place-items: center;
flex-shrink: 0;
}
.research-node-title strong {
font-size: 13px;
font-weight: 600;
line-height: 1.3;
}
.research-node-title > svg {
margin-left: auto;
color: #697958;
flex-shrink: 0;
}
.research-summary {
font-size: 12px;
line-height: 1.55;
color: var(--ink);
}
.research-effects {
display: flex;
flex-wrap: wrap;
gap: 5px 9px;
color: #6c794e;
}
.research-effects:empty {
display: none;
}
.research-effects > span,
.research-node-cost > span {
display: inline-flex;
gap: 4px;
align-items: center;
font-size: 10px;
}
.research-effects svg,
.research-node-cost svg {
flex-shrink: 0;
}
.research-node-cost {
border-top: 1px solid var(--line);
padding-top: 8px;
display: flex;
flex-wrap: wrap;
gap: 5px 9px;
width: 100%;
}
.research-node-cost .research-availability {
margin-left: auto;
color: var(--muted);
text-align: right;
}
.available .research-availability {
color: #456c3f;
}
.researched-label {
color: #4b7045;
}
.research-prerequisite {
display: flex;
gap: 5px;
align-items: center;
font-size: 10px;
padding: 8px 12px;
border-bottom: 1px solid var(--line);
width: 100%;
background: var(--paper2);
border-radius: 7px 7px 0 0;
}
.research-legend {
display: flex;
flex-wrap: wrap;
gap: 10px 22px;
align-items: center;
padding: 13px 25px;
border-top: 1px solid var(--line);
font-size: 11px;
color: var(--muted);
flex-shrink: 0;
}
.research-legend > span {
display: flex;
align-items: center;
gap: 5px;
}
.research-legend > span:last-child {
margin-left: auto;
}
.available-key::before {
content: '';
width: 9px;
height: 9px;
border: 1px solid #b18c4d;
border-radius: 3px;
}
.research-detail {
display: flex;
align-items: center;
gap: 18px;
border-top: 1px solid var(--line);
padding: 16px 25px;
background: var(--paper2);
max-height: 38%;
overflow: auto;
flex-shrink: 0;
}
.research-detail > div {
flex: 1;
}
.research-detail h3 {
font-size: 25px;
margin-bottom: 5px;
}
.research-detail p {
font-size: 12px;
line-height: 1.6;
}
.research-detail small {
display: block;
font-size: 11px;
margin-top: 7px;
color: var(--muted);
}
.research-detail .primary {
flex-direction: column;
gap: 5px;
min-width: 210px;
}
.research-detail .primary span {
font-size: 10px;
font-weight: 400;
}
.research-empty {
font-size: 14px;
padding: 20px;
color: var(--muted);
}
.dark .research-node.owned {
background: #344531;
}
.dark .research-effects,
.dark .researched-label,
.dark .available .research-availability {
color: #bbd09b;
}
@media (max-width: 760px) {
.research-dialog {
width: calc(100% - 16px);
height: calc(100dvh - 16px);
max-height: none;
}
.research-header {
padding: 15px;
gap: 8px;
flex-wrap: wrap;
}
.research-dialog h2 {
font-size: 29px;
}
.research-header > div {
flex: 1;
}
.research-header p {
font-size: 11px;
max-width: 250px;
}
.research-search {
order: 3;
width: 100%;
margin: 4px 0 0;
}
.research-filters {
flex-wrap: nowrap;
overflow-x: auto;
padding: 0 15px 12px;
}
.research-filters button {
white-space: nowrap;
}
.research-tree {
grid-template-columns: 1fr;
padding: 16px;
gap: 25px;
}
.research-summary {
font-size: 13px;
}
.research-detail {
padding: 12px 15px;
flex-wrap: wrap;
gap: 9px;
max-height: 42%;
}
.research-detail > div {
min-width: calc(100% - 45px);
}
.research-detail .primary {
order: 3;
width: 100%;
}
.research-legend {
padding: 10px 15px;
font-size: 10px;
gap: 8px 12px;
}
.research-legend > span:last-child {
display: none;
}
}

128
web-client/src/research.ts Normal file
View file

@ -0,0 +1,128 @@
import {
Wheat,
Warehouse,
Droplets,
Beef,
Pickaxe,
Hammer,
HeartPulse,
Route,
Fish,
Ship,
Shield,
Map,
BookOpen,
School,
GraduationCap,
Brain,
Swords,
Castle,
Anvil,
Users,
Sun,
Flame,
Church,
Landmark,
Handshake,
Coins,
Palette,
Dumbbell,
Drama,
Calculator,
Telescope,
Vote,
Scale,
Heart,
Store,
Flag,
Crown,
Shovel,
Scroll,
ShieldCheck,
Sparkles,
Zap,
} from 'lucide-svelte';
import type { AdvanceView } from './types';
// Short reading aids; the engine's complete rule text remains available on selection.
const advances = {
Farming: [Wheat, 'Collect food from grassland and wood from forests.'],
Storage: [Warehouse, 'Food storage increases from 2 to 7.'],
Irrigation: [Droplets, 'Collect food from barren land. Ignore famine.'],
Husbandry: [Beef, 'Collect from one land tile 2 spaces away; two with Roads. Once per turn.'],
Mining: [Pickaxe, 'Collect ore from mountains.'],
Engineering: [Hammer, 'Draw a wonder card. Build wonders in happy cities.'],
Sanitation: [HeartPulse, 'Recruit 1 settler for 1 mood. Ignore pestilence and epidemics.'],
Roads: [
Route,
'From/to cities, pay 1 food + 1 ore for +1 land range and ignore terrain. No exploring or boarding ships.',
],
Fishing: [Fish, 'Collect food from one sea tile.'],
Navigation: [Ship, 'Move ships around the map edge to the next sea tile.'],
WarShips: [Shield, 'Ignore the first hit in round 1 when attacking by ship or disembarking.'],
Cartography: [Map, 'Ship movement earns 1 idea; using Navigation also earns 1 culture.'],
Writing: [BookOpen, 'Draw an action card and an objective card.'],
PublicEducation: [School, 'Gain 1 idea when collecting in an Academy city. Once per turn.'],
FreeEducation: [
GraduationCap,
'After buying an advance with gold or ideas, trade 1 extra idea for 1 mood.',
],
Philosophy: [Brain, 'Gain 1 idea now, and 1 for each Science advance.'],
Tactics: [Swords, 'Move army units and use the tactics on action cards.'],
Siegecraft: [Castle, 'Cancel a Fortress’s extra die for 2 wood, or its hit protection for 2 ore.'],
SteelWeapons: [Anvil, 'Pay 1 ore for +2 combat strength in land battles; +1 versus Steel Weapons.'],
Draft: [Users, 'Recruit an infantry unit with 1 mood instead of resources.'],
Myths: [Sun, 'Spend mood to prevent event-driven city mood loss, except Pirates.'],
Rituals: [Flame, 'Use resources instead of mood when increasing happiness.'],
Priesthood: [Church, 'One Science advance per turn costs no resources. Still uses an action.'],
StateReligion: [Landmark, 'Build a Temple without paying food. Once per turn.'],
Bartering: [Handshake, 'Discard an action card for 1 gold or culture. Free, once per turn.'],
TradeRoutes: [Route, 'Settlers and ships near non-angry enemy cities earn up to 4 food per turn.'],
Taxes: [Coins, 'Spend an action and 1 mood for food, wood or ore equal to your city count. Once per turn.'],
Currency: [Coins, 'Take gold instead of food from Trade Routes and Taxes.'],
Arts: [Palette, 'Spend 1 culture for a free influence attempt. Once per turn.'],
Sports: [Dumbbell, 'Spend an action and 1–2 culture to raise a city’s mood 1–2 steps.'],
Monuments: [Landmark, 'Draw a wonder card. Wonder cities cannot be culturally influenced.'],
Theaters: [Drama, 'Swap 1 mood and 1 culture either way. Free, once per turn.'],
Math: [Calculator, 'Engineering and Roads cost no food.'],
Astronomy: [Telescope, 'Navigation and Cartography cost no food.'],
Medicine: [HeartPulse, 'Recover one resource spent after recruiting.'],
Metallurgy: [Anvil, 'Improve Steel Weapons. When collecting 2+ ore, replace 1 ore with gold.'],
Voting: [Vote, 'Spend 1 mood to take a free Increase Happiness action.'],
SeparationOfPower: [Scale, 'Culture tokens cannot boost influence attempts against your happy cities.'],
CivilLiberties: [Heart, 'Gain 3 mood for an action. Draft now costs 2 mood per infantry.'],
FreeEconomy: [Store, 'Spend 1 mood to collect without an action. Your only collection that turn.'],
Nationalism: [Flag, 'Recruit an army or ship unit to gain 1 mood or culture.'],
Totalitarianism: [Shield, 'Culture tokens cannot boost influence against cities with armies.'],
AbsolutePower: [Crown, 'Buy an extra action for 2 mood. Once per turn.'],
ForcedLabor: [Shovel, 'Spend 1 mood to treat angry cities as neutral this turn. Free, once per turn.'],
Dogma: [Scroll, 'New Temples grant a free Theocracy advance. Idea storage drops to 2.'],
Devotion: [ShieldCheck, 'Culture tokens cannot boost influence against your Temple cities.'],
Conversion: [Sparkles, '+1 to influence rolls. Successful attempts earn 1 culture.'],
Fanaticism: [Zap, '+2 in the first battle round at a Temple city. Gain infantry if you lose.'],
} as const;
export const groupIcons: Record<string, typeof Wheat> = {
Agriculture: Wheat,
Construction: Hammer,
Seafaring: Ship,
Education: GraduationCap,
Warfare: Swords,
Spirituality: Sun,
Economy: Coins,
Culture: Palette,
Science: Telescope,
Democracy: Vote,
Autocracy: Crown,
Theocracy: Church,
};
export function researchPresentation(advance: AdvanceView) {
const entry = advances[advance.id as keyof typeof advances];
return {
icon: entry?.[0] ?? groupIcons[advance.group] ?? BookOpen,
summary:
advance.id === 'Philosophy' && advance.description.includes('3 ideas')
? advance.description
: (entry?.[1] ?? advance.description),
};
}

1868
web-client/src/style.css Normal file

File diff suppressed because it is too large Load diff

176
web-client/src/types.ts Normal file
View file

@ -0,0 +1,176 @@
export type Pile = Partial<
Record<'food' | 'wood' | 'ore' | 'ideas' | 'gold' | 'mood_tokens' | 'culture_tokens', number>
>;
export type Resource = keyof Pile;
export type Move = string | Record<string, unknown>;
export type Terrain =
'Forest' | 'Fertile' | 'Mountain' | 'Barren' | 'Water' | 'Unexplored' | { Exhausted: string };
export interface City {
position: string;
mood_state: string;
pieces?: Record<string, unknown>;
activations?: number;
}
export interface Player {
id: number;
name?: string;
civilization: string;
resources?: Pile;
resource_limit?: Pile;
cities?: City[];
units?: { position: string; unit_type: string; id: number }[];
advances?: string[];
action_cards?: number[];
objective_cards?: number[];
}
export interface Game {
state: unknown;
players: Player[];
map: { tiles: [string, Terrain][] };
current_player_index: number;
actions_left: number;
age: number;
round: number;
log?: {
age: number;
rounds: { round: number; turns: { turn_type: unknown; actions?: LoggedAction[] }[] }[];
}[];
log_index: number;
}
export interface LoggedAction {
action?: Move;
log?: string[];
items?: {
player: number;
Structure?: { structure: unknown; balance: string; position: string };
HandCard?: { to: unknown };
}[];
combat_stats?: unknown;
}
export interface Choice {
position: string;
pile: Pile;
}
export interface Selection extends Choice {
times: number;
}
export interface CityView {
position: string;
size: number;
capacity: number;
maxPerTile: number;
maxRange2: number;
mood: string;
activations: number;
reason: string | null;
choices: Choice[];
}
export interface AdvanceView {
id: string;
name: string;
description: string;
owned: boolean;
reason: string | null;
payment: Pile;
action: Move | null;
group: string;
order: number;
required: string | null;
bonus: Pile | null;
unlocks: string | null;
}
export interface PlayerView {
index: number;
name: string;
civilization: string;
score: number;
cities: { position: string; size: number; capacity: number; mood: string; activations: number }[];
}
export interface View {
activePlayer: number;
canPlay: boolean;
supportedPhase: boolean;
players: PlayerView[];
cities: CityView[];
advances: AdvanceView[];
objectiveCards: {
id: number;
objectives: { name: string; description: string; timing: 'Instant' | 'Status phase' }[];
}[];
objectiveDecision: {
name: string;
description: string;
points: number;
cards: { id: number; name: string; action: Move }[];
skip: Move | null;
} | null;
canUndo: boolean;
canEndTurn: boolean;
}
export interface CollectionPreview {
action: Move;
total: Pile;
waste: Pile;
after: Pile;
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;
}
export interface JournalEntry {
id: string;
age: number;
round: number;
text: string;
kind:
| 'setup'
| 'collect'
| 'research'
| 'objective'
| 'end-turn'
| 'move'
| 'build'
| 'recruit'
| 'combat'
| 'card'
| 'event';
setup?: { player: string; civilization: string; position?: string };
}
export interface Session {
game: Game | null;
view: View | null;
seat?: number;
city: string | null;
focus: string | null;
mode: 'overview' | 'collect' | 'research';
selection: Selection[];
preview: CollectionPreview | null;
error: string;
pending: boolean;
tab: 'journal' | 'chat';
activityOpen: boolean;
help: boolean;
objectivesOpen: boolean;
dark: boolean;
unread: number;
avatars: string[];
reducedMotion: boolean;
colorBlind: boolean;
locale: string;
selectedAdvance: string | null;
toast: string;
topDown: boolean;
}
export const resourceNames: Record<Resource, string> = {
food: 'Food',
wood: 'Wood',
ore: 'Ore',
ideas: 'Ideas',
gold: 'Gold',
mood_tokens: 'Mood',
culture_tokens: 'Culture',
};
export const resources = Object.keys(resourceNames) as Resource[];
export const playerColors = ['#5086af', '#b96c4c', '#6d9173', '#ae92b6'];

46
web-client/src/viewer.ts Normal file
View file

@ -0,0 +1,46 @@
import { mount, unmount, tick } from 'svelte';
import { registerViewer } from '@boardgamers/protocol/viewer';
import App from './App.svelte';
import { Controller } from './controller';
import css from './style.css?inline';
const source = document.currentScript?.getAttribute('src');
const assetBase = new URL(source ? '.' : '/', source ? new URL(source, location.href) : location.href);
export const viewer = registerViewer<string, string>('clash3d', ({ target, ...commands }) => {
const style = document.createElement('style');
style.textContent = css;
document.head.append(style);
const controller = new Controller(commands, assetBase);
const app = mount(App, { target, props: { controller } });
const motion = matchMedia('(prefers-reduced-motion: reduce)');
controller.patch({ reducedMotion: motion.matches });
return {
chat: controller.chat,
async onState(state) {
await controller.load(state);
await tick();
},
onPlayer({ index }) {
controller.setPlayer(index);
},
onAvatars(avatars) {
controller.patch({ avatars });
},
onPreferences(prefs) {
controller.patch({
locale: typeof prefs.locale === 'string' ? prefs.locale : 'en',
colorBlind: prefs.colorBlind === true,
});
},
onTheme({ dark }) {
controller.patch({ dark });
},
onError(error) {
controller.patch({ error: String(error), pending: false });
},
destroy() {
controller.destroy();
void unmount(app);
style.remove();
},
};
});

18
web-client/tsconfig.json Normal file
View file

@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"allowJs": true,
"checkJs": false,
"resolveJsonModule": true,
"esModuleInterop": true,
"skipLibCheck": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"types": ["vite/client", "node"],
"allowImportingTsExtensions": true,
"noEmit": true
},
"include": ["src/**/*.ts", "src/**/*.svelte", "vite.config.ts"]
}

12
web-client/viewer.html Normal file
View file

@ -0,0 +1,12 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Clash 3D viewer</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/local-frame.ts"></script>
</body>
</html>

12
web-client/vite.config.ts Normal file
View file

@ -0,0 +1,12 @@
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { previewApi } from './scripts/preview-api';
export default defineConfig({
plugins: [svelte(), previewApi()],
build: {
lib: { entry: 'src/viewer.ts', name: 'Clash3DBundle', formats: ['iife'], fileName: () => 'viewer.js' },
target: 'es2022',
emptyOutDir: true,
},
server: { strictPort: true },
});