Allow Rituals payment allocation and full-storage food recipients

This commit is contained in:
coyotte508 2026-10-16 13:14:04 +02:00
commit 48c74446e5
12 changed files with 117 additions and 9 deletions

View file

@ -144,7 +144,7 @@ fn good_year(mut builder: IncidentBuilder, amount: u8, good_year_type: &GoodYear
builder = builder.add_incident_player_request(
IncidentTarget::ActivePlayer,
"Select a player to gain 1 food",
|p, _, _| p.resources.food < p.resource_limit.food,
|_, _, _| true,
i as i32,
move |game, s, _| {
s.other_player(s.choice)

View file

@ -155,7 +155,19 @@ pub fn happiness_preview(game: &Game, seat: usize, input: &Value) -> Result<Valu
&kind,
&origin,
)?;
let affordable = cost.cost.first_valid_payment(&p.resources);
let field = input["includePayments"].as_bool().unwrap_or(false).then(|| {
super::decisions::resource_field(
&cost.cost, "Payment", false, &p.resources, false, &p.resources,
)
});
let affordable = if input["payment"].is_null() {
cost.cost.first_valid_payment(&p.resources)
} else {
let selected = serde_json::from_value(input["payment"].clone())
.map_err(|e| e.to_string())?;
(p.resources.has_at_least(&selected) && cost.cost.is_valid_payment(&selected))
.then_some(selected)
};
let payment = affordable
.clone()
.unwrap_or_else(|| cost.cost.default_payment());
@ -166,6 +178,7 @@ pub fn happiness_preview(game: &Game, seat: usize, input: &Value) -> Result<Valu
});
Ok(json!({
"payment":payment,
"field":field,
"reason":action.is_none().then_some("Not enough resources"),
"action":action
}))

View file

