forked from WikiDeck/wikideck
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
655edf25b5 | ||
|
|
a0a051c10a | ||
|
|
b67192a08b | ||
|
|
2f1bba5e4c | ||
|
|
ec75875f0d | ||
|
|
a61c1a1342 | ||
|
|
75791f5861 | ||
|
|
7474b1c71d | ||
|
|
2cfdd9f437 | ||
|
|
26ad924565 | ||
|
|
86e544ea2e | ||
|
|
4bbc341bcb | ||
|
|
52c40bd3e3 | ||
|
|
bd6c7094b1 |
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="colorPrimary">#1e1e2e</color>
|
||||
<color name="colorPrimaryDark">#11111b</color>
|
||||
<color name="colorAccent">#cba6f7</color>
|
||||
<!-- Behind the status and navigation bars: matches the dark app header. -->
|
||||
<color name="wikideckChrome">#11111b</color>
|
||||
</resources>
|
||||
@@ -13,6 +13,9 @@
|
||||
<item name="windowActionBar">false</item>
|
||||
<item name="windowNoTitle">true</item>
|
||||
<item name="android:background">@null</item>
|
||||
<!-- Dark behind the status/navigation bars (edge-to-edge margins) to match the app chrome. -->
|
||||
<item name="android:windowBackground">@color/wikideckChrome</item>
|
||||
<item name="android:windowLightStatusBar">false</item>
|
||||
</style>
|
||||
|
||||
|
||||
|
||||
+84
-26
@@ -66,9 +66,15 @@ down. A `null` attention gives `pct_attention = null`.
|
||||
### 1.2 Fame → Cost
|
||||
`fame` = the integer mean (rounded half up) of the non-null percentiles.
|
||||
`cost` = 1 + the number of thresholds in `costThresholds` (5 ascending values, default
|
||||
`[15, 35, 55, 75, 90]`) that are ≤ `fame`. So cost runs 1–6.
|
||||
The defaults aim at a pool cost spread of about 15/20/20/20/15/10 %. They are retuned from the
|
||||
sample's fame distribution.
|
||||
`[26, 39, 51, 63, 78]` in v1.1) that are ≤ `fame`. So cost runs 1–6.
|
||||
**Thresholds are data, not guesses (v1.1).** `fame` is a *mean* of up to 3 percentiles, so it clusters
|
||||
around 50 even though each percentile is uniform. The v1.0 values `[15, 35, 55, 75, 90]` treated fame as
|
||||
uniform, so 82% of the pool landed on cost 2–4 (3/23/37/22/10/5 %). `costThresholds` is therefore set to
|
||||
the fame values at the **15/35/55/75/90 % points of the reference sample** (the same `card-sample.json`
|
||||
whose `percentiles` table §1.1 uses). That's the integer set that brings the sample's cost spread closest
|
||||
to the target 15/20/20/20/15/10 %. The v1.1 defaults come from the 236-card sample (fame 8–98) and
|
||||
give 13/20/22/20/15/10 %. Whenever council-data refreshes the sample, the percentile table and
|
||||
`costThresholds` are regenerated together and ship as one change. Pinned loaners (§2.1) are unaffected.
|
||||
|
||||
### 1.3 Power
|
||||
`power` = `powerByCost[cost]`, default `[_, 1, 2, 4, 6, 8, 10]` (cost 1 → 1 … cost 6 → 10). The
|
||||
@@ -96,7 +102,9 @@ mono-faction deck gains no consistency edge (§10: no v1 keyword scales with fac
|
||||
which means there is **no down arrow in v1**: 69% of cards trend negative, so a ▼ would mostly land as
|
||||
a quiet penalty on famous owned cards; modes can turn it back on), otherwise 0. A `null` value gives 0. Trend also needs `live.dailyAverage ≥ trendMinDaily` (default
|
||||
**20**), because percentages on tiny articles are noise; otherwise trend is 0. The host computes it **once at match start**, and it is frozen for
|
||||
the match. It shows as an arrow (▲/▼), not a number. It adds to power in every Topic.
|
||||
the match. It shows as an arrow (▲), not a number. It adds to power in every Topic. *Why no ▼ by default:* 69% of the sample has a
|
||||
negative `trendPercent`, and only busy (mostly owned, famous) cards pass `trendMinDaily`, so a ▼ would quietly penalise collectors.
|
||||
Modes may turn it back on with e.g. `trendDown: -25`.
|
||||
|
||||
### 1.7 Rarity
|
||||
The hash-derived `rarity` (`shared/protocol.ts:38`) is **cosmetic in v1** (frame colour only). Mining luck must not
|
||||
@@ -155,7 +163,7 @@ The engine does no I/O and only ever sees one version of each card.
|
||||
These are the default `starterDecks`: four 12-card loaner decks.
|
||||
- **Every deck has the same curve:** costs `1,1,2,2,3,3,3,4,4,5,5,6`. That's an average of 3.25, with 5 cards of cost 4 or more and 2 of cost 1.
|
||||
- **Every deck has the same shape:** 6 cards from each of two factions, and 4 cards for each home stat. So every deck can play on-topic in every lane.
|
||||
- **Loaner values are pinned.** council-data's percentile table and `starter-cards.json` don't exist yet, so a loaner carries
|
||||
- **Loaner values are pinned.** Cost, home and faction are hand-set (not derived from `starter-cards.json`), so a loaner carries
|
||||
`pinned: { cost, home, faction }`. For `check: 'loaner'` the engine takes these instead of §1.1–1.5.
|
||||
Everything after them still applies: `powerByCost`, `onTopicBonus`, `vanillaBonus`, the §10.1 keyword choice and `keywordParams`.
|
||||
A mode that changes those numbers changes loaners exactly as it changes owned cards.
|
||||
@@ -168,10 +176,12 @@ These are the default `starterDecks`: four 12-card loaner decks.
|
||||
The decks below pin their values on purpose, for two reasons. Famous, recognisable articles would all derive to cost 5–6.
|
||||
And the random sample has no Space cards (CARD_DATA.md finding 6).
|
||||
- **v1.1 note (factions):** CARD_DATA.md finding 6 shows the legacy `category()` split as Culture 53%, People 30%, Nature 9%,
|
||||
History 5%, Science 3%, Space 0%. Owned decks will therefore be about 50% viral and 30% local. Viral is the weakest keyword, so a typical owned deck
|
||||
History 5%, Science 3%, Space 0%. In v1, owned decks were therefore about 50% viral and 30% local. Viral was the weakest keyword, so a typical owned deck
|
||||
may be *weaker* than the starter decks. That's the wrong way round for "NFTs give variety, not power". v1 ships as is.
|
||||
For v1.1, sim-balance runs a **realistic owned deck** (12 cards drawn from `card-sample.json` with its real category mix)
|
||||
against each starter. If it wins under 45%, viral gets buffed first (e.g. cap 3, or a minimum of +1). The P31-based factions council-data proposes (People, Places, Nature, Works & Culture,
|
||||
against each starter. **v1.1 fix:** viral gets a base of +1, and Culture cards take a keyword by home stat (§10.1), so owned decks
|
||||
now have all six keywords in the mix. **BALANCE.md v1.1:** starters 52–53% overall, and owned vs starters 42–51%
|
||||
(weakest vs Headliners and Stargazers; v1.2 candidates: `nostalgic`/`translated` `powerDelta -1`, `local.amount 2`). The P31-based factions council-data proposes (People, Places, Nature, Works & Culture,
|
||||
Structures, Events & Ideas) are the v2 fix, and would need the host to fetch P31 (it isn't in `PageEnrichment`).
|
||||
|
||||
Keywords follow from §10.1: cost 1 → vanilla, otherwise the faction keyword (shown in brackets).
|
||||
@@ -208,7 +218,7 @@ Keywords follow from §10.1: cost 1 → vanilla, otherwise the faction keyword (
|
||||
| 5 | Great Wall of China | History | reach |
|
||||
| 6 | World War II | History | depth |
|
||||
|
||||
**C. Headliners: People (local) + Culture (viral)**
|
||||
**C. Headliners: People (local) + Culture (by home stat: attention → viral, depth → encyclopedic, reach → translated)**
|
||||
| Cost | Card | Faction | Home |
|
||||
|---|---|---|---|
|
||||
| 1 | Haiku | Culture | attention |
|
||||
@@ -311,6 +321,8 @@ The match lasts `turns` turns (default **6**, hard cap). Each turn has these pha
|
||||
- Each player queues an ordered list of plays `(handIndex, topic)`.
|
||||
- Total cost must be ≤ their energy, and each Topic needs room on that player's side.
|
||||
- Plays can be undone freely until **Commit**. Passing is an empty commit.
|
||||
- **Hidden means nothing leaks.** While you plan, the opponent's hand count and energy don't change
|
||||
visibly. Only the bare fact "opponent is ready" (`committed`) is shown. No queue count, no spent energy.
|
||||
- The turn timer is `turnSeconds` (default **25**). On timeout, whatever is queued is committed.
|
||||
4. **Reveal (interleaved)**
|
||||
- Plays reveal **one at a time, alternating**: the initiative player's 1st, the other player's
|
||||
@@ -360,13 +372,14 @@ the last turn's, and every "at scoring" Portal resolves **before** Topics are ju
|
||||
|
||||
| Line | Why it isn't dominant |
|
||||
|---|---|
|
||||
| All-famous (all max-stat) deck | It becomes an all-cost-5/6 deck with dead early turns. Cheap cards are more efficient **per energy**, expensive cards **per card**. Only 9 cards are seen per match (3 + 6 draws), so both matter. An all-cost-5/6 deck is **weak by design**: it has four dead turns (sim-balance interim: 0–15%). There is no hard deck rule in v1; the deck builder warns when a deck has fewer than 4 cards of cost ≤ 2, and every starter deck is curve-shaped (§2.1). **sim-balance target: a **top-heavy curve** (half the deck at cost 4 or more) vs curve ≥ 40%.** `energyByTurn [2..7]` is a v1.1 candidate. |
|
||||
| All-cheap flood (cost 1–2) | Weak by design: only 9 slots and 9 cards seen. Critic's sim under these rules: swarm vs curve about 7–11%. Its home is Culture's wide-turn keyword (§10). |
|
||||
| All one faction | No v1 keyword scales with faction count. `factionSynergyCap` is reserved for modes. Culture, the largest pool, has the weakest keyword (viral). |
|
||||
| "Always play the highest-power card" | It ignores the on-topic bonus, lane capacity and the hidden Portals. Critic's sim: 18–21% against a smart bot (target < 55%). |
|
||||
| All-famous (all max-stat) deck | It becomes an all-cost-5/6 deck with four dead early turns. Cheap cards are more efficient **per energy**, expensive cards **per card**, and only 9 cards are seen per match (3 + 6 draws). So a pure cost-5/6 deck is **weak by design**: **BALANCE.md v1: 15%**, and no lever (power curve, energy ramp) fixes it without breaking curve or swarm decks. There is no hard deck rule; the deck builder warns below 4 cards of cost ≤ 2, and every starter is curve-shaped (§2.1). **Target met:** a **top-heavy curve** (half the deck at cost 4 or more) wins **57%** (target ≥ 40%). `energyByTurn [2..7]` was rejected for v1.1: it lifts heavy decks but kills swarm (20%). |
|
||||
| All-cheap flood (cost 1–2) | Weak by design: only 9 slots and 9 cards seen. **BALANCE.md v1: 2%** (critic's sim 7–11%). Every lever that revives it breaks curve decks (sweep in BALANCE.md). viral (base +1, v1.1) is its consolation, not its fix. |
|
||||
| All one faction | No v1 keyword scales with faction count. `factionSynergyCap` is reserved for modes. Culture, the largest pool, splits over three keywords by home stat (§10.1), so it has no single keyword to stack. |
|
||||
| Owning NFTs buys power (pay-to-win) | Power depends only on cost (§1.3), and cost follows a fixed curve. **BALANCE.md v1.1 re-run (real `RULESET_V1_1`):** each starter deck averages **52–53%** overall. A realistic owned deck from `card-sample.json` wins **42–51%** against the starters (n ≈ 55 per pairing, ±13 pp). So owning cards buys variety, not power. v1.2 levers if owned decks should be a little stronger: `local.amount 2`, and `nostalgic`/`translated` `powerDelta -1` (the two strongest keywords, about +1.65 net per card). |
|
||||
| "Always play the highest-power card" | It ignores the on-topic bonus, lane capacity and the hidden Portals. **BALANCE.md v1:** the naive max-power line wins **40%** against greedy, and lookahead-lite beats greedy **60–70%**, so skill shows (target < 55%). Critic's sim: 18–21% against a smart bot. |
|
||||
| Stall or pass | Passing leaves lanes to any 1-power card. Two passing players draw. |
|
||||
| Mirror the AI | Hidden simultaneous commits: you only see the opponent's cards after you commit. |
|
||||
| Seat or initiative | Planning is simultaneous and initiative strictly alternates (each seat has it for 3 of the 6 turns). Target: each seat wins 48–52%. |
|
||||
| Seat or initiative | Planning is simultaneous and initiative strictly alternates (each seat has it for 3 of the 6 turns). **BALANCE.md v1.1 re-run (real `RULESET_V1_1`): first player 51.2% [48.8–53.6]** (target 48–52%; v1 was 53.4%). |
|
||||
| Forged or shopped stats | They only raise cost (§1.3), the host check falls back to live stats (§1.10), and trend is capped at ±1. |
|
||||
| Inflated live pageviews | Worth at most +1, frozen at match start, and only counts for articles with ≥ 20 views a day. |
|
||||
| Swinginess | No effect may change a lane by more than 6 power or move cards between lanes in v1 (a keyword-design rule for §10). |
|
||||
@@ -379,7 +392,7 @@ The engine takes a `RulesConfig` object. Peer-hosted modes override it (§11). D
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1.0",
|
||||
"version": "1.1",
|
||||
"deckSize": 12, "maxCopiesPerPage": 2, "maxLoaners": 12,
|
||||
"openingHand": 3, "handLimit": 7, "mulligan": false,
|
||||
"turns": 6, "turnSeconds": 25, "afkTurns": 2,
|
||||
@@ -388,10 +401,10 @@ The engine takes a `RulesConfig` object. Peer-hosted modes override it (§11). D
|
||||
"topicPool": [ /* inline Topic objects {id, name, stat, portal}; default = the 9 in §10.3 */ ],
|
||||
"keywordParams": { /* per-keyword numbers, keyed by keyword id (§10) */ },
|
||||
"portalParams": { /* per-Portal numbers, keyed by Topic id (§10.3) */ },
|
||||
"costThresholds": [15, 35, 55, 75, 90],
|
||||
"costThresholds": [26, 39, 51, 63, 78],
|
||||
"powerByCost": [0, 1, 2, 4, 6, 8, 10],
|
||||
"onTopicBonus": [0, 1, 1, 2, 2, 3, 3], "vanillaBonus": 1,
|
||||
"keywordsEnabled": ["viral","rising","local","encyclopedic","nostalgic","translated"], "ownedCards": true,
|
||||
"keywordsEnabled": ["viral","rising","local","encyclopedic","nostalgic","translated"], "cultureKeyword": "home", "ownedCards": true,
|
||||
"trendUp": 25, "trendDown": -200, "trendMinDaily": 20, "uncheckedCostCap": 4,
|
||||
"factionSynergyCap": 3,
|
||||
"verifyStats": true,
|
||||
@@ -418,7 +431,12 @@ Topics carry only a **stat**, never a faction. Every keyword below that mentions
|
||||
First rule that matches:
|
||||
1. `cost == 1` → **no keyword** (vanilla). The card gets +`vanillaBonus` power (default **1**), so a cost-1 card is 2.
|
||||
2. `"edition"` is in `keywordsEnabled` (off by default) and the deck holds another card with the same `pageId` → **edition**.
|
||||
3. Otherwise → the card's **faction keyword** from 10.2, if it's in `keywordsEnabled`. If not, the card is vanilla, *without* `vanillaBonus`.
|
||||
3. If the faction is **Culture** and `cultureKeyword` is `"home"` (v1.1 default) → the keyword for its **home stat**:
|
||||
attention → **viral**, depth → **encyclopedic**, reach → **translated**. (`"faction"` gives v1 behaviour: every Culture card is viral.)
|
||||
4. Otherwise → the card's **faction keyword** from 10.2.
|
||||
|
||||
In steps 3–4, if the chosen keyword isn't in `keywordsEnabled`, the card is vanilla, *without* `vanillaBonus`.
|
||||
*Why step 3:* Culture is about half of all owned cards. Without it, owned decks are half viral and see only 2 of the 6 keywords.
|
||||
|
||||
Rarity plays no part here (it's cosmetic, §1.7). Keywords don't lower power, and v1 has no per-keyword power deltas.
|
||||
If sim shows that a keyword is worth more than about 1 power on average, sim-balance sets `keywordParams.<id>.powerDelta` (default 0, range −3 to 0).
|
||||
@@ -427,16 +445,16 @@ If sim shows that a keyword is worth more than about 1 power on average, sim-bal
|
||||
|
||||
| Faction | id (card word) | Trigger | Reminder text | Cap | Order-sensitive? |
|
||||
|---|---|---|---|---|---|
|
||||
| Culture | **viral** | On reveal | +1 power for each other card you revealed earlier this turn. | +2 | yes: your queue order |
|
||||
| Culture | **viral** | On reveal | +1 power, plus +1 for each other card you revealed earlier this turn. | +3 | yes: your queue order |
|
||||
| Nature | **rising** | End of turn | +1 power. | +2 total | no |
|
||||
| People | **local** | Ongoing | +1 power while on-topic (the Topic's stat is its home stat). | +1 | no |
|
||||
| Science | **encyclopedic** | On reveal | +2 power if there are no other cards here (either side). | +2 | **yes: interleaving** |
|
||||
| Science | **encyclopedic** | On reveal | +2 power if you have no other cards here. | +2 | **yes: interleaving** |
|
||||
| History | **nostalgic** | On reveal | +2 power if you are losing here. | +2 | **yes: interleaving** |
|
||||
| Space | **translated** | On reveal | +1 power to your most recently revealed card in each *other* Topic. | +2 | yes |
|
||||
|
||||
Why this set: every keyword is one line and one trigger, and only adds power. The largest swing is +2 on one card,
|
||||
so no lane moves by more than 2 from a keyword. Nothing scales with faction count, so a mono-Culture deck gets no
|
||||
consistency edge (`factionSynergyCap` is unused in v1). Viral is Culture's weakest keyword, and it rewards wide turns.
|
||||
so no lane moves by more than 3 from a keyword (viral at its cap). Nothing scales with faction count, so a mono-Culture deck gets no
|
||||
consistency edge (`factionSynergyCap` is unused). Viral rewards wide turns, and Culture cards are spread over three keywords (§10.1 step 3).
|
||||
Three keywords (encyclopedic, nostalgic, translated) react to the interleaved reveal (§5.4), so initiative and queue order matter.
|
||||
|
||||
Precise rules (for engine-b):
|
||||
@@ -444,10 +462,12 @@ Precise rules (for engine-b):
|
||||
including earlier reveals this turn). The bonuses it grants are permanent counters.
|
||||
- **Ongoing** is a condition, recalculated whenever power is read.
|
||||
- **End of turn** resolves in §5.5 order: the initiative player's cards first, then Topic 1→3, then reveal order.
|
||||
- **viral:** counts the owner's cards revealed earlier in *this* turn's Reveal phase, in any Topic. Cards that went back to hand don't count.
|
||||
- **viral:** gain = min(`base` + `amount` × N, `cap`), where N = the owner's cards revealed earlier in *this* turn's Reveal phase, in any Topic.
|
||||
Cards that went back to hand don't count. v1.1: base 1, amount 1, cap 3 (v1 was base 0, cap 2).
|
||||
- **rising:** stops after it has gained +2 in total.
|
||||
- **local:** "on-topic" is exactly the §1.4/§6 condition. It's simply an extra +1 on top of `onTopicBonus`.
|
||||
- **encyclopedic:** "no other cards here" means both sides of this Topic are empty, apart from this card, when it reveals.
|
||||
- **encyclopedic:** with `sides: 1` (v1.1 default), "no other cards here" means **your** side of this Topic is empty, apart from this card,
|
||||
when it reveals; the opponent's cards don't matter. `sides: 2` is v1 (both sides empty).
|
||||
- **nostalgic:** "losing here" means the opponent's Topic power here is strictly greater than yours, counted just *before* this card is added.
|
||||
The consensus tie-break doesn't count: a tie is not losing.
|
||||
- **translated:** "most recently revealed" means the highest global reveal sequence number among your cards in that Topic. Topics where you have no card are skipped.
|
||||
@@ -463,13 +483,18 @@ These are engine-b's existing implementations. The faction-based versions of `lo
|
||||
|
||||
**`keywordParams` defaults** (keyed by keyword id; modes may change them within the §11 ranges):
|
||||
```json
|
||||
{ "viral": {"amount": 1, "cap": 2, "powerDelta": 0}, "rising": {"amount": 1, "cap": 2, "powerDelta": 0},
|
||||
"local": {"amount": 1, "powerDelta": 0}, "encyclopedic": {"amount": 2, "powerDelta": 0},
|
||||
{ "viral": {"base": 1, "amount": 1, "cap": 3, "powerDelta": 0}, "rising": {"amount": 1, "cap": 2, "powerDelta": -1},
|
||||
"local": {"amount": 1, "powerDelta": 0}, "encyclopedic": {"amount": 2, "sides": 1, "powerDelta": 0},
|
||||
"nostalgic": {"amount": 2, "powerDelta": 0}, "translated": {"amount": 1, "powerDelta": 0},
|
||||
"edition": {"amount": 2, "powerDelta": 0}, "obscure": {"powerDelta": 0}, "wildcard": {"powerDelta": 0} }
|
||||
```
|
||||
End-of-turn effects on the last turn resolve **before** scoring (§7).
|
||||
|
||||
**v1.2 candidates** (not in v1.1; decide on a larger run, per BALANCE.md's v1.1 re-run): the keyword values are still uneven:
|
||||
translated +1.64 and nostalgic +1.69 per card vs local +0.69 (critic's target was ±0.3). The starter decks stay even only because each one
|
||||
pairs a strong keyword with a weak one. The first levers are `nostalgic.powerDelta -1` and `translated.powerDelta -1`, plus `local.amount 2`
|
||||
if owned decks stay under 45% against Headliners. Both are config only.
|
||||
|
||||
### 10.3 Portals (Topic modifiers) and the default Topic pool
|
||||
Each Topic has `{ id, name, stat, portal | null }`. The default `topicPool` has 9 Topics, one plain and two with
|
||||
Portals for each stat. A Portal applies from the moment its Topic is revealed (§3), except where it says otherwise.
|
||||
@@ -529,7 +554,8 @@ A **mode** is data, published by a node operator and run by the match host:
|
||||
| `trendUp` / `trendDown` | 0–200 / −200–0 |
|
||||
| `factionSynergyCap` | 0–6 |
|
||||
| `keywordsEnabled` | any subset of the 9 implemented ids (the 6 v1 defaults + edition, obscure, wildcard); a card whose keyword is disabled is vanilla, *without* `vanillaBonus` |
|
||||
| `keywordParams`, `portalParams` | only the keys listed in §10 / §10.3; amounts and caps 0–6, `powerDelta` −3–0 |
|
||||
| `keywordParams`, `portalParams` | only the keys listed in §10 / §10.3; amounts and caps 0–6, `viral.base` 0–3, `encyclopedic.sides` 1–2, `powerDelta` −3–0 |
|
||||
| `cultureKeyword` | `"home"` or `"faction"` |
|
||||
| `verifyStats` | the host may only turn this off for modes that use only loaners (`maxLoaners == deckSize` and owned cards banned) |
|
||||
| `topicPool` | 3–20 Topics, Portal kinds only from 10.3 |
|
||||
|
||||
@@ -552,6 +578,9 @@ Example modes (good defaults for operators to publish):
|
||||
|
||||
## 12. Worked example match *(owner: council-designer-b)*
|
||||
|
||||
**Ruleset for this example: v1.0** (the golden test pins it): `cultureKeyword "faction"`, `viral {base 0, cap 2}`,
|
||||
`encyclopedic {sides 2}`, `rising.powerDelta 0`; everything else as §9. *(The v1.1 numbers are in §12.1.)*
|
||||
|
||||
These are the §1–9 rules as of this PR:
|
||||
- `powerByCost [0,1,2,4,6,8,10]`, `onTopicBonus [0,1,1,2,2,3,3]`, `vanillaBonus 1`
|
||||
- `laneCapacity 3`, `energyCarryMax 1`, interleaved reveals, alternating initiative, `portalReveal [2,3,4]`
|
||||
@@ -613,3 +642,32 @@ Final card values:
|
||||
- after turn 5, T2 is a 9–9 tie with Bo leading by consensus
|
||||
- Ana's carried energy is 1 at the start of turns 4, 5 and 6
|
||||
- Bo's carried energy is 1 at the start of turn 3
|
||||
|
||||
### 12.1 The same match under the v1.1 ruleset
|
||||
Same cards, Topics, hands and commit lists; ruleset = §9 defaults (v1.1: `viral {base 1, cap 3}`, `encyclopedic {sides 1}`,
|
||||
`rising.powerDelta -1`, `cultureKeyword "home"`). The example's Culture cards (Jazz, Pop music, Mona Lisa) are attention-home, so they stay viral.
|
||||
Energy and carry are unchanged.
|
||||
|
||||
What changes:
|
||||
- **rising −1:** Coral reef is 1 base and ends at 1+1+2 = **4**; Fern is 3 base and ends at 3+2+1 = **6**.
|
||||
- **viral base 1:** Jazz +2 (Mars earlier), Pop music +1 (base only), Mona Lisa +2 (Fern earlier).
|
||||
- **nostalgic still fires** for Library (Ana is losing T1 8–13 just before it). **encyclopedic still doesn't** (Einstein is already on Ana's side of T2).
|
||||
|
||||
| After turn | T1 | T2 | T3 |
|
||||
|---|---|---|---|
|
||||
| 1 | 3–0 | 0–3 | 0–0 |
|
||||
| 2 | 4–0 | 0–3 | 3–0 |
|
||||
| 3 | 7–0 | 0–9 | 3–3 |
|
||||
| 4 | 8–0 | 9–9 | 3–10 |
|
||||
| 5 | 8–8: **Ana leads** (consensus: on-topic 2 vs 0) | 9–10 | 13–11 |
|
||||
| 6, before scoring | 18–14 | 13–18 | 13–11 |
|
||||
| **final** (Main Page +1 per card in T2) | **18–14** | **15–21** | **13–11** |
|
||||
|
||||
**Ana still wins 2–1.** The moments in v1.1:
|
||||
- **Carry-over:** unchanged.
|
||||
- **Consensus:** moves to **T1 after turn 5** (8–8). Ana has two on-topic depth cards there (Octopus, Coral reef) and Bo has only the off-topic Jupiter.
|
||||
- **Interleaving:** unchanged in kind. If Ana had revealed Library before Fern, T1 would have been 8–8 at that moment, a tie is not losing,
|
||||
so nostalgic would not fire and T1 would end 16–14.
|
||||
|
||||
**v1.1 golden test:** expected `lanePower [[18,14],[15,21],[13,11]]`, winner p0. Also assert the T1 8–8 consensus lead for p0 after turn 5.
|
||||
(Cross-checked by council-critic with the #27 engine, `tower-plus:scratchpad/critic/golden11.ts`, and by hand by designer-b.)
|
||||
|
||||
@@ -174,7 +174,7 @@ interface CardInPlay { card: GameCard; owner: 0 | 1; lane: number; turn: number;
|
||||
interface PlayerView {
|
||||
you: 0 | 1; ruleset; turn; phase; initiative;
|
||||
energy: number; energyLeft: number; hand: GameCard[]; queue: { cardId; lane }[]; committed; deckCount;
|
||||
opponent: { handCount; deckCount; queuedCount; committed }; // never their cards or queue
|
||||
opponent: { handCount; deckCount; committed }; // §5.3: nothing about their queue (cards, count or energy) until reveal
|
||||
lanes: { topic: TopicDef /* stat always; id/name/portal masked until portalRevealed */, portalRevealed, cards: [mine, theirs],
|
||||
cardPower: [number[], number[]], power: [mine, theirs], leader: 'you' | 'opponent' | null }[];
|
||||
result: MatchResult | null;
|
||||
|
||||
@@ -121,6 +121,15 @@ also gets a fresh bearer token per lobby; only its hash is kept. When eom.dev ac
|
||||
shows peer modes with "Hosted by …" and links to the peer's own site to play there. No node
|
||||
proxies another node's matches.
|
||||
|
||||
### Restarts
|
||||
|
||||
Live lobbies, drafts and matches survive a node restart. The node saves them to
|
||||
`$WIKIDECK_DATA_DIR/game/live.json` every 15 s and on SIGTERM/SIGINT, and restores them on start.
|
||||
Player tokens keep working, and turn and draft timers restart from the moment the node is back.
|
||||
A lobby is dropped instead of restored if its mode is no longer hosted with the same `version`
|
||||
and rules, so a match never continues under different rules. A hard crash can lose up to 15 s
|
||||
of moves.
|
||||
|
||||
## 4. Credit for hosts
|
||||
|
||||
Every mode shows **"Hosted by <operator>"** (with the node's origin), its player counts,
|
||||
@@ -255,3 +264,9 @@ be pinned in consensus.
|
||||
starting with the preview-card pages. A card whose page isn't warm yet gets no bonus. This
|
||||
keeps load on the shared, rate-limited Wikipedia egress tiny: a few dozen pages per 6 hours per node.
|
||||
- Spectating and rematches.
|
||||
- **Separate game RPC budget.** `/api/game` sits behind the node's global `/api` admission
|
||||
budget (`WIKIDECK_RPC_REQUESTS_PER_SECOND`, 10 writes/s node-wide), so a flood of game
|
||||
traffic can delay chain RPC (and the reverse). At human speed this is fine. The fix is to give
|
||||
game routes their own `RpcBudget`, which means mounting them ahead of the shared budget in
|
||||
`server/testnet/http.ts`: a change to that shared file, so it's proposed in #6 rather than made
|
||||
tonight.
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# WikiDeck Android app (Night 1)
|
||||
|
||||
A Capacitor 7 shell (`dev.eom.wikideck`) around the React UI. It talks to a WikiDeck node over native HTTP.
|
||||
|
||||

|
||||
|
||||
## Build a debug APK
|
||||
You need JDK 21 (a full JDK with `javac`), the Android SDK (platform 35 and build-tools 35) and `ANDROID_HOME`.
|
||||
```
|
||||
android/build-debug.sh # testnet build: VITE_WIKIDECK_NETWORK=testnet, genesis 1792411200, node http://192.168.1.32:3101
|
||||
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
|
||||
```
|
||||
- **Settings:** override any of them with env vars, for example `VITE_NODE_URL=http://192.168.1.32:3102 android/build-debug.sh`.
|
||||
- **Network:** without `VITE_WIKIDECK_NETWORK=testnet`, the bundle is a **mainnet** build.
|
||||
- **Signing:** debug signing only. Nothing is published.
|
||||
|
||||
## How it works (`src/native.ts`, imported first in `main.tsx`; does nothing on the web)
|
||||
- **Node URL:** relative `fetch('/api/…')` and `fetch('/auth/…')` calls go to `VITE_NODE_URL`. The default is the Night-1 testnet node. A runtime override is available through `setNodeUrl()`, stored in localStorage.
|
||||
- **Native HTTP (`CapacitorHttp`):** fetches go through Android's HTTP stack. There's no CORS, and no WebView `Origin` header, so the node's POST origin check passes without any server change.
|
||||
- Verified: a POST from the app returns 400 (validation), while the same POST with `Origin: https://localhost` returns 403.
|
||||
- The interceptor merges headers (`content-length: 0, 384`). `native.ts` drops that header so `StateClient`'s size check works, and byte limits are still enforced while streaming.
|
||||
- **Mining:** RandomX is desktop-only. `isNativeApp()` hides the mining panel, and `html.native-app` lets CSS target the app.
|
||||
- **SSO:** "Log in with eom.dev" opens Dex in a Custom Tab (`setNativeBrowser(Browser)`). Dex redirects to `dev.eom.wikideck:/oauth/callback` (intent filter, `singleTask`), and `completeLogin()` has the node exchange the code.
|
||||
- **Android behaviour:**
|
||||
- The **back button** closes an open dialog first, then goes back in history, then minimizes the app.
|
||||
- The **keyboard** uses `adjustResize`.
|
||||
- **Edge-to-edge** margins are on, with a dark window behind the system bars.
|
||||
|
||||
## Emulator (inspiron-3670, user space)
|
||||
The SDK, AVD and JDK are under `~/worker/jobs/night/mobile-android/{sdk,avd,jdk}`, and `env.sh` sets the paths.
|
||||
```
|
||||
emulator -avd wikideck -no-window -no-audio -gpu swiftshader_indirect # headless, KVM
|
||||
adb exec-out screencap -p > shot.png
|
||||
```
|
||||
To inspect the WebView, forward DevTools with `adb forward tcp:9222 localabstract:webview_devtools_remote_$(adb shell pidof dev.eom.wikideck)`.
|
||||
|
||||
## Known gaps
|
||||
- **Real SSO login:** needs an eom.dev account and wasn't done tonight. The deep-link round trip was verified up to Dex's `invalid_grant` for a dummy code.
|
||||
- **Touch targets in the Play UI:** the dashed "Play here" lane zone doesn't respond to taps; only the lane plate does (reported on #5).
|
||||
- **Mining copy on the home hero:** "Explore mining" still shows in the app.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 143 KiB |
@@ -1,18 +1,23 @@
|
||||
/** Binds the mode host to the real engine through its public API (shared/game/index.ts). */
|
||||
import { DEFAULT_RULESET, parseRuleset, starterDeck, loanerCard, STARTER_POOL, validateDeck, createMatch,
|
||||
import { DEFAULT_RULESET, parseRuleset, starterDeck, previewPool as engineLoaners, validateDeck, createMatch,
|
||||
legalActions, applyAction, isOver, result, viewFor, Rng,
|
||||
type Action, type GameCard, type MatchState, type Ruleset } from '../../shared/game/index.ts';
|
||||
import type { EnginePort, Seat } from './engine-port.ts';
|
||||
|
||||
/**
|
||||
* Deterministic pool of loaner (non-NFT) cards for draft modes: seeded shuffles of the
|
||||
* starter pool, one copy per round, never exceeding the ruleset's per-page copy limit.
|
||||
* Deterministic pool of loaner (non-NFT) cards for draft modes: seeded shuffles of the engine's
|
||||
* frozen loaner cards (`previewPool(rules)`, derived with the mode's rules), one copy per round,
|
||||
* never exceeding the ruleset's per-page copy limit. Copies get distinct cardIds.
|
||||
*/
|
||||
export function previewPool(rules: Ruleset, seed: string, size: number): GameCard[] {
|
||||
const rng = Rng.fromSeed(`draft-pool:${seed}`);
|
||||
const loaners = engineLoaners(rules);
|
||||
const pool: GameCard[] = [];
|
||||
for (let copy = 0; pool.length < size && copy < rules.maxCopiesPerPage; copy++) {
|
||||
for (const spec of rng.shuffle(STARTER_POOL)) { if (pool.length >= size) break; pool.push(loanerCard(spec, copy)); }
|
||||
for (const card of rng.shuffle(loaners)) {
|
||||
if (pool.length >= size) break;
|
||||
pool.push({ ...card, cardId: `${card.cardId}:${copy}` });
|
||||
}
|
||||
}
|
||||
return pool;
|
||||
}
|
||||
|
||||
@@ -212,6 +212,45 @@ export class ModeHost {
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live lobbies and matches as JSON, so a restart (e.g. a redeploy) doesn't lose games.
|
||||
* Only the host's own data dir ever holds this; token hashes, never tokens, are stored.
|
||||
*/
|
||||
snapshot(): string {
|
||||
const live = [...this.lobbies.values()].filter(l => l.phase === 'waiting' || l.phase === 'drafting' || l.phase === 'playing');
|
||||
return JSON.stringify({ schema: 'wikideck-live-lobbies/1', savedAt: this.now(), lobbies: live.map(l => ({
|
||||
...l, mode: { id: l.mode.id, version: l.mode.version },
|
||||
players: l.players.map(p => ({ ...p, tokenHash: p.tokenHash.toString('hex') })) })) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore a snapshot written by `snapshot()`. Lobbies whose mode is no longer hosted with the
|
||||
* same version and rules are dropped. Timers restart from now, so nobody times out because
|
||||
* the node was down. Returns how many lobbies were restored.
|
||||
*/
|
||||
restore(json: string): number {
|
||||
const data = JSON.parse(json) as { schema?: string; lobbies?: any[] };
|
||||
if (data.schema !== 'wikideck-live-lobbies/1' || !Array.isArray(data.lobbies)) return 0;
|
||||
const now = this.now();
|
||||
let restored = 0;
|
||||
for (const raw of data.lobbies.slice(0, this.maxLobbies)) {
|
||||
const h = this.hosted.get(raw?.mode?.id);
|
||||
if (!h || h.mode.version !== raw.mode.version || JSON.stringify(h.rules) !== JSON.stringify(raw.rules)) continue;
|
||||
if (typeof raw.id !== 'string' || !LOBBY_ID.test(raw.id) || this.lobbies.has(raw.id)) continue;
|
||||
if (!['waiting', 'drafting', 'playing'].includes(raw.phase) || !Array.isArray(raw.players) || raw.players.length < 1 || raw.players.length > 2) continue;
|
||||
const lobby: Lobby = { ...raw, mode: h.mode, rules: h.rules,
|
||||
players: raw.players.map((p: any) => ({ id: String(p.id), name: String(p.name), seen: now, tokenHash: Buffer.from(String(p.tokenHash), 'hex') })),
|
||||
lastMove: now, createdAt: raw.phase === 'waiting' ? now : raw.createdAt, turnStartedAt: now };
|
||||
if (lobby.players.some(p => p.tokenHash.length !== 32)) continue;
|
||||
if (lobby.draft && lobby.mode.decks.kind === 'draft') lobby.draft.deadline = now + lobby.mode.decks.pickSeconds * 1000;
|
||||
if (lobby.phase === 'playing' && (lobby.state === undefined || !lobby.decks)) continue;
|
||||
if (lobby.phase === 'drafting' && !lobby.draft) continue;
|
||||
this.lobbies.set(lobby.id, lobby);
|
||||
restored++;
|
||||
}
|
||||
return restored;
|
||||
}
|
||||
|
||||
/** Expire idle lobbies, auto-pick stalled drafts, forfeit stalled matches, drop old lobbies. */
|
||||
sweep(): void {
|
||||
const now = this.now();
|
||||
|
||||
+33
-1
@@ -3,6 +3,7 @@
|
||||
* app.use('/api/game', await (await import('../game/index.ts')).gameRouter({ dataDir, enrichment: wikipediaEnrichment }));
|
||||
*/
|
||||
import { join } from 'node:path';
|
||||
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
||||
import type express from 'express';
|
||||
import { loadModes, hostIdentity, gamePeers } from './config.ts';
|
||||
import { ModeDiscovery } from './discovery.ts';
|
||||
@@ -15,7 +16,7 @@ import { TrendCache } from './trends.ts';
|
||||
type Enrichment = { get(pageId: number): Promise<{ pageviews: { trendPercent: number | null } }> };
|
||||
|
||||
export async function gameRouter(options: { dataDir: string | null; enrichment?: Enrichment;
|
||||
engine?: EnginePort<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean }): Promise<express.Router> {
|
||||
engine?: EnginePort<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean }): Promise<express.Router> {
|
||||
const env = options.env ?? process.env;
|
||||
const engine = options.engine ?? (await import('./engine-binding.ts')).engineBinding;
|
||||
const modes = loadModes(env);
|
||||
@@ -39,7 +40,38 @@ export async function gameRouter(options: { dataDir: string | null; enrichment?:
|
||||
store: new MatchStore(options.dataDir ? join(options.dataDir, 'game') : null),
|
||||
liveData: trends ? async pageId => trends!.get(pageId) : undefined });
|
||||
const discovery = new ModeDiscovery({ peers: gamePeers(env) });
|
||||
if (options.dataDir) persistLive(host, join(options.dataDir, 'game'), options.handleSignals !== false);
|
||||
const timer = setInterval(() => host.sweep(), 5_000);
|
||||
timer.unref();
|
||||
return createGameRouter(host, discovery);
|
||||
}
|
||||
|
||||
const MAX_LIVE_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Keep live lobbies and matches across restarts: restore `live.json` on start, save it every
|
||||
* 15 s and synchronously on SIGTERM/SIGINT. These listeners are registered when the router is
|
||||
* mounted, before the node's own shutdown handler, so the save finishes before it exits.
|
||||
*/
|
||||
export function persistLive(host: ModeHost, directory: string, handleSignals: boolean): { save(): void } {
|
||||
const file = join(directory, 'live.json');
|
||||
if (existsSync(file)) {
|
||||
try {
|
||||
const text = readFileSync(file, 'utf8');
|
||||
if (text.length <= MAX_LIVE_BYTES) console.log(`Game modes: restored ${host.restore(text)} live lobbies`);
|
||||
} catch (e) { console.error(`Game modes: could not restore live lobbies: ${(e as Error).message.slice(0, 200)}`); }
|
||||
// Keep the file we restored from for inspection; the next save writes a fresh one.
|
||||
try { renameSync(file, `${file}.restored`); } catch { /* ignore */ }
|
||||
}
|
||||
const save = () => {
|
||||
try {
|
||||
const tmp = `${file}.tmp`;
|
||||
writeFileSync(tmp, host.snapshot(), { mode: 0o600 });
|
||||
renameSync(tmp, file);
|
||||
} catch (e) { console.error(`Game modes: could not save live lobbies: ${(e as Error).message.slice(0, 200)}`); }
|
||||
};
|
||||
const timer = setInterval(save, 15_000);
|
||||
timer.unref();
|
||||
if (handleSignals) for (const signal of ['SIGTERM', 'SIGINT'] as const) process.once(signal, save);
|
||||
return { save };
|
||||
}
|
||||
|
||||
@@ -75,7 +75,9 @@ export function stateFromView(view: PlayerView, rng: Rng, filler: readonly GameC
|
||||
const me = view.you, them = other(me);
|
||||
const players = [] as unknown as [PlayerState, PlayerState];
|
||||
players[me] = { deck: draw(view.deckCount), hand: view.hand, energy: view.energy, queue: view.queue, committed: view.committed, afk: 0, carry: 0 };
|
||||
players[them] = { deck: draw(view.opponent.deckCount), hand: draw(view.opponent.handCount + view.opponent.queuedCount), energy: view.energy, queue: [], committed: false, afk: 0, carry: 0 };
|
||||
// Before #38 handCount excludes queued cards and queuedCount exists; after #38 handCount is the full hand.
|
||||
const o = view.opponent as { handCount: number; deckCount: number; queuedCount?: number };
|
||||
players[them] = { deck: draw(o.deckCount), hand: draw(o.handCount + (o.queuedCount ?? 0)), energy: view.energy, queue: [], committed: false, afk: 0, carry: 0 };
|
||||
let seq = 0;
|
||||
const lanes = view.lanes.map(l => {
|
||||
const cards = [] as unknown as [CardInPlay[], CardInPlay[]];
|
||||
|
||||
+4
-10
@@ -3,7 +3,8 @@
|
||||
* Pure and deterministic. The engine itself never reads raw 0–100 stats; hosts call
|
||||
* deriveCard() before createMatch. Owner: engine-b.
|
||||
*/
|
||||
import { FACTION_KEYWORD, V1_KEYWORDS } from './keywords.ts';
|
||||
import { FACTION_KEYWORD } from './keywords.ts';
|
||||
import { DEFAULT_RULESET } from './ruleset.ts';
|
||||
import { STATS, type Faction, type GameCard, type Rarity, type Stat } from './types.ts';
|
||||
|
||||
/** §1.4 tie-break order: depth and reach are the hardest to inflate. */
|
||||
@@ -44,15 +45,8 @@ export interface DerivationRules {
|
||||
uncheckedCostCap: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_DERIVATION: DerivationRules = {
|
||||
costThresholds: [15, 35, 55, 75, 90],
|
||||
powerByCost: [0, 1, 2, 4, 6, 8, 10],
|
||||
vanillaBonus: 1,
|
||||
keywordsEnabled: V1_KEYWORDS,
|
||||
keywordParams: {},
|
||||
trendUp: 25, trendDown: -200, trendMinDaily: 20, // −200: no down arrow in v1 (§1.6)
|
||||
uncheckedCostCap: 4,
|
||||
};
|
||||
/** Derivation defaults are the engine's DEFAULT_RULESET (a Ruleset is a DerivationRules). */
|
||||
export const DEFAULT_DERIVATION: DerivationRules = DEFAULT_RULESET;
|
||||
|
||||
/** §1.1: cut points strictly below, plus half of those equal, rounded down. */
|
||||
export function percentile(score: number, cuts: readonly number[]): number {
|
||||
|
||||
@@ -399,7 +399,7 @@ export function viewFor(state: MatchState, you: PlayerId): PlayerView {
|
||||
you, ruleset: state.ruleset, turn: state.turn, phase: state.phase, initiative: state.initiative,
|
||||
energy: me.energy, energyLeft: me.energy - queuedCost(me), hand: me.hand, queue: me.queue,
|
||||
committed: me.committed, deckCount: me.deck.length,
|
||||
opponent: { handCount: opp.hand.length - opp.queue.length, deckCount: opp.deck.length, queuedCount: opp.queue.length, committed: opp.committed },
|
||||
opponent: { handCount: opp.hand.length, deckCount: opp.deck.length, committed: opp.committed },
|
||||
lanes: state.lanes.map((lane, index) => {
|
||||
const power = lanePower(state, index);
|
||||
const mine = power[you], theirs = power[them];
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Public entry point of the WikiDeck game engine. Other teams import only from here. See docs/game/ENGINE_API.md. */
|
||||
export * from './types.ts';
|
||||
export { Rng, seedFromString, normalizeSeed, type RngState } from './rng.ts';
|
||||
export { DEFAULT_RULESET, RULESET_V1_0, DEFAULT_TOPIC_POOL, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts';
|
||||
export { DEFAULT_RULESET, RULESET_V1_0, RULESET_V1_1, DEFAULT_TOPIC_POOL, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts';
|
||||
export {
|
||||
ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor,
|
||||
serialize, deserialize, replay, validateDeck, cardPower, lanePower, laneLeader, laneCapacity, scoringPower, topicsLed, other, placeCard, revealPortal,
|
||||
|
||||
+19
-2
@@ -127,5 +127,22 @@ export const RULESET_V1_0: Ruleset = {
|
||||
starterDecks: 'default',
|
||||
};
|
||||
|
||||
/** DESIGN §9 defaults: the current rules version. */
|
||||
export const DEFAULT_RULESET: Ruleset = RULESET_V1_0;
|
||||
/**
|
||||
* DESIGN §9 v1.1 (PR #32): config-only changes on top of v1.0. costThresholds are fame quantiles of the
|
||||
* 236-card card-sample percentile table (#28), so they ship together with that table (shared/game/card-data.ts).
|
||||
*/
|
||||
export const RULESET_V1_1: Ruleset = {
|
||||
...RULESET_V1_0,
|
||||
version: '1.1',
|
||||
costThresholds: [26, 39, 51, 63, 78],
|
||||
cultureKeyword: 'home',
|
||||
keywordParams: {
|
||||
...RULESET_V1_0.keywordParams,
|
||||
viral: { base: 1, amount: 1, cap: 3, powerDelta: 0 },
|
||||
rising: { amount: 1, cap: 2, powerDelta: -1 },
|
||||
encyclopedic: { amount: 2, sides: 1, powerDelta: 0 },
|
||||
},
|
||||
};
|
||||
|
||||
/** DESIGN §9 defaults: the current rules version (v1.1, BALANCE.md 00:45: ship #32 as is). */
|
||||
export const DEFAULT_RULESET: Ruleset = RULESET_V1_1;
|
||||
|
||||
@@ -210,7 +210,11 @@ export interface PlayerView {
|
||||
queue: QueuedPlay[];
|
||||
committed: boolean;
|
||||
deckCount: number;
|
||||
opponent: { handCount: number; deckCount: number; queuedCount: number; committed: boolean };
|
||||
/**
|
||||
* DESIGN §5.3: planning is hidden. handCount still counts queued cards and no
|
||||
* opponent energy is exposed, so nothing changes while they queue; only `committed` does.
|
||||
*/
|
||||
opponent: { handCount: number; deckCount: number; committed: boolean };
|
||||
lanes: {
|
||||
/** Always visible; `portal` is null until the Portal is revealed. */
|
||||
topic: TopicDef;
|
||||
|
||||
@@ -16,6 +16,7 @@ import { IS_MAINNET, NETWORK_GENESIS_TIME, NETWORK_LABEL } from '../shared/netwo
|
||||
import { StateClient } from '../shared/rpc-client.ts';
|
||||
import { PlaySection } from './game/PlaySection.tsx';
|
||||
import { isNativeApp } from './native.ts';
|
||||
import { Landing } from './Landing.tsx';
|
||||
import './App.css';
|
||||
import './testnet.css';
|
||||
|
||||
@@ -182,6 +183,7 @@ export default function App() {
|
||||
<div className="hero-copy"><span className="eyebrow"><span /> MINE · COLLECT · TRADE CARDS</span><h1>Mine with your CPU.<br />Collect <span>the world.</span></h1><p>Turn illustrated Wikipedia discoveries into collectible cards. Mine with RandomX, build a collection around what you love, and trade cards directly with other collectors.</p><div className="hero-actions"><button className="button dark" onClick={goMine}><Pickaxe size={17} /> Explore mining <ArrowUpRight size={17} /></button><button className="text-button" onClick={() => setDialog('guide')}>How it works <ArrowRight size={16} /></button></div><div className="hero-foot"><span><Check size={13} /> CPU-friendly RandomX</span><span><Check size={13} /> Direct card-for-card trades</span></div></div>
|
||||
<div className="hero-visual"><div className="orbit orbit-one" /><div className="orbit orbit-two" /><span className="orbit-spark spark-one">✳</span><span className="orbit-spark spark-two">+</span><div className="floating-label label-top"><Sparkles size={12} /> Preview cards · not owned</div><div className="hero-card back-card"><Card card={samples[2]} onClick={() => setSelected(samples[2])} /></div><div className="hero-card front-card"><Card card={samples[0]} onClick={() => setSelected(samples[0])} /></div><div className="floating-label label-bottom"><Sparkles size={15} /> A world worth collecting <ArrowUpRight size={13} /></div></div>
|
||||
</section>
|
||||
<Landing onPlay={() => setView('Play')} />
|
||||
<section className="metrics" aria-label="Canonical chain statistics">
|
||||
<div><span className="metric-icon"><Layers3 size={19} /></span><div><span>Native NFTs minted</span><strong>{snapshot?.blocks.length.toLocaleString() ?? '—'}<small>canonical chain</small></strong></div></div>
|
||||
<div><span className="metric-icon"><Globe2 size={19} /></span><div><span>Block height</span><strong>{snapshot ? `#${snapshot.blocks.at(-1)?.height ?? 0}` : '—'}<small>current tip</small></strong></div></div>
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { BookOpen, Globe2, Megaphone, Play, Swords } from 'lucide-react';
|
||||
import './landing.css';
|
||||
|
||||
/** Game landing block (upstream WikiDeck/wikideck#3): explains Edit War and leads into Play. */
|
||||
export function Landing({ onPlay, onHowToPlay }: { onPlay: () => void; onHowToPlay?: () => void }) {
|
||||
return <section className="game-landing" aria-labelledby="game-landing-title">
|
||||
<div className="game-landing-copy">
|
||||
<div className="section-eyebrow"><Swords size={12} /> PLAY · EDIT WAR</div>
|
||||
<h2 id="game-landing-title">Your cards are a deck. Play it.</h2>
|
||||
<p>Edit War is a quick two-player card game, about 3–6 minutes a match. Each card is a Wikipedia article.
|
||||
Its power comes from how famous the article is, and it is strongest in a Topic that matches its best stat.</p>
|
||||
<ol className="game-landing-steps">
|
||||
<li><span>1</span><div><strong>Three Topics</strong><p>Each is judged on one stat: <Megaphone size={12} aria-hidden="true" /> attention, <BookOpen size={12} aria-hidden="true" /> depth or <Globe2 size={12} aria-hidden="true" /> reach.</p></div></li>
|
||||
<li><span>2</span><div><strong>Six turns</strong><p>Energy grows each turn. You and your opponent plan at the same time, then cards reveal one by one.</p></div></li>
|
||||
<li><span>3</span><div><strong>Win two Topics</strong><p>Lead in more Topics than your opponent when turn 6 ends.</p></div></li>
|
||||
</ol>
|
||||
<p className="game-landing-note">No cards yet? Pick a starter deck and play right away. Matches are off-chain: no card is ever moved or burned.</p>
|
||||
<div className="game-landing-actions">
|
||||
<button className="button dark game-landing-play" onClick={onPlay}><Play size={15} /> Play now</button>
|
||||
{onHowToPlay && <button className="text-button" onClick={onHowToPlay}>How to play</button>}
|
||||
</div>
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState, useSyncExternalStore } from 'react';
|
||||
import { Link2, LoaderCircle, LogIn, LogOut, UserRound } from 'lucide-react';
|
||||
import { getWallet, subscribeWallet, type Wallet } from '../wallet.ts';
|
||||
import { account, completeLogin, isCallback, linkWallet, login, logout, subscribeAuth, type Account } from './session.ts';
|
||||
import { account, authError, clearAuthError, completeLogin, isCallback, linkWallet, login, logout, subscribeAuth, type Account } from './session.ts';
|
||||
import './auth.css';
|
||||
|
||||
export function useAccount(): Account | undefined {
|
||||
@@ -20,6 +20,8 @@ const short = (s: string) => `${s.slice(0, 6)}…${s.slice(-4)}`;
|
||||
|
||||
export function LoginButton() {
|
||||
const me = useAccount();
|
||||
// Login failures from the web callback or a native deep link (completeLogin) land here.
|
||||
const loginError = useSyncExternalStore(subscribeAuth, authError, () => '');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [notice, setNotice] = useState('');
|
||||
@@ -30,7 +32,7 @@ export function LoginButton() {
|
||||
setBusy(true);
|
||||
completeLogin(location.href)
|
||||
.then(({ returnTo }) => history.replaceState(null, '', returnTo))
|
||||
.catch(e => { history.replaceState(null, '', '/'); setNotice(e instanceof Error ? e.message : 'Login failed'); })
|
||||
.catch(() => { history.replaceState(null, '', '/'); })
|
||||
.finally(() => setBusy(false));
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
@@ -39,7 +41,7 @@ export function LoginButton() {
|
||||
}, []);
|
||||
|
||||
const run = async (fn: () => Promise<unknown>) => {
|
||||
setBusy(true); setNotice('');
|
||||
setBusy(true); setNotice(''); clearAuthError();
|
||||
try { await fn(); } catch (e) { setNotice(e instanceof Error ? e.message : 'Request failed'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
@@ -49,7 +51,7 @@ export function LoginButton() {
|
||||
<span className="wallet-avatar">{busy ? <LoaderCircle className="spin" size={14} /> : <LogIn size={14} />}</span>
|
||||
<span className="auth-label">Log in with eom.dev</span>
|
||||
</button>
|
||||
{notice && <span className="auth-notice" role="alert">{notice}</span>}
|
||||
{(notice || loginError) && <span className="auth-notice" role="alert">{notice || loginError}</span>}
|
||||
</span>;
|
||||
|
||||
const linked = wallet && me.wallets.some(w => w.address === wallet.address);
|
||||
|
||||
@@ -33,6 +33,11 @@ function save(s: Session | undefined) {
|
||||
try { if (s) sessionStorage.setItem(SESSION_KEY, JSON.stringify(s)); else sessionStorage.removeItem(SESSION_KEY); } catch { /* memory only */ }
|
||||
notify();
|
||||
}
|
||||
let loginError = '';
|
||||
/** Last login failure (expired, state mismatch, cancelled, invalid_grant…), for the UI; '' when none. */
|
||||
export const authError = (): string => loginError;
|
||||
export function clearAuthError(): void { if (loginError) { loginError = ''; notify(); } }
|
||||
|
||||
export function account(): Account | undefined {
|
||||
if (current && current.expiresAt <= Date.now() + 30_000) save(undefined);
|
||||
return current?.account;
|
||||
@@ -102,6 +107,17 @@ export const isCallback = (url: string) => {
|
||||
|
||||
/** Finish a login from the redirect URL. Web: called on load. Capacitor: call from App 'appUrlOpen'. */
|
||||
export async function completeLogin(url: string): Promise<{ returnTo: string }> {
|
||||
try {
|
||||
const result = await finishLogin(url);
|
||||
clearAuthError();
|
||||
return result;
|
||||
} catch (e) {
|
||||
loginError = (e instanceof Error ? e.message : 'Login failed').slice(0, 200); notify();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function finishLogin(url: string): Promise<{ returnTo: string }> {
|
||||
const params = new URL(url).searchParams;
|
||||
const raw = sessionStorage.getItem(PENDING_KEY);
|
||||
sessionStorage.removeItem(PENDING_KEY); // single use
|
||||
|
||||
+13
-9
@@ -7,8 +7,8 @@ import type { LaneView, MatchView, UIAction, UICard } from './types.ts';
|
||||
type Sheet = { kind: 'card'; card: UICard; side: 'mine' | 'theirs' } | { kind: 'lane'; lane: LaneView } | { kind: 'concede' } | null;
|
||||
|
||||
/** The match screen itself: board, thumb dock and bottom sheets. Controllers (local bot / hosted lobby) feed it. */
|
||||
export function MatchBoard({ title, opponent, view, legal, onAct, problem, error, onTopicBonus }: {
|
||||
title: string; opponent: string; view: MatchView; legal: UIAction[]; onAct: (a: UIAction) => void;
|
||||
export function MatchBoard({ title, opponent, view, legal, onAct, problem, error, onTopicBonus, onResults }: {
|
||||
onResults?: () => void; title: string; opponent: string; view: MatchView; legal: UIAction[]; onAct: (a: UIAction) => void;
|
||||
problem?: (a: UIAction) => string | null; error?: string; onTopicBonus: number[];
|
||||
}) {
|
||||
const [selected, setSelected] = useState<string>();
|
||||
@@ -45,12 +45,13 @@ export function MatchBoard({ title, opponent, view, legal, onAct, problem, error
|
||||
else setSheet({ kind: 'lane', lane });
|
||||
};
|
||||
const ending = view.waitingForOpponent;
|
||||
const queuedCount = view.lanes.reduce((n, l) => n + l.staged.length, 0);
|
||||
const lastEvent = view.log.at(-1);
|
||||
|
||||
return <section className="match" aria-label={title}>
|
||||
<header className="match-bar">
|
||||
<span className="match-turn"><Hourglass size={14} /> Turn <b>{view.turn}</b>/{view.maxTurns}</span>
|
||||
<span className="match-opp" aria-label={`Opponent: ${view.oppHandCount} cards in hand, ${view.oppDeckCount} in deck`}>{opponent} · <Layers3 size={13} /> {view.oppHandCount}{view.oppQueued ? ` · ${view.oppQueued} queued` : ''}</span>
|
||||
<span className="match-opp" aria-label={`Opponent: ${view.oppHandCount} cards in hand, ${view.oppDeckCount} in deck`}>{opponent} · <Layers3 size={13} /> {view.oppHandCount}</span>
|
||||
<button className="icon-button" onClick={() => setSheet({ kind: 'concede' })} aria-label="Concede match"><Flag size={16} /></button>
|
||||
</header>
|
||||
{banner && <div className="turn-banner" role="status">{banner}</div>}
|
||||
@@ -67,11 +68,11 @@ export function MatchBoard({ title, opponent, view, legal, onAct, problem, error
|
||||
</div>
|
||||
<button className={`lane-plate ${lead}`} onClick={() => tapLane(lane)}
|
||||
aria-label={target ? `Play ${sel!.title} to ${lane.name}${onTopic ? `, on-topic +${topicBonus}` : ''}` : `${lane.name} Topic (${STAT_LABEL[lane.stat]}): you ${lane.myPower}, opponent ${lane.theirPower}. ${lane.modifier?.text ?? lane.portalNote ?? ''}`}>
|
||||
<span className="lane-score theirs" aria-hidden="true"><small>Opp</small>{lane.theirPower}</span>
|
||||
<span className="lane-score theirs" aria-hidden="true"><small>Opp</small>{lane.theirPower}{!!lane.scoringBonus?.[1] && <small className="lane-bonus">+{lane.scoringBonus[1]}</small>}</span>
|
||||
<span className="lane-name"><StatIcon stat={lane.stat} size={13} /><span>{lane.name}</span>{!lane.revealed && <small>?</small>}
|
||||
{lane.modifier && <small className="lane-rule">{lane.modifier.text}</small>}
|
||||
{lane.myPower === lane.theirPower && lane.leader && <small className="lane-tie">Tie: {lane.leader === 'you' ? 'you lead' : 'they lead'} on-topic</small>}</span>
|
||||
<span className="lane-score mine" aria-hidden="true"><small>You</small>{lane.myPower}</span>
|
||||
<span className="lane-score mine" aria-hidden="true"><small>You</small>{lane.myPower}{!!lane.scoringBonus?.[0] && <small className="lane-bonus">+{lane.scoringBonus[0]}</small>}</span>
|
||||
</button>
|
||||
<div className="lane-side mine" aria-label={`Your cards in ${lane.name}`}>
|
||||
{lane.mine.map(c => <GameCard key={c.id} card={c} size="board" fresh={fresh.has(c.id)} onClick={() => setSheet({ kind: 'card', card: c, side: 'mine' })} />)}
|
||||
@@ -84,7 +85,8 @@ export function MatchBoard({ title, opponent, view, legal, onAct, problem, error
|
||||
|
||||
<div className="play-dock match-dock">
|
||||
<p className="dock-note" role="status" aria-live="polite">
|
||||
{error ? <span className="dock-error">{error}</span>
|
||||
{view.over ? <>Final board. Topic totals include at-scoring Portals (+N).</>
|
||||
: error ? <span className="dock-error">{error}</span>
|
||||
: ending ? <><LoaderCircle className="spin" size={14} /> Opponent is choosing…</>
|
||||
: sel ? <><Zap size={12} /> <b>{sel.title}</b>{sel.keyword ? ` · ${sel.keyword.name}: ${sel.keyword.text}` : ''} Tap a lane.</>
|
||||
: lastEvent}
|
||||
@@ -100,9 +102,11 @@ export function MatchBoard({ title, opponent, view, legal, onAct, problem, error
|
||||
<b>{view.energy}</b>
|
||||
</span>
|
||||
<span className="deck-count"><Layers3 size={13} /> {view.deckCount}</span>
|
||||
<button className="button dark end-turn" disabled={ending || view.over} onClick={() => { setSelected(undefined); act({ type: 'endTurn' }); }}>
|
||||
{ending ? 'Waiting…' : view.turn === view.maxTurns ? 'End match' : 'End turn'}
|
||||
</button>
|
||||
{view.over ? <button className="button dark end-turn" onClick={onResults} disabled={!onResults}>See results</button>
|
||||
: <button className={`button ${queuedCount ? 'dark' : 'outline'} end-turn`} disabled={ending} onClick={() => { setSelected(undefined); act({ type: 'endTurn' }); }}
|
||||
aria-label={queuedCount ? undefined : 'Pass this turn without playing a card'}>
|
||||
{ending ? 'Waiting…' : !queuedCount ? 'Pass' : view.turn === view.maxTurns ? 'End match' : 'End turn'}
|
||||
</button>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -23,7 +23,6 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
|
||||
const view = useMemo(() => engine.view(state, 0), [state]);
|
||||
const legal = useMemo(() => engine.legal(state, 0), [state]);
|
||||
|
||||
useEffect(() => { if (engine.isOver(state)) { const t = setTimeout(() => onFinish(engine.result(state, 0)), 900); return () => clearTimeout(t); } }, [state, onFinish]);
|
||||
|
||||
// The bot moves once the player has committed (it never sees the player's queued plays).
|
||||
useEffect(() => {
|
||||
@@ -47,5 +46,5 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
|
||||
catch (e) { setError(e instanceof Error ? e.message : 'That move isn’t allowed.'); }
|
||||
};
|
||||
return <MatchBoard title={`${mode.name} match`} opponent={`${bot.name} bot`} view={view} legal={legal} onAct={act} error={error}
|
||||
problem={a => engine.problem(state, 0, a)} onTopicBonus={mode.ruleset.onTopicBonus} />;
|
||||
problem={a => engine.problem(state, 0, a)} onResults={engine.isOver(state) ? () => onFinish(engine.result(state, 0)) : undefined} onTopicBonus={mode.ruleset.onTopicBonus} />;
|
||||
}
|
||||
|
||||
+3
-13
@@ -23,7 +23,6 @@ export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const inFlight = useRef(false);
|
||||
const finished = useRef(false);
|
||||
const done = status?.phase === 'finished' || status?.phase === 'expired';
|
||||
|
||||
const refreshLobbies = useCallback(() => {
|
||||
@@ -50,17 +49,7 @@ export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
|
||||
return () => clearInterval(t);
|
||||
}, [seat, poll, done]);
|
||||
|
||||
// Once finished, stop polling and show results after a beat. The timer must survive later
|
||||
// re-renders, so it is only cleared on unmount.
|
||||
const finishTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||
useEffect(() => {
|
||||
const st = status?.state;
|
||||
if (finished.current || !status || !seat || status.phase !== 'finished' || !st?.result) return;
|
||||
finished.current = true;
|
||||
const names = st.lanes.map(l => l.topic.name);
|
||||
finishTimer.current = setTimeout(() => onFinish(resultView(st.result!, seat.seat, names, st.lanes.map(l => l.leader))), 900);
|
||||
}, [status, seat, onFinish]);
|
||||
useEffect(() => () => clearTimeout(finishTimer.current), []);
|
||||
// Once finished, stop polling; the final board stays up until the player opens the results.
|
||||
|
||||
const enter = async (fn: () => Promise<LobbySeat>) => {
|
||||
setBusy(true); setError('');
|
||||
@@ -106,7 +95,8 @@ export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
|
||||
return void send(() => online.act(seat, engineAction(a, seat.seat)));
|
||||
};
|
||||
return <MatchBoard title={`${mode.name} online match`} opponent={opp.slice(0, 24)} view={view} legal={legal} onAct={act}
|
||||
error={error} onTopicBonus={status.state.ruleset.onTopicBonus} />;
|
||||
error={error} onTopicBonus={status.state.ruleset.onTopicBonus}
|
||||
onResults={status.state.result ? () => onFinish(resultView(status.state!.result!, seat.seat, status.state!.lanes.map(l => l.topic.name), status.state!.lanes.map(l => l.leader))) : undefined} />;
|
||||
}
|
||||
|
||||
// ----- draft -----
|
||||
|
||||
+10
-3
@@ -88,6 +88,9 @@ function capacityFromView(v: PlayerView, i: number): number {
|
||||
export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capacity?: (lane: number) => number } = {}): MatchView {
|
||||
const rules = v.ruleset;
|
||||
const me = v.you;
|
||||
const opp = me === 0 ? 1 : 0;
|
||||
// After the last turn, show scoring power (incl. "at scoring" Portals) from the result, from my side.
|
||||
const final = v.result ? v.result.lanePower.map(p => [p[me], p[opp]] as [number, number]) : undefined;
|
||||
const onBoard = (c: CardInPlay, power: number, stat: string, allOnTopic: boolean) =>
|
||||
toUICard(c.card, rules, { id: `${c.owner}:${c.card.cardId}`, power, onTopic: allOnTopic || c.card.home === stat }); // both seats may share loaner cardIds
|
||||
const lanes: LaneView[] = v.lanes.map((lane, i) => {
|
||||
@@ -101,9 +104,13 @@ export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capaci
|
||||
theirs: lane.cards[1].map((c, k) => onBoard(c, lane.cardPower[1][k], lane.topic.stat, allOn)),
|
||||
staged: v.queue.filter(q => q.lane === i).flatMap(q => {
|
||||
const c = v.hand.find(h => h.cardId === q.cardId);
|
||||
return c ? [toUICard(c, rules)] : [];
|
||||
if (!c) return [];
|
||||
const onTopic = allOn || c.home === lane.topic.stat;
|
||||
const power = Math.max(0, c.power + c.trend + (onTopic ? rules.onTopicBonus[c.cost] ?? 0 : 0));
|
||||
return [toUICard(c, rules, { power, onTopic })];
|
||||
}),
|
||||
myPower: lane.power[0], theirPower: lane.power[1], leader: lane.leader,
|
||||
myPower: final ? final[i][0] : lane.power[0], theirPower: final ? final[i][1] : lane.power[1], leader: lane.leader,
|
||||
scoringBonus: final ? [final[i][0] - lane.power[0], final[i][1] - lane.power[1]] as [number, number] : undefined,
|
||||
capacity: opts.capacity ? opts.capacity(i) : capacityFromView(v, i),
|
||||
};
|
||||
});
|
||||
@@ -112,7 +119,7 @@ export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capaci
|
||||
me, turn: v.turn, maxTurns: rules.turns, energy: v.energyLeft, maxEnergy: v.energy,
|
||||
saved: Math.max(0, v.energy - (rules.energyByTurn[v.turn - 1] ?? 0) - rules.bonusEnergy),
|
||||
hand: v.hand.filter(c => !queued.has(c.cardId)).map(c => toUICard(c, rules)), deckCount: v.deckCount,
|
||||
oppHandCount: v.opponent.handCount, oppDeckCount: v.opponent.deckCount, oppQueued: v.opponent.queuedCount,
|
||||
oppHandCount: v.opponent.handCount, oppDeckCount: v.opponent.deckCount,
|
||||
lanes, log: opts.log ?? [], waitingForOpponent: v.committed && v.phase !== 'over', over: v.phase === 'over',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -205,3 +205,4 @@ html.wd-in-match .auth-wrap,body:has(.match) .auth-wrap{display:none}
|
||||
@media(max-width:480px){.hide-narrow{display:none}.play-actions{flex-wrap:nowrap}.play-actions .button{padding-inline:12px}}
|
||||
.show-narrow{display:none}
|
||||
@media(max-width:480px){.show-narrow{display:inline}.play-actions .button{min-width:0}}
|
||||
.lane-bonus{color:var(--ctp-yellow)!important;margin-left:2px}
|
||||
|
||||
+1
-1
@@ -39,6 +39,7 @@ export type LaneView = {
|
||||
theirPower: number;
|
||||
leader: 'you' | 'opponent' | null;
|
||||
capacity: number;
|
||||
scoringBonus?: [number, number]; // at-scoring Portal adjustments (mine, theirs), match over only
|
||||
};
|
||||
|
||||
export type MatchView = {
|
||||
@@ -52,7 +53,6 @@ export type MatchView = {
|
||||
deckCount: number;
|
||||
oppHandCount: number;
|
||||
oppDeckCount: number;
|
||||
oppQueued: number;
|
||||
lanes: LaneView[];
|
||||
log: string[]; // newest last, this seat's events only
|
||||
waitingForOpponent: boolean;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
.game-landing{margin:24px 0;padding:24px;border:1px solid var(--theme-border);border-radius:12px;background:var(--ctp-mantle)}
|
||||
.game-landing .section-eyebrow{display:flex;align-items:center;gap:6px;color:var(--theme-accent)}
|
||||
.game-landing h2{font-size:24px;line-height:1.25;letter-spacing:-.5px;margin:12px 0}
|
||||
.game-landing p{font-size:13px;line-height:1.75;color:var(--ctp-subtext0);margin:0 0 14px;max-width:720px}
|
||||
.game-landing-steps{list-style:none;padding:0;margin:18px 0;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}
|
||||
.game-landing-steps li{display:flex;gap:12px;align-items:flex-start;padding:14px;border-radius:10px;background:var(--ctp-base);border:1px solid var(--theme-border)}
|
||||
.game-landing-steps li>span{flex:none;display:grid;place-items:center;width:28px;height:28px;border-radius:50%;background:var(--theme-accent);color:var(--ctp-base);font-weight:700;font-size:13px}
|
||||
.game-landing-steps strong{display:block;font-size:14px;color:var(--ctp-text);margin-bottom:4px}
|
||||
.game-landing-steps p{font-size:12px;line-height:1.6;margin:0}
|
||||
.game-landing-steps svg{vertical-align:-2px}
|
||||
.game-landing-note{font-size:12px!important}
|
||||
.game-landing-actions{display:flex;align-items:center;gap:18px;flex-wrap:wrap}
|
||||
.game-landing .game-landing-play{min-height:44px;height:auto;padding:12px 22px;font-size:12px;gap:8px}
|
||||
@media(max-width:800px){.game-landing-steps{grid-template-columns:1fr}}
|
||||
@media(max-width:480px){.game-landing{padding:18px 16px}.game-landing h2{font-size:20px}.game-landing .game-landing-play{width:100%;justify-content:center}}
|
||||
@@ -2,6 +2,7 @@
|
||||
// On the web it does nothing: relative `/api/...` requests keep going to the serving origin.
|
||||
import { Capacitor } from '@capacitor/core';
|
||||
import { App } from '@capacitor/app';
|
||||
import { Browser } from '@capacitor/browser';
|
||||
import './native.css';
|
||||
|
||||
/** True inside the Android/iOS app shell. Use it to hide desktop-only features such as RandomX mining. */
|
||||
@@ -84,4 +85,13 @@ if (isNativeApp()) {
|
||||
if (parsed.protocol !== 'dev.eom.wikideck:') return;
|
||||
if (deepLinkHandlers.size) deepLinkHandlers.forEach(h => h(parsed)); else pendingDeepLink = parsed;
|
||||
});
|
||||
// eom.dev SSO (src/auth, sso team). Imported lazily so this module still runs before anything else.
|
||||
// Login opens Dex in the system browser (Custom Tab); the redirect comes back as a deep link.
|
||||
const auth = import('./auth/session.ts');
|
||||
void auth.then(({ setNativeBrowser }) => setNativeBrowser(Browser));
|
||||
onDeepLink(url => {
|
||||
void auth.then(({ isCallback, completeLogin }) => {
|
||||
if (isCallback(url.href)) return completeLogin(url.href);
|
||||
}).catch(error => console.warn('[native] SSO callback failed', error));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -31,3 +31,24 @@ test('account native: login opens the system browser with PKCE and the app redir
|
||||
assert.equal(auth.isCallback(`dev.eom.wikideck:/oauth/callback?code=c&state=${pending.state}`), true);
|
||||
} finally { Object.assign(g, saved); }
|
||||
});
|
||||
|
||||
test('account native: completeLogin failures are exposed to the UI via authError', async () => {
|
||||
const g = globalThis as Record<string, unknown>;
|
||||
const saved = { Capacitor: g.Capacitor, sessionStorage: g.sessionStorage };
|
||||
const store = new Map<string, string>();
|
||||
g.sessionStorage = { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); },
|
||||
removeItem: (k: string) => { store.delete(k); } };
|
||||
g.Capacitor = { isNativePlatform: () => true, Plugins: {} };
|
||||
try {
|
||||
const auth = await import('../src/auth/session.ts');
|
||||
let events = 0; const off = auth.subscribeAuth(() => { events++; });
|
||||
store.set('wikideck.auth.pending', JSON.stringify({ state: 'real-state', nonce: 'n', verifier: 'v', redirectUri: 'dev.eom.wikideck:/oauth/callback',
|
||||
returnTo: '/', createdAt: Date.now() }));
|
||||
await assert.rejects(auth.completeLogin('dev.eom.wikideck:/oauth/callback?code=c&state=forged'), /state mismatch/);
|
||||
assert.match(auth.authError(), /state mismatch/);
|
||||
assert.ok(events >= 1, 'subscribers are notified');
|
||||
auth.clearAuthError();
|
||||
assert.equal(auth.authError(), '');
|
||||
off();
|
||||
} finally { Object.assign(g, saved); }
|
||||
});
|
||||
|
||||
+24
-1
@@ -88,7 +88,6 @@ test('queued plays are hidden until reveal; undo refunds; committed seats get no
|
||||
assert.ok(play, 'turn 1 should have a 1-cost play');
|
||||
state = applyAction(state, play);
|
||||
assert.equal(viewFor(state, 0).energyLeft, 0);
|
||||
assert.equal(viewFor(state, 1).opponent.queuedCount, 1);
|
||||
assert.equal(JSON.stringify(viewFor(state, 1)).includes(`"${play.cardId}"`), false);
|
||||
assert.equal(viewFor(applyAction(state, { type: 'undo', player: 0, cardId: play.cardId }), 0).energyLeft, 1);
|
||||
state = commit(state, 0);
|
||||
@@ -111,6 +110,30 @@ test('viewFor never leaks the opponent hand, deck order, queue, seed or RNG stat
|
||||
assert.deepEqual(view.hand.map(c => c.cardId), state.players[0].hand.map(c => c.cardId));
|
||||
});
|
||||
|
||||
test('planning is hidden: the opponent view is identical before and after queuing, until commit', () => {
|
||||
for (let seed = 0; seed < 10; seed++) {
|
||||
let state = createMatch(DEFAULT_RULESET, decks(`plan-${seed}`), seed);
|
||||
for (let turn = 0; turn < 4 && !isOver(state); turn++) {
|
||||
const before = JSON.stringify(viewFor(state, 1));
|
||||
let queued = 0;
|
||||
for (;;) {
|
||||
const play = legalActions(state, 0).find(a => a.type === 'play');
|
||||
if (!play) break;
|
||||
state = applyAction(state, play);
|
||||
queued++;
|
||||
assert.equal(JSON.stringify(viewFor(state, 1)), before, `seed ${seed} turn ${state.turn}: view changed after ${queued} queued`);
|
||||
}
|
||||
if (queued) {
|
||||
const undo = legalActions(state, 0).find(a => a.type === 'undo')!;
|
||||
assert.equal(JSON.stringify(viewFor(applyAction(state, undo), 1)), before, 'undo must not show either');
|
||||
}
|
||||
state = commit(state, 0);
|
||||
assert.equal(viewFor(state, 1).opponent.committed, true);
|
||||
state = commit(state, 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('energy: energyByTurn + carry (max 1) of unspent energy', () => {
|
||||
let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 3);
|
||||
const first = state.players[0].hand[0].cardId;
|
||||
|
||||
+15
-15
@@ -1,7 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_DERIVATION, percentile, percentiles, fame, costFor, homeStat, trendFor, keywordFor, deriveCard, deriveDeck,
|
||||
RULESET_V1_0, percentile, percentiles, fame, costFor, homeStat, trendFor, keywordFor, deriveCard, deriveDeck,
|
||||
type CardInput, type PercentileTable, type DerivationRules, type Faction,
|
||||
} from '../shared/game/index.ts';
|
||||
import { forAll } from './game/property.ts';
|
||||
@@ -9,7 +9,7 @@ import { forAll } from './game/property.ts';
|
||||
/** Cut points 1..99: score s sits at percentile ~s, which makes examples readable. */
|
||||
const LINEAR = Array.from({ length: 99 }, (_, i) => i + 1);
|
||||
const TABLE: PercentileTable = { attention: LINEAR, depth: LINEAR, reach: LINEAR };
|
||||
const RULES = DEFAULT_DERIVATION;
|
||||
const RULES: DerivationRules = RULESET_V1_0; // pinned: these examples are v1.0 numbers
|
||||
const LIVE = { trendPercent: null, dailyAverage: null };
|
||||
|
||||
function input(stats: CardInput['snapshot']['stats'], overrides: Partial<CardInput> = {}): CardInput {
|
||||
@@ -76,10 +76,10 @@ test('keyword choice: cost 1 vanilla, faction keyword otherwise, disabled → pl
|
||||
|
||||
test('deriveCard: cost, power, vanillaBonus, home, trend and source', () => {
|
||||
// pct 80/70/60 → fame 70 → cost 4 → power 6, Science → encyclopedic
|
||||
const card = deriveCard(input({ attention: 81, depth: 71, reach: 61 }, { live: { trendPercent: 40, dailyAverage: 50 } }), TABLE);
|
||||
const card = deriveCard(input({ attention: 81, depth: 71, reach: 61 }, { live: { trendPercent: 40, dailyAverage: 50 } }), TABLE, RULES);
|
||||
assert.deepEqual(card, { cardId: 'c1', pageId: 1, title: 'T', faction: 'Science', rarity: 'Common',
|
||||
cost: 4, power: 6, home: 'attention', trend: 1, keyword: 'encyclopedic', source: 'owned', check: 'verified' });
|
||||
const cheap = deriveCard(input({ attention: 5, depth: 5, reach: 5 }, { check: 'loaner' }), TABLE);
|
||||
const cheap = deriveCard(input({ attention: 5, depth: 5, reach: 5 }, { check: 'loaner' }), TABLE, RULES);
|
||||
assert.deepEqual([cheap.cost, cheap.power, cheap.keyword, cheap.source], [1, 2, null, 'loaner']);
|
||||
const disabled = deriveCard(input({ attention: 81, depth: 71, reach: 61 }), TABLE, { ...RULES, keywordsEnabled: [] });
|
||||
assert.deepEqual([disabled.power, disabled.keyword], [6, null]);
|
||||
@@ -87,14 +87,14 @@ test('deriveCard: cost, power, vanillaBonus, home, trend and source', () => {
|
||||
|
||||
test('rarity is cosmetic: it never changes cost, power or keyword (§1.7)', () => {
|
||||
const stats = { attention: 40, depth: 60, reach: 20 };
|
||||
const cards = (['Common', 'Rare', 'Epic', 'Legendary'] as const).map(rarity => deriveCard(input(stats, { rarity }), TABLE));
|
||||
const cards = (['Common', 'Rare', 'Epic', 'Legendary'] as const).map(rarity => deriveCard(input(stats, { rarity }), TABLE, RULES));
|
||||
for (const card of cards) assert.deepEqual({ ...card, rarity: 'Common' }, { ...cards[0], rarity: 'Common' });
|
||||
});
|
||||
|
||||
test('unchecked cards are capped at uncheckedCostCap and keep their home stat (§1.10)', () => {
|
||||
const stats = { attention: 100, depth: 100, reach: 99 };
|
||||
const checked = deriveCard(input(stats), TABLE);
|
||||
const unchecked = deriveCard(input(stats, { check: 'unchecked' }), TABLE);
|
||||
const checked = deriveCard(input(stats), TABLE, RULES);
|
||||
const unchecked = deriveCard(input(stats, { check: 'unchecked' }), TABLE, RULES);
|
||||
assert.equal(checked.cost, 6);
|
||||
assert.equal(unchecked.cost, 4);
|
||||
assert.equal(unchecked.power, RULES.powerByCost[4]);
|
||||
@@ -114,18 +114,18 @@ test('deriveDeck marks copies for Edition when it is enabled', () => {
|
||||
const c = { ...a, cardId: 'c', pageId: 8 };
|
||||
const rules = { ...RULES, keywordsEnabled: [...RULES.keywordsEnabled, 'edition'] };
|
||||
assert.deepEqual(deriveDeck([a, b, c], TABLE, rules).map(card => card.keyword), ['edition', 'edition', 'viral']);
|
||||
assert.deepEqual(deriveDeck([a, b, c], TABLE).map(card => card.keyword), ['viral', 'viral', 'viral']);
|
||||
assert.deepEqual(deriveDeck([a, b, c], TABLE, RULES).map(card => card.keyword), ['viral', 'viral', 'viral']);
|
||||
});
|
||||
|
||||
test('power depends only on cost: forged stats only move a card up the curve (§1.3)', () => {
|
||||
forAll(300, g => {
|
||||
const stats = { attention: g.bool(0.1) ? null : g.int(0, 100), depth: g.int(0, 100), reach: g.int(0, 100) };
|
||||
const card = deriveCard(input(stats, { category: g.pick(['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const) }), TABLE);
|
||||
const card = deriveCard(input(stats, { category: g.pick(['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const) }), TABLE, RULES);
|
||||
assert.ok(card.cost >= 1 && card.cost <= 6);
|
||||
assert.equal(card.power, RULES.powerByCost[card.cost] + (card.cost === 1 ? RULES.vanillaBonus : 0));
|
||||
assert.ok(stats[card.home] !== null, 'home is never a null stat');
|
||||
const bumped = { ...stats, depth: Math.min(100, stats.depth + g.int(1, 30)) };
|
||||
assert.ok(deriveCard(input(bumped), TABLE).cost >= card.cost, 'raising a stat never lowers cost');
|
||||
assert.ok(deriveCard(input(bumped), TABLE, RULES).cost >= card.cost, 'raising a stat never lowers cost');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -136,19 +136,19 @@ test('deriveCard rejects a rules config with no power for the derived cost', ()
|
||||
test('pinned values replace §1.1–1.5 for loaners only (§2.1)', () => {
|
||||
const pinned = { cost: 5, home: 'reach' as const, faction: 'History' as const };
|
||||
const stats = { attention: 5, depth: 5, reach: 5 };
|
||||
const loaner = deriveCard(input(stats, { check: 'loaner', pinned, rarity: 'Epic', live: { trendPercent: 99, dailyAverage: 999 } }), TABLE);
|
||||
const loaner = deriveCard(input(stats, { check: 'loaner', pinned, rarity: 'Epic', live: { trendPercent: 99, dailyAverage: 999 } }), TABLE, RULES);
|
||||
assert.deepEqual([loaner.cost, loaner.power, loaner.home, loaner.faction, loaner.keyword, loaner.rarity, loaner.trend, loaner.source],
|
||||
[5, 8, 'reach', 'History', 'nostalgic', 'Common', 0, 'loaner']);
|
||||
const owned = deriveCard(input(stats, { pinned }), TABLE);
|
||||
const owned = deriveCard(input(stats, { pinned }), TABLE, RULES);
|
||||
assert.deepEqual([owned.cost, owned.faction], [1, 'Science'], 'pinned is ignored when check !== loaner');
|
||||
const cheap = deriveCard(input(stats, { check: 'loaner', pinned: { ...pinned, cost: 1 } }), TABLE);
|
||||
const cheap = deriveCard(input(stats, { check: 'loaner', pinned: { ...pinned, cost: 1 } }), TABLE, RULES);
|
||||
assert.deepEqual([cheap.power, cheap.keyword], [2, null], 'vanillaBonus still applies to pinned cost-1');
|
||||
});
|
||||
|
||||
test('cultureKeyword (v1.1 hook): home gives Culture cards {attention: viral, depth: encyclopedic, reach: translated}', () => {
|
||||
const home = { ...RULES, cultureKeyword: 'home' as const };
|
||||
const culture = (stats: CardInput['snapshot']['stats']) => input(stats, { category: 'Culture' });
|
||||
assert.equal(deriveCard(culture({ attention: 80, depth: 40, reach: 40 }), TABLE).keyword, 'viral', 'v1 default: faction');
|
||||
assert.equal(deriveCard(culture({ attention: 80, depth: 40, reach: 40 }), TABLE, RULES).keyword, 'viral', 'v1 default: faction');
|
||||
assert.equal(deriveCard(culture({ attention: 80, depth: 40, reach: 40 }), TABLE, home).keyword, 'viral');
|
||||
assert.equal(deriveCard(culture({ attention: 40, depth: 80, reach: 40 }), TABLE, home).keyword, 'encyclopedic');
|
||||
assert.equal(deriveCard(culture({ attention: 40, depth: 40, reach: 80 }), TABLE, home).keyword, 'translated');
|
||||
@@ -160,7 +160,7 @@ test('a full Ruleset works as DerivationRules (hosts can derive with the mode ru
|
||||
const { DEFAULT_RULESET } = await import('../shared/game/index.ts');
|
||||
const a = deriveCard(input({ attention: 81, depth: 71, reach: 61 }), TABLE, DEFAULT_RULESET);
|
||||
const b = deriveCard(input({ attention: 81, depth: 71, reach: 61 }), TABLE);
|
||||
assert.deepEqual(a, b);
|
||||
assert.deepEqual(a, b, 'default derivation rules are DEFAULT_RULESET');
|
||||
});
|
||||
|
||||
test('parseRuleset accepts a stored pre-v1.1 ruleset without cultureKeyword (defaults to faction)', async () => {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
RULESET_V1_0, applyAction, createMatch, isOver, lanePower, result, starterDeck, topicsLed,
|
||||
RULESET_V1_0, RULESET_V1_1, applyAction, createMatch, isOver, lanePower, result, starterDeck, topicsLed,
|
||||
type Action, type GameCard, type MatchState, type PlayerId, type Ruleset, type Stat, type Faction,
|
||||
} from '../shared/game/index.ts';
|
||||
|
||||
@@ -54,16 +54,19 @@ const PLAN: [PlayerId, string, number][][] = [
|
||||
[[1, 'Fern', T1], [0, 'Library of Alexandria', T1], [1, 'Mona Lisa', T2], [0, 'Periodic table', T2]],
|
||||
];
|
||||
|
||||
function setup(): MatchState {
|
||||
const rules: Ruleset = structuredClone(RULESET_V1_0); // §12 is pinned to the v1.0 ruleset
|
||||
function setup(base: Ruleset = RULESET_V1_0): MatchState {
|
||||
const rules: Ruleset = structuredClone(base); // §12 is pinned to the v1.0 ruleset; §12.1 passes v1.1
|
||||
const state = createMatch(rules, [starterDeck('golden-a'), starterDeck('golden-b')], 1);
|
||||
const pool = state.ruleset.topicPool;
|
||||
const find = (id: string) => pool.find(t => t.id === id) ?? assert.fail(`topic ${id} missing from the default pool`);
|
||||
const topics = [find('archive'), find('main-page'), find('translations')];
|
||||
state.lanes = topics.map(topic => ({ topic, portalRevealed: false, cards: [[], []] }));
|
||||
// Inject: every card the example plays starts in hand, nothing left to draw.
|
||||
state.players[0].hand = structuredClone(ANA);
|
||||
state.players[1].hand = structuredClone(BO);
|
||||
// The §12 table gives v1.0-derived cards; under another ruleset apply its keyword powerDelta (§10.1).
|
||||
const adjust = (cards: GameCard[]) => cards.map(c => ({ ...c,
|
||||
power: c.power + (c.keyword ? (rules.keywordParams[c.keyword]?.powerDelta ?? 0) : 0) }));
|
||||
state.players[0].hand = adjust(structuredClone(ANA));
|
||||
state.players[1].hand = adjust(structuredClone(BO));
|
||||
for (const p of state.players) p.deck = [];
|
||||
state.initiative = 0; // Ana has initiative on odd turns
|
||||
return state;
|
||||
@@ -122,3 +125,27 @@ test('§12 golden: per-turn Topic powers match the table', opts, () => {
|
||||
assert.deepEqual(state.lanes.map((_, lane) => lanePower(state, lane)), expected[turn], `after turn ${turn + 1}`);
|
||||
});
|
||||
});
|
||||
|
||||
test('§12.1 golden (v1.1 ruleset): 18–14, 15–21, 13–11; Ana wins 2–1; T1 8–8 consensus to Ana after turn 5', () => {
|
||||
let state = setup(RULESET_V1_1);
|
||||
const after: [number, number][][] = [];
|
||||
for (const plays of PLAN) {
|
||||
state = playTurn(state, plays);
|
||||
after.push(state.lanes.map((_, lane) => lanePower(state, lane)));
|
||||
}
|
||||
assert.deepEqual(after.slice(0, 5), [
|
||||
[[3, 0], [0, 3], [0, 0]],
|
||||
[[4, 0], [0, 3], [3, 0]],
|
||||
[[7, 0], [0, 9], [3, 3]],
|
||||
[[8, 0], [9, 9], [3, 10]],
|
||||
[[8, 8], [9, 10], [13, 11]],
|
||||
]);
|
||||
const r = result(state)!;
|
||||
assert.deepEqual(r.lanePower, [[18, 14], [15, 21], [13, 11]]);
|
||||
assert.equal(r.winner, 0);
|
||||
// Replay turns 1–5 to check the T1 consensus lead.
|
||||
let five = setup(RULESET_V1_1);
|
||||
for (const plays of PLAN.slice(0, 5)) five = playTurn(five, plays);
|
||||
assert.deepEqual(lanePower(five, T1), [8, 8]);
|
||||
assert.deepEqual(topicsLed(five), [2, 1]); // T1 by consensus + T3; Bo leads T2
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_DERIVATION, DEFAULT_RULESET, FACTION_KEYWORD, STARTER_DECKS, createMatch, starterDeckById, validateDeck,
|
||||
DEFAULT_DERIVATION, DEFAULT_RULESET, RULESET_V1_0, RULESET_V1_1, keywordFor, STARTER_DECKS, createMatch, starterDeckById, validateDeck,
|
||||
} from '../shared/game/index.ts';
|
||||
|
||||
const countBy = (keys: string[]) => keys.reduce<Record<string, number>>((m, k) => ({ ...m, [k]: (m[k] ?? 0) + 1 }), {});
|
||||
@@ -19,14 +19,17 @@ test('four starter decks, each with the frozen curve, 6+6 factions and 4 cards p
|
||||
}
|
||||
});
|
||||
|
||||
test('starter cards follow §10.1 and the power curve like owned cards', () => {
|
||||
for (const def of STARTER_DECKS) for (const card of starterDeckById(def.id)) {
|
||||
for (const [label, rules] of [['v1.0', RULESET_V1_0], ['v1.1', RULESET_V1_1]] as const)
|
||||
test(`starter cards follow §10.1 and the power curve like owned cards (${label})`, () => {
|
||||
for (const def of STARTER_DECKS) for (const card of starterDeckById(def.id, rules)) {
|
||||
assert.equal(card.source, 'loaner');
|
||||
assert.equal(card.rarity, 'Common');
|
||||
assert.equal(card.trend, 0);
|
||||
assert.match(card.cardId, /^loaner:[a-z0-9-]+$/);
|
||||
if (card.cost === 1) assert.deepEqual([card.keyword, card.power], [null, 2]);
|
||||
else assert.deepEqual([card.keyword, card.power], [FACTION_KEYWORD[card.faction], DEFAULT_DERIVATION.powerByCost[card.cost]]);
|
||||
if (card.cost === 1) { assert.deepEqual([card.keyword, card.power], [null, 2]); continue; }
|
||||
const { keyword } = keywordFor(card.faction, card.cost, false, rules, card.home);
|
||||
assert.equal(card.keyword, keyword);
|
||||
assert.equal(card.power, rules.powerByCost[card.cost] + (rules.keywordParams[keyword!]?.powerDelta ?? 0));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -67,7 +70,8 @@ test('previewPool derives the frozen starter-cards.json loaners through §1', as
|
||||
assert.equal(c.source, 'loaner');
|
||||
assert.match(c.cardId, /^loaner:\d+$/);
|
||||
assert.ok(c.cost >= 1 && c.cost <= 6);
|
||||
assert.equal(c.power, DEFAULT_DERIVATION.powerByCost[c.cost] + (c.keyword === null && c.cost === 1 ? DEFAULT_DERIVATION.vanillaBonus : 0));
|
||||
const delta = c.keyword ? (DEFAULT_DERIVATION.keywordParams[c.keyword]?.powerDelta ?? 0) : 0;
|
||||
assert.equal(c.power, DEFAULT_DERIVATION.powerByCost[c.cost] + (c.keyword === null && c.cost === 1 ? DEFAULT_DERIVATION.vanillaBonus : 0) + delta);
|
||||
}
|
||||
// 12 of them make a legal loaner deck.
|
||||
assert.deepEqual(validateDeck(DEFAULT_RULESET, pool.slice(0, 12)), []);
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
/** Hand-built boards for keyword and Portal unit tests (engine-b). */
|
||||
import {
|
||||
DEFAULT_RULESET, KEYWORDS, PORTALS, Rng, cardPower, createMatch, lanePower, starterDeck,
|
||||
RULESET_V1_0, KEYWORDS, PORTALS, Rng, cardPower, createMatch, lanePower, starterDeck,
|
||||
type CardInPlay, type EffectContext, type GameCard, type MatchState, type PlayerId, type Stat, type TopicDef,
|
||||
} from '../../shared/game/index.ts';
|
||||
|
||||
@@ -9,7 +9,7 @@ export const topic = (stat: Stat, portal: string | null = null, id = portal ?? `
|
||||
|
||||
/** Empty board, turn 1; lanes are depth / attention / reach plain Topics unless given. */
|
||||
export function board(topics: TopicDef[] = [topic('depth'), topic('attention'), topic('reach')], revealed = true): MatchState {
|
||||
const state = createMatch(DEFAULT_RULESET, [starterDeck('a'), starterDeck('b')], 'keyword-test');
|
||||
const state = createMatch(RULESET_V1_0, [starterDeck('a'), starterDeck('b')], 'keyword-test'); // unit tests use v1.0 numbers
|
||||
state.lanes = topics.map(t => ({ topic: t, portalRevealed: revealed, cards: [[], []] as [CardInPlay[], CardInPlay[]] }));
|
||||
return state;
|
||||
}
|
||||
|
||||
+61
-2
@@ -5,7 +5,7 @@ import express from 'express';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { gameRouter } from '../server/game/index.ts';
|
||||
import { previewPool } from '../server/game/engine-binding.ts';
|
||||
import { DEFAULT_RULESET, STARTER_POOL, replay, parseRuleset } from '../shared/game/index.ts';
|
||||
import { DEFAULT_RULESET, replay, parseRuleset, previewPool as engineLoaners } from '../shared/game/index.ts';
|
||||
import { parseMode, resolveRuleset, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts';
|
||||
import { ModeListSchema } from '../shared/game/modes.ts';
|
||||
|
||||
@@ -134,7 +134,8 @@ test('modes api: draft preview pool is deterministic and deck-legal', () => {
|
||||
assert.deepEqual(p1, p2);
|
||||
assert.equal(p1.length, 30);
|
||||
assert.equal(new Set(p1.map(c => c.cardId)).size, 30);
|
||||
assert.equal(previewPool(DEFAULT_RULESET, 'x', 100).length, STARTER_POOL.length * DEFAULT_RULESET.maxCopiesPerPage);
|
||||
assert.equal(previewPool(DEFAULT_RULESET, 'x', 100).length, engineLoaners(DEFAULT_RULESET).length * DEFAULT_RULESET.maxCopiesPerPage);
|
||||
assert.ok(p1.every(c => c.check === 'loaner' && c.source === 'loaner'), 'only engine loaner data');
|
||||
});
|
||||
|
||||
test('modes api: the rule examples in HOSTING.md are valid modes', () => {
|
||||
@@ -207,3 +208,61 @@ test('modes api: mode rules are checked beyond the engine schema and rejected, n
|
||||
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, { keywordsEnabled: ['viral', 'edition', 'wildcard'] }, parseModeRuleset));
|
||||
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, {}, parseModeRuleset));
|
||||
});
|
||||
|
||||
test('modes api: live matches survive a node restart (snapshot on shutdown, restore on start)', async () => {
|
||||
const { ModeHost } = await import('../server/game/host.ts');
|
||||
const { MatchStore } = await import('../server/game/store.ts');
|
||||
const { engineBinding } = await import('../server/game/engine-binding.ts');
|
||||
const { persistLive } = await import('../server/game/index.ts');
|
||||
const { mkdtempSync, rmSync, existsSync } = await import('node:fs');
|
||||
const { tmpdir } = await import('node:os');
|
||||
const { join } = await import('node:path');
|
||||
const dir = mkdtempSync(join(tmpdir(), 'modes-live-'));
|
||||
try {
|
||||
const modes = [parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } }),
|
||||
parseMode({ schema: MODE_SCHEMA_VERSION, id: 'draft', version: 1, name: 'D', description: 'x', decks: { kind: 'draft', poolSize: 30 }, rules: { deckSize: 10, openingHand: 4 } })];
|
||||
const make = () => new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes, engine: engineBinding, store: new MatchStore(dir) });
|
||||
const first = make();
|
||||
persistLive(first, dir, false);
|
||||
const a = first.createLobby('classic', alice);
|
||||
const b = await first.join(a.lobbyId, bob);
|
||||
// Random seed: the opening hand may have nothing playable on turn 1, so fall back to commit.
|
||||
const legal = (first.view(a.lobbyId, a.token) as any).legalActions;
|
||||
await first.act(a.lobbyId, a.token, legal.find((x: any) => x.type === 'play') ?? legal.find((x: any) => x.type === 'commit'));
|
||||
const d = first.createLobby('draft', alice);
|
||||
const e = await first.join(d.lobbyId, bob);
|
||||
const pick = (first.view(d.lobbyId, d.token) as any).draft;
|
||||
await first.pick(d.lobbyId, [d.token, e.token][pick.toPick]!, 0);
|
||||
const waiting = first.createLobby('classic', { name: 'Cy', secret: 'cy-secret-0123456789abcdefghij' });
|
||||
const before = first.view(a.lobbyId, b.token) as any;
|
||||
persistLive(first, dir, false).save();
|
||||
|
||||
// "Restart": a fresh host restores the snapshot. Same tokens keep working.
|
||||
const second = make();
|
||||
persistLive(second, dir, false);
|
||||
assert.ok(existsSync(join(dir, 'live.json.restored')));
|
||||
const after = second.view(a.lobbyId, b.token) as any;
|
||||
assert.equal(after.phase, 'playing');
|
||||
assert.deepEqual(after.state, before.state, 'match state restored exactly');
|
||||
assert.equal((second.view(d.lobbyId, d.token) as any).phase, 'drafting');
|
||||
assert.equal((second.view(waiting.lobbyId) as any).phase, 'waiting');
|
||||
// Finish the restored match: the record replays.
|
||||
for (let i = 0; i < 200; i++) {
|
||||
const v = second.view(a.lobbyId, a.token) as any;
|
||||
if (v.phase !== 'playing') break;
|
||||
for (const t of [a.token, b.token]) {
|
||||
const w = second.view(a.lobbyId, t) as any;
|
||||
const c = w.legalActions?.find((x: any) => x.type === 'commit');
|
||||
if (c) await second.act(a.lobbyId, t, c);
|
||||
}
|
||||
}
|
||||
const end = second.view(a.lobbyId, a.token) as any;
|
||||
assert.equal(end.phase, 'finished');
|
||||
const rec = second.matchRecord(end.matchId);
|
||||
assert.equal(replay(rec.rules as any, rec.decks as any, rec.seed, rec.actions.map(x => x.action) as any).result?.winner ?? null, rec.winner);
|
||||
// Rules changed under a mode → its lobbies are dropped, not run under different rules.
|
||||
const changed = new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, engine: engineBinding, store: new MatchStore(null),
|
||||
modes: [parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' }, rules: { turns: 5 } })] });
|
||||
assert.equal(changed.restore(second.snapshot()), 0);
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
test('landing explains Edit War and offers a thumb-sized Play button (upstream #3)', async () => {
|
||||
const read = (file: string) => readFile(new URL(`../${file}`, import.meta.url), 'utf8');
|
||||
const [landing, css, app] = await Promise.all([read('src/Landing.tsx'), read('src/landing.css'), read('src/App.tsx')]);
|
||||
assert.match(app, /<Landing onPlay=\{\(\) => setView\('Play'\)\} \/>/, 'App mounts the landing block and its button opens Play');
|
||||
assert.match(landing, /export function Landing\(\{ onPlay/);
|
||||
assert.match(landing, /onClick=\{onPlay\}/);
|
||||
assert.match(landing, /Play now/);
|
||||
for (const idea of ['Three Topics', 'Six turns', 'Win two Topics', 'starter deck', 'off-chain']) assert.ok(landing.includes(idea), idea);
|
||||
assert.doesNotMatch(css, /:hover/, 'no hover-only interactions');
|
||||
assert.match(css, /min-height:44px/, 'tap target is at least 44px');
|
||||
assert.doesNotMatch(css, /#[0-9a-f]{3,6}\b/i, 'colours come from the Catppuccin theme variables');
|
||||
});
|
||||
+16
-1
@@ -61,7 +61,6 @@ test('my view never shows the opponent’s queued cards', () => {
|
||||
s = engine.apply(s, 1, play!);
|
||||
const mine = engine.view(s, 0);
|
||||
assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
|
||||
assert.equal(mine.oppQueued, 1);
|
||||
const theirs = engine.view(s, 1);
|
||||
assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1);
|
||||
assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand');
|
||||
@@ -126,3 +125,19 @@ test('leaderboard parsers cap and sanitise host data', async () => {
|
||||
assert.deepEqual(parseLeaderboard({ entries: [{ name: '', wins: 2 }] }), [{ name: 'Anonymous', wins: 2, losses: 0, draws: 0, played: 0 }]);
|
||||
assert.deepEqual(parseLeaderboard(42), []);
|
||||
});
|
||||
|
||||
test('the final board shows scoring power, and queued cards preview their lane power', () => {
|
||||
const s = playOut('final-board');
|
||||
const v = engine.view(s, 0), r = engine.result(s, 0);
|
||||
assert.ok(v.over);
|
||||
v.lanes.forEach((l, i) => { assert.equal(l.myPower, r.lanes[i].myPower); assert.equal(l.theirPower, r.lanes[i].theirPower); });
|
||||
let m = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('q')], 'queued-power');
|
||||
const play = engine.legal(m, 0).find(a => a.type === 'play');
|
||||
if (play?.type === 'play') {
|
||||
m = engine.apply(m, 0, play);
|
||||
const lane = engine.view(m, 0).lanes[play.lane];
|
||||
const [q] = lane.staged;
|
||||
const bonus = q.home === lane.stat ? DEFAULT_RULESET.onTopicBonus[q.cost] : 0;
|
||||
assert.equal(q.power, q.basePower + q.trend + bonus);
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user