@ -164,7 +164,7 @@ fn great_seer_choice_description(game: &Game, handler: &PersistentEventHandler)
Some(format!("Choose {recipient}.{remaining}"))
}
fn resource_field(
pub(super) fn resource_field(
cost: &PaymentOptions,
name: &str,
optional: bool,

View file

@ -385,3 +385,5 @@ Viewer 0.1.132 / engine 0.4.95 treats undefended city captures as battles for Ca
Viewer 0.1.133 shortens the Barbarian map guide and removes its two trailing caveats to leave more map visible on mobile.
Viewer 0.1.134 lets the Barbarian, Pirate, Trade Routes and Regions guides collapse to a title bar while keeping their map overlays visible.
Viewer 0.1.135 / engine 0.4.96 exposes Rituals happiness payment allocation and allows food-distribution events to target other players at their storage limit; excess food is wasted normally.

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.134",
"version": "0.1.135",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.134",
"version": "0.1.135",
"dependencies": {
"@boardgamers/protocol": "0.9.0",
"lucide-svelte": "^0.577.0",

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.134",
"version": "0.1.135",
"private": true,
"type": "module",
"scripts": {

View file

@ -3,6 +3,8 @@
import { Smile, Meh, ArrowRight, Check, Zap, X } from 'lucide-svelte';
import type { Controller } from './controller';
import { happinessPreview, happinessTargets } from './happiness';
import PaymentPicker from './PaymentPicker.svelte';
import { resourceNames, type Pile } from './types';
import ResourceAmount from './ResourceAmount.svelte';
import CityFacts from './CityFacts.svelte';
import ContextualCards from './ContextualCards.svelte';
@ -21,7 +23,15 @@
const targets = $derived(
focused ? happinessTargets($session, (input) => controller.query(input), focused.position) : [],
);
const preview = $derived(happinessPreview($session, (input) => controller.query(input)));
const basePreview = $derived(happinessPreview($session, (input) => controller.query(input), undefined, undefined, undefined, true));
const selectionKey = $derived(JSON.stringify([steps, $session.happinessLawgiver, variant, $session.game?.players.find((p) => p.id === $session.seat)?.resources]));
let chosen = $state<{ key: string; payment: Pile } | null>(null);
const payment = $derived(chosen?.key === selectionKey ? chosen.payment : basePreview.payment);
const preview = $derived(chosen?.key === selectionKey
? happinessPreview($session, (input) => controller.query(input), steps, $session.happinessLawgiver, payment)
: basePreview);
const field = $derived(basePreview.field);
function choosePayment(payment: Pile) { chosen = { key: selectionKey, payment }; }
const cityName = (position: string) =>
cities.find((c) => c.position === position)?.capital
? 'Capital'
@ -126,10 +136,29 @@
{#if !cities.some((city) => city.mood !== 'Happy')}<p class="movement-hint">
All your cities are already happy.
</p>{/if}
{#if selected.length && field && field.resources.length > 1}
{#if field.choices}
<PaymentPicker options={field.choices.map((payment) => ({ payment }))} value={payment}
onChange={choosePayment} pending={!!$session.playback || $session.pending} />
{:else}
<div class="payment-amounts">
{#each field.resources as resource}
{@const available = $session.game?.players.find((p) => p.id === $session.seat)?.resources?.[resource] ?? 0}
<label><span>{resourceNames[resource]}</span>
<select aria-label={resourceNames[resource]} value={payment[resource] ?? 0}
disabled={!!$session.playback || $session.pending}
onchange={(event) => choosePayment({ ...payment, [resource]: Number(event.currentTarget.value) })}>
{#each Array.from({ length: available + 1 }, (_, n) => n) as n}<option value={n}>{n}</option>{/each}
</select>
</label>
{/each}
</div>
{/if}
{/if}
{#if preview.reason}<p class="inline-error">{preview.reason}</p>{/if}
<footer class="happiness-map-footer">
<span class="happiness-total" aria-label="Total happiness cost">
{#if selected.length}<ResourceAmount pile={preview.payment} />{/if}
{#if selected.length}<ResourceAmount pile={payment} />{/if}
<span title={variant?.free ? 'Free action' : 'Costs 1 action'}
><Zap size={13} />{variant?.free ? 0 : 1}</span
>

View file

@ -2715,3 +2715,33 @@ test('Collect preselects all tiles only when their count equals capacity', async
assert.equal(app.session().selection.length, city.capacity - 1, 'manual deselection remains available');
} finally { app.close(); }
});
test('Rituals happiness lets the player choose repeated resources or a mixed payment', async () => {
const app = paymentController(), c = app.controller;
try {
const game = JSON.parse(fixture('advances/increase_happiness_voting'));
game.players[0].advances.push('Myths', 'Rituals');
game.players[0].resources = { food: 7, wood: 7, ore: 7, ideas: 7, gold: 7, mood_tokens: 7 };
const raw = JSON.stringify(game);
c.setPlayer(0);
await c.load(engine.stripSecret(raw, 0));
c.openCities('C2', 'happiness');
c.setHappinessCity('C2', 2);
const base = happinessPreview(app.session(), (input) => c.query(input), undefined, undefined, undefined, true);
const total = Object.values(base.payment).reduce((sum, n) => sum + (n ?? 0), 0);
assert(total > 1);
assert(base.field?.resources.includes('food'));
for (const payment of [{ food: total }, { food: total - 1, ore: 1 }]) {
const quote = happinessPreview(app.session(), (input) => c.query(input), undefined, undefined, payment);
assert(quote.action, JSON.stringify(quote));
assert.deepEqual(quote.payment, payment);
const after = JSON.parse(engine.tryMove(raw, JSON.stringify(quote.action), 0));
assert.equal(after.players[0].resources.food, 7 - payment.food);
assert.equal(after.players[0].resources.ore, 7 - (payment.ore ?? 0));
}
const invalid = happinessPreview(app.session(), (input) => c.query(input), undefined, undefined, { food: 1 });
assert.equal(invalid.action, null, 'underpayment cannot be submitted');
} finally {
app.close();
}
});

View file

@ -0,0 +1,28 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const move = (game: any, action: unknown) =>
JSON.parse(engine.tryMove(JSON.stringify(game), JSON.stringify(action), engine.currentPlayer(JSON.stringify(game))));
test('A good year allows a full-storage recipient and wastes their excess food', () => {
let game = JSON.parse(readFileSync(new URL('../../server/tests/test_games/incidents/good_year/good_year.json', import.meta.url), 'utf8'));
const third = structuredClone(game.players[1]);
third.id = 2;
third.civilization = 'India';
third.cities = [];
third.units = [];
third.resources.food = third.resource_limit.food;
game.players[2].id = 3;
game.players.splice(2, 0, third);
const otherFood = game.players[1].resources.food;
game = move(game, { Response: { SelectAdvance: 'Storage' } });
game = move(game, { Response: { SelectUnitType: 'Elephant' } });
const request = game.events.at(-1).handler.request.SelectPlayer;
assert.deepEqual(request.choices, [1, 2]);
game = move(game, { Response: { SelectPlayer: 2 } });
assert.equal(game.players[2].resources.food, third.resource_limit.food);
assert.equal(game.players[1].resources.food, otherFood);
});

View file

@ -1,4 +1,4 @@
import type { HappinessPreview, Session } from './types';
import type { HappinessPreview, Session, Pile } from './types';
type Query = <T>(input: unknown) => T;
@ -7,6 +7,8 @@ export function happinessPreview(
query: Query,
steps = session.happinessSteps ?? {},
lawgiverCity = session.happinessLawgiver ?? null,
payment?: Pile,
includePayments = false,
): HappinessPreview {
const cities = Object.entries(steps).filter(([, n]) => n > 0);
const variant = session.view?.happinessActions?.[session.happinessVariant ?? 0];
@ -14,6 +16,8 @@ export function happinessPreview(
try {
return query<HappinessPreview>({
kind: 'happiness',
payment,
includePayments,
cities,
variant: variant.value,
lawgiver: cities.some(([position]) => position === lawgiverCity),

View file

@ -197,6 +197,7 @@ test('Voting shows city costs separately and charges its fee once across the sel
assert.ok(request([[pos, 1]]).action);
assert.ok(request(both, regular.value).action);
assert.deepEqual(request(both), {
field: null,
payment: { mood_tokens: 5 },
action: null,
reason: 'Not enough resources',

View file

@ -651,6 +651,7 @@ export interface ActionVariant {
surcharge?: Pile;
}
export interface HappinessPreview {
field?: Decision['fields'][number] | null;
action: Move | null;
payment: Pile;
reason: string | null;