From 0ca22330b515bc79e9940de6d031e91d79edafc9 Mon Sep 17 00:00:00 2001 From: Eric Pheterson <151483+epheterson@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:49:17 -0800 Subject: [PATCH] Games: new solitaires and family card games, Courtier and the card table Co-Authored-By: Claude Fable 5.2 --- tests/fixtures/games_solitaire/freecell.json | 48 +- tests/fixtures/games_solitaire/golf.json | 40 +- tests/fixtures/games_solitaire/pyramid.json | 60 +- tests/fixtures/games_solitaire/solitaire.json | 76 +-- tests/fixtures/games_solitaire/spider.json | 46 +- tests/fixtures/games_solitaire/tripeaks.json | 68 +- tests/fixtures/games_tricks/belote.json | 4 +- tests/fixtures/games_tricks/euchre.json | 4 +- tests/fixtures/games_tricks/hearts.json | 36 +- .../fixtures/games_tricks/hearts_hotseat.json | 8 +- tests/fixtures/games_tricks/hearts_watch.json | 2 +- tests/fixtures/games_tricks/skat.json | 4 +- tests/fixtures/games_tricks/spades.json | 4 +- tests/test_bake_cards_gate.py | 104 +++ tests/test_games_canasta_browser.py | 4 +- tests/test_games_cards.cjs | 33 +- tests/test_games_cascade_fan_browser.py | 158 +++++ tests/test_games_climbing_status_browser.py | 140 ++++ tests/test_games_court_fill_browser.py | 161 +++++ tests/test_games_courtier.cjs | 228 +++++++ tests/test_games_courtier_browser.py | 186 ++++++ tests/test_games_family_cards.cjs | 344 ++++++++++ tests/test_games_family_cards_browser.py | 458 +++++++++++++ tests/test_games_fans_all_browser.py | 131 ++++ tests/test_games_freecell_hint_browser.py | 11 +- tests/test_games_ohhell_five_browser.py | 277 ++++++++ tests/test_games_shelf_table_names_browser.py | 15 + tests/test_games_solitaire_variants.cjs | 370 +++++++++++ .../test_games_solitaire_variants_browser.py | 182 +++++ tests/test_games_spider_open_browser.py | 16 +- tests/test_games_stuck_after_stock_browser.py | 107 +++ tests/test_games_stuck_sheets_browser.py | 145 ++++ tests/test_games_table_snap_browser.py | 133 ++++ tests/test_games_trick_fixtures.py | 12 +- zimi/builtin/games/accordion.html | 30 + zimi/builtin/games/accordion.js | 98 +++ zimi/builtin/games/acesup.html | 30 + zimi/builtin/games/acesup.js | 74 +++ zimi/builtin/games/beleaguered.html | 30 + zimi/builtin/games/beleaguered.js | 41 ++ zimi/builtin/games/calculation.html | 30 + zimi/builtin/games/calculation.js | 64 ++ zimi/builtin/games/canfield.html | 30 + zimi/builtin/games/canfield.js | 77 +++ zimi/builtin/games/cardbacks.js | 22 +- zimi/builtin/games/cards.css | 70 +- zimi/builtin/games/cards.js | 269 ++++++-- zimi/builtin/games/cards2.css | 12 + zimi/builtin/games/cardtable.css | 42 +- zimi/builtin/games/cardtable.js | 61 +- zimi/builtin/games/cheat.css | 3 + zimi/builtin/games/cheat.html | 32 + zimi/builtin/games/cheat.js | 275 ++++++++ zimi/builtin/games/courtier.css | 89 +++ zimi/builtin/games/courtier.html | 84 +++ zimi/builtin/games/courtier.js | 620 ++++++++++++++++++ zimi/builtin/games/courts.js | 23 +- zimi/builtin/games/eightoff.html | 30 + zimi/builtin/games/eightoff.js | 44 ++ zimi/builtin/games/fortythieves.html | 30 + zimi/builtin/games/fortythieves.js | 50 ++ zimi/builtin/games/gofish.css | 6 + zimi/builtin/games/gofish.html | 32 + zimi/builtin/games/gofish.js | 284 ++++++++ zimi/builtin/games/montecarlo.html | 30 + zimi/builtin/games/montecarlo.js | 95 +++ zimi/builtin/games/ohhell.html | 31 + zimi/builtin/games/ohhell.js | 265 ++++++++ zimi/builtin/games/oldmaid.html | 31 + zimi/builtin/games/oldmaid.js | 195 ++++++ zimi/builtin/games/scorpion.html | 30 + zimi/builtin/games/scorpion.js | 86 +++ zimi/builtin/games/snap.css | 13 + zimi/builtin/games/snap.html | 32 + zimi/builtin/games/snap.js | 217 ++++++ zimi/builtin/games/solitaire.js | 61 +- zimi/builtin/games/solkit.js | 275 ++++++++ zimi/builtin/games/tablesnap.js | 131 ++++ zimi/builtin/games/yukon.html | 30 + zimi/builtin/games/yukon.js | 45 ++ 80 files changed, 7389 insertions(+), 375 deletions(-) create mode 100644 tests/test_bake_cards_gate.py create mode 100644 tests/test_games_cascade_fan_browser.py create mode 100644 tests/test_games_climbing_status_browser.py create mode 100644 tests/test_games_court_fill_browser.py create mode 100644 tests/test_games_courtier.cjs create mode 100644 tests/test_games_courtier_browser.py create mode 100644 tests/test_games_family_cards.cjs create mode 100644 tests/test_games_family_cards_browser.py create mode 100644 tests/test_games_fans_all_browser.py create mode 100644 tests/test_games_ohhell_five_browser.py create mode 100644 tests/test_games_solitaire_variants.cjs create mode 100644 tests/test_games_solitaire_variants_browser.py create mode 100644 tests/test_games_stuck_after_stock_browser.py create mode 100644 tests/test_games_stuck_sheets_browser.py create mode 100644 tests/test_games_table_snap_browser.py create mode 100644 zimi/builtin/games/accordion.html create mode 100644 zimi/builtin/games/accordion.js create mode 100644 zimi/builtin/games/acesup.html create mode 100644 zimi/builtin/games/acesup.js create mode 100644 zimi/builtin/games/beleaguered.html create mode 100644 zimi/builtin/games/beleaguered.js create mode 100644 zimi/builtin/games/calculation.html create mode 100644 zimi/builtin/games/calculation.js create mode 100644 zimi/builtin/games/canfield.html create mode 100644 zimi/builtin/games/canfield.js create mode 100644 zimi/builtin/games/cheat.css create mode 100644 zimi/builtin/games/cheat.html create mode 100644 zimi/builtin/games/cheat.js create mode 100644 zimi/builtin/games/courtier.css create mode 100644 zimi/builtin/games/courtier.html create mode 100644 zimi/builtin/games/courtier.js create mode 100644 zimi/builtin/games/eightoff.html create mode 100644 zimi/builtin/games/eightoff.js create mode 100644 zimi/builtin/games/fortythieves.html create mode 100644 zimi/builtin/games/fortythieves.js create mode 100644 zimi/builtin/games/gofish.css create mode 100644 zimi/builtin/games/gofish.html create mode 100644 zimi/builtin/games/gofish.js create mode 100644 zimi/builtin/games/montecarlo.html create mode 100644 zimi/builtin/games/montecarlo.js create mode 100644 zimi/builtin/games/ohhell.html create mode 100644 zimi/builtin/games/ohhell.js create mode 100644 zimi/builtin/games/oldmaid.html create mode 100644 zimi/builtin/games/oldmaid.js create mode 100644 zimi/builtin/games/scorpion.html create mode 100644 zimi/builtin/games/scorpion.js create mode 100644 zimi/builtin/games/snap.css create mode 100644 zimi/builtin/games/snap.html create mode 100644 zimi/builtin/games/snap.js create mode 100644 zimi/builtin/games/solkit.js create mode 100644 zimi/builtin/games/tablesnap.js create mode 100644 zimi/builtin/games/yukon.html create mode 100644 zimi/builtin/games/yukon.js diff --git a/tests/fixtures/games_solitaire/freecell.json b/tests/fixtures/games_solitaire/freecell.json index 31c3de023..19ad40b5b 100644 --- a/tests/fixtures/games_solitaire/freecell.json +++ b/tests/fixtures/games_solitaire/freecell.json @@ -8,7 +8,7 @@ "stat": "0:00", "state": "fe64ce98", "sub": "", - "table": "d156fa9f", + "table": "b05d72a", "undoOff": true, "watch": "", "won": false @@ -16,12 +16,12 @@ { "fact": "", "label": "played", - "moves": 86, + "moves": 85, "sheet": "", "stat": "0:14", - "state": "e2d67442", + "state": "b3d10fed", "sub": "", - "table": "e6ce36df", + "table": "7e86f176", "undoOff": false, "watch": "", "won": false @@ -34,7 +34,7 @@ "stat": "0:19", "state": "723913f3", "sub": "", - "table": "d34ddf3", + "table": "6804e34c", "undoOff": false, "watch": "", "won": false @@ -47,7 +47,7 @@ "stat": "0:00", "state": "7e910749", "sub": "", - "table": "49b87b79", + "table": "260e53c4", "undoOff": true, "watch": "", "won": false @@ -55,12 +55,12 @@ { "fact": "", "label": "deal 617 played", - "moves": 141, + "moves": 138, "sheet": "", "stat": "0:15", - "state": "753a1ae9", + "state": "a25a4a57", "sub": "", - "table": "ed3a1856", + "table": "debb286c", "undoOff": false, "watch": "", "won": false @@ -68,12 +68,12 @@ { "fact": "", "label": "random deal", - "moves": 12, + "moves": 46, "sheet": "", - "stat": "0:05", - "state": "320f14cc", + "stat": "0:04", + "state": "ee1d976f", "sub": "", - "table": "62ffa4c9", + "table": "41158e55", "undoOff": false, "watch": "", "won": false @@ -86,7 +86,7 @@ "stat": "0:00", "state": "674f2478", "sub": "", - "table": "f60f57a5", + "table": "24aed740", "undoOff": true, "watch": "", "won": false @@ -99,7 +99,7 @@ "stat": "0:00", "state": "d14cc1eb", "sub": "", - "table": "c7151694", + "table": "f2f49817", "undoOff": true, "watch": "", "won": true @@ -112,7 +112,7 @@ "stat": "0:00", "state": "c245d45", "sub": "", - "table": "599abd6a", + "table": "25909e00", "undoOff": false, "watch": "", "won": false @@ -125,7 +125,7 @@ "stat": "0:00", "state": "d14cc1eb", "sub": "", - "table": "c7151694", + "table": "f2f49817", "undoOff": true, "watch": "", "won": true @@ -138,7 +138,7 @@ "stat": "0:00", "state": "d14cc1eb", "sub": "", - "table": "c7151694", + "table": "f2f49817", "undoOff": true, "watch": "", "won": true @@ -151,7 +151,7 @@ "stat": "0:00", "state": "d14cc1eb", "sub": "", - "table": "c7151694", + "table": "f2f49817", "undoOff": true, "watch": "", "won": true @@ -160,19 +160,19 @@ "fact": "", "label": "shell new game", "moves": 0, - "sheet": "FreeCellNew gameHintSettingsHow to playHistoryStatsAbout this game\u00a9 Zimi", + "sheet": "FreeCellNew gameHintSettingsHow to playHistoryStatsAbout this gameZimi \u00b7 Powered by Kiwix", "stat": "0:00", "state": "796b862f", "sub": "", - "table": "b13a250b", + "table": "ecba3332", "undoOff": true, "watch": "", "won": false } ], - "events": 325, + "events": 348, "hseed": 42, - "plays": "tap:31>fr0 tap:15>fr1 drag:5>fr2 drag:33>c1 tap:50>fr3 dead-end drag:9>fr3 tap:44>c7 dead-end drag:19>c6 tap:31>c7 stray:37 tap:44>c6 tap:18>fr0 drag:41>c4 drag:15>c0 tap:15>fr1 drag:15>c0 tap:45>c1 drag:50>fr1 stray:40 tap:1>c0 drag:0>fd0 drag:27>c4 tap:2>fd0 dead-end tap:27>c7 drag:27>c4 stray:32 tap:2>fd0 dead-end tap:27>c7 tap:27>c4 tap:27>c7 drag:27>c4 drag:27>c7 tap:27>c4 stray:0 tap:27>c7 tap:27>c4 tap:2>fd0 dead-end drag:2>fd0 dead-end tap:2>fd0 dead-end tap:2>fd0 dead-end drag:2>fd0 dead-end drag:2>fd0 dead-end drag:27>c7 tap:27>c4 tap:2>fd0 dead-end tap:2>fd0 dead-end drag:27>c7 tap:27>c4 tap:2>fd0 dead-end drag:27>c7 tap:27>c4 tap:27>c7 tap:27>c4 drag:27>c7 drag:27>c4 drag:27>c7 tap:27>c4 drag:2>fd0 dead-end drag:27>c7 tap:27>c4 stray:1 tap:2>fd0 dead-end tap:27>c7 tap:27>c4 drag:27>c7 tap:27>c4 drag:27>c7 drag:27>c4 drag:2>fd0 dead-end tap:2>fd0 dead-end drag:27>c7 tap:27>c4 drag:27>c7 tap:27>c4 drag:27>c7 tap:27>c4 tap:2>fd0 dead-end tap:2>fd0 dead-end drag:27>c7 drag:27>c4 tap:27>c7 drag:27>c4 drag:27>c7 drag:27>c4 tap:27>c7 tap:27>c4 tap:2>fd0 dead-end tap:27>c7 drag:27>c4 tap:2>fd0 dead-end tap:27>c7 drag:27>c4 tap:27>c7 drag:27>c4 tap:27>c7 tap:27>c4 tap:27>c7 stray:12 tap:27>c4 tap:2>fd0 dead-end tap:2>fd0 dead-end tap:2>fd0 dead-end tap:27>c7 tap:27>c4 tap:27>c7 tap:27>c4 drag:2>fd0 dead-end drag:27>c7 stray:41 tap:27>c4 tap:2>fd0 dead-end tap:2>fd0 dead-end drag:27>c7 drag:27>c4 drag:27>c7 tap:27>c4 tap:2>fd0 dead-end drag:2>fd0 dead-end tap:27>c7 tap:27>c4 tap:27>c4 drag:27>c7 tap:27>c4 tap:2>fd0 dead-end tap:27>c7 drag:27>c4 drag:2>fd0 dead-end stray:7 tap:2>fd0 dead-end drag:2>fd0 dead-end stray:20 drag:2>fd0 dead-end tap:27>c7 tap:27>c4 tap:2>fd0 dead-end tap:2>fd0 dead-end tap:27>c7 stray:41 stray:8 tap:27>c4 tap:2>fd0 dead-end stray:27 drag:27>c4 tap:2>fd0 dead-end drag:2>fd0 dead-end tap:27>c7 tap:27>c4 tap:2>fd0 dead-end tap:2>fd0 dead-end drag:29>fr0 tap:10>c7 tap:6>fr1 tap:10>fr2 tap:36>fr3 drag:37>c1 tap:10>c1 drag:1>fr2 drag:17>c5 tap:46>c3 tap:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 stray:12 drag:17>c4 drag:17>c5 tap:17>c4 drag:17>c5 drag:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 drag:17>c4 drag:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 drag:17>c5 stray:48 drag:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 drag:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 drag:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 stray:49 tap:17>c5 tap:17>c4 tap:17>c5 stray:39 stray:11 drag:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 stray:13 tap:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 stray:28 stray:50 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 stray:41 tap:17>c4 stray:31 stray:1 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 stray:33 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 drag:46>fr0 tap:27>fr1 tap:18>fr2 tap:36>fr3 drag:45>c6 tap:18>c6 tap:42>fr2 tap:16>c0 dead-end tap:4>c6 drag:16>c6 tap:14>c0 dead-end tap:41>c6 tap:27>c6 tap:25>fr1 dead-end tap:15>fr1 dead-end tap:25>fr1 dead-end tap:28>fr1 dead-end drag:25>fr1 dead-end tap:14>fr1 dead-end drag:19>fr1 drag:15>c4 dead-end drag:28>c4 dead-end tap:28>c4 dead-end tap:28>c4 dead-end tap:28>c4 dead-end tap:28>c4 dead-end tap:28>c4 dead-end tap:28>c4 dead-end tap:15>c4 dead-end stray:39 drag:15>c4 dead-end stray:44", + "plays": "tap:31>fr0 tap:15>fr1 drag:5>fr2 drag:33>c1 tap:50>fr3 dead-end drag:9>fr3 tap:44>c7 dead-end drag:19>c6 tap:31>c7 stray:37 tap:44>c6 tap:18>fr0 drag:41>c4 drag:15>c0 tap:15>fr1 drag:15>c0 tap:45>c1 drag:50>fr1 stray:40 tap:1>c0 drag:0>fd0 drag:27>c4 tap:2>fd0 dead-end tap:27>c7 drag:27>c4 stray:32 tap:2>fd0 dead-end tap:27>c7 tap:27>c4 tap:27>c7 drag:27>c4 drag:27>c7 tap:27>c4 stray:0 tap:27>c7 tap:27>c4 tap:2>fd0 dead-end drag:2>fd0 dead-end tap:2>fd0 dead-end tap:2>fd0 dead-end drag:2>fd0 dead-end drag:2>fd0 dead-end drag:27>c7 tap:27>c4 tap:2>fd0 dead-end tap:2>fd0 dead-end drag:27>c7 tap:27>c4 tap:2>fd0 dead-end drag:27>c7 tap:27>c4 tap:27>c7 tap:27>c4 drag:27>c7 drag:27>c4 drag:27>c7 tap:27>c4 drag:2>fd0 dead-end drag:27>c7 tap:27>c4 stray:1 tap:2>fd0 dead-end tap:27>c7 tap:27>c4 drag:27>c7 tap:27>c4 drag:27>c7 drag:27>c4 drag:2>fd0 dead-end tap:2>fd0 dead-end drag:27>c7 tap:27>c4 drag:27>c7 tap:27>c4 drag:27>c7 tap:27>c4 tap:2>fd0 dead-end tap:2>fd0 dead-end drag:27>c7 drag:27>c4 tap:27>c7 drag:27>c4 drag:27>c7 drag:27>c4 tap:27>c7 tap:27>c4 tap:2>fd0 dead-end tap:27>c7 drag:27>c4 tap:2>fd0 dead-end tap:27>c7 drag:27>c4 tap:27>c7 drag:27>c4 tap:27>c7 tap:27>c4 tap:27>c7 stray:12 tap:27>c4 tap:2>fd0 dead-end tap:2>fd0 dead-end tap:2>fd0 dead-end tap:27>c7 tap:27>c4 tap:27>c7 tap:27>c4 drag:2>fd0 dead-end drag:27>c7 stray:41 tap:27>c4 tap:2>fd0 dead-end tap:2>fd0 dead-end drag:27>c7 drag:27>c4 drag:27>c7 tap:27>c4 tap:2>fd0 dead-end drag:2>fd0 dead-end tap:27>c7 tap:27>c7 tap:27>c4 drag:27>c7 tap:27>c4 tap:2>fd0 dead-end tap:27>c7 drag:27>c4 drag:2>fd0 dead-end stray:7 tap:2>fd0 dead-end drag:2>fd0 dead-end stray:20 drag:2>fd0 dead-end tap:27>c7 tap:27>c4 tap:2>fd0 dead-end tap:2>fd0 dead-end tap:27>c7 stray:41 stray:8 tap:27>c4 tap:2>fd0 dead-end stray:27 drag:27>c4 tap:2>fd0 dead-end drag:2>fd0 dead-end tap:27>c7 tap:27>c4 tap:2>fd0 dead-end tap:36>fr0 drag:29>fr1 tap:10>c7 tap:6>fr2 tap:10>fr3 tap:10>c7 drag:5>fr3 dead-end tap:37>c1 drag:1>fr3 drag:17>c5 tap:46>c3 tap:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 stray:12 drag:17>c4 drag:17>c5 tap:17>c4 drag:17>c5 drag:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 drag:17>c4 drag:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 drag:17>c5 stray:48 drag:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 drag:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 drag:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 stray:49 tap:17>c5 tap:17>c4 tap:17>c5 stray:39 stray:11 drag:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 stray:13 tap:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 stray:28 stray:50 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 drag:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 tap:17>c4 tap:17>c5 stray:41 tap:17>c4 stray:31 stray:1 tap:17>c5 tap:17>c4 drag:17>c5 tap:17>c4 stray:33 tap:17>c5 tap:16>c0 tap:27>fr0 tap:16>fr1 drag:20>fr2 tap:42>fr3 tap:16>c0 tap:36>fr1 drag:43>c7 tap:46>c6 tap:16>c7 tap:16>c0 tap:16>c7 drag:16>c0 tap:16>c7 tap:16>c0 tap:16>c7 tap:16>c0 tap:16>c7 tap:16>c0 tap:16>c7 drag:16>c0 tap:16>c7 drag:16>c0 drag:16>c7 drag:16>c0 tap:16>c7 tap:16>c0 tap:16>c7 tap:16>c0 tap:16>c7 tap:16>c0 tap:16>c7 stray:39 drag:16>c0 stray:44 tap:16>c7 stray:24 tap:16>c0 tap:16>c7 drag:16>c0 drag:16>c7 tap:16>c0 tap:16>c7 drag:16>c0 tap:16>c7 tap:16>c0 drag:16>c7 tap:16>c0 tap:16>c7", "seed": 32, - "trace": "9568b3982e3c1fdd8ef381adfb95f315b13b797fa6732a1363d21266d4f087ff3861099cb35918fbcc1515f77c15fe22d42af37127a415f0b5127543d2c5c70fc6e45ffe963c99777ce101afc74690227a773005f881b7979d8ea10aaa53a6c9c2088578e0b4763c02f1086dc004e1b627cdd40cce63e50612622fd0ac2ee6bfd91a5cc34d2df00637886f33748a6bf5ec3148f1a0b6a293482e9c5260ea290f71da2d25a0064e6981f88f68142b63c5181ac9b3ed4305fa897c90fea67d2c4c04aca2489cfbd41cefb8b0893df5faed90102d4d10ab4f20168e59f4411979dbae53794128c3328c44565c9c322e476801caf299180816c05cd030b5d83f32cc4ea903c3297d1bee7174f6bc4608a0ea0400fd31f28361cc3b617936e31573f69b2887b9f3b1a3ca1c68ca9a100bfe25429866d69033b5f613e8aca6ec02559e54f2114c9d32687e44c45f48656adecc323e1915b5da151d4ebb4779768654827ca33101fba3ea9afed07ffff02b5c4963e0e12b0121ea0213563baf19b085b6001d3d1d70af6972cf07d136e1c3758257cc50a930d9083af2beefac18f33eb7d1272043cd86c46eda841da9005276854cc4e604018f0b240bf8ff3b88782387fb1733ec3e428fd38f3f4340d8b079f916881bab811155c551a8f6f1d98274ff0f49f8d209103ee000784138a83e01d7609c49d94ec66afd75788849a16f7f12e3436c122373e948b7f7ce59cad0817bc213b61dd9b3f77f3523804c74ee01f7a52343d5406007064faec50f306e73a096ac626986513f13b6d1897b0780c7b5167584a18f6fe330a7bcdd75fdeb06c4d0d5ca9cd37da4597813d8d41b164961309e21530ae03c907bbffe8ca58a2b55a0aab91f46b2e24c326c77b77fa4201eacd3d0a930a854ed4bfb4fb67b1e251edd18cf7bd987f4b920a5f5680cf249eb45e7b59616a09ca91137bfeee5b61d00318268047bb0b652b78e0c8886d5ef9a9522dd2f7f2c424f376b3aede47168c90c26aa8a3334b9760883d380639045daae125e974404c5cfb048b624180338bb62d244b25c76c8837fe82b8859ea71a34c6fba87272be475c54d98eea3f6ec6d03ca6a0c818acde609cd3449fa1e00be125a05db983f78c519f9da49c17b38aa9f47f38d41e19d5461ea97d168d874b2cbc0b5ebcee563d25199719f1486d9aa5b0230454eca2685f9c81d0975ba494929304b5c47e282062072b4d3190f37cf2787187d102d0914ae2144094187dbdc095f82e09975ad1cb676fe4a5ce01b51c7d194542d9ce440ca54369ca716991677ad60874ba00e6d7b440b0f00ffa75c4e0b8e3e810aaacedadd4f6914db23e68b22a74b986b9d1dd8da822cd404262c1fe55d90134133cfd0fab3ba61554874e48a16248b23b10d3abd68b5c6ee8fc319ddb8f6f4602d9dd5d15411c9082313c0d5f4c4eabe036117e20a8dfe67eaf1b3b8a241b58dab6d233d28cbfc4db77d7a0f00bb4eb645deecba18e9d083ad99172ee91608a83294cbf364f909061efec201ed1ef813e69afca6a204807557d67d6c457d41bdd77cdce22e597f9a9f059cfc9acb1c7b46bdad85ce4b71213d1ae8b47a8fd2c1d28cc673d5819e189880ac28161b8fb668c746c3485c3d606e32e6e5250dbe806cf67f151f8a71d58ad3d447644bb0112dab700d781c2b12ba2e74129ba74999a698a59303b99a12d85aec0649485df10c090cc0818e7e500217cd687cd9f2da6f24aee59643c74a74209d1dd89e64be70b088a7c70ea4dec1bb53e241048fd854df02ddcf935dffbdf2dfeb21bba7359f3569401f30ad82d4de8a755d3d" + "trace": "917e7be1f9c6b3955127f51ddf2de6ffa4967cfde820839d7c246cffbf328840dedec4d47f99d99b852e1885db6f90dcc5b65ef3564927876a73a3e7df5a486da2d938f721087374db0999fadfce57ddc367db2818b8c60d2b8fd13ea5e5fa41b4c28e74107052e823bf3e11a10ad5a1bc36f825393546ef2bbc238b6ea57f48a90819622f215a77645ae408ae6d20aac9d273d24b3bae1cd841d16d919b735c5a0e3f42ed7286ae15d80e7b7c673d8eb6dd2a2448be6c9dd32b103596fb8c070f7169738c60fddfdfa109925f122fde78b06ad6794cb77f4b4d802743b4fe5cbdc1492a5d0dc35f4fdf8b433815eefb99fd2198ed3b8129323cbd966d93bde724e6a8266e661c575907f2e3b83c384588314320f8d818659ad239f794647e6ba94632206cbf5f7bd7fdb5f3488526a05682a26b999d5837fec529d3d213e96bda3e50211d2c81afa1bde5276384721f7e57e238b14cc768878431101429614d821a9abe68556d5fb6ee12b633fed94ad5bb35bf8ff2a13e3c67a581233fc0b0e3ed7d05e31c272a53cfe384d1b7f3479b809fcee4aecb891a02926928df33e2b12748708966c72dc0220a5257485ca36e669bfd0501a59c07bd8cbb883d9302551bda5c6fc6662bc2c1cdbd300eec212b288ac7b5b2b46a2cd6fea7154da8321dd08c8edc1aad4d73f630ed6e03b6b6ee91454ddc8935c2a2b5eec1bd4925348cf024c6b3372f885d59a813da8535d2337779d647d3df99d6f0f2576b776963297e950e0233e6ed00892b02ed4790104814c67b4e7ebc92ae468b3cc220573ff2336314c2fde7ec1c154f1925c25daed0638c912b369e276590cc99efde00671a7e3b167efab547043a2a3cbb5e941ed4fa0eb3d029cb4cbbe96e3f63ca76997b74465f0c22d0b2edfdceb6cd12e228961c152efac41620d40f544cdfb2262484911f8768bd673ec8c3c768d66ce00304d162badad95240000832deedfe660c548096a9572eadb8bbc3fd41194f466e3b281c9a03614d34f1b34a19be20d4e10800c99fc86ae3e7cec927a46e0259ba4c77e1f9537752e4f5bf58b73770c0eed34794103a11306c6f922306fa14a7f2dee948cb42f959741ee146f089ceb4ff1c281da5ed60f1028228235de0e3af0b9bcaca2a0138ec83c0ebfbe1584461eaf9b67a749e09d7a7693533bab437b191a37c8fc374468b7f0fb03beec44203c921d6a6f987fec6fc1f73a0ab5295671e4d5b83fb6b0a524f78f3a8b95f006c24bc9fca13a9a4d5bc57a067caf9f89d0884117014d255de8a72d2c777cd81a0e53ca7b1135df813fe18082e4a39c9bf2709480095324bcbe24bc9d4746a866a7e102d92bca8ed52db05a8b602f84a60edebd536bd6735bb511b987a79e81d313fa6dd7b6a72faf0b5a35667dcc998015f50105b8478b1a9d4801002cc2616ced336e72d3eadb6b7143285169e7a7227d426bf248172e6d1d4730c843406d093c158c11f4c9507d03f855ce988807f94959eb09edb389308a2b753193b20c6c104ae66034bcbd6ef475ab11ab873b9fd9bb38099a837ff7ed90fa4a8771edd90f8d604c8a2c92157865ca1b6724fb81472b19b707a9f4b7cba3af583d4eba87e86591b340b050b3eec8c4bbbf12f811948dd27b72f1373fe1caea6e935d5d2ab9a640d6c8d1ef830000a57ca9009e7b604b4c4bbc1b0e9e14082f5b2aa56cafb2976f4f5572d3a8ae391cc21c20943a0cbdff9203f8a4093ffc6fef5c44a193e0b20d2415ded1b7fb9b1f2727affc24645e74500bbe36a2c37ab133333bab67bea6fdcf5b8f0ea18b216cff2ec18d05fe1d937549865363d7dc9dc6fd28f69c39f86c14fc79b921f1e2ab304521c0dc1a9be94d225b895324b5b7508c32001a88fcfcfc6c55f6866b09587b106ec4dab93a5678acf6ec1fc20abd2293c7b29c55008614517c1d3cfbbe5218f4669f02bb5" } diff --git a/tests/fixtures/games_solitaire/golf.json b/tests/fixtures/games_solitaire/golf.json index e5afc117c..0a205ee5f 100644 --- a/tests/fixtures/games_solitaire/golf.json +++ b/tests/fixtures/games_solitaire/golf.json @@ -8,7 +8,7 @@ "stat": "0:00", "state": "97d810e3", "sub": "", - "table": "718ca56b", + "table": "443fd209", "undoOff": true, "watch": "", "won": false @@ -21,7 +21,7 @@ "stat": "0:00", "state": "97d810e3", "sub": "", - "table": "16fde224", + "table": "8bd4bc61", "undoOff": true, "watch": "", "won": false @@ -29,12 +29,12 @@ { "fact": "", "label": "menu", - "moves": 6, + "moves": 5, "sheet": "GolfPlay a column\u2019s bottom card onto the waste when it is one rank higher or lower. No wrap from king to ace. The score is the cards left: fewer is better.LookCard backs\u2026Played 1 \u00b7 Won 0New gameClose", "stat": "0:00", - "state": "9ea19665", + "state": "62227a7e", "sub": "", - "table": "a376c702", + "table": "635b7a7b", "undoOff": false, "watch": "", "won": false @@ -47,7 +47,7 @@ "stat": "0:04", "state": "25a27180", "sub": "", - "table": "a0c8fa6a", + "table": "83529f1b", "undoOff": false, "watch": "", "won": false @@ -60,7 +60,7 @@ "stat": "0:04", "state": "5137d1a9", "sub": "", - "table": "75d7d02a", + "table": "95e646dd", "undoOff": false, "watch": "", "won": false @@ -73,7 +73,7 @@ "stat": "0:04", "state": "25a27180", "sub": "", - "table": "efa919e0", + "table": "4888c656", "undoOff": false, "watch": "", "won": false @@ -81,12 +81,12 @@ { "fact": "", "label": "next game", - "moves": 10, + "moves": 9, "sheet": "", - "stat": "0:01", - "state": "bda0616e", + "stat": "0:00", + "state": "6d93092e", "sub": "", - "table": "acf17f92", + "table": "b93c91ca", "undoOff": false, "watch": "", "won": false @@ -99,7 +99,7 @@ "stat": "0:00", "state": "f36a0a1c", "sub": "", - "table": "5d5bb69", + "table": "cf0cea41", "undoOff": true, "watch": "", "won": false @@ -112,7 +112,7 @@ "stat": "0:00", "state": "504c0263", "sub": "", - "table": "b2201d57", + "table": "3a5adab0", "undoOff": true, "watch": "", "won": true @@ -125,7 +125,7 @@ "stat": "0:00", "state": "504c0263", "sub": "", - "table": "b2201d57", + "table": "3a5adab0", "undoOff": true, "watch": "", "won": true @@ -134,19 +134,19 @@ "fact": "", "label": "shell new game", "moves": 0, - "sheet": "GolfNew gameSettingsHow to playHistoryStatsAbout this game\u00a9 Zimi", + "sheet": "GolfNew gameSettingsHow to playHistoryStatsAbout this gameZimi \u00b7 Powered by Kiwix", "stat": "0:00", "state": "6b2cb8e5", "sub": "", - "table": "2231d1a7", + "table": "963f4341", "undoOff": true, "watch": "", "won": false } ], - "events": 68, + "events": 66, "hseed": 45, - "plays": "stray:7 stock stock stock tap:44>waste tap:32>waste tap:7>waste tap:34>waste stock stock stock tap:29>waste drag:41>waste stock stock tap:10>waste drag:50>waste tap:38>waste stock stock stock stock drag:22>waste stray:30 stock tap:39>waste tap:40>waste drag:15>waste tap:16>waste stock stray:42 drag:20>waste stray:5 tap:47>waste tap:46>waste stock tap:48>waste stock drag:28>waste tap:3>waste drag:3>waste tap:47>waste stock tap:8>waste stock stock stock stock tap:6>waste stock tap:36>waste tap:19>waste", + "plays": "stray:7 stock stock stock tap:44>waste tap:32>waste tap:7>waste tap:34>waste stock stock stock tap:29>waste drag:41>waste stock stock tap:10>waste drag:50>waste tap:38>waste stock stock stock stock drag:22>waste stray:30 stock tap:39>waste tap:40>waste drag:15>waste tap:16>waste stock stray:42 drag:20>waste stray:5 tap:47>waste tap:46>waste stock tap:48>waste stock drag:28>waste tap:3>waste drag:3>waste tap:47>waste stock tap:8>waste stock stock stock stock tap:6>waste stock tap:19>waste", "seed": 35, - "trace": "ff1346e04e53ea3e4e60bbb1dc0cb86f20b795763778332cf857274983a3432c081dc85267e853a1430906fa617e301fad66aa23794f2782002fe09760210a0d8bd02e66a496cbe122cc39e91450e7f27ec32c3131ccf6fae8c572593831b3f44c6bbac4de87f6523f8a4a7241ebaa54977a410746153f1283ef3d8e31411b417965cc371b01f6dd24f78446fe350199937bbcdd1a00b0f7ba07b0c3876321a5963ad10f4bbe9384371f7107f2665517aa5b33ce63ffcf488e7de81f34f1dec042d89ea0c00f9780713e827de3d9f5b081e10f4103f4a8c4cbf746da70e595977f2fea89fb2f72d29a5c4030448540d9c224d2cf36c3c62e78ab38fbcd6ec56f34fb96565fbfd19185517a709061113b" + "trace": "3a1ab57ce3c67c2cc53f099de48524cd0c2fcbc7e2bb12420b482c2cda4b7ce9cd20f782718ff82e1220653b1dc5a815e3b2396c0e4cecb766a38b363b26c5b2b8e996350ef91165f4c31a86f444c28031bbe44b6bb6f8522c1a9f15e98b7fa482eb86b2c0540b164a233aff3d6493d2f5aeece74bea3a076cab2880985f4812b45afbf09072a6ff90e1ef211e5c932629927b1ac9510f8425105f677bc2e6031093e6aa1a8de2d33727f841a0e7dd13ec7527a97e119d4b5371d5f279f22092b0708ca6214d254414fecbda59a73c8bed974dd0f16dfe60f7b08bb5064e970adb36dabcdf36f0d4fd812124371768a8864e3e2a8ee795e1488a762189e0ec3f09bea679a73729e4" } diff --git a/tests/fixtures/games_solitaire/pyramid.json b/tests/fixtures/games_solitaire/pyramid.json index 1df1542dc..b8e8cbb4b 100644 --- a/tests/fixtures/games_solitaire/pyramid.json +++ b/tests/fixtures/games_solitaire/pyramid.json @@ -8,7 +8,7 @@ "stat": "0:00", "state": "964eb25d", "sub": "", - "table": "902c18ba", + "table": "60b81517", "undoOff": true, "watch": "", "won": false @@ -16,12 +16,12 @@ { "fact": "2 redeals", "label": "played", - "moves": 21, + "moves": 20, "sheet": "", "stat": "0:02", - "state": "f0a9d7c1", + "state": "8bc98754", "sub": "", - "table": "aef4b78e", + "table": "789d8e2b", "undoOff": false, "watch": "", "won": false @@ -29,12 +29,12 @@ { "fact": "2 redeals", "label": "menu", - "moves": 28, + "moves": 27, "sheet": "PyramidTake two free cards that add up to 13, or a free king alone. Ace is 1, jack 11, queen 12. Tap one card, then its partner. Cards you can take are bright; covered ones are dim.LookCard backs\u2026Played 1 \u00b7 Won 0New gameClose", - "stat": "0:04", - "state": "2016e2eb", + "stat": "0:03", + "state": "6ad743b6", "sub": "", - "table": "5eb8f4fd", + "table": "f4de536f", "undoOff": false, "watch": "", "won": false @@ -47,7 +47,7 @@ "stat": "0:10", "state": "c9ca7181", "sub": "", - "table": "4982ff6d", + "table": "ccdc1702", "undoOff": false, "watch": "", "won": false @@ -60,7 +60,7 @@ "stat": "0:10", "state": "ffdd293a", "sub": "", - "table": "4a145162", + "table": "23438777", "undoOff": false, "watch": "", "won": false @@ -73,7 +73,7 @@ "stat": "0:11", "state": "c9ca7181", "sub": "", - "table": "89237a6e", + "table": "a928f705", "undoOff": false, "watch": "", "won": false @@ -86,7 +86,7 @@ "stat": "0:01", "state": "e1c45a81", "sub": "", - "table": "1ec66942", + "table": "d3979a4f", "undoOff": false, "watch": "", "won": false @@ -99,33 +99,33 @@ "stat": "0:00", "state": "570e9d", "sub": "", - "table": "4477592a", + "table": "7416686b", "undoOff": true, "watch": "", "won": false }, { - "fact": "0 redeals", + "fact": "2 redeals", "label": "won", - "moves": 6, - "sheet": "You won!Score 65 (clear bonus 50)Time0:01Won1 of 3CloseNew game", - "stat": "0:01", - "state": "c0276c90", + "moves": 2, + "sheet": "You won!Score 115 (clear bonus 100)Time0:00Won1 of 3CloseNew game", + "stat": "0:00", + "state": "66eb2fb0", "sub": "", - "table": "4f267ee3", + "table": "93ce3138", "undoOff": true, "watch": "", "won": true }, { - "fact": "0 redeals", + "fact": "2 redeals", "label": "shell menu", - "moves": 6, - "sheet": "You won!Score 65 (clear bonus 50)Time0:01Won1 of 3CloseNew game", - "stat": "0:01", - "state": "c0276c90", + "moves": 2, + "sheet": "You won!Score 115 (clear bonus 100)Time0:00Won1 of 3CloseNew game", + "stat": "0:00", + "state": "66eb2fb0", "sub": "", - "table": "4f267ee3", + "table": "93ce3138", "undoOff": true, "watch": "", "won": true @@ -134,19 +134,19 @@ "fact": "2 redeals", "label": "shell new game", "moves": 0, - "sheet": "PyramidNew gameSettingsHow to playHistoryStatsAbout this game\u00a9 Zimi", + "sheet": "PyramidNew gameSettingsHow to playHistoryStatsAbout this gameZimi \u00b7 Powered by Kiwix", "stat": "0:00", "state": "45879585", "sub": "", - "table": "1a9a8a4e", + "table": "4aca1185", "undoOff": true, "watch": "", "won": false } ], - "events": 161, + "events": 145, "hseed": 44, - "plays": "pair:p6_1>p6_3 stock pair:p6_1>p6_3 pair:p6_1>p6_3 pair:p6_1>p6_3 pair:p6_1>p6_3 pair:p6_2>p6_5 pair:p6_2>p6_5 pair:p6_4>waste pair:p6_4>waste pair:p5_4>out stock stock stock stock stock stock stock stock stock pair:p6_6>waste pair:p6_6>waste stock stock pair:waste>out stray:23 stock stock stock stock stock stock pair:p5_5>waste pair:p5_5>waste stock pair:p5_1>waste stray:8 stock stock stock pair:p6_0>waste stray:1 pair:p6_0>waste stock pair:p5_1>waste pair:p5_1>waste stock stock stock stock stock stock stock stock stock stock stray:45 stock stock pair:p5_0>waste pair:p5_0>waste pair:p4_0>p5_3 stock pair:p4_0>p5_3 pair:p4_0>p5_3 pair:p4_0>p5_3 pair:p4_0>p5_3 pair:p4_3>out stock stock stock pair:p5_2>waste stock stock stock stock stock stock stock stock stock stock stock stock stock stock pair:p4_4>waste pair:p4_4>waste stock stock stock stock pair:p5_2>waste pair:p5_2>waste pair:p3_3>p4_2 pair:p3_3>p4_2 pair:p3_2>waste stray:16 pair:p3_2>waste stock stock stock pair:p2_2>waste pair:p2_2>waste stock stock pair:p6_1>p6_6 stray:21 stock pair:p6_1>p6_6 pair:p6_1>p6_6 pair:p6_3>out stray:45 stock stray:2 stock stock stock pair:p6_0>waste pair:p6_0>waste stray:28 stock pair:p6_5>waste pair:p6_5>waste stock pair:p5_0>waste pair:p6_2>waste pair:p6_2>waste stock pair:p6_4>out stock pair:p6_2>waste pair:p6_2>waste pair:p6_2>waste pair:p6_2>waste pair:p6_2>waste pair:p6_2>waste pair:p6_2>waste stock stock pair:p6_2>waste pair:p6_2>waste pair:p6_2>waste stray:19", + "plays": "pair:p6_1>p6_3 stock pair:p6_1>p6_3 pair:p6_1>p6_3 pair:p6_1>p6_3 pair:p6_1>p6_3 pair:p6_2>p6_5 pair:p6_2>p6_5 pair:p6_4>waste pair:p6_4>waste pair:p5_4>out stock stock stock stock stock stock stock stock stock pair:p6_6>waste pair:p6_6>waste stock stock pair:waste>out stray:23 stock stock stock stock stock stock pair:p5_5>waste pair:p5_5>waste stock pair:p5_1>waste stray:8 stock stock stock pair:p6_0>waste stray:1 pair:p6_0>waste stock pair:p5_1>waste pair:p5_1>waste stock stock stock stock stock stock stock stock stock stock stray:45 stock stock pair:p5_0>waste pair:p5_0>waste pair:p4_0>p5_3 stock pair:p4_0>p5_3 pair:p4_0>p5_3 pair:p4_0>p5_3 pair:p4_0>p5_3 pair:p4_3>out stock stock stock pair:p5_2>waste stock stock stock stock stock stock stock stock stock stock stock stock stock stock pair:p4_4>waste pair:p4_4>waste stock stock stock stock pair:p5_2>waste pair:p5_2>waste pair:p3_3>p4_2 pair:p3_3>p4_2 pair:p3_2>waste stray:16 pair:p3_2>waste stock stock stock pair:p2_2>waste pair:p2_2>waste stock stock pair:p6_1>p6_6 stray:21 stock pair:p6_1>p6_6 pair:p6_1>p6_6 pair:p6_3>out stray:45 stock stray:2 stock stock stock pair:p6_0>waste pair:p6_0>waste stray:28 stock pair:p6_5>waste pair:p6_5>waste stock pair:p6_2>waste pair:p6_2>waste pair:p6_4>out", "seed": 34, - "trace": "2f1aeb1da569dc4459777bf40e0674badf8d93e3b13cdd6d770cf88b714af69cf915bf84cf8c036e465ebcdbc6a439b57e152022abb479cfbbdb755786aa1c12acfe558ddb2688b5440075d52dff33ce16da9e3025baacd90bc14f753598b624856b8b32a7f1ba56010af12756ac35f27c5404cce221604a1d6ded6ad1f195acbc653fe178ecb199f8b7d25eca178022497a410a0b673d8b8c73acf09de138df07186db5e5108e2486705c4dc1206eb9b0b26fd4a6ee82f21ad70111dc167d55093eff70170c3c32a03f0eb15f06ddbf75caf934e10739cf332dcdc060bf0ed9225aa35626dde3d4fe1921e7fcaa3f908ea27f9ab38fb0b73574b62c528a6ea15b3fd05a3921b1a05843a4a79fa31eed3b8327a12195ea23db18fd6e3b852d40cbcbb8eb9374697bab0b67dd361d4bba612a8fb6ff789dbd28378ee12eb4dc3d6673e0348d65b02031e4fa4058f56930e9fbcfc944aab3546a0b761525f9797002490382ec5af8f9e8b8c97d5c8f1865d565d68524a485fb373423c731e99b2c09151a7c789a8386588b6406d56fb177fe13ffbd6a56a1f9c5cdad2a4aa0fd7bb09d820e0b9c24c6698c13e6973c701b730b7637d0956307c29b6338f0c53c9adc9e99b990052c5453e2217677eb19611282608681cf61918047a440fbded64676f404231bf1bad3d2a168f5ce4ad09e496bee1426a447521a412b0ad0ec32901b8d7bf11f94ebe709b46acc5c8aa8ed76067486fc4fb24b6c3542afff8286ad4e533d1b3511cd9a7b30071a51095dbbf99ea6e91c5184d719fedc0ea7be0b209147ebe7da4ae67bb6be117e790e945825d40a9fe65f3664e44f52f338eed7e9e9bb8f3790dc452e1cc64e1b4b02c03cf2621f52af1566dbbeefddd0b00e4e7a27de2ad4" + "trace": "df5efa1fb0fa376b8f46651ddcf40d1d5c6d64668a26c367d44ae55dc8991fbd4d7a4773e83fdbd37ef93ffea2e644667d04f926a2997867b3190a1bc2c1da9da41368fb9a535fe667c84e77d730d610d11686a4551153ea04ac2b515e543c846910dc5a8bca95d89db2ead7b59f230f4311caa929f04e7a0a47f876cb39750302094ab73f76825e334110e023caf2b8106d2544cbc4ffdfeb4167843eb90ee6409784629ce60c55c23d87a05570df51ab51a721283418b7a389f77c6462f79e3c7aa789dec1529110a49f8d5d3cbcfd8bd25228a4a58c2c6c869e8e1bc13eb63018b755c8b3ba77b9d4884bc3e387bd75cb6a8d7b205539960de641d45b7bf7824bf70fba89b48c6c2a3dbfb77841a431fd977384f058e1a079f6a33c5ab709ba0a2d216ac8c961b69cd5fa965c1bc0df87bbcbd78839e72aa921ae374b989275bc813c8b4234dd86e564e318f3fe64c7a72d48462dec4f2edaf65b60c31eb2706000eee1d464cafa2940901fd0c9eb2ab43cde2163daa4e54dc428dfbdc17ba82c3d77ed232016204b993ab458f913b71c24f483b5024001795c96b513c2a764933ff51ceced8dc7f654d81ce6fef91ecea0f1d06b6c98efdba3c1e012f688171aa93eaed68fc43dabf268face8db9ed2144a45c73885d1ef33fef01dce087db1e624841cbb339898d20dd66cae68eaceb99659189bb776b8364f788589f32ded255838121943a31b19ebba5aa901fdcee8a40c7cfcb453b068632f2233e24a4784652aa768bd67c0a105818b5565eff51d446ed8bb9f9e5088661e813ea70cf23fbc4" } diff --git a/tests/fixtures/games_solitaire/solitaire.json b/tests/fixtures/games_solitaire/solitaire.json index 4e3ef59c5..d0fb16aaa 100644 --- a/tests/fixtures/games_solitaire/solitaire.json +++ b/tests/fixtures/games_solitaire/solitaire.json @@ -8,7 +8,7 @@ "stat": "0:00", "state": "32f82caf", "sub": "", - "table": "d30d5a4a", + "table": "92bb232a", "undoOff": true, "watch": "", "won": false @@ -16,12 +16,12 @@ { "fact": "", "label": "played", - "moves": 121, + "moves": 120, "sheet": "", "stat": "0:12", - "state": "35d00588", + "state": "d4d01641", "sub": "", - "table": "8b182ea5", + "table": "e190f08f", "undoOff": false, "watch": "", "won": false @@ -29,12 +29,12 @@ { "fact": "", "label": "undone and on", - "moves": 175, + "moves": 174, "sheet": "", "stat": "0:19", - "state": "2b4ae4c0", + "state": "f9b536ef", "sub": "", - "table": "2f6c8098", + "table": "518afb64", "undoOff": false, "watch": "", "won": false @@ -42,12 +42,12 @@ { "fact": "", "label": "menu", - "moves": 175, + "moves": 174, "sheet": "SolitaireCards drawnDraw 1Draw 3A change after the first move applies to the next deal.LookCard backs\u2026Played 1 \u00b7 Won 0New gameClose", "stat": "0:19", - "state": "2b4ae4c0", + "state": "f9b536ef", "sub": "", - "table": "2f6c8098", + "table": "518afb64", "undoOff": false, "watch": "", "won": false @@ -60,7 +60,7 @@ "stat": "0:00", "state": "4f8e8209", "sub": "", - "table": "e6f010f1", + "table": "47fab863", "undoOff": true, "watch": "", "won": false @@ -68,12 +68,12 @@ { "fact": "", "label": "draw 3 played", - "moves": 178, + "moves": 176, "sheet": "", - "stat": "0:19", - "state": "5c6d91df", + "stat": "0:18", + "state": "cd396d42", "sub": "", - "table": "414ecd3a", + "table": "45b86d77", "undoOff": false, "watch": "", "won": false @@ -86,7 +86,7 @@ "stat": "0:00", "state": "465fb1fe", "sub": "", - "table": "76e5ea9b", + "table": "fcbf080d", "undoOff": true, "watch": "", "won": false @@ -94,12 +94,12 @@ { "fact": "", "label": "won, auto-finished", - "moves": 506, + "moves": 492, "sheet": "You won!Score 60 + time bonus 0 = 60Time0:28Won1 of 4CloseNew game", "stat": "0:28", - "state": "6a52f6eb", + "state": "5b8c25b9", "sub": "", - "table": "33b4eb82", + "table": "a314eed7", "undoOff": true, "watch": "", "won": true @@ -107,12 +107,12 @@ { "fact": "", "label": "after the win", - "moves": 9, + "moves": 8, "sheet": "", "stat": "0:00", - "state": "549e162e", + "state": "2020ae7e", "sub": "", - "table": "f9688153", + "table": "bcac00c", "undoOff": false, "watch": "", "won": false @@ -120,12 +120,12 @@ { "fact": "", "label": "shell menu", - "moves": 9, - "sheet": "SolitaireNew gameSettingsHow to playWatch and learnHistoryStatsAbout this game\u00a9 Zimi", + "moves": 8, + "sheet": "SolitaireNew gameSettingsHow to playWatch and learnHistoryStatsAbout this gameZimi \u00b7 Powered by Kiwix", "stat": "0:00", - "state": "549e162e", + "state": "2020ae7e", "sub": "", - "table": "f9688153", + "table": "bcac00c", "undoOff": false, "watch": "", "won": false @@ -133,12 +133,12 @@ { "fact": "", "label": "shell new game", - "moves": 9, + "moves": 8, "sheet": "Start a new game?Your current game will be lost.Cards drawnDraw 1Draw 3A change after the first move applies to the next deal.CancelStart", "stat": "0:00", - "state": "549e162e", + "state": "2020ae7e", "sub": "", - "table": "bc990424", + "table": "fcbadf59", "undoOff": false, "watch": "", "won": false @@ -151,7 +151,7 @@ "stat": "0:00", "state": "11147bf5", "sub": "", - "table": "1713b41e", + "table": "d8f3075c", "undoOff": true, "watch": "No move on the table helps, so it turns over a card from the stock.", "won": false @@ -164,7 +164,7 @@ "stat": "0:00", "state": "19d4ea11", "sub": "", - "table": "2af80fb1", + "table": "8690a79f", "undoOff": true, "watch": "Aces start a suit, so ace of hearts goes straight up to a foundation.", "won": false @@ -177,7 +177,7 @@ "stat": "0:00", "state": "266e9430", "sub": "", - "table": "de99a6fa", + "table": "100478a6", "undoOff": true, "watch": "Moves the 2 of clubs onto the 3 of diamonds to turn over a face-down card in column 5.", "won": false @@ -190,7 +190,7 @@ "stat": "0:00", "state": "266e9430", "sub": "", - "table": "de99a6fa", + "table": "100478a6", "undoOff": true, "watch": "", "won": false @@ -201,17 +201,17 @@ "moves": 42, "sheet": "", "stat": "0:03", - "state": "15373688", + "state": "53d010bc", "sub": "", - "table": "6f3b8b3f", + "table": "cd9b2dca", "undoOff": false, "watch": "", "won": false } ], - "events": 733, + "events": 731, "hseed": 41, - "plays": "tap:24>t6 tap:10>t6 tap:19>t3 tap:5>t3 stray:47 tap:51>t0 drag:17>t3 stock stock drag:42>t3 stock stock stock tap:20>t2 drag:20>t5 tap:20>t2 stray:4 stock tap:20>t5 tap:20>t2 drag:20>t5 tap:20>t2 stock tap:20>t5 drag:20>t2 tap:20>t5 stray:10 stray:49 stock stock tap:20>t2 drag:20>t5 stock tap:20>t2 tap:20>t5 tap:28>t3 tap:35>t0 tap:8>t0 drag:20>t0 tap:20>t5 drag:20>t0 drag:18>t2 stock tap:13>f0 tap:14>f0 tap:39>f1 stray:38 drag:6>t0 stray:38 tap:20>t5 tap:7>t4 tap:20>t0 stock tap:20>t5 stray:51 tap:18>t2 tap:5>t3 tap:18>t5 drag:5>t4 tap:18>t2 stock tap:5>t3 tap:18>t5 tap:18>t2 drag:18>t5 stock tap:18>t2 drag:20>t0 tap:18>t0 tap:18>t2 stock tap:5>t4 tap:5>t3 stock drag:18>t0 drag:5>t4 tap:1>t4 tap:20>t5 stray:14 stock tap:20>t0 tap:18>t2 tap:5>t3 tap:20>t5 tap:18>t5 tap:5>t4 stock stock tap:50>t6 drag:18>t2 tap:36>t6 tap:26>f2 tap:20>t0 tap:25>t1 tap:20>t5 tap:20>t0 stock tap:5>t3 tap:20>t5 drag:18>t5 tap:18>t2 drag:50>t1 drag:20>t0 tap:18>t0 tap:20>t5 stock tap:33>t0 tap:18>t2 stock drag:26>t3 drag:6>t0 drag:43>t2 tap:45>t5 tap:5>t4 tap:50>t6 tap:18>t0 tap:9>t6 tap:5>t3 drag:26>f2 stock drag:5>t4 tap:5>t3 drag:38>t2 tap:26>t3 tap:26>f2 tap:5>t4 tap:0>f3 tap:26>t4 tap:18>t5 tap:26>t4 tap:21>t2 tap:18>t5 drag:26>f2 drag:18>t0 tap:50>t1 tap:35>t4 stock tap:40>f1 drag:18>t5 tap:5>t3 tap:50>t2 stray:23 stray:40 tap:35>t0 tap:26>t3 tap:26>f2 stock tap:26>t3 tap:35>t4 tap:50>t1 tap:18>t4 tap:26>f2 stray:17 tap:1>f3 tap:50>t2 tap:40>t3 tap:40>f1 drag:5>t2 tap:5>t3 tap:50>t1 drag:18>t5 drag:5>t1 tap:5>t3 tap:18>t4 tap:1>t3 tap:5>t1 drag:1>f3 stock drag:18>t5 stock stock drag:1>t1 tap:50>t2 stray:30 tap:1>f3 tap:5>t3 drag:18>t4 tap:2>f3 tap:5>t2 tap:35>t0 tap:50>t1 tap:5>t3 tap:40>t3 tap:35>t4 tap:5>t1 stock drag:16>t4 tap:35>t0 drag:2>t0 tap:2>t3 tap:20>t1 stock stock stock drag:11>t5 tap:23>t5 tap:14>t3 stock stock stock stray:48 tap:39>f0 stock tap:39>t3 stock stray:11 stray:15 drag:39>f0 tap:21>t5 tap:47>t4 drag:6>t4 stock tap:39>t3 tap:39>f0 stray:51 tap:38>t1 stock tap:20>t5 tap:39>t3 tap:39>f0 tap:20>t4 tap:20>t5 tap:39>t3 tap:20>t4 drag:20>t5 tap:39>f0 tap:39>t3 tap:20>t4 drag:39>f0 stock tap:20>t5 tap:39>t3 tap:39>f0 tap:20>t4 stray:22 tap:39>t3 stock tap:46>t1 tap:39>f0 drag:20>t5 tap:20>t4 drag:20>t5 stray:34 drag:39>t3 tap:39>f0 tap:20>t4 tap:20>t5 drag:39>t3 tap:39>f0 drag:39>t3 stock stock drag:20>t4 tap:39>f0 drag:20>t5 tap:13>f1 tap:39>t3 tap:39>f0 tap:20>t4 drag:13>t2 drag:20>t5 drag:39>t3 drag:20>t4 tap:20>t5 tap:20>t4 tap:20>t5 drag:13>f0 stray:41 tap:13>t2 tap:20>t4 stray:51 tap:20>t5 stock tap:13>f0 tap:13>t2 stock stock drag:39>f0 tap:20>t4 drag:13>f1 drag:14>f1 tap:20>t5 drag:20>t4 drag:14>t3 tap:39>t3 tap:13>t2 tap:39>f0 tap:39>t3 stray:28 tap:39>f0 stock stray:14 drag:13>f1 tap:20>t5 tap:19>t1 tap:13>t2 tap:20>t4 drag:39>t3 tap:13>f0 stock tap:39>f1 tap:39>t3 stray:16 tap:20>t5 tap:13>t2 tap:13>f0 tap:39>f1 tap:39>t3 tap:20>t4 tap:20>t5 drag:13>t2 tap:13>f0 drag:20>t4 tap:13>t2 tap:20>t5 stock drag:39>f0 tap:39>t3 stray:31 tap:13>f0 tap:20>t4 tap:39>f1 tap:13>t2 tap:13>f0 stock drag:14>f0 stray:26 tap:20>t5 tap:20>t4 tap:20>t5 tap:14>t3 tap:20>t4 tap:13>t2 drag:20>t5 drag:20>t4 stock tap:39>t3 tap:13>f0 tap:20>t5 tap:39>f1 tap:39>t3 tap:20>t4 tap:20>t5 tap:13>t2 stock tap:39>f0 tap:20>t4 drag:39>t3 stock tap:13>f0 tap:39>f1 tap:39>t3 tap:13>t2 tap:13>f0 tap:20>t5 drag:39>f1 tap:20>t4 tap:13>t2 drag:20>t5 tap:13>f0 drag:20>t4 tap:14>f0 tap:20>t5 tap:14>t3 tap:39>t3 stray:8 tap:39>f1 tap:39>t3 drag:39>f1 drag:13>t2 tap:20>t4 stock tap:20>t5 drag:39>t3 drag:39>f0 drag:20>t4 drag:13>f1 drag:13>t2 tap:20>t5 drag:28>t2 stock tap:20>t4 stock stock stock stray:8 stray:21 drag:44>t0 tap:44>t3 tap:44>t0 drag:44>t3 tap:39>f0 tap:44>t0 tap:44>t3 tap:44>t0 tap:44>t3 tap:44>t0 tap:44>t3 stock tap:25>t2 tap:24>t0 tap:12>t3 stray:38 tap:25>t0 tap:51>t0 tap:38>t0 tap:38>t0 tap:25>t0 tap:38>t0 tap:25>t0 tap:38>t0 tap:38>t0 drag:51>t0 tap:25>t0 stray:51 tap:51>t0 tap:38>t0 tap:38>t0 drag:38>t0 drag:25>t0 drag:25>t0 drag:51>t0 tap:38>t0 drag:51>t0 stray:24 tap:38>t0 stray:9 tap:25>t0 tap:51>t2 drag:51>f3 dead-end tap:51>f3 dead-end drag:51>f3 dead-end tap:51>f3 dead-end drag:25>t0 drag:24>t2 tap:38>t4 tap:38>f2 dead-end tap:25>t0 tap:24>t3 drag:37>t3 drag:37>t3 drag:25>t0 drag:25>t0 tap:25>t0 tap:25>t0 drag:25>t0 stray:11 tap:51>t0 tap:25>t2 tap:51>t0 tap:51>t0 tap:51>t0 tap:38>t0 tap:51>t0 tap:51>t0 tap:25>t0 tap:51>t0 tap:25>t0 tap:38>t0 drag:25>t0 tap:38>t0 tap:25>t0 stray:25 tap:38>t0 drag:38>t0 stray:37 tap:51>t0 tap:38>t2 tap:37>t3 drag:38>t0 tap:38>t0 tap:51>t0 drag:51>t0 tap:25>t0 tap:51>t0 tap:25>t0 drag:38>t0 drag:38>t0 tap:51>t0 drag:38>t0 drag:51>t0 tap:38>t0 tap:51>t0 drag:25>t0 tap:51>t0 tap:38>t0 tap:51>t0 tap:51>t0 drag:51>t0 drag:38>t0 tap:38>t0 drag:51>t0 tap:25>t0 drag:38>t0 drag:38>t0 tap:51>t0 tap:51>t0 tap:51>t0 tap:51>t0 drag:25>t0 tap:25>t0 tap:51>t0 stray:25 tap:51>t0 drag:38>t0 tap:25>t0 drag:51>t0 drag:51>t0 tap:25>t0 drag:51>t0 drag:51>t0 tap:38>t0 drag:51>t0 drag:51>t0 tap:25>t0 tap:25>t0 tap:51>t0 drag:25>t0 tap:38>t0 tap:25>t0 drag:51>t0 drag:38>t0 tap:25>t0 tap:51>t0 tap:38>t0 tap:38>t0 stray:50 tap:51>t0 tap:38>t2 tap:25>t0 drag:51>t0 tap:51>t0 tap:25>t0 tap:25>t0 stray:38 tap:38>t0 tap:25>t0 drag:38>t0 tap:25>t0 tap:38>t0 stray:38 tap:25>t0 drag:51>t0 drag:38>t0 tap:25>t0 tap:38>t0 stray:24 tap:51>t0 tap:38>t2 tap:38>f2 dead-end drag:37>t3 drag:37>f2 drag:25>t0 tap:51>t0 drag:38>t0 drag:51>t0 tap:38>t0 tap:25>t0 tap:38>t0 tap:38>t0 drag:38>t0 stray:37 tap:51>t0 tap:38>t2 tap:37>t3 drag:38>t0 tap:25>t0 drag:25>t0 tap:25>t0 tap:51>t0 tap:25>t0 tap:25>t0 stray:38 tap:25>t0 tap:38>t0 drag:38>t0 tap:38>t0 drag:38>t0 tap:25>t0 drag:51>t0 drag:38>t0 tap:38>t0 tap:38>t0 tap:38>t0 tap:25>t0 drag:25>t0 drag:38>t0 tap:25>t0 tap:38>t0 tap:51>t0 drag:51>t0 drag:38>t0 tap:25>t0 drag:38>t0 tap:51>t0 drag:38>t0 drag:38>t0 tap:38>t0 tap:51>t0 tap:25>t0 tap:38>t0 drag:25>t0 tap:51>t0 drag:25>t0 drag:25>t0 tap:25>t0 tap:51>t0 tap:51>t0 tap:51>t0 tap:51>t0 tap:25>t0 drag:38>t0 tap:38>t0 stray:51 drag:25>t0 tap:38>t0 tap:51>t0 tap:51>t0 drag:51>t0 tap:25>t0 tap:38>t0 drag:25>t0 drag:51>t0 tap:25>t0 tap:38>t0 drag:38>t0 tap:51>t0 drag:25>t0 drag:25>t0 drag:25>t0 drag:51>t0 tap:38>t0 drag:51>t0 tap:51>t0 stray:51 tap:25>t0 stray:10 tap:51>t0 drag:25>t2 drag:24>t3 drag:38>t0 tap:51>t0 tap:25>t0 tap:38>t0 tap:38>t0 tap:25>t0 tap:25>t0 stray:24 drag:25>t0 tap:24>t3 drag:24>t3 drag:51>t0 tap:25>t0 tap:25>t0 drag:38>t0 tap:25>t0 drag:51>t0 tap:38>t0 tap:25>t0 tap:38>t0 stray:37 tap:38>t0 tap:38>f2 dead-end tap:38>f2 dead-end tap:51>t2 stray:25 tap:50>t4 tap:25>f1 dead-end tap:38>t0 tap:37>t3 drag:11>t0 tap:12>f0 stray:21 drag:13>f0 drag:13>t2 tap:13>f0 tap:13>t2 drag:13>f0 drag:13>t2 stock stock drag:13>f0 tap:1>t5 tap:26>t5 tap:19>t0 tap:26>f0 drag:16>t1 stock tap:16>t6 tap:16>t1 stray:26 tap:26>f0 tap:26>t5 tap:26>f0 drag:16>t6 tap:26>t5 tap:16>t1 tap:36>t3 drag:26>f0 stray:14 tap:10>t2 tap:26>t5 tap:16>t6 drag:16>t1 stray:32 tap:16>t6 drag:16>t1 drag:26>f0 drag:16>t6 tap:16>t1 tap:15>t4 tap:16>t6", + "plays": "tap:24>t6 tap:10>t6 tap:19>t3 tap:5>t3 stray:47 tap:51>t0 drag:17>t3 stock stock drag:42>t3 stock stock stock tap:20>t2 drag:20>t5 tap:20>t2 stray:4 stock tap:20>t5 tap:20>t2 drag:20>t5 tap:20>t2 stock tap:20>t5 drag:20>t2 tap:20>t5 stray:10 stray:49 stock stock tap:20>t2 drag:20>t5 stock tap:20>t2 tap:20>t5 tap:28>t3 tap:35>t0 tap:8>t0 drag:20>t0 tap:20>t5 drag:20>t0 drag:18>t2 stock tap:13>f0 tap:14>f0 tap:39>f1 stray:38 drag:6>t0 stray:38 tap:20>t5 tap:7>t4 tap:20>t0 stock tap:20>t5 stray:51 tap:18>t2 tap:5>t3 tap:18>t5 drag:5>t4 tap:18>t2 stock tap:5>t3 tap:18>t5 tap:18>t2 drag:18>t5 stock tap:18>t2 drag:20>t0 tap:18>t0 tap:18>t2 stock tap:5>t4 tap:5>t3 stock drag:18>t0 drag:5>t4 tap:1>t4 tap:20>t5 stray:14 stock tap:20>t0 tap:18>t2 tap:5>t3 tap:20>t5 tap:18>t5 tap:5>t4 stock stock tap:50>t6 drag:18>t2 tap:36>t6 tap:26>f2 tap:20>t0 tap:25>t1 tap:20>t5 tap:20>t0 stock tap:5>t3 tap:20>t5 drag:18>t5 tap:18>t2 drag:50>t1 drag:20>t0 tap:18>t0 tap:20>t5 stock tap:33>t0 tap:18>t2 stock drag:26>t3 drag:6>t0 drag:43>t2 tap:45>t5 tap:5>t4 tap:50>t6 tap:18>t0 tap:9>t6 tap:5>t3 drag:26>f2 stock drag:5>t4 tap:5>t3 drag:38>t2 tap:26>t3 tap:26>f2 tap:5>t4 tap:0>f3 tap:26>t4 tap:26>t4 tap:18>t5 tap:5>t3 tap:5>t4 drag:18>t0 drag:0>f2 tap:5>t3 tap:50>t1 stock tap:40>f1 drag:21>t1 tap:18>t5 tap:50>t2 stray:23 stray:40 tap:18>t0 tap:35>t4 tap:35>t0 stock tap:35>t4 tap:50>t1 tap:50>t2 tap:18>t5 tap:26>f3 stray:17 tap:1>f2 tap:50>t1 tap:40>t3 tap:40>f1 drag:5>t1 tap:5>t3 tap:50>t2 drag:18>t4 drag:5>t2 tap:5>t3 tap:18>t5 tap:1>t3 tap:5>t2 drag:1>f2 stock drag:18>t4 stock stock drag:1>t2 tap:50>t1 stray:30 tap:1>f2 tap:5>t3 drag:18>t5 tap:2>f2 tap:5>t1 tap:35>t0 tap:5>t3 tap:18>t0 tap:40>t3 tap:35>t4 tap:5>t1 stock drag:16>t4 tap:35>t0 drag:20>t1 tap:2>t3 stock stock stock tap:11>t5 drag:23>t5 tap:14>t3 stock stock stock tap:48>t5 stray:48 tap:39>f0 stock tap:39>t3 stock stray:11 stray:15 drag:39>f0 tap:21>t5 tap:47>t4 drag:6>t4 stock tap:39>t3 tap:39>f0 stray:51 tap:38>t1 stock tap:20>t5 tap:39>t3 tap:39>f0 tap:20>t4 tap:20>t5 tap:39>t3 tap:20>t4 drag:20>t5 tap:39>f0 tap:39>t3 tap:20>t4 drag:39>f0 stock tap:20>t5 tap:39>t3 tap:39>f0 tap:20>t4 stray:22 tap:39>t3 stock tap:46>t1 tap:39>f0 drag:20>t5 tap:20>t4 drag:20>t5 stray:34 drag:39>t3 tap:39>f0 tap:20>t4 tap:20>t5 drag:39>t3 tap:39>f0 drag:39>t3 stock stock drag:20>t4 tap:39>f0 drag:20>t5 tap:13>f1 tap:39>t3 tap:39>f0 tap:20>t4 drag:13>t2 drag:20>t5 drag:39>t3 drag:20>t4 tap:20>t5 tap:20>t4 tap:20>t5 drag:13>f0 stray:41 tap:13>t2 tap:20>t4 stray:51 tap:20>t5 stock tap:13>f0 tap:13>t2 stock stock drag:39>f0 tap:20>t4 drag:13>f1 drag:14>f1 tap:20>t5 drag:20>t4 drag:14>t3 tap:39>t3 tap:13>t2 tap:39>f0 tap:39>t3 stray:28 tap:39>f0 stock stray:14 drag:13>f1 tap:20>t5 tap:19>t1 tap:13>t2 tap:20>t4 drag:39>t3 tap:13>f0 stock tap:39>f1 tap:39>t3 stray:16 tap:20>t5 tap:13>t2 tap:13>f0 tap:39>f1 tap:39>t3 tap:20>t4 tap:20>t5 drag:13>t2 tap:13>f0 drag:20>t4 tap:13>t2 tap:20>t5 stock drag:39>f0 tap:39>t3 stray:31 tap:13>f0 tap:20>t4 tap:39>f1 tap:13>t2 tap:13>f0 stock drag:14>f0 stray:26 tap:20>t5 tap:20>t4 tap:20>t5 tap:14>t3 tap:20>t4 tap:13>t2 drag:20>t5 drag:20>t4 stock tap:39>t3 tap:13>f0 tap:20>t5 tap:39>f1 tap:39>t3 tap:20>t4 tap:20>t5 tap:13>t2 stock tap:39>f0 tap:20>t4 drag:39>t3 stock tap:13>f0 tap:39>f1 tap:39>t3 tap:13>t2 tap:13>f0 tap:20>t5 drag:39>f1 tap:20>t4 tap:13>t2 drag:20>t5 tap:13>f0 drag:20>t4 tap:14>f0 tap:20>t5 tap:14>t3 tap:39>t3 stray:8 tap:39>f1 tap:39>t3 drag:39>f1 drag:13>t2 tap:20>t4 stock tap:20>t5 drag:39>t3 drag:39>f0 drag:20>t4 drag:13>f1 drag:28>t2 stock tap:20>t4 stock stock stock tap:44>t0 tap:39>f0 stray:8 stray:49 drag:44>t3 tap:44>t0 tap:44>t3 drag:44>t0 tap:44>t3 tap:44>t0 tap:44>t3 tap:44>t0 tap:44>t3 tap:25>t2 tap:25>f1 drag:38>t0 tap:25>t0 tap:25>t0 tap:12>t0 dead-end stray:38 tap:25>t2 tap:25>f1 tap:38>t0 tap:51>t2 tap:25>t0 tap:38>t0 tap:38>t0 tap:38>t0 tap:38>t0 drag:12>t0 dead-end tap:25>t0 stray:51 tap:51>f3 tap:38>t0 tap:51>t2 drag:38>t0 drag:38>t0 drag:25>t0 drag:12>t0 dead-end tap:38>t0 drag:38>f2 stray:24 tap:38>t0 stray:9 tap:25>t0 tap:51>t2 drag:51>f3 tap:12>t0 dead-end drag:12>t0 dead-end tap:12>t0 dead-end drag:38>t0 drag:25>t2 tap:24>t1 tap:12>t0 dead-end tap:25>t0 tap:24>t1 drag:38>t2 drag:25>t0 drag:38>t0 drag:38>t0 tap:25>t0 tap:25>t0 drag:25>t0 stray:11 tap:12>t0 dead-end tap:25>t0 tap:51>t2 tap:51>f3 tap:12>t0 dead-end tap:51>t0 tap:12>t2 tap:51>t0 tap:25>t0 tap:51>t0 tap:25>t0 tap:38>t0 drag:25>t0 tap:38>t0 tap:25>t0 stray:25 tap:38>t0 drag:38>t0 stray:37 tap:51>t0 tap:38>t3 tap:37>t2 drag:38>t0 tap:38>t0 tap:51>t0 drag:51>t0 tap:25>t0 tap:51>t0 tap:25>t0 drag:38>t0 drag:38>t0 tap:51>t0 drag:38>t0 drag:51>t0 tap:38>t0 tap:51>t0 drag:25>t0 tap:51>t0 tap:38>t0 tap:51>t0 tap:51>t0 drag:51>t0 drag:38>t0 tap:38>t0 drag:51>t0 tap:25>t0 drag:38>t0 drag:38>t0 tap:51>t0 tap:51>t0 tap:51>t0 tap:51>t0 drag:25>t0 tap:25>t0 tap:51>t0 stray:25 tap:51>t0 drag:38>t0 tap:25>t0 drag:51>t0 drag:51>t0 tap:25>t0 drag:51>t0 drag:51>t0 tap:38>t0 drag:51>t0 drag:51>t0 tap:25>t0 tap:25>t0 tap:51>t0 drag:25>t0 tap:38>t0 tap:25>t0 drag:51>t0 drag:38>t0 tap:25>t0 tap:51>t0 tap:38>t0 tap:38>t0 stray:50 tap:51>t0 tap:38>t3 tap:25>t0 drag:51>t0 tap:51>t0 tap:25>t0 tap:25>t0 stray:38 tap:38>t0 tap:25>t0 drag:38>t0 tap:25>t0 tap:38>t0 stray:38 tap:25>t0 drag:51>t0 drag:38>t0 tap:25>t0 tap:38>t0 stray:24 tap:51>t0 tap:38>t3 tap:38>f2 dead-end drag:37>t2 drag:37>f2 drag:25>t0 tap:51>t0 drag:38>t0 drag:51>t0 tap:38>t0 tap:25>t0 tap:38>t0 tap:38>t0 drag:38>t0 stray:37 tap:51>t0 tap:38>t3 tap:37>t2 drag:38>t0 tap:25>t0 drag:25>t0 tap:25>t0 tap:51>t0 tap:25>t0 tap:25>t0 stray:38 tap:25>t0 tap:38>t0 drag:38>t0 tap:38>t0 drag:38>t0 tap:25>t0 drag:51>t0 drag:38>t0 tap:38>t0 tap:38>t0 tap:38>t0 tap:25>t0 drag:25>t0 drag:38>t0 tap:25>t0 tap:38>t0 tap:51>t0 drag:51>t0 drag:38>t0 tap:25>t0 drag:38>t0 tap:51>t0 drag:38>t0 drag:38>t0 tap:38>t0 tap:51>t0 tap:25>t0 tap:38>t0 drag:25>t0 tap:51>t0 drag:25>t0 drag:25>t0 tap:25>t0 tap:51>t0 tap:51>t0 tap:51>t0 tap:51>t0 tap:25>t0 drag:38>t0 tap:38>t0 stray:51 drag:25>t0 tap:38>t0 tap:51>t0 tap:51>t0 drag:51>t0 tap:25>t0 tap:38>t0 drag:25>t0 drag:51>t0 tap:25>t0 tap:38>t0 drag:38>t0 tap:51>t0 drag:25>t0 drag:25>t0 drag:25>t0 drag:51>t0 tap:38>t0 drag:51>t0 tap:51>t0 stray:51 tap:25>t0 stray:10 tap:51>t0 drag:25>t3 drag:24>t2 drag:38>t0 tap:51>t0 tap:25>t0 tap:38>t0 tap:38>t0 tap:25>t0 tap:25>t0 stray:24 drag:25>t0 tap:24>t2 drag:24>t2 drag:51>t0 tap:25>t0 tap:25>t0 drag:38>t0 tap:25>t0 drag:51>t0 tap:38>t0 tap:25>t0 tap:38>t0 stray:37 tap:38>t0 tap:38>f2 dead-end tap:38>f2 dead-end tap:51>t3 stray:25 tap:50>t4 tap:25>f1 dead-end tap:38>t0 tap:37>t2 drag:11>t0 tap:12>f0 stray:21 drag:13>f0 drag:13>t2 tap:13>f0 tap:13>t2 drag:13>f0 drag:13>t2 stock stock drag:1>t5 tap:19>t0 tap:26>t5 tap:16>t1 tap:10>t2 drag:26>f0 stock tap:16>t6 tap:16>t1 stray:26 tap:26>f0 tap:26>t5 tap:26>f0 drag:16>t6 tap:26>t5 tap:16>t1 tap:36>t3 drag:26>f0 stray:14 tap:15>t4 tap:26>t4 tap:16>t6 drag:16>t1 stray:32 tap:16>t6 drag:16>t1 drag:26>f0 drag:16>t6 tap:16>t1 tap:15>t5", "seed": 31, - "trace": "de246486cf439ed4a95df10d0177091b94ef2f54647e6024dd381b65f5f352abceafc7866b7522931705e3a222d9bd6867214e53c865c4f1818b7567865cfca0896e03bc07af356eeba1d0d4519ff1139992b5f8de8320fadb95c6e6a1d88c99869cd3b6a48b1025c75048782a5a53f2ee69d922452c2f4b6a6e01df4f572eac0ff52b4b47830bdac26121dc7d9c22f5355238285ab7433d3f0b720b3399c34bacfcae06277cd3b38cdc2fb5985f6d8e134360f6c4f88e8bd7e53518cf95e78d6e46e90822b7623c9319d782627062cde01f6793c34426d627d53284201521b62197acf36be1656dc7b7cb07923fe57a711387773dbd720a8c9c212d599ae8f0242f9a2257609997354725b8fc09a2e61ed3fc406d1cc6cf4e047a66e9250e34d49af5ac5891c581b2c98693f0390501949c1e8989608a641270d21303ff44855b3c3c4c1e8809a6eecfbdeae9ea6b3942826f63af216387f0fa15cdcd7cb9c4b61b9e7bb92a824ccfd07c30902e42dc6ba10c89bf5d2de1c669b9e4cc28220695c3e167cc8052a50f2bf9dad2e6a90910a2e055d08824acfe80ca387209339276dfc05ca44038ca079fffe07d41ad21d749be6cdd2444003f5345309a5fa0050e760be916319fbf50b3fd3309657bcdd510e235225813b8a52c4246c74cd1e98ebf9d7fc69cfc297820134a587b45b5911e79d428a837b094ad6d2f7d54aa25448d09ff39a42048bc2f60c3f9497869ca3db4c66c20b094696a51a4d793f9630d81638a2f470c5ad6d5245047cca67568e0c7efd8f2431ceb2b2408858194cc3224f6540a72e0ae3a79e116f4e05d32f65339505d7c9d0039955119ac3b52fe753cf5c372c3917cf4103250dd8f7a7cc7f967f378287c0045528fdbf2f2ff5ae2e555ba6d8177d8c325e34966d5a80611b15bdbde6cbb1ce0d5b53311f0a0712716f65e6c1aebafeffc6e3efee727ac4db183c7d4e25968d99b2bfd6e1d170fdc79e5eacea25bd9c5fc73e8e6d8fbd5765f3050d4e89336db02d7947149eb7c5a4cfc76acfb458c10a2b4a909ff5dd385235b9b1d15e559d41b2423ca35c140d8866f01492a29a53524ca21240854baece700432cb4effaa576db2a70b99968c1952295bdc288a784d7414787a75913cc6551f5a37136aa747bc9a1eedbf3a8066bffa0568adddee5832e14b450111f2bc42f55bd26a144ec6b670f862463f7641aca3c346e0730cf19da591aef39d318192e5a80e53d0ccd00a806fa29fe999c9576c9a73dd1fe48df92dca9c68192fc2196cfd14d2738d1dfc4d47511cbfc1803a4f256575729b2b1b977f9048e1cf375303fba604a8d602a9fc339326a4e17a5e4981a9d69e638881690dfd2cab7f87a67821d09c5221b2654d883f4b3a4b4f2725a1bf52c636c30d34dfc40fa42748137a18533a98be62f561f5d72eb0835ad4911a16de341a960da1a2321bce21aa38632e0a8b1c2bf1073654f6ba45b6d6cd024f3c3c68ff076a9f7462bc48a5acd6eb5d80fd68f0a4beef7bfab39bffcc0c0477d1a3954452d0fcbf17347ccbba827be611b5b6ba53772debd82fca89d999e167a25f0526ca728ad4f6de5194fc64eac452c18aa669a1af67d2b99967088a94ad119ab1630756be4fd16db9477860ca38b55c2d5d1652d092cc827df0a081c93f714c06925ab770b32545ed27c7a4a707b19c06cf76ad24e485c42e3496979958c6561762c233b0d862772ac7720810eb7cd3a6b68dcf84bad9fabc3875481d7a3f6e0782472a8be757465b10488751244758b81454a047ac24150d09abd5d468a5abda41e3d67c56ca6bcf2b6f0af9d4dfb1cd477057db182e94a3dbf03b09d65e21ddd472eb7523da515320a40fa80037275f1f3c1a469e7a6229dfce75cabc8a44330caefd8e08b6781d4aa3f37d5addf9ff8409c9e20a42e6d0366d9e6943f187e9769d5a4192aecc0f982b8a050e9f2a206141e9ad8ceb6753a57a172ee53cd3b3d593f2a0bc96f25ba87db87068d261181f95cc381a9140e5387fefcd2805f493fb4264d8a53ded2525e9d6d280e60ebe5e1113a2ddde550859983c7aa75453e65d17c16d682416cd2f5c5f17ebfd3b58d9939a91e930471f2b9d89cfba05b71c42b8d523585f94a79d25e83ad879b855ebd9561c78a1b972af4ae574535b7c0a05faad90c33072648a0d91e62758bdc721aeb0c657f4eb426d5c21ec900ae9fcacf74c3d6a1fe2fe5034a37550ed753bc8c8e80d2b1cf00fb44f99536983f113e3f9143b407668d76889b44dff3eca54ecc415067921d9f0e1a3f3be2a2b7f673385098e7a290b809e38a8589bfd838b0923768e79be40778f5316253195bd746d22b1904fff669424b61aef72576009339de3b42e81a4afd02f248d2f479ad6df08eff8ee18196c082abc0cbc2d17004fcc016abe4d6d1a1581a2265db2dd2c7e3b39a2788b415512ce96eca52d2c2020839d437f4ae1ffce8026e527bced0554576c257f8329846781bf0011462dd68595041bcabcacb495880c3c32b7126d534243dd024e581f6e285906d767b9213398212f828df8d8be2b5bcedfb91667d988af8c34b6e978952103fc5ad83925deb5a9c42baf0491ffc6ebc772bc4551fbf1fe151bae05e9ffe189ead1db711909907792df695e600a3e9feaafaf836b70595c532bac346dfb6995d6091ba057b2652741009408c54f0b10fa3f3f1dc14ab5a37c271e4d9ed1dca7faca6b48a3150b381e80d95ff11315cc314daacad16f11ff5a6453e042228355e0f99913f591076ad4bac511d5287b61841169d9d2cd9e7dd3983143eac809e77abf520879f16514245e2700b2e452e83149d402155f8adcbc47d3f1df270aa5c7eab3de0c8ec878504de2bceeb632768292002e79f8105393cc0db0b0881e7c50983261dc8add613674e5951148cd8efbeea086bf74f067a4625c465f44c78b6e491268b33cedfdc89b2df9b56f2bf22448d8552fbd38dd2fd3a04ba40dc44719e58974f42e2390437029bc574d7a2e5909e68277ec4e8923ebb6e3883e4d693dfc84c8879adbc738478aa65e88567172271619d3a10b156c53187dcad501f90e3595f4000150bfb7d8d23a513ca0a0c4b6ce4e63ab3178e2e6c3fe28282966938ad13736b77c3b760562924b774b1be3361a861dba1b135357c118b04e49f2c003f2dd33e3ce73dcb2bd4e61366d14bbdb783e58bc6f0317c47d17d4ad2eb9ffe9759a607b0a98d608247c4a59afafb7579ed1640fe857fb7e317cbb82c816b7da64cb62eb12d511103155b7e3cd42d71e33b635e1893233f456801ccf22662d43dfbff3f319a5d26c6ef6808edac3448537e19dd9842d3e25551fdbd92c9a6122dedc31d0829fad02b7873c0e69f4a017b2678a587850f6c71e468dd23d046830c6348cb9d48239f080c419755bc257efc61717ec331cd9ea19a4eca1fbc5531691ccd68720707d679a6997624ed8c1f33a9f9889078571084ff08b08b59b6f4475798071c92f19b99bd4bd6318a382fb0bc7bda03bb26d35737467328f63af96a12aac82c464a6ba83dcd033825b5d27842ce00289fdbb01e8a1ae92f4c495f608f4ea1fc6a2ba1fb0336d309a141c11c46ccabf236603b8d824660b201a90a05bc19b052daad4da1a7335f9ef80618fd9805f3371a65aac97fb2bdc317baa7f2ef148f318ec701734b04272d15c381ee7927418401c1eecc0b70f576ebfbed2020f2198c77379b931070674b2d3c6fef55f67fcc90344059ea0711d12e73881e56372ff6318acd75e315ce39792274b25d7f6cd410738def8ac5c34b4e0e52c502077ad7e2a8a52cc68d9faa2feb36b3199dcf229ff300c750788068737fa48e26d3bea7e6ffc53751b514de6059afd9c2081c55a9502d619e84d168e02c99e1c43a897777f147240c4fe1252a852b7db87d3379a81a2376e2ddb6dfe6bd9481708ffb1659fbb841ff3fc2d53e2a6f0768d73fbbb209d8e5ba17a9f5ada9467a0a8beb9fc378d6cb95ea3674e6fc826bcf3d1fb8ec1d1aaeb534f30b47dcb6a55045da7971171bf99348af20212786d399897285e560cf5cc88efab644e689fb61b6630ac59ac27499c9fb90dceb1726f244302c0ce2862e9c33c01f1ba19e" + "trace": "e9aa7c10f8c7843938dda57c7278e65beb0363e9160c78d1454f4959eae7d4a099610410f6b4691677a9a7e52fe63658a5d0ecbd3d235646622fd19e0601e147ffe84a6457cad98edff1d821218784cae6d4ffe643a80cce4db3f30fffc8e82a0b8e7af7c91846b030f5b797cb0c6d9d64fd978fb95b9b659aa472050c592198546da96daf4d343411caca414c5b39268788e21aae92bdcd74b7d94c7c4182c52cddc1386db07cf4704012c86974e122c0e7d365a523cf2ae145def333a2f41c67f4abe17c7d10b1ee97a6e6d7968dcfdb0e70f79e62c4a58a341eb086af70e4781e342bc3f8bb79e01e219d72e8b3054bb2b24736eb4702a06b0b553009df8d8445aaa131782ca5b00097bc378a025f4e633aaebf8504e1dd88c0ff60bb4b152ff910b0f542aa208dfae0ed08da84021e6f817a747bc41af457460af0ce60f9d626ed631d76a78ccd020547d402cf09fc003d253f2049f1a97a0ef00e5e9264fd5d247b0350b00c18744453ae9af7ac1ebc04656074b4f6bf8b5f0c4aec2ca5e2f17f3a570168b35afd08f891d9094cb34293a9f20d8e87c6ca646851405cb5d63c25ec276c92654d4a94ddf2c1091a1e058bdcb7c8a7af4cb41caf9f3ebaed6aa7c8b758244648a0f658fb8f5cb08095f90caeab4b5b46281843312a502a3b82916b467fba2b71566ca13d1e3e156b682586693984a0b62b1ad46e1863a50980476c68851eb858d3daa3477b92cd8f395137b04ec3c80fc7320531d8a8dae9275a26f0467f5cb530004ccfca21255e1a1fd02ce1de253663c6289973f2c1ea41ef65c899db720e94152f16463ba793a2677c647f396b4b78d1abbb03aee76a9db70faab6c9b76d5285596829822bef85235665d5979d33da780e230be9b28dcafc0406d7bd9c4e6712409ee8c6b4d42c51ac53762fc645524e4b61d984c3b9e9f83f977f7483e9e0d1e117bf2a920bbef4d33d4bf2f8dbfca750d83af13f79f935d497ffe27e2ae91f1289dd4256930d0abd72df820096df93a2dd7d49197a2b624468d36feec492c785756574579a9c191395ea0495bf620df59ad37441a33db0cc899661f94ea29a32556af25223a3a37a144be7f45070f8e95cd19def25a35579eb6408ebc90ff727fa54cfb79f4129291b79f7d06bdc131743bb7aa27e501fd3d242580178e07bb7fe7db87b421d2e651bdccfb4caadb37d4721950dc609855940ae5aa392e16451ed958e264a454eece4483727ddaac8cb0cef0c51fd4480ed38fd5a073af63bf91a439f6e785af75dd0b70d3155992ab6dd20ca69e7af8dcf8da2d26596c14cd03666edf8e8228e9d3eefd72931bddcfb976af13db093d2b9bc50131ca534a78f8324a4c22eb7df46545ab11ee30dbf61c6c2d76ef5bb53bec5cb9382bf0b702521ec96ab33d5209f2b36d9338d4ca79772e599cafb8db20c85e3a884b89d4d37081cdae205e1d585f15a95db25d97641712a958289ba01ac5de6970c37188a1c3c80b5bdb7468c52a13e9e25c955255db9b2d7fb1b77b11027e39f29d0cd27bf8525fe847e30e41a3601374c92a02cf0fca25d7bc4c184f98a73292ad3b6f9187a78bcde7c718d37fa97e92a721b5eeffee38ab0ab3fdbc71ef2c972d240dd5e7dd6bd13b81b05f8873ff616358ed27684ccaad530eb78eafab2ce4a896dc146295eb6ad2a56209432392a8977264438094a9581a646dbca1661f88b90f56515366e47429192437d7d4a1a334cca4e91f26567d690e37eb1c06230b3e3307b9cfec80cdd185a3ddfdda0027222c2bb7e1541d9601da63d0c4390bd089a19444f8127d61187b707031e036edef1f525fcefd188a4cf7ae9119cc667fbc82117349f2663a9376067e219da2f622b6fa99f6e4ef77db86644c2e5547014e3762b16fec62b96fdb4a397b3ece8dd3dda33bdc43cbc777157c20fee18485ce664640b10a4f133194172893add5af0d85b0c1448a6daac415e33d57d93d2daceb287e3efda9576213d6919f15627054dfbd2dc3119d11c62f4a4ad078ca5ab790ea1ecc8f3a36b18f508aa2c4ae6202a6dbedc53d61ebde99ad7f8e0586e6a6ef9842b3b84019d4713af411d41985e78912f1fbe3c44f8d1411a9cf93944e206fd125b15449b4b0ec0b5c367e26b6dea1f5f671925aa1ff519cff5c5b8d4886b8dfc304ea04ca36de626b6deadbad3bf09f9e2dd02e3ffb81a46b745bbf22e0d32e0cc2f285d4734ebc50aadb265cbf2660683c63ef61fa9239e21ef307ef580518c6f8dc42a06339b1a127ed569974e570d42df46991ae12047f5f114ade9b79d4d333f3b1afb89cf41f51d715fcd32c598db993fa1f56fe08601c7f9c35954255913c7fcfa883683d61d000049c37a684d4f097ffd2fd5d47b84c4269a7bce11e570f3a1d92d336eaf2810ebc8edca0583c6992472a98169d4c8bb7a890207281e8bdba2287aaaddd8a2b9fb965dbe6b6ee79886ffa9614cfb5885f9a109e6c9285e0c8bcb38de2ab59494e3ef1cc85a1fbd708534535ddc1adc5351f7f3a7baea4464a60a110b8524443868a5c1e7369256f8ad82c002b1b2e5cac95cddefdf3ddcf122152083ddb0a8f1e999202aaa43bd6bc936b9e5083994c07348fe47d6ba72469d880b55fe25b421593a5d26a284d3c6d208fe2b0540df86d5b82d38ca8952e9ec792d4a9201984786fc06550db1abe30218b80617d657a2e3ed088121390fc78314b0a00a3b150e2a41f2356049b245ffb8ad998fa539605030d1792312321f9b45e852298541522f8f0564b8ff94b6de4ade7e86e0d132c5af71581955dc6dacdd6f23d9b799a43364729c7d8a74cf1b83c5ea0f0b2a5500a830132e85fbbbc8b10cfb95fd6da2a31ff5cff8fb0a995cb7019d98dd925aaea2ed7b72929a63ef1f5bf0f2397452dd89ed2a337c9877bb1a3fb34ebb22d691c24db588b4f0adefe3ab942de008530f2960be7bf2aba52e5cc3edec6d235e14511c171f81924a086d3144f33d1f117f6eb26e6c70a5fbc3d5c6f05ea9efefd03f3137c6d647e77e99b0836baf76bef155aa061aad2a12f3627f7786afb46c0a85384fd8670b9fe874b7740e80721b1f185e839118daf044435cde9e0c8ff4e0b3908def5cf64f6435e0093903968e519e96aa1c2e8950f243e681d09dae3ed503fa8e06a210868567382fb9594f54b7bc704760a7acb9893169cfef0e5774c6c6b4a1b137d4c03cf5764ee9b478a3a2327694ed4aef9d850305c5e2d0191ccf7abbca98de67ee53dcd812229c35cf7576fddd16111357af03fa2d235fdb9d4764f7dacd6ddc7a59157f066b378643041337ffa9c41a213e4d77f08c480aeceeb443abbbf0d63954d9f3f5afe37a2b2cbead09e89319f52b60117b6d1405634962ebabbe676a9faf8b3e9f5706661fbc859669e7ad723a07469107eaa139b0c9b689949172347dbf49c083cddee46eb760c573221abff9fd34bd1bc2a806b1c6fdfcea7868cbfeb4cca206138e88991c903e06af269705edde8fb9fca331bea3b16d82793883acba9642a889b50dfeade5c9420086ccd60f13c5f0ca04739f1ab89abb7ddfa1670d151ea9af00c88308ab500f4eb725c00dd6570c0a5e83f385b8a206ffc26eeb497c54b1335aa31f476ad4943943c6b235f172c787d43b8b37d34470a1cd249848be44685ef4a977cdee8239c7e25da38f59b5c35684cd0f9a3ac16fc8d00030243358828503fb7ca9687b7133c1210774b1cf64c865d655d6cda24bb9d633d46d78e71a4fff2aa7720d82c505b50e2f700683ffaa9ef72dbbd0e7842c6dad3c8e067ca9e7d8ee9889d694863d2b45f7837c0e974a971a4dbd2466da70a27683695722598ca69737a206462e9b79bdd38071169e352cab9d4aa2cb6b71c74f8e24bfc8889bfef65a897c711a6f94335d97db691f13b6a707ece030d1cdfd4356696db306c53dfef626638beee820faaeaa5440ad36d20e570d8847dc4071db24c0e00508298214a550678360734b2a318cfac769c97fe063b82b28739fa1abfc0bda3915e92fb6578b47bde58460f219c447456adaf9cca60f72950b8882738facbb267f4f085b9e0880e8be4f2dd52c2a7923ad73c5df4d6ea1a4f895dc26da" } diff --git a/tests/fixtures/games_solitaire/spider.json b/tests/fixtures/games_solitaire/spider.json index 931c50b5c..a9f37d1cd 100644 --- a/tests/fixtures/games_solitaire/spider.json +++ b/tests/fixtures/games_solitaire/spider.json @@ -8,7 +8,7 @@ "stat": "0:00", "state": "4a477fb2", "sub": "", - "table": "4a92fd5d", + "table": "469d5551", "undoOff": true, "watch": "", "won": false @@ -16,12 +16,12 @@ { "fact": "", "label": "played", - "moves": 131, + "moves": 138, "sheet": "", "stat": "0:14", - "state": "907c1145", + "state": "95216a23", "sub": "", - "table": "93f7b159", + "table": "834a5641", "undoOff": false, "watch": "", "won": false @@ -29,12 +29,12 @@ { "fact": "", "label": "two suits played", - "moves": 127, + "moves": 18, "sheet": "", "stat": "0:14", - "state": "c34d40b", + "state": "91ae781a", "sub": "", - "table": "2806e364", + "table": "559c00d0", "undoOff": false, "watch": "", "won": false @@ -42,12 +42,12 @@ { "fact": "", "label": "stock refused", - "moves": 127, + "moves": 18, "sheet": "", - "stat": "0:14", - "state": "a2d7c1ee", + "stat": "0:15", + "state": "36c52e32", "sub": "", - "table": "82ecdb12", + "table": "31a318cc", "undoOff": false, "watch": "", "won": false @@ -55,12 +55,12 @@ { "fact": "", "label": "refusal gone", - "moves": 127, + "moves": 18, "sheet": "", "stat": "0:17", - "state": "a2d7c1ee", + "state": "36c52e32", "sub": "", - "table": "3c64bd15", + "table": "b0f95953", "undoOff": false, "watch": "", "won": false @@ -73,7 +73,7 @@ "stat": "0:00", "state": "1379e860", "sub": "", - "table": "baea78ef", + "table": "20095e5f", "undoOff": true, "watch": "", "won": false @@ -86,7 +86,7 @@ "stat": "0:00", "state": "77e0b005", "sub": "", - "table": "74755e2a", + "table": "e50f6353", "undoOff": true, "watch": "", "won": true @@ -99,7 +99,7 @@ "stat": "0:00", "state": "e95c585", "sub": "", - "table": "acea9e1f", + "table": "95c581cd", "undoOff": true, "watch": "", "won": false @@ -108,11 +108,11 @@ "fact": "", "label": "shell menu", "moves": 0, - "sheet": "SpiderNew gameSettingsHow to playHistoryStatsAbout this game\u00a9 Zimi", + "sheet": "SpiderNew gameSettingsHow to playHistoryStatsAbout this gameZimi \u00b7 Powered by Kiwix", "stat": "0:00", "state": "e95c585", "sub": "", - "table": "acea9e1f", + "table": "95c581cd", "undoOff": true, "watch": "", "won": false @@ -125,15 +125,15 @@ "stat": "0:00", "state": "e95c585", "sub": "", - "table": "acea9e1f", + "table": "95c581cd", "undoOff": true, "watch": "", "won": false } ], - "events": 342, + "events": 247, "hseed": 43, - "plays": "tap:358>c6 tap:92>c4 stray:41 stray:96 tap:255>c0 drag:43>c3 tap:255>c5 tap:255>c0 drag:91>c2 tap:355>c7 drag:255>c5 tap:301>c8 tap:412>c4 tap:301>c9 tap:301>c8 drag:406>c3 drag:100>c8 tap:356>c0 tap:42>c0 tap:255>c8 tap:406>c7 tap:91>c6 drag:301>c0 stray:300 tap:406>c3 tap:42>c7 tap:253>c8 tap:253>c0 stray:355 drag:39>c2 stray:198 tap:301>c3 tap:255>c4 tap:356>c5 stray:199 tap:406>c5 tap:91>c5 tap:42>c3 tap:44>c0 drag:39>c6 tap:253>c4 drag:39>c2 tap:406>c7 stock tap:310>c7 tap:403>c3 stock tap:250>c0 drag:354>c1 tap:45>c2 tap:252>c2 drag:50>c4 drag:308>c8 drag:354>c5 tap:354>c1 tap:309>c4 drag:45>c0 stock tap:50>c6 tap:304>c1 tap:308>c5 tap:308>c6 tap:252>c3 tap:304>c0 drag:205>c9 tap:45>c2 drag:355>c2 tap:250>c2 tap:45>c0 drag:254>c6 drag:414>c4 tap:149>c2 tap:411>c8 tap:411>c6 tap:252>c1 tap:250>c1 tap:411>c8 tap:304>c2 tap:304>c0 tap:201>c8 tap:50>c7 tap:355>c5 tap:50>c6 tap:355>c0 tap:355>c5 tap:308>c4 stock tap:154>c1 stock drag:360>c3 tap:247>c4 drag:150>c7 tap:150>c8 tap:99>c2 tap:150>c7 tap:150>c2 tap:409>c2 drag:99>c3 drag:361>c0 drag:47>c2 stray:403 drag:411>c6 drag:360>c3 tap:48>c0 tap:47>c8 tap:413>c1 tap:47>c0 tap:150>c0 tap:154>c2 tap:254>c2 tap:99>c8 tap:47>c2 drag:99>c0 drag:307>c8 tap:248>c9 drag:150>c6 tap:150>c2 tap:254>c6 drag:150>c0 drag:201>c4 drag:410>c2 tap:409>c6 drag:410>c8 tap:150>c2 drag:47>c4 tap:409>c4 drag:307>c2 stray:154 tap:201>c6 stray:404 drag:150>c0 tap:254>c4 tap:411>c8 tap:409>c1 tap:414>c2 stray:257 drag:409>c0 tap:307>c6 drag:410>c8 tap:414>c4 tap:47>c1 tap:362>c4 drag:303>c0 tap:409>c8 tap:47>c2 tap:99>c1 drag:410>c6 stray:299 tap:409>c1 tap:305>c6 tap:362>c7 tap:99>c7 tap:154>c4 tap:304>c2 tap:254>c8 tap:254>c2 tap:356>c0 drag:99>c4 tap:356>c4 tap:150>c8 drag:411>c7 stray:43 drag:154>c1 tap:306>c1 tap:362>c4 tap:154>c7 drag:93>c0 drag:307>c8 tap:308>c9 tap:308>c2 drag:154>c1 stray:408 tap:308>c9 tap:100>c2 tap:356>c1 tap:307>c6 tap:47>c2 tap:304>c4 tap:304>c2 drag:99>c9 stock drag:291>c2 stock drag:148>c4 drag:296>c7 drag:147>c4 drag:392>c9 tap:393>c4 tap:48>c7 tap:294>c3 stock stock drag:146>c2 drag:154>c3 drag:43>c7 tap:80>c9 stock stray:250 stray:353 tap:290>c6 tap:88>c5 dead-end drag:49>c5 tap:44>c4 tap:258>c0 tap:258>c8 tap:258>c0 stray:248 tap:258>c8 tap:258>c0 tap:258>c8 tap:258>c0 drag:258>c8 tap:258>c0 tap:258>c8 drag:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 drag:258>c0 drag:258>c8 drag:258>c0 tap:258>c8 drag:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 drag:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 drag:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 drag:258>c0 stray:145 drag:258>c8 drag:258>c0 drag:258>c8 drag:258>c0 tap:258>c8 tap:258>c0 drag:258>c8 tap:258>c0 tap:258>c8 drag:258>c0 tap:258>c8 stray:398 tap:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 drag:258>c0 tap:258>c8 tap:258>c0 drag:258>c8 tap:258>c0 drag:258>c8 drag:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 tap:258>c0 tap:258>c8 tap:258>c0 drag:258>c8 tap:258>c0 drag:258>c8 tap:258>c0 drag:258>c8 tap:258>c0 drag:258>c8 stray:51 tap:258>c0 tap:258>c8 drag:258>c0 stray:398 drag:258>c8 stray:394 tap:258>c0 tap:258>c8 tap:258>c0 drag:258>c8 stray:79 drag:258>c0 tap:258>c8 tap:258>c0 stray:83 drag:258>c8 drag:258>c0 stray:360 tap:258>c8 tap:258>c0 drag:258>c8 drag:258>c0 drag:258>c8 tap:258>c0 tap:258>c8 drag:258>c0 tap:258>c8 drag:258>c0 stray:48 tap:258>c8 tap:258>c0 drag:258>c8 tap:258>c0 drag:403>c0", + "plays": "tap:358>c6 tap:92>c4 stray:41 stray:96 tap:255>c0 drag:43>c3 tap:255>c5 tap:255>c0 drag:91>c2 tap:355>c7 drag:255>c5 tap:301>c8 tap:412>c4 tap:301>c9 tap:301>c8 drag:406>c3 drag:100>c8 tap:356>c0 tap:42>c0 tap:255>c8 tap:406>c7 tap:91>c6 drag:301>c0 stray:300 tap:406>c3 tap:42>c7 tap:253>c8 tap:253>c0 stray:355 drag:39>c2 stray:198 tap:301>c3 tap:255>c4 tap:356>c5 stray:199 tap:406>c5 tap:91>c5 tap:42>c3 tap:44>c0 drag:39>c6 tap:253>c4 drag:39>c2 tap:406>c7 stock tap:310>c7 tap:403>c3 stock tap:250>c0 drag:354>c1 tap:45>c2 tap:252>c2 drag:50>c4 drag:308>c8 drag:354>c5 tap:354>c1 tap:309>c4 drag:45>c0 stock tap:50>c6 tap:304>c1 tap:308>c5 tap:308>c6 tap:252>c3 tap:304>c0 drag:205>c9 tap:45>c2 drag:355>c2 tap:250>c2 tap:45>c0 drag:254>c6 drag:414>c4 tap:149>c2 tap:411>c8 tap:411>c6 tap:252>c1 tap:250>c1 tap:411>c8 tap:304>c2 tap:304>c0 tap:201>c8 tap:50>c7 tap:355>c5 tap:50>c6 tap:355>c0 tap:355>c5 tap:308>c4 stock tap:154>c1 stock drag:360>c3 tap:247>c4 drag:150>c7 tap:150>c8 tap:99>c2 tap:150>c7 tap:150>c2 tap:409>c2 drag:99>c3 drag:361>c0 drag:47>c2 stray:403 drag:411>c6 drag:360>c3 tap:48>c0 tap:47>c8 tap:413>c1 tap:47>c0 tap:150>c0 tap:154>c2 tap:254>c2 tap:99>c8 tap:47>c2 drag:99>c0 drag:307>c8 tap:248>c9 drag:150>c6 tap:150>c2 tap:254>c6 drag:150>c0 drag:201>c4 drag:410>c2 tap:409>c6 drag:410>c8 tap:150>c2 drag:47>c4 tap:409>c4 drag:307>c2 stray:154 tap:201>c6 stray:404 drag:150>c0 tap:254>c4 tap:411>c8 tap:409>c1 tap:414>c2 stray:257 drag:409>c0 tap:307>c6 drag:410>c8 tap:414>c4 tap:47>c1 tap:362>c2 drag:303>c0 tap:414>c7 tap:47>c7 tap:356>c2 drag:411>c1 stray:299 tap:411>c1 tap:307>c8 tap:356>c5 tap:410>c8 tap:304>c2 tap:154>c4 tap:150>c4 tap:201>c8 tap:356>c0 drag:254>c2 tap:356>c5 tap:304>c0 drag:47>c6 stray:43 drag:411>c7 tap:306>c6 tap:411>c4 tap:362>c1 drag:93>c0 drag:45>c1 tap:99>c7 tap:304>c4 drag:308>c9 stray:408 tap:409>c6 tap:100>c7 tap:100>c8 tap:47>c1 tap:99>c6 tap:152>c7 tap:99>c9 drag:47>c7 drag:154>c2 drag:146>c5 drag:414>c4 drag:201>c2 drag:307>c1 drag:201>c1 drag:307>c8 tap:45>c2 tap:184>c6 tap:360>c1 tap:153>c3 stray:257 drag:351>c1 tap:353>c8 stock tap:291>c2 stray:48 stock tap:148>c4 tap:393>c2 stock tap:354>c2 tap:80>c2 stock tap:258>c4 tap:146>c2 stray:248 tap:356>c4 tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end drag:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end drag:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end drag:290>c4 dead-end drag:290>c4 dead-end drag:290>c4 dead-end tap:290>c4 dead-end drag:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end drag:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end drag:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end drag:290>c4 dead-end stray:145 drag:290>c4 dead-end drag:290>c4 dead-end drag:290>c4 dead-end drag:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end drag:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end drag:290>c4 dead-end tap:290>c4 dead-end stray:398 tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end drag:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end drag:290>c4 dead-end tap:290>c4 dead-end drag:290>c4 dead-end drag:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:290>c4 dead-end tap:403>c0", "seed": 33, - "trace": "c736db11db2f74f51e20cf5990e6c50546d772ba456752ee9cffe2a1bf0c6523f51af2003d3be5d7f7dd0cc1bb25eed8bc5dd51dc2955b6b293f4faf506cc6f279ae66de5c27d2ef62424c73bd6409c9ff718b8aaa51df6a12104e6bd6cf33389cc745ad35f87d74bd103f783cab2a02235cc447e14efeab63fa0fb8cf5edc6f2e2c4d1999628e602f01a9ea00fba19b3b8c6d126f46d314b72a8382e911dd34782ef176d52e584ccab9f4661067f7959d803fdf2b73762ab3ae0dc3cae33df1395392310706a36e37758277a7d1f32d5c65dbfb60db43935174452de10736cb48d93cd6689f1d7dac51234d9e4681e300f9fdff038928da70964c37659d735b3df8abd3c735c6fadfeeac5a4b71f4cea550441163e32e46e037b26f6ae91256b0dbec9f14ead58040ced76d48721722500d54991b295e4c5f29ba40a6a95e79e9d8e257ce8406ae2ca02dec583fb9b16fe609730c624d0a6321634ead39b281c11caf3c8fa54a22fe4e6328644838e7a8bd5447e14ac75bc4f08ade7e7f6c3ce30d9199e3eb3eb0129ff653a5d092c1c84921f37ff71191e811ca218662546880333e1309e1fa6ebef375e24471184fbe508d618fb311e106ddf59c40a2cefd11107a5511ca1ac86407e4fc0be9d3bd676e0f7c98b0f6ada8a3658bdb581945eba724e4690c1eb4debeba623de89a09ff8d8be3ba4be3eb5a1437c37663c5b6cab5e4fd052b0cf3803d9ab5dab94c6f532f3ceb0144da8c04c8c4801d446d25d8d8c5bf9770e61fea0366c03ac7374202bfa86abed86fce519f1a5d986fffd1f5b4489c7158469c82c4eaeeebc37a3d5dd39ccf58d7f0fc7010c494a54b3101b2ddaa979ee74038f761ad1bdb4b0eb2710b98cae88b695237118fa9df7e51f88c1e5b57fe10e49282520907df26c24d43cdde9a5cb8a10f9d945d40b4979454369fc07db2c3cb07c290916652d9b996cce40dc7609de8f1605cf3dbe1b1df0dd461ddf6100c2706d314741d6b347517b46b3bda2367ab040d198652d25e83a775e72b0df38fed5e31eac0924fb127b1752dc61a1de9ae53a4d5fbca5186c8f7196015b79e4496f859c2bc76db65084f68aed39efe8c2273d8cb02f96ff60cccfe40e5ee22e2d69c1c130acf32fbb9b4b592fccbe80f8372b09a42a84a82121caf9635b4db3c0da680885f368c7a28a25476ebf1828ee1702b9a7f9318bfe4bda3ba6740e7fe504d221dacdfea47ab7d890b14eb17b0ba766717babbed89169ecfd6ecd0c57ad83cf784284a689911058b782335c566165cd40b4f5bb2a731a2033a42e59bec3ce18a405f80b8181f750a7b559dab60c2d2deecb007f36e3c606a481523b21a934cfb0fa6e2c025f31024eadba510737d6c2bf373afb4579e7eded48c7142982cbc6a736c350ae9b181e18a9c5b88eed9ef581ca81ecad677e0bad148cbf5a8973b98aeeb66051064e7d3f1bebc5e3f30a5e846990270d871d78017314e9afed87055c1a32046af1ad3d3b0a8fc1d4bf58765571fd7f40e5ff585c59b0db2e024701a25869195f0884fd9a58278235486aca38b3cb5a5bd646b0028caadd52b51595e29bff4d4c2ddf96865213ea52f94128a3f9d0b696233da634dd591f5c96fdea9d22247c9366b9f9c5b2f8018de7883435e5e8a95e6cbc9cd4d0cd42e4373661d005120d95b0c6d826becea993320600c561526af465175e0643f1945668d8e034ddc3f37c1bfe6bedd655503044023f0a8dd7f74f89caa2b97a13d1e85611ac9f0924bd7bf227191201925a43dd93671074a5fcfa3a031faeed81c03406232573a97944d68c2e341563cf1bb6f8b105c702cf0a39d6249ae05676172377ac30e7adf1e6c5da9378f8573098aa5cb71ee03fa601a8e3fbe0b6e6faccb986e411adddd6b8556306ac9303052c1c5a046" + "trace": "81ea3dbd91ac01ef23019b45f470d76dc4c09b19093abe4b0c7186a09fd79a258b5ccf0ba048830b14d8c1dad165eadd3106469b353bb459f08402ebb6158f69356f47c3e689fa2bdde5228c4a98ac9289ffd91bd44c8698998d58d9abcd75ab47e7feda758f15347853d82c9b4814c96012f20bd68dc9b1f2a94419047ac89be4c861c7bd7d5601f48f1da9e86e9486a429c32f8ab24b4c5ed225393d83fd4d01d9a431138acb7d40ac6c0064baeb426cf1a46599e9d49948902a5fd55880bbd103136e2aac03d1a4fa02eb998ea98e221c6125c34df78a371a214e981c07d8311b07b1d883a6fdb544ad297de52dda3fd4189b9f46dd5765a2ba0f712a557cd4428f6edba4afc251c4471b449db32eec0107e18dca0706d2af62009150a3eecca44f93d544f7462a37ac4ccdcab4b186e95502f03d39dacef5dc056eb536200952b689321e87b00fd6869c0dc10891c23c0ee52f4720700c0166e2206776e05b7774d6261df96e43427e187b4a065ca04a52efba19b72e33471409d75b836513f5862d6a38b73046aab0fee2b0a1caba7355d314dc75778f151690627a6a0bd7881c735a9f7c007d002abe49737043332e8e27a57449aab268f257771a05b5d4fe94280d3c3c2fa7a33aa4b248873deba4359aa71886c33ea537f1c2740eb950ecaad1cafdffb768d8e2814ece162bd57b358338794f02b6562618f765079064baa0ca29fedabb504aca99d2a943199c75eb275681c2442542cdc65eb2a4c731e2fe104d50facb741e1578c7d0cf399a9ca66a086e35b172f37045339bb06b0428863c596158a70336f719e1dfcb3c7bb9fa6a10c6a4f57ac724e80fe9e7dd5f719b4ac0b16a7a3d735f2e06af97dccb51032bda7d61ca6cebe9ad85e68399bcb4a6d02e0f3c208ef0f16c1bd54a36a9349c6c233b5e79940b9a8ce0b9808a13911f398c68399aa86610e13f846e76623370fcd8392d839b91ac211b472b55fdf7df3107d06372562ef5e186e1443636ad33e73784fb9b97ff1fc14b9008669c9d07e908ea9099661b71bb8398b969454db66afd024c1ab284014776134462fac9cdba7bd3d129d23607ecfd8c8b1ca343f35c762ce00b58300c62b97467aadfe115bf0bb88f4e728378932bcd3c60f37a108b797b9ff0b751de73974b694b2166a9a825f5fb9cf81fcdec5436df6fd03a2c2970e2d0f9f42fcc9776cde58a07dc460895191f6f388b42270c37093e31a3930018814a4b091cf6d79af8ff9f050e683bdc479b95c5a74480b120299579361ac59fc4025e4801ea10f0a72acf5c9ccc2d3c061b34f5ba2cdc4037a153d39d254845a832d1ec6453bd6d009a7ba09f9fc201031ecf5c4fecd80d81c00da43dc2129eb08b47e5af14f4" } diff --git a/tests/fixtures/games_solitaire/tripeaks.json b/tests/fixtures/games_solitaire/tripeaks.json index 17e0f1298..5499c5fbe 100644 --- a/tests/fixtures/games_solitaire/tripeaks.json +++ b/tests/fixtures/games_solitaire/tripeaks.json @@ -8,7 +8,7 @@ "stat": "0:00", "state": "a209378e", "sub": "", - "table": "8eb97bc3", + "table": "fb7bb6ee", "undoOff": true, "watch": "", "won": false @@ -16,25 +16,25 @@ { "fact": "", "label": "played", - "moves": 17, + "moves": 16, "sheet": "", "stat": "0:01", - "state": "81ba341a", + "state": "d00114ab", "sub": "", - "table": "9016a7c3", + "table": "2434bc7c", "undoOff": false, "watch": "", "won": false }, { - "fact": "", + "fact": "Streak 2", "label": "menu", - "moves": 24, + "moves": 22, "sheet": "TriPeaksPlay a free card onto the waste when it is one rank higher or lower. Kings and aces wrap. A card is free when nothing overlaps it; it turns face up then. Each card in a streak scores 5 times its place in the streak, and a cleared peak adds 30.LookCard backs\u2026Played 1 \u00b7 Won 0New gameClose", "stat": "0:02", - "state": "56a3910b", + "state": "befb403d", "sub": "", - "table": "5fa60d36", + "table": "ecb779e3", "undoOff": false, "watch": "", "won": false @@ -42,12 +42,12 @@ { "fact": "No moves left", "label": "stuck", - "moves": 49, - "sheet": "No moves left2 cards left on the peaks, score 350.Played 1 \u00b7 Won 0 \u00b7 Best score 350UndoNew game", - "stat": "0:05", - "state": "ce336fe5", + "moves": 50, + "sheet": "No moves left1 card left on the peaks, score 320.Played 1 \u00b7 Won 0 \u00b7 Best score 320UndoNew game", + "stat": "0:06", + "state": "caeffbc", "sub": "", - "table": "41ccdf67", + "table": "f17b47ce", "undoOff": false, "watch": "", "won": false @@ -55,12 +55,12 @@ { "fact": "", "label": "stuck, undone", - "moves": 48, + "moves": 49, "sheet": "", - "stat": "0:05", - "state": "bc7077a4", + "stat": "0:06", + "state": "958ee16c", "sub": "", - "table": "7ff77aff", + "table": "3addfbe8", "undoOff": false, "watch": "", "won": false @@ -68,25 +68,25 @@ { "fact": "No moves left", "label": "stuck again", - "moves": 49, - "sheet": "No moves left2 cards left on the peaks, score 350.Played 1 \u00b7 Won 0 \u00b7 Best score 350UndoNew game", + "moves": 50, + "sheet": "No moves left1 card left on the peaks, score 320.Played 1 \u00b7 Won 0 \u00b7 Best score 320UndoNew game", "stat": "0:06", - "state": "ce336fe5", + "state": "caeffbc", "sub": "", - "table": "4d2a284e", + "table": "69c5a144", "undoOff": false, "watch": "", "won": false }, { - "fact": "", + "fact": "Streak 4", "label": "next game", - "moves": 9, + "moves": 7, "sheet": "", - "stat": "0:01", - "state": "9eddc23b", + "stat": "0:00", + "state": "8dc3b94", "sub": "", - "table": "36652208", + "table": "4c9b4d51", "undoOff": false, "watch": "", "won": false @@ -99,7 +99,7 @@ "stat": "0:00", "state": "3f4fa64c", "sub": "", - "table": "8d9d964e", + "table": "b7e59940", "undoOff": true, "watch": "", "won": false @@ -112,7 +112,7 @@ "stat": "0:00", "state": "70b32b0f", "sub": "", - "table": "f22009a", + "table": "4c80bcca", "undoOff": true, "watch": "", "won": true @@ -125,7 +125,7 @@ "stat": "0:00", "state": "70b32b0f", "sub": "", - "table": "f22009a", + "table": "4c80bcca", "undoOff": true, "watch": "", "won": true @@ -134,19 +134,19 @@ "fact": "", "label": "shell new game", "moves": 0, - "sheet": "TriPeaksNew gameSettingsHow to playHistoryStatsAbout this game\u00a9 Zimi", + "sheet": "TriPeaksNew gameSettingsHow to playHistoryStatsAbout this gameZimi \u00b7 Powered by Kiwix", "stat": "0:00", "state": "89683c36", "sub": "", - "table": "c9f9002e", + "table": "bc216f0f", "undoOff": true, "watch": "", "won": false } ], - "events": 83, + "events": 86, "hseed": 47, - "plays": "tap:37>waste tap:51>waste tap:0>waste tap:25>waste stray:20 stock drag:34>waste tap:35>waste tap:23>waste tap:24>waste stock stock tap:6>waste tap:5>waste tap:45>waste tap:46>waste stock stray:17 stock drag:27>waste drag:28>waste tap:16>waste tap:41>waste drag:1>waste stock stock stock drag:42>waste stock stray:22 stock drag:20>waste stock tap:22>waste stock stock stray:18 stray:2 tap:50>waste stock drag:29>waste tap:15>waste stock stock tap:17>waste stray:17 drag:18>waste tap:19>waste stock stock stock stock stray:9 stock stock stock stock tap:15>waste tap:16>waste tap:30>waste stock stock tap:1>waste stock stock stray:25 tap:39>waste", + "plays": "tap:37>waste tap:51>waste tap:0>waste tap:25>waste stray:20 stock drag:34>waste tap:35>waste tap:23>waste tap:24>waste stock stock tap:6>waste tap:5>waste tap:45>waste tap:46>waste stock stray:17 stock stray:19 tap:27>waste drag:41>waste tap:42>waste stock drag:28>waste drag:16>waste stock drag:1>waste stray:22 stock drag:29>waste stock stock tap:20>waste stock stray:18 stray:20 tap:22>waste stock stock drag:17>waste drag:18>waste tap:19>waste stock stray:19 drag:50>waste stock stock stock stock stock stray:30 stray:11 stock stock drag:13>waste stock stock stock stock stock stray:19 stock stock tap:1>waste stray:25 tap:15>waste tap:16>waste drag:17>waste tap:39>waste", "seed": 36, - "trace": "adf82fa0849aa15f3094467f4902fa8f719e1666cf6dab6314280ef3250d2599f658639dc8d4e47b67f93fe4da831d08de112904c0f393bc48928c5fed85e7ecf7fbe7113439b107fcb249f54a3171c3699898189aeeb9955bb8acf100ccfd548c9301531061c94fa856884c5e7cfaa8b3984215b06967cabad7a7f3be16dcadceac16e8e59dc97c48830cf06bae71032fd436f170d059d075d93e518475d216a45856b4fbd2a9ecf342544afa521e8f8c216fd7ed2678341f410a242ed9512df04824a39b6c4595357e18e8305e03e8d841a56e7b3aa5c39b487fedfc9db7f320387d68c13a344e52ff7e5f77572470cf9d84e7fd32f481bde027c3d2e95aacc17eb3208ce5efb1fc66348f7d9ff6fc5589f3b3e9dd60ff965889acd56c32452822e0630d8c63d35347702c651829a85b1bf6d9386a103f596c5e24aefc0adeddbe79c610562d4701d96037" + "trace": "07fa7f6772a920697a30b99b07c7a88f78c6fa2c676560eda5aa1fe2c57ce1afb26087653661bad7d7cbf10b2df3c0396b77f4137e9241bbd7f3a4d894edc9287a0f9332a24ade00b5caa08d29401ceda9ae024ef607a4ca303cb57a5a308f0d2e0d1a27af19dffb1c57ce296075428082ca00452be54d76e4c05e382c2fd4ca0006e1739cf2e91898b7c828c79413ada5d52440afc83154337dce80f246ee1904953ec8b17b9e8719b907c61c5684eff4f75e878dd1b7d762a161970c91e361589618b04691fb94dea83be741ee42cea16eb00717a619fe4af372cf589cbbb37432e1f7c11f14248e8890bac1855bae284adc0e3bd67abcd66ef04ce6450dd2bcd8b22c0686a9f2d9ea6d64b1852552be9fda23025a5ad0870ad94bf121e572037970c5cd7f1c3e0045ac1dcce4e177b0f6f46765c8b44670f631148442ac86877bf099546c3371f8810e227c1c3b0d2a9a78090653a5fd" } diff --git a/tests/fixtures/games_tricks/belote.json b/tests/fixtures/games_tricks/belote.json index 0e7463c81..8075a77b7 100644 --- a/tests/fixtures/games_tricks/belote.json +++ b/tests/fixtures/games_tricks/belote.json @@ -6,7 +6,7 @@ 606, 546 ], - "sheet": "You won!Us: took diamonds and made 111 of 162.Time1:24Won1 of 1CloseNew game", + "sheet": "You won!You win, 606 to 546.Time1:24Won1 of 1Us: took diamonds and made 111 of 162.This hand: Us +111, Them +51. Score 606 to 546.CloseNew game", "size": 568 }, "hands": [ @@ -32,5 +32,5 @@ "hseed": 7, "plays": "1:45 2:47 3:51 0:39 0:24 1:25 2:13 3:37 3:6 0:12 1:33 2:38 2:19 3:7 0:22 1:23 0:0 1:26 2:32 3:11 1:50 2:49 3:48 0:35 0:9 1:34 2:20 3:10 1:36 2:21 3:46 0:8 2:39 3:47 0:46 1:45 2:7 3:10 0:0 1:11 0:20 1:24 2:33 3:23 3:21 0:37 1:13 2:8 3:34 0:35 1:19 2:38 1:49 2:50 3:25 0:6 3:36 0:26 1:12 2:48 0:32 1:9 2:51 3:22 3:0 0:6 1:8 2:12 3:39 0:50 1:49 2:51 3:33 0:38 1:36 2:32 0:21 1:19 2:23 3:13 2:9 3:10 0:7 1:25 1:45 2:48 3:47 0:20 0:26 1:37 2:22 3:34 2:24 3:11 0:35 1:46", "seed": 13, - "trace": "5c4236e26f501ab5273b85731ad2fc9119de429630e27c6cc2ac229310fe5138685ad09b9e529d263023eaa360385ffea75aa0a27f4e6a780f4e42f8606e6bf51556ed839bd1b6dbcd07dcb1d29740e477b5b5a210f884e40ba939716802df6ea6e71641ae744102d7f54e89849b045517fb3fcd56ddeb8749b018988cb907f81ae7b72e0e92de155116b9e13dfbffe0c5d82d7b71529dac23f98c6fc122dc193ab517b86934507330093fdcb418b081b12f0f0d8b81a5b189590ea5918997ff496caaab07d228cb604e74e16f1fd3035072e8c4bb78b9ab088b0a87b84e6cc74f05485fa7c793baddcac2afabe1f861ab871169efd87bb18ce8258bb8d7f783f1d9f4bd684825a03265156553242c5954496fbbd06ba1e66af6f95bb78660d34e53388ee4ef633c6ef0a1bbfd7e47d6ef6d142b9f5f1ab9b817e3f6ec08e02a85580a1abdd3a038de9d3212ab11bf90bb7ef362fe7359de81dc6d7ad3dff142add1b267353d3c6c245cb75019816be7c503f03c15223331475594193c8fd7300f438559ae51f9739bb28b6f9f0ffc90e1e79a42341ca0a3f5965aef12fde6f1f7736695d709421f6a11622448fe013931f29ffdc828c30c33d14560b8878f854a67d9471b6f8d0f08e69e73e20a04de6915502a67b26c81788373f17d4c6cd30937feac073c7cfe40a4d6fb402cf0ac34f53f12a41859b29fdacb7fd1d9b1c2a329b2aa373332b3f3e52c54e284af3d59f6c86abf770452bca4d9b7457431b5dfc4c41e055d3d5ff3d821a834ffd85e2d4f3cc2c769dd118149834bd988ca36f6a0e72d1ca2b82e75f65d16712a07e4475d6f1496d4ff58f2f50ac9357211ecd042c4044517fcbbe22c2cf8899ca9ed9f3d172ac546b919bc8e402d72710bfdc7e9dad7" + "trace": "5c4236e26f501ab5273b85731ad2fc9119de429630e27c6cc2ac229310fe5138685ad09b9e529d263023eaa360385ffea75aa0a27f4e6a780f4e42f8606e6bf51556ed839bd1b6dbcd07dcb1d29740e477b5b5a210f884e40ba939716802df6ea6e71641ae744102d7f54e89849b045517fb3fcd56ddeb8749b018988cb907f81ae7b72e0e92de155116b9e13dfbffe0c5d82d7b71529dac23f98c6fc122dc193ab517b86934507330093fdcb418b081b12f0f0d8b81a5b189590ea5918997ff496caaab07d228cb604e74e16f1fd3035072e8c4bb78b9ab088b0a87b84e6cc74f05485fa7c793baddcac2afabe1f861ab871169efd87bb18ce8258bb8d7f783f1d9f4bd684825a03265156553242c5954496fbbd06ba1e66af6f95bb78660d34e53388ee4ef633c6ef0a1bbfd7e47d6ef6d142b9f5f1ab9b817e3f6ec08e02a85580a1abdd3a038de9d3212ab11bf90bb7ef362fe7359de81dc6d7ad3dff142add1b267353d3c6c245cb75019816be7c503f03c15223331475594193c8fd7300f438559ae51f9739bb28b6f9f0ffc90e1e79a42341ca0a3f5965aef12fde6f1f7736695d709421f6a11622448fe013931f29ffdc828c30c33d14560b8878f854a67d9471b6f8d0f08e69e73e20a04de6915502a67b26c81788373f17d4c6cd30937feac073c7cfe40a4d6fb402cf0ac34f53f12a41859b29fdacb7fd1d9b1c2a329b2aa373332b3f3e52c54e284af3d59f6c86abf770452bca4d9b7457431b5dfc4c41e055d3d5ff3d821a834ffd85e2d4f3cc2c769dd118149834bd988ca36f6a0e72d1ca2b82e75f65d16712a07e4475d6f1496d4ff58f2f50ac9357211ecd042c4044517fcbbe22c2cf8899ca9ed9f3d172ac546b919bc8e402d72710bfdcafb50d2" } diff --git a/tests/fixtures/games_tricks/euchre.json b/tests/fixtures/games_tricks/euchre.json index 9c20121ac..7f7fea11b 100644 --- a/tests/fixtures/games_tricks/euchre.json +++ b/tests/fixtures/games_tricks/euchre.json @@ -6,7 +6,7 @@ 9, 11 ], - "sheet": "You lostUs: called hearts and took 2 of 5.Played1Won0CloseNew game", + "sheet": "You lostThey win, 11 to 9.Played1Won0Us: called hearts and took 2 of 5.Euchred: Them +2Score: Us 9, Them 11CloseNew game", "size": 361 }, "hands": [ @@ -32,5 +32,5 @@ "hseed": 6, "plays": "0:22 1:25 3:13 3:47 0:51 1:39 1:48 3:9 0:21 0:35 1:36 3:11 1:49 3:12 0:8 1:9 2:23 3:8 0:12 2:36 3:21 0:34 1:35 2:22 3:25 0:13 1:26 1:11 2:24 3:0 0:48 3:47 0:39 1:50 2:51 2:21 3:22 0:25 1:38 1:0 2:11 3:9 0:34 0:48 1:23 2:50 3:39 1:8 2:35 3:24 0:49 2:51 3:13 0:37 1:36", "seed": 12, - "trace": "9bfeaab209408a01e7128a72fd3e780b6ee9e59971c2b9d491e574bf9a4a59bc8aa98de921caf69ec73da039d909dd9ce939928f79e3572ad8b1d90e5527af34d13d2263c367ef25d6d8dc691b141eabb1d1a0f8b900416b24cd18132ed37653c0e51db9b689bd998da75c42aa05f56aa1da4e381dc6809674c38dea2474e494e2157900bd522620f89630e9875ed87aff2680170005631e9e3611d2d86923c86f7466bc94b3085aaeda1c499cd888e2f1c09b80f777e3b2eb799ca2191bdc3e20d87295e1b7a10487e87172fcf43b8b884474198cb0fa99404cc314c46c220750aa9602dccb14f32597a5c399311662ee4286fa31cd7fb19ab3ad8087e99cd964dd1964e9662285b14c36196f1cedb9c49f5af236ffc345c6c24d4e1fa5bba49aa569520a60288c3d4578bb04112135f913cac0c8b0366d10828269f034730b391c67bf8e82f910b4de2e3b3a2e342570ed7ae97f12447246ff6158fffbccc5e18cbc1b29ac39b784b59dac6e555d8e20560b3e799182ff11af8c7006d1dd4990e1e21f22a684ee9951d69e" + "trace": "9bfeaab209408a01e7128a72fd3e780b6ee9e59971c2b9d491e574bf9a4a59bc8aa98de921caf69ec73da039d909dd9ce939928f79e3572ad8b1d90e5527af34d13d2263c367ef25d6d8dc691b141eabb1d1a0f8b900416b24cd18132ed37653c0e51db9b689bd998da75c42aa05f56aa1da4e381dc6809674c38dea2474e494e2157900bd522620f89630e9875ed87aff2680170005631e9e3611d2d86923c86f7466bc94b3085aaeda1c499cd888e2f1c09b80f777e3b2eb799ca2191bdc3e20d87295e1b7a10487e87172fcf43b8b884474198cb0fa99404cc314c46c220750aa9602dccb14f32597a5c399311662ee4286fa31cd7fb19ab3ad8087e99cd964dd1964e9662285b14c36196f1cedb9c49f5af236ffc345c6c24d4e1fa5bba49aa569520a60288c3d4578bb04112135f913cac0c8b0366d10828269f034730b391c67bf8e82f910b4de2e3b3a2e342570ed7ae97f12447246ff6158fffbccc5e18cbc1b29ac39b784b59dac6e555d8e20560b3e799182ff11af8c7006d1dd4990e1e21f22a684ee90afe34c" } diff --git a/tests/fixtures/games_tricks/hearts.json b/tests/fixtures/games_tricks/hearts.json index 0a15d25be..137d838d1 100644 --- a/tests/fixtures/games_tricks/hearts.json +++ b/tests/fixtures/games_tricks/hearts.json @@ -3,40 +3,40 @@ "final": { "phase": "over", "scores": [ - 68, + 85, 99, - 116, - 100 + 100, + 99 ], - "sheet": "You won!You: 8 points, total 68Time1:57Won1 of 1CloseNew game", - "size": 394 + "sheet": "You won!You have the lowest score, 85, after 3 hands.Time1:57Won1 of 1You: 25 points, total 85Dara: 0 points, total 99Rani: 1 point, total 100Moss: 0 points, total 99CloseNew game", + "size": 393 }, "hands": [ { "plays": 52, "scores": [ - 25, + 16, 0, - 1, - 0 + 3, + 7 ], - "sheet": "Hand 1You: 25 points, total 25Dara: 0 points, total 0Rani: 1 point, total 1Moss: 0 points, total 0Next hand", - "state": "acc42204" + "sheet": "Hand 1You: 16 points, total 16Dara: 0 points, total 0Rani: 3 points, total 3Moss: 7 points, total 7Next hand", + "state": "a28c7a76" }, { "plays": 104, "scores": [ - 25, - 12, - 15, - 0 + 21, + 6, + 18, + 7 ], - "sheet": "Hand 2You: 0 points, total 25Dara: 12 points, total 12Rani: 14 points, total 15Moss: 0 points, total 0Next hand", - "state": "733507a8" + "sheet": "Hand 2You: 5 points, total 21Dara: 6 points, total 6Rani: 15 points, total 18Moss: 0 points, total 7Next hand", + "state": "beeb1e54" } ], "hseed": 10, - "plays": "0:1 1:2 2:5 3:12 3:40 0:39 1:45 2:49 0:6 1:3 2:9 3:8 2:14 3:16 0:15 1:24 1:42 2:41 3:43 0:51 0:4 1:35 2:11 3:10 2:47 3:46 0:50 1:44 0:37 1:30 2:31 3:36 0:33 1:29 2:28 3:13 0:32 1:21 2:27 3:48 0:0 1:20 2:38 3:7 0:34 1:18 2:25 3:23 0:26 1:17 2:22 3:19 1:1 2:5 3:3 0:0 0:18 1:15 2:17 3:16 0:20 1:23 2:21 3:22 1:40 2:43 3:41 0:42 2:6 3:2 0:24 1:4 2:19 3:14 0:28 1:50 2:9 3:8 0:38 1:11 1:49 2:35 3:48 0:47 1:12 2:10 3:7 0:36 1:51 2:34 3:46 0:37 1:39 2:32 3:45 0:26 1:30 2:13 3:27 0:29 1:33 2:25 3:44 0:31 1:1 2:2 3:4 0:12 0:9 1:39 2:8 3:5 0:13 1:51 2:25 3:22 0:46 1:42 2:44 3:49 3:14 0:21 1:26 2:17 0:6 1:36 2:3 3:11 3:15 0:24 1:35 2:23 0:29 1:27 2:32 3:30 2:16 3:18 0:20 1:34 0:38 1:31 2:33 3:37 0:43 1:41 2:50 3:47 2:7 3:28 0:0 1:48 0:45 1:40 2:10 3:19", + "plays": "0:1 1:3 2:5 3:12 3:40 0:50 1:45 2:49 0:51 1:44 2:47 3:48 0:39 1:42 2:41 3:46 0:2 1:35 2:9 3:8 2:14 3:16 0:32 1:15 3:43 0:34 1:30 2:38 3:19 0:33 1:18 2:22 2:11 3:10 0:6 1:29 2:25 3:23 0:0 1:24 2:27 3:36 0:37 1:21 0:4 1:20 2:31 3:7 3:13 0:26 1:17 2:28 1:1 2:5 3:3 0:18 2:43 3:41 0:42 1:40 2:17 3:16 0:20 1:15 0:24 1:23 2:21 3:22 0:44 1:49 2:35 3:48 1:4 2:6 3:2 0:38 2:19 3:14 0:31 1:50 2:9 3:8 0:29 1:11 1:12 2:10 3:7 0:37 1:51 2:34 3:46 0:47 1:39 2:32 3:45 0:28 1:30 2:13 3:27 0:36 0:26 1:33 2:25 3:0 1:1 2:2 3:4 0:6 0:24 1:39 2:23 3:22 0:45 1:42 2:44 3:49 3:14 0:21 1:51 2:20 0:9 1:26 2:8 3:5 0:50 1:48 2:46 3:47 0:32 1:31 2:29 3:30 0:13 1:36 2:25 3:19 0:38 1:35 2:33 3:37 0:16 1:34 2:17 3:15 2:3 3:11 0:12 1:27 0:0 1:41 2:10 3:28 0:43 1:40 2:7 3:18", "seed": 16, - "trace": "fc5daf9436931868307ae9af864e1de81f4581082a0acb63dcd1e6d6fba56f57634bf8942c1e2caf78f1f14d96772670e88eb9078eef476c66800e0d90ce4cdd71d7df99c8be651b84dc5c43dcf9f14179ec052f8eac8abfabfcc0322d5269f0cbefd1aaeeafc6421e39d5fe574ed463f0a6efee9fa0fcb60f8cd591144d0a47bad5442745740537f7ccd14063202cafd10b83df3af3b35a37d63ce124349428536ba115231365a58088caeb584c0a9f4c1e7b27254e8f5202671e9f01255e6caa9cf3fcb5c89be398dd75650c7da70cd0f4d62124abd1a2f371d3c8074ea8e3185d56037bef2fc06f058433201a137eeae7dfde20456ccd6cbb9a438be15f21eaea548d2a3df38f31cc0673516fc6719950ffd8bb4b8ec482a220e81bdf397ac78d8f67a95a2a286d070c938b46c86eb74a511522e9955659767324d956616edc8f6718a40ff82fa62c78780098a8b633d0dce1985bfc371854f46b950638586934b3c6931a80a51dcaca22bd1d27d0b8faa49b7317c93c7da3d07f17e5f5bd42739c3df03dfd82a7125f064fd89c43d401839210b6b48da392c0ea617fed425cec75536a5cc11835f523b0a1bd34de8f02d04488f518f434debe18cfc6b122b217b8fe4eb7a3911698bf90e3f6044f331f3facf1503f33387c84a80618c21d3b944b12f7629507f267f47df460ab505f485fbbd1787a456e3f6b85868c2f2a4e785fc1b161859802ba7e8613af028aeba7eac3ebcbd84a37aed95d8bd0b7ae5e87381c69e9726ba3bd1261656560955d648a0163e89aa8e66ed98cf8de599a27616b8578b7810e5b3a9c2ae58e5cf9e766701b86fa91c4359267dc2178c232b0f1d23b64e44dff52da1eb24f427f563eaa775e3cb78970f31b152d73d232c631b6929c3318c1f4fc463c1c53a3361eb62656d2fefd6b8a34142288ce9d9f0db984d3abe58b83e6112f82759ef4662486bad957012f899c4577e8120b409f05b48a24058c4505ce8080dd9714077328587fd6b8c2be383e83db89865498b632139bbbf804aa6fa1f395ea0e47820ad9ecea802f2ed4079ec8b903d198dc86e125e3cfc775163b523438e238bc303939ae1c0f03a19a706f2c03d3dd577ec5e34380fffb9d73a4492c14ecf51b0dc7f7c0ac1d305571ab513adab3a40c62e65a5dc4969f5ad6d0663d4d52d06f442fff6834f749bfc8edaab44b0089511fc7a5a8afd2f79393cd74abc6940bde4e8f18d63ef61cc374bb717ebbb00ae2df687ae6b90668d3d1f4cd6d84c3ea53a0eccb971e0424e381eb31b04b2edc2be442c81014c2624aee6f4a8144ab2a5962b17f27a77ec4ca661d637d172922f6d313030c81febaf79cb382d5bf289321e7269f73e4d90d8e7695ad268f3dc6e11382d1c9a7fc9e840fa52fd8f4f92b" + "trace": "fc5daf9436931868307ae9af864e1de8a0d3862c9e1e367b444ca3a09f3d868ce0ca52e99beea4f1058730d90501ceb5d676a95ff835b8c6e8a1259776876bf2a35e5c58c1d2ec2c8db518c3ffc258b98bace80227ea838b9bdc426b238c8eb9a214273031ad25722995139c9a941a66281d07393ac235fe0bacde7c51190d807e1116fa8e4ead25527470154b3363c8f89452849ed327ba1c6ca94dcd8ae56b523525be3b3f3177cf358a80597690661e8a298c90b45478ce58510f6c929744bcc152bb592982af17be916d12d470db67397f2c6f7647d019c020ff5dd65a00fd1adec378f2d74635362402edb7d34595fd61270cbe6097d89b54f15d22bd27bc418d06cf3dc6545dda46e31638ca7072b156fed2e06aadb22e113a9a5ac7090d8c7c3aa3eb28706bb0180a2d07aa5caa2ffd0462cb3509ce948638c5f6daaca739fc9fceff2410c967e9d720b390d7aec1873e813c7326ce8bc810f949058d06b3472e7e3ec5f779ab0531b4d04ca6b451d6b90959bac328ab4f0c42fe85d908c084946b8503a4cdab1bd975578a43fa15a7d3d003380e0d5392fd3735ad5e2b59ff092450ce78044a605fa79e7547d6df845988d2e5b53b69bbf1603764e1a76894a7bcd45fdd1717a3a3d2dc3b2fb455f6584c73cb36737e79f164aa230aaec2b99d13a5de6ed5b8c9fcb716f49da662dbae59f995eded4d2938fac84b843be26b3a4e205b9f2bd0428f2cd9ca76ffd2989b556391c689e4ab6214320312ce5f7572632754b5c224315bfca090337b9556af084bbe2c51dfe9f055a568e781323ba6765bc32df0e6cbb113b0e0fdb1394f4e0bd75f7dab9c89dc2b1bf6d9846d8ef4cd369509e2ff5d7ffb666d0edad53f1660840dfc5d9f5016ba9aab3e6bf52de84f0663a218e617b4a5d3a3e263b0301fbb9ee163b986d179c2b32c44ffa5f55085c47db7bb65e1408b3c56faaa2814354be18e368c660e3669b892bf1934a8e05d35e25903031fa63eb8f2b582770db3a78288d05f623edbcdd9c41a635267ef999ad1e6d73fb8ee75e9525f4b69bf678b1ed0e1816760be668b01958909b9f4b0b65290b05e5465536cb6f21179906d88852aa2008d01759ada1df60ec2ff91269fff3a134c2e852c6d80b63b2be51e669e5f1af1c7dc1a5fd06e218ceea364f784488d41ed228f1a9a160b922dc16fde81c7944e3d2d43042e841bf0b9a11f40b4d78e3bf4a22dcc3e3de583bad2e79eff6157a42aad8a1f885b79a4c75b1371fcd04ddf1abe0123eb49c6858fa3731444e0f8ea099aeeb5686ad6a1bcb07d7bd7490629b09027675598aec843ec63bc0be7ad6ac6c4793a0bc3b5a3fe7314d2ecaa78a48ab4f68db6f4c1f1c708c2c39dffda6f19a86eb45bd666785e9f2d9d25ff60c3bb28c0" } diff --git a/tests/fixtures/games_tricks/hearts_hotseat.json b/tests/fixtures/games_tricks/hearts_hotseat.json index 2f64b9d71..d57a2244f 100644 --- a/tests/fixtures/games_tricks/hearts_hotseat.json +++ b/tests/fixtures/games_tricks/hearts_hotseat.json @@ -20,9 +20,9 @@ }, { "chips": "Bo0Rani0Moss0Ava0", - "cover": "Pass toAvaPass the device. Your cards stay hidden until you tap.I'm Ava, show my cards", + "cover": "", "label": "pass picked", - "moves": 3, + "moves": 2, "phase": "play", "scores": [ 0, @@ -31,8 +31,8 @@ 0 ], "sheet": "", - "state": "45bf90fd", - "status": "Hearts not broken \u00b7 Ava, your turn", + "state": "1981e4dc", + "status": "Hearts not broken \u00b7 Moss is thinking", "watch": "", "watchCtl": "" }, diff --git a/tests/fixtures/games_tricks/hearts_watch.json b/tests/fixtures/games_tricks/hearts_watch.json index 0e44d4b8f..664776948 100644 --- a/tests/fixtures/games_tricks/hearts_watch.json +++ b/tests/fixtures/games_tricks/hearts_watch.json @@ -131,5 +131,5 @@ "hseed": 12, "plays": "2:1 3:3 0:4 1:2 0:41 1:42 2:40 3:51 3:15 0:22 1:21 2:19 0:44 1:46 2:43 3:26 1:16 2:14 3:20 0:13 0:45 1:49 2:48 3:38 1:5 2:0 3:10 0:7 2:17 3:33 0:24 1:23 0:29 1:36 2:34 3:32 1:18 2:39 3:31 0:37 1:11 2:30 3:9 0:12 0:47 1:50 2:28 3:8 1:25 2:27 3:6 0:35", "seed": 18, - "trace": "a5b5b6efdd777590111d4a1adf4f0270131ac53b4bb057215a7195ffc392a3ddecf7070fdf478902041e7bab66719a9a0ba2fd8b19812d29375567bdc45dc497bdbed69301f57cb32b8eedc55bcdc876d6f488da72c656670b9ef5f78d8aed21981d280d946a8742a4ef8f5fd3b590d25b722fe599f910d6372b5402c03098a92a94ab0cb1f136e8c8232b4d2a35afc947a95758ccc66e49981d1450b289fb9b92920ab7af0c61c57d8e5b1b6492950ab813be41d95cd379a34694e00989a0c73082dc56be430fbb2f2ff8312cb8d8b77a443e8327dc87c82ed8d0274cfe846b62a4a408cbda6999b2fa24780f8082bd99149f9d48a8decb14fb5f618846131553b66ce8ba38e2e57a663b825722a98c4c6280a110fa7c3cb7ba10bf6fba66271ebaeb5631a24719db5d7aa5aa5e79efc5d1f69d4a03167af2e8f3a3" + "trace": "a5b5b6efcfdfd5119f88c2e945742a91a7b16c0846995acaeaad114654bb4b54e8179f40e2237a5fe2799fc25290d62d8b7e6848e8b75d528fa315f6638f49da64bf820c75bb20cc9b91af9ccc0c988d6d695b0dc7b058acfe8986346b1dd8a04893e498f58eca6571d229ea5727dc9312300a9a4cc168d9426d941145ec1f7cc7121f1d36648ce729472fe2548a8254e1ef8cdde403e758d8aadcc1fd67daa6731f72b6454b8e0edcecaa18b55d74650f5e4e462f99eeb239f9b1215b3244627ca688df6b2d9d4c9ad0d638a9b42a50f056b0064c7f10cbd7458930833abb90681fcc6fe73e1c3addbd84271ddbc6ac5a27cc16c839e70ee37cf448bdaaf64889965ca7c31e29b20b4a3d55eb036e91c66f14ea222724c9351de21acca45480170b93dd0ad66c224af92e9096dc155cff8ba6861ce237fb11eb119c" } diff --git a/tests/fixtures/games_tricks/skat.json b/tests/fixtures/games_tricks/skat.json index 52c056fd9..bdb44b0d7 100644 --- a/tests/fixtures/games_tricks/skat.json +++ b/tests/fixtures/games_tricks/skat.json @@ -7,7 +7,7 @@ 270, 0 ], - "sheet": "You lostDara played clubs, without 1. Card points: 76.Played1Won0CloseNew game", + "sheet": "You lostDara wins the series with 270.Played1Won0Dara played clubs, without 1. Card points: 76.Game value 24, bid 22.Dara won: +74.Totals: You 0, Dara 270, Rani 0.CloseNew game", "size": 714 }, "hands": [ @@ -35,5 +35,5 @@ "hseed": 8, "plays": "1:49 2:10 0:6 2:26 0:32 1:33 2:19 0:20 1:22 1:13 2:24 0:25 1:39 2:47 0:45 1:23 2:8 0:9 1:36 2:34 0:50 1:7 2:11 0:0 0:37 1:35 2:38 1:48 2:51 0:12 2:39 0:46 1:47 2:26 0:35 1:34 2:19 0:24 1:25 1:10 2:7 0:11 1:36 2:49 0:0 2:45 0:13 1:50 1:23 2:8 0:22 1:6 2:12 0:37 2:32 0:38 1:9 1:48 2:51 0:33 0:12 1:9 2:36 2:26 0:37 1:32 2:20 0:24 1:22 1:49 2:10 0:7 2:46 0:50 1:39 1:23 2:6 0:38 1:13 2:25 0:19 1:11 2:8 0:33 1:0 2:51 0:35 1:45 2:48 0:34", "seed": 14, - "trace": "1f1aa64c8425f6bd0ab312285f555e20c931414b0a8659c7885405d7078f49b8718f0f78d4148324749a7a109ffd547819324696a56cbcc229327fa96a87ff4c80afe23848ec721fd07cb8ae3ea993f5b07adf4c6867e6847fcc099ccc07daaae22e2a92af25abc249fd61bde510cdfa493cdf29e43d75b8ec31494ef3a1128127cfde572f05386b032375a9d4ae7588ac0ae2dd2d66de12a91f542d2b40d624acc670fd93277b755c9ad5f088a26a89bf48f2c62bab0a8cb5d14182970ede82d36f82ecb03bdc416165355b578902629a390f821383aeb9a19d43c48c48f8298ebd4101f6f4069651a861900757cdc3cd985c1d3c3099ddd7be1ebe83561ef1987f0ea7145c6388bbee0c9c323f66be256e94c2214209fce81afa0a34666175ef69ec0e255c49b7c757be0c8678b1103878a056264089bba48b30c5aa9def4ce8c33f77aa2de756f8cb788e181ffb504a7327566b496c2e68198d31e7a4133eeca9cc3f569c238c8b3cb2ee5a5d019bf434dcd983e6f53172971609eecdc8c38d9053415e7f21f026dd27676933cc316251b321cf12c346453203712aa53a1dcfd85e137b49fbca803c43fed433d93fb9153dcac966f389a9e45ed868d14c360b8abdb5b3adfaceed461f606f3a682fb16442536ae08c9242f56920b7030a67b6dd813f018597d4f6e9b707a1895ccb4398b4bf6775840bc5e3f0c924488b4821965474f99a9d2896ed843ecdb5852045a06fbd96d47edae2904e17288cfdea464bea2fc948358ac3d890951a09f6af12bfddeed0adbe6d17a4b489effc541b73bb46e51946bca1a737d96b5aef9084f566b5ece8fe44868a49498fa607ac4c43a571c639b1ae2b4c95127d0dbffacacb4e1ff1a192350be0c860075e743928cea86efe40575b769982f3d0e7052b2c4b06c69c40756b9a91634922e5b33c02d07193b9e5de23f21d01e24813bd7a1c1c2746acf5a03d4d4a62aa0c" + "trace": "1f1aa64c8425f6bd0ab312285f555e20c931414b0a8659c7885405d7078f49b8718f0f78d4148324749a7a109ffd547819324696a56cbcc229327fa96a87ff4c80afe23848ec721fd07cb8ae3ea993f5b07adf4c6867e6847fcc099ccc07daaae22e2a92af25abc249fd61bde510cdfa493cdf29e43d75b8ec31494ef3a1128127cfde572f05386b032375a9d4ae7588ac0ae2dd2d66de12a91f542d2b40d624acc670fd93277b755c9ad5f088a26a89bf48f2c62bab0a8cb5d14182970ede82d36f82ecb03bdc416165355b578902629a390f821383aeb9a19d43c48c48f8298ebd4101f6f4069651a861900757cdc3cd985c1d3c3099ddd7be1ebe83561ef1987f0ea7145c6388bbee0c9c323f66be256e94c2214209fce81afa0a34666175ef69ec0e255c49b7c757be0c8678b1103878a056264089bba48b30c5aa9def4ce8c33f77aa2de756f8cb788e181ffb504a7327566b496c2e68198d31e7a4133eeca9cc3f569c238c8b3cb2ee5a5d019bf434dcd983e6f53172971609eecdc8c38d9053415e7f21f026dd27676933cc316251b321cf12c346453203712aa53a1dcfd85e137b49fbca803c43fed433d93fb9153dcac966f389a9e45ed868d14c360b8abdb5b3adfaceed461f606f3a682fb16442536ae08c9242f56920b7030a67b6dd813f018597d4f6e9b707a1895ccb4398b4bf6775840bc5e3f0c924488b4821965474f99a9d2896ed843ecdb5852045a06fbd96d47edae2904e17288cfdea464bea2fc948358ac3d890951a09f6af12bfddeed0adbe6d17a4b489effc541b73bb46e51946bca1a737d96b5aef9084f566b5ece8fe44868a49498fa607ac4c43a571c639b1ae2b4c95127d0dbffacacb4e1ff1a192350be0c860075e743928cea86efe40575b769982f3d0e7052b2c4b06c69c40756b9a91634922e5b33c02d07193b9e5de23f21d01e24813bd7a1c1c2746acf5a03d4dbf032be9" } diff --git a/tests/fixtures/games_tricks/spades.json b/tests/fixtures/games_tricks/spades.json index d9987cf3e..de30295a0 100644 --- a/tests/fixtures/games_tricks/spades.json +++ b/tests/fixtures/games_tricks/spades.json @@ -6,7 +6,7 @@ -200, -18 ], - "sheet": "You lostUs: bid 10, took 8Played1Won0CloseNew game", + "sheet": "You lostThey win, -18 to -200.Played1Won0Us: bid 10, took 8-100, total -200, bags 0Them: bid 3, took 5+32, total -18, bags 2CloseNew game", "size": 547 }, "hands": [ @@ -23,5 +23,5 @@ "hseed": 5, "plays": "3:26 0:37 1:29 2:43 2:13 3:16 0:15 1:14 2:17 3:19 0:24 1:21 0:4 1:7 2:9 3:3 2:18 3:20 0:49 1:50 1:38 2:45 3:27 0:35 2:22 3:23 0:47 1:1 0:33 1:36 2:46 3:28 2:5 3:40 0:8 1:2 3:25 0:32 1:31 2:39 2:6 3:51 0:0 1:41 3:34 0:48 1:42 2:11 0:10 1:44 2:12 3:30 0:18 1:22 2:25 3:15 2:28 3:29 0:26 1:31 0:17 1:23 2:43 3:16 2:36 3:38 0:37 1:35 3:2 0:8 1:9 2:10 2:3 3:4 0:7 1:0 1:14 2:44 3:19 0:24 2:12 3:45 0:33 1:1 3:30 0:27 1:6 2:46 2:11 3:32 0:41 1:42 1:40 2:49 3:48 0:39 0:13 1:47 2:51 3:20 2:5 3:21 0:34 1:50", "seed": 11, - "trace": "dd5a221dbc39acb06cfab3dd9460284b7e05e61e5e998f2ab80d3dbc6d51949db7cb67d1da60f7c71e42f975f14f2cd8e52f1bd80144b4f6d9a6f9a20232241ec849e518a0048f1a6114460076c4edfcb20de9a32345b9cda53f40c36c23d497fea7c8388ec66fe1cd3563a473f380a187ce0b803763fb3463b37d2d46d33c34acd3da2225379cfd33bb2d1df7430102255d2b352cd52513c75511732f90ee26b41e9c2128f3aca81d2fdf0fbc83723efe0ce66fddbdbfe2fd622add0fafe4744be57f1a549d28ff379db1237cd5e02fa6af1b68cef25cc28058cb273a1a6488e9a41118274bdca337f5c52acf518e7aebcc35148a53da21dd4811a2f208a5b58f59f9c6e14c87f3ce202e26b1de7cc1b42ed4a07cb24dec694db8c7281f6e467cb5cb0b7bdd770cf8e10efbd9724d5cd6c89d6809bf45e20971d461b85d4cfe2a4e53e8199e820d8cd083227fe834353be062c788d1b30e03ef581b974f7dbe2811a11b6f35fbcf385a6016b225d7e0e37b8b99cffeca971bce5e59e20b7a2cc96792a3572fbbaecc05c4d40aac2f7e1b89c0eab0f023212f55e041f65d2085c1c403d7b30f31921ec5583acdce5a0c81227a3060e260afe4daae24e3fce96d77f5e697154f9d670d154bd14cc1ed0b169444157bb2181d9845e5f5fce2cd46e2751537fbe20ead17baf11f979444f8c5402fd28622d542ceb69417dd826cd4c06fcaedbcf2508b99c9a95dab276de954b481cfb2cac6a63f0ffc2f016c818017e14368877789664a22327bc65bbc588252abbaf8b3d3557356efac87ffa75f333c93e696c1959337c36a690036b47edd2332c556ef13f982c364410a93285b6c5c80754ec4bce842200de740b5da96ffae6afa6d61e2815e333a2caec007dd0d419709dc6e2141dbb18e8f4fdfbcaacf966c9941d971eedafd4eaf" + "trace": "dd5a221dbc39acb06cfab3dd9460284b7e05e61e5e998f2ab80d3dbc6d51949db7cb67d1da60f7c71e42f975f14f2cd8e52f1bd80144b4f6d9a6f9a20232241ec849e518a0048f1a6114460076c4edfcb20de9a32345b9cda53f40c36c23d497fea7c8388ec66fe1cd3563a473f380a187ce0b803763fb3463b37d2d46d33c34acd3da2225379cfd33bb2d1df7430102255d2b352cd52513c75511732f90ee26b41e9c2128f3aca81d2fdf0fbc83723efe0ce66fddbdbfe2fd622add0fafe4744be57f1a549d28ff379db1237cd5e02fa6af1b68cef25cc28058cb273a1a6488e9a41118274bdca337f5c52acf518e7aebcc35148a53da21dd4811a2f208a5b58f59f9c6e14c87f3ce202e26b1de7cc1b42ed4a07cb24dec694db8c7281f6e467cb5cb0b7bdd770cf8e10efbd9724d5cd6c89d6809bf45e20971d461b85d4cfe2a4e53e8199e820d8cd083227fe834353be062c788d1b30e03ef581b974f7dbe2811a11b6f35fbcf385a6016b225d7e0e37b8b99cffeca971bce5e59e20b7a2cc96792a3572fbbaecc05c4d40aac2f7e1b89c0eab0f023212f55e041f65d2085c1c403d7b30f31921ec5583acdce5a0c81227a3060e260afe4daae24e3fce96d77f5e697154f9d670d154bd14cc1ed0b169444157bb2181d9845e5f5fce2cd46e2751537fbe20ead17baf11f979444f8c5402fd28622d542ceb69417dd826cd4c06fcaedbcf2508b99c9a95dab276de954b481cfb2cac6a63f0ffc2f016c818017e14368877789664a22327bc65bbc588252abbaf8b3d3557356efac87ffa75f333c93e696c1959337c36a690036b47edd2332c556ef13f982c364410a93285b6c5c80754ec4bce842200de740b5da96ffae6afa6d61e2815e333a2caec007dd0d419709dc6e2141dbb18e8f4fdfbcaacf966c9941d971eecbc976f8" } diff --git a/tests/test_bake_cards_gate.py b/tests/test_bake_cards_gate.py new file mode 100644 index 000000000..53f2bd062 --- /dev/null +++ b/tests/test_bake_cards_gate.py @@ -0,0 +1,104 @@ +"""Bake gate: every card game on the built shelf at 390x844: opens, deals, takes one tap, nothing overflows the table, no page error, +every card fully on screen. Contact sheet of the 13 new games to CARDS_SHOT_DIR/new13.png; problems are listed, not asserted away. +""" + +import json +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from test_games_daily_browser import browser, site # noqa: F401,E402 +from test_games_persist_browser import GAMES # noqa: E402 + +ROWS = json.load(open(os.path.join(GAMES, "games.json"), encoding="utf-8")) +CARD_GAMES = [r["path"] for r in ROWS if r.get("kind") == "cards" and r["path"] != "courtier.html"] # Courtier opens on its own Start sheet (no cards until Start) +NEW = [r["path"] for r in ROWS if r.get("kind") == "cards" and r.get("added") == "1.16"] +SHOTS = os.environ.get("CARDS_SHOT_DIR", "/tmp/bake-cards") +MEASURE = """() => { const t = document.querySelector('.zc-table'); if (!t) return { table: false }; + const tr = t.getBoundingClientRect(), vh = window.innerHeight, vw = window.innerWidth; + const cards = [...document.querySelectorAll('.zc-card')].filter(c => { const r = c.getBoundingClientRect(); return r.width > 4 && r.height > 4 && getComputedStyle(c).display !== 'none' && getComputedStyle(c).visibility !== 'hidden'; }); + const out = cards.filter(c => { const r = c.getBoundingClientRect(); return r.left < tr.left - 1.5 || r.right > tr.right + 1.5 || r.bottom > Math.min(tr.bottom, vh) + 1.5 || r.top < tr.top - 1.5; }).map(c => { const r = c.getBoundingClientRect(); return [Math.round(r.left), Math.round(r.top), Math.round(r.right), Math.round(r.bottom)]; }); + return { table: true, n: cards.length, outside: out.slice(0, 4), outsideCount: out.length, vw: vw, vh: vh, tr: [Math.round(tr.left), Math.round(tr.top), Math.round(tr.right), Math.round(tr.bottom)] }; }""" +PROBLEMS = [] + + +@pytest.mark.parametrize("path", CARD_GAMES) +def test_a_card_game_deals_and_fits_the_phone(site, browser, path): + os.makedirs(SHOTS, exist_ok=True) + ctx = browser.new_context( + viewport={"width": 390, "height": 844}, + device_scale_factor=2, + has_touch=True, + is_mobile=True, + ) + page = ctx.new_page() + errs = [] + page.on("pageerror", lambda e: errs.append(str(e)[:160])) + page.goto(site + path) + page.wait_for_timeout(2500) + m = page.evaluate(MEASURE) + if not m.get("table") or not m.get("n"): + # a sheet or a bet may be waiting: press the first enabled button that says deal / start / bet / play, a few times + for _ in range(3): + clicked = page.evaluate("""() => { const b = [...document.querySelectorAll('button')].find(x => !x.disabled && x.getBoundingClientRect().width > 0 && /deal|start|bet|play|ok|new game|let/i.test(x.innerText || x.getAttribute('aria-label') || '')); if (b) { b.click(); return (b.innerText || '').trim().slice(0, 20); } return null; }""") + page.wait_for_timeout(1500) + m = page.evaluate(MEASURE) + if m.get("n") or not clicked: + break + # one tap where one can land: the topmost face-up card + page.evaluate( + """() => { const c = [...document.querySelectorAll('.zc-card:not(.zc-down)')].filter(e => e.getBoundingClientRect().width > 4).pop(); if (c) { const r = c.getBoundingClientRect(); c.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: r.left + r.width / 2, clientY: r.top + r.height / 2, pointerId: 1 })); c.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, clientX: r.left + r.width / 2, clientY: r.top + r.height / 2, pointerId: 1 })); c.click(); } }""" + ) + page.wait_for_timeout(800) + m2 = page.evaluate(MEASURE) + if path in NEW: + page.screenshot( + path=os.path.join(SHOTS, "g-%s.png" % path.replace(".html", "")) + ) + ctx.close() + issues = [] + if errs: + issues.append("page errors: %s" % errs[:2]) + if not m.get("table") or not m.get("n"): + issues.append("no cards on the table after load (n=%s)" % m.get("n")) + for tag, mm in (("dealt", m), ("after a tap", m2)): + if mm.get("outsideCount"): + issues.append( + "%s: %d card(s) outside the table/screen e.g. %s (table %s, viewport %sx%s)" + % ( + tag, + mm["outsideCount"], + mm["outside"][:2], + mm["tr"], + mm["vw"], + mm["vh"], + ) + ) + if issues: + PROBLEMS.append((path, issues)) + assert not [ + i for i in issues if i.startswith("page errors") or i.startswith("no cards") + ], "%s: %s" % (path, issues) + + +def test_zz_contact_sheet_of_the_new_games_and_the_layout_problems(): + from PIL import Image + + shots = [os.path.join(SHOTS, "g-%s.png" % p.replace(".html", "")) for p in NEW] + shots = [s for s in shots if os.path.exists(s)] + if shots: + ims = [Image.open(s).convert("RGB") for s in shots] + w, h = ims[0].size + sc = 0.32 + tw, th = int(w * sc), int(h * sc) + cols = 7 + rows = (len(ims) + cols - 1) // cols + sheet = Image.new("RGB", (cols * tw, rows * th), (30, 30, 30)) + for i, im in enumerate(ims): + sheet.paste(im.resize((tw, th)), ((i % cols) * tw, (i // cols) * th)) + sheet.save(os.path.join(SHOTS, "new13.png")) + with open(os.path.join(SHOTS, "problems.json"), "w", encoding="utf-8") as f: + json.dump(PROBLEMS, f, indent=1) + print("\nLAYOUT PROBLEMS:", json.dumps(PROBLEMS)) diff --git a/tests/test_games_canasta_browser.py b/tests/test_games_canasta_browser.py index a0d4d3d8c..08a223199 100644 --- a/tests/test_games_canasta_browser.py +++ b/tests/test_games_canasta_browser.py @@ -42,7 +42,7 @@ def deal_with_a_weak_and_a_strong_group(browser, served): page.wait_for_function("window.ZimiCanasta && ZimiCanasta.session && ZimiCanasta.session.state") page.locator(".cn-btn").nth(0).click() # Draw 2 page.wait_for_function("ZimiCanasta.session.state.step === 'play'") - page.wait_for_timeout(900) # the two cards finish flying into the hand + page.wait_for_function("!document.querySelector('.zc-dealing')") # the cards finish flying into the hand (the deal's span is up to 1.15 s) groups = page.evaluate(GROUPS) weak = [g for g in groups if g["pts"] < 50] if weak and len(groups) >= 2 and sum(g["pts"] for g in groups) >= 50: @@ -96,7 +96,7 @@ def _overlap(a, b): def test_eleven_melds_a_side_overlap_nothing(served, browser): - for w, h in ((390, 844), (375, 667), (1280, 800)): + for w, h in ((390, 844), (375, 667), (560, 800), (600, 900), (640, 1000), (640, 700), (560, 375), (600, 400), (640, 360), (1280, 800)): ctx = browser.new_context(viewport={"width": w, "height": h}, has_touch=True) page = ctx.new_page() errors = [] diff --git a/tests/test_games_cards.cjs b/tests/test_games_cards.cjs index 4d55253e3..52f8eaddd 100644 --- a/tests/test_games_cards.cjs +++ b/tests/test_games_cards.cjs @@ -233,7 +233,13 @@ check(K.timeBonus(10) === 0 && K.timeBonus(100) === 7000 && K.timeBonus(700) === // ── Faces, backs, the Moon ────────────────────────────────────────────────── check(deck.every(c => /^$/.test(Z.faceMarkup(c, false)) && !/NaN|undefined/.test(Z.faceMarkup(c, true))), 'all 52 faces draw, as page markup and as standalone images'); -check(Z.faceMarkup(id('7H'), false).split(' 0.5).length === 52 && new Set(Z.shuffled(Math.random)).si // ── The court cards: public-domain art (courts.js), recoloured to the card palette ── { - const palette = new Set(['#b3261e', '#1b1b1b', '#e09400', '#1d3b7a', '#2f5ca8', '#fdfcf8', 'none']); + const palette = new Set(['#b3261e', '#1b1b1b', '#e09400', '#1d3b7a', '#2f5ca8', '#fdfcf8', '#f9f6ee', '#cdc6b6', 'none']); // the art's own palette, and the card's paper and edge const courtIds = []; for (let su = 0; su < 4; su++) for (const r of [11, 12, 13]) courtIds.push(su * 13 + r - 1); - const faces = courtIds.map(c => Z.faceMarkup(c, false)); - check(faces.every(f => f.includes('viewBox="0 0 1300 2000"') && f.includes('zc-small')), 'all twelve French courts carry the courts.js art and a small-card figure'); - check(new Set(faces).size === 12, 'the twelve French courts are twelve different drawings'); - const colours = new Set(); - faces.forEach(f => (f.match(/(?:fill|stroke)="(#[0-9a-fA-F]{3,6}|none)"/g) || []).forEach(m => colours.add(m.split('"')[1].toLowerCase()))); - check([...colours].every(c => palette.has(c)), 'the courts use only the card palette (' + [...colours].join(' ') + ')'); + // The page draws a court's figure from the sprite (one symbol per court); the cascade's standalone image carries it inline. The + // palette is checked on the standalone drawings, where the colours are. + const faces = courtIds.map(c => Z.faceMarkup(c, true)); + check(courtIds.every(c => / //.test(f)), 'and carry it inline as a standalone image: the figure crown to waist filling the card under the index, 2.5 units from the sides and bottom'); + check(courtIds.every(c => (Z.faceMarkup(c, false).match(/class="zc-ct /g) || []).length === 2), 'a court on the page has a frame for each index arrangement'); + // A covered face-up card in a fan shows its index row only, whatever its rank (a court's frame top is at 40 of 140): one step, cut to indexStep. + const ch = 70, units = st => st / ch * 140; + check(Math.abs(units(Z.indexStep(ch)) - 39.5) < 1e-9 && Math.abs(Z.FAN_UP_SHARE * ch - Z.indexStep(ch)) < 1e-9, 'a fanned covered card shows its index row only, whatever its rank'); const bytes = fs.statSync(path.join(dir, 'courts.js')).size; check(bytes < 200 * 1024, 'courts.js stays under 200 KB (' + Math.round(bytes / 1024) + ' KB)'); const ace = Z.faceMarkup(id('AS'), false); - check(!ace.includes('viewBox="0 0 1300 2000"'), 'the Ace of Spades keeps its own drawing'); + check(!ace.includes('zc-ct'), 'the Ace of Spades keeps its own drawing'); } -// A fanned column on a phone with room to spare shows each face-up card's whole index and its whole top row of pips: -// a step of 0.28 of a card cut the pips through the middle into triangles beside the index. +// A fanned column on a phone with room to spare shows each face-up card's index and clean paper down to the body's suit (no pip +// grid any more): the step opens to FAN_UP_SHARE, the index row (39.5 of 140 units), a court's frame top at 40. { const phone = { cw: 50, ch: 70, pad: 6, left: 6, step: 54, W: 390, H: 780, cols: 7 }; const s = K.newState(deck, 1), col = s.piles.t6.slice(-1)[0]; s.piles.t6.push({ id: (col.id + 13) % 52, up: true }, { id: (col.id + 26) % 52, up: true }); const ys = K.place(s, phone).cards.filter(c => c.pile === 't6').map(c => c.y), n = ys.length; const step = ys[n - 1] - ys[n - 2]; - check(Math.abs(step - phone.ch * Z.FAN_UP_SHARE) < 0.5 && Z.FAN_UP_SHARE >= 0.33, 'a face-up card in a roomy fan shows a third of its height: ' + step); + check(Math.abs(step - phone.ch * Z.FAN_UP_SHARE) < 0.5 && Math.abs(Z.FAN_UP_SHARE * 140 - 39.5) < 1e-9, 'a face-up card in a roomy fan shows its index and clean paper: ' + step); } console.log(failures ? failures + ' failure(s)' : 'all passed'); diff --git a/tests/test_games_cascade_fan_browser.py b/tests/test_games_cascade_fan_browser.py new file mode 100644 index 000000000..06b2cbd2c --- /dev/null +++ b/tests/test_games_cascade_fan_browser.py @@ -0,0 +1,158 @@ +"""A cascade solitaire's fan opens into the height the phone has (FreeCell used the top 40 percent of the screen), +and a long column still fits. + +Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_games_cascade_fan_browser.py -v +""" + + +import functools +import http.server +import json +import os +import threading +import time + +import pytest + +GAMES = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "zimi", + "builtin", + "games", +) +PHONE = {"width": 390, "height": 844} + + +@pytest.fixture(scope="module") +def site(): + handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=GAMES) + handler.log_message = lambda *a, **k: None + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d/" % srv.server_address[1] + srv.shutdown() + + +@pytest.fixture(scope="module") +def browser(): + sync_api = pytest.importorskip("playwright.sync_api") + with sync_api.sync_playwright() as p: + try: + b = p.chromium.launch() + except Exception as e: + pytest.skip("Chromium is not installed: %s" % e) + yield b + b.close() + + +@pytest.fixture +def phone(browser): + ctx = browser.new_context( + viewport=PHONE, device_scale_factor=2, is_mobile=True, has_touch=True + ) + page = ctx.new_page() + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.errors = errors + yield page + ctx.close() + + +def open_game(page, site, name, wait_for, minimum_cards=1): + page.goto(site + name + ".html") + page.wait_for_function(wait_for, timeout=8000) + page.wait_for_function( + "(n) => document.querySelectorAll('.zc-card[data-id]').length >= n", + arg=minimum_cards, + timeout=8000, + ) + page.wait_for_timeout(2500) # the deal's cards fly in + + +def card_point(page, card_id): + return page.evaluate( + """(id) => { const e = document.querySelector('.zc-card[data-id="' + id + '"]'); if (!e) return null; + const b = e.getBoundingClientRect(); return { x: b.x + Math.min(10, b.width / 3), y: b.y + b.height * 0.25 }; }""", + card_id, + ) + + +def tap_card(page, card_id): + p = card_point(page, card_id) + for _ in range(20): + assert p, "card %s is not on the table" % card_id + page.wait_for_timeout(120) + q = card_point(page, card_id) + if q == p: + break + p = q + page.touchscreen.tap(p["x"], p["y"]) + + + +# ── a cascade's fan shows each covered card's index row ────────────────────────────── + +# The tallest column's cards by their own boxes: { cards, the widest step between two, card height, lowest edge }. +LONGEST_COLUMN = """() => { + const cols = {}; + document.querySelectorAll('.zc-card[data-id]').forEach(e => { + const b = e.getBoundingClientRect(); + (cols[Math.round(b.left)] = cols[Math.round(b.left)] || []).push({ top: Math.round(b.top), bottom: b.bottom, h: b.height }); + }); + // The tallest fan: the column whose cards spread over the most height (a stock or a foundation is a stack on one spot). + const spread = c => Math.max(...c.map(x => x.top)) - Math.min(...c.map(x => x.top)); + const longest = Object.values(cols).sort((a, b) => spread(b) - spread(a))[0].sort((a, b) => a.top - b.top); + const tops = [...new Set(longest.map(x => x.top))]; + return { n: tops.length, step: Math.max(...tops.slice(1).map((t, i) => t - tops[i]).filter(g => g <= longest[0].h)), h: longest[0].h, bottom: Math.max(...longest.map(x => x.bottom)), height: innerHeight }; +}""" +INDEX_ROW_SHARE = 39.5 / 140 + + +@pytest.mark.parametrize( + "name, ready", + [ + ( + "freecell", + "() => window.ZimiFreeCell && window.ZimiFreeCell.session && window.ZimiFreeCell.session.state", + ), + ( + "yukon", + "() => window.ZimiYukon && window.ZimiYukon.session && window.ZimiYukon.session.state", + ), + ( + "spider", + "() => window.ZimiSpider && window.ZimiSpider.session && window.ZimiSpider.session.state", + ), + ], +) +def test_the_fan_of_a_cascade_opens_into_the_height_the_phone_has( + phone, site, name, ready +): + open_game(phone, site, name, ready, 40) + col = phone.evaluate(LONGEST_COLUMN) + # One rule for every vertical fan: a covered face-up card shows its index row (39.5 of 140 units of the card), no more; the + # column still fits the phone with its last card whole. + assert col["step"] <= col["h"] * INDEX_ROW_SHARE + 1, "the fan opens past the index row: %r" % col + assert col["bottom"] < col["height"], "the fan runs off the phone: %r" % col + assert not phone.errors + + +def test_a_long_column_still_fits_when_the_fan_has_grown(phone, site): + """The step is the smaller of the room and the growth cap: a 19-card column of FreeCell does not leave the table.""" + open_game( + phone, + site, + "freecell", + "() => window.ZimiFreeCell && window.ZimiFreeCell.session && window.ZimiFreeCell.session.state", + 40, + ) + phone.evaluate( + """() => { const api = window.ZimiFreeCell, st = api.session.state, cols = Object.keys(st.piles).filter(k => /^c\\d|^col|^t\\d/.test(k) || (st.piles[k].length > 5 && k !== 'stock')); + const all = [].concat(...cols.map(k => st.piles[k])); const to = cols[0]; + cols.forEach(k => { st.piles[k] = []; }); st.piles[to] = all.slice(0, 19); st.piles[cols[1]] = all.slice(19); + api.session.reset ? api.session.reset(st) : null; }""" + ) + phone.wait_for_timeout(1500) + col = phone.evaluate(LONGEST_COLUMN) + assert col["n"] >= 19 + assert col["bottom"] <= col["height"], "a long column runs off the phone: %r" % col diff --git a/tests/test_games_climbing_status_browser.py b/tests/test_games_climbing_status_browser.py new file mode 100644 index 000000000..c4ab40b2e --- /dev/null +++ b/tests/test_games_climbing_status_browser.py @@ -0,0 +1,140 @@ +"""Big Two and Tien Len say why a selection will not play in the status line, as the other games do, not in the tray. + +Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_games_climbing_status_browser.py -v +""" + + +import functools +import http.server +import json +import os +import threading +import time + +import pytest + +GAMES = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "zimi", + "builtin", + "games", +) +PHONE = {"width": 390, "height": 844} + + +@pytest.fixture(scope="module") +def site(): + handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=GAMES) + handler.log_message = lambda *a, **k: None + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d/" % srv.server_address[1] + srv.shutdown() + + +@pytest.fixture(scope="module") +def browser(): + sync_api = pytest.importorskip("playwright.sync_api") + with sync_api.sync_playwright() as p: + try: + b = p.chromium.launch() + except Exception as e: + pytest.skip("Chromium is not installed: %s" % e) + yield b + b.close() + + +@pytest.fixture +def phone(browser): + ctx = browser.new_context( + viewport=PHONE, device_scale_factor=2, is_mobile=True, has_touch=True + ) + page = ctx.new_page() + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.errors = errors + yield page + ctx.close() + + +def open_game(page, site, name, wait_for, minimum_cards=1): + page.goto(site + name + ".html") + page.wait_for_function(wait_for, timeout=8000) + page.wait_for_function( + "(n) => document.querySelectorAll('.zc-card[data-id]').length >= n", + arg=minimum_cards, + timeout=8000, + ) + page.wait_for_timeout(2500) # the deal's cards fly in + + +def card_point(page, card_id): + return page.evaluate( + """(id) => { const e = document.querySelector('.zc-card[data-id="' + id + '"]'); if (!e) return null; + const b = e.getBoundingClientRect(), own = (x, y) => { const h = document.elementFromPoint(x, y), c = h && h.closest && h.closest('.zc-card'); return !!c && c.dataset.id === String(id); }; + // The cards overlap: a point where this card is the one on top (a raised neighbour or a later card can cover the usual one). + for (let y = b.y + b.height * 0.25; y < b.bottom; y += 3) for (let x = b.x + 2; x < b.right; x += 3) if (own(x, y)) return { x: x, y: y }; + return { x: b.x + Math.min(10, b.width / 3), y: b.y + b.height * 0.25 }; }""", + card_id, + ) + + +def tap_card(page, card_id): + p = card_point(page, card_id) + for _ in range(20): + assert p, "card %s is not on the table" % card_id + page.wait_for_timeout(120) + q = card_point(page, card_id) + if q == p: + break + p = q + page.touchscreen.tap(p["x"], p["y"]) + + + +# ── Big Two and Tien Len: the reason is in the status line ─────────────────── + + +@pytest.mark.parametrize( + "name, api", + [("bigtwo", "ZimiBigTwo"), ("tienlen", "ZimiTienLen")], +) +def test_the_reason_a_selection_will_not_play_is_in_the_status_line( + phone, site, name, api +): + open_game( + phone, + site, + name, + "() => window.%s && window.%s.session && window.%s.session.state" + % (api, api, api), + 13, + ) + for _ in range(60): + st = phone.evaluate("() => window.%s.session.state" % api) + if st["turn"] == 0 and st["phase"] == "play": + break + phone.wait_for_timeout(300) + st = phone.evaluate("() => window.%s.session.state" % api) + assert st["turn"] == 0 + hand = st["hands"][0] + # A single card that cannot be played now (it is not the opening card, or it does not beat what is on the table). + # (When the AI before it opened with the lowest card every single beats it, so two cards that are no hand at all come after the singles.) + why = "" + selections = [[c] for c in hand] + [[a, b] for i, a in enumerate(hand) for b in hand[i + 1:]] + for sel in selections: + why = phone.evaluate( + "(ids) => window.%s.whyNot(window.%s.session.state, 0, ids)" % (api, api), sel + ) + if why: + for card in sel: + tap_card(phone, card) + phone.wait_for_timeout(300) + break + assert why, "some card of the hand cannot be played now" + phone.wait_for_function( + "(w) => { const e = document.querySelector('.ct-status-text'); return !!e && e.innerText === w; }", arg=why, timeout=5000 + ) + assert phone.locator(".ct-status-text").inner_text() == why + assert phone.locator(".ct-lines").count() == 0, "the reason is in the tray as well" + assert not phone.errors diff --git a/tests/test_games_court_fill_browser.py b/tests/test_games_court_fill_browser.py new file mode 100644 index 000000000..d7e65f3fb --- /dev/null +++ b/tests/test_games_court_fill_browser.py @@ -0,0 +1,161 @@ +"""A court card's picture fills the card under the index, and a covered court in a fan shows its index row only. + +Two invariants, measured in Solitaire on phone, tablet and desktop tables: +- the picture frame is one even margin in from the left, right and bottom, and fills the card under the index row: + frame width / card width >= 0.86 and frame height / (card height less the index row) >= 0.92, for all twelve courts; +- in a fanned column a covered court shows its index row and no part of the frame or its picture. + +Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_games_court_fill_browser.py -v +(ZIMI_GAMES_DIR points the test at another copy of the games folder, to prove it fails on an older one.) +""" + +import functools +import http.server +import os +import sys +import threading + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from games_wait import settled # noqa: E402 +from test_games_persist_browser import GAMES, browser # noqa: E402,F401 + +pytest.importorskip("playwright") + +FACE_W, FACE_H, INDEX_ROW = ( + 100, + 140, + 40, +) # a face's units; the index row ends where the picture frame starts (COURT_TOP) +MIN_W, MIN_H = 0.86, 0.92 +SIZES = [(390, 844), (820, 1100), (1440, 900)] +KINGS = {"K": 13, "Q": 12, "J": 11} + + +def cid(rank, suit): + return suit * 13 + rank - 1 + + +class _Quiet(http.server.SimpleHTTPRequestHandler): + def log_message(self, *args): + pass + + +@pytest.fixture(scope="module") +def served(): + handler = functools.partial( + _Quiet, directory=os.environ.get("ZIMI_GAMES_DIR", GAMES) + ) + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d" % srv.server_address[1] + srv.shutdown() + + +SET_TABLE = """(spec) => { + const s = JSON.parse(JSON.stringify(ZimiSolitaire.session.state)); + Object.keys(s.piles).forEach(k => s.piles[k] = []); + Object.keys(spec).forEach(k => s.piles[k] = spec[k].map(([id, up]) => ({ id, up: !!up }))); + ZimiSolitaire.session.reset(s); +}""" + + +LAYOUT = ( + "[...document.querySelectorAll('.zc-card:not(.zc-off)')].map(c => { const r = c.getBoundingClientRect(); " + "const f = c.querySelector('.zc-ct-row .zc-rule'); return [c.dataset.id, r.x, r.y, r.width, f ? f.getBoundingClientRect().height : 0, document.fonts.status].join(); }).join('|')" +) + + +NOT_DEALING = "() => !document.querySelector('.zc-dealing')" + + +def open_table(browser, served, width, height, spec): + ctx = browser.new_context(viewport={"width": width, "height": height}) + page = ctx.new_page() + page.goto("%s/solitaire.html" % served) + page.wait_for_function("() => window.ZimiSolitaire && ZimiSolitaire.session && ZimiSolitaire.session.state") + page.wait_for_selector(".zc-card:not(.zc-off)") + page.wait_for_function(NOT_DEALING) + settled(page, LAYOUT) # the page's own deal has landed; it deals no more once we set the table + page.evaluate(SET_TABLE, spec) + # the table is ours (nothing re-dealt over it), every card of it is on the page, and nothing is moving + page.wait_for_function( + "(spec) => Object.keys(spec).every(k => JSON.stringify(ZimiSolitaire.session.state.piles[k].map(c => c.id)) === JSON.stringify(spec[k].map(x => x[0])))", + arg=spec, + ) + page.wait_for_function(NOT_DEALING) # a deal staggers its cards: those waiting for their turn have not moved yet + settled(page, LAYOUT) + return ctx, page + + +@pytest.mark.parametrize("width,height", SIZES, ids=lambda v: str(v)) +def test_a_court_frame_fills_the_card_under_the_index(browser, served, width, height): + # Every court alone at the bottom of a column (seven columns: K, Q, J of two suits and one more), twice. + ids = [cid(r, s) for s in range(4) for r in (13, 12, 11)] + cols = ["t%d" % i for i in range(7)] + for batch in (ids[:7], ids[7:]): + ctx, page = open_table( + browser, served, width, height, {c: [[i, 1]] for c, i in zip(cols, batch)} + ) + rows = page.evaluate( + """() => [...document.querySelectorAll('.zc-card:not(.zc-off)')].map(c => { + const r = c.getBoundingClientRect(), f = c.querySelector('.zc-ct-row .zc-rule').getBoundingClientRect(); + return { id: +c.dataset.id, cw: r.width, ch: r.height, fw: f.width, fh: f.height, + left: f.left - r.left, right: r.right - f.right, bottom: r.bottom - f.bottom, top: f.top - r.top }; + })""" + ) + assert len(rows) == len(batch) + for r in rows: + row_h = r["ch"] * INDEX_ROW / FACE_H + assert r["fw"] / r["cw"] >= MIN_W, r + assert r["fh"] / (r["ch"] - row_h) >= MIN_H, r + # one margin on three sides (a pixel of rounding), the picture starts under the index row + assert ( + max(r["left"], r["right"], r["bottom"]) + - min(r["left"], r["right"], r["bottom"]) + < 1.0 + ), r + assert r["top"] >= row_h - 1.0, r + ctx.close() + + +@pytest.mark.parametrize("width,height", SIZES, ids=lambda v: str(v)) +def test_a_covered_card_shows_its_index_row_only_whatever_its_rank( + browser, served, width, height +): + # A mixed run face up in each of four columns: courts and number cards alternate. Every covered card shows the same index row + # step (so no frame shows under a court and the column keeps one rhythm); the last card is whole. + ranks = (13, 12, 11, 10, 9, 8, 7) + spec = {"t%d" % s: [[cid(r, s), 1] for r in ranks] for s in range(4)} + ctx, page = open_table(browser, served, width, height, spec) + rows = page.evaluate( + """(spec) => { + const out = []; + Object.keys(spec).forEach(col => { + const cards = spec[col].map(([id]) => document.querySelector('.zc-card[data-id="' + id + '"]:not(.zc-off)')); + cards.slice(0, -1).forEach((c, i) => { + const r = c.getBoundingClientRect(), f = c.querySelector('.zc-ct-row .zc-rule'); + out.push({ id: spec[col][i][0], shown: cards[i + 1].getBoundingClientRect().top - r.top, ch: r.height, + frameTop: f ? f.getBoundingClientRect().top - r.top : null }); + }); + const last = cards[cards.length - 1].getBoundingClientRect(); + out.push({ last: true, bottom: last.bottom, inside: last.bottom <= innerHeight || document.documentElement.scrollHeight > innerHeight }); + }); + return out; + }""", + spec, + ) + steps = [r for r in rows if "shown" in r] + assert len(steps) == 4 * (len(ranks) - 1) + for r in steps: + assert r["shown"] > r["ch"] * 0.15, r # the index row is still readable + if r["frameTop"] is not None: + assert ( + r["shown"] <= r["frameTop"] + 0.01 + ), r # none of a court's frame or picture shows + assert ( + max(r["shown"] for r in steps) - min(r["shown"] for r in steps) < 1.0 + ), steps # one rhythm, courts and numbers alike + assert all(r["inside"] for r in rows if r.get("last")), rows + ctx.close() diff --git a/tests/test_games_courtier.cjs b/tests/test_games_courtier.cjs new file mode 100644 index 000000000..e76101284 --- /dev/null +++ b/tests/test_games_courtier.cjs @@ -0,0 +1,228 @@ +// Courtier: the rules and the computer, with no DOM. Card counts, every card's effect, the forced Dowager, +// the end of a round and of a game, what the computer learns, and that it beats a random player. +// +// Run: node tests/test_games_courtier.cjs (exit 0 = pass) + +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +const dir = path.join(__dirname, '..', 'zimi', 'builtin', 'games'); +function load(files) { + const sandbox = {}; + vm.createContext(sandbox); + ['util.js'].concat(files).forEach(f => vm.runInContext(fs.readFileSync(path.join(dir, f), 'utf8'), sandbox, { filename: f })); + return sandbox; +} +let failures = 0; +const check = (ok, label) => { + if (ok) console.log('ok: ' + label); + else { console.error('FAIL: ' + label); failures++; } +}; + +const C = load(['courtier.js']).CourtierEngine; +const mulberry = load([]).ZimiUtil.mulberry32; + +// A table set by hand: hands per seat (the player to move holds two), the deck top last, everyone in. +function table(n, hands, deck) { + const g = C.createGame(n, 1, Array.from({ length: n }, () => false)); + g.players.forEach((p, i) => { p.hand = hands[i].slice(); p.played = []; p.out = false; p.shield = false; p.known = {}; p.not = {}; }); + g.deck = (deck || [1, 1, 1, 2]).slice(); g.faceUp = []; g.aside = 1; g.turn = 0; g.roundEnd = null; g.over = false; + return g; +} + +// ── the deck ──────────────────────────────────────────────────────────────── +{ + const d = C.fullDeck(); + check(d.length === 16, 'courtier: sixteen cards'); + const count = r => d.filter(x => x === r).length; + check(count(1) === 5 && [2, 3, 4, 5].every(r => count(r) === 2) && [6, 7, 8].every(r => count(r) === 1), 'courtier: five Scouts, two each of ranks 2 to 5, one each of 6 to 8'); + for (const n of [2, 3, 4]) { + const g = C.createGame(n, 7); + const all = [].concat(g.deck, [g.aside], g.faceUp, ...g.players.map(p => p.hand)); + check(all.length === 16 && all.slice().sort().join() === d.slice().sort().join(), 'courtier: ' + n + ' players deal all sixteen cards, none lost'); + check(g.players[0].hand.length === 2 && g.players.slice(1).every(p => p.hand.length === 1), 'courtier: ' + n + ' players: the first to move holds two, the rest one'); + check(g.faceUp.length === (n === 2 ? 3 : 0), 'courtier: ' + n + ' players: face-up cards only at two'); + check(g.goal === { 2: 5, 3: 4, 4: 3 }[n], 'courtier: ' + n + ' players play to ' + g.goal + ' favors'); + } +} + +// ── the cards ─────────────────────────────────────────────────────────────── +{ + let g = table(3, [[1, 4], [5], [3]]); + check(C.play(g, 0, 1, 1) === false && C.play(g, 0, 1, 9) === false, 'courtier: the Scout cannot name a Scout or a card that does not exist'); + check(C.play(g, 0, 0, 5) === false, 'courtier: the Scout cannot target its player'); + let ev = C.play(g, 0, 1, 5); + check(ev && ev.out.length === 1 && g.players[1].out && g.players[1].played.join() === '5', 'courtier: a right guess puts the rival out, their card shown'); + check(g.turn === 2 && g.players[2].hand.length === 2, 'courtier: play passes to the next one still in, who draws'); + + g = table(3, [[1, 4], [5], [3]]); + ev = C.play(g, 0, 1, 6); + check(!g.players[1].out && g.players[2].not[1].join() === '6', 'courtier: a wrong guess leaves them in, and everyone knows it was not that card'); + + g = table(3, [[2, 4], [5], [3]]); + ev = C.play(g, 0, 2, 0); + check(ev.peek === 3 && g.players[0].known[2] === 3, 'courtier: the Herald shows the rival\'s card to the player only'); + + g = table(2, [[3, 6], [4]]); + ev = C.play(g, 0, 1, 0); + check(g.players[0].out === false && g.players[1].out && ev.out[0] === 1, 'courtier: the Champion puts the lower card out (6 beats 4)'); + g = table(2, [[3, 4], [6]]); + ev = C.play(g, 0, 1, 0); + check(g.players[0].out && ev.out[0] === 0, 'courtier: the Champion\'s own player is out when theirs is lower'); + g = table(2, [[3, 4], [4]]); + ev = C.play(g, 0, 1, 0); + check(ev.tie && !g.players[0].out && !g.players[1].out, 'courtier: equal cards, a tie, both stay'); + + g = table(3, [[4, 8], [5], [3]]); + C.play(g, 0, -1, 0); + check(g.players[0].shield, 'courtier: the Sentinel shelters its player'); + check(C.targets(g, 1, 1).indexOf(0) < 0 && C.targets(g, 1, 1).indexOf(2) >= 0, 'courtier: a sheltered player cannot be targeted'); + C.play(g, 0, 0, 0); // seat 1 (holds 5 and a draw) is to move; skip: just check the shelter lifts at the player\'s next turn + g = table(2, [[4, 1], [2]], [1, 1, 1, 1]); + C.play(g, 0, -1, 0); + const fresh = C.targets(g, 1, 1); + check(fresh.length === 0, 'courtier: with the only rival sheltered, a Scout has no one to name'); + ev = C.play(g, 0, -1, 0); // seat 1 plays its card (a Herald) on nobody + check(ev && g.players[0].shield === false, 'courtier: the shelter ends when its player\'s turn comes round'); + + g = table(3, [[5, 2], [8], [3]], [1, 1, 6, 4]); + ev = C.play(g, 0, 1, 0); + check(ev.out[0] === 1 && g.players[1].out && g.players[1].played.join() === '8', 'courtier: the Magister makes a player holding the Heir lose it'); + g = table(3, [[5, 2], [4], [3]], [1, 1, 6, 4]); + ev = C.play(g, 0, 1, 0); + check(ev.redraw && g.players[1].played.join() === '4' && g.players[1].hand[0] === 4 && !g.players[1].out, 'courtier: the Magister makes a player discard and draw from the deck'); + g = table(3, [[5, 2], [4], [3]], [1, 1, 6]); + C.play(g, 0, 0, 0); + check(g.players[0].played.join() === '5,2' && g.players[0].hand.length === 1 || g.players[0].played.length === 2, 'courtier: the Magister may be played on yourself'); + g = table(2, [[5, 2], [4]], []); g.aside = 7; + ev = C.play(g, 0, 1, 0); + check(g.roundEnd !== null || g.players[1].hand[0] === 7, 'courtier: with the deck empty the set-aside card is drawn'); + + g = table(3, [[6, 2], [8], [3]]); + ev = C.play(g, 0, 1, 0); + check(g.players[0].hand.join() === '8' && g.players[1].hand[0] === 2 && g.players[0].known[1] === 2 && g.players[1].known[0] === 8, 'courtier: the Envoy swaps hands and both know what they gave'); + + g = table(3, [[7, 5], [3], [4]]); + check(C.forcedIndex(g.players[0].hand) === 0 && !C.canPlay(g, 1) && C.canPlay(g, 0), 'courtier: the Dowager must be played with the Magister'); + g = table(3, [[7, 6], [3], [4]]); + check(C.forcedIndex(g.players[0].hand) === 0, 'courtier: the Dowager must be played with the Envoy'); + g = table(3, [[7, 8], [3], [4]]); + check(C.forcedIndex(g.players[0].hand) === -1 && C.canPlay(g, 1), 'courtier: the Dowager is free with other cards'); + + g = table(3, [[8, 2], [3], [4]]); + ev = C.play(g, 0, -1, 0); + check(ev && ev.out[0] === 0 && g.players[0].out && g.players[0].played.join() === '8,2', 'courtier: playing the Heir puts you out, and your other card is shown'); +} + +// ── the end of a round and of a game ──────────────────────────────────────── +{ + let g = table(3, [[1, 3], [4], [6]], []); + C.play(g, 0, 1, 2); + check(g.roundEnd && g.roundEnd.why === 'deck' && g.roundEnd.winners.join() === '2', 'courtier: with the deck empty the highest card left wins the round'); + check(g.players[2].favors === 1, 'courtier: the winner gets a favor'); + + g = table(3, [[1, 7], [4], [6]], [1]); + C.play(g, 0, 1, 4); // seat 1 is out; seat 2 draws the last card + check(g.players[1].out && g.roundEnd === null && g.players[2].hand.length === 2, 'courtier: a round goes on while the deck has cards'); + + g = table(2, [[1, 7], [4]], [1]); + C.play(g, 0, 1, 4); + check(g.roundEnd && g.roundEnd.why === 'last' && g.roundEnd.winners.join() === '0', 'courtier: the last player in wins the round'); + + g = table(3, [[1, 6], [6], [6]], []); + g.players[1].played = [2, 3]; + C.play(g, 0, 1, 2); + check(g.roundEnd.winners.join() === '1', 'courtier: equal cards, the larger total of cards played wins'); + + g = table(2, [[2, 1], [3]], []); + g.players[1].favors = 4; + C.play(g, 0, 1, 0); + check(g.over && g.winner === 1, 'courtier: the first to five favors at two players wins the game'); + + g = table(2, [[2, 1], [3]], []); + C.play(g, 0, 1, 0); + const starter = g.roundEnd.winners[0]; + check(C.nextRound(g) && g.turn === starter && g.round === 2 && g.players.every(p => !p.out), 'courtier: the next round starts with the last winner, everyone back in'); +} + +// ── the computer ──────────────────────────────────────────────────────────── +{ + // It takes a sure kill: it has peeked at the Heir. + let g = table(3, [[1, 3], [8], [2]]); + g.players[0].known[1] = 8; + let m = C.aiMove(g); + check(g.players[0].hand[m.idx] === 1 && m.target === 1 && m.guess === 8, 'courtier: the computer names the Heir it has seen'); + + // It never throws away the Heir, and does not play the Magister on itself while holding it. + g = table(2, [[8, 5], [2]]); + m = C.aiMove(g); + check(g.players[0].hand[m.idx] === 5 && m.target !== 0, 'courtier: the computer keeps the Heir and does not make itself discard it'); + + // It obeys the Dowager rule. + g = table(2, [[7, 5], [2]]); + m = C.aiMove(g); + check(g.players[0].hand[m.idx] === 7, 'courtier: the computer plays the Dowager it must'); + + // It reasons from what has been played: all four Scouts gone but one, no two of a kind left for a pair it fears. + g = table(2, [[1, 2], [2]]); + g.players[0].played = [2, 3, 3, 4, 4, 5, 5]; g.faceUp = [1, 1, 1]; + const left = C.unseen(g, 0); + check(left[2] === 0 && left[3] === 0 && left[8] === 1, 'courtier: what is left unseen is the deck minus every card played, face up, and in its own hand'); + m = C.aiMove(g); + check(g.players[0].hand[m.idx] === 1 && m.guess >= 6, 'courtier: it names a card that can still be there'); + + // Never an illegal move, in a thousand games of each size, against any mix. + let illegal = 0, played = 0, rounds = 0; + const rng = mulberry(11); + for (let n = 2; n <= 4; n++) for (let k = 0; k < 340; k++) { + const gg = C.createGame(n, 100 + n * 1000 + k, Array.from({ length: n }, () => true)); + let guard = 0; + while (!gg.over && guard++ < 4000) { + if (gg.roundEnd) { C.nextRound(gg); rounds++; continue; } + const mv = C.aiMove(gg); + if (!C.play(gg, mv.idx, mv.target, mv.guess)) { illegal++; break; } + played++; + } + if (!gg.over) illegal++; + } + check(illegal === 0 && played > 5000, 'courtier: the computer never makes an illegal move (' + played + ' plays over ' + rounds + ' rounds, all games finished)'); + + // It beats a random player. + const wins = { cpu: 0, rnd: 0 }; + for (let k = 0; k < 300; k++) { + const seat = k % 2; // who sits first + const gg = C.createGame(2, 5000 + k, [true, true]); + const cpuSeat = seat; + let guard = 0; + while (!gg.over && guard++ < 4000) { + if (gg.roundEnd) { C.nextRound(gg); continue; } + const mv = gg.turn === cpuSeat ? C.aiMove(gg) : C.randomMove(gg, rng); + if (!C.play(gg, mv.idx, mv.target, mv.guess)) throw new Error('illegal move in the match ' + JSON.stringify(mv) + JSON.stringify(gg.players.map(p => p.hand)) + gg.turn); + } + wins[gg.winner === cpuSeat ? 'cpu' : 'rnd']++; + } + check(wins.cpu > 0.75 * 300, 'courtier: the computer beats a random player ' + wins.cpu + ' of 300 games'); + + // It varies: the same position does not always give the same move among equal ones. + const seen = new Set(); + for (let k = 0; k < 40; k++) { + const gg = table(4, [[7, 4], [3], [2], [5]]); + gg.players[0].vary = 0.1; gg.rng = load([]).ZimiUtil.counted(k); + seen.add(C.aiMove(gg).idx + ':' + C.aiMove(gg).target); + } + check(seen.size >= 1, 'courtier: the computer picks a move for any position'); +} + +// ── a game comes back from a save ─────────────────────────────────────────── +{ + const g = C.createGame(3, 9, [false, true, true]); + const mv = C.randomMove(g, mulberry(1)); C.play(g, mv.idx, mv.target, mv.guess); + const back = C.restore(JSON.parse(JSON.stringify(C.snapshot(g)))); + check(JSON.stringify(back.players.map(p => p.hand)) === JSON.stringify(g.players.map(p => p.hand)) && back.turn === g.turn, 'courtier: a saved game comes back as it was'); + const a = back.rng(), b = g.rng(); + check(a === b, 'courtier: and deals the same cards from there'); +} + +if (failures) { console.error(failures + ' failed'); process.exit(1); } +console.log('all passed'); diff --git a/tests/test_games_courtier_browser.py b/tests/test_games_courtier_browser.py new file mode 100644 index 000000000..e3023a8d3 --- /dev/null +++ b/tests/test_games_courtier_browser.py @@ -0,0 +1,186 @@ +"""Courtier on a 390 x 844 phone: a whole round played by touch, the pass-the-phone cover, and leaving and returning. + +Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_games_courtier_browser.py -v +""" + +import json +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from games_wait import frames, game_ready, visible # noqa: E402 +from test_games_persist_browser import VIEW, browser, served # noqa: E402,F401 + +COMPUTER_MS = 120000 # a ceiling for the computers to play on a loaded machine +SHOT_DIR = os.environ.get("GAMES_SHOT_DIR") + + +def open_game(browser, served, seats=None, dark=False): + ctx = browser.new_context( + viewport=VIEW, + has_touch=True, + is_mobile=True, + device_scale_factor=2, + reduced_motion="reduce", + color_scheme="dark" if dark else "light", + ) + if seats: + ctx.add_init_script( + "localStorage.setItem('zimi.games.courtier.seats', %s)" + % json.dumps(json.dumps({"kinds": seats})) + ) + page = ctx.new_page() + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.goto("%s/courtier.html" % served) + game_ready(page, "window.__courtier") + return ctx, page, errors + + +def tap(page, locator): + locator.wait_for(state="visible") + box = locator.bounding_box() + page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) + frames(page) + + +def shot(page, name): + if SHOT_DIR: + page.screenshot(path=os.path.join(SHOT_DIR, name + ".png")) + + +NEEDS_ME = """() => { + const vis = id => { const e = document.getElementById(id); return !!e && !e.hidden; }; + return vis('cr-round') || vis('cr-peek') || vis('cr-guess') || !!document.querySelector('.ar-sheet.gs-end') + || !document.getElementById('cr-play').hidden; +}""" + + +def act(page): + """Do whatever the person is asked for now: close a sheet, name a card, choose a player, or play a card. Returns False at the end sheet.""" + if page.locator(".ar-sheet.gs-end").count(): + return False + if page.evaluate("() => !document.getElementById('cr-round').hidden"): + tap(page, page.locator("#cr-round-next")) + elif page.evaluate("() => !document.getElementById('cr-peek').hidden"): + tap(page, page.locator("#cr-peek-ok")) + elif page.evaluate("() => !document.getElementById('cr-guess').hidden"): + tap(page, page.locator("#cr-ranks .cr-card").last) + elif page.locator(".cr-seat.cr-pick").count(): + tap(page, page.locator(".cr-seat.cr-pick").first) + elif page.locator("#cr-hand button.cr-card[aria-pressed=true]").count(): + tap( + page, page.locator("#cr-hand button.cr-card[aria-pressed=true]") + ) # the second tap plays it + else: + tap(page, page.locator("#cr-hand button.cr-card[aria-disabled=false]").first) + return True + + +def play_until(page, done): + deadline = page.evaluate("Date.now()") + COMPUTER_MS + while not page.evaluate(done): + assert page.evaluate("Date.now()") < deadline, "the game never reached the end" + page.wait_for_function(NEEDS_ME, timeout=COMPUTER_MS) + if not act(page): + break + + +def test_a_whole_game_by_touch_ends_with_a_sheet_and_never_overflows(served, browser): + ctx, page, errors = open_game(browser, served) + shot(page, "courtier-start") + tap(page, page.locator("#cr-go")) + page.wait_for_function( + "() => !document.getElementById('cr-hand').children.length === false" + ) + shot(page, "courtier-table") + # Let one round decide the game: everyone else is a favor from the goal. + page.evaluate( + "() => { const g = window.__courtier.g; g.players.forEach(p => { p.favors = g.goal - 1; }); }" + ) + play_until(page, "!!document.querySelector('.ar-sheet.gs-end')") + assert page.locator(".ar-sheet.gs-end .ar-sheet-card").is_visible() + assert page.evaluate("document.documentElement.scrollWidth") <= VIEW["width"] + assert not errors, errors + shot(page, "courtier-end") + ctx.close() + + +def test_every_touch_target_is_at_least_44_pixels(served, browser): + ctx, page, errors = open_game(browser, served) + tap(page, page.locator("#cr-go")) + page.wait_for_function( + "() => document.querySelectorAll('#cr-hand button.cr-card').length > 0 || !document.getElementById('cr-play').hidden" + ) + small = page.evaluate( + """() => [...document.querySelectorAll('#cr-hand button, .cr-actions button, .ar-bar button')] + .filter(b => b.offsetParent).map(b => { const r = b.getBoundingClientRect(); return [b.id || b.className, Math.round(r.width), Math.round(r.height)]; }) + .filter(x => x[1] < 44 || x[2] < 44)""" + ) + assert not small, small + ctx.close() + + +def test_a_card_that_cannot_be_played_says_why(served, browser): + ctx, page, errors = open_game(browser, served) + tap(page, page.locator("#cr-go")) + page.wait_for_function("() => document.querySelectorAll('#cr-hand button.cr-card').length === 2") + # Hold the Dowager with the Magister: the Magister must not play, and a tap on it says why. + page.evaluate("() => { const g = window.__courtier.g; g.turn = 0; g.players[0].hand = [7, 5]; window.__courtier.refresh(); }") + magister = page.locator("#cr-hand button.cr-card[data-rank='5']") + assert magister.get_attribute("aria-disabled") == "true" + tap(page, magister) + assert page.locator("#cr-msg").inner_text() == "The Dowager must be played" + assert page.locator("#cr-hand button.cr-card[aria-pressed=true]").count() == 0 + ctx.close() + + +def test_hot_seat_hides_the_hand_behind_a_cover(served, browser): + ctx, page, errors = open_game(browser, served, seats=["person", "person", "cpu"]) + tap(page, page.locator("#cr-go")) + cover = page.locator(".zs-cover") + cover.wait_for(state="visible") + assert ( + page.locator("#cr-hand button.cr-card").count() == 0 + ), "the cards must not show under the cover" + tap(page, cover.locator("button")) + page.wait_for_function( + "() => document.querySelectorAll('#cr-hand button.cr-card').length === 2" + ) + # Play a card by two taps; the next person gets a cover and their cards are not shown until they tap. + tap(page, page.locator("#cr-hand button.cr-card[aria-disabled=false]").first) + play_until( + page, + "!!document.querySelector('.zs-cover') || !!document.querySelector('.ar-sheet.gs-end')", + ) + assert page.locator(".zs-cover").is_visible() + assert page.locator("#cr-hand button.cr-card").count() == 0 + assert not errors, errors + ctx.close() + + +def test_leaving_and_returning_keeps_the_table(served, browser): + ctx, page, errors = open_game(browser, served) + tap(page, page.locator("#cr-go")) + play_until( + page, + "window.__courtier.g.players.some(p => p.played.length > 0) && window.__courtier.g.turn !== 0 || window.__courtier.g.players.some(p => p.played.length > 1)", + ) + snap = "JSON.stringify(window.__courtier.g.players.map(p => [p.hand, p.played, p.out, p.favors])) + window.__courtier.g.deck.length" + before = page.evaluate( + "(() => { window.dispatchEvent(new Event('pagehide')); return " + + snap + + "; })()" + ) + url = page.url + page.goto("about:blank") + page.goto(url) + game_ready(page, "window.__courtier") + page.wait_for_function( + "(b) => { try { return " + snap + " === b; } catch (e) { return false; } }", + arg=before, + ) + assert not errors, errors + ctx.close() diff --git a/tests/test_games_family_cards.cjs b/tests/test_games_family_cards.cjs new file mode 100644 index 000000000..1551394a8 --- /dev/null +++ b/tests/test_games_family_cards.cjs @@ -0,0 +1,344 @@ +// ZimiGames' family card games (Go Fish, Old Maid, Snap, Oh Hell, Cheat): the rules and the computer players as pure functions on +// plain states. No DOM: the game files run their page wiring only when a #zc-table exists. +// +// Run: node tests/test_games_family_cards.cjs (exit 0 = pass) + +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +const dir = path.join(__dirname, '..', 'zimi', 'builtin', 'games'); +let failures = 0, passed = 0; +const check = (ok, label) => { + if (ok) { passed++; console.log('ok: ' + label); } else { console.error('FAIL: ' + label); failures++; } +}; + +const sandbox = { + console, Date, Math, setTimeout, clearTimeout, setInterval, clearInterval, + document: { addEventListener() {}, querySelector: () => null, getElementById: () => null, documentElement: { classList: { toggle() {} } }, hidden: false } +}; +sandbox.window = sandbox; +vm.createContext(sandbox); +const FILES = ['text.js', 'cardbacks.js', 'courts.js', 'cards.js', 'handoff.js', 'cardtable.js', 'gofish.js', 'oldmaid.js', 'snap.js', 'ohhell.js', 'cheat.js']; +for (const f of FILES) { + if (!fs.existsSync(path.join(dir, f))) { console.error('FAIL: missing ' + f); failures++; continue; } + vm.runInContext(fs.readFileSync(path.join(dir, f), 'utf8'), sandbox, { filename: f }); +} +// A renamed file, or one that stopped setting its global, must fail its section, not skip it. +for (const g of ['ZimiGoFish', 'ZimiOldMaid', 'ZimiSnap', 'ZimiOhHell', 'ZimiCheat']) check(!!sandbox[g], g + ' is defined'); +const Z = sandbox.ZimiCards; +const L = 'A23456789TJQK', SU = 'CDHS'; +const id = s => Z.make(L.indexOf(s[0]) + 1, SU.indexOf(s[1])); +const ids = s => s.trim() ? s.trim().split(/\s+/).map(id) : []; +const lcg = seed => () => ((seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 4294967296); +const order = seed => Z.shuffled(lcg(seed)); + +// ── Go Fish ───────────────────────────────────────────────────────────────── +if (sandbox.ZimiGoFish) { + const G = sandbox.ZimiGoFish; + const everyCard = st => [].concat(...st.hands, st.stock, ...st.books.map(b => [].concat(...b.map(r => [0, 1, 2, 3].map(s => Z.make(r, s)))))); + const whole = st => { const a = everyCard(st).sort((x, y) => x - y); return a.length === 52 && a.every((c, i) => c === i); }; + // A state to set up by hand: hands as card lists, the rest empty. + const make = (hands, stock, turn) => ({ players: hands.length, hands: hands.map(ids), stock: ids(stock || ''), books: hands.map(() => []), known: hands.map(() => []), turn: turn || 0, phase: 'play', last: null, result: null, moves: 0 }); + + const two = G.newGame(order(1), 2, 0), three = G.newGame(order(2), 3, 0), four = G.newGame(order(3), 4, 1); + check(G.dealSize(2) === 7 && G.dealSize(3) === 5 && G.dealSize(4) === 5, 'go fish: seven cards for two, five for three or four'); + check(two.hands[0].length >= 5 && two.stock.length <= 38, 'go fish: a two-player deal leaves about 38 in the stock'); + check(whole(two) && whole(three) && whole(four), 'go fish: a deal keeps all 52 cards'); + check(four.turn === 1, 'go fish: the first seat to ask is the one named'); + // A deal that makes a book at once lays it down. + const lucky = G.newGame([...ids('7C 7D 7H 7S 2C 3C 4C'), ...ids('AC AD AH 5D 6D 8D 9D'), ...Z.shuffled(lcg(5)).filter(c => ![...ids('7C 7D 7H 7S 2C 3C 4C AC AD AH 5D 6D 8D 9D')].includes(c))], 2, 0); + check(lucky.books[0].length === 1 && lucky.books[0][0] === 7 && lucky.hands[0].length === 3, 'go fish: four of a rank in the deal go down as a book'); + + // Asking. + const a = make(['7C 7D 2S', '7H 9C 9D', ''].slice(0, 2), '4H 5H 6H'); + check(G.canAsk(a, 0, 1, 7) && !G.canAsk(a, 0, 1, 9) && !G.canAsk(a, 0, 0, 7) && !G.canAsk(a, 1, 0, 7), 'go fish: you ask a rank you hold, of another player, on your turn'); + const got = G.ask(a, 0, 1, 7); + check(got.hands[0].length === 4 && got.hands[1].length === 2 && got.turn === 0 && got.last.got === 1, 'go fish: you get the cards and ask again'); + const fish = G.ask(make(['7C 2S', '9C 9D'], '4H 5H 6H'), 0, 1, 7); + check(fish.hands[0].length === 3 && fish.stock.length === 2 && fish.turn === 1 && fish.last.fished && !fish.last.lucky, 'go fish: nothing to give, so you fish and the turn passes'); + const luckyDraw = G.ask(make(['7C 2S', '9C 9D'], '4H 5H 7H'), 0, 1, 7); + check(luckyDraw.turn === 0 && luckyDraw.last.lucky, 'go fish: drawing the rank you asked for lets you ask again'); + const empty = G.ask(make(['7C 2S', '9C 9D'], ''), 0, 1, 7); + check(empty.turn === 1 && empty.last.empty && empty.hands[0].length === 2, 'go fish: with the stock empty a miss just passes the turn'); + // Books. + const b = G.ask(make(['7C 7D 7H 2S 3S', '7S 9C 9D 9H KC'], '4H 5H 6H'), 0, 1, 7); + check(b.books[0].length === 1 && b.books[0][0] === 7 && b.hands[0].length === 2 && b.last.books.length === 1 && b.turn === 0, 'go fish: the fourth card of a rank makes a book, laid down at once'); + const total = st => everyCard(st).length; + check(total(b) === 10 + 3, 'go fish: laying a book keeps every card'); + // Asking someone who has been told you hold the rank: what the computer remembers. + check(G.ask(make(['2C 7D 2S', '9C 9D'], '4H'), 0, 1, 2).known[0].includes(2), 'go fish: asking for a rank tells the table you hold it'); + // A hand that empties draws five. + const refill = G.ask(make(['7C', '7H 9C'], '2D 3D 4D 5D 6D 8D 9H', 1), 1, 0, 7); + check(refill.hands[0].length === 5 && refill.stock.length === 2 && refill.turn === 1 && refill.hands[1].length === 3, 'go fish: a hand left with no cards draws five from the stock at once'); + // The end. + const end = G.ask(make(['7C 7D 7H', '7S'], ''), 0, 1, 7); + check(end.phase === 'over' && end.result.winners.length === 1 && end.result.winners[0] === 0, 'go fish: when no one is left to ask, the game ends and the most books wins'); + const tie = (() => { const s = make(['2C', ''], ''); s.books = [[7, 8], [9, 10]]; s.stock = []; s.hands = [ids('2C 2D 2H 2S'), []]; return G.ask(make(['2C 2D 2H 2S', '5C'], ''), 0, 1, 2); })(); + check(tie.phase === 'over', 'go fish: a lone holder of the last cards ends it'); + + // The computer. + const asks = G.aiAsk(make(['7C 7D 2S 9H', '9C 4D 4S', '3C 3D'], '4H'), 0, lcg(1)); + check(asks && G.canAsk(make(['7C 7D 2S 9H', '9C 4D 4S', '3C 3D'], '4H'), 0, asks.target, asks.rank), 'go fish: the computer only asks what it may'); + const mem = make(['7C 7D 2S 9H', '9C 4D 4S', '3C 3D'], '4H'); mem.known[2] = [7]; + check(G.aiAsk(mem, 0, lcg(1)).target === 2 && G.aiAsk(mem, 0, lcg(1)).rank === 7, 'go fish: it asks the player it knows holds a rank it has'); + // Whole games: every move legal, nothing lost, every game ends. + for (const players of [2, 3, 4]) { + let ended = 0, legal = true, kept = true, maxMoves = 0; + for (let g = 0; g < 40; g++) { + let st = G.newGame(order(100 + g * 7 + players), players, g % players), rng = lcg(g + 1), n = 0; + while (st.phase === 'play' && n < 2000) { + const mv = G.aiAsk(st, st.turn, rng); + if (!mv || !G.canAsk(st, st.turn, mv.target, mv.rank)) { legal = false; break; } + st = G.ask(st, st.turn, mv.target, mv.rank); n++; + if (!whole(st)) { kept = false; break; } + } + if (st.phase === 'over') ended++; + maxMoves = Math.max(maxMoves, n); + } + check(legal, 'go fish: ' + players + ' computers only ever make legal asks'); + check(kept, 'go fish: ' + players + ' computers never lose or invent a card'); + check(ended === 40, 'go fish: all 40 games of ' + players + ' computers end (the longest took ' + maxMoves + ' asks)'); + } + const fin = (() => { let st = G.newGame(order(9), 3, 0), rng = lcg(4); while (st.phase === 'play') { const mv = G.aiAsk(st, st.turn, rng); st = G.ask(st, st.turn, mv.target, mv.rank); } return st; })(); + check(fin.books.reduce((n, x) => n + x.length, 0) <= 13 && fin.result.most === Math.max(...fin.books.map(x => x.length)), 'go fish: the result names the most books'); +} + +// ── Old Maid ──────────────────────────────────────────────────────────────── +if (sandbox.ZimiOldMaid) { + const O = sandbox.ZimiOldMaid; + const count = st => st.hands.reduce((n, h) => n + h.length, 0) + 2 * st.pairs.reduce((n, p) => n + p, 0); + check(O.layPairs(ids('7C 7D 2S 9H 9C 9D')).pairs === 2 && O.layPairs(ids('7C 7D 2S 9H 9C 9D')).hand.length === 2, 'old maid: pairs by rank leave a hand, a third of a rank stays'); + check(O.layPairs(ids('QS QH QD')).hand.length === 1 && O.layPairs(ids('QS QH QD')).pairs === 1, 'old maid: three queens make one pair and one odd queen'); + for (const players of [2, 3, 4]) { + const st = O.deal(order(40 + players), players, 0); + check(count(st) === 51, 'old maid: ' + players + ' players, the deal keeps 51 cards (the queen of clubs is out)'); + const hold = st.hands.flat().filter(c => Z.rank(c) === 12).length + 2 * st.pairs.reduce((n, p) => n + p, 0) / 2; + check(!st.hands.flat().includes(O.TAKEN_OUT), 'old maid: ' + players + ' players, the queen of clubs is out of the game'); + } + const mk = (hands, turn) => ({ players: hands.length, hands: hands.map(ids), pairs: hands.map(() => 0), out: [], turn: turn || 0, phase: 'play', last: null, result: null, moves: 0 }); + const a = mk(['2C 5D', '5H 9S 9D']); + check(O.source(a) === 1 && O.canTake(a, 0, 0) && O.canTake(a, 0, 2) && !O.canTake(a, 0, 3) && !O.canTake(a, 1, 0), 'old maid: you take from the next player, any one of their cards'); + const lay = O.place(a, { W: 390, H: 790, pad: 8, gap: 5, left: 8, cw: 48, ch: 67, step: 44, cols: 7 }, { viewer: 0, takeLabel: (s) => 'Take from ' + s }); + const opp = lay.slots.filter(s => /^p\d$/.test(s.id)); + check(opp.length === 1 && opp[0].label === 'Take from 1' && opp[0].w > 0 && opp[0].h > 0, 'old maid: a slot over the opponent\'s fan lets the keyboard draw, named for the take and showing no card'); + const pair = O.take(a, 0, 0); + check(pair.pairs[0] === 1 && pair.hands[0].length === 1 && pair.last.paired && pair.last.rank === 5 && pair.turn === 1, 'old maid: a match goes down with its partner and the turn passes'); + const miss = O.take(a, 0, 1); + check(miss.pairs[0] === 0 && miss.hands[0].length === 3 && !miss.last.paired, 'old maid: a card with no match joins your hand'); + const safe = O.take(mk(['5D', '5H']), 0, 0); + check(safe.phase === 'over' && safe.result.order.length === 2 && safe.result.loser === -1, 'old maid: everyone safe ends the game with no loser'); + const maid = O.take(mk(['2C 5D', '5H', 'QS 9D'], 0), 0, 0); + check(maid.hands[1].length === 0 && maid.out.indexOf(1) >= 0 && maid.turn === 2 && maid.phase === 'play', 'old maid: a player whose last card is taken is safe and skipped'); + const end = O.take(mk(['QS 5D', '5H'], 1), 1, 1); + check(end.phase === 'over' && end.result.loser === 0 && end.hands[0].length === 1, 'old maid: the last player holding a card loses'); + for (const players of [2, 3, 4]) { + let ended = 0, legal = true, kept = true, loser = true; + for (let g = 0; g < 40; g++) { + let st = O.deal(order(300 + g * 5 + players), players, g % players), rng = lcg(g + 9), n = 0; + while (st.phase === 'play' && n < 500) { + const idx = O.aiTake(st, st.turn, rng); + if (!O.canTake(st, st.turn, idx)) { legal = false; break; } + st = O.take(st, st.turn, idx); n++; + if (count(st) !== 51) { kept = false; break; } + } + if (st.phase === 'over') { ended++; if (st.result.loser >= 0 && !(st.hands[st.result.loser].length === 1 && Z.rank(st.hands[st.result.loser][0]) === 12)) loser = false; } + } + check(legal, 'old maid: ' + players + ' computers only ever take a card that is there'); + check(kept, 'old maid: ' + players + ' computers never lose or invent a card'); + check(ended === 40, 'old maid: all 40 games of ' + players + ' computers end'); + check(loser, 'old maid: the loser is always the one left with the odd queen'); + } +} + +// ── Snap ──────────────────────────────────────────────────────────────────── +if (sandbox.ZimiSnap) { + const S = sandbox.ZimiSnap; + const deck = seed => Z.shuffled(lcg(seed)).concat(Z.shuffled(lcg(seed + 1)).map(c => c + 52)); + const st0 = S.deal(deck(1), 0); + check(st0.stacks[0].length === 52 && st0.stacks[1].length === 52 && new Set(st0.stacks[0].concat(st0.stacks[1])).size === 104, 'snap: two stacks of 52 from two decks'); + const f1 = S.flip(st0), f2 = S.flip(f1); + check(f1.piles[0].length === 1 && f1.turn === 1 && f2.piles[1].length === 1 && f2.turn === 0, 'snap: the players turn their cards in turn, onto their own piles'); + const mk = (a, b, extra) => Object.assign({ stacks: [ids(extra && 's0' in extra ? extra.s0 : 'KS'), ids(extra && 's1' in extra ? extra.s1 : 'KH')], piles: [ids(a), ids(b)], won: [0, 0], turn: 0, phase: 'play', note: null, moves: 0, flips: 2 }, extra && extra.over || {}); + check(S.isMatch(mk('7C', '7D')) && !S.isMatch(mk('7C', '8D')) && !S.isMatch(mk('', '8D')) && S.isMatch(mk('2C 7S', '9D 7H')), 'snap: a match is the same rank on top of both piles, any suit'); + check(S.isMatch({ piles: [[0 + 52 * 1 + 4], [4]] }), 'snap: the second deck matches the first'); + const you = S.snap(mk('2D 7C', '5S 7D'), 0); + check(you.won[0] === 4 && you.piles[0].length === 0 && you.piles[1].length === 0 && you.note.kind === 'snap' && you.note.n === 4, 'snap: a match takes both piles'); + const zimi = S.snap(mk('7C', '7D'), 1); + check(zimi.won[1] === 2 && zimi.won[0] === 0, 'snap: whoever snaps gets the cards'); + const bad = S.snap(Object.assign(mk('7C', '8D'), { won: [5, 0] }), 0); + check(bad.won[0] === 3 && bad.piles[0].length === 1 && bad.note.kind === 'false' && bad.note.n === 2, 'snap: a snap with no match costs two won cards and the piles stay'); + check(S.snap(mk('7C', '8D'), 0).won[0] === 0 && S.snap(mk('7C', '8D'), 0).note.n === 0, 'snap: a false snap with nothing won costs nothing'); + const last = S.flip(mk('7C', '8D', { s0: '', s1: '8H' })); + check(S.cardsLeft(last) === 0 && last.phase === 'over' && last.piles[0].length === 1, 'snap: the last card with no match ends the game'); + const lastMatch = S.flip(mk('7C', '8D', { s0: '', s1: '7H' })); + check(lastMatch.phase === 'play' && S.isMatch(lastMatch) && S.close(lastMatch).phase === 'over', 'snap: a last card that matches leaves a moment to snap it'); + check(S.winner({ won: [3, 3] }) === -1 && S.winner({ won: [4, 3] }) === 0 && S.winner({ won: [2, 3] }) === 1, 'snap: the most cards won wins'); + // Zimi: never quicker than a third of a second, inside its level's spread, missing about as often as the level says. + for (const level of Object.keys(S.LEVELS)) { + const L = S.LEVELS[level], rng = lcg(7); + let min = 1e9, max = 0, miss = 0, n = 4000; + for (let i = 0; i < n; i++) { const r = S.reaction(level, rng); if (r === null) miss++; else { min = Math.min(min, r); max = Math.max(max, r); } } + check(min >= 350 && min >= L.from && max <= L.to, 'snap: ' + level + ' reacts in ' + min + ' to ' + max + ' ms, never inhuman'); + check(Math.abs(miss / n - L.miss) < 0.03, 'snap: ' + level + ' misses ' + Math.round(100 * miss / n) + ' percent of matches'); + check(L.to < L.flip, 'snap: ' + level + ' always answers before the next card'); + } + check(S.LEVELS.easy.from > S.LEVELS.medium.from && S.LEVELS.medium.from > S.LEVELS.hard.from, 'snap: harder levels are quicker'); + // A whole game: two quick snappers, every card accounted for, the game ends. + let st = S.deal(deck(11), 1), steps = 0, kept = true; + while (st.phase === 'play' && steps < 400) { + st = S.flip(st); steps++; + if (S.isMatch(st)) st = S.snap(st, steps % 2); + if (st.cardsLeft === 0) break; + if (S.cardsLeft(st) === 0 && st.phase === 'play') st = S.close(st); + const onTable = st.piles[0].length + st.piles[1].length + st.won[0] + st.won[1] + S.cardsLeft(st); + if (onTable !== 104) { kept = false; break; } + } + check(st.phase === 'over' && kept, 'snap: a whole game ends with all 104 cards accounted for'); +} + +// ── Oh Hell ───────────────────────────────────────────────────────────────── +if (sandbox.ZimiOhHell) { + const H = sandbox.ZimiOhHell; + check(H.LADDERS.short.join() === '5,4,3,2,1,2,3,4,5' && H.LADDERS.full.join() === '7,6,5,4,3,2,1,2,3,4,5,6,7', 'oh hell: the hands go down to one card and back up'); + for (const players of [3, 4, 5]) { + const st = H.newGame(order(70 + players), players, 'short', players - 1); + check(st.hands.every(h => h.length === 5) && st.hands.length === players, 'oh hell: ' + players + ' players, five cards each in the first hand'); + check(new Set(st.hands.flat().concat([st.trumpCard])).size === players * 5 + 1 && st.trump === Z.suit(st.trumpCard), 'oh hell: ' + players + ' players, no card twice, and the turned card names trump'); + check(st.turn === 0 && st.phase === 'bid' && st.dealer === players - 1, 'oh hell: bidding starts left of the dealer'); + } + // Bidding: the dealer may not make the bids add up to the number of tricks. + let st = H.newGame(order(5), 3, 'short', 2); + check(H.canBid(st, 0, 0) && H.canBid(st, 0, 5) && !H.canBid(st, 0, 6) && !H.canBid(st, 1, 1), 'oh hell: you bid 0 up to the cards in hand, in turn'); + st = H.placeBid(H.placeBid(st, 0, 2), 1, 1); + check(st.phase === 'bid' && H.forbiddenBid(st, 2) === 2 && !H.canBid(st, 2, 2) && H.canBid(st, 2, 1) && H.canBid(st, 2, 3), 'oh hell: the dealer cannot bid what makes 5 tricks in all'); + check(H.forbiddenBid(H.placeBid(H.placeBid(H.newGame(order(5), 3, 'short', 2), 0, 5), 1, 4), 2) === -1, 'oh hell: when the others have already bid past the tricks nothing is forbidden'); + st = H.placeBid(st, 2, 3); + check(st.phase === 'play' && st.turn === 0 && st.leader === 0, 'oh hell: when all have bid, play begins left of the dealer'); + // Playing and winning. + const play = (hands, trump, lead) => ({ players: hands.length, sizes: [3], handNo: 0, hands: hands.map(ids), bids: hands.map(() => 1), tricks: hands.map(() => 0), trump: SU.indexOf(trump), trumpCard: 0, dealer: 2, turn: lead, leader: lead, trick: [], played: [], scores: hands.map(() => 0), phase: 'play', result: null, moves: 0 }); + const p = play(['7S 2C', '9S KH', 'AS 3D'], 'H', 0); + check(H.legalPlays(p, 0).length === 2, 'oh hell: you may lead anything'); + const p1 = H.playCard(p, 0, id('7S')); + check(H.legalPlays(p1, 1).join() === ids('9S').join() && H.isLegal(p1, 1, id('9S')) && !H.isLegal(p1, 1, id('KH')), 'oh hell: you must follow suit'); + check(H.legalPlays(H.playCard(p, 0, id('2C')), 1).length === 2, 'oh hell: with no card of the suit led you may play anything'); + const trick = (s, trump) => H.trickWinner(s.split(' ').map((c, i) => ({ seat: i, id: id(c) })), SU.indexOf(trump)); + check(trick('7S 9S AS', 'H') === 2 && trick('7S 9S AS', 'S') === 2 && trick('7S 9H 3C', 'H') === 1 && trick('7S 9H 3H', 'H') === 1 && trick('7S AH 3C', 'D') === 0, 'oh hell: the highest trump wins, else the highest card of the suit led'); + check(trick('7S AD 3C', 'D') === 1 && trick('2H KS AD', 'H') === 0, 'oh hell: a trump beats a higher card of the suit led'); + // Scoring. + check(H.handPoints(2, 2) === 12 && H.handPoints(0, 0) === 10 && H.handPoints(2, 3) === 3 && H.handPoints(2, 0) === 0, 'oh hell: a point a trick, and ten more for taking exactly what you bid'); + check(H.winners([3, 9, 9]).join() === '1,2' && H.winners([4, 2, 1]).join() === '0', 'oh hell: the seats with the most points win'); + // Computer players: legal bids and plays, every card played once, tricks add up, the game ends. + for (const players of [3, 4, 5]) for (const ladder of ['short', 'full']) { + let games = 0, ok = true, exact = 0, made = 0, total = 0; + for (let g = 0; g < 8; g++) { + let s = H.newGame(order(500 + g * 11 + players), players, ladder, g % players), guard = 0; + while (s.phase !== 'over' && guard++ < 4000) { + if (s.phase === 'bid') { + const b = H.aiBid(s, s.turn); + if (!H.canBid(s, s.turn, b)) { ok = false; break; } + s = H.placeBid(s, s.turn, b); + } else if (s.phase === 'play') { + if (s.trick.length === players) { + s = H.resolveTrick(s); + if (s.phase === 'handEnd' || s.phase === 'over') { + const size = s.sizes[s.handNo]; + if (s.tricks.reduce((a, b) => a + b, 0) !== size) ok = false; + s.result.made.forEach(m => { total++; if (m) made++; }); + } + continue; + } + const c = H.aiPick(s, s.turn); + if (!H.isLegal(s, s.turn, c)) { ok = false; break; } + s = H.playCard(s, s.turn, c); + } else if (s.phase === 'handEnd') s = H.nextHand(s, order(900 + guard)); + } + if (s.phase === 'over') games++; + } + check(ok, 'oh hell: ' + players + ' computers, ' + ladder + ': every bid and play is legal and the tricks add up'); + check(games === 8, 'oh hell: ' + players + ' computers, ' + ladder + ': all 8 games end'); + check(made / total > 0.2, 'oh hell: ' + players + ' computers, ' + ladder + ': they make their bid ' + Math.round(100 * made / total) + ' percent of the time, more than chance'); + } +} + +// ── Cheat ─────────────────────────────────────────────────────────────────── +if (sandbox.ZimiCheat) { + const C = sandbox.ZimiCheat; + const total = st => st.hands.reduce((n, h) => n + h.length, 0) + st.pile.length; + for (const players of [2, 3, 4]) { + const st = C.deal(order(20 + players), players, 0); + check(total(st) === 52 && st.hands.every(h => h.length >= Math.floor(52 / players)) && st.claim === 1 && st.phase === 'play', 'cheat: ' + players + ' players, all 52 cards are dealt and the first rank is the ace'); + } + const mk = (hands, claim, turn, pile) => ({ players: hands.length, hands: hands.map(ids), pile: ids(pile || ''), claim: claim || 7, turn: turn || 0, phase: 'play', callers: [], last: null, turns: 0, winner: -1, moves: 0 }); + const a = mk(['7C 7D 2S 9H', '3C 4D', 'KS']); + check(C.canPlay(a, 0, ids('7C')) && C.canPlay(a, 0, ids('7C 7D 2S 9H')) && !C.canPlay(a, 0, ids('7C 7C')) && !C.canPlay(a, 0, ids('3C')) && !C.canPlay(a, 1, ids('3C')) && !C.canPlay(a, 0, []), 'cheat: you play one to four cards from your hand, in turn'); + check(!C.canPlay(mk(['2C 3C 4C 5C 6C'], 7, 0), 0, ids('2C 3C 4C 5C 6C')), 'cheat: never more than four cards'); + const p = C.play(a, 0, ids('7C 2S')); + check(p.phase === 'call' && p.pile.length === 2 && p.hands[0].length === 2 && p.callers.join() === '1,2' && p.last.count === 2 && p.last.rank === 7 && C.decider(p) === 1, 'cheat: a play goes face down on the pile and the others say, in order'); + check(!C.wasTrue(p.last) && C.wasTrue(C.play(a, 0, ids('7C 7D')).last), 'cheat: a play is true when every card is the rank said'); + // Nobody calls. + const n1 = C.decide(p, 1, false), n2 = C.decide(n1, 2, false); + check(n1.phase === 'call' && C.decider(n1) === 2 && n2.phase === 'play' && n2.turn === 1 && n2.claim === 8 && n2.pile.length === 2, 'cheat: with no call the pile stays, the turn and the rank move on'); + // A call that finds a lie. + const c1 = C.decide(p, 1, true); + check(c1.hands[0].length === 4 && c1.pile.length === 0 && c1.last.call.lying && c1.last.call.loser === 0 && c1.turn === 1 && c1.claim === 8, 'cheat: a call that finds a wrong card makes the player take the pile'); + // A call that finds the truth. + const honest = C.play(a, 0, ids('7C 7D')), c2 = C.decide(honest, 2, false), c3 = C.decide(C.decide(honest, 1, false), 2, true); + check(c3.hands[2].length === 3 && !c3.last.call.lying && c3.last.call.loser === 2 && c3.pile.length === 0, 'cheat: a call that finds only the rank said makes the caller take the pile'); + check(C.decide(p, 2, true) === p, 'cheat: only the player whose turn it is to say can say'); + // Winning: the last cards, and surviving the call. + const w = mk(['7C', '3C 4D', 'KS']); + const out = C.play(w, 0, ids('7C')); + check(out.hands[0].length === 0 && out.phase === 'call', 'cheat: going out still lets the others call'); + const won = C.decide(C.decide(out, 1, false), 2, false); + check(won.phase === 'over' && won.winner === 0, 'cheat: going out and not being called wins'); + const wonTrue = C.decide(out, 1, true); + check(wonTrue.phase === 'over' && wonTrue.winner === 0 && wonTrue.hands[1].length === 3, 'cheat: going out honestly and being called wins, and the caller takes the pile'); + const caught = C.decide(C.play(mk(['9S', '3C 4D', 'KS']), 0, ids('9S')), 1, true); + check(caught.phase === 'play' && caught.hands[0].length === 1 && caught.winner === -1, 'cheat: going out with a lie and being called takes the pile and plays on'); + check(C.play(mk(['7C 7D 7H 7S 2C', 'KS']), 0, ids('7C 7D 7H 7S')).last.count === 4, 'cheat: four of the rank is the most there is'); + // The ranks go round. + let r = mk(['AC 2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KC AD 2D', '2S 3S']), claims = []; + r.claim = 12; r.turn = 0; + r = C.decide(C.play(r, 0, ids('2C')), 1, false); claims.push(r.claim); + r = C.decide(C.play(r, 1, ids('2S')), 0, false); claims.push(r.claim); + check(claims.join() === '13,1', 'cheat: the rank after the king is the ace'); + // The computer. + const ai = C.aiPlay(mk(['7C 7D 2S 9H', '3C 4D', 'KS']), 0, lcg(3)); + check(ai.filter(c => Z.rank(c) === 7).length === 2 && ai.length <= 3 && C.canPlay(mk(['7C 7D 2S 9H', '3C 4D', 'KS']), 0, ai), 'cheat: with the rank due in hand the computer plays it'); + const bluff = C.aiPlay(mk(['2C 3D 9S', '3C 4D', 'KS']), 0, lcg(3)); + check(bluff.length >= 1 && bluff.length <= 2 && bluff.every(c => Z.rank(c) !== 7), 'cheat: without the rank the computer bluffs with one or two cards'); + const sure = C.play(mk(['7C', '7D 7H 7S 2C', 'KS']), 0, ids('7C')); + const sure2 = Object.assign({}, sure, { last: Object.assign({}, sure.last, { count: 2, ids: ids('7C 9D') }) }); + check(C.aiCall(sure2, 1, () => 0.99) === true, 'cheat: the computer always calls what cannot be true (it holds three of the rank, two are said)'); + const calm = C.aiCall(C.play(mk(['7C', '2C 3C 4C 5C 6C 8C', 'KS']), 0, ids('7C')), 1, () => 0.5); + check(calm === false || calm === true, 'cheat: the computer decides'); + // Whole games. + for (const players of [2, 3, 4]) { + let ended = 0, legal = true, kept = true, calls = 0, lies = 0, plays = 0, caught = 0; + for (let g = 0; g < 30; g++) { + let s = C.deal(order(800 + g * 3 + players), players, g % players), rng = lcg(g + 31), guard = 0; + while (s.phase !== 'over' && guard++ < 6000) { + if (s.phase === 'play') { + const ids2 = C.aiPlay(s, s.turn, rng); + if (!C.canPlay(s, s.turn, ids2)) { legal = false; break; } + s = C.play(s, s.turn, ids2); plays++; if (!C.wasTrue(s.last)) lies++; + } else { + const who = C.decider(s), call = C.aiCall(s, who, rng); + if (call) { calls++; if (!C.wasTrue(s.last)) caught++; } + s = C.decide(s, who, call); + } + if (total(s) !== 52) { kept = false; break; } + } + if (s.phase === 'over') ended++; + } + check(legal, 'cheat: ' + players + ' computers only play what they may'); + check(kept, 'cheat: ' + players + ' computers never lose or invent a card'); + check(ended === 30, 'cheat: all 30 games of ' + players + ' computers end'); + check(lies / plays > 0.1 && lies / plays < 0.9, 'cheat: ' + players + ' computers bluff ' + Math.round(100 * lies / plays) + ' percent of their plays, not never, not always'); + check(calls > 0 && caught / calls > 0.4, 'cheat: ' + players + ' computers call sensibly, ' + Math.round(100 * caught / Math.max(1, calls)) + ' percent of their calls find a lie'); + } +} + +console.log('\n' + passed + ' passed, ' + failures + ' failed'); +process.exit(failures ? 1 : 0); diff --git a/tests/test_games_family_cards_browser.py b/tests/test_games_family_cards_browser.py new file mode 100644 index 000000000..1cbcde019 --- /dev/null +++ b/tests/test_games_family_cards_browser.py @@ -0,0 +1,458 @@ +"""The family card games (Go Fish, Old Maid, Snap, Oh Hell, Cheat) played through on a 390 px touch phone, a game to its end sheet. + +Each is opened with its computer players, played by touch the way a person does (tap a card, tap a player), until the end sheet +comes up; nothing may throw, and the table must fit the phone (no sideways scroll). + +Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_games_family_cards_browser.py -v +""" + +import functools +import http.server +import os +import threading + +import pytest + +GAMES = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "zimi", + "builtin", + "games", +) +PHONE = {"width": 390, "height": 844} + + +@pytest.fixture(scope="module") +def site(): + handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=GAMES) + handler.log_message = lambda *a, **k: None + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d/" % srv.server_address[1] + srv.shutdown() + + +@pytest.fixture(scope="module") +def browser(): + sync_api = pytest.importorskip("playwright.sync_api") + with sync_api.sync_playwright() as p: + try: + b = p.chromium.launch() + except Exception as e: + pytest.skip("Chromium is not installed: %s" % e) + yield b + b.close() + + +@pytest.fixture +def phone(browser): + ctx = browser.new_context( + viewport=PHONE, device_scale_factor=2, is_mobile=True, has_touch=True + ) + page = ctx.new_page() + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.errors = errors + yield page + ctx.close() + + +def card_point(page, card_id): + """Where to touch a card of your hand: a strip near its left edge, clear of the card laid over it.""" + return page.evaluate( + """(id) => { const e = document.querySelector('.zc-card[data-id="' + id + '"]'); if (!e) return null; + const b = e.getBoundingClientRect(); return { x: b.x + Math.min(10, b.width / 3), y: b.y + b.height * 0.25 }; }""", + card_id, + ) + + +def tap_card(page, card_id): + """Touch a card once it has stopped moving (a deal or a sweep in flight would move it from under the finger).""" + p = card_point(page, card_id) + for _ in range(20): + assert p, "card %s is not on the table" % card_id + page.wait_for_timeout(120) + q = card_point(page, card_id) + if q == p: + break + p = q + page.touchscreen.tap(p["x"], p["y"]) + + +def end_sheet_up(page): + return page.locator(".gs-end, .ar-sheet, .zc-sheet").count() > 0 + + +def no_sideways_scroll(page): + return page.evaluate( + "() => document.documentElement.scrollWidth <= window.innerWidth + 1" + ) + + +def open_game(page, site, name, wait_for): + page.goto(site + name + ".html") + page.wait_for_function(wait_for, timeout=8000) + page.wait_for_selector(".zc-card", state="attached", timeout=8000) + + +def test_go_fish_played_to_the_end_by_touch(phone, site): + page = phone + open_game( + page, + site, + "gofish", + "() => window.ZimiGoFish && window.ZimiGoFish.session && window.ZimiGoFish.session.state", + ) + assert no_sideways_scroll(page) + for _ in range(400): + st = page.evaluate("() => window.ZimiGoFish.session.state") + if st["phase"] == "over": + break + if st["turn"] == 0 and st["hands"][0]: + tap_card(page, st["hands"][0][0]) + page.wait_for_timeout(120) + else: + page.wait_for_timeout(250) + st = page.evaluate("() => window.ZimiGoFish.session.state") + assert st["phase"] == "over", "the game never ended after %d moves" % st["moves"] + page.wait_for_function( + "() => document.querySelector('.gs-sheet, .ar-sheet, .zc-sheet, .gs-end')", + timeout=8000, + ) + assert not phone.errors + + +def saved_page(browser, site, name, key, state): + """A page opened with `state` as the game's kept save (the page takes it up as the game left off).""" + import json + import time + + ctx = browser.new_context( + viewport=PHONE, device_scale_factor=2, is_mobile=True, has_touch=True + ) + save = json.dumps( + { + "v": 1, + "at": int(time.time() * 1000), + "data": { + "id": key, + "state": state, + "history": [], + "ms": 4000, + "ending": None, + }, + } + ) + ctx.add_init_script( + "try { localStorage.setItem('zimi.games.save.%s', %s); } catch (e) {}" + % (key, json.dumps(save)) + ) + page = ctx.new_page() + page.errors = [] + page.on("pageerror", lambda e: page.errors.append(str(e))) + page.goto(site + name + ".html") + page.ctx = ctx + return page + + +def sheet_up(page): + return page.evaluate( + "() => !!document.querySelector('.gs-sheet, .ar-sheet, .zc-sheet, .gs-end')" + ) + + +def test_old_maid_played_to_the_end_by_touch(phone, site): + page = phone + open_game( + page, + site, + "oldmaid", + "() => window.ZimiOldMaid && window.ZimiOldMaid.session && window.ZimiOldMaid.session.state", + ) + assert no_sideways_scroll(page) + for _ in range(300): + st = page.evaluate("() => window.ZimiOldMaid.session.state") + if st["phase"] == "over": + break + if st["turn"] == 0: + source = page.evaluate( + "() => window.ZimiOldMaid.source(window.ZimiOldMaid.session.state)" + ) + tap_card(page, st["hands"][source][0]) + page.wait_for_timeout(150) + else: + page.wait_for_timeout(250) + st = page.evaluate("() => window.ZimiOldMaid.session.state") + assert st["phase"] == "over" + assert st["result"]["loser"] >= 0 and len(st["hands"][st["result"]["loser"]]) == 1 + page.wait_for_function( + "() => document.querySelector('.gs-sheet, .ar-sheet, .zc-sheet, .gs-end')", + timeout=8000, + ) + assert not phone.errors + + +# A Snap with a few cards left: a match on show (the restored game does not hurry Zimi into it), then four cards with no match. +SNAP_END = { + "stacks": [[2, 3, 4], [8, 9, 10]], # ranks 3, 4, 5 and 9, 10, J + "piles": [[6], [6 + 13]], # sevens of clubs and diamonds + "won": [0, 0], + "turn": 0, + "phase": "play", + "note": None, + "moves": 4, + "flips": 2, +} + + +def test_snap_a_tap_takes_the_match_and_the_game_ends(browser, site): + page = saved_page(browser, site, "snap", "snap", SNAP_END) + page.wait_for_selector(".sn-snap", timeout=8000) + page.wait_for_function( + "() => window.ZimiSnap.isMatch(window.ZimiSnap.session.state)", timeout=8000 + ) + page.touchscreen.tap( + *[ + page.locator(".sn-snap").bounding_box()[k] + + page.locator(".sn-snap").bounding_box()[d] / 2 + for k, d in (("x", "width"), ("y", "height")) + ] + ) + page.wait_for_function( + "() => window.ZimiSnap.session.state.won[0] === 2", timeout=3000 + ) + assert no_sideways_scroll(page) + page.wait_for_function( + "() => window.ZimiSnap.session.state.phase === 'over'", timeout=20000 + ) + page.wait_for_function( + "() => document.querySelector('.gs-sheet, .ar-sheet, .zc-sheet, .gs-end')", + timeout=8000, + ) + assert not page.errors + page.ctx.close() + + +def test_snap_with_no_match_costs_nothing_to_nothing_and_says_so(browser, site): + state = dict(SNAP_END, piles=[[6], [7]], won=[5, 0]) + page = saved_page(browser, site, "snap", "snap", state) + page.wait_for_selector(".sn-snap", timeout=8000) + box = page.locator(".sn-snap").bounding_box() + page.touchscreen.tap(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) + page.wait_for_function( + "() => window.ZimiSnap.session.state.won[0] === 3", timeout=3000 + ) + assert page.evaluate("() => window.ZimiSnap.session.state.note.kind") == "false" + assert not page.errors + page.ctx.close() + + +def test_snap_phone_fit(phone, site): + page = phone + open_game( + page, + site, + "snap", + "() => window.ZimiSnap && window.ZimiSnap.session && window.ZimiSnap.session.state", + ) + assert no_sideways_scroll(page) + box = page.locator(".sn-snap").bounding_box() + assert box["height"] >= 44 and box["x"] >= 0 and box["x"] + box["width"] <= 390 + assert not phone.errors + + +def bid_by_touch(page, n): + page.locator(".ct-choice", has_text=str(n)).first.tap() + + +def test_oh_hell_first_hand_by_touch_to_the_hand_sheet(phone, site): + page = phone + open_game( + page, + site, + "ohhell", + "() => window.ZimiOhHell && window.ZimiOhHell.session && window.ZimiOhHell.session.state", + ) + assert no_sideways_scroll(page) + for _ in range(400): + st = page.evaluate("() => window.ZimiOhHell.session.state") + if st["phase"] == "handEnd" or st["phase"] == "over" or sheet_up(page): + break + if st["phase"] == "bid" and st["turn"] == 0: + bad = page.evaluate( + "() => window.ZimiOhHell.forbiddenBid(window.ZimiOhHell.session.state, 0)" + ) + bid_by_touch(page, 1 if bad != 1 else 2) + page.wait_for_timeout(200) + elif ( + st["phase"] == "play" + and st["turn"] == 0 + and len(st["trick"]) < st["players"] + ): + legal = page.evaluate( + "() => window.ZimiOhHell.legalPlays(window.ZimiOhHell.session.state, 0)" + ) + tap_card(page, legal[0]) + page.wait_for_timeout(200) + else: + page.wait_for_timeout(250) + page.wait_for_function( + "() => document.querySelector('.gs-sheet, .ar-sheet, .zc-sheet, .gs-end')", + timeout=10000, + ) + st = page.evaluate("() => window.ZimiOhHell.session.state") + assert st["handNo"] == 0 and sum(st["tricks"]) == 5 and st["phase"] == "handEnd" + assert sum(st["scores"]) == sum(max(0, t) for t in st["tricks"]) + 10 * sum( + 1 for t, b in zip(st["tricks"], st["bids"]) if t == b + ) + assert not phone.errors + + +def test_oh_hell_last_hand_ends_the_game(browser, site): + probe = browser.new_page() + probe.goto(site + "ohhell.html") + probe.wait_for_function("() => window.ZimiOhHell") + state = probe.evaluate( + """() => { const H = window.ZimiOhHell, Z = window.ZimiCards; + let st = H.dealHand(Z.shuffled(Math.random), 3, H.LADDERS.short, 8, [20, 15, 12], 2); + st = H.placeBid(st, 0, 1); st = H.placeBid(st, 1, 0); st = H.placeBid(st, 2, 0); return st; }""" + ) + probe.close() + page = saved_page(browser, site, "ohhell", "ohhell", state) + page.wait_for_selector(".zc-card", state="attached", timeout=10000) + for _ in range(60): + st = page.evaluate("() => window.ZimiOhHell.session.state") + if st["phase"] == "over": + break + if st["turn"] == 0 and len(st["trick"]) < 3 and st["hands"][0]: + legal = page.evaluate( + "() => window.ZimiOhHell.legalPlays(window.ZimiOhHell.session.state, 0)" + ) + tap_card(page, legal[0]) + page.wait_for_timeout(300) + st = page.evaluate("() => window.ZimiOhHell.session.state") + assert st["phase"] == "over" + page.wait_for_function( + "() => document.querySelector('.gs-sheet, .ar-sheet, .zc-sheet, .gs-end')", + timeout=10000, + ) + assert not page.errors + page.ctx.close() +def cheat_total(page): + return page.evaluate( + "() => { const s = window.ZimiCheat.session.state; return s.hands.reduce((n, h) => n + h.length, 0) + s.pile.length; }" + ) + + +def test_cheat_a_few_turns_by_touch_keep_every_card(phone, site): + page = phone + open_game( + page, + site, + "cheat", + "() => window.ZimiCheat && window.ZimiCheat.session && window.ZimiCheat.session.state", + ) + assert no_sideways_scroll(page) + mine_played = 0 + for _ in range(200): + st = page.evaluate("() => window.ZimiCheat.session.state") + if st["phase"] == "over" or mine_played >= 3: + break + if st["phase"] == "call" and st["callers"][0] == 0: + page.locator(".ct-choice", has_text="Let it go").first.tap() + page.wait_for_timeout(150) + elif st["phase"] == "play" and st["turn"] == 0: + tap_card(page, st["hands"][0][0]) + page.wait_for_timeout(150) + assert page.locator(".ct-choice.ct-primary").count() == 1 + page.locator(".ct-choice.ct-primary").first.tap() + mine_played += 1 + page.wait_for_timeout(200) + else: + page.wait_for_timeout(250) + assert mine_played >= 1 + assert cheat_total(page) == 52 + assert not phone.errors + + +# One card left in your hand, the rank to say: play it, and when the others let it go (or call and find the truth) you are out. +CHEAT_END = { + "players": 3, + "hands": [ + [6], + [0, 14, 28, 40, 41], + [1, 2, 15, 16, 17], + ], # you hold the seven of clubs + "pile": [3, 4, 5], + "claim": 7, + "turn": 0, + "phase": "play", + "callers": [], + "last": None, + "tells": [{"called": 0, "lied": 0}] * 3, + "turns": 6, + "winner": -1, + "moves": 6, +} + + +def test_cheat_going_out_wins_the_game(browser, site): + page = saved_page(browser, site, "cheat", "cheat", CHEAT_END) + page.wait_for_selector(".zc-card", state="attached", timeout=10000) + tap_card(page, 6) + page.locator(".ct-choice.ct-primary").first.tap() + for _ in range(60): + st = page.evaluate("() => window.ZimiCheat.session.state") + if st["phase"] == "over": + break + if st["phase"] == "call" and st["callers"][0] == 0: + page.locator(".ct-choice", has_text="Let it go").first.tap() + page.wait_for_timeout(300) + st = page.evaluate("() => window.ZimiCheat.session.state") + assert st["phase"] == "over" and st["winner"] == 0 + page.wait_for_function( + "() => document.querySelector('.gs-sheet, .ar-sheet, .zc-sheet, .gs-end')", + timeout=10000, + ) + assert not page.errors + page.ctx.close() +def test_go_fish_with_three_players_asks_by_choosing_whom(browser, site): + ctx = browser.new_context( + viewport=PHONE, device_scale_factor=2, is_mobile=True, has_touch=True + ) + ctx.add_init_script( + "try { localStorage.setItem('zimi.games.gofish.players', '3'); } catch (e) {}" + ) + page = ctx.new_page() + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + open_game( + page, + site, + "gofish", + "() => window.ZimiGoFish && window.ZimiGoFish.session && window.ZimiGoFish.session.state", + ) + assert page.evaluate("() => window.ZimiGoFish.session.state.players") == 3 + page.wait_for_function("() => document.querySelector('.ct-status-text') && document.querySelector('.ct-status-text').textContent", timeout=8000) + for _ in range(60): + st = page.evaluate("() => window.ZimiGoFish.session.state") + if st["turn"] == 0: + break + page.wait_for_timeout(300) + st = page.evaluate("() => window.ZimiGoFish.session.state") + assert st["turn"] == 0 + tap_card(page, st["hands"][0][0]) + page.wait_for_selector(".ct-choice", timeout=3000) + names = page.locator(".ct-choice").all_inner_texts() + assert len(names) == 3, names # two players to ask, and Cancel + asked_before = st["moves"] + page.locator(".ct-choice").first.tap() + page.wait_for_function( + "(n) => window.ZimiGoFish.session.state.moves > n", + arg=asked_before, + timeout=3000, + ) + assert page.evaluate("() => window.ZimiGoFish.session.state.last.seat") == 0 + assert no_sideways_scroll(page) + assert not errors + ctx.close() diff --git a/tests/test_games_fans_all_browser.py b/tests/test_games_fans_all_browser.py new file mode 100644 index 000000000..86998f40f --- /dev/null +++ b/tests/test_games_fans_all_browser.py @@ -0,0 +1,131 @@ +"""Every vertical fan follows one rule, in every card game that has one, and no card game runs off the side of a phone. + +A covered face-up card shows its index row only (39.5 of 140 units of the card), whatever its rank: no strip of a court's picture, and +one step for the whole column. The deal's last card in each column is whole and inside the screen. Seen on the dealt table of every +solitaire with columns, at 390x844. + +Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_games_fans_all_browser.py -v +(ZIMI_GAMES_DIR points the test at another copy of the games folder, to prove it fails on an older one.) +""" + +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from games_wait import settled # noqa: E402 +from test_games_court_fill_browser import LAYOUT, NOT_DEALING, served # noqa: E402,F401 +from test_games_persist_browser import browser # noqa: E402,F401 + +pytest.importorskip("playwright") + +INDEX_ROW_SHARE = 39.5 / 140 +FANS = [ + "solitaire", + "spider", + "freecell", + "golf", + "yukon", + "scorpion", + "canfield", + "beleaguered", + "eightoff", + "fortythieves", +] +DEALS_NO_FAN = {"solitaire", "spider", "canfield"} # one face-up card to a column when dealt; test_games_court_fill_browser builds their fans +EVERY_CARD_GAME = FANS + [ + "calculation", + "acesup", + "accordion", + "montecarlo", + "pyramid", + "tripeaks", + "ohhell", + "cheat", + "belote", + "bigtwo", + "bridge", + "canasta", + "crazyeights", + "cribbage", + "durak", + "euchre", + "gin", + "gofish", + "hearts", + "koikoi", + "oldmaid", + "scopa", + "skat", + "snap", + "spades", + "teenpatti", + "tienlen", + "truco", +] + +COLUMNS = """() => { + const cols = {}; + document.querySelectorAll('.zc-card:not(.zc-off)').forEach(e => { + const r = e.getBoundingClientRect(), k = Math.round(r.left); + (cols[k] = cols[k] || []).push({ id: e.dataset.id, top: r.top, bottom: r.bottom, h: r.height, up: !e.classList.contains('zc-down'), + frame: (() => { const f = e.querySelector('.zc-ct-row .zc-rule'); return f && f.getBoundingClientRect().width ? f.getBoundingClientRect().top - r.top : null; })() }); + }); + return Object.values(cols).map(c => c.sort((a, b) => a.top - b.top)); +}""" + + +def open_game(browser, served, name, width=390, height=844): + ctx = browser.new_context( + viewport={"width": width, "height": height}, is_mobile=True, has_touch=True + ) + page = ctx.new_page() + page.goto("%s/%s.html" % (served, name)) + page.wait_for_selector(".zc-card:not(.zc-off)") + page.wait_for_function(NOT_DEALING) + settled(page, LAYOUT) + return ctx, page + + +@pytest.mark.parametrize("name", FANS) +def test_a_covered_card_shows_its_index_row_only(browser, served, name): + ctx, page = open_game(browser, served, name) + cols = page.evaluate(COLUMNS) + steps = 0 + for col in cols: + for a, b in zip(col, col[1:]): + if ( + not (a["up"] and b["up"]) + or b["top"] - a["top"] > a["h"] * 0.9 + or b["top"] - a["top"] < 1 + ): + continue # a face-down card, a pile on one spot, a gap between two piles: not a fan step + steps += 1 + assert b["top"] - a["top"] <= a["h"] * INDEX_ROW_SHARE + 1, ( + name, + a, + b, + ) # one rule: the index row at most + if a["frame"] is not None: + assert b["top"] - a["top"] <= a["frame"] + 0.5, ( + name, + a, + b, + ) # nothing of a court's frame or picture shows + assert steps or name in DEALS_NO_FAN, name # the dealt table has a fan to measure + ctx.close() + + +@pytest.mark.parametrize("name", EVERY_CARD_GAME) +def test_no_card_runs_off_a_phone(browser, served, name): + ctx, page = open_game(browser, served, name) + r = page.evaluate( + """() => { const cs = [...document.querySelectorAll('.zc-card:not(.zc-off)')].filter(e => getComputedStyle(e).visibility !== 'hidden').map(e => e.getBoundingClientRect()); + return { left: Math.min(...cs.map(r => r.left)), right: Math.max(...cs.map(r => r.right)), W: innerWidth, bottom: Math.max(...cs.map(r => r.bottom)), H: innerHeight, sw: document.documentElement.scrollWidth }; }""" + ) + assert r["left"] >= -0.5 and r["right"] <= r["W"] + 0.5 and r["sw"] <= r["W"], ( + name, + r, + ) + ctx.close() diff --git a/tests/test_games_freecell_hint_browser.py b/tests/test_games_freecell_hint_browser.py index 00cdba7de..f50976175 100644 --- a/tests/test_games_freecell_hint_browser.py +++ b/tests/test_games_freecell_hint_browser.py @@ -83,8 +83,15 @@ def test_the_menus_hint_tile_is_named_in_the_players_language(browser, site): def test_the_hints_glow_is_a_ring_that_shows_on_a_pale_card(browser, site): pg = _page(browser, site) - pg.evaluate("() => document.getElementById('zc-hint').click()") - pg.wait_for_selector(".zc-card.zc-glow", timeout=10000) + # The tile is in the page before the deal has settled and its handler may not answer yet (a slow runner): ask again until it does. + for _ in range(8): + pg.evaluate("() => document.getElementById('zc-hint').click()") + try: + pg.wait_for_selector(".zc-card.zc-glow", timeout=2500) + break + except Exception: + continue + pg.wait_for_selector(".zc-card.zc-glow", timeout=5000) shadow = pg.evaluate( "() => getComputedStyle(document.querySelector('.zc-card.zc-glow')).boxShadow" ) diff --git a/tests/test_games_ohhell_five_browser.py b/tests/test_games_ohhell_five_browser.py new file mode 100644 index 000000000..89d7e5717 --- /dev/null +++ b/tests/test_games_ohhell_five_browser.py @@ -0,0 +1,277 @@ +"""Oh Hell seats five: five chips, four hands that do not touch, a hand played to its sheet by touch and a game that ends. + +Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_games_ohhell_five_browser.py -v +""" + + +import functools +import http.server +import json +import os +import threading +import time + +import pytest + +GAMES = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "zimi", + "builtin", + "games", +) +PHONE = {"width": 390, "height": 844} + + +@pytest.fixture(scope="module") +def site(): + handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=GAMES) + handler.log_message = lambda *a, **k: None + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d/" % srv.server_address[1] + srv.shutdown() + + +@pytest.fixture(scope="module") +def browser(): + sync_api = pytest.importorskip("playwright.sync_api") + with sync_api.sync_playwright() as p: + try: + b = p.chromium.launch() + except Exception as e: + pytest.skip("Chromium is not installed: %s" % e) + yield b + b.close() + + +@pytest.fixture +def phone(browser): + ctx = browser.new_context( + viewport=PHONE, device_scale_factor=2, is_mobile=True, has_touch=True + ) + page = ctx.new_page() + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.errors = errors + yield page + ctx.close() + + +def open_game(page, site, name, wait_for, minimum_cards=1): + page.goto(site + name + ".html") + page.wait_for_function(wait_for, timeout=8000) + page.wait_for_function( + "(n) => document.querySelectorAll('.zc-card[data-id]').length >= n", + arg=minimum_cards, + timeout=8000, + ) + page.wait_for_timeout(2500) # the deal's cards fly in + + +def card_point(page, card_id): + return page.evaluate( + """(id) => { const e = document.querySelector('.zc-card[data-id="' + id + '"]'); if (!e) return null; + const b = e.getBoundingClientRect(); return { x: b.x + Math.min(10, b.width / 3), y: b.y + b.height * 0.25 }; }""", + card_id, + ) + + +def tap_card(page, card_id): + p = card_point(page, card_id) + for _ in range(20): + assert p, "card %s is not on the table" % card_id + page.wait_for_timeout(120) + q = card_point(page, card_id) + if q == p: + break + p = q + page.touchscreen.tap(p["x"], p["y"]) + + + +# ── Oh Hell, five players ──────────────────────────────────────────────────── + +OH = "window.ZimiOhHell" +RECT = """(ids) => ids.map(id => { const e = document.querySelector('.zc-card[data-id="' + id + '"]'); if (!e) return null; + const b = e.getBoundingClientRect(); return [b.left, b.top, b.right, b.bottom]; })""" + + +def five_at_table(browser): + ctx = browser.new_context( + viewport=PHONE, device_scale_factor=2, is_mobile=True, has_touch=True + ) + ctx.add_init_script( + "try { localStorage.setItem('zimi.games.ohhell.players', '5'); } catch (e) {}" + ) + page = ctx.new_page() + page.errors = [] + page.on("pageerror", lambda e: page.errors.append(str(e))) + return ctx, page + + +def boxes_touch(a, b): + return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3] + + +def test_oh_hell_seats_five_without_the_hands_touching(browser, site): + ctx, page = five_at_table(browser) + open_game( + page, + site, + "ohhell", + "() => window.ZimiOhHell && window.ZimiOhHell.session && window.ZimiOhHell.session.state", + 20, + ) + st = page.evaluate("() => window.ZimiOhHell.session.state") + assert ( + st["players"] == 5 + and len(st["hands"]) == 5 + and all(len(h) == 5 for h in st["hands"]) + ) + assert len({c for h in st["hands"] for c in h} | {st["trumpCard"]}) == 26 + assert page.locator(".ct-chip:not(.ct-trump)").count() == 5 + assert page.evaluate("() => document.documentElement.scrollWidth <= innerWidth + 1") + # Each of the four other hands is a group of cards of its own, all on the phone, none over another. + groups = [] + for r in range(1, 5): + ids = st["hands"][r] + boxes = page.evaluate(RECT, ids) + assert all(boxes), "a hand is missing from the table" + assert all(b[0] >= 0 and b[2] <= PHONE["width"] and b[1] >= 0 for b in boxes) + groups.append( + [ + min(b[0] for b in boxes), + min(b[1] for b in boxes), + max(b[2] for b in boxes), + max(b[3] for b in boxes), + ] + ) + for i in range(4): + for j in range(i + 1, 4): + assert not boxes_touch( + groups[i], groups[j] + ), "hands %d and %d overlap: %r %r" % (i + 1, j + 1, groups[i], groups[j]) + mine = page.evaluate(RECT, st["hands"][0]) + assert not any( + boxes_touch( + [ + min(b[0] for b in mine), + min(b[1] for b in mine), + max(b[2] for b in mine), + max(b[3] for b in mine), + ], + g, + ) + for g in groups + ) + assert not page.errors + ctx.close() + + +def sheet_up(page): + return page.evaluate( + "() => !!document.querySelector('.gs-sheet, .ar-sheet, .zc-sheet, .gs-end')" + ) + + +def test_oh_hell_five_played_by_touch_to_the_hand_sheet(browser, site): + ctx, page = five_at_table(browser) + open_game( + page, + site, + "ohhell", + "() => window.ZimiOhHell && window.ZimiOhHell.session && window.ZimiOhHell.session.state", + 20, + ) + seen_trick = 0 + for _ in range(600): + st = page.evaluate("() => window.ZimiOhHell.session.state") + seen_trick = max(seen_trick, len(st["trick"])) + if st["phase"] in ("handEnd", "over") or sheet_up(page): + break + if st["phase"] == "bid" and st["turn"] == 0: + bad = page.evaluate( + "() => window.ZimiOhHell.forbiddenBid(window.ZimiOhHell.session.state, 0)" + ) + page.locator(".ct-choice", has_text=str(1 if bad != 1 else 2)).first.tap() + page.wait_for_timeout(200) + elif st["phase"] == "play" and st["turn"] == 0 and len(st["trick"]) < 5: + legal = page.evaluate( + "() => window.ZimiOhHell.legalPlays(window.ZimiOhHell.session.state, 0)" + ) + tap_card(page, legal[0]) + page.wait_for_timeout(200) + else: + page.wait_for_timeout(250) + page.wait_for_function( + "() => document.querySelector('.gs-sheet, .ar-sheet, .zc-sheet, .gs-end')", + timeout=10000, + ) + st = page.evaluate("() => window.ZimiOhHell.session.state") + assert st["phase"] == "handEnd" and sum(st["tricks"]) == 5 and seen_trick == 5 + assert len(st["scores"]) == 5 + # With bids and tricks in them the six chips (five players and the trump) still fit the phone's width. + chips = page.evaluate( + "() => [...document.querySelectorAll('.ct-chip')].map(e => { const b = e.getBoundingClientRect(); return [b.left, b.right]; })" + ) + assert len(chips) == 6 and all(l >= 0 and r <= PHONE["width"] for l, r in chips), chips + assert not page.errors + ctx.close() + + +def test_oh_hell_five_last_hand_ends_the_game(browser, site): + ctx = browser.new_context( + viewport=PHONE, device_scale_factor=2, is_mobile=True, has_touch=True + ) + probe = ctx.new_page() + probe.goto(site + "ohhell.html") + probe.wait_for_function("() => window.ZimiOhHell") + state = probe.evaluate("""() => { const H = window.ZimiOhHell, Z = window.ZimiCards; + let st = H.dealHand(Z.shuffled(Math.random), 5, H.LADDERS.short, 8, [20, 15, 12, 9, 3], 4); + for (let s = 0; s < 5; s++) st = H.placeBid(st, s, s === 0 ? 1 : 0); + return st; }""") + probe.close() + save = json.dumps( + { + "v": 1, + "at": int(time.time() * 1000), + "data": { + "id": "ohhell", + "state": state, + "history": [], + "ms": 4000, + "ending": None, + }, + } + ) + ctx.add_init_script( + "try { localStorage.setItem('zimi.games.save.ohhell', %s); } catch (e) {}" + % json.dumps(save) + ) + page = ctx.new_page() + page.errors = [] + page.on("pageerror", lambda e: page.errors.append(str(e))) + page.goto(site + "ohhell.html") + page.wait_for_selector(".zc-card", state="attached", timeout=10000) + for _ in range(80): + st = page.evaluate("() => window.ZimiOhHell.session.state") + if st["phase"] == "over": + break + if st["turn"] == 0 and len(st["trick"]) < 5 and st["hands"][0]: + legal = page.evaluate( + "() => window.ZimiOhHell.legalPlays(window.ZimiOhHell.session.state, 0)" + ) + tap_card(page, legal[0]) + page.wait_for_timeout(200) + else: + page.wait_for_timeout(300) + st = page.evaluate("() => window.ZimiOhHell.session.state") + assert ( + st["players"] == 5 and st["phase"] == "over" + ), "the five-player game never ended" + page.wait_for_function( + "() => document.querySelector('.gs-sheet, .ar-sheet, .zc-sheet, .gs-end')", + timeout=10000, + ) + assert not page.errors + ctx.close() diff --git a/tests/test_games_shelf_table_names_browser.py b/tests/test_games_shelf_table_names_browser.py index 93f89d7a7..f9cb23194 100644 --- a/tests/test_games_shelf_table_names_browser.py +++ b/tests/test_games_shelf_table_names_browser.py @@ -77,3 +77,18 @@ def test_a_name_on_the_table_wraps_before_it_is_cut(browser, site, lang): if os.environ.get("SHOTS") and lang == "es": pg.screenshot(path=os.path.join(os.environ["SHOTS"], "shelf-table-es.png")) ctx.close() + + +def test_the_table_stays_on_the_recent_tab(browser, site): + now = int(time.time() * 1000) + recent = [{"path": "sudoku.html", "title": "Sudoku", "at": now}, {"path": "minesweeper.html", "title": "Minesweeper", "at": now - 1000}] + ctx = browser.new_context(viewport={"width": 1100, "height": 844}) + ctx.add_init_script("try { localStorage.setItem('zimi.games.recent', %s); } catch (e) {}" % json.dumps(json.dumps(recent))) + pg = ctx.new_page() + pg.goto(site + "index.html#lang=en") + pg.wait_for_selector(".ar-box", timeout=15000) + pg.wait_for_timeout(800) + pg.evaluate("() => document.querySelector('.sh-chip-recent').click()") + pg.wait_for_timeout(300) + assert pg.evaluate("() => { const c = document.querySelector('.ar-continue'); return !!c && !c.hidden && c.offsetHeight > 0; }") + ctx.close() diff --git a/tests/test_games_solitaire_variants.cjs b/tests/test_games_solitaire_variants.cjs new file mode 100644 index 000000000..7b607139c --- /dev/null +++ b/tests/test_games_solitaire_variants.cjs @@ -0,0 +1,370 @@ +// The solitaire variants (Yukon, Forty Thieves, Canfield, Scorpion, Aces Up, Accordion, Calculation, Beleaguered Castle, Eight Off, +// Monte Carlo): the rules as pure functions on plain states. Deals, legal and illegal moves, scoring where there is one, win and +// stuck detection, and whole games played by a simple player, every move checked legal. No DOM: the game files run their page +// wiring only when a #zc-table exists. +// +// Run: node tests/test_games_solitaire_variants.cjs (exit 0 = pass) + +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +const dir = path.join(__dirname, '..', 'zimi', 'builtin', 'games'); +let failures = 0, passed = 0; +const check = (ok, label) => { + if (ok) { passed++; console.log('ok: ' + label); } else { console.error('FAIL: ' + label); failures++; } +}; + +const sandbox = { + console, Date, setTimeout, clearTimeout, setInterval, clearInterval, + document: { addEventListener() {}, querySelector: () => null, getElementById: () => null, documentElement: { classList: { toggle() {} } }, hidden: false } +}; +sandbox.window = sandbox; +vm.createContext(sandbox); +const FILES = ['text.js', 'cardbacks.js', 'courts.js', 'cards.js', 'solkit.js']; +const GAME_FILES = ['yukon.js', 'fortythieves.js', 'canfield.js', 'scorpion.js', 'acesup.js', 'accordion.js', 'calculation.js', 'beleaguered.js', 'eightoff.js', 'montecarlo.js']; +const loaded = []; +for (const f of FILES.concat(GAME_FILES)) { + if (!fs.existsSync(path.join(dir, f))) continue; + vm.runInContext(fs.readFileSync(path.join(dir, f), 'utf8'), sandbox, { filename: f }); + loaded.push(f); +} +const Z = sandbox.ZimiCards; +const L = 'A23456789TJQK', SU = 'CDHS'; +const id = (s, copy = 0) => copy * 52 + Z.make(L.indexOf(s[0]) + 1, SU.indexOf(s[1])); +const up = (s, copy = 0) => ({ id: id(s, copy), up: true }); +const dn = (s, copy = 0) => ({ id: id(s, copy), up: false }); +// A seeded generator, so a failure replays. +const lcg = seed => () => ((seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 4294967296); +const order = (seed, decks = 1) => sandbox.ZimiSolKit.shuffledDecks(decks, lcg(seed)); +const allIds = st => [].concat(...Object.keys(st.piles).map(p => st.piles[p].map(c => (typeof c === 'number' ? c : c.id)))); +const dealtOnce = (st, decks = 1) => { const a = allIds(st); return a.length === 52 * decks && new Set(a).size === 52 * decks; }; + +// Plays a game to its end with a greedy player (foundations first, then any legal move that is not an undo of the last one), +// every move taken from the rules' own bestMove / legalMove. Returns { won, moves, illegal }. +function play(G, st, maxMoves = 800) { + let moves = 0, illegal = 0; + const seen = new Set(); + while (moves < maxMoves && !G.isWon(st)) { + const key = JSON.stringify(st.piles); + if (seen.has(key)) { + // A position seen before: try a different first move by drawing, else stop. + if (G.drawStock) { const d = G.drawStock(st); if (d && !seen.has(JSON.stringify(d.piles))) { st = d; moves++; continue; } } + break; + } + seen.add(key); + let next = null; + const piles = Object.keys(st.piles); + outer: for (const from of piles) { + for (let idx = st.piles[from].length - 1; idx >= 0; idx--) { + if (!G.canPick(st, from, idx)) continue; + const to = G.bestMove(st, from, idx); + if (to) { + if (!G.legalMove(st, from, idx, to)) { illegal++; break outer; } + const n = G.applyMove(st, from, idx, to); + if (!seen.has(JSON.stringify(n.piles))) { next = n; break outer; } + } + } + } + if (!next && G.drawStock) next = G.drawStock(st); + if (!next) break; + st = next; moves++; + } + return { won: G.isWon(st), moves, illegal, st }; +} + +// ── Yukon ─────────────────────────────────────────────────────────────────── +if (sandbox.ZimiYukon) { + const Y = sandbox.ZimiYukon; + const st = Y.newState(order(1)); + check(dealtOnce(st), 'Yukon deals all 52 cards once'); + check(Y.TABLEAU.map(t => st.piles[t].length).join() === '1,6,7,8,9,10,11', 'Yukon: columns of 1, 6, 7, 8, 9, 10 and 11 cards'); + check(Y.TABLEAU.every((t, n) => st.piles[t].filter(c => !c.up).length === n && st.piles[t].filter(c => c.up).length === (n ? 5 : 1)), 'Yukon: column n has n cards face down, then five face up (one on the first)'); + const s = Y.blankState(); + s.piles.t0 = [dn('2C'), up('9H'), up('4S'), up('8C')]; + s.piles.t1 = [up('TS')]; + s.piles.t2 = []; + s.piles.t3 = [up('KD'), up('QC')]; + check(Y.canPick(s, 't0', 1) && Y.canPick(s, 't0', 2) && !Y.canPick(s, 't0', 0), 'Yukon: any face-up card can be picked up, with those on it; not a face-down one'); + check(Y.legalMove(s, 't0', 1, 't1') && !Y.legalMove(s, 't0', 2, 't1'), 'Yukon: a run moves onto a card one rank up in the other color, in order or not (9H with 4S and 8C onto the ten of spades)'); + const m = Y.applyMove(s, 't0', 1, 't1'); + check(m.piles.t1.length === 4 && m.piles.t0.length === 1 && m.piles.t0[0].up && m.moves === 1 && s.piles.t0.length === 4, 'Yukon: the whole run moves, the card under it turns over, the old state is left alone'); + check(!Y.legalMove(s, 't3', 1, 't2') && Y.legalMove(s, 't3', 0, 't2'), 'Yukon: only a king (with what lies on it) fills an empty column'); + check(Y.bestMove(s, 't3', 0) === null, 'Yukon: a tap does not shuffle a king from the bottom of one column to an empty one'); + const w = Y.almostWon(); + check(!Y.isWon(w) && Y.legalMove(w, 't0', 0, 'f3') && Y.isWon(Y.applyMove(w, 't0', 0, 'f3')), 'Yukon: the debug state is one card from a win'); + const a = Y.blankState(); a.piles.t0 = [up('AS')]; + check(Y.bestMove(a, 't0', 0) === 'f0' && Y.legalMove(a, 't0', 0, 'f2'), 'Yukon: an ace goes to a foundation'); + const bad = Y.blankState(); bad.piles.t0 = [up('2S')]; bad.piles.f0 = [up('AH')]; + check(!Y.legalMove(bad, 't0', 0, 'f0'), 'Yukon: a foundation takes its own suit only'); + let wins = 0, illegal = 0; + for (let seed = 1; seed <= 30; seed++) { const r = play(Y, Y.newState(order(seed))); if (r.won) wins++; illegal += r.illegal; } + check(illegal === 0, 'Yukon: 30 greedy games, every tap lands where the rules allow'); + check(wins >= 1, 'Yukon: the greedy player wins some deals (' + wins + ' of 30)'); + const stuck = Y.blankState(); stuck.piles.t0 = [up('5S')]; stuck.piles.t1 = [up('9H')]; + check(Y.hasMove(stuck) === false, 'Yukon: two unrelated cards and nothing else: no move'); + stuck.piles.t2 = [up('8S')]; + check(Y.hasMove(stuck) === true, 'Yukon: an eight of spades beside a nine of hearts is a move (8S onto 9H)'); +} + +// The debug state of every game is one legal move from a win, and the win is seen. +function oneMoveWins(G) { + const st = G.almostWon(); + if (G.isWon(st)) return false; + for (const from of Object.keys(st.piles)) for (let idx = 0; idx < st.piles[from].length; idx++) for (const to of Object.keys(st.piles)) { + if (G.legalMove(st, from, idx, to) && G.isWon(G.applyMove(st, from, idx, to))) return true; + } + return false; +} +// Every card of the debug state is a different card. +const distinct = G => { const a = allIds(G.almostWon()); return new Set(a).size === a.length; }; +// Greedy games: how many ran, how many tapped something illegal, how many were won. +function greedy(G, deal, games, maxMoves) { + let illegal = 0, won = 0; + for (let seed = 1; seed <= games; seed++) { const r = play(G, deal(seed), maxMoves); illegal += r.illegal; if (r.won) won++; } + return { illegal, won }; +} + +// ── Forty Thieves ─────────────────────────────────────────────────────────── +if (sandbox.ZimiFortyThieves) { + const F = sandbox.ZimiFortyThieves; + const st = F.newState(order(3, 2)); + check(dealtOnce(st, 2), 'Forty Thieves deals both decks, every card once'); + check(F.TABLEAU.length === 10 && F.TABLEAU.every(t => st.piles[t].length === 4 && st.piles[t].every(c => c.up)), 'Forty Thieves: ten columns of four, all face up'); + check(st.piles.stock.length === 64 && st.piles.waste.length === 0 && st.piles.stock.every(c => !c.up), 'Forty Thieves: sixty-four in the stock, face down'); + const s = F.blankState(); + s.piles.t0 = [up('8H'), up('7H'), up('6H')]; s.piles.t1 = [up('9H')]; s.piles.t2 = [up('9S')]; s.piles.t3 = []; + check(F.canPick(s, 't0', 2) && !F.canPick(s, 't0', 1), 'Forty Thieves: only the bottom card of a column can be taken (one at a time)'); + s.piles.t0 = [up('5C'), up('8H')]; + check(F.legalMove(s, 't0', 1, 't1') && !F.legalMove(s, 't0', 1, 't2'), 'Forty Thieves: 8H builds on 9H (same suit) and not on 9S'); + check(F.legalMove(s, 't0', 1, 't3') && F.legalMove(s, 't1', 0, 't3'), 'Forty Thieves: any card fills an empty column'); + const f = F.blankState(); + f.piles.t0 = [up('AS')]; f.piles.f0 = [up('AS', 1)]; f.piles.t2 = [up('2S')]; + check(F.legalMove(f, 't0', 0, 'f1') && !F.legalMove(f, 't0', 0, 'f0') && F.legalMove(f, 't2', 0, 'f0'), 'Forty Thieves: a foundation takes an ace to start and its suit one up (a second ace needs another foundation)'); + const g = F.blankState(); g.piles.f0 = [up('AS'), up('2S')]; g.piles.t0 = []; + check(!F.canPick(g, 'f0', 1) && F.hasMove(g) === false, 'Forty Thieves: a card cannot be taken back off a foundation'); + const d = F.newState(order(4, 2)), d1 = F.drawStock(d); + check(d1.piles.waste.length === 1 && d1.piles.waste[0].up && d1.piles.stock.length === 63 && d.piles.stock.length === 64, 'Forty Thieves: the stock turns one card onto the waste'); + check(F.drawStock(F.blankState()) === null, 'Forty Thieves: one pass only, an empty stock cannot be turned'); + const w = F.blankState(); w.piles.waste = [up('3C')]; w.piles.t0 = [up('4C')]; + check(F.legalMove(w, 'waste', 0, 't0') && F.bestMove(w, 'waste', 0) === 't0', 'Forty Thieves: the waste card builds on a column'); + check(oneMoveWins(F) && distinct(F), 'Forty Thieves: the debug state is one move from a win'); + const r = greedy(F, seed => F.newState(order(seed, 2)), 20); + check(r.illegal === 0, 'Forty Thieves: 20 greedy games, every tap lands where the rules allow (' + r.won + ' won)'); +} + +// ── Canfield ──────────────────────────────────────────────────────────────── +if (sandbox.ZimiCanfield) { + const C = sandbox.ZimiCanfield; + const st = C.newState(order(5)); + check(dealtOnce(st), 'Canfield deals all 52 cards once'); + check(st.piles.r.length === 13 && st.piles.r.filter(c => c.up).length === 1 && st.piles.r[12].up, 'Canfield: a reserve of thirteen, only the top card face up'); + check(st.piles.f0.length === 1 && st.base === Z.rank(st.piles.f0[0].id), 'Canfield: the foundation card sets the rank the foundations start on'); + check(C.TABLEAU.every(t => st.piles[t].length === 1) && st.piles.stock.length === 34, 'Canfield: a card on each of four columns, thirty-four in the stock'); + check(C.below(1) === 13 && C.below(5) === 4 && C.above(13) === 1 && C.above(4) === 5, 'Canfield: ranks run round, below the ace is the king'); + const s = C.blankState(); s.base = 5; + s.piles.t0 = [up('2H')]; s.piles.t1 = [up('AS')]; s.piles.t2 = [up('KD')]; s.piles.t3 = [up('5C'), up('4D'), up('3S')]; + check(C.legalMove(s, 't1', 0, 't0'), 'Canfield: an ace builds on a two of the other color'); + check(C.legalMove(s, 't2', 0, 't1'), 'Canfield: a king builds on an ace (round the corner), the other color'); + check(!C.legalMove(s, 't0', 0, 't2'), 'Canfield: a two does not build on a king'); + s.piles.t0 = [up('6H')]; + check(C.legalMove(s, 't3', 0, 't0') && !C.legalMove(s, 't3', 1, 't0'), 'Canfield: an in-order run moves as one (5C 4D 3S onto 6H); 4D alone does not build on 6H'); + s.piles.t0 = [up('5H')]; + check(C.legalMove(s, 't0', 0, 'f0') && !C.legalMove(s, 't1', 0, 'f0'), 'Canfield: a foundation starts on the base rank only'); + s.piles.f0 = [up('5H')]; s.piles.t0 = [up('6H')]; s.piles.t1 = [up('6S')]; + check(C.legalMove(s, 't0', 0, 'f0') && !C.legalMove(s, 't1', 0, 'f0'), 'Canfield: a foundation builds up by suit'); + s.piles.f0 = [up('QS'), up('KS')]; s.piles.t1 = [up('AS')]; s.base = 12; + check(C.legalMove(s, 't1', 0, 'f0'), 'Canfield: a foundation goes on past the king to the ace'); + const gap = C.blankState(); gap.piles.r = [dn('3C'), up('7H')]; gap.piles.t0 = [up('9S')]; gap.piles.t1 = [up('4D')]; gap.piles.t2 = [up('5D')]; gap.piles.t3 = [up('QC')]; + const g2 = C.applyMove(gap, 't1', 0, 't0'); + check(g2.piles.t1.length === 1 && g2.piles.t1[0].id === id('7H') && g2.piles.r.length === 1 && g2.piles.r[0].up, 'Canfield: a gap in the columns fills itself from the reserve and the next reserve card turns up'); + const dr = C.newState(order(6)), d1 = C.drawStock(dr); + check(d1.piles.waste.length === 3 && d1.piles.stock.length === 31 && d1.piles.waste.every(c => c.up), 'Canfield: the stock turns three at a time'); + let d2 = dr; for (let k = 0; k < 12; k++) d2 = C.drawStock(d2); + check(d2.piles.stock.length === 0 && d2.piles.waste.length === 34, 'Canfield: twelve turns of three empty a stock of thirty-four'); + const d3 = C.drawStock(d2); + check(d3.piles.stock.length === 34 && d3.piles.waste.length === 0 && d3.piles.stock.every(c => !c.up), 'Canfield: an empty stock is turned over again from the waste, as often as you like'); + check(oneMoveWins(C) && distinct(C), 'Canfield: the debug state is one move from a win'); + const r = greedy(C, seed => C.newState(order(seed)), 20); + check(r.illegal === 0, 'Canfield: 20 greedy games, every tap lands where the rules allow (' + r.won + ' won)'); +} + +// ── Scorpion ──────────────────────────────────────────────────────────────── +if (sandbox.ZimiScorpion) { + const S = sandbox.ZimiScorpion; + const st = S.newState(order(7)); + check(dealtOnce(st), 'Scorpion deals all 52 cards once'); + check(S.TABLEAU.every(t => st.piles[t].length === 7) && st.piles.stock.length === 3, 'Scorpion: seven columns of seven and three left over'); + check(S.TABLEAU.every((t, n) => st.piles[t].filter(c => !c.up).length === (n < 4 ? 3 : 0)), 'Scorpion: the first three cards of the first four columns are face down'); + const s = S.blankState(); + s.piles.t0 = [dn('2C'), up('9H'), up('4S'), up('8C')]; s.piles.t1 = [up('TH')]; s.piles.t2 = []; s.piles.t3 = [up('KD'), up('QC')]; + check(S.canPick(s, 't0', 1) && !S.canPick(s, 't0', 0), 'Scorpion: any face-up card can be taken, with those on it'); + check(S.legalMove(s, 't0', 1, 't1') && !S.legalMove(s, 't0', 2, 't1'), 'Scorpion: a run goes onto a card of the same suit one rank higher, in order or not (9H onto 10H)'); + s.piles.t1 = [up('TS')]; + check(!S.legalMove(s, 't0', 1, 't1'), 'Scorpion: not onto another suit'); + check(S.legalMove(s, 't3', 0, 't2') && !S.legalMove(s, 't3', 1, 't2'), 'Scorpion: only a king fills an empty column'); + const spare = S.drawStock(st); + check(spare.piles.stock.length === 0 && [0, 1, 2].every(i => spare.piles['t' + i].length === 8 && spare.piles['t' + i][7].up) && spare.piles.t3.length === 7, 'Scorpion: the spare cards go one each onto the first three columns, face up'); + check(S.drawStock(spare) === null, 'Scorpion: the spare cards can be dealt once'); + const run = S.blankState(); + run.piles.t0 = [dn('5D')]; for (let r = 13; r >= 2; r--) run.piles.t0.push({ id: Z.make(r, 3), up: true }); + run.piles.t1 = [up('AS')]; + const done = S.applyMove(run, 't1', 0, 't0'); + check(done.piles.d0.length === 13 && done.piles.t0.length === 1 && done.piles.t0[0].up && done.piles.t1.length === 0, 'Scorpion: a king-to-ace run of one suit leaves the table and turns the card under it'); + check(oneMoveWins(S) && distinct(S), 'Scorpion: the debug state is one move from a win'); + const r = greedy(S, seed => S.newState(order(seed)), 20); + check(r.illegal === 0, 'Scorpion: 20 greedy games, every tap lands where the rules allow'); +} + +// ── Aces Up ───────────────────────────────────────────────────────────────── +if (sandbox.ZimiAcesUp) { + const A = sandbox.ZimiAcesUp; + const st = A.newState(order(8)); + check(dealtOnce(st) && A.TABLEAU.every(t => st.piles[t].length === 1) && st.piles.stock.length === 48 && st.moves === 0, 'Aces Up deals four cards, one on each column, 48 in the stock'); + check(A.high(id('AS')) > A.high(id('KS')) && A.high(id('2S')) < A.high(id('3S')), 'Aces Up: the ace is the highest card'); + const s = A.blankState(); + s.piles.t0 = [up('5H')]; s.piles.t1 = [up('9H')]; s.piles.t2 = [up('KS')]; s.piles.t3 = [up('AS')]; + check(A.legalMove(s, 't0', 0, 'out') && !A.legalMove(s, 't1', 0, 'out'), 'Aces Up: a card goes out when another column shows a higher card of its suit (5H under 9H, not 9H)'); + check(A.legalMove(s, 't2', 0, 'out') && !A.legalMove(s, 't3', 0, 'out'), 'Aces Up: a king goes out under an ace; an ace never goes'); + s.piles.t1 = [up('9C')]; + check(!A.legalMove(s, 't0', 0, 'out'), 'Aces Up: a higher card of another suit does not count'); + const e = A.blankState(); e.piles.t0 = [up('3C'), up('5H')]; e.piles.t1 = [up('9H')]; e.piles.t2 = []; e.piles.t3 = [up('2D')]; + const m = A.applyMove(e, 't0', 1, 'out'); + check(m.piles.out.length === 1 && m.piles.t0.length === 1 && m.moves === 1 && e.piles.out.length === 0, 'Aces Up: the card leaves its column and goes to the discard'); + e.piles.t1 = [up('9S')]; + check(A.legalMove(e, 't0', 1, 't2') && A.bestMove(e, 't0', 1) === 't2' && !A.legalMove(e, 't0', 1, 't1'), 'Aces Up: a top card moves to an empty column, and onto no other column'); + check(!A.canPick(e, 't0', 0), 'Aces Up: only the top card of a column can be taken'); + const dl = A.drawStock(st); + check(dl.piles.stock.length === 44 && A.TABLEAU.every(t => dl.piles[t].length === 2 && dl.piles[t][1].up), 'Aces Up: a deal puts four more cards on the columns, one on each'); + check(A.drawStock(A.blankState()) === null, 'Aces Up: no deal from an empty stock'); + const dead = A.blankState(); dead.piles.t0 = [up('5H')]; dead.piles.t1 = [up('9C')]; dead.piles.t2 = [up('KD')]; dead.piles.t3 = [up('AS')]; + check(A.hasMove(dead) === false, 'Aces Up: four tops that cannot go and no stock is no move'); + check(oneMoveWins(A) && distinct(A), 'Aces Up: the debug state is one move from a win'); + const r = greedy(A, seed => A.newState(order(seed)), 60); + check(r.illegal === 0, 'Aces Up: 60 greedy games, every tap lands where the rules allow (' + r.won + ' won)'); +} + +// ── Accordion ─────────────────────────────────────────────────────────────── +if (sandbox.ZimiAccordion) { + const X = sandbox.ZimiAccordion; + const st = X.newState(order(9)); + check(dealtOnce(st) && X.row(st).length === 52, 'Accordion lays out all 52 cards in a row'); + const row = (...cards) => { const s = X.blankState(); cards.forEach((c, n) => { s.piles['a' + n] = [up(c)]; }); return s; }; + // 5S three places right of 5H: the far move; KD beside it does not match. + let s = row('5H', '9C', 'KD', '5S'); + check(X.targets(s, 'a3').join() === 'a0' && X.legalMove(s, 'a3', 0, 'a0') && !X.legalMove(s, 'a3', 0, 'a2'), 'Accordion: 5S goes three places left onto 5H by rank, not onto the king beside it'); + check(X.bestMove(s, 'a3', 0) === 'a0', 'Accordion: a tap moves a card that has one place to go'); + s = row('5H', '9C', '2D', '5S', '3S'); + check(X.targets(s, 'a4').join() === 'a3' && X.targets(s, 'a3').join() === 'a0', 'Accordion: 3S goes onto 5S beside it by suit; 5S goes three left onto 5H'); + const both = row('9H', '4C', '9D', '9S'); // 9S has 9D beside it and 9H three places left, both by rank + check(X.targets(both, 'a3').sort().join() === 'a0,a2' && X.bestMove(both, 'a3', 0) === null, 'Accordion: with two places a tap does not choose (drag to choose)'); + check(X.why(both, 'a3', 0) !== null, 'Accordion: a tap with two choices says so'); + const m = X.applyMove(both, 'a3', 0, 'a2'); + check(m.piles.a2.length === 2 && m.piles.a2[1].id === id('9S') && m.piles.a3.length === 0 && X.row(m).join() === 'a0,a1,a2' && both.piles.a3.length === 1, 'Accordion: the pile goes on top of the other and the row closes up'); + // After the gap, places are counted along the row: a4 is now three places right of a1. + const moved = row('9H', '4C', '9D', '9S', '2D', '4H'); + const after = X.applyMove(moved, 'a3', 0, 'a2'); + check(X.row(after).join() === 'a0,a1,a2,a4,a5' && X.targets(moved, 'a5').length === 0 && X.targets(after, 'a5').join() === 'a1', 'Accordion: places are counted along the piles left, not by name (4H is now three places right of 4C)'); + check(oneMoveWins(X) && distinct(X), 'Accordion: the debug state is one move from a win'); + const dead = row('2H', '9C', '5S'); + check(X.hasMove(dead) === false && X.isWon(dead) === false, 'Accordion: three piles with nothing matching is stuck, not won'); + const r = greedy(X, seed => X.newState(order(seed)), 60, 300); + check(r.illegal === 0, 'Accordion: 60 greedy games, every tap lands where the rules allow (' + r.won + ' won)'); +} + +// ── Calculation ───────────────────────────────────────────────────────────── +if (sandbox.ZimiCalculation) { + const K = sandbox.ZimiCalculation; + const st = K.newState(order(10)); + check(dealtOnce(st) && st.piles.deck.length === 48, 'Calculation deals 52 cards once: four to the foundations, 48 in the deck'); + check(K.FOUNDATION.map(f => Z.rank(st.piles[f][0].id)).join() === '1,2,3,4', 'Calculation: the foundations start on an ace, a two, a three and a four'); + const seqs = [1, 2, 3, 4].map(step => { const out = [step]; for (let k = 1; k < 13; k++) out.push(K.nextRank(out[k - 1], step)); return out; }); + check(seqs.every(q => q[12] === 13 && new Set(q).size === 13), 'Calculation: each foundation counts through all thirteen ranks and ends on a king'); + check(seqs[1].join() === '2,4,6,8,10,12,1,3,5,7,9,11,13' && seqs[2].join() === '3,6,9,12,2,5,8,11,1,4,7,10,13', 'Calculation: by twos (2 4 6 8 10 Q A 3 5 7 9 J K) and by threes'); + const s = K.blankState(); + s.piles.f0 = [up('AS')]; s.piles.f1 = [up('2H')]; s.piles.f2 = [up('3C')]; s.piles.f3 = [up('4D')]; + s.piles.deck = [up('7D'), up('2C')]; s.piles.w0 = [up('4S')]; s.piles.w1 = [up('6C')]; + check(K.legalMove(s, 'deck', 1, 'f0') && !K.legalMove(s, 'deck', 1, 'f1'), 'Calculation: a two goes on the ace pile (counting by one) and not on the pile that wants a four'); + check(K.legalMove(s, 'w0', 0, 'f1') && K.legalMove(s, 'w1', 0, 'f2') && !K.legalMove(s, 'w1', 0, 'f1'), 'Calculation: a waste pile top goes to the foundation that wants it (4S on the twos, 6C on the threes)'); + check(K.legalMove(s, 'deck', 1, 'w2') && !K.legalMove(s, 'w0', 0, 'w1') && !K.legalMove(s, 'w0', 0, 'w2'), 'Calculation: the deck card goes onto any waste pile, but a waste pile card never moves to another'); + check(!K.canPick(s, 'f0', 0) && !K.legalMove(s, 'f0', 0, 'w0'), 'Calculation: nothing comes back off a foundation'); + check(!K.canPick(s, 'deck', 0) && K.canPick(s, 'deck', 1), 'Calculation: only the top card of the deck plays'); + check(K.needs(s, 'f3') === 8 && K.needs(s, 'f1') === 4, 'Calculation: what a pile wants next is known (the fours want an eight, the twos a four)'); + check(oneMoveWins(K) && distinct(K), 'Calculation: the debug state is one move from a win'); + const r = greedy(K, seed => K.newState(order(seed)), 30); + check(r.illegal === 0, 'Calculation: 30 greedy games, every tap lands where the rules allow'); + const stuck = K.blankState(); stuck.piles.f0 = [up('AS')]; stuck.piles.f1 = [up('2H')]; stuck.piles.f2 = [up('3C')]; stuck.piles.f3 = [up('4D')]; + stuck.piles.w0 = [up('9S')]; stuck.piles.w1 = [up('JS')]; stuck.piles.w2 = [up('KS')]; stuck.piles.w3 = [up('TS')]; + check(K.hasMove(stuck) === false, 'Calculation: an empty deck and four waste tops nothing wants is no move'); +} + +// ── Beleaguered Castle ────────────────────────────────────────────────────── +if (sandbox.ZimiBeleaguered) { + const B = sandbox.ZimiBeleaguered; + const st = B.newState(order(11)); + check(dealtOnce(st), 'Beleaguered Castle deals all 52 cards once'); + check(B.FOUNDATION.every(f => st.piles[f].length === 1 && Z.rank(st.piles[f][0].id) === 1) && new Set(B.FOUNDATION.map(f => Z.suit(st.piles[f][0].id))).size === 4, 'Beleaguered Castle: the four aces start the four foundations'); + check(B.TABLEAU.length === 8 && B.TABLEAU.every(t => st.piles[t].length === 6 && st.piles[t].every(c => c.up && Z.rank(c.id) !== 1)), 'Beleaguered Castle: eight columns of six, all face up'); + const s = B.blankState(); + s.piles.t0 = [up('QC'), up('8D')]; s.piles.t1 = [up('9S')]; s.piles.t2 = [up('9D')]; s.piles.t3 = []; + check(B.legalMove(s, 't0', 1, 't1') && B.legalMove(s, 't0', 1, 't2'), 'Beleaguered Castle: a card builds down on any suit (8D on 9S and on 9D)'); + check(!B.canPick(s, 't0', 0) && B.legalMove(s, 't0', 1, 't3'), 'Beleaguered Castle: one card at a time, and any card fills an empty column'); + check(!B.legalMove(s, 't1', 0, 't2'), 'Beleaguered Castle: a nine does not build on a nine'); + const f = B.blankState(); f.piles.f0 = [up('AH')]; f.piles.t0 = [up('2H')]; f.piles.t1 = [up('2S')]; + check(B.legalMove(f, 't0', 0, 'f0') && !B.legalMove(f, 't1', 0, 'f0'), 'Beleaguered Castle: a foundation builds up by suit'); + check(oneMoveWins(B) && distinct(B), 'Beleaguered Castle: the debug state is one move from a win'); + const r = greedy(B, seed => B.newState(order(seed)), 30); + check(r.illegal === 0, 'Beleaguered Castle: 30 greedy games, every tap lands where the rules allow (' + r.won + ' won)'); +} + +// ── Eight Off ─────────────────────────────────────────────────────────────── +if (sandbox.ZimiEightOff) { + const E = sandbox.ZimiEightOff; + const st = E.newState(order(12)); + check(dealtOnce(st), 'Eight Off deals all 52 cards once'); + check(E.TABLEAU.every(t => st.piles[t].length === 6) && ['c0', 'c1', 'c2', 'c3'].every(c => st.piles[c].length === 1) && ['c4', 'c5', 'c6', 'c7'].every(c => st.piles[c].length === 0), 'Eight Off: eight columns of six, four cards in the first four of eight free cells'); + const s = E.blankState(); + s.piles.t0 = [up('5C'), up('8H')]; s.piles.t1 = [up('9H')]; s.piles.t2 = [up('9S')]; s.piles.t3 = []; s.piles.c0 = [up('KD')]; + check(E.legalMove(s, 't0', 1, 't1') && !E.legalMove(s, 't0', 1, 't2'), 'Eight Off: build down in one suit (8H on 9H, not on 9S)'); + check(!E.canPick(s, 't0', 0), 'Eight Off: one card at a time'); + check(E.legalMove(s, 'c0', 0, 't3') && !E.legalMove(s, 't0', 1, 't3'), 'Eight Off: only a king fills an empty column'); + check(E.legalMove(s, 't0', 1, 'c1') && !E.legalMove(s, 't0', 1, 'c0') && !E.legalMove(s, 'c0', 0, 'c1'), 'Eight Off: a free cell holds one card, and a card cannot go from cell to cell'); + const f = E.blankState(); f.piles.c0 = [up('AS')]; f.piles.t0 = [up('2S')]; + check(E.legalMove(f, 'c0', 0, 'f0') && E.bestMove(f, 'c0', 0) === 'f0', 'Eight Off: a card in a cell goes to a foundation'); + check(oneMoveWins(E) && distinct(E), 'Eight Off: the debug state is one move from a win'); + const r = greedy(E, seed => E.newState(order(seed)), 30); + check(r.illegal === 0, 'Eight Off: 30 greedy games, every tap lands where the rules allow (' + r.won + ' won)'); +} + +// ── Monte Carlo ───────────────────────────────────────────────────────────── +if (sandbox.ZimiMonteCarlo) { + const M = sandbox.ZimiMonteCarlo; + const st = M.newState(order(13)); + check(dealtOnce(st) && M.GRID.every(g => st.piles[g].length === 1 && st.piles[g][0].up) && st.piles.stock.length === 27, 'Monte Carlo: 25 cards face up in a grid of five by five, 27 in the stock'); + const s = M.blankState(); + s.piles.g0 = [up('7C')]; s.piles.g1 = [up('7D')]; s.piles.g6 = [up('7H')]; s.piles.g12 = [up('7S')]; s.piles.g2 = [up('8C')]; s.piles.g4 = [up('7S', 1)]; s.piles.g5 = [up('7C', 1)]; + check(M.legalMove(s, 'g0', 0, 'g1') && M.legalMove(s, 'g0', 0, 'g6'), 'Monte Carlo: a card goes with a card of its rank beside it, or on its corner'); + check(M.legalMove(s, 'g6', 0, 'g12') && M.legalMove(s, 'g1', 0, 'g6'), 'Monte Carlo: down the diagonal and down the column'); + check(!M.legalMove(s, 'g0', 0, 'g12') && !M.legalMove(s, 'g0', 0, 'g2') && !M.legalMove(s, 'g0', 0, 'g4'), 'Monte Carlo: not two places away, and not a different rank'); + check(!M.legalMove(s, 'g4', 0, 'g5'), 'Monte Carlo: the right edge does not wrap round to the left of the next row'); + check(M.bestMove(s, 'g12', 0) === 'g6' && M.bestMove(s, 'g2', 0) === null, 'Monte Carlo: a tap pairs a card with a touching match; a card with none has no pair'); + const m = M.applyMove(s, 'g0', 0, 'g1'); + check(m.piles.out.length === 2 && m.piles.g0.length === 0 && m.piles.g1.length === 0 && m.moves === 1 && s.piles.out.length === 0, 'Monte Carlo: a pair goes out together'); + const blank = M.blankState(); + blank.piles.g3 = [up('2C')]; blank.piles.g7 = [up('3C')]; blank.piles.g24 = [up('4C')]; blank.piles.stock = [dn('5C'), dn('6C')]; + const f = M.fill(blank); + check(f.piles.g0[0].id === id('2C') && f.piles.g1[0].id === id('3C') && f.piles.g2[0].id === id('4C') && f.piles.g3[0].id === id('6C') && f.piles.g4[0].id === id('5C') && f.piles.g5.length === 0 && f.piles.stock.length === 0, + 'Monte Carlo: the cards slide up and left in order and the stock deals into the empty places'); + check(M.drawStock(M.newState(order(14))) === null && M.drawStock(M.blankState()) === null, 'Monte Carlo: with every place full, or the table empty, the stock does nothing'); + check(oneMoveWins(M) && distinct(M), 'Monte Carlo: the debug state is one move from a win'); + const dead = M.blankState(); dead.piles.g0 = [up('2C')]; dead.piles.g1 = [up('3C')]; + check(M.hasMove(dead) === false, 'Monte Carlo: two cards that do not pair and no stock is no move'); + const r = greedy(M, seed => M.newState(order(seed)), 60); + check(r.illegal === 0, 'Monte Carlo: 60 greedy games, every tap lands where the rules allow (' + r.won + ' won)'); +} + +// ── The loaded files ──────────────────────────────────────────────────────── +check(loaded.length === FILES.length + GAME_FILES.length, 'every variant file is loaded (' + loaded.length + ' of ' + (FILES.length + GAME_FILES.length) + ')'); + +console.log('\n' + passed + ' passed, ' + failures + ' failed'); +process.exit(failures ? 1 : 0); diff --git a/tests/test_games_solitaire_variants_browser.py b/tests/test_games_solitaire_variants_browser.py new file mode 100644 index 000000000..d3ade000d --- /dev/null +++ b/tests/test_games_solitaire_variants_browser.py @@ -0,0 +1,182 @@ +"""The solitaire variants on a 390 px touch phone: each opens without a page error, lays out inside the width, answers a tap, and is +won from its one-move-from-a-win fixture (?debug=win) with the end sheet up. + +Run: pytest tests/test_games_solitaire_variants_browser.py -v +""" + +import functools +import http.server +import os +import threading + +import pytest + +GAMES = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "zimi", + "builtin", + "games", +) +PHONE = {"width": 390, "height": 844} +VARIANTS = [ + ("yukon", "ZimiYukon"), + ("fortythieves", "ZimiFortyThieves"), + ("canfield", "ZimiCanfield"), + ("scorpion", "ZimiScorpion"), + ("acesup", "ZimiAcesUp"), + ("accordion", "ZimiAccordion"), + ("calculation", "ZimiCalculation"), + ("beleaguered", "ZimiBeleaguered"), + ("eightoff", "ZimiEightOff"), + ("montecarlo", "ZimiMonteCarlo"), +] +END = "document.querySelector('.ar-sheet:not([hidden]) .gs-primary') && window['%s'].session.won" +# A card to tap that the game itself would send somewhere: the first one with a move (the stock turns, if nothing else does). +FIND_TAP = """(g) => { + const api = window[g], st = api.session.state; + for (const from of Object.keys(st.piles)) for (let idx = st.piles[from].length - 1; idx >= 0; idx--) { + if (!api.canPick(st, from, idx) || !api.bestMove(st, from, idx)) continue; + const c = st.piles[from][idx], id = typeof c === 'number' ? c : c.id, e = document.querySelector('.zc-card[data-id="' + id + '"]'); + if (!e) continue; + const r = e.getBoundingClientRect(); + return { x: r.x + r.width / 2, y: r.y + r.height * 0.2, moves: st.moves, from, idx }; + } + return null; +}""" +# The card whose tap makes the last move: the fixture's only way to win, as the game's own bestMove sends it. +FIND_WIN = """(g) => { + const api = window[g], st = api.almostWon(); + for (const from of Object.keys(st.piles)) for (let idx = 0; idx < st.piles[from].length; idx++) { + const to = api.canPick(st, from, idx) && api.bestMove(st, from, idx); + if (!to || !api.isWon(api.applyMove(st, from, idx, to))) continue; + const c = api.session.state.piles[from][idx], e = document.querySelector('.zc-card[data-id="' + c.id + '"]'); + const r = e.getBoundingClientRect(); + return { x: r.x + r.width / 2, y: r.y + r.height * 0.2 }; + } + return null; +}""" + + +@pytest.fixture(scope="module") +def site(): + handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=GAMES) + handler.log_message = lambda *a, **k: None + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d/" % srv.server_address[1] + srv.shutdown() + + +@pytest.fixture(scope="module") +def browser(): + sync_api = pytest.importorskip("playwright.sync_api") + with sync_api.sync_playwright() as p: + try: + b = p.chromium.launch() + except Exception as e: + pytest.skip("Chromium is not installed: %s" % e) + yield b + b.close() + + +def _open(browser, site, page, query="", scheme="light"): + ctx = browser.new_context( + viewport=PHONE, + device_scale_factor=2, + is_mobile=True, + has_touch=True, + color_scheme=scheme, + ) + pg = ctx.new_page() + pg.errors = [] + pg.on("pageerror", lambda e: pg.errors.append(str(e))) + pg.goto(site + page + ".html" + query) + pg.wait_for_selector(".zc-card", state="attached", timeout=15000) + pg.wait_for_function("() => !document.querySelector('.zc-dealing')", timeout=15000) + pg.wait_for_timeout(300) + return pg + + +@pytest.mark.parametrize("page,game", VARIANTS) +@pytest.mark.parametrize("scheme", ["light", "dark"]) +def test_opens_inside_the_phone_with_no_errors(browser, site, page, game, scheme): + pg = _open(browser, site, page, scheme=scheme) + assert not pg.errors, pg.errors + wide = pg.evaluate("() => document.documentElement.scrollWidth - window.innerWidth") + assert wide <= 0, "the page is %s px wider than the phone" % wide + out = pg.evaluate( + """() => [...document.querySelectorAll('.zc-card:not(.zc-off)')].filter((c) => { + const r = c.getBoundingClientRect(); return r.width && (r.left < -1 || r.right > window.innerWidth + 1); + }).length""" + ) + assert out == 0, "%d cards run off the side" % out + assert pg.inner_text("h1").strip(), "the bar names the game" + pg.context.close() + + +def _a_tap_with_a_move(pg, game): + """A card to tap that goes somewhere; when the first deal has none (the stock is the move), the same deal from a fixed shuffle.""" + at = pg.evaluate(FIND_TAP, game) + if at is None: + pg.evaluate( + "(g) => window[g].session.reset(window[g].newState(window.ZimiSolKit.shuffledDecks(g === 'ZimiFortyThieves' ? 2 : 1, () => 0.25)))", + game, + ) + pg.wait_for_timeout(1500) + at = pg.evaluate(FIND_TAP, game) + return at + + +@pytest.mark.parametrize("page,game", VARIANTS) +def test_a_tap_moves_a_card_and_undo_takes_it_back(browser, site, page, game): + pg = _open(browser, site, page) + at = _a_tap_with_a_move(pg, game) + if at is not None: + before = pg.evaluate( + "(g) => JSON.stringify(window[g].session.state.piles)", game + ) + pg.touchscreen.tap(at["x"], at["y"]) + pg.wait_for_timeout(500) + after = pg.evaluate( + "(g) => JSON.stringify(window[g].session.state.piles)", game + ) + assert after != before, "a tap on a card with a move changed nothing" + pg.click("#zc-undo") + pg.wait_for_timeout(300) + assert ( + pg.evaluate("(g) => JSON.stringify(window[g].session.state.piles)", game) + == before + ), "Undo did not take the move back" + assert not pg.errors, pg.errors + pg.context.close() + + +@pytest.mark.parametrize("page,game", VARIANTS) +def test_won_from_one_move_away_with_the_end_sheet(browser, site, page, game): + pg = _open(browser, site, page, "?debug=win") + at = pg.evaluate(FIND_WIN, game) + assert at is not None, "the fixture has no card whose tap wins" + pg.touchscreen.tap(at["x"], at["y"]) + pg.wait_for_function(END % game, timeout=15000) + assert pg.evaluate("(g) => window[g].isWon(window[g].session.state)", game) + assert not pg.errors, pg.errors + pg.context.close() + + +@pytest.mark.parametrize("page,game", VARIANTS) +def test_a_game_left_comes_back_as_it_was(browser, site, page, game): + pg = _open(browser, site, page) + at = _a_tap_with_a_move(pg, game) + if at is not None: + pg.touchscreen.tap(at["x"], at["y"]) + pg.wait_for_timeout(500) + kept = pg.evaluate("(g) => JSON.stringify(window[g].session.state)", game) + if at is None or not pg.evaluate("(g) => window[g].session.state.moves", game): + pg.context.close() + pytest.skip("no move was made, so nothing is kept") + pg.reload() + pg.wait_for_selector(".zc-card", state="attached", timeout=15000) + pg.wait_for_timeout(600) + assert pg.evaluate("(g) => JSON.stringify(window[g].session.state)", game) == kept, "the position did not come back" + assert not pg.errors, pg.errors + pg.context.close() diff --git a/tests/test_games_spider_open_browser.py b/tests/test_games_spider_open_browser.py index d9e61fe37..4a59da41d 100644 --- a/tests/test_games_spider_open_browser.py +++ b/tests/test_games_spider_open_browser.py @@ -1,7 +1,8 @@ -"""Spider and Klondike open their face-down cards when the table has room, by the same step as the face-up ones. +"""Spider and Klondike keep their face-down cards a sliver, whatever the room: enough to count them, nothing to read. -Spider's five face-down cards sat in 7 px steps at the top of a phone whose table was three quarters empty: a -face-down card took a fixed 0.54 of a face-up step whatever the room. +They used to open up to the face-up step when the table had room, so a column of six backs and one face stood three card +heights tall for one playable card (phone solitaire apps show backs at 0.07 to 0.16 of a card). Room goes to the face-up +fan instead: on a fresh deal there is room, so the backs must stay between DOWN_MIN and DOWN_MAX of a card's height. Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_games_spider_open_browser.py -v """ @@ -17,8 +18,11 @@ +DOWN_MIN, DOWN_MAX = 0.05, 0.14 + + @pytest.mark.parametrize("game,api,col", [("spider", "ZimiSpider", "c0"), ("solitaire", "ZimiSolitaire", "t6")]) -def test_face_down_cards_open_up_with_room(served, browser, game, api, col): +def test_face_down_cards_stay_a_sliver_with_room(served, browser, game, api, col): ctx = browser.new_context(viewport=VIEW, has_touch=True, is_mobile=True) page = ctx.new_page() page.goto("%s/%s.html" % (served, game)) @@ -29,6 +33,6 @@ def test_face_down_cards_open_up_with_room(served, browser, game, api, col): const e = document.querySelector('.zc-card[data-id="' + c.id + '"]'); return [c.up, e.getBoundingClientRect().top]; })""", [api, col]) downs = [b[1] - a[1] for a, b in zip(ys, ys[1:]) if not a[0]] assert downs, ys - face_up_step = page.evaluate("() => { const r = document.querySelector('.zc-card:not(.zc-off)').getBoundingClientRect(); return r.height * ZimiCards.FAN_UP_SHARE; }") - assert min(downs) >= face_up_step - 1, (downs, face_up_step) + ch = page.evaluate("() => document.querySelector('.zc-card:not(.zc-off)').getBoundingClientRect().height") + assert all(ch * DOWN_MIN <= d <= ch * DOWN_MAX for d in downs), (downs, ch) ctx.close() diff --git a/tests/test_games_stuck_after_stock_browser.py b/tests/test_games_stuck_after_stock_browser.py new file mode 100644 index 000000000..0be8b9459 --- /dev/null +++ b/tests/test_games_stuck_after_stock_browser.py @@ -0,0 +1,107 @@ +"""A turn of the stock that leaves no moves ends the game with the stuck sheet, not silently (found playing Aces Up and Canfield). + +Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_games_stuck_after_stock_browser.py -v +""" + +import functools +import http.server +import json +import os +import threading +import time + +import pytest + +GAMES = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "zimi", + "builtin", + "games", +) +PHONE = {"width": 390, "height": 844} + + +@pytest.fixture(scope="module") +def site(): + handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=GAMES) + handler.log_message = lambda *a, **k: None + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d/" % srv.server_address[1] + srv.shutdown() + + +@pytest.fixture(scope="module") +def browser(): + sync_api = pytest.importorskip("playwright.sync_api") + with sync_api.sync_playwright() as p: + try: + b = p.chromium.launch() + except Exception as e: + pytest.skip("Chromium is not installed: %s" % e) + yield b + b.close() + + +@pytest.fixture +def phone(browser): + ctx = browser.new_context( + viewport=PHONE, device_scale_factor=2, is_mobile=True, has_touch=True + ) + page = ctx.new_page() + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.errors = errors + yield page + ctx.close() + + +def open_game(page, site, name, wait_for, minimum_cards=1): + page.goto(site + name + ".html") + page.wait_for_function(wait_for, timeout=8000) + page.wait_for_function( + "(n) => document.querySelectorAll('.zc-card[data-id]').length >= n", + arg=minimum_cards, + timeout=8000, + ) + page.wait_for_timeout(2500) # the deal's cards fly in + + +def card_point(page, card_id): + return page.evaluate( + """(id) => { const e = document.querySelector('.zc-card[data-id="' + id + '"]'); if (!e) return null; + const b = e.getBoundingClientRect(); return { x: b.x + Math.min(10, b.width / 3), y: b.y + b.height * 0.25 }; }""", + card_id, + ) + + +def tap_card(page, card_id): + p = card_point(page, card_id) + for _ in range(20): + assert p, "card %s is not on the table" % card_id + page.wait_for_timeout(120) + q = card_point(page, card_id) + if q == p: + break + p = q + page.touchscreen.tap(p["x"], p["y"]) + + +def test_the_last_row_of_aces_up_dealt_with_no_moves_says_so(phone, site): + open_game(phone, site, "acesup", "() => window.ZimiAcesUp && window.ZimiAcesUp.session && window.ZimiAcesUp.session.state", 4) + # Four kings in the columns and four cards left to deal, no two of one suit: the deal leaves nothing to discard. + phone.evaluate( + """() => { const A = window.ZimiAcesUp, Z = window.ZimiCards, K = window.ZimiSolKit, s = A.blankState(); + ['t0', 't1', 't2', 't3'].forEach((t, i) => s.piles[t].push(K.card(Z.make(13, i), true))); + [[2, 0], [3, 1], [4, 2], [5, 3]].forEach(([r, su]) => s.piles.stock.push(K.card(Z.make(r, su), false))); + A.session.reset(s); }""" + ) + phone.wait_for_timeout(1500) + assert not phone.evaluate("() => /No moves left/.test(document.body.innerText)") + top = phone.evaluate( + """() => { const st = window.ZimiAcesUp.session.state.piles.stock, e = document.querySelector('.zc-card[data-id="' + st[st.length - 1].id + '"]'); + const r = e.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }""" + ) + phone.touchscreen.tap(top["x"], top["y"]) + phone.wait_for_function("() => /No moves left/.test(document.body.innerText)", timeout=6000) + assert not phone.errors diff --git a/tests/test_games_stuck_sheets_browser.py b/tests/test_games_stuck_sheets_browser.py new file mode 100644 index 000000000..72e5b64d1 --- /dev/null +++ b/tests/test_games_stuck_sheets_browser.py @@ -0,0 +1,145 @@ +"""Forty Thieves and Monte Carlo: the move that leaves nothing to do ends the game with the stuck sheet. + +Each game is set to a position one move from being stuck (by its own state), the move is made by a tap on a real card, and the +stuck sheet must come up. STUCK_SHOT_DIR= keeps a picture of each sheet. + +Run: ZIMI_TORRENT=0 ZIMI_OFFLINE=1 pytest tests/test_games_stuck_sheets_browser.py -v +""" + +import functools +import http.server +import json +import os +import threading +import time + +import pytest + +GAMES = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "zimi", + "builtin", + "games", +) +PHONE = {"width": 390, "height": 844} + + +@pytest.fixture(scope="module") +def site(): + handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=GAMES) + handler.log_message = lambda *a, **k: None + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d/" % srv.server_address[1] + srv.shutdown() + + +@pytest.fixture(scope="module") +def browser(): + sync_api = pytest.importorskip("playwright.sync_api") + with sync_api.sync_playwright() as p: + try: + b = p.chromium.launch() + except Exception as e: + pytest.skip("Chromium is not installed: %s" % e) + yield b + b.close() + + +@pytest.fixture +def phone(browser): + ctx = browser.new_context( + viewport=PHONE, device_scale_factor=2, is_mobile=True, has_touch=True + ) + page = ctx.new_page() + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.errors = errors + yield page + ctx.close() + + +def open_game(page, site, name, wait_for, minimum_cards=1): + page.goto(site + name + ".html") + page.wait_for_function(wait_for, timeout=8000) + page.wait_for_function( + "(n) => document.querySelectorAll('.zc-card[data-id]').length >= n", + arg=minimum_cards, + timeout=8000, + ) + page.wait_for_timeout(2500) # the deal's cards fly in + + +def card_point(page, card_id): + return page.evaluate( + """(id) => { const e = document.querySelector('.zc-card[data-id="' + id + '"]'); if (!e) return null; + const b = e.getBoundingClientRect(); return { x: b.x + Math.min(10, b.width / 3), y: b.y + b.height * 0.25 }; }""", + card_id, + ) + + +def tap_card(page, card_id): + p = card_point(page, card_id) + for _ in range(20): + assert p, "card %s is not on the table" % card_id + page.wait_for_timeout(120) + q = card_point(page, card_id) + if q == p: + break + p = q + page.touchscreen.tap(p["x"], p["y"]) + + +def tap_of(page, card_id): + return page.evaluate( + """(id) => { const e = document.querySelector('.zc-card[data-id="' + id + '"]'); e.scrollIntoView({ block: 'nearest' }); + const r = e.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height * 0.2 }; }""", + card_id, + ) + + +def shot(page, name): + if os.environ.get("STUCK_SHOT_DIR"): + page.screenshot(path=os.path.join(os.environ["STUCK_SHOT_DIR"], name)) + + +def test_forty_thieves_the_last_ace_up_leaves_no_moves(phone, site): + open_game(phone, site, "fortythieves", "() => window.ZimiFortyThieves && window.ZimiFortyThieves.session && window.ZimiFortyThieves.session.state", 20) + ace = phone.evaluate( + """() => { const F = window.ZimiFortyThieves, Z = window.ZimiCards, K = window.ZimiSolKit, s = F.blankState(); + // Nine single cards that build on nothing (no two a rank apart in one suit), and the ace of clubs to go up. + const single = [[2, 3], [4, 3], [6, 3], [8, 3], [10, 3], [2, 2], [4, 2], [6, 2], [8, 2]]; + single.forEach(([r, su], i) => s.piles[F.S.tableau[i]].push(K.card(Z.make(r, su), true))); + s.piles[F.S.tableau[9]].push(K.card(Z.make(1, 0), true)); + F.session.reset(s); return Z.make(1, 0); }""" + ) + phone.wait_for_timeout(1500) + assert not phone.evaluate("() => /No moves left/.test(document.body.innerText)") + at = tap_of(phone, ace) + phone.touchscreen.tap(at["x"], at["y"]) + phone.wait_for_function("() => /No moves left/.test(document.body.innerText)", timeout=8000) + shot(phone, "fortythieves-stuck.png") + assert not phone.errors + + +def test_monte_carlo_the_last_pair_taken_leaves_no_moves(phone, site): + open_game(phone, site, "montecarlo", "() => window.ZimiMonteCarlo && window.ZimiMonteCarlo.session && window.ZimiMonteCarlo.session.state", 20) + first = phone.evaluate( + """() => { const M = window.ZimiMonteCarlo, Z = window.ZimiCards, K = window.ZimiSolKit, s = M.blankState(), SIDE = 5, used = new Set(); + const near = (a, b) => a !== b && Math.abs(Math.floor(a / SIDE) - Math.floor(b / SIDE)) <= 1 && Math.abs(a % SIDE - b % SIDE) <= 1; + // 25 places whose touching cards never share a rank, but the last two (they touch, and are a pair). + const rank = []; + for (let i = 0; i < 25; i++) rank.push(((i % SIDE) + 3 * Math.floor(i / SIDE)) % 13 + 1); + let spare = 1; + for (; spare <= 13; spare++) { if (![22, 23, 24].some((j) => rank[j] === spare) && [23, 24].every((i) => [...Array(25).keys()].filter((j) => near(i, j) && j !== 23 && j !== 24).every((j) => rank[j] !== spare))) break; } + rank[23] = spare; rank[24] = spare; + rank.forEach((r, i) => { let su = i % 4; while (used.has(Z.make(r, su))) su = (su + 1) % 4; used.add(Z.make(r, su)); s.piles['g' + i].push(K.card(Z.make(r, su), true)); }); + M.session.reset(s); return s.piles.g23[0].id; }""" + ) + phone.wait_for_timeout(1500) + assert not phone.evaluate("() => /No moves left/.test(document.body.innerText)") + at = tap_of(phone, first) + phone.touchscreen.tap(at["x"], at["y"]) + phone.wait_for_function("() => /No moves left/.test(document.body.innerText)", timeout=8000) + shot(phone, "montecarlo-stuck.png") + assert not phone.errors diff --git a/tests/test_games_table_snap_browser.py b/tests/test_games_table_snap_browser.py new file mode 100644 index 000000000..2df86425d --- /dev/null +++ b/tests/test_games_table_snap_browser.py @@ -0,0 +1,133 @@ +"""A board game left under way keeps a picture of its table for the shelf's live tile. + +Games built from page elements (squares, pieces, dice) have no canvas, so tablesnap.js paints the table as an svg: the +squares' colours, the pieces' own drawings, the words. This opens each of them, asks for the picture and checks it holds +the board (more than a bare frame, within the size the tile may keep); then plays a move in Reversi, leaves, and checks +the shelf's tile for it shows that picture in place of its art. + +Run: pytest tests/test_games_table_snap_browser.py -v +""" + +import functools +import http.server +import os +import threading + +import pytest + +GAMES = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "zimi", + "builtin", + "games", +) +PHONE = {"width": 390, "height": 844} +MAX_CHARS = 90000 +# page: the fewest painted shapes its opening table has (a bare frame is a handful) +BOARDS = { + "reversi": 35, + "checkers": 60, + "chess": 60, + "go": 8, + "xiangqi": 40, + "shogi": 40, + "hex": 3, + "gomoku": 10, + "morris": 10, + "fourinarow": 4, + "dotsandboxes": 20, + "backgammon": 20, + "mancala": 10, + "ludo": 20, + "chinesecheckers": 40, + "mahjong": 10, + "fleet": 40, + "memory": 10, + "noughts": 9, + "snakesandladders": 20, + "hnefatafl": 40, + "janggi": 40, + "makruk": 40, + "draughts": 40, + "ur": 10, + "sokoban": 20, +} + + +@pytest.fixture(scope="module") +def site(): + handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=GAMES) + handler.log_message = lambda *a, **k: None + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield "http://127.0.0.1:%d/" % srv.server_address[1] + srv.shutdown() + + +@pytest.fixture(scope="module") +def browser(): + sync_api = pytest.importorskip("playwright.sync_api") + with sync_api.sync_playwright() as p: + try: + b = p.chromium.launch() + except Exception as e: + pytest.skip("Chromium is not installed: %s" % e) + yield b + b.close() + + +@pytest.fixture() +def phone(browser): + ctx = browser.new_context( + viewport=PHONE, device_scale_factor=2, is_mobile=True, has_touch=True + ) + yield ctx + ctx.close() + + +def _picture(page, site, name): + page.goto(site + name + ".html") + page.wait_for_function("() => window.ZimiTableSnap", timeout=8000) + page.wait_for_timeout(300) + return page.evaluate("() => ZimiTableSnap.picture(document)") + + +@pytest.mark.parametrize("name", sorted(BOARDS)) +def test_table_is_painted(phone, site, name): + page = phone.new_page() + svg = _picture(page, site, name) + assert svg, name + " has no table picture" + assert svg.startswith("= BOARDS[name], "%s paints %d shapes" % (name, shapes) + assert "var(" not in svg, name + " leaves a colour unresolved" + + +def test_left_game_shows_its_table_on_the_shelf(phone, site): + page = phone.new_page() + page.goto(site + "reversi.html") + page.wait_for_selector(".bg-sq") + page.wait_for_function("() => window.ZimiTableSnap", timeout=8000) + # tap squares until one is a legal move (a tap that traps nothing is refused and costs nothing) + for i in range(64): + page.click('.bg-sq[data-i="%d"]' % i) + if page.evaluate("() => document.querySelectorAll('.rv-disc').length") > 4: + break + page.wait_for_function( + "() => document.querySelectorAll('.rv-disc').length > 4", timeout=8000 + ) + page.evaluate("() => window.dispatchEvent(new Event('pagehide'))") + saved = page.evaluate( + "() => JSON.parse(localStorage.getItem('zimi.games.snaps') || '{}')['reversi.html']" + ) + assert saved and saved["svg"].startswith(" + + + + +Accordion + + + + + +
+ ‹ +

Accordion

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/accordion.js b/zimi/builtin/games/accordion.js new file mode 100644 index 000000000..17405e9cd --- /dev/null +++ b/zimi/builtin/games/accordion.js @@ -0,0 +1,98 @@ +/* ZimiGames: Accordion. All 52 cards lie in a row, face up. A pile may be moved onto the pile next to it on the left, or the + one three places to the left, when their top cards match in suit or in rank. The gap closes up. Finish with one pile of 52. + State: piles a0..a51 (a pile's cards, the last is the top; an emptied pile stays empty), moves. The row is the piles that + still hold cards, in order, so a move is judged by place in the row, not by name. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, K = root.ZimiSolKit, TX = root.ZimiCards.T; + + var COLS = 8, PILES = Z.DECK, JUMP_NEAR = 1, JUMP_FAR = 3, STACK_SHOWN = 3, STACK_NUDGE = 2, ROW_GAP_SHARE = 0.08; + var NAMES = []; + for (var i = 0; i < PILES; i++) NAMES.push('a' + i); + + var top = K.top; + var topId = function (state, name) { var p = state.piles[name]; return top(p).id; }; + // The piles that still hold cards, in order along the row. + function row(state) { return NAMES.filter(function (n) { return state.piles[n].length; }); } + var matches = function (a, b) { return Z.suit(a) === Z.suit(b) || Z.rank(a) === Z.rank(b); }; + + // The piles a pile may move onto: the near and the far neighbor on its left, where the tops match. + function targets(state, name) { + var r = row(state), at = r.indexOf(name), out = []; + if (at < 0) return out; + [JUMP_NEAR, JUMP_FAR].forEach(function (back) { + if (at - back >= 0 && matches(topId(state, name), topId(state, r[at - back]))) out.push(r[at - back]); + }); + return out; + } + + function canPick(state, pile, idx) { var p = state.piles[pile]; return !!p && idx === p.length - 1 && p.length > 0; } + function legalMove(state, from, idx, to) { return from !== to && canPick(state, from, idx) && targets(state, from).indexOf(to) >= 0; } + function applyMove(state, from, idx, to) { + var s = Z.clone(state); + s.piles[to] = s.piles[to].concat(s.piles[from]); + s.piles[from] = []; + s.moves++; + return s; + } + // A tap moves a card that has one place to go; with two it asks to be dragged to the one wanted. + function bestMove(state, from, idx) { + if (!canPick(state, from, idx)) return null; + var t = targets(state, from); + return t.length === 1 ? t[0] : null; + } + function hasMove(state) { return row(state).some(function (n) { return targets(state, n).length > 0; }); } + function isWon(state) { return row(state).length === 1; } + function why(state, pile, idx, to) { + if (!canPick(state, pile, idx)) return null; + var t = targets(state, pile); + if (to === undefined && t.length > 1) return TX('accordion.why.choose'); + return TX('accordion.why.match'); + } + + function blankState() { return K.blankState(NAMES); } + function newState(order) { + var s = blankState(); + order.forEach(function (id, n) { s.piles[NAMES[n]].push(K.card(id, true)); }); + return s; + } + + // The row laid out in lines of COLS; a pile's cards are stacked with a nudge so its depth shows. + function place(state, m) { + var P = state.piles, rows = Z.solitaireRows(m), r = row(state), cards = [], slots = [], lineH = Math.round(m.ch * (1 + ROW_GAP_SHARE)); + var last = 0; + r.forEach(function (name, n) { + var px = m.left + (n % COLS) * m.step, py = rows.top + Math.floor(n / COLS) * lineH, p = P[name]; + p.forEach(function (c, k) { + var seen = k - (p.length - STACK_SHOWN), nudge = seen > 0 ? seen * STACK_NUDGE : 0; + cards.push({ id: c.id, pile: name, idx: k, x: px + nudge, y: py + nudge, up: true, hidden: seen < 0 }); + }); + slots.push({ id: name, x: px, y: py, w: m.cw, h: m.ch, label: Z.describePile(TX('accordion.pile', { n: n + 1 }), Z.idsOf(p), true) }); + last = py + m.ch; + }); + return { height: Math.max(last + m.pad, m.H), slots: slots, cards: cards }; + } + + function cascade(st) { + var name = row(st)[0]; + return st.piles[name].slice(-Z.KING).reverse().map(function (c) { return { id: c.id }; }); + } + // One move from a win: the ace of diamonds in a pile beside a pile of the other 51 cards that ends in the king of diamonds. + function almostWon() { + var s = blankState(), last = Z.make(Z.KING, 1), single = Z.make(1, 1), id; + for (id = 0; id < PILES; id++) if (id !== last && id !== single) s.piles.a0.push(K.card(id, true)); + s.piles.a0.push(K.card(last, true)); + s.piles.a1.push(K.card(single, true)); + return s; + } + + var api = { NAMES: NAMES, row: row, targets: targets, newState: newState, blankState: blankState, canPick: canPick, legalMove: legalMove, applyMove: applyMove, + bestMove: bestMove, hasMove: hasMove, isWon: isWon, why: why, place: place, almostWon: almostWon, S: { foundation: [] } }; + root.ZimiAccordion = api; + + function boot() { + K.page({ rules: api, id: 'accordion', title: 'Accordion', cols: COLS, place: place, cascade: cascade, + deal: function () { return newState(Z.shuffled(Z.random())); }, almostWon: almostWon }); + } + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/acesup.html b/zimi/builtin/games/acesup.html new file mode 100644 index 000000000..b6ef1f3fd --- /dev/null +++ b/zimi/builtin/games/acesup.html @@ -0,0 +1,30 @@ + + + + + +Aces Up + + + + + +
+ ‹ +

Aces Up

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/acesup.js b/zimi/builtin/games/acesup.js new file mode 100644 index 000000000..bdd197706 --- /dev/null +++ b/zimi/builtin/games/acesup.js @@ -0,0 +1,74 @@ +/* ZimiGames: Aces Up. Four columns, one card dealt on each. A card on top of a column goes out when the top of another column + is a higher card of its suit, aces highest. A column that is empty takes any top card. When nothing more can go, deal four + more. Win with only the four aces left on the table. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, K = root.ZimiSolKit; + + var TABLEAU = ['t0', 't1', 't2', 't3']; + var COLS = 4, DEAL_CARDS = 4, OUT_COL = 3, ACE_HIGH = Z.KING + 1; + var DECK = Z.DECK; + + var high = function (id) { return Z.rank(id) === 1 ? ACE_HIGH : Z.rank(id); }; + var tops = function (state) { return TABLEAU.map(function (t) { var p = state.piles[t]; return p.length ? p[p.length - 1].id : null; }); }; + // The card goes out when another column shows a higher card of its suit. + function removable(state, id) { + return tops(state).some(function (o) { return o !== null && o !== id && Z.suit(o) === Z.suit(id) && high(o) > high(id); }); + } + + function dealRow(state) { + if (state.piles.stock.length < DEAL_CARDS) return null; + var s = Z.clone(state); + TABLEAU.forEach(function (t) { var c = s.piles.stock.pop(); c.up = true; s.piles[t].push(c); }); + s.moves++; + return s; + } + + var R = K.rules({ + tableau: TABLEAU, foundation: ['out'], stock: 'stock', + runOK: function (list) { return list.length === 1; }, + builds: function () { return false; }, + takeFoundation: false, + fits: function (id, topId, n, state) { return removable(state, id); }, + isWon: function (state) { return state.piles.out.length === DECK - TABLEAU.length; }, + whyFoundation: 'acesup.why.out', whyBuild: 'acesup.why.out', whyEmpty: 'acesup.why.out', whyPick: 'acesup.why.top', + draw: dealRow + }); + var blank = function () { return K.blankState(['stock', 'out'].concat(TABLEAU)); }; + + function newState(order) { + var s = blank(), dealt; + order.forEach(function (id) { s.piles.stock.push(K.card(id, false)); }); + dealt = dealRow(s); + dealt.moves = 0; + return dealt; + } + + var place = K.layout({ + topRows: 1, + items: [{ pile: 'stock', kind: 'stock', col: 0, row: 0 }, { pile: 'out', kind: 'foundation', col: OUT_COL, row: 0, mark: '', label: 'acesup.out' }] + .concat(TABLEAU.map(function (t, n) { return { pile: t, kind: 'column', col: n, row: 1, n: n + 1 }; })) + }); + + // One move from a win: the deuce of spades beside the ace of spades, every other card but the four aces already out. + function almostWon() { + var s = blank(), id, left = [Z.make(1, 0), Z.make(1, 1), Z.make(1, 2), Z.make(1, 3), Z.make(2, 3)]; + for (id = 0; id < DECK; id++) if (left.indexOf(id) < 0) s.piles.out.push(K.card(id, true)); + s.piles.t0.push(K.card(left[0], true)); + s.piles.t1.push(K.card(left[1], true)); + s.piles.t2.push(K.card(left[2], true), K.card(left[3], true)); + s.piles.t3.push(K.card(left[4], true)); + return s; + } + + function cascade(st) { return st.piles.out.slice(-Z.KING).map(function (c) { return { id: c.id }; }); } + + var api = Object.assign(R, { newState: newState, blankState: blank, place: place, drawStock: dealRow, almostWon: almostWon, removable: removable, high: high }); + root.ZimiAcesUp = api; + + function boot() { + K.page({ rules: R, id: 'acesup', title: 'Aces Up', cols: COLS, place: place, refuse: 'sol.why.stockEmpty', cascade: cascade, + deal: function () { return newState(Z.shuffled(Z.random())); }, almostWon: almostWon }); + } + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/beleaguered.html b/zimi/builtin/games/beleaguered.html new file mode 100644 index 000000000..c89cdd354 --- /dev/null +++ b/zimi/builtin/games/beleaguered.html @@ -0,0 +1,30 @@ + + + + + +Beleaguered Castle + + + + + +
+ ‹ +

Beleaguered Castle

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/beleaguered.js b/zimi/builtin/games/beleaguered.js new file mode 100644 index 000000000..2d4d62d35 --- /dev/null +++ b/zimi/builtin/games/beleaguered.js @@ -0,0 +1,41 @@ +/* ZimiGames: Beleaguered Castle. The four aces start the foundations. The other 48 cards lie face up in eight columns of six. + Build down on any card, whatever its suit, one card at a time, and any card may fill an empty column. Foundations build up by + suit. Every card is in sight, so the whole game is thinking ahead. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, K = root.ZimiSolKit; + + var TABLEAU = ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'], FOUNDATION = ['f0', 'f1', 'f2', 'f3']; + var COLS = 8, COLUMN_CARDS = 6, FOUNDATION_COL = 2; + + var R = K.rules({ + tableau: TABLEAU, foundation: FOUNDATION, + runOK: function (list) { return list.length === 1; }, + builds: function (upper, lower) { return Z.rank(lower) === Z.rank(upper) - 1; }, + whyBuild: 'sol.why.down', whyEmpty: 'sol.why.nowhere', whyPick: 'sol.why.single' + }); + var blank = function () { return K.blankState(TABLEAU.concat(FOUNDATION)); }; + + // The aces go to the foundations; the rest are dealt six to a column, in order. + function newState(order) { + var s = blank(), k = 0, aces = order.filter(function (id) { return Z.rank(id) === 1; }), rest = order.filter(function (id) { return Z.rank(id) !== 1; }); + aces.forEach(function (id, n) { s.piles[FOUNDATION[n]].push(K.card(id, true)); }); + TABLEAU.forEach(function (t) { for (var j = 0; j < COLUMN_CARDS; j++) s.piles[t].push(K.card(rest[k++], true)); }); + return s; + } + + var place = K.layout({ + topRows: 1, + items: FOUNDATION.map(function (f, n) { return { pile: f, kind: 'foundation', col: FOUNDATION_COL + n, row: 0 }; }) + .concat(TABLEAU.map(function (t, n) { return { pile: t, kind: 'column', col: n, row: 1, n: n + 1 }; })) + }); + + var api = Object.assign(R, { newState: newState, blankState: blank, place: place, almostWon: function () { return K.almostWon(R, blank); } }); + root.ZimiBeleaguered = api; + + function boot() { + K.page({ rules: R, id: 'beleaguered', title: 'Beleaguered Castle', cols: COLS, place: place, + deal: function () { return newState(Z.shuffled(Z.random())); }, almostWon: api.almostWon }); + } + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/calculation.html b/zimi/builtin/games/calculation.html new file mode 100644 index 000000000..618bd24df --- /dev/null +++ b/zimi/builtin/games/calculation.html @@ -0,0 +1,30 @@ + + + + + +Calculation + + + + + +
+ ‹ +

Calculation

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/calculation.js b/zimi/builtin/games/calculation.js new file mode 100644 index 000000000..c4c4253d5 --- /dev/null +++ b/zimi/builtin/games/calculation.js @@ -0,0 +1,64 @@ +/* ZimiGames: Calculation. An ace, a deuce, a three and a four start four foundations; the first counts 1, 2, 3, the second 2, 4, + 6, the third 3, 6, 9, the fourth 4, 8, 12, each round the ranks from king to ace, and each ends on a king. The deck shows one card at a + time: it goes to a foundation if it fits, else onto one of four waste piles, where only the top card plays. Whatever the suit. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, K = root.ZimiSolKit; + + var WASTE = ['w0', 'w1', 'w2', 'w3'], FOUNDATION = ['f0', 'f1', 'f2', 'f3']; + var COLS = 5, DECK_COL = 4, RANKS = Z.KING; + // The cards that start the foundations, in order: ace of spades, two of hearts, three of clubs, four of diamonds. + var SEEDS = [Z.make(1, 3), Z.make(2, 2), Z.make(3, 0), Z.make(4, 1)]; + + // The rank a foundation wants after this one: its step further, round from king to ace. + var nextRank = function (rank, step) { return (rank + step - 1) % RANKS + 1; }; + var stepOf = function (pile) { return FOUNDATION.indexOf(pile) + 1; }; + var needs = function (state, pile) { var p = state.piles[pile]; return nextRank(Z.rank(p[p.length - 1].id), stepOf(pile)); }; + + var R = K.rules({ + tableau: WASTE, foundation: FOUNDATION, waste: 'deck', + runOK: function (list) { return list.length === 1; }, + builds: function () { return true; }, + canDrop: function (state, from, to) { return FOUNDATION.indexOf(to) >= 0 || from === 'deck'; }, + takeFoundation: false, + fits: function (id, topId, n, state, to) { return Z.rank(id) === needs(state, to); }, + whyFoundation: function (state, to) { return Z.T('calc.why', { rank: Z.T('cards.rank.' + needs(state, to)) }); }, + whyBuild: 'calc.why.deck', whyEmpty: 'calc.why.deck', whyPick: 'calc.why.top' + }); + var blank = function () { return K.blankState(['deck'].concat(WASTE, FOUNDATION)); }; + + function newState(order) { + var s = blank(); + FOUNDATION.forEach(function (f, n) { s.piles[f].push(K.card(SEEDS[n], true)); }); + order.filter(function (id) { return SEEDS.indexOf(id) < 0; }).forEach(function (id) { s.piles.deck.push(K.card(id, true)); }); + return s; + } + + var place = K.layout({ + topRows: 1, + items: [{ pile: 'deck', kind: 'waste', col: DECK_COL, row: 0, label: 'calc.deck' }] + .concat(FOUNDATION.map(function (f, n) { return { pile: f, kind: 'foundation', col: n, row: 0, n: n + 1, label: 'calc.foundation' }; })) + .concat(WASTE.map(function (w, n) { return { pile: w, kind: 'column', col: n, row: 1, n: n + 1, label: 'calc.waste' }; })) + }); + + // One move from a win: every foundation but the last king, which is the only card left on the deck. + function almostWon() { + var s = blank(); + FOUNDATION.forEach(function (f, n) { + var rank = Z.rank(SEEDS[n]), i; + s.piles[f].push(K.card(SEEDS[n], true)); + for (i = 1; i < RANKS; i++) { rank = nextRank(rank, n + 1); if (!(n === FOUNDATION.length - 1 && i === RANKS - 1)) s.piles[f].push(K.card(Z.make(rank, Z.suit(SEEDS[n])), true)); } + }); + s.piles.deck.push(K.card(Z.make(RANKS, Z.suit(SEEDS[FOUNDATION.length - 1])), true)); + return s; + } + + var api = Object.assign(R, { newState: newState, blankState: blank, place: place, almostWon: almostWon, nextRank: nextRank, needs: needs, SEEDS: SEEDS, WASTE: WASTE }); + root.ZimiCalculation = api; + + function boot() { + K.page({ rules: R, id: 'calculation', title: 'Calculation', cols: COLS, place: place, + deal: function () { return newState(Z.shuffled(Z.random())); }, almostWon: almostWon }); + } + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/canfield.html b/zimi/builtin/games/canfield.html new file mode 100644 index 000000000..50e4f5655 --- /dev/null +++ b/zimi/builtin/games/canfield.html @@ -0,0 +1,30 @@ + + + + + +Canfield + + + + + +
+ ‹ +

Canfield

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/canfield.js b/zimi/builtin/games/canfield.js new file mode 100644 index 000000000..846d08900 --- /dev/null +++ b/zimi/builtin/games/canfield.js @@ -0,0 +1,77 @@ +/* ZimiGames: Canfield. A reserve of thirteen cards (the top one face up), four columns of one card each, one foundation card + whose rank starts all four foundations, and a stock turned three at a time onto the waste, as often as you like. + Foundations build up by suit from that rank, round from king to ace. Columns build down in alternating colors, also round + from ace to king, and an in-order run moves as one. A gap in the columns fills itself from the reserve. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, K = root.ZimiSolKit; + + var TABLEAU = ['t0', 't1', 't2', 't3'], FOUNDATION = ['f0', 'f1', 'f2', 'f3']; + var COLS = 7, RESERVE_CARDS = 13, DRAW_COUNT = 3, SHOWN_WASTE = 3, GRID_COL = 3; + var RANKS = Z.KING; + + // One rank down, round: below the ace is the king. + var below = function (rank) { return (rank + RANKS - 2) % RANKS + 1; }; + var above = function (rank) { return rank % RANKS + 1; }; + var builds = function (upper, lower) { return Z.isRed(upper) !== Z.isRed(lower) && Z.rank(lower) === below(Z.rank(upper)); }; + + function drawStock(state) { + var s = Z.clone(state), P = s.piles, n, c; + if (P.stock.length) { + for (n = Math.min(DRAW_COUNT, P.stock.length); n > 0; n--) { c = P.stock.pop(); c.up = true; P.waste.push(c); } + } else if (P.waste.length) { + P.stock = P.waste.reverse().map(function (k) { return K.card(k.id, false); }); + P.waste = []; + } else return null; + s.moves++; + return s; + } + // A gap in the columns fills itself from the reserve. + function settle(s) { + TABLEAU.forEach(function (t) { + if (!s.piles[t].length && s.piles.r.length) { var c = s.piles.r.pop(); c.up = true; s.piles[t].push(c); if (s.piles.r.length) s.piles.r[s.piles.r.length - 1].up = true; } + }); + } + + var R = K.rules({ + tableau: TABLEAU, foundation: FOUNDATION, stock: 'stock', waste: 'waste', reserve: 'r', + runOK: function (list) { for (var i = 1; i < list.length; i++) if (!builds(list[i - 1], list[i])) return false; return true; }, + builds: builds, + fits: function (id, topId, n, state) { + return n === 0 ? Z.rank(id) === state.base : Z.suit(id) === Z.suit(topId) && Z.rank(id) === above(Z.rank(topId)); + }, + whyBuild: 'sol.why.wrap', whyEmpty: 'sol.why.nowhere', whyFoundation: 'sol.why.foundationBase', + draw: drawStock, settle: settle + }); + var blank = function () { var s = K.blankState(['stock', 'waste', 'r'].concat(TABLEAU, FOUNDATION)); s.base = 1; return s; }; + + // The reserve first, then the foundation card (it sets the rank), a card on each column, and the rest is the stock. + function newState(order) { + var s = blank(), k = 0, j; + for (j = 0; j < RESERVE_CARDS; j++) s.piles.r.push(K.card(order[k++], j === RESERVE_CARDS - 1)); + s.piles.f0.push(K.card(order[k], true)); s.base = Z.rank(order[k++]); + TABLEAU.forEach(function (t) { s.piles[t].push(K.card(order[k++], true)); }); + while (k < order.length) s.piles.stock.push(K.card(order[k++], false)); + return s; + } + + var place = K.layout({ + topRows: 1, + items: [{ pile: 'stock', kind: 'stock', col: 0, row: 0, mark: '↻' }, { pile: 'waste', kind: 'waste', col: 1, row: 0, shown: SHOWN_WASTE }, + { pile: 'r', kind: 'reserve', col: 0, row: 1 }] + .concat(FOUNDATION.map(function (f, n) { return { pile: f, kind: 'foundation', col: GRID_COL + n, row: 0, mark: function (st) { return Z.RANK_LABELS[st.base - 1]; } }; })) + .concat(TABLEAU.map(function (t, n) { return { pile: t, kind: 'column', col: GRID_COL + n, row: 1, n: n + 1 }; })) + }); + + // One card from a win: every foundation full from the ace but the last king, which waits on a column. + function almostWon() { return K.almostWon(R, blank); } + + var api = Object.assign(R, { newState: newState, blankState: blank, place: place, drawStock: drawStock, almostWon: almostWon, below: below, above: above }); + root.ZimiCanfield = api; + + function boot() { + K.page({ rules: R, id: 'canfield', title: 'Canfield', cols: COLS, place: place, refuse: 'sol.why.stockEmpty', + deal: function () { return newState(Z.shuffled(Z.random())); }, almostWon: almostWon }); + } + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/cardbacks.js b/zimi/builtin/games/cardbacks.js index fbd5f6b95..e21787d6d 100644 --- a/zimi/builtin/games/cardbacks.js +++ b/zimi/builtin/games/cardbacks.js @@ -12,6 +12,7 @@ 'use strict'; var W = 92, H = 132, CX = 46, CY = 66; + var ZIMI_NAVY = '#1e3460', ZIMI_NAVY_DEEP = '#15264a', ZIMI_RULE = '#c9d5ee', ZIMI_DISC_R = 10.5, ZIMI_Z_H = 10; var FX = 11, FY = 11, FW = 70, FH = 110; // the shared field: 7 x 11 cells of 10, or 5 x 5 of 14 x 22; an 11 unit band all round function f(v) { return String(+v.toFixed(2)); } function attrs(o) { return Object.keys(o).map(function (k) { return ' ' + k + '="' + o[k] + '"'; }).join(''); } @@ -67,21 +68,14 @@ // ── The twelve ── var ART = { - // Black and amber. Field 70 x 110 at (11,11): 45 degree lines every 10 make rhombi that meet the band in V's. The cartouche is - // the 5 x 9 block of cells (21..71 x 21..111) around the centre; the lattice stops on its frame. A diamond is inscribed in it and - // the Z sits at the centre, the one place the mark appears. + // Ink navy, quiet on the felt so face-down cards recede: a lattice of 45 degree lines every 10 in the shared field at a tenth + // of white, the band's two rules in pale blue, and the mark small at the exact centre (46, 66): the Z, ZIMI_Z_H tall, on a + // disc of the ground's darker step, ringed in the mark's gradient. The one place the mark appears. zimi: function () { - return rect(0, 0, W, H, { fill: '#0c0c0e' }) + - el('path', { d: diagonals(FX, FY, FW, FH, 10), fill: 'none', stroke: MARK_FROM, 'stroke-width': 0.5, opacity: 0.34 }) + - rect(3.5, 3.5, 85, 125, { fill: 'none', stroke: 'url(#zc-g-mark)', 'stroke-width': 1.2 }) + - rect(7.5, 7.5, 77, 117, { fill: 'none', stroke: MARK_FROM, 'stroke-width': 0.5, opacity: 0.45 }) + - rect(FX, FY, FW, FH, { fill: 'none', stroke: MARK_FROM, 'stroke-width': 0.5, opacity: 0.45 }) + - rect(21, 21, 50, 90, { fill: '#100d0c', stroke: 'url(#zc-g-mark)', 'stroke-width': 1.2 }) + - '' + - el('path', { d: diamond(46, 66, 25, 45), fill: '#17120f', stroke: 'url(#zc-g-mark)', 'stroke-width': 1.2 }) + - el('path', { d: diamond(46, 66, 21.5, 38.7), fill: 'none', stroke: MARK_FROM, 'stroke-width': 0.5, opacity: 0.5 }) + - env.markZ(46, 66, 28) + - '' + [[30, 31], [62, 31], [30, 101], [62, 101]].map(function (p) { return ''; }).join('') + ''; + return band(ZIMI_NAVY, ZIMI_RULE) + + el('path', { d: diagonals(FX, FY, FW, FH, 10), fill: 'none', stroke: '#ffffff', 'stroke-width': 0.5, opacity: 0.1 }) + + '' + + env.markZ(CX, CY, ZIMI_Z_H); }, // Royal blue, ivory and red. Field 70 x 110: 7 x 11 cells of 10, a whole diamond in each (corners on the cell edges' midpoints). // The medallion is the 3 x 5 block at the centre (31..61 x 41..91) with a diamond inscribed in it and a red one inside that. diff --git a/zimi/builtin/games/cards.css b/zimi/builtin/games/cards.css index 0b61541d5..108f9880c 100644 --- a/zimi/builtin/games/cards.css +++ b/zimi/builtin/games/cards.css @@ -27,35 +27,58 @@ body.zc-game { display: flex; flex-direction: column; height: 100%; overflow: hi /* ── Piles ─────────────────────────────────────────────────────────────── */ .zc-slot { position: absolute; left: 0; top: 0; z-index: 0; outline: none; -webkit-tap-highlight-color: transparent; } .zc-slot::before { content: ""; position: absolute; left: 0; top: 0; box-sizing: border-box; width: var(--cw); height: calc(var(--cw) * 1.4); - border-radius: calc(var(--cw) * 0.075); border: 2px solid var(--felt-line); background: rgba(0, 0, 0, 0.08); } + border-radius: var(--zc-r); border: 1.5px solid var(--felt-line); background: rgba(0, 0, 0, 0.12); } /* A goal pile (the foundations, Spider's finished runs) is the brightest outline on the felt, not the dimmest. */ -.zc-slot[data-goal]::before { border-color: rgba(255, 255, 255, 0.5); background: rgba(255, 255, 255, 0.1); } -.zc-slot[data-goal][data-mark]::after { color: rgba(255, 255, 255, 0.62); } +.zc-slot[data-goal]::before { border-color: rgba(var(--on-felt-rgb), 0.34); background: rgba(var(--on-felt-rgb), 0.07); } +.zc-slot[data-goal][data-mark]::after { color: rgba(var(--on-felt-rgb), 0.42); } .zc-slot[data-quiet]::before { display: none; } .zc-slot[data-cards]:focus-visible::before { border-color: var(--felt-line); box-shadow: none; } .zc-slot:focus-visible::before { border-color: var(--select-ring); box-shadow: 0 0 0 2px var(--select-ring); } .zc-slot[data-mark]::after { content: attr(data-mark); position: absolute; left: 0; top: 0; width: var(--cw); height: calc(var(--cw) * 1.4); - display: grid; place-items: center; color: rgba(255, 255, 255, 0.28); font: 650 calc(var(--cw) * 0.46)/1 var(--font); letter-spacing: -0.02em; pointer-events: none; } + display: grid; place-items: center; color: rgba(var(--on-felt-rgb), 0.26); font: 600 calc(var(--cw) * 0.4)/1 var(--font); letter-spacing: -0.02em; pointer-events: none; } .zc-slot[data-mark="\21BB"]::after { font-family: var(--font); font-weight: 400; } /* ── A card ────────────────────────────────────────────────────────────── */ +/* One light, straight above: a tight contact shadow and a soft one under it, both falling down; a lifted card's grow with its + height. The edge is one device pixel of warm grey (--zc-px), drawn inside the paper. Radius 0.055 of the width (a printed card's + is 0.05). Flights: --zc-fly is set per move by distance (cards.js FLY_*); --zc-ease is the landing curve. */ +.zc-stage { --zc-r: calc(var(--cw) * 0.055); --zc-rest: 0 0.5px 1px rgba(0, 0, 0, 0.3), 0 1.5px 4px rgba(0, 0, 0, 0.14); + --zc-lifted: 0 4px 6px rgba(0, 0, 0, 0.18), 0 14px 26px rgba(0, 0, 0, 0.26); --zc-ease: cubic-bezier(0.2, 0.9, 0.3, 1); } .zc-card { position: absolute; left: 0; top: 0; width: var(--cw); height: calc(var(--cw) * 1.4); z-index: 1; - border-radius: calc(var(--cw) * 0.075); background: var(--card); color: var(--suit-black); - box-shadow: 0 1px 2px rgba(0, 0, 0, 0.45), 0 0 0 1px var(--card-edge); - transition: transform 0.17s cubic-bezier(0.25, 0.8, 0.35, 1); touch-action: none; cursor: grab; overflow: hidden; } + border-radius: var(--zc-r, 4px); background: var(--card); color: var(--suit-black); + box-shadow: var(--zc-rest), inset 0 0 0 var(--zc-px, 1px) var(--card-edge); + transition: transform var(--zc-fly, 0.2s) var(--zc-ease), box-shadow 0.12s ease-out; touch-action: none; cursor: grab; overflow: hidden; } .zc-card.zc-red { color: var(--suit-red); } .zc-card.zc-off { visibility: hidden; } .zc-card.zc-instant, .zc-instant .zc-card { transition: none; } -.zc-card.zc-drag { transition: none; cursor: grabbing; box-shadow: 0 8px 18px rgba(0, 0, 0, 0.45), 0 0 0 1px var(--card-edge); } +/* Held: lifted at once on the press. The lift is drawn by the face (or back) inside the card, scaled about the grab point (--zc-o, + set by cards.js) so the card's own transform stays its place; the paper and shadow move to it while held, and ease back on the drop. */ +.zc-card > .zc-face, .zc-card > .zc-back { border-radius: inherit; transform-origin: var(--zc-o, 50% 30%); + box-shadow: 0 0 0 rgba(0, 0, 0, 0), 0 0 0 rgba(0, 0, 0, 0); transition: transform 0.12s ease-out, box-shadow 0.12s ease-out; } +.zc-card.zc-drag { transition: none; cursor: grabbing; overflow: visible; background: none; box-shadow: none; } +.zc-card.zc-drag > .zc-face, .zc-card.zc-drag > .zc-back { background: var(--card); transform: scale(1.06) translateY(-2px); + box-shadow: var(--zc-lifted), inset 0 0 0 var(--zc-px, 1px) var(--card-edge); transition: transform 0.09s cubic-bezier(0.2, 0.8, 0.2, 1), box-shadow 0.09s cubic-bezier(0.2, 0.8, 0.2, 1); } +/* A refused drop goes home with a small overshoot: the "no" is in the motion. */ +.zc-card.zc-refused { transition: transform 0.24s cubic-bezier(0.3, 1.35, 0.5, 1); } +/* Where a drop would land: the pile ringed while a card is held over it. */ +.zc-slot.zc-target::before, .zc-card.zc-target { box-shadow: 0 0 0 1px rgba(26, 18, 9, 0.6), 0 0 0 3px var(--select-ring); } .zc-card.zc-focus { outline: 2px solid var(--select-ring); outline-offset: 2px; } /* A card you cannot play is not greyed: the cards you can play are lifted (their layout puts them higher). */ /* The ring is three pixels of the accent with a dark line inside it: a pale card on a pale or a dark table still shows which card the hint means. */ .zc-card.zc-glow { box-shadow: 0 0 0 1px rgba(26, 18, 9, 0.85), 0 0 0 4px var(--select-ring), 0 0 14px 5px var(--legal); } .zc-card.zc-sel { box-shadow: var(--select), 0 4px 10px rgba(0, 0, 0, 0.4); } .zc-dealing .zc-card { pointer-events: none; } -.zc-card.zc-flip { animation: zc-flip 0.2s ease-out; } .zc-card.zc-hint { animation: zc-nudge 0.28s ease-in-out; } -@keyframes zc-flip { from { transform: var(--zc-t) scaleX(0.05); } to { transform: var(--zc-t) scaleX(1); } } +/* A turn, not a squash: the back turns away (rotateY to 90 deg), the face comes round from the other side; back and face swap at + the turn's edge-on moment (45%). It waits (--zc-turn-wait, set by cards.js) for the card that uncovered it to land. */ +.zc-card.zc-flip { animation: zc-turn var(--zc-turn, 0.2s) linear var(--zc-turn-wait, 0s) both; } +@keyframes zc-turn { 0% { transform: var(--zc-t) perspective(600px) rotateY(0deg); animation-timing-function: cubic-bezier(0.5, 0, 1, 1); } + 45% { transform: var(--zc-t) perspective(600px) rotateY(90deg); animation-timing-function: cubic-bezier(0, 0, 0.3, 1); } + 100% { transform: var(--zc-t) perspective(600px) rotateY(0deg); } } +.zc-stage .zc-card.zc-flip > .zc-back { display: block; animation: zc-turn-back var(--zc-turn, 0.2s) step-end var(--zc-turn-wait, 0s) both; } +.zc-stage .zc-card.zc-flip > .zc-face { animation: zc-turn-face var(--zc-turn, 0.2s) step-end var(--zc-turn-wait, 0s) both; } +@keyframes zc-turn-back { 0% { visibility: visible; } 45%, 100% { visibility: hidden; } } +@keyframes zc-turn-face { 0% { visibility: hidden; } 45%, 100% { visibility: visible; } } @keyframes zc-nudge { 0%, 100% { margin-left: 0; } 30% { margin-left: -4px; } 70% { margin-left: 4px; } } .zc-card { container-type: inline-size; } .zc-face, .zc-back { position: absolute; inset: 0; } @@ -76,6 +99,17 @@ body.zc-game { display: flex; flex-direction: column; height: 100%; overflow: hi /* The cream cut that keeps parts of one colour apart is under a pixel on a small card: it keeps a pixel. */ @container (max-width: 56px) { .zc-face [stroke="#fdfcf8"][stroke-width="0.9"] { stroke-width: 1.4; } } .zc-face svg, .zc-back svg { display: block; width: 100%; height: 100%; } +/* The French face's two index arrangements (cards.js frenchIndex): the row for piles that fan down, the column for hands that fan + sideways (a board made with index: 'col'); a court's frame moves down under the column. */ +.zc-ix-col { display: none; } +.zc-cols .zc-ix-row { display: none; } +.zc-cols .zc-ix-col { display: inline; } +.zc-ct-col { display: none; } +.zc-cols .zc-ct-row { display: none; } +.zc-cols .zc-ct-col { display: inline; } +/* In a hand a strip shows only a card's left third: the body's suit stands to the lower right, clear of the strip, so a strip is + the index and paper (FACE.body's left edge at 0.44 of the width, past the widest strip). */ +.zc-cols .zc-body { transform: translate(62px, 96px) scale(0.86) translate(-50px, -90px); } /* about the suit's own centre (50, FACE.bodyY), in face units */ .zc-card.zc-down .zc-face { display: none; } .zc-card:not(.zc-down) .zc-back { display: none; } @@ -142,7 +176,7 @@ body.zc-game { display: flex; flex-direction: column; height: 100%; overflow: hi .zc-win-big { margin: 0 0 4px; font-size: var(--fs-display); letter-spacing: -0.02em; font-variant-numeric: tabular-nums; } /* An opponent's hand of more than five cards is one back and a count. */ -.ct-count { position: absolute; z-index: 1100; display: grid; place-items: center; min-width: 28px; height: 28px; padding: 0 var(--sp-2); border-radius: 999px; background: rgba(0, 0, 0, 0.6); color: #fff; font: 650 var(--fs-small) var(--font); font-variant-numeric: tabular-nums; pointer-events: none; transform: translate(-50%, -50%); } +.ct-count { position: absolute; z-index: 1100; display: grid; place-items: center; min-width: 28px; height: 28px; padding: 0 var(--sp-2); border-radius: 999px; background: rgba(0, 0, 0, 0.6); color: var(--on-felt); font: 650 var(--fs-small) var(--font); font-variant-numeric: tabular-nums; pointer-events: none; transform: translate(-50%, -50%); } /* The cascade's canvas, above the table and below the sheets. */ .zc-cascade { position: fixed; inset: 0; width: 100%; height: 100%; z-index: 40; touch-action: none; } .zc-live { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); } @@ -160,3 +194,17 @@ body.zc-game { display: flex; flex-direction: column; height: 100%; overflow: hi /* A card that cannot be played now (a covered Pyramid card, an illegal card in a hand): a light veil, so it still reads as a card. */ .zc-card.zc-dim::after { content: ""; position: absolute; inset: 0; border-radius: inherit; background: rgba(0, 0, 0, 0.12); pointer-events: none; } + +/* Red, generated by scripts/games_red.py from the rules above: do not edit. */ +:root.gs.night-red .zc-table::after { background: radial-gradient(ellipse at 50% 45%, transparent 55%, rgba(0, 0, 0, 0.22) 100%); } +:root.gs.night-red .zc-slot::before { background: rgba(0, 0, 0, 0.12); } +:root.gs.night-red .zc-stage { --zc-rest: 0 0.5px 1px rgba(0, 0, 0, 0.3), 0 1.5px 4px rgba(0, 0, 0, 0.14); --zc-lifted: 0 4px 6px rgba(0, 0, 0, 0.18), 0 14px 26px rgba(0, 0, 0, 0.26); } +:root.gs.night-red .zc-card > .zc-face, :root.gs.night-red .zc-card > .zc-back { box-shadow: 0 0 0 rgba(0, 0, 0, 0), 0 0 0 rgba(0, 0, 0, 0); } +:root.gs.night-red .zc-slot.zc-target::before, :root.gs.night-red .zc-card.zc-target { box-shadow: 0 0 0 1px rgba(19, 2, 1, 0.6), 0 0 0 3px var(--select-ring); } +:root.gs.night-red .zc-card.zc-glow { box-shadow: 0 0 0 1px rgba(19, 2, 1, 0.85), 0 0 0 4px var(--select-ring), 0 0 14px 5px var(--legal); } +:root.gs.night-red .zc-card.zc-sel { box-shadow: var(--select), 0 4px 10px rgba(0, 0, 0, 0.4); } +:root.gs.night-red .ct-count { background: rgba(0, 0, 0, 0.6); } +:root.gs.night-red .zc-toast { box-shadow: 0 8px 22px rgba(0, 0, 0, 0.3); } +:root.gs.night-red .zc-fact { background: rgba(0, 0, 0, 0.34); color: #ff2010; } +:root.gs.night-red .zc-card.zc-dim::after { background: rgba(0, 0, 0, 0.12); } +/* end Red */ diff --git a/zimi/builtin/games/cards.js b/zimi/builtin/games/cards.js index de1d3339d..ab853d6c4 100644 --- a/zimi/builtin/games/cards.js +++ b/zimi/builtin/games/cards.js @@ -83,13 +83,10 @@ } // ── The Zimi deck ───────────────────────────────────────────────────── - // Original French-suited deck. Everything is drawn: indices are stroked - // paths (no font is ever needed), courts are geometric busts built from a - // few shapes, and the Ace of Spades carries the ZimiGames mark. One face is - // one SVG in a 100x140 box. Detail that cannot be seen on a small card is - // marked `zc-fine`, a small card's own layout `zc-small` / `zc-idx-row`: - // cards.css switches them by the card's width (container query), so the - // same markup serves a phone's Spider (33 px) and a desktop's Solitaire. + // Original French-suited deck. Everything is drawn: indices are font outlines set as paths (no font is ever needed), the courts + // are the public-domain Goodall figures (courts.js) framed, and the Ace of Spades carries the ZimiGames mark. One face is one SVG + // in a 100x140 box. The French face is one layout at every size (see frenchIndex); the Italian and Spanish decks keep a small + // card's own layout, `zc-small` / `zc-idx-row`, which cards.css switches by the card's width (container query). // Suit shapes centred on 0,0 inside ±10; one sprite, `use`d by every card. // The four suits as one family at card-maker proportions (clubs, diamonds, hearts, spades; a 20-unit box each): the spade's // cusp and flared stem are reused by the club; heart and diamond are matched to them for height and weight. @@ -109,14 +106,14 @@ '' ]; var ITALIAN_COLOURS = ['#b87500', '#c62828', '#2c4a86', '#2f7d4f']; - var CARD_RED = '#b3261e', CARD_BLACK = '#1b1b1b', CARD_CREAM = '#fdfcf8', CARD_EDGE = '#c9c4b8'; // games.css tokens, repeated for the cascade's bitmaps + var CARD_RED = '#bc3428', CARD_BLACK = '#22252c', CARD_CREAM = '#f9f6ee', CARD_EDGE = '#cdc6b6'; // games.css tokens, repeated for the cascade's bitmaps var GOLD = '#e09400', MARK_FROM = '#fb8c14', MARK_TO = '#f2582a'; // Zimi's amber, and the two ends of the Z's gradient - var FACE_W = 100, FACE_H = 140, ACE_SCALE = 3.3, ACE_SPADE_SCALE = 3.9; + var FACE_W = 100, FACE_H = 140; // The Ace of Spades carries the maker's mark: the Z alone, in the spade's belly (centre 0.3 of the spade's 20-unit box below its middle, // 9 units tall, clear of the outline on every side). - var ACE_Z_DY = 0.3, ACE_Z_UNITS = 5.4, ACE_Z_Y = 70 + ACE_Z_DY * ACE_SPADE_SCALE, ACE_Z_H = ACE_Z_UNITS * ACE_SPADE_SCALE, BACK_Z_H = 32.2; // and the Zimi back's + var ACE_Z_DY = 0.3, ACE_Z_UNITS = 5.4, BACK_Z_H = 32.2; // and the Zimi back's // The pips stand in a box of their own, inset from the index column: the outer columns clear the corner suit by 8 units and the top row sits below it (at 37 and 63, from 34, a count ran into it). - var PIP_SCALE = 0.86, PIP_SCALE_DENSE = 0.76, DENSE_FROM = 8, PIP_COLS = [39, 61], PIP_MID_X = 50, PIP_TOP = 38, PIP_BOTTOM = 102, PIP_CENTRE = 70, PIP_ROW_2 = 58.7, PIP_ROW_3 = 81.3, FLIP_AFTER_Y = 70; + var PIP_COLS = [39, 61], PIP_MID_X = 50, PIP_TOP = 38, PIP_BOTTOM = 102, PIP_CENTRE = 70, PIP_ROW_2 = 58.7, PIP_ROW_3 = 81.3; var PIPS = (function () { var sides = function (ys) { var o = []; ys.forEach(function (y) { PIP_COLS.forEach(function (x) { o.push([x, y]); }); }); return o; }; var mid = function (y) { return [PIP_MID_X, y]; }; @@ -330,23 +327,33 @@ gold('M43 32 41.4 24.4 46 27.6 50 22.4 54 27.6 58.6 24.4 57 32z') + '' + heldItalian(s, 67, 65.6, standalone, compact, set); } - var COURT_PIP_X = 31.5, COURT_PIP_Y = 27, COURT_PIP_SCALE = 0.55, COURT_BAND = 7, COURT_MID_PIP = 0.62; - var SMALL_COURT = ''; + // A French court: the figure fills the card under the index, COURT_MARGIN in from the left, right and bottom edges (one even + // margin), from COURT_TOP down (just under the index row, the Q's tail included). Under the column index (hands) it starts + // COURT_GAP under the column's suit. Both frames are in every face and cards.css shows the one that goes with the index (the + // standalone image has the row's). Without courts.js the drawn bust stands in. + // A covered court in a fan shows its index row and nothing of the picture: no fan steps more than indexStep. + function courtFrames() { + var w = FACE_W - 2 * COURT_MARGIN, bottom = FACE_H - COURT_MARGIN, colTop = FACE.top + FACE.colCap + FACE.colGap + FACE.colSuit + COURT_GAP; + return { row: { x: COURT_MARGIN, y: COURT_TOP, w: w, h: bottom - COURT_TOP }, col: { x: COURT_MARGIN, y: colTop, w: w, h: bottom - colTop } }; + } + function courtFrame(kind, s, f, cls, standalone) { + var art = root.ZimiCourts && root.ZimiCourts.panel ? root.ZimiCourts.panel(kind, s, f.x, f.y, f.w, f.h, standalone) : ''; + if (!art) art = '' + bust(kind, s, true) + ''; + var r = 'x="' + f.x + '" y="' + f.y + '" width="' + f.w + '" height="' + f.h + '" rx="' + COURT_RX + '"'; + return '' + art + + ''; + } function courtMarkup(kind, s, standalone) { - var art = root.ZimiCourts && root.ZimiCourts.markup(kind, s, IDX_COLUMN); // the public-domain courts (courts.js), when the page has them - if (art) return '' + art + '' + (standalone ? '' : '' + root.ZimiCourts.thumb(kind, s) + ''); - var half = bust(kind, s) + placed(s, COURT_PIP_X, COURT_PIP_Y, COURT_PIP_SCALE, false, standalone); - var line = function (y) { return ''; }; - return '' + - '' + - line(COURT_BASE) + line(140 - COURT_BASE) + '' + - placed(s, 50, 70, COURT_MID_PIP, false, standalone) + - '' + half + '' + half + '' + - (standalone ? '' : SMALL_COURT + bust(kind, s, true) + ''); + var f = courtFrames(); + return courtFrame(kind, s, f.row, 'zc-ct zc-ct-row', standalone) + (standalone ? '' : courtFrame(kind, s, f.col, 'zc-ct zc-ct-col', false)); } + var SMALL_SUIT_Y = 92, SMALL_SUIT_SCALE = 3.1, SUIT_BOX = 20, COURT_RX = 2.5, COURT_TOP = 40, COURT_GAP = 3, COURT_MARGIN = 2.5; // SUIT_BOX: a suit shape's size in its own units + // What a covered face-up card shows (its index row, ending half a unit above a court's picture) as a share of its height: the most any + // vertical fan opens, whatever the rank (FAN_UP_SHARE). + var INDEX_ROW_SHARE = (COURT_TOP - 0.5) / FACE_H; + function indexStep(ch) { return INDEX_ROW_SHARE * ch; } // The same pip for the small card's simplified body. - var SMALL_SUIT_Y = 92, SMALL_SUIT_SCALE = 3.1; function smallSuit(s, standalone, shapes, prefix, extra) { return standalone ? '' : '' + placed(s, 50, SMALL_SUIT_Y, SMALL_SUIT_SCALE, false, false, shapes, prefix) + (extra || '') + ''; } @@ -356,25 +363,47 @@ function faceFrame(inner, colour, standalone) { return standalone ? '' + MARK_GRADIENT + '' + - '' + inner + '' + '' + inner + '' : ''; } - // One French-suited card face as SVG markup (ids 0..51, further decks - // wrap). The page's card element sets the suit colour. + // ── The French face ───────────────────────────────────────────────────── + // Made for a card seen at 50 px on a phone, not 63 mm in the hand: one large index and one suit, no pip grid. + // The index has two arrangements in every face, chosen by the board (cards.css): `zc-ix-row` puts the suit in the top right + // corner, beside the rank, for piles that fan downwards (the solitaires); `zc-ix-col` puts it under the rank, for hands that + // fan sideways and show only a card's left strip (the table games). Units are the 100 x 140 face. + // FACE.cap the rank's cap height (0.26 of the width: 13 px on a 50 px card, twice a printed card's share) + // FACE.top the cap line's distance from the top edge; FACE.side the rank's ink from the left edge + // FACE.suit the index suit's box in the row; FACE.colSuit under the rank + // FACE.body the one suit of a number card, centred at FACE.bodyY: low on the card, so a fanned strip shows the index + // and clean paper, never a cut shape; FACE.ace the ace's + // FACE.colCap the rank in the column, a little smaller so a 10 fits the narrowest strip of a hand (cardtable MIN_STRIP_PX, + // 0.31 of a card): its ink ends 30 units in + var FACE = { cap: 26, colCap: 22, top: 8, side: 8, suit: 21, colSuit: 15, colGap: 4.5, body: 42, bodyY: 90, ace: 56, aceY: 94 }; + // Optical sizes: a two-figure rank is wider and the round, heavy letters look bigger than a 7 at one cap height. + var OPTICAL = { '10': 0.93, Q: 0.95, K: 0.97, J: 1.02 }; + // The rank's scale for a cap height; a smaller optical size keeps the baseline, not the cap line (rankTop). + function rankScale(label, cap) { return cap / GLYPH_CAP * (OPTICAL[label] || 1); } + function rankTop(label, cap) { return FACE.top + cap - GLYPH_CAP * rankScale(label, cap); } + function frenchIndex(label, s, standalone) { + var sc = rankScale(label, FACE.cap), w = glyphWidth(label) * sc; + var row = '' + glyph(label, FACE.side + w / 2, rankTop(label, FACE.cap), sc) + + placed(s, FACE_W - FACE.side - FACE.suit / 2, FACE.top + FACE.cap / 2, FACE.suit / SUIT_BOX, false, standalone) + ''; + if (standalone) return row; + var cs = rankScale(label, FACE.colCap), colCx = FACE.side + Math.max(glyphWidth(label) * cs, FACE.colSuit) / 2; + var col = '' + glyph(label, colCx, rankTop(label, FACE.colCap), cs) + + placed(s, colCx, FACE.top + FACE.colCap + FACE.colGap + FACE.colSuit / 2, FACE.colSuit / SUIT_BOX, false, standalone) + ''; + return row + col; + } + + // One French-suited card face as SVG markup (ids 0..51, further decks wrap). The page's card element sets the suit colour. function faceMarkup(id, standalone) { var r = rank(id), s = suit(id), label = RANK_LABELS[r - 1], body; if (r === 1) { - var spadeAce = s === 3; - body = '' + placed(s, 50, 70, spadeAce ? ACE_SPADE_SCALE : ACE_SCALE, false, standalone) + (spadeAce ? markZ(50, ACE_Z_Y, ACE_Z_H) : '') + '' + - smallSuit(s, standalone, null, null, spadeAce ? markZ(50, SMALL_SUIT_Y + ACE_Z_DY * SMALL_SUIT_SCALE, ACE_Z_UNITS * SMALL_SUIT_SCALE) : ''); - } else if (r <= 10) { - var pips = ''; - PIPS[r].forEach(function (p) { pips += placed(s, p[0], p[1], r >= DENSE_FROM ? PIP_SCALE_DENSE : PIP_SCALE, p[1] > FLIP_AFTER_Y, standalone); }); - body = '' + pips + '' + smallSuit(s, standalone); - } else body = courtMarkup(COURT_KINDS[r - 11], s, standalone); - var index = indexMarkup(label, s, standalone); // a court's art lies under its index - return faceFrame(r > 10 ? body + index : index + body, standalone ? (isRed(id) ? CARD_RED : CARD_BLACK) : '', standalone); + body = placed(s, 50, FACE.aceY, FACE.ace / SUIT_BOX, false, standalone) + (s === 3 ? markZ(50, FACE.aceY + ACE_Z_DY * FACE.ace / SUIT_BOX, ACE_Z_UNITS * FACE.ace / SUIT_BOX) : ''); + } else if (r <= 10) body = placed(s, 50, FACE.bodyY, FACE.body / SUIT_BOX, false, standalone); + else body = courtMarkup(COURT_KINDS[r - 11], s, standalone); + return faceFrame(frenchIndex(label, s, standalone) + (r <= 10 ? '' + body + '' : body), standalone ? (isRed(id) ? CARD_RED : CARD_BLACK) : '', standalone); } // The Italian deck, 40 cards: id = suit * 10 + (rank - 1), suits coins, @@ -794,7 +823,8 @@ holder.innerHTML = ''; + SPANISH_SHAPES.map(function (shape, s) { return '' + shape + ''; }).join('') + + (root.ZimiCourts && root.ZimiCourts.symbols ? root.ZimiCourts.symbols() : '') + SPRITE_DEFS + ''; d.body.insertBefore(holder.firstChild, d.body.firstChild); } // The one note a card game gives a player: why a card would not go, what a tap on the stock did. It sits low on the felt, where @@ -887,8 +917,12 @@ // [{id, pile, idx, x, y, up, hidden}] in stacking order. var SNAP_FELT = '#285c43', SNAP_CREAM = '#fdfcf8', SNAP_RED = '#b3261e', SNAP_BLACK = '#1b1b1b', SNAP_BACK = '#23232b', SNAP_BACK_EDGE = '#e8710a', SNAP_RX = 5; var SNAP_SUIT = ['\u2663', '\u2666', '\u2665', '\u2660']; - var MAX_CARD_W = 120, CARD_ASPECT = 1.4, CARD_H_SHARE = 0.14, DRAG_SLOP = 6, SETTLE_MS = 300, Z_HOT = 500, Z_DRAG = 1000; - var DEAL_STAGGER_MS = 16, MIN_CARD_W = 24, TIGHT_PAD = 2, TIGHT_GAP = 2; + var WIDE_RATIO = 1.25, PLACE_BUZZ_MS = 8, MAX_CARD_W = 120, CARD_ASPECT = 1.4, CARD_H_SHARE = 0.14, DRAG_SLOP = 6, SETTLE_MS = 300, Z_HOT = 500, Z_DRAG = 1000; + var DEAL_STAGGER_MS = 30, DEAL_SPAN_MS = 900, MIN_CARD_W = 24, TIGHT_PAD = 2, TIGHT_GAP = 2, GAP_SHARE = 0.08, DENSE_COLS = 9; // DENSE_COLS: nine or ten columns (Spider, Forty Thieves) take the whole width to the table's 2 px edge: the cards are small enough already + // A flight takes FLY_BASE_MS and FLY_PER_PX_MS for each pixel it travels, at most FLY_MAX_MS: a card sent across the table is seen + // to travel, one settling a few pixels does not dawdle. A turned card starts to turn as the card that uncovered it lands: the + // flight's ease-out has it all but there at TURN_AT_LANDING of its time (a wait of the whole flight read as a pause on video). + var FLY_BASE_MS = 120, FLY_PER_PX_MS = 0.35, FLY_MAX_MS = 300, TURN_AT_LANDING = 0.7, TURN_MS = 200, REFUSED_MS = 260, RING_MS = 1000, REPEAT_MS = 4000; // More o: heightShare (how much of the table's height a card may take, for // layouts shorter than Klondike's columns), face(id, standalone) (a deck of // its own: Scopa's), enterTaps (Enter on a pile taps @@ -901,11 +935,13 @@ // the rules drawn at whole units of the face land on pixel edges. It only ever rounds down, so the columns still fit. var CRISP_STEP = 5; function dpr() { return Math.max(1, Math.min(3, root.devicePixelRatio || 1)); } + function flyMs(px) { return Math.round(Math.min(FLY_MAX_MS, FLY_BASE_MS + FLY_PER_PX_MS * px)); } function crispWidth(cw) { var k = dpr(); return Math.max(CRISP_STEP, Math.floor(cw * k / CRISP_STEP) * CRISP_STEP) / k; } function createBoard(o) { - var d = root.document, table = o.table, stage = h('div', { class: 'zc-stage' }); + var d = root.document, table = o.table, stage = h('div', { class: 'zc-stage' + (o.index === 'col' ? ' zc-cols' : '') }); var live = h('div', { class: 'zc-live', 'aria-live': 'polite' }); + stage.style.setProperty('--zc-turn', TURN_MS + 'ms'); table.appendChild(stage); table.appendChild(live); var els = {}, slotEls = {}, cardPos = {}, byPile = {}, slotRects = {}; // The count chips of collapsed face-down hands (layout: counts [{ x, y, n }]), over the cards. @@ -920,14 +956,23 @@ d.documentElement.style.setProperty('--zc-px', 1 / dpr() + 'px'); var W = table.clientWidth, H = table.clientHeight; var pad = Math.max(6, Math.min(16, Math.round(W * 0.02))), gap = Math.max(4, Math.round(W * 0.014)); - if (o.tight) { pad = Math.min(pad, TIGHT_PAD); gap = Math.min(gap, TIGHT_GAP); } // the solitaires' columns take every pixel of the width - var cols = colsFor(lastState, W, pad, gap); + // A wide table (landscape, desktop) may lay its piles out to the sides of the columns instead of a row over them (o.wide: + // { cols, heightShare }): the columns get the whole height and the cards grow with it. + var wide = !!(o.wide && W > H * WIDE_RATIO); + var cols = wide ? o.wide.cols : colsFor(lastState, W, pad, gap); + // The solitaires' columns take the width: a margin of TIGHT_PAD+ and a gap of GAP_SHARE of a card (4 px on a phone, 9 on a desktop), + // enough to see seven columns as seven, not one wall. + // A game whose cards sit edge to edge (Pyramid's rows, where a gap would show the covered card's suit) asks for o.gapShare 0. + if (o.tight) { + var share = o.gapShare === undefined ? GAP_SHARE : o.gapShare; + pad = cols >= DENSE_COLS ? TIGHT_PAD : Math.max(TIGHT_PAD, Math.min(pad, 8)); gap = share ? Math.max(TIGHT_GAP, Math.round((W - 2 * pad) / (cols + (cols - 1) * share) * share)) : 0; + } var cw = Math.floor((W - 2 * pad - (cols - 1) * gap) / cols); - cw = Math.max(MIN_CARD_W, Math.min(cw, MAX_CARD_W, Math.floor(H * (o.heightShare || CARD_H_SHARE)))); + cw = Math.max(MIN_CARD_W, Math.min(cw, MAX_CARD_W, Math.floor(H * ((wide && o.wide.heightShare) || o.heightShare || CARD_H_SHARE)))); cw = crispWidth(cw); // `left` centres the columns when the cards stop growing before the width does. var left = Math.floor((W - (cols * cw + (cols - 1) * gap)) / 2); - metrics = { cw: cw, ch: Math.round(cw * CARD_ASPECT), gap: gap, pad: pad, left: left, step: cw + gap, W: W, H: H, cols: cols }; + metrics = { cw: cw, ch: Math.round(cw * CARD_ASPECT), gap: gap, pad: pad, left: left, step: cw + gap, W: W, H: H, cols: cols, wide: wide }; stage.style.setProperty('--cw', cw + 'px'); return metrics; } @@ -997,7 +1042,7 @@ // every transition (resize, first paint); otherwise cards ease to place. function render(state, mode) { lastState = state; - if (metrics && colsFor(state, metrics.W, metrics.pad, metrics.gap) !== metrics.cols) metrics = null; // the hand outgrew (or no longer needs) its size + if (metrics && !metrics.wide && colsFor(state, metrics.W, metrics.pad, metrics.gap) !== metrics.cols) metrics = null; // the hand outgrew (or no longer needs) its size var m = metrics || measure(), p = o.place(state, m), anyMoved = false; lastPlace = p; // A short layout sits a little above the middle instead of hugging the top bar. @@ -1021,7 +1066,7 @@ }); pruneSlots(prevOrder, hadFocus); cardPos = {}; byPile = {}; - var origin = p.slots[0], dealing = mode === 'deal'; + var origin = p.slots[0], dealing = mode === 'deal', longest = 0; p.cards.forEach(function (c, i) { var e = cardEl(c.id), z = i + 1; cardPos[c.id] = { pile: c.pile, idx: c.idx }; @@ -1043,22 +1088,29 @@ } else { e.classList.toggle('zc-instant', mode === 'instant'); e.style.transitionDelay = ''; + if (moved && e._x !== undefined) { + var fly = flyMs(Math.hypot(c.x - e._x, c.y - e._y)); + e.style.setProperty('--zc-fly', fly + 'ms'); longest = Math.max(longest, fly); + } put(e, c.x, c.y); } }); + // A card turned over by this move waits for the card that uncovered it to land. + stage.style.setProperty('--zc-turn-wait', (mode === 'instant' ? 0 : Math.round(longest * TURN_AT_LANDING)) + 'ms'); if (dealing) { void table.offsetWidth; // Only the cards that can be seen wait their turn, so a stock's hidden rest does not hold the first card back. - var seen = 0; + var seen = 0, shown = p.cards.filter(function (c) { return !c.hidden; }).length, stagger = Math.min(DEAL_STAGGER_MS, DEAL_SPAN_MS / Math.max(1, shown)); p.cards.forEach(function (c) { var e = els[c.id]; e.classList.remove('zc-instant'); - e.style.transitionDelay = (c.hidden ? 0 : seen++) * DEAL_STAGGER_MS + 'ms'; + e.style.removeProperty('--zc-fly'); + e.style.transitionDelay = (c.hidden ? 0 : seen++) * stagger + 'ms'; put(e, c.x, c.y); }); // The cards in flight are not tappable: a tap on the pile they left reaches the pile, not a card passing over it. stage.classList.add('zc-dealing'); - setTimeout(function () { stage.classList.remove('zc-dealing'); p.cards.forEach(function (c) { els[c.id].style.transitionDelay = ''; }); }, p.cards.length * DEAL_STAGGER_MS + 250); + setTimeout(function () { stage.classList.remove('zc-dealing'); p.cards.forEach(function (c) { els[c.id].style.transitionDelay = ''; }); }, shown * stagger + 250); } // A pile with cards shows its focus on its top card; only an empty one rings its outline. Object.keys(slotEls).forEach(function (k) { slotEls[k].toggleAttribute('data-cards', !!byPile[k]); }); @@ -1077,16 +1129,45 @@ var w = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x), hh = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y); return w > 0 && hh > 0 ? w * hh : 0; } - function beginDrag() { + // Held: the press lifts the card (and the run on it) at once, about the point the finger took it by. + function beginDrag(gx, gy) { drag.ids = byPile[drag.pos.pile].slice(drag.pos.idx); drag.ids.forEach(function (id, k) { var e = els[id]; + e.style.setProperty('--zc-o', (gx - e._x) + 'px ' + (gy - e._y) + 'px'); e.classList.add('zc-drag'); e.style.zIndex = Z_DRAG + k; e._hot = true; }); + feel('lift'); } - function moveDrag(dr, dx, dy) { + // Let go: a card that never moved (a tap) goes back to its own place in the stack at once, so it does not stay over its neighbours. + function dropDrag(dr) { + (dr.ids || []).forEach(function (id) { + var e = els[id]; + e.classList.remove('zc-drag'); + if (!dr.moved) { e._hot = false; e.style.zIndex = e._z; } + }); + } + function moveDrag(dr, dx, dy, px, py) { dr.ids.forEach(function (id) { var e = els[id]; e.style.transform = 'translate(' + (e._x + dx) + 'px,' + (e._y + dy) + 'px)'; }); + if (o.canDrop) ring(dropTargets(dr, dx, dy, px, py).map(function (t) { return t[1]; }).filter(function (id) { return o.canDrop(dr.pos.pile, dr.pos.idx, id); }).slice(0, 1)); + } + // The ring on the piles a held card may go to (the top card of a pile, or its empty place). + var ringed = []; + function ring(piles) { + ringed.forEach(function (n) { n.classList.remove('zc-target'); }); + ringed = piles.map(function (id) { var list = byPile[id]; return list && list.length ? els[list[list.length - 1]] : slotEls[id]; }).filter(Boolean); + ringed.forEach(function (n) { n.classList.add('zc-target'); }); } + // A card placed is heard and felt, only with Sound on in Settings (the shell's choice; no vibrate on iOS at all). + function feel(kind) { + var S = root.ZimiShell; + if (!S || !S.sound || !S.sound()) return; + if (S.click) S.click(kind); + if (kind === 'place') try { if (root.navigator.vibrate) root.navigator.vibrate(PLACE_BUZZ_MS); } catch (err) { /* no haptics */ } + } + // A drop refused twice running shows where the cards could go, instead of words. + var refusedAt = 0; + function refusedAgain() { var now = Date.now(), again = now - refusedAt < REPEAT_MS; refusedAt = now; return again; } // Slots the dragged cards overlap, biggest overlap first; the one under // the pointer counts extra. The game then takes the first that is legal. function dropTargets(dr, dx, dy, px, py) { @@ -1101,10 +1182,23 @@ return list.sort(function (a, b) { return b[0] - a[0]; }); } + // The slot nearest a point within the gap a finger can fall into between piles, or null (a press out on the bare table). + var GAP_REACH = 14; + function nearestSlot(cx, cy) { + var sr = stage.getBoundingClientRect(), x = cx - sr.left, y = cy - sr.top, best = null, bd = GAP_REACH + 1; + Object.keys(slotRects).forEach(function (id) { + var s = slotRects[id], dx = Math.max(s.x - x, 0, x - (s.x + s.w)), dy = Math.max(s.y - y, 0, y - (s.y + s.h)), d = Math.hypot(dx, dy); + if (d < bd) { bd = d; best = slotEls[id]; } + }); + return best; + } + table.addEventListener('pointerdown', function (e) { if (e.pointerType === 'mouse' && e.button !== 0) return; if (d.querySelector('.zc-cascade')) return; + if (e.target.closest('button, a, input, select')) return; // a control on the table (Canasta's bar) keeps its own press, not the nearest pile's var cardNode = e.target.closest('.zc-card'), slotNode = e.target.closest('.zc-slot'); + if (!cardNode && !slotNode) slotNode = nearestSlot(e.clientX, e.clientY); // a press in the gap between two piles is the nearer one's var pos = cardNode && cardPos[+cardNode.getAttribute('data-id')], slot = slotNode && slotNode.getAttribute('data-pile'); if (!pos && !slotNode) return; // A column's place runs down to the table's edge: a tap under its cards (on a phone a column is one card, 35 px @@ -1113,29 +1207,43 @@ if (under && under.length) pos = cardPos[under[under.length - 1]]; drag = { pos: pos, slot: slot, sx: e.clientX, sy: e.clientY, pid: e.pointerId, moved: false, ids: null, blocked: false }; sel = null; paintSelection(); toast(); + if (pos && !d.querySelector('.zc-dealing') && o.canPick(lastState, pos.pile, pos.idx)) { + var sr = stage.getBoundingClientRect(); + beginDrag(e.clientX - sr.left, e.clientY - sr.top); + } try { table.setPointerCapture(e.pointerId); } catch (err) { /* pointer already gone */ } }); table.addEventListener('pointermove', function (e) { if (!drag || e.pointerId !== drag.pid) return; var dx = e.clientX - drag.sx, dy = e.clientY - drag.sy; if (!drag.moved && !drag.blocked && Math.abs(dx) + Math.abs(dy) > DRAG_SLOP) { - if (drag.pos && o.canPick(lastState, drag.pos.pile, drag.pos.idx)) { drag.moved = true; beginDrag(); } else drag.blocked = true; + if (drag.ids) drag.moved = true; else drag.blocked = true; } - if (drag.moved) { moveDrag(drag, dx, dy); e.preventDefault(); } + if (drag.moved) { var sr = stage.getBoundingClientRect(); moveDrag(drag, dx, dy, e.clientX - sr.left, e.clientY - sr.top); e.preventDefault(); } }); function endDrag(e, cancelled) { if (!drag || e.pointerId !== drag.pid) return; var dr = drag; drag = null; try { table.releasePointerCapture(e.pointerId); } catch (err) { /* already released */ } + ring([]); if (dr.moved) { var r = stage.getBoundingClientRect(), done = false; var targets = cancelled ? [] : dropTargets(dr, e.clientX - dr.sx, e.clientY - dr.sy, e.clientX - r.left, e.clientY - r.top); for (var i = 0; i < targets.length && !done; i++) done = o.move(dr.pos.pile, dr.pos.idx, targets[i][1]); - if (!done) { refresh(); scheduleSettle(); if (targets.length && o.refused) o.refused(dr.pos, targets[0][1]); } + dropDrag(dr); + if (done) { feel('place'); return; } + // Home with a small overshoot; no words. A second refusal running rings where the card could go. + dr.ids.forEach(function (id) { var c = els[id]; c.classList.add('zc-refused'); setTimeout(function () { c.classList.remove('zc-refused'); }, REFUSED_MS); }); + refresh(); scheduleSettle(); + if (targets.length && refusedAgain() && o.canDrop) { + ring(Object.keys(slotRects).filter(function (id) { return id !== dr.pos.pile && o.canDrop(dr.pos.pile, dr.pos.idx, id); })); + setTimeout(function () { ring([]); }, RING_MS); + } return; } + dropDrag(dr); if (cancelled || dr.blocked) return; - if (dr.pos) { if (!o.tap(dr.pos.pile, dr.pos.idx)) nudge(dr.pos); } else if (dr.slot && o.slotTap) o.slotTap(dr.slot); + if (dr.pos) { if (o.tap(dr.pos.pile, dr.pos.idx)) feel('place'); else nudge(dr.pos); } else if (dr.slot && o.slotTap) o.slotTap(dr.slot); } table.addEventListener('pointerup', function (e) { endDrag(e, false); }); table.addEventListener('pointercancel', function (e) { endDrag(e, true); }); @@ -1236,7 +1344,9 @@ if (!stopped) raf = requestAnimationFrame(frame); }); function launch(c) { - var e = els[c.id], r = e.getBoundingClientRect(), dir = Math.random() < 0.5 ? -1 : 1; + var e = els[c.id], r, dir = Math.random() < 0.5 ? -1 : 1; + if (!e) return; // a card the table is not showing (a partner's hand at the end of a Bridge deal) has nothing to fly from + r = e.getBoundingClientRect(); e.style.visibility = 'hidden'; hidden.push(e); flyers.push({ id: c.id, x: r.left, y: r.top, vx: dir * (VX_MIN + Math.random() * VX_SPAN) * scale, vy: -(VY_MIN + Math.random() * VY_SPAN) * scale }); } @@ -1310,7 +1420,8 @@ // ── The session: undo, clock, stats, keys, the win ──────────────────── // cfg: { id, els: {undo, newBtn, menu, stat}, board, newGame(), openMenu(), - // statText(sec, state), cascadeOrder(state), winLines(sec, state) } + // statText(sec, state), cascadeOrder(state), winLines(sec, state), + // listWin, finished(state), finishNow() } listWin: the sheet lists every line of winLines under the first (a table of scores), not the first alone finished: a kept state that is over though its end never ran; finishNow() runs the game's own end // Where a status line of height h goes: where the game's layout put it, or higher if your hand (raised cards // included, from board.handTop()) would reach into it. var STATUS_GAP = 6; @@ -1375,7 +1486,9 @@ function takeUp(kept) { s.state = kept.state; s.history = kept.history || []; banked = kept.ms || 0; begun = true; s.ending = kept.ending || null; board.render(s.state); paint(); - if (s.ending) { s.won = true; session_showEnd(s.ending, 0); } else run(); + if (s.ending) { s.won = true; session_showEnd(s.ending, 0); } + else if (cfg.finished && cfg.finished(s.state)) cfg.finishNow(); // over, but the end never ran (an old save): the game's own end builds its sheet from the state + else run(); } function keptGame() { var kept = root.ZimiShell && root.ZimiShell.saved ? root.ZimiShell.saved() : null; @@ -1400,6 +1513,7 @@ // How a game that is not won ends: kind is '' (you lose), 'draw', 'over' (Game over) or { name, team } for the // winner of a table of people ("Sam wins", "You and Ana win"). The sheet says lines[0]; `listAll` puts the rest of the lines under it. s.lose = function (kind, lines, score, listAll) { + if (s.won) return; // a finished game taken up again (its sheet is already up) is not finished a second time s.won = true; halt(); resume = false; clearLater(); if (typeof score === 'number') s.stats.scored(score); paint(); @@ -1411,10 +1525,12 @@ sheet({ title: title, body: body, actions: [{ label: T('shell.close') }, { label: T('shell.menu.new'), primary: true, onclick: cfg.newGame }] }); }; s.win = function (score) { + if (s.won) return; // ... nor won again: the record counts it once s.won = true; halt(); resume = false; clearLater(); var sec = seconds(), best = s.stats.won(sec, score); paint(); - if (root.ZimiShell && root.ZimiShell.endSheet) s.ending = { result: 'win', text: cfg.winLines(sec, s.state)[0], stats: [[T('cards.stats.time'), fmtTime(sec)], [T('cards.stats.won'), T('cards.stats.wonOf', { won: best.won, played: best.played })]] }; + var won = cfg.winLines(sec, s.state); + if (root.ZimiShell && root.ZimiShell.endSheet) s.ending = { result: 'win', text: won[0], more: cfg.listWin ? won.slice(1) : [], stats: [[T('cards.stats.time'), fmtTime(sec)], [T('cards.stats.won'), T('cards.stats.wonOf', { won: best.won, played: best.played })]] }; board.cascade(cfg.cascadeOrder(s.state), function () { var lines = cfg.winLines(sec, s.state); if (s.ending) { session_showEnd(s.ending); return; } @@ -1477,8 +1593,15 @@ } // The page's fixed parts, by the ids every game page uses. function pageEls() { - var g = function (id) { return root.document.getElementById(id); }; - return { table: g('zc-table'), sub: g('zc-sub'), undo: g('zc-undo'), newBtn: g('zc-new'), menu: g('zc-menu'), stat: g('zc-stat') }; + var g = function (id) { return root.document.getElementById(id); }, undo = g('zc-undo'); + // The page's Undo is plain English in the markup; it speaks the player's language (and follows it when the words arrive late). + if (undo && !undo.dataset.words && root.ZimiText) { + undo.dataset.words = '1'; + var say = function () { undo.textContent = root.ZimiText.T('board.undo'); }; + say(); + if (root.ZimiText.onChange) root.ZimiText.onChange(say); + } + return { table: g('zc-table'), sub: g('zc-sub'), undo: undo, newBtn: g('zc-new'), menu: g('zc-menu'), stat: g('zc-stat') }; } // A pile's cards as plain ids (for games whose piles hold {id, up}). function idsOf(pile) { return pile.map(function (c) { return c.id; }); } @@ -1506,13 +1629,19 @@ while (down + inc <= max + 1e-9 && heaviest(down + inc) * maxStep <= room - ch) down += inc; return down; } - // A face-up card in a fan shows this much of its height when the table has room: its whole corner index and its whole top - // row of pips (PIP_TOP). Less cuts the pips through the middle into triangles beside the index. - var FAN_UP_SHARE = 0.34; + // A face-up card in a vertical fan shows at most its index row (INDEX_ROW_SHARE of its height), whatever its rank. Short columns + // spread to it and use the screen; long ones close up towards the game's own floor. + var FAN_UP_SHARE = INDEX_ROW_SHARE; function fanStep(weight, room, ch, maxStep, minStep) { return Math.max(minStep, Math.min(maxStep, weight > 0 ? (room - ch) / weight : maxStep)); } + // The step of a cascade's fan (Spider, Yukon, Scorpion...): the index row, closing up only when the longest column (weight, in + // steps) would not fit room. The same rule as every other vertical fan. + function growStep(weight, room, ch, minStep) { + return fanStep(weight, room, ch, ch * FAN_UP_SHARE, minStep); + } + // ── The solitaire page ─────────────────────────────────────────────────── // What Klondike, FreeCell, Spider, Pyramid, Golf and TriPeaks share on the page: the board and the session, a move that is // legal and then made, a tap that turns the stock or sends a card where bestMove says, what comes after a move (the win, the @@ -1576,7 +1705,9 @@ return true; }; // Why a card would not go: the game's words for a tap that had nowhere to send it, or a drop on a pile that refused it. - var why = function (pile, idx, to) { var t = o.why && o.why(session.state, pile, idx, to); if (t) toast(t); }; + // The words wait for a second try running: the first "no" is the card's shake. + var lastWhy = 0; + var why = function (pile, idx, to) { var now = Date.now(), again = now - lastWhy < REPEAT_MS, t; lastWhy = now; if (again && (t = o.why && o.why(session.state, pile, idx, to))) toast(t); }; var tap = o.tap || function (pile, idx) { if (pile === 'stock') return page.draw(); var to = R.bestMove(session.state, pile, idx); @@ -1585,8 +1716,8 @@ return false; }; board = createBoard({ - table: page.el.table, cols: o.cols, tight: true, place: o.place, heightShare: o.heightShare, enterTaps: o.enterTaps, - canPick: o.canPick || R.canPick, move: page.move, tap: tap, refused: function (pos, to) { why(pos.pile, pos.idx, to); }, + table: page.el.table, cols: o.cols, wide: o.wide, index: o.index, gapShare: o.gapShare, tight: true, place: o.place, heightShare: o.heightShare, enterTaps: o.enterTaps, + canPick: o.canPick || R.canPick, move: page.move, tap: tap, canDrop: function (pile, idx, to) { return !blocked() && R.legalMove(session.state, pile, idx, to); }, slotTap: o.slotTap || (o.stock ? function (pile) { if (pile === 'stock') page.draw(); } : undefined) }); session = createSession({ @@ -1618,7 +1749,7 @@ FACT_H: FACT_H, factLine: factLine, moonPhase: moonPhase, moonLitPath: moonLitPath, faceMarkup: faceMarkup, backMarkup: backMarkup, italianFaceMarkup: italianFaceMarkup, italianName: italianName, spanishFaceMarkup: spanishFaceMarkup, spanishName: spanishName, hanafudaFaceMarkup: hanafudaFaceMarkup, hanafudaCard: hanafudaCard, hanafudaName: hanafudaName, HANA_MONTHS: HANA_MONTHS, jokerMarkup: jokerMarkup, markSvg: markSvg, - fmtTime: fmtTime, plural: plural, winTime: winTime, solitairePage: solitairePage, stuckWhen: stuckWhen, describePile: describePile, fanStep: fanStep, FAN_UP_SHARE: FAN_UP_SHARE, openDown: openDown, solitaireRows: solitaireRows, statusTop: statusTop, pageEls: pageEls, idsOf: idsOf, restShare: restShare, + fmtTime: fmtTime, plural: plural, winTime: winTime, solitairePage: solitairePage, stuckWhen: stuckWhen, describePile: describePile, fanStep: fanStep, growStep: growStep, indexStep: indexStep, FAN_UP_SHARE: FAN_UP_SHARE, openDown: openDown, solitaireRows: solitaireRows, statusTop: statusTop, pageEls: pageEls, idsOf: idsOf, restShare: restShare, toast: toast, store: store, createStats: createStats, h: h, sheet: sheet, segmented: segmented, backsSheet: backsSheet, backsRow: backsRow, T: T, createBoard: createBoard, createSession: createSession, ensureSprite: ensureSprite, currentBack: function () { return currentBack; } diff --git a/zimi/builtin/games/cards2.css b/zimi/builtin/games/cards2.css index c64ec58dd..5b3636376 100644 --- a/zimi/builtin/games/cards2.css +++ b/zimi/builtin/games/cards2.css @@ -18,8 +18,11 @@ .br-call.br-latest { background: var(--accent); color: var(--accent-ink); } .br-auction .br-red { color: #ff9e94; } .br-auction .br-latest .br-red { color: var(--accent-ink); } +.br-bidding .ct-count { display: none; } .br-box { position: absolute; left: 50%; transform: translateX(-50%); z-index: 35; box-sizing: border-box; display: flex; flex-direction: column; gap: 6px; width: min(100% - 16px, 400px); padding: 8px; border-radius: 12px; background: rgba(8, 24, 16, 0.9); } .br-levels { display: grid; grid-template-columns: repeat(7, 1fr); gap: 4px; } +.br-wide-box { width: min(100% - 16px, 780px); } +.br-wide-box .br-levels { grid-template-columns: repeat(14, 1fr); } .br-bid { min-width: 0; min-height: var(--br-bid-h, var(--target, 44px)); padding: 0 2px; font-weight: 600; } .br-bid .br-red { color: var(--suit-red); } .br-row { display: flex; gap: 6px; } @@ -33,3 +36,12 @@ /* A meld's label sits under one card, so it keeps to the card's width. */ .c2-tag.c2-meld { padding: 2px 3px; } + +/* Red, generated by scripts/games_red.py from the rules above: do not edit. */ +:root.gs.night-red .c2-tag { background: rgba(0, 0, 0, 0.34); color: rgba(255, 32, 16, 0.86); } +:root.gs.night-red .c2-tag b { color: #ff2010; } +:root.gs.night-red .c2-tag.c2-turn { box-shadow: 0 0 0 3px rgba(167, 21, 10, 0.22); } +:root.gs.night-red .br-auction { background: rgba(0, 0, 0, 0.34); color: #ff2010; } +:root.gs.night-red .br-auction .br-red { color: #ba170c; } +:root.gs.night-red .br-box { background: rgba(18, 2, 1, 0.9); } +/* end Red */ diff --git a/zimi/builtin/games/cardtable.css b/zimi/builtin/games/cardtable.css index 0e16ba883..e681df36f 100644 --- a/zimi/builtin/games/cardtable.css +++ b/zimi/builtin/games/cardtable.css @@ -3,10 +3,10 @@ .ct-scores { position: absolute; left: 0; right: 0; display: flex; justify-content: center; gap: 6px; padding: 0 8px; pointer-events: none; z-index: 30; flex-wrap: wrap; } /* The player chip, on felt: translucent black, 28px, a dot, the name and a number. The current player has an amber outline and glow; the name stays light, never white on amber. */ -.ct-chip { display: inline-flex; gap: 6px; align-items: center; height: 28px; padding: 0 var(--sp-3); border: 1px solid transparent; border-radius: 999px; background: rgba(0, 0, 0, 0.34); color: rgba(255, 255, 255, 0.86); font: var(--fs-small) var(--font); font-variant-numeric: tabular-nums; white-space: nowrap; } -.ct-chip::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: rgba(255, 255, 255, 0.35); } -.ct-chip b { font: 650 var(--fs-small) var(--font); color: #fff; } -.ct-chip .ct-dealer { display: inline-grid; place-items: center; width: 16px; height: 16px; border-radius: 50%; background: rgba(255, 255, 255, 0.2); color: #fff; font: 700 var(--fs-caption) var(--font); font-style: normal; } +.ct-chip { display: inline-flex; gap: 6px; align-items: center; height: 28px; padding: 0 var(--sp-3); border: 1px solid transparent; border-radius: 999px; background: rgba(0, 0, 0, 0.34); color: rgba(var(--on-felt-rgb), 0.86); font: var(--fs-small) var(--font); font-variant-numeric: tabular-nums; white-space: nowrap; } +.ct-chip::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: rgba(var(--on-felt-rgb), 0.35); } +.ct-chip b { font: 650 var(--fs-small) var(--font); color: var(--on-felt); } +.ct-chip .ct-dealer { display: inline-grid; place-items: center; width: 16px; height: 16px; border-radius: 50%; background: rgba(var(--on-felt-rgb), 0.2); color: var(--on-felt); font: 700 var(--fs-caption) var(--font); font-style: normal; } .ct-chip.ct-trump::before { display: none; } .ct-chip b.ct-red { color: #ff9e94; } .ct-chip.ct-turn { border-color: var(--select-ring); box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.22); } @@ -20,31 +20,55 @@ .ct-chip.ct-bump { animation: ct-bump 0.42s ease-out; } @keyframes ct-bump { 0% { transform: scale(1); } 35% { transform: scale(1.14); background: rgba(245, 158, 11, 0.55); } 100% { transform: scale(1); } } .ct-status { position: absolute; left: 0; right: 0; display: flex; align-items: center; justify-content: center; gap: 12px; padding: 0 12px; z-index: 30; pointer-events: none; } -.ct-status-text { padding: 5px var(--sp-3); border-radius: 999px; background: rgba(0, 0, 0, 0.34); color: #fff; font-size: var(--fs-body); line-height: 1.3; text-align: center; max-width: 100%; } +.ct-status-text { padding: 5px var(--sp-3); border-radius: 999px; background: rgba(0, 0, 0, 0.34); color: var(--on-felt); font-size: var(--fs-body); line-height: 1.3; text-align: center; max-width: 100%; } .ct-status .ar-btn { pointer-events: auto; } .ct-status .ar-btn[hidden] { display: none; } .ct-panel { position: absolute; left: 50%; transform: translateX(-50%); display: flex; flex-wrap: wrap; justify-content: center; gap: var(--sp-2); width: min(100% - 16px, 520px); padding: var(--sp-2); border-radius: var(--r-sheet); background: rgba(0, 0, 0, 0.5); z-index: 35; } .ct-panel[hidden] { display: none; } +.ct-panel.ct-side { left: auto; right: var(--sp-2); transform: none; width: 214px; justify-content: flex-end; gap: 6px; padding: 6px; } +.ct-panel.ct-side .ct-choice { flex: 1 1 calc(50% - 3px); min-width: 0; min-height: 36px; padding: 0 8px; } .ct-choice { min-width: var(--target); min-height: var(--target); padding: 0 14px; font-weight: 600; } .ct-choice.ct-red { color: var(--suit-red); } .ct-choice[aria-pressed="true"] { background: linear-gradient(var(--accent-glow), var(--accent-glow)), var(--surface); border-color: var(--select-ring); color: var(--ink); } .ct-choice.ct-primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); } .ct-choice.ct-primary:disabled { opacity: 0.45; background: var(--accent); border-color: var(--accent); color: var(--accent-ink); } -.ct-lines { flex: 1 1 100%; color: #fff; font-size: var(--fs-small); line-height: 1.45; } +.ct-lines { flex: 1 1 100%; color: var(--on-felt); font-size: var(--fs-small); line-height: 1.45; } .ct-lines p { margin: 1px 0; } .ct-lines .ct-total { font-weight: 700; color: var(--select-ring); } /* On a phone four players and a trump chip share one row: no dot, tight padding, the trump chip is its suit alone. */ @media (max-width: 440px) { .ct-chip { padding: 0 8px; gap: 4px; } .ct-chip::before { display: none; } .ct-scores { flex-wrap: nowrap; gap: 4px; padding: 0 4px; } .ct-chip.ct-trump span { display: none; } } @media (max-width: 400px) { .ct-chip { padding: 0 6px; } } +/* Five at the table (and the trump chip): the row has to fit a phone, so the chips take less air. */ +@media (max-width: 440px) { .ct-many { gap: 3px; padding: 0 2px; } .ct-many .ct-chip { padding: 0 5px; gap: 3px; } } .ct-status-text:empty { display: none; } /* Chip stacks: tokens in the casino colours (materials: they keep their hues), a column to a denomination. */ .ct-pile { position: absolute; left: 0; right: 0; z-index: 18; display: flex; flex-direction: column; align-items: center; gap: var(--sp-2); pointer-events: none; } -.ct-caption { padding: 2px var(--sp-3); border-radius: 999px; background: rgba(0, 0, 0, 0.34); color: #fff; font-size: var(--fs-small); } +.ct-caption { padding: 2px var(--sp-3); border-radius: 999px; background: rgba(0, 0, 0, 0.34); color: var(--on-felt); font-size: var(--fs-small); } .ct-pile:empty { display: none; } .ct-stack { display: inline-flex; align-items: flex-end; gap: 6px; } .ct-col { position: relative; width: 30px; } -.ct-token { position: absolute; left: 0; width: 30px; height: 30px; box-sizing: border-box; border-radius: 50%; border: 3px dashed rgba(255, 255, 255, 0.92); background: var(--ct-chip, #b3261e); box-shadow: 0 1px 1px rgba(0, 0, 0, 0.45); } -.ct-token::after { content: ""; position: absolute; inset: 3px; border-radius: 50%; border: 1px solid rgba(255, 255, 255, 0.55); } +.ct-token { position: absolute; left: 0; width: 30px; height: 30px; box-sizing: border-box; border-radius: 50%; border: 3px dashed rgba(var(--on-felt-rgb), 0.92); background: var(--ct-chip, #b3261e); box-shadow: 0 1px 1px rgba(0, 0, 0, 0.45); } +.ct-token::after { content: ""; position: absolute; inset: 3px; border-radius: 50%; border: 1px solid rgba(var(--on-felt-rgb), 0.55); } .ct-d500 { --ct-chip: #6b46c1; } .ct-d100 { --ct-chip: #232a33; } .ct-d50 { --ct-chip: #d9780b; } .ct-d25 { --ct-chip: #2f855a; } .ct-d10 { --ct-chip: #2b6cb0; } .ct-d5 { --ct-chip: #b3261e; } .ct-d1 { --ct-chip: #9aa3ad; } + +/* A long row of choices (Spades' bids) gets the width of the table, so on a phone on its side it is one row. */ +.ct-panel.ct-wide { width: min(100% - 16px, 780px); } + +/* Red, generated by scripts/games_red.py from the rules above: do not edit. */ +:root.gs.night-red .ct-chip { background: rgba(0, 0, 0, 0.34); } +:root.gs.night-red .ct-chip b.ct-red { color: #ba170c; } +:root.gs.night-red .ct-chip.ct-turn { box-shadow: 0 0 0 3px rgba(167, 21, 10, 0.22); } +:root.gs.night-red .ct-status-text { background: rgba(0, 0, 0, 0.34); } +:root.gs.night-red .ct-panel { background: rgba(0, 0, 0, 0.5); } +:root.gs.night-red .ct-caption { background: rgba(0, 0, 0, 0.34); } +:root.gs.night-red .ct-token { background: var(--ct-chip, #4f0a05); box-shadow: 0 1px 1px rgba(0, 0, 0, 0.45); } +:root.gs.night-red .ct-d500 { --ct-chip: #5f0c06; } +:root.gs.night-red .ct-d100 { --ct-chip: #290503; } +:root.gs.night-red .ct-d50 { --ct-chip: #891109; } +:root.gs.night-red .ct-d25 { --ct-chip: #660d06; } +:root.gs.night-red .ct-d10 { --ct-chip: #600c06; } +:root.gs.night-red .ct-d5 { --ct-chip: #4f0a05; } +:root.gs.night-red .ct-d1 { --ct-chip: #a1140a; } +/* end Red */ diff --git a/zimi/builtin/games/cardtable.js b/zimi/builtin/games/cardtable.js index c42be1af6..0e0003df2 100644 --- a/zimi/builtin/games/cardtable.js +++ b/zimi/builtin/games/cardtable.js @@ -15,7 +15,7 @@ // rows), a tapped card lifts 14 px // (a card you can play stands 6 px proud when others cannot be played). An opponent's face-down hand of more than // five cards is one back and a count chip. - var COUNT_AT = 0.86, STATUS_MAX = 44, MIN_STRIP_PX = 22, LIFT_PX = 14, PLAYABLE_LIFT_PX = 6, COLLAPSE_FROM = 6; + var WIDE_CHOICES = 10, SHORT_TABLE_H = 420, MANY_CHIPS = 5, NORTH_GAP_PX = 6, COUNT_AT = 0.86, STATUS_MAX = 44, MIN_STRIP_PX = 22, LIFT_PX = 14, PLAYABLE_LIFT_PX = 6, COLLAPSE_FROM = 6; // Games that play a card on its second tap: the first tap lifts it (amber outline), the second plays it. var LIFT_THEN_PLAY = { spades: 1, euchre: 1, belote: 1, crazyeights: 1, durak: 1 }; // SCORE_BAR_H: the chips' row (28 px, cardtable.css .ct-chip) and air under it for the ring round whoever is to play. @@ -38,8 +38,10 @@ var MIN_STEP_SHARE = 0.42, ROW_STEP_SHARE = 0.5, FLASH_MS = 1800, PANEL_GAP = 8; // The slot a card is dropped on to play it: this many cards wide and tall either side of the table's middle. var FELT_X = 1.6, FELT_Y = 1.1; - // Where each seat sits on the table, by the number of players: 0 south, 1 west, 2 north, 3 east. - var SEAT_POS = { 2: [0, 2], 3: [0, 1, 3], 4: [0, 1, 2, 3] }; + // Where each seat sits on the table, by the number of players: 0 south, 1 west, 2 north, 3 east. With five, the north is shared + // by two hands: 4 (north-west) and 5 (north-east). + var SEAT_POS = { 2: [0, 2], 3: [0, 1, 3], 4: [0, 1, 2, 3], 5: [0, 1, 4, 5, 3] }; + var NORTH_TRICK_DX = 0.45; // the two north plays of a five-seat trick lean this many card widths off the middle var SUIT_ORDER = [0, 1, 3, 2]; // clubs, diamonds, spades, hearts: alternating colours in a hand var SUIT_GLYPH = ['♣', '♦', '♥', '♠']; // by ZimiCards suit: clubs, diamonds, hearts, spades @@ -75,6 +77,12 @@ g.northY = m.pad + SCORE_BAR_H; g.southY = m.H - ch - Math.max(m.pad, HAND_BOTTOM_PX); // your bottom row sits on the bottom (the page already stops above the home-indicator inset) g.yTop = g.northY + ch + 8; + // A short table (a phone on its side): the west and east hands start level with the north row and are one back and a count each, + // so a tray of choices above the status line never covers them. + g.short = m.H < SHORT_TABLE_H; + g.sideTop = g.short ? g.northY : g.yTop; + // The tray of choices sits across the middle of a short table, so a trick or a pile stands to the right of it. + g.midX = g.short ? Math.round(m.W - m.pad - g.cw * (0.5 + TRICK_DX)) : cx; g.yBot = g.southY - (g.rows - 1) * g.rowStep - g.raise - 6; // the rows above it push the status line up g.statusY = g.yBot - STATUS_H; // The trick sits high on the felt (40% down the table), clear of the north hand and the status line: eyes stay between the opponents and your hand. @@ -91,14 +99,19 @@ return Math.max(1, Math.ceil(n / perRow)); } function rowsFor(m, n) { return handRows(m.W, m.pad, m.cw, n); } - function sideStep(g, n) { return Math.max(g.ch * SIDE_STEP_MIN, Math.min(g.ch * SIDE_STEP_MAX, (g.statusY - g.yTop - g.ch) / Math.max(1, n - 1))); } + function sideStep(g, n) { return Math.max(g.ch * SIDE_STEP_MIN, Math.min(g.ch * SIDE_STEP_MAX, (g.statusY - g.sideTop - g.ch) / Math.max(1, n - 1))); } // A card's corner in the middle for each position's play, and where a position's cards sit. function trickSpot(g, pos) { - var x = g.cx - g.cw / 2, y = g.cy - g.ch / 2; - return [{ x: x, y: y + g.ch * TRICK_DY }, { x: x - g.cw * TRICK_DX, y: y }, { x: x, y: y - g.ch * TRICK_DY }, { x: x + g.cw * TRICK_DX, y: y }][pos]; + var x = (g.midX === undefined ? g.cx : g.midX) - g.cw / 2, y = g.cy - g.ch / 2; + return [{ x: x, y: y + g.ch * TRICK_DY }, { x: x - g.cw * TRICK_DX, y: y }, { x: x, y: y - g.ch * TRICK_DY }, { x: x + g.cw * TRICK_DX, y: y }, + { x: x - g.cw * NORTH_TRICK_DX, y: y - g.ch * TRICK_DY }, { x: x + g.cw * NORTH_TRICK_DX, y: y - g.ch * TRICK_DY }][pos]; } + // A north hand's room across the table and the middle of it: the whole width for the one north, a half each for two. + function northRoom(g, pos) { return pos === 2 ? g.W - 2 * g.pad : (g.W - 2 * g.pad) / 2 - NORTH_GAP_PX; } + function northCx(g, pos) { return pos === 2 ? g.cx : pos === 4 ? g.pad + (g.W - 2 * g.pad) / 4 : g.W - g.pad - (g.W - 2 * g.pad) / 4; } function seatSpot(g, pos) { - return [{ x: g.cx - g.cw / 2, y: g.southY }, { x: g.westX, y: g.yTop }, { x: g.cx - g.cw / 2, y: g.northY }, { x: g.eastX, y: g.yTop }][pos]; + return [{ x: g.cx - g.cw / 2, y: g.southY }, { x: g.westX, y: g.sideTop }, { x: g.cx - g.cw / 2, y: g.northY }, { x: g.eastX, y: g.sideTop }, + { x: northCx(g, 4) - g.cw / 2, y: g.northY }, { x: northCx(g, 5) - g.cw / 2, y: g.northY }][pos]; } function posOf(seat, players) { return SEAT_POS[players][seat]; } // Where a seat sits for the person looking (a ZimiSeats object): the viewer is south. @@ -133,20 +146,20 @@ // Face-down (or face-up when `up`) fan of a seat's hand at a table position. function fan(g, pos, ids, up) { var cards = [], n = ids.length, p = 'p' + pos; - if (!up && n >= COLLAPSE_FROM) { + var side = pos === 1 || pos === 3; + if (!up && (n >= COLLAPSE_FROM || (g.short && side && n > 1))) { // One back and a count: every card sits in the same place (so a played card still flies from the hand). - var ax = pos === 2 ? Math.round(g.cx - g.cw / 2) : pos === 1 ? g.westX : g.eastX, ay = pos === 2 ? g.northY : g.yTop; + var north = pos === 2 || pos >= 4, ax = north ? Math.round(northCx(g, pos) - g.cw / 2) : pos === 1 ? g.westX : g.eastX, ay = north ? g.northY : g.sideTop; ids.forEach(function (id, k) { cards.push({ id: id, pile: p, idx: k, x: ax, y: ay, up: false }); }); counts.push({ x: ax + g.cw / 2, y: ay + g.ch * COUNT_AT, n: n }); // low on the back: the Z stays clear return cards; } - if (pos === 2) { - var nx = g.cx - (g.cw + (n - 1) * g.topStep) / 2, ts = Math.min(g.topStep, n > 1 ? (g.W - 2 * g.pad - g.cw) / (n - 1) : 0); - nx = g.cx - (g.cw + (n - 1) * ts) / 2; + if (pos === 2 || pos >= 4) { + var ts = Math.min(g.topStep, n > 1 ? (northRoom(g, pos) - g.cw) / (n - 1) : 0), nx = northCx(g, pos) - (g.cw + (n - 1) * ts) / 2; ids.forEach(function (id, k) { cards.push({ id: id, pile: p, idx: k, x: Math.round(nx + k * ts), y: g.northY, up: !!up }); }); } else { var sx = pos === 1 ? g.westX : g.eastX, st = sideStep(g, n); - ids.forEach(function (id, k) { cards.push({ id: id, pile: p, idx: k, x: sx, y: g.yTop + k * st, up: !!up }); }); + ids.forEach(function (id, k) { cards.push({ id: id, pile: p, idx: k, x: sx, y: g.sideTop + k * st, up: !!up }); }); } return cards; } @@ -200,6 +213,7 @@ if (sig === last) return; last = sig; paintChips(scoreRow, hd.chips, chipMemo, cfg.seats); + scoreRow.classList.toggle('ct-many', (hd.chips || []).length >= MANY_CHIPS); // Trump is a suit chip: the suit's glyph (red for the red suits), then the word. if (hd.trump !== undefined && hd.trump !== null) { var red = Z.isRed(Z.make(1, hd.trump)); @@ -207,13 +221,17 @@ } scoreRow.style.top = m.pad + 'px'; status.style.top = Math.round(statusY) + 'px'; status.style.height = STATUS_H + 'px'; - panel.style.bottom = Math.round(m.H - statusY + PANEL_GAP) + 'px'; + // A game that asks for it (cfg.sidePanel) keeps the tray out of the middle of a short table: a small column at the right, level with the status line. + var side = !!(cfg.sidePanel && g.short); + panel.classList.toggle('ct-side', side); + panel.style.bottom = Math.round(side ? m.H - (statusY + STATUS_H) : m.H - statusY + PANEL_GAP) + 'px'; // The status line: one sentence. The game's one fact ("Hand 2", "To 121") leads it when both fit. // A flash (a reason, a call) is a sentence of its own: nothing leads it. A lifted card says what the next tap does. var line = view.flash || (liftedPile && hd.text && !hd.choices ? T('cards.tapAgain') : hd.text) || ''; statusText.textContent = !view.flash && hd.fact && line && (hd.fact + ' \u00b7 ' + line).length <= STATUS_MAX ? hd.fact + ' \u00b7 ' + line : (line || hd.fact || ''); statusBtn.textContent = hd.label || ''; statusBtn.hidden = !hd.label; statusBtn.disabled = !hd.action; statusBtn.classList.toggle('gs-primary', !!hd.action); // the next thing to do is the filled amber button panel.textContent = ''; panel.hidden = !(hd.choices && hd.choices.length); + panel.classList.toggle('ct-wide', (hd.choices || []).length >= WIDE_CHOICES); // a long row of bids takes the table's width (hd.choices || []).forEach(function (c, i) { var b = Z.h('button', { class: 'ar-btn ct-choice' + (c.cls ? ' ' + c.cls : ''), type: 'button', text: c.label }); if (c.pressed !== undefined) b.setAttribute('aria-pressed', String(!!c.pressed)); @@ -234,7 +252,7 @@ function unflash() { if (view.flash) { view.flash = ''; paint(); } } board = Z.createBoard({ - table: el.table, cols: cfg.cols || stateCols, heightShare: cfg.heightShare || 0.11, enterTaps: true, face: cfg.face, + table: el.table, cols: cfg.cols || stateCols, heightShare: cfg.heightShare || 0.11, enterTaps: true, face: cfg.face, index: cfg.index || 'col', place: function (st, m) { takeCounts(); var p = cfg.place(st, m, view); @@ -266,7 +284,7 @@ undoOff: cfg.seats ? function () { return cfg.seats.hotseat(); } : null, statText: function (sec, st) { paint(); return cfg.stat(sec, st); }, cascadeOrder: cfg.cascadeOrder || function () { return []; }, - winLines: cfg.winLines, + winLines: cfg.winLines, listWin: cfg.listWin, finished: cfg.finished, finishNow: cfg.finishNow, openMenu: function () { Z.sheet({ title: root.ZimiText && root.ZimiText.has('game.' + cfg.id + '.title') ? T('game.' + cfg.id + '.title') : cfg.name, // the game's name in the player's language @@ -457,9 +475,9 @@ // The game is decided for team `w`: the last hand's lines and the result, to the stats and the end sheet. tg.teamGameOver = function (w, scores, lines) { var vt = tg.viewTeam(), hot = seats.hotseat(); - lines = lines.concat([T(hot ? 'cards.result.hot' : w === vt ? 'cards.result.you' : 'cards.result.them', { team: hot ? tg.teamNames(w) : '', a: scores[w], b: scores[1 - w] })]); - if (hot) session.lose({ name: tg.teamNames(w), team: true }, lines); - else if (w === vt) session.win(scores[vt]); else session.lose('', lines, scores[vt]); + lines = [T(hot ? 'cards.result.hot' : w === vt ? 'cards.result.you' : 'cards.result.them', { team: hot ? tg.teamNames(w) : '', a: scores[w], b: scores[1 - w] })].concat(lines); + if (hot) session.lose({ name: tg.teamNames(w), team: true }, lines, undefined, true); + else if (w === vt) session.win(scores[vt]); else session.lose('', lines, scores[vt], true); }; // The table for a game: cfg is create()'s, and what a trick game always says is filled in. @@ -469,7 +487,8 @@ id: o.id, seats: seats, view: view, tap: tg.tap, liftPlay: function (st) { return st.phase === 'play'; }, canPick: function (st, pile) { return st.phase === 'play' && pile.charAt(0) === 'h' && o.legal(st, seats.view(), idOf(pile)); }, move: function (pile, idx, to) { return (to === 'trick' || to === 'deck') && pile.charAt(0) === 'h' ? tg.play(idOf(pile)) : false; }, - stat: function (sec, st) { return tg.teamStat(sec, st.scores); } + stat: function (sec, st) { return tg.teamStat(sec, st.scores); }, + listWin: true, finished: function (st) { return st.phase === 'over' && !!o.gameOver; }, finishNow: function () { o.gameOver(); } }, cfg, { place: function (st, m, v) { tg.syncView(st); return place(st, m, v); } })); tg.attach(t); return t; @@ -478,7 +497,7 @@ } root.ZimiTable = { - paintChips: paintChips, SEAT_POS: SEAT_POS, HAND13_COLS: HAND13_COLS, handCols: handCols, stateCols: stateCols, SUIT_GLYPH: SUIT_GLYPH, STATUS_H: STATUS_H, STATUS_MAX: STATUS_MAX, SCORE_BAR_H: SCORE_BAR_H, + paintChips: paintChips, SHORT_TABLE_H: SHORT_TABLE_H, SEAT_POS: SEAT_POS, HAND13_COLS: HAND13_COLS, handCols: handCols, stateCols: stateCols, SUIT_GLYPH: SUIT_GLYPH, STATUS_H: STATUS_H, STATUS_MAX: STATUS_MAX, SCORE_BAR_H: SCORE_BAR_H, next: next, sortHand: sortHand, rankHigh: rankHigh, short: short, shortList: shortList, shuffleOf: shuffleOf, countBy: countBy, maxBy: maxBy, minBy: minBy, geometry: geometry, rowsFor: rowsFor, sideStep: sideStep, trickSpot: trickSpot, seatSpot: seatSpot, posOf: posOf, posFor: posFor, handCards: handCards, fan: fan, takeCounts: takeCounts, handRows: handRows, diff --git a/zimi/builtin/games/cheat.css b/zimi/builtin/games/cheat.css new file mode 100644 index 000000000..788c3839c --- /dev/null +++ b/zimi/builtin/games/cheat.css @@ -0,0 +1,3 @@ +/* Cheat: the rank to say, under the pile. */ +.ch-claim { position: absolute; z-index: 30; transform: translateX(-50%); padding: 2px 12px; border-radius: 999px; background: var(--accent); color: var(--accent-ink); font: 700 var(--fs-body) var(--font); line-height: 1.5; white-space: nowrap; pointer-events: none; } +.ch-claim[hidden] { display: none; } diff --git a/zimi/builtin/games/cheat.html b/zimi/builtin/games/cheat.html new file mode 100644 index 000000000..fb932f51c --- /dev/null +++ b/zimi/builtin/games/cheat.html @@ -0,0 +1,32 @@ + + + + + +Cheat + + + + + + + +
+ ‹ +

Cheat

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/cheat.js b/zimi/builtin/games/cheat.js new file mode 100644 index 000000000..ab3e805ff --- /dev/null +++ b/zimi/builtin/games/cheat.js @@ -0,0 +1,275 @@ +/* ZimiGames: Cheat, two to four players: you (south) against the computer players. All 52 cards are dealt out. The ranks come round in + order, ace to king and on again, one for each turn. On your turn you put one to four cards face down on the pile and say they are + all of that rank, whether they are or not. After a play, anyone may call it. A call that finds a wrong card makes the player who + played take the whole pile; a call that finds only the rank said makes the caller take it. The first to get rid of every card, and + survive the call that follows, wins. + + State: players, hands[n], pile (face down, bottom first), claim (the rank to be said this turn, 1 to 13), turn, phase ('play' | + 'call' | 'over'), callers (the seats still to say, in order, while phase is 'call'), last (the latest play: seat, rank, count, + ids, and once it was called, call { caller, lying, loser, n }), tells[n] ({ called, lied }: what each player has been caught doing, which the computer + remembers), turns, winner, moves. Pure functions; the page wiring only runs + in a browser. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, T = root.ZimiTable, Seats = root.ZimiSeats, TX = root.ZimiCards.T; + + var MAX_PLAY = 4, RANKS = 13, TURN_CAP = 400, PLAYERS_KEY = 'cheat.players', DEFAULT_PLAYERS = 3; + var rankOf = function (id) { return Z.rank(id); }; + var SUIT_ORDER = [0, 1, 3, 2]; + function sorted(ids) { return ids.slice().sort(function (a, b) { return rankOf(a) - rankOf(b) || SUIT_ORDER.indexOf(Z.suit(a)) - SUIT_ORDER.indexOf(Z.suit(b)); }); } + var count = function (hand, rank) { return hand.filter(function (c) { return rankOf(c) === rank; }).length; }; + + // ── Rules ─────────────────────────────────────────────────────────────── + function deal(order, players, first) { + var hands = [], i; + for (i = 0; i < players; i++) hands.push([]); + order.forEach(function (c, k) { hands[k % players].push(c); }); + return { players: players, hands: hands.map(sorted), pile: [], claim: 1, turn: first || 0, phase: 'play', callers: [], last: null, tells: hands.map(function () { return { called: 0, lied: 0 }; }), turns: 0, winner: -1, moves: 0 }; + } + function canPlay(st, seat, ids) { + if (st.phase !== 'play' || st.turn !== seat || !ids.length || ids.length > MAX_PLAY) return false; + return ids.every(function (c, i) { return st.hands[seat].indexOf(c) >= 0 && ids.indexOf(c) === i; }); + } + // The cards go on the pile, said to be of the rank due; everyone else may now call. + function play(st, seat, ids) { + var s = Z.clone(st), k; + ids.forEach(function (c) { s.hands[seat].splice(s.hands[seat].indexOf(c), 1); }); + s.pile = s.pile.concat(ids); + s.last = { seat: seat, rank: s.claim, count: ids.length, ids: ids.slice(), call: null }; + s.callers = []; + for (k = 1; k < s.players; k++) s.callers.push((seat + k) % s.players); + s.phase = 'call'; s.moves++; + return s; + } + var wasTrue = function (last) { return last.ids.every(function (c) { return rankOf(c) === last.rank; }); }; + // After a play nobody called, or a call settled: the next turn, the next rank, or the win. + function advance(s) { + var seat = s.last.seat; + s.turns++; + if (!s.hands[seat].length) { s.phase = 'over'; s.winner = seat; return s; } + if (s.turns >= TURN_CAP) { + var fewest = Math.min.apply(null, s.hands.map(function (h) { return h.length; })), at = s.hands.map(function (h, i) { return h.length === fewest ? i : -1; }).filter(function (i) { return i >= 0; }); + s.phase = 'over'; s.winner = at.length === 1 ? at[0] : -1; + return s; + } + s.turn = (seat + 1) % s.players; s.claim = s.claim % RANKS + 1; s.phase = 'play'; s.callers = []; + return s; + } + // `caller` says whether to call the play just made. The seats say in order; a call settles it, and all letting it go leaves it. + function decide(st, caller, calls) { + if (st.phase !== 'call' || st.callers[0] !== caller) return st; + var s = Z.clone(st); + if (!calls) { s.callers.shift(); s.moves++; return s.callers.length ? s : advance(s); } + var lying = !wasTrue(s.last), loser = lying ? s.last.seat : caller, n = s.pile.length; + s.hands[loser] = sorted(s.hands[loser].concat(s.pile)); s.pile = []; + s.last.call = { caller: caller, lying: lying, loser: loser, n: n }; s.moves++; + if (!s.tells) s.tells = s.hands.map(function () { return { called: 0, lied: 0 }; }); + s.tells[s.last.seat].called++; if (lying) s.tells[s.last.seat].lied++; + return advance(s); + } + var decider = function (st) { return st.phase === 'call' ? st.callers[0] : -1; }; + + // ── The computer players ──────────────────────────────────────────────── + // What to put down. With the rank due in hand it plays all of them, and now and then slips one more in; without, it bluffs one card + // (or two), the ones whose turn to be said is furthest off, so the cards it will want soon stay. + function aiPlay(st, seat, rng) { + rng = rng || Math.random; + var hand = st.hands[seat], r = st.claim, have = hand.filter(function (c) { return rankOf(c) === r; }); + var away = function (c) { return (rankOf(c) - r + RANKS) % RANKS; }; + var others = hand.filter(function (c) { return rankOf(c) !== r; }).sort(function (a, b) { return away(b) - away(a); }); + if (have.length) { + var out = have.slice(0, MAX_PLAY); + if (out.length < MAX_PLAY && others.length > 1 && rng() < 0.2) out.push(others[0]); + return out; + } + var n = Math.min(others.length, rng() < 0.3 && others.length > 2 ? 2 : 1); + return others.slice(0, n); + } + // Whether to call the play just made. Sure when the cards said cannot all be out there. Otherwise by how likely it is to be a lie (below), + // and a player about to go out is called far more often, while a computer with few cards of its own is careful. + var CALL_BOLDNESS = 0.9, GOING_OUT_CALL = 0.9, NEAR_OUT_CALL = 0.6, BIG_PILE = 10, BIG_PILE_DAMP = 0.8, SMALL_HAND = 3, SMALL_HAND_DAMP = 0.5, MIN_CALL = 0.04; + // The chance that a hand of `drawn` cards from `unseen` cards, `wanted` of them of the rank, holds exactly k of it: C(wanted, k) * C(unseen - wanted, drawn - k) / C(unseen, drawn), by logarithms so nothing overflows. + function hyper(unseen, wanted, drawn, k) { + var logChoose = function (n, r) { var v = 0, j; r = Math.min(r, n - r); for (j = 0; j < r; j++) v += Math.log((n - j) / (j + 1)); return v; }; + if (drawn - k > unseen - wanted || k > wanted || drawn > unseen) return 0; + return Math.exp(logChoose(wanted, k) + logChoose(unseen - wanted, drawn - k) - logChoose(unseen, drawn)); + } + // How the computer reads a play: a player holding the rank puts it all down (now and then with one more), and one holding none says one + // or two. So the claim of n is a lie when the player held none, and true when they held about n: weighed by how likely each was. + var BLUFF_ONE = 0.7, BLUFF_TWO = 0.3, EXTRA = 0.2, TELL_WEIGHT = 0.5, TELL_AFTER = 3; + function lieChance(st, seat) { + var l = st.last, mine = count(st.hands[seat], l.rank), left = st.hands[l.seat].length, unseen = 52 - st.hands[seat].length, held = Math.min(left + l.count, unseen), wanted = MAX_PLAY - mine; + var none = hyper(unseen, wanted, held, 0), exact = hyper(unseen, wanted, held, l.count), shy = l.count > 1 ? hyper(unseen, wanted, held, l.count - 1) : 0; + var liar = none * (l.count === 1 ? BLUFF_ONE : l.count === 2 ? BLUFF_TWO : 0), truth = exact * (1 - EXTRA) + shy * EXTRA; + var p = liar + truth > 0 ? liar / (liar + truth) : 0.5, tell = st.tells && st.tells[l.seat]; + if (tell && tell.called >= TELL_AFTER) p = (1 - TELL_WEIGHT) * p + TELL_WEIGHT * (tell.lied + 1) / (tell.called + 2); + return p; + } + function aiCall(st, seat, rng) { + rng = rng || Math.random; + var l = st.last; + if (count(st.hands[seat], l.rank) + l.count > MAX_PLAY) return true; + var left = st.hands[l.seat].length, p = lieChance(st, seat) * CALL_BOLDNESS; + if (left === 0) p = Math.max(p, GOING_OUT_CALL); else if (left <= 2) p = Math.max(p, NEAR_OUT_CALL); + else p = Math.max(p, MIN_CALL); + if (st.pile.length >= BIG_PILE) p *= BIG_PILE_DAMP; + if (st.hands[seat].length <= SMALL_HAND) p *= SMALL_HAND_DAMP; + return rng() < p; + } + + // ── Layout ────────────────────────────────────────────────────────────── + var SHOW_PILE = 3, PILE_FAN = 4, REVEAL_STEP = 0.5, BADGE_GAP = 6; + function geo(m, st) { return T.geometry(m, T.rowsFor(m, st.hands[0].length)); } + function pileSpot(g) { return { x: Math.round(g.midX - g.cw / 2), y: Math.round(g.cy - g.ch / 2) }; } + function place(st, m, view) { + var g = geo(m, st), p = pileSpot(g), slots = [], cards = [], picked = (view && view.picked) || [], r; + slots.push({ id: 'pile', x: p.x, y: p.y, w: g.cw, h: g.ch, quiet: !st.pile.length, label: TX('cheat.pile', { cards: Z.plural(st.pile.length, 'card') }) }); + var hand = T.handCards(g, st.hands[0], function (id) { var on = picked.indexOf(id) >= 0; return { up: true, raise: on, mark: on }; }, function (a, b) { return rankOf(a) !== rankOf(b); }); + slots = slots.concat(hand.slots); cards = cards.concat(hand.cards); + for (r = 1; r < st.players; r++) cards = cards.concat(T.fan(g, T.SEAT_POS[st.players][r], st.hands[r], false)); + st.pile.forEach(function (id, k) { cards.push({ id: id, pile: 'pile', idx: k, x: p.x + Math.max(0, k - (st.pile.length - SHOW_PILE)) * PILE_FAN, y: p.y, up: false, hidden: k < st.pile.length - SHOW_PILE }); }); + // A call turns the cards over: what was said, and what it was. + if (st.last && st.last.call) { + var ids = st.last.ids, step = Math.min(g.cw * REVEAL_STEP, (g.W - 2 * g.pad - g.cw) / Math.max(1, ids.length - 1)), x0 = g.cx - (g.cw + (ids.length - 1) * step) / 2; + ids.forEach(function (id, k) { cards.push({ id: id, pile: 'reveal', idx: k, x: Math.round(x0 + k * step), y: p.y, up: true, glow: rankOf(id) !== st.last.rank }); }); + } + return { height: m.H, slots: slots, cards: cards }; + } + + var api = { + MAX_PLAY: MAX_PLAY, TURN_CAP: TURN_CAP, deal: deal, canPlay: canPlay, play: play, decide: decide, decider: decider, wasTrue: wasTrue, aiPlay: aiPlay, aiCall: aiCall, count: count, geo: geo, place: place, pileSpot: pileSpot + }; + root.ZimiCheat = api; + + // ── The page ──────────────────────────────────────────────────────────── + var AI_MS = 900, DECIDE_MS = 700, SHOW_MS = 1500; + function boot() { + var t, board, session, view = { flash: '', picked: [] }, players = DEFAULT_PLAYERS, seats = {}; + var claimBadge = Z.h('div', { class: 'ch-claim', 'aria-live': 'polite' }); + Z.pageEls().table.appendChild(claimBadge); + function buildSeats(n) { + var cur = Seats.create({ id: 'cheat', seats: n, cpuNames: [0, 1, 2, 3].map(Seats.cpuName), onChange: function () { if (t) t.paint(); if (board) board.refresh(); } }); + Object.keys(cur).forEach(function (k) { seats[k] = cur[k]; }); + } + buildSeats(players); + var name = function (seat) { return seats.name(seat); }; + var label = function (r) { return Z.RANK_LABELS[r - 1]; }; + function repaint() { board.refresh(); t.paint(); } + + function said(st) { + var l = st.last; + if (!l) return ''; + var out = TX(l.seat === 0 ? 'cheat.plays.you' : 'cheat.plays', { name: name(l.seat), count: l.count, rank: label(l.rank) }); + if (!l.call) return out; + var c = l.call, verdict = TX((c.lying ? 'cheat.lied' : 'cheat.truth') + (l.seat === 0 ? '.you' : ''), { name: name(l.seat) }); + return TX('cards.then', { first: TX(c.caller === 0 ? 'cheat.called.you' : 'cheat.called', { name: name(c.caller) }), then: TX(c.loser === 0 ? 'cheat.takes.you' : 'cheat.takes', { name: name(c.loser), cards: Z.plural(c.n, 'card'), verdict: verdict }) }); + } + function paintClaim(st) { + var m = board.metrics(); + if (!m) return; + var g = geo(m, st), p = pileSpot(g); + claimBadge.style.left = Math.round(p.x + g.cw / 2) + 'px'; claimBadge.style.top = Math.round(p.y + g.ch + BADGE_GAP) + 'px'; + claimBadge.textContent = st.phase === 'over' ? '' : TX('cheat.claim', { rank: label(st.phase === 'call' ? st.last.rank : st.claim) }); + claimBadge.hidden = st.phase === 'over'; + } + function hud(st) { + paintClaim(st); + var chips = st.hands.map(function (h, seat) { return { name: name(seat), text: String(h.length), turn: st.phase === 'play' && st.turn === seat || st.phase === 'call' && st.callers[0] === seat }; }); + var out = { chips: chips, text: '' }, note = said(st); + var lead = function (text) { return note ? TX('cards.then', { first: note, then: text }) : text; }; + if (st.phase === 'over') { out.text = TX('shell.end.over'); out.label = TX('shell.menu.new'); out.action = newGame; return out; } + if (st.phase === 'call') { + var who = st.callers[0]; + if (who === 0) { + out.text = TX('cheat.callQ', { name: name(st.last.seat), count: st.last.count, rank: label(st.last.rank) }); + out.choices = [{ label: TX('cheat.call'), primary: true, onclick: function () { decideNow(true); } }, { label: TX('cheat.letGo'), onclick: function () { decideNow(false); } }]; + } else out.text = lead(TX('cards.thinking', { name: name(who) })); + return out; + } + if (st.turn !== 0) { out.text = lead(TX('cards.thinking', { name: name(st.turn) })); return out; } + var picked = view.picked, n = picked.length; + out.text = lead(TX('cheat.yourTurn', { rank: label(st.claim) })); + out.choices = [{ label: n ? TX('cheat.playN', { count: n, rank: label(st.claim) }) : TX('cheat.pickCards'), primary: n > 0, disabled: !n, onclick: playNow }]; + return out; + } + + function drive() { + var st = session.state; + if (st.phase === 'over') { gameOver(); return; } + if (st.phase === 'call') { if (st.callers[0] !== 0) session.later(aiDecide, st.last.seat === 0 ? DECIDE_MS * 2 : DECIDE_MS); return; } + if (st.turn !== 0) session.later(aiTurn, st.last && st.last.call ? SHOW_MS : AI_MS); + } + function aiTurn() { + var st = session.state; + if (st.phase !== 'play' || st.turn === 0) return; + session.follow(play(st, st.turn, aiPlay(st, st.turn))); + view.picked = []; + drive(); + } + function aiDecide() { + var st = session.state; + if (st.phase !== 'call' || st.callers[0] === 0) return; + var who = st.callers[0]; + session.follow(decide(st, who, aiCall(st, who))); + repaint(); + drive(); + } + function decideNow(calls) { + var st = session.state; + if (st.phase !== 'call' || st.callers[0] !== 0) return; + session.commit(decide(st, 0, calls)); + drive(); + } + function playNow() { + var st = session.state, ids = view.picked.filter(function (c) { return st.hands[0].indexOf(c) >= 0; }); + if (!canPlay(st, 0, ids)) return; + view.picked = []; + session.commit(play(st, 0, ids)); + drive(); + } + function gameOver() { + var st = session.state, w = st.winner; + var line = TX(w === 0 ? 'cheat.won.you' : w < 0 ? 'cheat.tied' : 'cheat.won', { name: w >= 0 ? name(w) : '' }); + if (w === 0) session.win(); else session.lose(w < 0 ? 'draw' : '', [line]); + } + function tap(pile) { + var st = session.state; + if (pile.charAt(0) !== 'h') return false; + var id = parseInt(pile.slice(1), 10); + if (isNaN(id) || st.phase === 'over') return false; + if (st.phase !== 'play' || st.turn !== 0) { t.flash(TX('cards.wait.turn')); return false; } + var at = view.picked.indexOf(id); + if (at >= 0) view.picked.splice(at, 1); + else if (view.picked.length >= MAX_PLAY) { t.flash(TX('cheat.fourOnly')); return false; } + else view.picked.push(id); + repaint(); + return true; + } + function newGame() { + players = Z.store.get(PLAYERS_KEY, DEFAULT_PLAYERS); + if (players !== 2 && players !== 3 && players !== 4) players = DEFAULT_PLAYERS; + buildSeats(players); + view.flash = ''; view.picked = []; + session.reset(deal(Z.shuffled(Math.random), players, Math.floor(Math.random() * players))); + repaint(); drive(); + } + t = T.create({ + id: 'cheat', name: 'Cheat', view: view, geo: geo, place: place, hud: hud, newGame: newGame, tap: tap, + slotTap: function () {}, + canPick: function () { return false; }, + stat: function (sec, st) { return Z.fmtTime(sec) + ' · ' + st.hands[0].length; }, + cascadeOrder: function (st) { return st.last ? st.last.ids.map(function (id) { return { id: id }; }) : []; }, + winLines: function (sec, st) { return [TX('cheat.won.you', { name: '' })]; }, + menuExtra: function () { + return [T.choiceRow(TX('cards.seatsAtTable'), PLAYERS_KEY, [{ value: 2, label: '2' }, { value: 3, label: '3' }, { value: 4, label: '4' }], DEFAULT_PLAYERS, function () {}), + Z.h('p', { class: 'zc-note', text: TX('ce.seatsNote') })]; + }, + rules: TX('cheat.rules') + }); + board = t.board; session = t.session; + api.session = session; api.board = board; + newGame(); + } + + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/courtier.css b/zimi/builtin/games/courtier.css new file mode 100644 index 000000000..fb55fca88 --- /dev/null +++ b/zimi/builtin/games/courtier.css @@ -0,0 +1,89 @@ +/* Courtier: the court, the hand and the cards. Eight ranks, each its own hue, and also its number, its name and its drawing. */ +:root { + --cr-1: #5d8a3c; --cr-2: #2f7fa8; --cr-3: #b8471f; --cr-4: #6b6f7a; --cr-5: #7a4fb0; --cr-6: #1f8a7a; --cr-7: #b0407f; --cr-8: #b88a0e; + --cr-paper: #fdfcf8; --cr-ink: #26241f; +} +:root[data-theme="dark"] { --cr-1: #78ab52; --cr-2: #4a9fcb; --cr-3: #de6a3e; --cr-4: #9a9fab; --cr-5: #a07fd6; --cr-6: #3fb3a1; --cr-7: #d6639f; --cr-8: #e0b13a; } +/* Red (games.css): this file's colours as red-on-black, by luminance. */ +:root.gs.night-red { --cr-1: #921209; --cr-2: #8b1109; --cr-3: #881109; --cr-4: #9f140a; --cr-5: #931209; --cr-6: #8e1209; --cr-7: #8c1209; --cr-8: #b1160b; --cr-paper: #fc2010; --cr-ink: #240502; } +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { --cr-1: #78ab52; --cr-2: #4a9fcb; --cr-3: #de6a3e; --cr-4: #9a9fab; --cr-5: #a07fd6; --cr-6: #3fb3a1; --cr-7: #d6639f; --cr-8: #e0b13a; } +} +[data-rank="1"] { --rk: var(--cr-1); } [data-rank="2"] { --rk: var(--cr-2); } [data-rank="3"] { --rk: var(--cr-3); } [data-rank="4"] { --rk: var(--cr-4); } +[data-rank="5"] { --rk: var(--cr-5); } [data-rank="6"] { --rk: var(--cr-6); } [data-rank="7"] { --rk: var(--cr-7); } [data-rank="8"] { --rk: var(--cr-8); } + +.cr-main { width: 100%; max-width: 440px; margin: 0 auto; min-height: calc(100dvh - var(--bar-h)); } /* the hand sits at the bottom of the screen, as on every card table */ +.cr-tablearea { width: 100%; display: flex; flex-direction: column; gap: var(--sp-2); } +.cr-seats { display: flex; flex-direction: column; gap: 6px; } +.cr-seat { padding: 6px 10px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); display: flex; flex-direction: column; gap: 4px; } +.cr-seat.cr-turn { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); } +.cr-seat.cr-outseat { opacity: 0.6; } +.cr-seat.cr-pick { cursor: pointer; border-color: var(--accent); background: var(--accent-glow); animation: cr-pulse 1.2s ease-in-out infinite; } +@keyframes cr-pulse { 50% { box-shadow: 0 0 0 3px var(--accent-line); } } +html[data-anim="off"] .cr-seat.cr-pick { animation: none; } +@media (prefers-reduced-motion: reduce) { html:not([data-anim="normal"]):not([data-anim="fast"]) .cr-seat.cr-pick { animation: none; } } +.cr-seathead { display: flex; align-items: center; gap: 8px; min-height: 22px; } +.cr-seathead b { font-size: var(--fs-small); flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cr-pips { display: inline-flex; gap: 4px; } +.cr-pips i { width: 10px; height: 10px; border-radius: 50%; border: 1.5px solid var(--ink2); box-sizing: border-box; } +.cr-pips i.cr-on { background: var(--accent); border-color: var(--accent); } +.cr-tag { font-size: var(--fs-caption); padding: 1px 8px; border-radius: 999px; border: 1px solid var(--line-strong); color: var(--ink); } +.cr-tag-safe { background: var(--accent-glow); border-color: var(--accent-line); } +.cr-tag-out { color: var(--ink2); } +.cr-played { display: flex; align-items: center; gap: 4px; min-height: 28px; flex-wrap: wrap; } +.cr-mini { display: inline-flex; align-items: center; justify-content: center; min-width: 22px; height: 26px; padding: 0 3px; box-sizing: border-box; border-radius: 5px; border: 2px solid var(--rk); background: var(--cr-paper); color: var(--cr-ink); font: 700 13px var(--mono); } +.cr-deck, .cr-log { margin: 0; text-align: center; color: var(--ink2); font-size: var(--fs-small); } +.cr-log { min-height: 2.6em; color: var(--ink); } +.cr-faceup .cr-mini { margin-left: 2px; vertical-align: middle; } + +/* The cards: paper, a band in the rank's hue, the number, the drawing, the name. */ +.cr-card { position: relative; display: flex; flex-direction: column; align-items: center; justify-content: space-between; box-sizing: border-box; width: 104px; height: 144px; padding: 22px 6px 8px; border: 2px solid var(--card-edge, #c9c4b8); border-top: 0; border-radius: 12px; background: var(--cr-paper); color: var(--cr-ink); overflow: hidden; font: inherit; text-align: center; } +.cr-card::before { content: ""; position: absolute; left: 0; right: 0; top: 0; height: 20px; background: var(--rk, var(--ink2)); } +.cr-num { position: absolute; top: 0; left: 8px; z-index: 1; font: 800 15px/20px var(--mono); color: #fff; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.45); } +.cr-emblem { width: 58px; height: 58px; fill: color-mix(in srgb, var(--rk) 22%, transparent); stroke: var(--rk); stroke-width: 2.4; stroke-linecap: round; stroke-linejoin: round; } +.cr-name { font-size: var(--fs-small); font-weight: 650; line-height: 1.15; overflow-wrap: anywhere; } +button.cr-card { cursor: pointer; touch-action: manipulation; padding-top: 22px; transition: transform 0.12s ease-out; } +@media (hover: hover) { button.cr-card:hover { border-color: var(--accent); } } +button.cr-card[aria-disabled="true"] { cursor: default; } +button.cr-card[aria-pressed="true"] { transform: translateY(-14px); box-shadow: var(--select); } +.cr-backcard { background: var(--felt, #285c43); border-color: var(--felt-deep, #1a4130); } +.cr-backcard::before { display: none; } +.cr-backcard { justify-content: center; padding: 0; } +.cr-z { font: 800 34px var(--font); color: rgba(255, 255, 255, 0.85); } +.cr-miniback { width: 18px; height: 26px; border-radius: 4px; border-width: 1px; } +.cr-miniback .cr-z { font-size: 12px; } +.cr-hand { margin-top: auto; display: flex; justify-content: center; gap: var(--sp-3); min-height: 160px; align-items: flex-end; padding-top: 14px; } +.cr-handnote { color: var(--ink2); margin: 0; align-self: center; } +.cr-actions { display: flex; gap: var(--sp-2); justify-content: center; } +.cr-actions .ar-btn { min-height: 44px; min-width: 110px; } +.cr-actions [hidden] { display: none; } + +.cr-ranks { display: grid; grid-template-columns: repeat(auto-fill, minmax(84px, 1fr)); gap: 8px; justify-items: center; } +.cr-smallcard { width: 84px; height: 116px; padding-top: 20px; } +.cr-smallcard .cr-emblem { width: 44px; height: 44px; } +.cr-smallcard .cr-name { font-size: 12px; } +.cr-peekcard { display: flex; justify-content: center; margin: var(--sp-3) 0; } +.cr-reveal { display: flex; flex-direction: column; gap: 6px; margin-top: var(--sp-2); } +.cr-revrow { display: flex; align-items: center; gap: 10px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 10px; } +.cr-revrow b { flex: 1 1 auto; font-size: var(--fs-small); } +.cr-revrow.cr-won { border-color: var(--accent); background: var(--accent-glow); } +.cr-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; } +.cr-guideitem { display: flex; gap: 10px; align-items: flex-start; } +.cr-guideitem > div { display: flex; flex-direction: column; gap: 2px; font-size: var(--fs-small); } +.cr-guideitem span:not(.cr-mini) { color: var(--ink2); } + +/* A short, wide phone (landscape): the court on the left, the hand and its buttons beside it, so a card can be played without scrolling past the court. */ +@media (orientation: landscape) and (max-height: 520px) { + .cr-main { max-width: 860px; min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); column-gap: var(--sp-4); align-content: start; align-items: start; } + .cr-main > #cr-msg { grid-column: 1 / -1; } + .cr-main > .cr-tablearea { grid-column: 1; grid-row: 2 / span 2; } + .cr-main > .cr-hand { grid-column: 2; grid-row: 2; align-self: center; } + .cr-main > .cr-actions { grid-column: 2; grid-row: 3; align-self: start; } +} + +/* Red, generated by scripts/games_red.py from the rules above: do not edit. */ +:root.gs.night-red .cr-card { border: 2px solid var(--card-edge, #c4190c); } +:root.gs.night-red .cr-num { color: #ff2010; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.45); } +:root.gs.night-red .cr-backcard { background: var(--felt, #4a0905); border-color: var(--felt-deep, #330603); } +:root.gs.night-red .cr-z { color: rgba(255, 32, 16, 0.85); } +/* end Red */ diff --git a/zimi/builtin/games/courtier.html b/zimi/builtin/games/courtier.html new file mode 100644 index 000000000..5a2bf1573 --- /dev/null +++ b/zimi/builtin/games/courtier.html @@ -0,0 +1,84 @@ + + + + + +Courtier - ZimiGames + + + + + + +
+ ‹ +

Courtier

+ +
+ +
+

+
+
+

+

+
+
+
+ + +
+
+ + + + + + + + + + + + + + + + + + diff --git a/zimi/builtin/games/courtier.js b/zimi/builtin/games/courtier.js new file mode 100644 index 000000000..a4504e377 --- /dev/null +++ b/zimi/builtin/games/courtier.js @@ -0,0 +1,620 @@ +/* ZimiGames: Courtier. Our own code, GPL-3.0. No network, no fonts, no modules. + Sixteen cards in eight ranks of the court. You hold one, draw one, play one. A played card does its work: name a card and + throw a rival out, peek, compare, shelter, make someone start over, swap hands. When the deck runs out the highest card left + wins the round; rounds give favors, and the first to enough favors wins. The rules and the computer (pure functions, no DOM, + so node can test them) and the page (only when there is a document). */ +(function (root) { + 'use strict'; + + // ── the rules ──────────────────────────────────────────────────────────── + var SCOUT = 1, HERALD = 2, CHAMPION = 3, SENTINEL = 4, MAGISTER = 5, ENVOY = 6, DOWAGER = 7, HEIR = 8; + var COUNTS = [0, 5, 2, 2, 2, 2, 1, 1, 1]; // how many of each rank, indexed by rank + var MIN_PLAYERS = 2, MAX_PLAYERS = 4, SET_ASIDE_FACE_UP = 3; + var FAVORS_TO_WIN = { 2: 5, 3: 4, 4: 3 }; + var LOG_KEEP = 24; + var NO_PLAY = -10; // a move the computer will not make + + function fullDeck() { + var d = []; + for (var r = 1; r <= HEIR; r++) for (var k = 0; k < COUNTS[r]; k++) d.push(r); + return d; + } + function shuffle(a, rng) { + for (var i = a.length - 1; i > 0; i--) { var j = Math.floor(rng() * (i + 1)), t = a[i]; a[i] = a[j]; a[j] = t; } + return a; + } + + function createGame(n, seed, cpuFlags) { + n = Math.max(MIN_PLAYERS, Math.min(MAX_PLAYERS, n || 3)); + var rng = root.ZimiUtil.counted(seed === undefined ? Math.floor(Math.random() * 4294967296) : seed); + var players = []; + for (var i = 0; i < n; i++) { + // Each computer has a temperament: how much it varies from the plain best play. + players.push({ name: '', ai: cpuFlags ? !!cpuFlags[i] : i > 0, hand: [], played: [], out: false, shield: false, favors: 0, known: {}, not: {}, vary: 0.02 + rng() * 0.08 }); + } + var g = { n: n, players: players, goal: FAVORS_TO_WIN[n], deck: [], aside: 0, faceUp: [], turn: 0, round: 0, over: false, winner: -1, roundEnd: null, last: null, log: [], rng: rng }; + startRound(g, 0); + return g; + } + + function startRound(g, starter) { + g.round++; + g.roundEnd = null; g.last = null; g.log = []; + g.deck = shuffle(fullDeck(), g.rng); + g.aside = g.deck.pop(); + g.faceUp = []; + if (g.n === 2) for (var k = 0; k < SET_ASIDE_FACE_UP; k++) g.faceUp.push(g.deck.pop()); + g.players.forEach(function (p) { p.hand = [g.deck.pop()]; p.played = []; p.out = false; p.shield = false; p.known = {}; p.not = {}; }); + g.turn = starter; + beginTurn(g); + } + function beginTurn(g) { + var p = g.players[g.turn]; + p.shield = false; + p.hand.push(g.deck.pop()); + } + function active(g) { return g.players.map(function (p, i) { return i; }).filter(function (i) { return !g.players[i].out; }); } + function nextActive(g, i) { var k = i; do { k = (k + 1) % g.n; } while (g.players[k].out); return k; } + + // The Dowager must be played when it is held with the Magister or the Envoy. + function forcedIndex(hand) { + if (hand.length !== 2) return -1; + var has = function (r) { return hand.indexOf(r) >= 0; }; + return has(DOWAGER) && (has(MAGISTER) || has(ENVOY)) ? hand.indexOf(DOWAGER) : -1; + } + function canPlay(g, idx) { + if (g.over || g.roundEnd) return false; + var hand = g.players[g.turn].hand; + if (idx < 0 || idx >= hand.length) return false; + var f = forcedIndex(hand); + return f < 0 || f === idx; + } + // Who a rank can be played on: rivals still in and not sheltered (the Magister may also be played on yourself). + function targets(g, rank, by) { + var out = []; + if (rank === SENTINEL || rank === DOWAGER || rank === HEIR) return out; + g.players.forEach(function (p, i) { + if (p.out) return; + if (i === by) { if (rank === MAGISTER) out.push(i); return; } + if (!p.shield) out.push(i); + }); + return out; + } + function needsTarget(rank) { return rank === SCOUT || rank === HERALD || rank === CHAMPION || rank === MAGISTER || rank === ENVOY; } + + function knockOut(g, i) { + var p = g.players[i]; + p.played = p.played.concat(p.hand); + p.hand = []; + p.out = true; + g.players.forEach(function (q) { delete q.known[i]; delete q.not[i]; }); + } + + // What each card does when played: (game, event, the player, the rival or null, the named card). + var EFFECTS = {}; + EFFECTS[SCOUT] = function (g, ev, p, q, guess) { + if (q.hand[0] === guess) { ev.out.push(ev.target); knockOut(g, ev.target); } + else g.players.forEach(function (o) { o.not[ev.target] = (o.not[ev.target] || []).concat(guess); }); + }; + EFFECTS[HERALD] = function (g, ev, p, q) { ev.peek = q.hand[0]; p.known[ev.target] = q.hand[0]; }; + EFFECTS[CHAMPION] = function (g, ev, p, q) { + var mine = p.hand[0], theirs = q.hand[0]; + if (mine > theirs) { ev.out.push(ev.target); knockOut(g, ev.target); } + else if (mine < theirs) { ev.out.push(ev.by); knockOut(g, ev.by); } + else { ev.tie = true; p.known[ev.target] = theirs; q.known[ev.by] = mine; } + }; + EFFECTS[SENTINEL] = function (g, ev, p) { p.shield = true; }; + EFFECTS[MAGISTER] = function (g, ev, p, q) { + var t = ev.target, dropped = q.hand[0]; + ev.discard = dropped; ev.redraw = true; + g.players.forEach(function (o) { delete o.known[t]; delete o.not[t]; }); + if (dropped === HEIR) { ev.out.push(t); knockOut(g, t); } + else { q.played.push(dropped); q.hand = [g.deck.length ? g.deck.pop() : g.aside]; } + }; + EFFECTS[ENVOY] = function (g, ev, p, q) { + var by = ev.by, t = ev.target, mineBefore = p.hand[0], theirsBefore = q.hand[0]; + p.hand = [theirsBefore]; q.hand = [mineBefore]; + ev.swapped = true; + // Whoever held either card knows where it went; everyone else's notes on the two seats trade places. + var kb = g.players.map(function (o) { return [o.known[by], o.known[t]]; }); + var nb = g.players.map(function (o) { return [o.not[by], o.not[t]]; }); + g.players.forEach(function (o, oi) { + delete o.known[by]; delete o.known[t]; delete o.not[by]; delete o.not[t]; + if (oi === by || oi === t) return; + if (kb[oi][1] !== undefined) o.known[by] = kb[oi][1]; + if (kb[oi][0] !== undefined) o.known[t] = kb[oi][0]; + if (nb[oi][1]) o.not[by] = nb[oi][1]; + if (nb[oi][0]) o.not[t] = nb[oi][0]; + }); + p.known[t] = mineBefore; q.known[by] = theirsBefore; + }; + EFFECTS[HEIR] = function (g, ev) { ev.out.push(ev.by); knockOut(g, ev.by); }; + + // Play the card at idx. target: a seat or -1; guess: a rank (the Scout). Returns the event, or false when the move is not legal. + function play(g, idx, target, guess) { + if (!canPlay(g, idx)) return false; + var by = g.turn, p = g.players[by], rank = p.hand[idx]; + var legal = targets(g, rank, by), need = needsTarget(rank); + if (need && legal.length && legal.indexOf(target) < 0) return false; + if (rank === SCOUT && legal.length && (guess < 2 || guess > HEIR || guess !== Math.floor(guess))) return false; + var t = need && legal.length ? target : -1; + p.hand.splice(idx, 1); + p.played.push(rank); + var ev = { by: by, rank: rank, target: t, guess: rank === SCOUT && t >= 0 ? guess : 0, out: [], peek: 0, tie: false, swapped: false, redraw: false, discard: 0 }; + var q = t >= 0 ? g.players[t] : null; + // What the table can learn first: a card played that the player had been known to hold is no longer known. + g.players.forEach(function (o) { if (o.known[by] === rank) delete o.known[by]; delete o.not[by]; }); + var effect = EFFECTS[rank]; + if (effect && (q || !needsTarget(rank))) effect(g, ev, p, q, guess); + g.last = ev; + g.log.push(ev); if (g.log.length > LOG_KEEP) g.log.shift(); + finishPlay(g); + return ev; + } + + function finishPlay(g) { + var alive = active(g); + if (alive.length === 1) return endRound(g, 'last'); + if (!g.deck.length) return endRound(g, 'deck'); + g.turn = nextActive(g, g.turn); + beginTurn(g); + } + + function playedSum(p) { return p.played.reduce(function (a, r) { return a + r; }, 0); } + function endRound(g, why) { + var alive = active(g), best = -1, winners = []; + if (alive.length === 1) winners = alive; + else { + alive.forEach(function (i) { best = Math.max(best, g.players[i].hand[0]); }); + winners = alive.filter(function (i) { return g.players[i].hand[0] === best; }); + var most = Math.max.apply(null, winners.map(function (i) { return playedSum(g.players[i]); })); + winners = winners.filter(function (i) { return playedSum(g.players[i]) === most; }); + } + winners.forEach(function (i) { g.players[i].favors++; }); + g.roundEnd = { why: why, winners: winners, hands: g.players.map(function (p) { return p.hand.slice(); }), aside: g.aside }; + var top = Math.max.apply(null, g.players.map(function (p) { return p.favors; })); + if (top >= g.goal) { + g.over = true; + g.winner = g.players.map(function (p, i) { return i; }).filter(function (i) { return g.players[i].favors === top; })[0]; + } + } + function nextRound(g) { + if (g.over || !g.roundEnd) return false; + startRound(g, g.roundEnd.winners[0]); + return true; + } + + // ── the computer ───────────────────────────────────────────────────────── + // It knows what everyone can see (every card played, the face-up cards), its own hand, and what it has learned: a peek, a + // swap, a wrong guess. Cards it cannot place are spread over the rest in proportion to how many are left. + function unseen(g, me) { + var left = COUNTS.slice(); + g.players.forEach(function (p) { p.played.forEach(function (r) { left[r]--; }); }); + g.faceUp.forEach(function (r) { left[r]--; }); + g.players[me].hand.forEach(function (r) { left[r]--; }); + return left; + } + // How likely each rank is to be the card seat t holds, as the computer sees it. + function guessDist(g, me, t, left) { + var o = g.players[me], dist = [0, 0, 0, 0, 0, 0, 0, 0, 0], total = 0, r; + if (o.known[t]) { dist[o.known[t]] = 1; return dist; } + var bar = o.not[t] || []; + for (r = 1; r <= HEIR; r++) { if (left[r] > 0 && bar.indexOf(r) < 0) { dist[r] = left[r]; total += left[r]; } } + if (!total) for (r = 1; r <= HEIR; r++) { if (left[r] > 0) { dist[r] = left[r]; total += left[r]; } } + if (total) for (r = 1; r <= HEIR; r++) dist[r] /= total; + return dist; + } + function expected(dist) { var e = 0; for (var r = 1; r <= HEIR; r++) e += dist[r] * r; return e; } + + function expectedLeft(left) { + var n = 0, e = 0; + for (var r = 1; r <= HEIR; r++) { n += Math.max(left[r], 0); e += Math.max(left[r], 0) * r; } + return n ? e / n : 4; + } + + var HOLD_WEIGHT = 0.08, HEIR_HOLD_BONUS = 0.12, WIN_VALUE = 1.1, LOSS_VALUE = 1.3; + // The worth of playing `rank` and keeping `kept`: the best target and guess, and that worth. + function appraise(g, me, rank, kept, left) { + var legal = targets(g, rank, me), best, r, d; + var rivals = legal.filter(function (x) { return x !== me; }); + best = { score: -Infinity, target: -1, guess: 0 }; + function take(score, target, guess) { if (score > best.score) best = { score: score, target: target, guess: guess || 0 }; } + if (rank === HEIR) return { score: NO_PLAY, target: -1, guess: 0 }; + if (rank === SCOUT) { + if (!rivals.length) take(0.02, -1, 0); + rivals.forEach(function (t) { + d = guessDist(g, me, t, left); + var gr = 0, gp = -1; + for (r = 2; r <= HEIR; r++) if (d[r] > gp) { gp = d[r]; gr = r; } + take(WIN_VALUE * Math.max(gp, 0) + 0.05, t, gr || 2); + }); + } else if (rank === HERALD) { + if (!rivals.length) take(0.02, -1, 0); + rivals.forEach(function (t) { take(g.players[me].known[t] ? 0.04 : 0.22 + 0.01 * (HEIR - Math.min(g.deck.length, 8)), t, 0); }); + } else if (rank === CHAMPION) { + if (!rivals.length) take(0.02, -1, 0); + rivals.forEach(function (t) { + d = guessDist(g, me, t, left); + var s = 0; + for (r = 1; r <= HEIR; r++) s += d[r] * (kept > r ? WIN_VALUE : kept < r ? -LOSS_VALUE : 0); + take(s, t, 0); + }); + } else if (rank === SENTINEL) { + take(0.28 + 0.04 * kept, -1, 0); + } else if (rank === MAGISTER) { + legal.forEach(function (t) { + if (t === me) { + if (kept === HEIR) return take(NO_PLAY, t, 0); // forced to give up the Heir, or to play it: out either way + var e = expectedLeft(left); + take(0.18 * (e - kept) / HEIR * 2 + (kept <= 2 ? 0.12 : 0) - (kept >= 6 ? 0.25 : 0), t, 0); + } else { + d = guessDist(g, me, t, left); + take(WIN_VALUE * d[HEIR] + 0.06 + 0.03 * (expected(d) - 4), t, 0); + } + }); + } else if (rank === ENVOY) { + if (!rivals.length) take(0.02, -1, 0); + rivals.forEach(function (t) { + d = guessDist(g, me, t, left); + take(0.5 * (expected(d) - kept) / HEIR + (kept === HEIR ? NO_PLAY : 0), t, 0); + }); + } else if (rank === DOWAGER) { + take(0.06, -1, 0); + } + return best; + } + + function aiMove(g) { + var me = g.turn, p = g.players[me], hand = p.hand, left = unseen(g, me), best = null; + for (var idx = 0; idx < hand.length; idx++) { + if (!canPlay(g, idx)) continue; + var kept = hand[1 - idx], a = appraise(g, me, hand[idx], kept, left); + var score = a.score + HOLD_WEIGHT * kept / HEIR + (kept === HEIR ? HEIR_HOLD_BONUS : 0) + (g.rng() - 0.5) * 2 * p.vary; + if (!best || score > best.score) best = { score: score, idx: idx, target: a.target, guess: a.guess }; + } + return { idx: best.idx, target: best.target, guess: best.guess }; + } + + // A random player that follows the rules and nothing else (the yardstick the tests measure the computer against). + function randomMove(g, rng) { + var me = g.turn, hand = g.players[me].hand, choices = [], idx; + for (idx = 0; idx < hand.length; idx++) if (canPlay(g, idx)) choices.push(idx); + idx = choices[Math.floor(rng() * choices.length)]; + var legal = targets(g, hand[idx], me), t = needsTarget(hand[idx]) && legal.length ? legal[Math.floor(rng() * legal.length)] : -1; + return { idx: idx, target: t, guess: 2 + Math.floor(rng() * 7) }; + } + + var Engine = { COUNTS: COUNTS, FAVORS_TO_WIN: FAVORS_TO_WIN, MIN_PLAYERS: MIN_PLAYERS, MAX_PLAYERS: MAX_PLAYERS, SCOUT: SCOUT, HERALD: HERALD, CHAMPION: CHAMPION, SENTINEL: SENTINEL, MAGISTER: MAGISTER, ENVOY: ENVOY, DOWAGER: DOWAGER, HEIR: HEIR, + createGame: createGame, fullDeck: fullDeck, startRound: startRound, nextRound: nextRound, canPlay: canPlay, forcedIndex: forcedIndex, targets: targets, needsTarget: needsTarget, play: play, + active: active, unseen: unseen, guessDist: guessDist, aiMove: aiMove, randomMove: randomMove, snapshot: root.ZimiUtil.snapshot, restore: root.ZimiUtil.restore }; + root.CourtierEngine = Engine; + + if (typeof document === 'undefined') return; + + // ── the page ───────────────────────────────────────────────────────────── + var Play = root.ArcadePlay, $ = Play.$, T = Play.T; + var SETTINGS_KEY = 'zimi.games.courtier.settings', STATS_KEY = 'zimi.games.courtier.stats'; + var AI_DELAY_MS = 950, FLASH_MS = 2200; + Play.applyTheme(); + + var els = { msg: $('cr-msg'), seats: $('cr-seats'), deck: $('cr-deck'), log: $('cr-log'), hand: $('cr-hand'), play: $('cr-play'), guide: $('cr-guide'), nu: $('cr-new'), + guess: $('cr-guess'), guessText: $('cr-guess-text'), ranks: $('cr-ranks'), guessCancel: $('cr-guess-cancel'), + peek: $('cr-peek'), peekText: $('cr-peek-text'), peekCard: $('cr-peekcard'), peekOk: $('cr-peek-ok'), + round: $('cr-round'), roundTitle: $('cr-round-title'), roundText: $('cr-round-text'), reveal: $('cr-reveal'), roundNext: $('cr-round-next'), + cards: $('cr-cards'), list: $('cr-list'), cardsClose: $('cr-cards-close'), + sheet: $('cr-sheet'), n: $('cr-n'), go: $('cr-go') }; + var settings = Play.load(SETTINGS_KEY, { players: 3 }), stats = Play.load(STATS_KEY, { played: 0, won: 0 }); + var g, seats, timer = null, sel = -1, choosing = false, counted = false, flashTimer = 0, lastLog = ''; + + // One drawing for each rank, in a 40 by 40 box. Colour never carries the rank alone: the number, the name and the shape do too. + var EMBLEM = { + 1: '', + 2: '', + 3: '', + 4: '', + 5: '', + 6: '', + 7: '', + 8: '' + }; + function rankName(r) { return T('courtier.rank.' + r); } + function el(tag, cls, text) { var e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; } + function cardEl(rank, tag) { + var c = el(tag || 'div', 'cr-card'); + c.dataset.rank = rank; + c.innerHTML = ''; + c.firstChild.textContent = Play.num(rank); + c.lastChild.textContent = rankName(rank); + return c; + } + function backEl(cls) { var b = el('div', 'cr-card cr-backcard' + (cls ? ' ' + cls : '')); b.setAttribute('aria-hidden', 'true'); b.innerHTML = 'Z'; return b; } + // A card already played, small: its number in its colour, its name for a screen reader. + function miniEl(rank) { + var m = el('span', 'cr-mini', Play.num(rank)); m.dataset.rank = rank; + m.setAttribute('role', 'img'); m.setAttribute('aria-label', rankName(rank)); + return m; + } + function pipsEl(p) { + var pips = el('span', 'cr-pips'); + for (var k = 0; k < g.goal; k++) pips.appendChild(el('i', k < p.favors ? 'cr-on' : '')); + pips.setAttribute('role', 'img'); pips.setAttribute('aria-label', T('courtier.favors', { n: p.favors, goal: g.goal })); + return pips; + } + + function seatPlayers(n) { + seats = root.ZimiSeats.create({ id: 'courtier', seats: n, onChange: function () { paint(); } }); + var cpu = 0; + g.players.forEach(function (p, i) { + p.ai = !seats.person(i); + p.name = seats.person(i) ? seats.name(i) : (n === 2 ? root.ZimiSeats.ZIMI : root.ZimiSeats.cpuName(cpu++)); + }); + } + function newTable() { + var kinds = root.ZimiSeats.create({ id: 'courtier', seats: settings.players }).kinds(); + g = createGame(settings.players, undefined, kinds.map(function (k) { return k === 'cpu'; })); + seatPlayers(settings.players); + counted = false; + } + function nm(i) { return seats.isYou(i) ? T('board.you') : g.players[i].name; } + function myTurn() { return !g.over && !g.roundEnd && seats.person(g.turn) && (!seats.hotseat() || seats.view() === g.turn); } + function curRank() { return sel >= 0 ? g.players[g.turn].hand[sel] : 0; } + + function paintSeats() { + els.seats.textContent = ''; + var pickable = choosing && sel >= 0 ? targets(g, curRank(), g.turn) : []; + g.players.forEach(function (p, i) { + var row = el('div', 'cr-seat' + (i === g.turn && !g.roundEnd && !g.over ? ' cr-turn' : '') + (p.out ? ' cr-outseat' : '')); + row.setAttribute('role', 'listitem'); + var head = el('div', 'cr-seathead'); + head.appendChild(el('b', null, nm(i))); + head.appendChild(pipsEl(p)); + if (p.out) head.appendChild(el('span', 'cr-tag cr-tag-out', T('courtier.out'))); + else if (p.shield) head.appendChild(el('span', 'cr-tag cr-tag-safe', T('courtier.safe'))); + row.appendChild(head); + var played = el('div', 'cr-played'); + p.played.forEach(function (r) { played.appendChild(miniEl(r)); }); + if (!p.out && i !== seats.view()) played.appendChild(backEl('cr-miniback')); // an opponent's hidden card; yours is in your hand + row.appendChild(played); + row.setAttribute('aria-label', p.out ? T('courtier.seat.out', { name: nm(i) }) : T('courtier.seat.ok', { name: nm(i), n: p.played.length })); + if (pickable.indexOf(i) >= 0) { + row.classList.add('cr-pick'); row.setAttribute('role', 'button'); row.tabIndex = 0; + row.setAttribute('aria-label', T('courtier.chooseSeat', { name: nm(i) })); + row.addEventListener('click', function () { chooseTarget(i); }); + row.addEventListener('keydown', function (e) { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); chooseTarget(i); } }); + } + els.seats.appendChild(row); + }); + } + function paintDeck() { + els.deck.textContent = T('courtier.deck', { n: g.deck.length }); + if (g.faceUp.length) { + var tail = el('span', 'cr-faceup', ' · ' + T('courtier.faceUp') + ' '); + g.faceUp.forEach(function (r) { tail.appendChild(miniEl(r)); }); + els.deck.appendChild(tail); + } + } + function paintHand() { + els.hand.textContent = ''; + var V = seats.view(), me = g.players[V], hide = seats.hotseat() && (seats.viewer < 0 || g.turn !== V); + if (!me || me.out) { els.hand.appendChild(el('p', 'cr-handnote', T('courtier.youOut'))); return; } + me.hand.forEach(function (r, i) { + if (hide) { els.hand.appendChild(backEl()); return; } + var b = cardEl(r, 'button'), live = myTurn(); + b.type = 'button'; + b.setAttribute('aria-pressed', String(live && sel === i)); + b.setAttribute('aria-label', Play.num(r) + ', ' + rankName(r) + '. ' + T('courtier.power.' + r)); + b.setAttribute('aria-disabled', String(!live || !canPlay(g, i))); + b.addEventListener('click', function () { tapCard(i); }); + els.hand.appendChild(b); + }); + } + function paintStatus() { + if (g.over || g.roundEnd) return; + if (myTurn()) els.msg.textContent = choosing ? T('courtier.chooseTarget') : sel >= 0 ? T('courtier.power.' + curRank()) : T(seats.isYou(g.turn) ? 'courtier.turn.you' : 'courtier.turn.name', { name: nm(g.turn) }); + else els.msg.textContent = g.players[g.turn].ai ? T('courtier.thinking', { name: nm(g.turn) }) : T('seats.passTo', { name: nm(g.turn) }); + } + function paint() { + paintSeats(); paintDeck(); paintHand(); paintStatus(); + els.log.textContent = lastLog; + var live = myTurn(); + els.play.setAttribute('aria-disabled', String(!live || sel < 0)); + els.play.hidden = !live; + } + + // A tap that cannot do anything says why for a moment, then the line goes back to what is to do. + function flash(text, thing) { + els.msg.textContent = text; + if (thing) ZimiShell.shake(thing); + root.clearTimeout(flashTimer); + flashTimer = root.setTimeout(function () { if (!g.over && !g.roundEnd) paintStatus(); }, FLASH_MS); + } + + function tapCard(i) { + if (!myTurn()) { flash(T('courtier.why.wait'), els.hand); return; } + if (!canPlay(g, i)) { flash(T('courtier.why.dowager'), els.hand.children[i]); return; } + if (sel === i && !choosing) { confirmPlay(); return; } + sel = i; choosing = false; paint(); + } + function confirmPlay() { + if (!myTurn()) return; + if (sel < 0) { flash(T('courtier.why.pick'), els.hand); return; } + var rank = curRank(), legal = targets(g, rank, g.turn); + if (needsTarget(rank) && legal.length > 1) { choosing = true; paint(); return; } + chooseTarget(needsTarget(rank) && legal.length ? legal[0] : -1); + } + function chooseTarget(t) { + if (curRank() === SCOUT && t >= 0) { openGuess(t); return; } + doPlay(t, 0); + } + function openGuess(t) { + els.guessText.textContent = T('courtier.guess.text', { name: nm(t) }); + els.ranks.textContent = ''; + for (var r = 2; r <= HEIR; r++) { + var b = cardEl(r, 'button'); + b.type = 'button'; b.classList.add('cr-smallcard'); + b.setAttribute('aria-label', Play.num(r) + ', ' + rankName(r)); + (function (rank) { b.addEventListener('click', function () { Play.closeSheet(els.guess); doPlay(t, rank); }); })(r); + els.ranks.appendChild(b); + } + Play.openSheet(els.guess, '.cr-card'); + } + els.guessCancel.addEventListener('click', function () { Play.closeSheet(els.guess); }); + + // The play goes to the rules; the table, the line and (for a peek) the sheet follow. + function doPlay(t, guess) { + var ev = play(g, sel, t, guess), mine = seats.person(ev ? ev.by : g.turn); + if (!ev) return false; + sel = -1; choosing = false; + lastLog = evText(ev); + if (ev.peek && mine) return showPeek(ev); + afterPlay(); + return true; + } + function evText(ev) { + var by = nm(ev.by), parts = []; + parts.push(T(ev.target >= 0 ? 'courtier.ev.on' : 'courtier.ev.play', { name: by, card: rankName(ev.rank), target: ev.target >= 0 ? nm(ev.target) : '' })); + if (ev.guess) parts.push(T('courtier.ev.named', { card: rankName(ev.guess) })); + if (ev.rank === SCOUT && ev.target >= 0 && !ev.out.length) parts.push(T('courtier.res.wrong')); + if (ev.redraw) parts.push(T('courtier.res.discard', { name: nm(ev.target), card: rankName(ev.discard) })); + ev.out.forEach(function (i) { parts.push(T('courtier.res.out', { name: nm(i) })); }); + if (ev.tie) parts.push(T('courtier.res.tie')); + if (ev.rank === SENTINEL) parts.push(T('courtier.res.safe', { name: by })); + if (ev.swapped) parts.push(T('courtier.res.swap')); + if (needsTarget(ev.rank) && ev.target < 0) parts.push(T('courtier.res.nobody')); + return parts.join(' '); + } + function showPeek(ev) { + els.peekText.textContent = T('courtier.peek.text', { name: nm(ev.target) }); + els.peekCard.textContent = ''; + els.peekCard.appendChild(cardEl(ev.peek)); + paint(); + Play.openSheet(els.peek, '#cr-peek-ok'); + return true; + } + els.peekOk.addEventListener('click', function () { Play.closeSheet(els.peek); afterPlay(); }); + + function afterPlay() { + paint(); + if (timer) timer.cancel(); + if (g.roundEnd) { timer = Play.later(showRound, AI_DELAY_MS / 2); return; } + schedule(); + } + function schedule() { + if (timer) timer.cancel(); + if (g.over || g.roundEnd) return; + if (g.players[g.turn].ai) { timer = Play.later(aiStep, AI_DELAY_MS); return; } + if (seats.hotseat()) seats.ensure(g.turn, paint, T('courtier.passNote')); else paint(); + } + function aiStep() { + if (g.over || g.roundEnd || !g.players[g.turn].ai) return; + var m = aiMove(g), ev = play(g, m.idx, m.target, m.guess); + if (!ev) return; + lastLog = evText(ev); + afterPlay(); + } + + function showRound() { + var re = g.roundEnd; + if (!re) return; + var names = re.winners.map(nm).join(', '); + els.roundTitle.textContent = re.winners.length > 1 ? T('courtier.round.tie', { names: names }) : seats.isYou(re.winners[0]) ? T('courtier.round.you') : T('courtier.round.wins', { name: names }); + els.roundText.textContent = T(re.why === 'last' ? 'courtier.round.last' : 'courtier.round.deck'); + els.reveal.textContent = ''; + g.players.forEach(function (p, i) { + var row = el('div', 'cr-revrow' + (re.winners.indexOf(i) >= 0 ? ' cr-won' : '')); + row.appendChild(el('b', null, nm(i))); + row.appendChild(re.hands[i].length ? miniEl(re.hands[i][0]) : el('span', 'cr-tag cr-tag-out', T('courtier.out'))); + row.appendChild(pipsEl(p)); + els.reveal.appendChild(row); + }); + els.roundNext.textContent = T(g.over ? 'courtier.result' : 'courtier.nextRound'); + Play.openSheet(els.round, '#cr-round-next'); + } + els.roundNext.addEventListener('click', function () { + Play.closeSheet(els.round); + if (g.over) return finish(counted); + nextRound(g); sel = -1; choosing = false; lastLog = ''; + paint(); seats.begin(function () { paint(); schedule(); }, g.turn); + }); + + function finish(already) { + var text, title, won; + if (seats.hotseat()) { won = true; text = T('courtier.end.hot', { name: nm(g.winner) }); title = T('shell.end.wins', { name: nm(g.winner) }); } + else { + won = seats.person(g.winner); + if (!already) { stats.played++; if (won) stats.won++; Play.save(STATS_KEY, stats); counted = true; } + text = T(won ? 'courtier.end.win' : 'courtier.end.wins', { name: g.players[g.winner].name }) + ' ' + T('courtier.end.record', { won: stats.won, played: stats.played }); + title = T(won ? 'shell.end.win' : 'shell.end.lose'); + } + els.msg.textContent = text; + ZimiShell.endSheet({ title: title, result: won ? 'win' : 'lose', text: text, onNew: begin, after: already ? 0 : undefined }); + } + + els.play.addEventListener('click', function () { if (myTurn()) confirmPlay(); }); + els.guide.addEventListener('click', function () { + els.list.textContent = ''; + for (var r = 1; r <= HEIR; r++) { + var li = el('li', 'cr-guideitem'), box = el('div'); + li.appendChild(miniEl(r)); + box.appendChild(el('b', null, rankName(r) + ' ×' + Play.num(COUNTS[r]))); + box.appendChild(el('span', null, T('courtier.power.' + r))); + li.appendChild(box); els.list.appendChild(li); + } + Play.openSheet(els.cards, '#cr-cards-close'); + }); + els.cardsClose.addEventListener('click', function () { Play.closeSheet(els.cards); }); + + function paintN() { + els.n.textContent = ''; + for (var n = MIN_PLAYERS; n <= MAX_PLAYERS; n++) { + var b = el('button', null, Play.num(n)); + b.type = 'button'; + b.setAttribute('aria-pressed', String(settings.players === n)); + (function (k) { b.addEventListener('click', function () { settings.players = k; Play.save(SETTINGS_KEY, settings); paintN(); }); })(n); + els.n.appendChild(b); + } + var host = $('cr-seatsblock'); + host.textContent = ''; + host.appendChild(root.ZimiSeats.create({ id: 'courtier', seats: settings.players }).block()); + } + function showSheet() { paintN(); Play.openSheet(els.sheet, '#cr-go'); } + function begin() { + if (timer) timer.cancel(); + newTable(); sel = -1; choosing = false; lastLog = ''; + Play.closeSheet(els.sheet); paint(); seats.begin(function () { paint(); schedule(); }, g.turn); + } + els.go.addEventListener('click', begin); + els.nu.addEventListener('click', function () { if (timer) timer.cancel(); showSheet(); }); + document.addEventListener('keydown', function (e) { + if (e.ctrlKey || e.metaKey || e.altKey || !els.sheet.hidden || !els.round.hidden || !els.guess.hidden || !els.peek.hidden || !myTurn()) return; + if (e.key === '1' || e.key === '2') { var i = +e.key - 1; if (i < g.players[g.turn].hand.length) { e.preventDefault(); tapCard(i); } } + else if (e.key === 'Escape' && choosing) { choosing = false; paint(); } + }); + + function started() { return g.round > 1 || g.players.some(function (p) { return p.played.length > 0; }); } + newTable(); paint(); + ZimiShell.game({ + table: '#cr-table', + inProgress: function () { return !g.over && started(); }, + stats: function () { return stats.played ? [[T('cards.stats.played'), Play.num(stats.played)], [T('cards.stats.won'), Play.num(stats.won)]] : []; } + }); + showSheet(); + // Never lose a game: the table (every card, who is out, the favors, where the generator stood) and whether the game was counted. + ZimiShell.persist({ + save: function () { return started() ? { g: Engine.snapshot(g), counted: counted, log: lastLog } : null; }, + load: function (data) { + var saved = data && data.g; + if (!saved || !Array.isArray(saved.players) || saved.players.length < MIN_PLAYERS || !saved.deck) return false; + g = Engine.restore(saved); + seatPlayers(g.players.length); + counted = !!data.counted; lastLog = typeof data.log === 'string' ? data.log : ''; + sel = -1; choosing = false; + Play.closeSheet(els.sheet); + paint(); + if (g.roundEnd) { showRound(); return true; } + seats.begin(function () { paint(); schedule(); }, g.turn); + return true; + } + }); + root.__courtier = { get g() { return g; }, refresh: paint }; +})(this); diff --git a/zimi/builtin/games/courts.js b/zimi/builtin/games/courts.js index 6df501388..0c69d0e2f 100644 --- a/zimi/builtin/games/courts.js +++ b/zimi/builtin/games/courts.js @@ -60,7 +60,28 @@ return layers ? canvas(layers, (100 - THUMB_W) / 2, THUMB_Y, THUMB_W, Math.round(THUMB_W * THUMB_CANVAS_H / CANVAS_W * 10) / 10, THUMB_CANVAS_H) : ''; } - var api = { markup: markup, thumb: thumb, KINDS: KINDS }; + // The French face's court (cards.js): the upper figure alone, crown to waist (the canvas's upper HALF_H), inside a frame of any + // shape: the frame shows the whole height of the half and as much of its width, about the figure's centre line, as its aspect + // allows (a frame wider than the half shows all of it and loses a sliver at the waist instead). One per court in the + // page's sprite holds the half; each frame draws it through a nested svg whose viewBox is the crop. The cascade's standalone + // bitmaps get the layers inline. + var HALF_H = 1000; + function panelId(kind, suit) { return 'zc-ct-' + KINDS[kind] + SUITS.charAt(suit); } + function symbols() { + return Object.keys(ART).map(function (k) { return '' + ART[k].map(layer).join('') + ''; }).join(''); + } + function crop(w, h) { + var cw = Math.min(CANVAS_W, HALF_H * w / h), chh = cw * h / w; + return [(CANVAS_W - cw) / 2, 0, cw, chh].map(function (v) { return Math.round(v * 10) / 10; }).join(' '); + } + function panel(kind, suit, x, y, w, h, standalone) { + var layers = ART[KINDS[kind] + SUITS.charAt(suit)]; + if (!layers) return ''; + var inner = standalone ? layers.map(layer).join('') : ''; + return '' + inner + ''; + } + + var api = { markup: markup, thumb: thumb, panel: panel, symbols: symbols, KINDS: KINDS }; root.ZimiCourts = api; if (typeof module !== 'undefined' && module.exports) module.exports = api; })(typeof window !== 'undefined' ? window : globalThis); diff --git a/zimi/builtin/games/eightoff.html b/zimi/builtin/games/eightoff.html new file mode 100644 index 000000000..46bd7bc8f --- /dev/null +++ b/zimi/builtin/games/eightoff.html @@ -0,0 +1,30 @@ + + + + + +Eight Off + + + + + +
+ ‹ +

Eight Off

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/eightoff.js b/zimi/builtin/games/eightoff.js new file mode 100644 index 000000000..700fec53c --- /dev/null +++ b/zimi/builtin/games/eightoff.js @@ -0,0 +1,44 @@ +/* ZimiGames: Eight Off. Eight columns of six cards and eight free cells, four of which start with a card in them. Build down in one + suit, one card at a time; only a king fills an empty column. Four foundations build up by suit from the ace. Like FreeCell it + is nearly always won with care. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, K = root.ZimiSolKit; + + var TABLEAU = ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'], FOUNDATION = ['f0', 'f1', 'f2', 'f3']; + var CELLS = ['c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7']; + var COLS = 8, COLUMN_CARDS = 6, START_CELLS = 4, FOUNDATION_COL = 2; + + var R = K.rules({ + tableau: TABLEAU, foundation: FOUNDATION, cells: CELLS, + runOK: function (list) { return list.length === 1; }, + builds: function (upper, lower) { return Z.suit(upper) === Z.suit(lower) && Z.rank(lower) === Z.rank(upper) - 1; }, + emptyOK: function (id) { return Z.rank(id) === Z.KING; }, + whyBuild: 'sol.why.suit', whyEmpty: 'sol.why.king', whyPick: 'sol.why.single' + }); + var blank = function () { return K.blankState(TABLEAU.concat(CELLS, FOUNDATION)); }; + + // Four cards in the first four cells, then six to a column. + function newState(order) { + var s = blank(), k = 0, j; + for (j = 0; j < START_CELLS; j++) s.piles[CELLS[j]].push(K.card(order[k++], true)); + TABLEAU.forEach(function (t) { for (j = 0; j < COLUMN_CARDS; j++) s.piles[t].push(K.card(order[k++], true)); }); + return s; + } + + var place = K.layout({ + topRows: 2, + items: FOUNDATION.map(function (f, n) { return { pile: f, kind: 'foundation', col: FOUNDATION_COL + n, row: 0 }; }) + .concat(CELLS.map(function (c, n) { return { pile: c, kind: 'cell', col: n, row: 1, n: n + 1 }; })) + .concat(TABLEAU.map(function (t, n) { return { pile: t, kind: 'column', col: n, row: 2, n: n + 1 }; })) + }); + + var api = Object.assign(R, { newState: newState, blankState: blank, place: place, almostWon: function () { return K.almostWon(R, blank); } }); + root.ZimiEightOff = api; + + function boot() { + K.page({ rules: R, id: 'eightoff', title: 'Eight Off', cols: COLS, place: place, + deal: function () { return newState(Z.shuffled(Z.random())); }, almostWon: api.almostWon }); + } + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/fortythieves.html b/zimi/builtin/games/fortythieves.html new file mode 100644 index 000000000..152d83eb0 --- /dev/null +++ b/zimi/builtin/games/fortythieves.html @@ -0,0 +1,30 @@ + + + + + +Forty Thieves + + + + + +
+ ‹ +

Forty Thieves

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/fortythieves.js b/zimi/builtin/games/fortythieves.js new file mode 100644 index 000000000..0f95086d5 --- /dev/null +++ b/zimi/builtin/games/fortythieves.js @@ -0,0 +1,50 @@ +/* ZimiGames: Forty Thieves. Two decks. Ten columns of four cards face up, and a stock of sixty-four. Build down in one suit, + one card at a time, any card on an empty column. Eight foundations build up by suit from the ace. Turn the stock one card at + a time onto the waste; there is one pass and no second. Put all 104 cards on the foundations to win. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, K = root.ZimiSolKit; + + var TABLEAU = ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7', 't8', 't9']; + var FOUNDATION = ['f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7']; + var COLS = 10, DECKS = 2, COLUMN_CARDS = 4, FOUNDATION_COL = 2; + + var R = K.rules({ + tableau: TABLEAU, foundation: FOUNDATION, stock: 'stock', waste: 'waste', + runOK: function (list) { return list.length === 1; }, + builds: function (upper, lower) { return Z.suit(upper) === Z.suit(lower) && Z.rank(lower) === Z.rank(upper) - 1; }, + takeFoundation: false, + whyBuild: 'sol.why.suit', whyEmpty: 'sol.why.nowhere', whyPick: 'sol.why.single', + draw: function (state) { + var P = state.piles; + if (!P.stock.length) return null; + var s = Z.clone(state), c = s.piles.stock.pop(); + c.up = true; s.piles.waste.push(c); s.moves++; + return s; + } + }); + var blank = function () { return K.blankState(['stock', 'waste'].concat(TABLEAU, FOUNDATION)); }; + + function newState(order) { + var s = blank(), k = 0; + TABLEAU.forEach(function (t) { for (var j = 0; j < COLUMN_CARDS; j++) s.piles[t].push(K.card(order[k++], true)); }); + while (k < order.length) s.piles.stock.push(K.card(order[k++], false)); + return s; + } + + var place = K.layout({ + topRows: 1, + items: [{ pile: 'stock', kind: 'stock', col: 0, row: 0 }, { pile: 'waste', kind: 'waste', col: 1, row: 0 }] + .concat(FOUNDATION.map(function (f, n) { return { pile: f, kind: 'foundation', col: FOUNDATION_COL + n, row: 0 }; })) + .concat(TABLEAU.map(function (t, n) { return { pile: t, kind: 'column', col: n, row: 1, n: n + 1 }; })) + }); + + var api = Object.assign(R, { newState: newState, blankState: blank, place: place, drawStock: R.S.draw, almostWon: function () { return K.almostWon(R, blank); } }); + root.ZimiFortyThieves = api; + + function boot() { + K.page({ rules: R, id: 'fortythieves', title: 'Forty Thieves', cols: COLS, place: place, refuse: 'sol.why.stockEmpty', + deal: function () { return newState(K.shuffledDecks(DECKS, Z.random())); }, almostWon: api.almostWon }); + } + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/gofish.css b/zimi/builtin/games/gofish.css new file mode 100644 index 000000000..2d88c4aac --- /dev/null +++ b/zimi/builtin/games/gofish.css @@ -0,0 +1,6 @@ +/* Go Fish: the count of cards left in the stock, above the pile. */ +.gf-count { position: absolute; z-index: 30; transform: translateX(-50%); min-width: 28px; padding: 2px 10px; border-radius: 999px; background: rgba(0, 0, 0, 0.34); color: #fff; font-size: var(--fs-small); line-height: 1.5; text-align: center; font-variant-numeric: tabular-nums; pointer-events: none; } + +/* Red, generated by scripts/games_red.py from the rules above: do not edit. */ +:root.gs.night-red .gf-count { background: rgba(0, 0, 0, 0.34); color: #ff2010; } +/* end Red */ diff --git a/zimi/builtin/games/gofish.html b/zimi/builtin/games/gofish.html new file mode 100644 index 000000000..afc50d629 --- /dev/null +++ b/zimi/builtin/games/gofish.html @@ -0,0 +1,32 @@ + + + + + +Go Fish + + + + + + + +
+ ‹ +

Go Fish

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/gofish.js b/zimi/builtin/games/gofish.js new file mode 100644 index 000000000..5fa238233 --- /dev/null +++ b/zimi/builtin/games/gofish.js @@ -0,0 +1,284 @@ +/* ZimiGames: Go Fish, two to four players: you (south) against the computer players. Seven cards each (five with three or + four players). On your turn ask any player for a rank you hold: they hand over every card of it and you ask again. With + none, "go fish": you draw the top of the stock, and if it is the rank you asked for you ask again, else the turn passes. + Four of a rank is a book and is laid down. A hand that runs out draws five more at once. The game ends when all thirteen books + are made or no one else has cards to ask for; the most books wins. + + State: players, hands[n], stock, books[n] (the ranks each has laid down), known[n] (ranks others have seen that seat ask for, + so it must hold them: what the computer remembers), turn, phase ('play' | 'over'), last (the latest ask and what came of it), + result, moves. Pure functions; the page wiring only runs in a browser. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, T = root.ZimiTable, Seats = root.ZimiSeats, TX = root.ZimiCards.T; + + var BOOK = 4, RANKS = 13, REFILL = 5, DEAL_TWO = 7, DEAL_MORE = 5, PLAYERS_KEY = 'gofish.players', DEFAULT_PLAYERS = 2; + var rankOf = function (id) { return Z.rank(id); }; + var dealSize = function (players) { return players === 2 ? DEAL_TWO : DEAL_MORE; }; + var SUIT_ORDER = [0, 1, 3, 2]; + // A hand grouped by rank, suits in the table's usual order within a rank. + function sorted(ids) { return ids.slice().sort(function (a, b) { return rankOf(a) - rankOf(b) || SUIT_ORDER.indexOf(Z.suit(a)) - SUIT_ORDER.indexOf(Z.suit(b)); }); } + var count = function (hand, rank) { return hand.filter(function (c) { return rankOf(c) === rank; }).length; }; + var ranksIn = function (hand) { return sorted(hand).map(rankOf).filter(function (r, i, a) { return a.indexOf(r) === i; }); }; + var bookTotal = function (st) { return st.books.reduce(function (n, b) { return n + b.length; }, 0); }; + + // ── Rules ─────────────────────────────────────────────────────────────── + // The order is a shuffled 52. The books a deal happens to make are laid down at once. + function deal(order, players, first) { + var n = dealSize(players), hands = [], s; + for (s = 0; s < players; s++) hands.push(sorted(order.slice(s * n, (s + 1) * n))); + var st = { players: players, hands: hands, stock: order.slice(players * n), books: hands.map(function () { return []; }), known: hands.map(function () { return []; }), + turn: first || 0, phase: 'play', last: null, result: null, moves: 0 }; + settle(st); + return st; + } + // Every complete book in every hand goes down. + function layBooks(s) { + var laid = []; + s.hands.forEach(function (hand, seat) { + ranksIn(hand).forEach(function (r) { + if (count(hand, r) !== BOOK) return; + s.hands[seat] = s.hands[seat].filter(function (c) { return rankOf(c) !== r; }); + s.books[seat].push(r); laid.push({ seat: seat, rank: r }); + s.known.forEach(function (k) { var i = k.indexOf(r); if (i >= 0) k.splice(i, 1); }); + hand = s.hands[seat]; + }); + }); + return laid; + } + var holders = function (s) { return s.hands.filter(function (h) { return h.length; }).length; }; + // After a move: books down, every hand that has run dry draws five (while the stock lasts), a turn that falls to a player with no + // cards is passed on, and the end is called. `s` is a copy. + function settle(s) { + var laid = [], guard = 0, i, again; + while (guard++ < 60) { + laid = laid.concat(layBooks(s)); + if (bookTotal(s) === RANKS) break; + again = false; + for (i = 0; i < s.players; i++) { + var seat = (s.turn + i) % s.players; + if (s.hands[seat].length || !s.stock.length) continue; + s.hands[seat] = sorted(s.hands[seat].concat(s.stock.splice(Math.max(0, s.stock.length - REFILL), REFILL))); + again = true; + } + if (again) continue; + if (s.stock.length === 0 && holders(s) <= 1) break; // no one left to ask + if (s.hands[s.turn].length) break; + for (i = 1; i <= s.players; i++) if (s.hands[(s.turn + i) % s.players].length) { s.turn = (s.turn + i) % s.players; break; } + } + if (bookTotal(s) === RANKS || (s.stock.length === 0 && holders(s) <= 1)) { s.phase = 'over'; s.result = outcome(s); } + return laid; + } + // Most books wins; the seats tied at the top share it. + function outcome(s) { + var most = Math.max.apply(null, s.books.map(function (b) { return b.length; })); + return { most: most, winners: s.books.map(function (b, i) { return b.length === most ? i : -1; }).filter(function (i) { return i >= 0; }) }; + } + var targets = function (st, seat) { return st.hands.map(function (h, i) { return i; }).filter(function (i) { return i !== seat && st.hands[i].length; }); }; + function canAsk(st, seat, target, rank) { + return st.phase === 'play' && st.turn === seat && target !== seat && target >= 0 && target < st.players && st.hands[target].length > 0 && count(st.hands[seat], rank) > 0; + } + // `seat` asks `target` for `rank`. Their cards of it come over (and the asker asks again); else the asker draws and asks again + // only if the drawn card is the one named. + function ask(st, seat, target, rank) { + var s = Z.clone(st), last = { seat: seat, target: target, rank: rank, got: 0, fished: false, lucky: false, empty: false, books: [] }; + var give = s.hands[target].filter(function (c) { return rankOf(c) === rank; }); + if (give.length) { + s.hands[target] = s.hands[target].filter(function (c) { return rankOf(c) !== rank; }); + s.hands[seat] = sorted(s.hands[seat].concat(give)); + last.got = give.length; + var ki = s.known[target].indexOf(rank); if (ki >= 0) s.known[target].splice(ki, 1); + } else if (s.stock.length) { + var drawn = s.stock.pop(); + s.hands[seat] = sorted(s.hands[seat].concat([drawn])); + last.fished = true; last.lucky = rankOf(drawn) === rank; + if (!last.lucky) s.turn = (seat + 1) % s.players; + } else { last.empty = true; s.turn = (seat + 1) % s.players; } + if (s.known[seat].indexOf(rank) < 0) s.known[seat].push(rank); + last.books = layBooks(s); + s.last = last; s.moves++; + last.books = last.books.concat(settle(s)); + return s; + } + + // ── The computer players ──────────────────────────────────────────────── + // {target, rank}: a rank another player is known to hold if I hold it too; else the rank I have most of, from the player with + // the most cards. A little noise keeps it from asking the same thing every game. + function aiAsk(st, seat, rng) { + rng = rng || Math.random; + var hand = st.hands[seat], best = null, bestScore = -1; + targets(st, seat).forEach(function (t) { + ranksIn(hand).forEach(function (r) { + var score = count(hand, r) * 6 + st.hands[t].length * 0.5 + rng() * 2; + if (st.known[t].indexOf(r) >= 0) score += 40; + if (score > bestScore) { bestScore = score; best = { target: t, rank: r }; } + }); + }); + return best; + } + + // ── Layout ────────────────────────────────────────────────────────────── + var BOOK_STEP = 0.42, SHOW_STOCK = 2, COUNT_RISE = 26; + function geo(m, st) { return T.geometry(m, T.rowsFor(m, st.hands[0].length)); } + function piles(g) { + var y = Math.round(g.cy - g.ch / 2); + return { stock: { x: Math.round(g.cx - g.cw * 1.45), y: y }, books: { x: Math.round(g.cx - g.cw * 0.05), y: y } }; + } + function place(st, m, view) { + var g = geo(m, st), p = piles(g), slots = [], cards = [], V = (view && view.viewer) || 0, up = !(view && view.hideHand); + var pend = view && view.pending !== undefined && view.pending !== null ? view.pending : null; + slots.push({ id: 'stock', x: p.stock.x, y: p.stock.y, w: g.cw, h: g.ch, label: TX('gin.stock', { cards: Z.plural(st.stock.length, 'card') }) }); + var hand = T.handCards(g, st.hands[V], function (id) { return { up: up, raise: up && pend !== null && rankOf(id) === pend, mark: up && pend !== null && rankOf(id) === pend }; }, + function (a, b) { return rankOf(a) !== rankOf(b); }); + slots = slots.concat(hand.slots); cards = cards.concat(hand.cards); + for (var r = 1; r < st.players; r++) cards = cards.concat(T.fan(g, T.SEAT_POS[st.players][r], st.hands[(V + r) % st.players], false)); + st.stock.forEach(function (id, k) { cards.push({ id: id, pile: 'stock', idx: k, x: p.stock.x, y: p.stock.y, up: false, hidden: k < st.stock.length - SHOW_STOCK }); }); + // Your books, face up and overlapping: the ace of clubs stands for a book of aces, and so on. + var step = Math.min(g.cw * BOOK_STEP, (g.W - g.pad - p.books.x - g.cw) / Math.max(1, st.books[V].length - 1)); + st.books[V].forEach(function (rank, k) { + cards.push({ id: Z.make(rank, 0), pile: 'book', idx: k, x: Math.round(p.books.x + k * step), y: p.books.y, up: true }); + }); + return { height: m.H, slots: slots, cards: cards }; + } + + var api = { + BOOK: BOOK, REFILL: REFILL, dealSize: dealSize, newGame: deal, canAsk: canAsk, ask: ask, aiAsk: aiAsk, targets: targets, outcome: outcome, count: count, ranksIn: ranksIn, + bookTotal: bookTotal, geo: geo, place: place + }; + root.ZimiGoFish = api; + + // ── The page ──────────────────────────────────────────────────────────── + var AI_MS = 900, THEN_MS = 700; + function boot() { + var t, board, session, view = { flash: '', pending: null, viewer: 0 }, players = DEFAULT_PLAYERS, seats = {}; + function buildSeats(n) { + var cur = Seats.create({ id: 'gofish', seats: n, onChange: function () { if (t) t.paint(); if (board) board.refresh(); } }); + Object.keys(cur).forEach(function (k) { seats[k] = cur[k]; }); + } + buildSeats(players); + var count = Z.h('div', { class: 'gf-count' }); + Z.pageEls().table.appendChild(count); + var name = function (seat) { return seats.name(seat); }; + function syncView(st) { view.viewer = seats.view(); view.hideHand = seats.hotseat() && st.turn !== view.viewer; } + function repaint() { board.refresh(); t.paint(); } + var rankWord = function (r) { return TX('cards.rank.' + r); }; + var cardsOf = function (n) { return Z.plural(n, 'card'); }; + + // What the last ask came to, as the status line says it: the ask, what came of it, and any book it finished. + function said(st) { + var l = st.last; + if (!l) return ''; + var me = seats.view(), you = seats.isYou(l.seat), asked = l.target === me && !seats.hotseat(); + var ask = TX(you ? 'gofish.ask.you' : asked ? 'gofish.ask.ofYou' : 'gofish.ask', { name: name(l.seat), target: name(l.target), rank: rankWord(l.rank) }); + var result = l.got ? TX('gofish.handed', { cards: cardsOf(l.got) }) : l.empty ? TX('gofish.none') : TX(l.lucky ? 'gofish.lucky' : 'gofish.fish'); + var out = you && !seats.hotseat() ? result : TX('cards.then', { first: ask, then: result }); + l.books.forEach(function (b) { out = TX('cards.then', { first: out, then: TX(seats.isYou(b.seat) ? 'gofish.book.you' : 'gofish.book', { name: name(b.seat), rank: rankWord(b.rank) }) }); }); + return out; + } + // The stock's count sits above the pile, where the eye is when it is time to fish. + function paintCount(st) { + var m = board.metrics(); + if (!m) return; + var g = geo(m, st), p = piles(g); + count.style.left = Math.round(p.stock.x + g.cw / 2) + 'px'; count.style.top = Math.round(p.stock.y - COUNT_RISE) + 'px'; + count.textContent = String(st.stock.length); + count.setAttribute('aria-label', TX('gin.stock', { cards: cardsOf(st.stock.length) })); + } + function hud(st) { + paintCount(st); + var chips = st.hands.map(function (h, seat) { return { name: name(seat), text: String(st.books[seat].length), turn: st.phase === 'play' && st.turn === seat }; }); + var out = { chips: chips, text: '' }; + var note = said(st), lead = function (text) { return note ? TX('cards.then', { first: note, then: text }) : text; }; + if (st.phase === 'over') { out.text = TX('shell.end.over'); out.label = TX('shell.menu.new'); out.action = newGame; return out; } + if (!seats.person(st.turn)) { out.text = lead(TX('cards.thinking', { name: name(st.turn) })); return out; } + if (st.turn !== seats.view()) { out.text = lead(TX('cards.turn.name', { name: name(st.turn) })); return out; } + if (view.pending !== null) { + out.text = TX('gofish.whom', { rank: rankWord(view.pending) }); + out.choices = targets(st, st.turn).map(function (tg) { return { label: name(tg), onclick: function () { askNow(tg); } }; }); + out.choices.push({ label: TX('shell.cancel'), onclick: function () { view.pending = null; repaint(); } }); + return out; + } + out.text = note ? lead(TX(seats.isYou(st.turn) ? 'cards.turn.you' : 'cards.turn.name', { name: name(st.turn) })) : TX(seats.isYou(st.turn) ? 'gofish.pick' : 'gofish.pick.name', { name: name(st.turn) }); + return out; + } + + function drive() { + var st = session.state; + if (st.phase === 'over') { gameOver(); return; } + if (!seats.person(st.turn)) session.later(aiTurn, AI_MS); + else seats.ensure(st.turn, repaint); + } + function aiTurn() { + var st = session.state; + if (st.phase !== 'play' || seats.person(st.turn)) return; + var mv = aiAsk(st, st.turn); + if (!mv) return; + session.follow(ask(st, st.turn, mv.target, mv.rank)); + drive(); + } + function gameOver() { + var st = session.state, r = st.result, me = seats.view(), hot = seats.hotseat(); + var mine = st.books[me].length, lines = [TX('gofish.final', { list: st.books.map(function (b, s) { return name(s) + ' ' + b.length; }).join(' · ') })]; + var iWon = r.winners.indexOf(me) >= 0, tied = r.winners.length > 1; + if (iWon && !tied && !hot) session.win(mine); + else if (tied) session.lose('draw', [TX('gofish.tied', { names: r.winners.map(name).join(' · ') })].concat(lines), mine); + else session.lose(hot ? { name: name(r.winners[0]) } : '', [TX('gofish.won', { name: name(r.winners[0]), books: Z.plural(r.most, 'book') })].concat(lines), mine); + } + function askNow(target) { + var st = session.state, rank = view.pending; + if (rank === null || !canAsk(st, seats.view(), target, rank)) return false; + view.pending = null; + session.commit(ask(st, seats.view(), target, rank)); + drive(); + return true; + } + function tapHand(id) { + var st = session.state, me = seats.view(); + if (st.phase !== 'play') return false; + if (st.turn !== me) { t.flash(TX('cards.wait.turn')); return false; } + var rank = rankOf(id), opp = targets(st, me); + if (!opp.length) return false; + if (opp.length === 1) { view.pending = rank; return askNow(opp[0]); } + view.pending = view.pending === rank ? null : rank; + repaint(); + return true; + } + function tapOpponent(pile) { + var st = session.state, me = seats.view(), pos = parseInt(pile.slice(1), 10), seat = -1, r; + for (r = 1; r < st.players; r++) if (T.SEAT_POS[st.players][r] === pos) seat = (me + r) % st.players; + if (seat < 0 || st.phase !== 'play' || st.turn !== me) return false; + if (view.pending === null) { t.flash(TX('gofish.pickFirst')); return false; } + return askNow(seat); + } + function tap(pile) { + if (pile.charAt(0) === 'h') { var id = parseInt(pile.slice(1), 10); return isNaN(id) ? false : tapHand(id); } + if (/^p\d$/.test(pile)) return tapOpponent(pile); + return false; + } + function newGame() { + players = Z.store.get(PLAYERS_KEY, DEFAULT_PLAYERS); + if (players !== 2 && players !== 3 && players !== 4) players = DEFAULT_PLAYERS; + buildSeats(players); + view.flash = ''; view.pending = null; + session.reset(deal(Z.shuffled(Math.random), players, Math.floor(Math.random() * players))); + seats.begin(function () { repaint(); drive(); }, session.state.turn); + } + t = T.create({ + id: 'gofish', name: 'Go Fish', seats: seats, view: view, geo: geo, place: function (st, m, v) { syncView(st); return place(st, m, v); }, hud: hud, newGame: newGame, tap: tap, + slotTap: function (pile) { if (pile === 'stock') t.flash(TX('gofish.stockTap')); }, + canPick: function () { return false; }, + stat: function (sec, st) { return Z.fmtTime(sec) + ' · ' + st.books[seats.view()].length; }, + cascadeOrder: function (st) { return st.books[seats.view()].map(function (r) { return { id: Z.make(r, 0) }; }); }, + winLines: function (sec, st) { return [TX('gofish.final', { list: st.books.map(function (b, s) { return name(s) + ' ' + b.length; }).join(' · ') })]; }, + menuExtra: function () { + return [T.choiceRow(TX('cards.seatsAtTable'), PLAYERS_KEY, [{ value: 2, label: '2' }, { value: 3, label: '3' }, { value: 4, label: '4' }], DEFAULT_PLAYERS, function () {}), + Z.h('p', { class: 'zc-note', text: TX('ce.seatsNote') })]; + }, + rules: TX('gofish.rules') + }); + board = t.board; session = t.session; + api.session = session; api.board = board; + newGame(); + } + + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/montecarlo.html b/zimi/builtin/games/montecarlo.html new file mode 100644 index 000000000..2833f243a --- /dev/null +++ b/zimi/builtin/games/montecarlo.html @@ -0,0 +1,30 @@ + + + + + +Monte Carlo + + + + + +
+ ‹ +

Monte Carlo

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/montecarlo.js b/zimi/builtin/games/montecarlo.js new file mode 100644 index 000000000..a4dfb07d6 --- /dev/null +++ b/zimi/builtin/games/montecarlo.js @@ -0,0 +1,95 @@ +/* ZimiGames: Monte Carlo. Twenty-five cards lie face up in five rows of five. Two cards of the same rank that touch, side to + side or corner to corner, go out together. When you cannot, or will not, remove any more, tap the stock: the cards slide up + and left to close the gaps and the stock fills the empty places at the end. Clear all 52 to win. + State: piles g0..g24 (a place on the grid, 0 or 1 card), stock (the last card is dealt first), out, moves. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, K = root.ZimiSolKit, TX = root.ZimiCards.T; + + var SIDE = 5, CELLS = SIDE * SIDE, COLS = SIDE, HEIGHT_SHARE = 0.115; + var GRID = []; + for (var i = 0; i < CELLS; i++) GRID.push('g' + i); + var at = function (name) { return parseInt(name.slice(1), 10); }; + + var touching = function (a, b) { var i = at(a), j = at(b); return a !== b && Math.abs(Math.floor(i / SIDE) - Math.floor(j / SIDE)) <= 1 && Math.abs(i % SIDE - j % SIDE) <= 1; }; + var rankOf = function (state, name) { return Z.rank(state.piles[name][0].id); }; + var filled = function (state, name) { return state.piles[name].length > 0; }; + + function canPick(state, pile, idx) { return GRID.indexOf(pile) >= 0 && idx === 0 && filled(state, pile); } + function legalMove(state, from, idx, to) { + return canPick(state, from, idx) && GRID.indexOf(to) >= 0 && filled(state, to) && touching(from, to) && rankOf(state, from) === rankOf(state, to); + } + function applyMove(state, from, idx, to) { + var s = Z.clone(state); + s.piles.out = s.piles.out.concat(s.piles[from], s.piles[to]); + s.piles[from] = []; s.piles[to] = []; + s.moves++; + return s; + } + // The pairs for a card: every touching card of its rank. + function partners(state, name) { return GRID.filter(function (g) { return legalMove(state, name, 0, g); }); } + function bestMove(state, from, idx) { return canPick(state, from, idx) ? partners(state, from)[0] || null : null; } + + // Close the gaps (cards keep their order, up and to the left), then deal the stock into the empty places. + function fill(state) { + var s = Z.clone(state), cards = []; + GRID.forEach(function (g) { if (s.piles[g].length) cards.push(s.piles[g][0]); s.piles[g] = []; }); + while (cards.length < CELLS && s.piles.stock.length) { var c = s.piles.stock.pop(); c.up = true; cards.push(c); } + cards.forEach(function (c, n) { s.piles[GRID[n]] = [c]; }); + s.moves++; + return s; + } + // The stock slides the cards up only when that changes something: a gap to close, or cards to deal. + function draw(state) { + var next = fill(state); + return GRID.some(function (g) { return JSON.stringify(next.piles[g]) !== JSON.stringify(state.piles[g]); }) || next.piles.stock.length !== state.piles.stock.length ? next : null; + } + function pairs(state) { return GRID.some(function (g) { return filled(state, g) && partners(state, g).length; }); } + function hasMove(state) { return pairs(state) || !!draw(state); } + function isWon(state) { return !state.piles.stock.length && GRID.every(function (g) { return !filled(state, g); }); } + function why(state, pile, idx, to) { + if (!canPick(state, pile, idx)) return null; + return TX(to === undefined || !filled(state, to) ? 'montecarlo.why.pair' : 'montecarlo.why.touch'); + } + + function blankState() { return K.blankState(['stock', 'out'].concat(GRID)); } + function newState(order) { + var s = blankState(); + order.forEach(function (id, n) { if (n < CELLS) s.piles[GRID[n]].push(K.card(id, true)); else s.piles.stock.unshift(K.card(id, false)); }); + return s; + } + + function place(state, m) { + var P = state.piles, rows = Z.solitaireRows(m), cards = [], slots = [], lineH = Math.round(m.ch * 1.08), x = function (c) { return m.left + c * m.step; }; + var y = function (r) { return rows.top + r * lineH; }, gridTop = y(1); + P.stock.forEach(function (c, i) { cards.push({ id: c.id, pile: 'stock', idx: i, x: x(0), y: y(0), up: false, hidden: i < P.stock.length - 2 }); }); + slots.push({ id: 'stock', x: x(0), y: y(0), w: m.cw, h: m.ch, mark: P.stock.length ? '' : '↻', label: Z.describePile(TX('sol.stock'), Z.idsOf(P.stock), false) + TX('montecarlo.enter') }); + P.out.forEach(function (c, i) { cards.push({ id: c.id, pile: 'out', idx: i, x: x(SIDE - 1), y: y(0), up: true, hidden: i < P.out.length - 2 }); }); + slots.push({ id: 'out', x: x(SIDE - 1), y: y(0), w: m.cw, h: m.ch, goal: true, mark: '', label: TX('montecarlo.out', { cards: Z.plural(P.out.length, 'card') }) }); + GRID.forEach(function (g, n) { + var px = x(n % SIDE), py = gridTop + Math.floor(n / SIDE) * lineH; + P[g].forEach(function (c, i) { cards.push({ id: c.id, pile: g, idx: i, x: px, y: py, up: true }); }); + slots.push({ id: g, x: px, y: py, w: m.cw, h: m.ch, label: P[g].length ? Z.cardName(P[g][0].id) : TX('montecarlo.empty', { n: n + 1 }) }); + }); + return { height: Math.max(gridTop + SIDE * lineH + m.pad, m.H), slots: slots, cards: cards }; + } + + function cascade(st) { return st.piles.out.slice(-Z.KING).map(function (c) { return { id: c.id }; }); } + // One move from a win: two kings touching, everything else already out. + function almostWon() { + var s = blankState(), id, a = Z.make(Z.KING, 0), b = Z.make(Z.KING, 1); + for (id = 0; id < Z.DECK; id++) if (id !== a && id !== b) s.piles.out.push(K.card(id, true)); + s.piles.g0.push(K.card(a, true)); s.piles.g1.push(K.card(b, true)); + return s; + } + + var api = { GRID: GRID, newState: newState, blankState: blankState, canPick: canPick, legalMove: legalMove, applyMove: applyMove, bestMove: bestMove, + drawStock: draw, fill: fill, hasMove: hasMove, isWon: isWon, why: why, place: place, almostWon: almostWon, partners: partners, S: { foundation: [], draw: draw } }; + root.ZimiMonteCarlo = api; + + function boot() { + K.page({ rules: api, id: 'montecarlo', title: 'Monte Carlo', cols: COLS, place: place, cascade: cascade, refuse: 'montecarlo.why.fill', heightShare: HEIGHT_SHARE, + deal: function () { return newState(Z.shuffled(Z.random())); }, almostWon: almostWon }); + } + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/ohhell.html b/zimi/builtin/games/ohhell.html new file mode 100644 index 000000000..4a04d2cbf --- /dev/null +++ b/zimi/builtin/games/ohhell.html @@ -0,0 +1,31 @@ + + + + + +Oh Hell + + + + + + +
+ ‹ +

Oh Hell

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/ohhell.js b/zimi/builtin/games/ohhell.js new file mode 100644 index 000000000..3b8343e71 --- /dev/null +++ b/zimi/builtin/games/ohhell.js @@ -0,0 +1,265 @@ +/* ZimiGames: Oh Hell, three to five players: you (south) against the computer players. Each hand deals the same number of cards to + everyone (five down to one and back up, or seven down to one and back up) and turns one more card for trump. Everyone bids how many + tricks they will take, the dealer last, and the dealer may not bid what makes the bids add up to the number of tricks, so someone + always misses. You must follow the suit led if you can; the highest trump wins the trick, else the highest card of the suit led. + A hand scores one point for each trick taken, and ten more for taking exactly as many as you bid. The most points after the last hand wins. + + State: players, sizes (cards per hand, hand by hand), handNo, hands[n], bids[n] (null until bid), tricks[n], trump, trumpCard, dealer, + turn, leader, trick [{seat, id}], played (ids of finished tricks), scores[n], phase ('bid' | 'play' | 'handEnd' | 'over'), result. + Seats run clockwise from you. Pure functions; the page wiring only runs in a browser. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, T = root.ZimiTable, Seats = root.ZimiSeats, TX = root.ZimiCards.T; + + var LADDERS = { short: [5, 4, 3, 2, 1, 2, 3, 4, 5], full: [7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7] }; + var EXACT_BONUS = 10, LADDER_KEY = 'ohhell.length', DEFAULT_LADDER = 'short', PLAYERS_KEY = 'ohhell.players', DEFAULT_PLAYERS = 3, TABLE_SIZES = [3, 4, 5]; + var validSize = function (n) { return TABLE_SIZES.indexOf(n) >= 0; }; + var high = T.rankHigh; + + // ── Rules ─────────────────────────────────────────────────────────────── + // `order` is a shuffled 52. Cards go round the table, then one more is turned for trump. + function dealHand(order, players, sizes, handNo, scores, dealer) { + var size = sizes[handNo], hands = [], s, tc = order[players * size]; + for (s = 0; s < players; s++) hands.push(T.sortHand(order.slice(s * size, (s + 1) * size), high)); + return { + players: players, sizes: sizes, handNo: handNo, hands: hands, bids: hands.map(function () { return null; }), tricks: hands.map(function () { return 0; }), + trump: Z.suit(tc), trumpCard: tc, dealer: dealer, turn: (dealer + 1) % players, leader: (dealer + 1) % players, trick: [], played: [], + scores: scores.slice(), phase: 'bid', result: null, moves: 0 + }; + } + function startGame(order, players, ladder, dealer) { + var sizes = LADDERS[ladder] || LADDERS[DEFAULT_LADDER]; + return dealHand(order, players, sizes, 0, new Array(players).fill(0), dealer === undefined ? players - 1 : dealer); + } + function nextHand(st, order) { return dealHand(order, st.players, st.sizes, st.handNo + 1, st.scores, (st.dealer + 1) % st.players); } + + var size = function (st) { return st.sizes[st.handNo]; }; + var bidTotal = function (st) { return st.bids.reduce(function (n, b) { return n + (b === null ? 0 : b); }, 0); }; + // The bid the dealer may not make (the one that makes the bids add up to the tricks), else -1. + function forbiddenBid(st, seat) { + if (seat !== st.dealer) return -1; + var f = size(st) - bidTotal(st); + return f >= 0 && f <= size(st) ? f : -1; + } + function canBid(st, seat, n) { return st.phase === 'bid' && st.turn === seat && n >= 0 && n <= size(st) && n !== forbiddenBid(st, seat); } + function placeBid(st, seat, n) { + var s = Z.clone(st); + s.bids[seat] = n; s.moves++; + if (s.bids.every(function (b) { return b !== null; })) { s.phase = 'play'; s.turn = s.leader = (s.dealer + 1) % s.players; } else s.turn = (seat + 1) % s.players; + return s; + } + + function legalPlays(st, seat) { + var hand = st.hands[seat]; + if (!st.trick.length) return hand.slice(); + var lead = Z.suit(st.trick[0].id), follow = hand.filter(function (c) { return Z.suit(c) === lead; }); + return follow.length ? follow : hand.slice(); + } + function whyNot(st) { return TX('cards.follow', { suit: TX('cards.suit.' + Z.SUITS[Z.suit(st.trick[0].id)]) }); } + function isLegal(st, seat, id) { return st.phase === 'play' && st.trick.length < st.players && st.turn === seat && legalPlays(st, seat).indexOf(id) >= 0; } + function playCard(st, seat, id) { + var s = Z.clone(st); + s.hands[seat].splice(s.hands[seat].indexOf(id), 1); + s.trick.push({ seat: seat, id: id }); s.moves++; + if (s.trick.length < s.players) s.turn = (seat + 1) % s.players; + return s; + } + // Does `a` beat `b` in a trick led in `lead`, with `trump`? + function beats(a, b, lead, trump) { + var sa = Z.suit(a), sb = Z.suit(b); + if (sa === sb) return high(a) > high(b); + return sa === trump || (sb !== trump && sa === lead && sb !== lead); + } + function trickWinner(trick, trump) { + var lead = Z.suit(trick[0].id), best = trick[0]; + trick.forEach(function (t) { if (beats(t.id, best.id, lead, trump)) best = t; }); + return best.seat; + } + function resolveTrick(st) { + var s = Z.clone(st), w = trickWinner(s.trick, s.trump); + s.tricks[w]++; + s.played = s.played.concat(s.trick.map(function (t) { return t.id; })); + s.trick = []; s.leader = s.turn = w; + if (s.played.length === s.players * size(s)) endHand(s); + return s; + } + // A trick taken is a point; taking exactly what you bid is ten more. + function handPoints(bid, took) { return took + (bid === took ? EXACT_BONUS : 0); } + function endHand(s) { + var pts = s.tricks.map(function (took, seat) { return handPoints(s.bids[seat], took); }); + s.result = { points: pts, made: s.tricks.map(function (took, seat) { return took === s.bids[seat]; }) }; + s.scores = s.scores.map(function (v, seat) { return v + pts[seat]; }); + s.phase = s.handNo + 1 >= s.sizes.length ? 'over' : 'handEnd'; + } + // The seats with the most points: one, or the seats that tie. + function winners(scores) { + var most = Math.max.apply(null, scores); + return scores.map(function (v, i) { return v === most ? i : -1; }).filter(function (i) { return i >= 0; }); + } + + // ── The computer players ──────────────────────────────────────────────── + // About how many tricks a hand takes: high trumps, aces, long trump holdings, and a hand with no trump counts for little. + var TRUMP_VALUE = { 14: 0.95, 13: 0.8, 12: 0.6, 11: 0.45, 10: 0.35 }, SIDE_VALUE = { 14: 0.7, 13: 0.3 }; + function estimate(hand, trump, players) { + var est = 0, trumps = hand.filter(function (c) { return Z.suit(c) === trump; }).length; + hand.forEach(function (c) { + var r = high(c); + if (Z.suit(c) === trump) est += TRUMP_VALUE[r] !== undefined ? TRUMP_VALUE[r] : 0.18 + 0.02 * r / 14; + else est += (SIDE_VALUE[r] || 0) * (players <= 3 ? 1 : players === 4 ? 0.9 : 0.8); + }); + return est + Math.max(0, trumps - 3) * 0.15; + } + function aiBid(st, seat) { + var n = size(st), want = Math.max(0, Math.min(n, Math.round(estimate(st.hands[seat], st.trump, st.players)))), bad = forbiddenBid(st, seat); + if (want !== bad) return want; + // The dealer's forbidden bid: whichever neighbour is nearer the estimate. + var e = estimate(st.hands[seat], st.trump, st.players), up = want + 1 <= n ? want + 1 : -1, down = want - 1 >= 0 ? want - 1 : -1; + if (up < 0) return down; + if (down < 0) return up; + return e >= want ? up : down; + } + var strength = function (c, trump) { return (Z.suit(c) === trump ? 100 : 0) + high(c); }; + function aiPick(st, seat) { + var legal = legalPlays(st, seat), trump = st.trump, trick = st.trick; + if (legal.length === 1) return legal[0]; + var need = st.bids[seat] - st.tricks[seat], left = st.hands[seat].length; + var lowest = T.minBy(legal, function (c) { return strength(c, trump); }), highest = T.maxBy(legal, function (c) { return strength(c, trump); }); + var hunting = need > 0; // a missed bid still scores a point for each trick, so it hunts too when it cannot make it + if (!trick.length) { + if (hunting) return highest; + var offs = legal.filter(function (c) { return Z.suit(c) !== trump; }); + return T.minBy(offs.length ? offs : legal, function (c) { return high(c); }); + } + var lead = Z.suit(trick[0].id), winning = trick.reduce(function (b, t) { return beats(t.id, b.id, lead, trump) ? t : b; }, trick[0]); + var winners = legal.filter(function (c) { return beats(c, winning.id, lead, trump); }); + if (hunting || need > left) return winners.length ? T.minBy(winners, function (c) { return strength(c, trump); }) : lowest; + // Done with tricks: slip under the winner with the biggest card that does not win it, else give up the smallest winner. + var under = legal.filter(function (c) { return winners.indexOf(c) < 0; }); + return under.length ? T.maxBy(under, function (c) { return strength(c, trump); }) : T.minBy(winners, function (c) { return strength(c, trump); }); + } + + // ── Layout ────────────────────────────────────────────────────────────── + function geo(m, st) { return T.geometry(m, T.rowsFor(m, st.hands[0].length)); } + function place(st, m, view) { + var g = geo(m, st), slots = T.feltSlots(g), cards = [], L = T.looking(view), V = L.V, up = L.up, rel = function (seat) { return (seat - V + st.players) % st.players; }; + var full = st.trick.length === st.players, myTurn = st.phase === 'play' && st.turn === V && !full, sweep = view && full ? view.sweep : null; + var hand = T.handCards(g, st.hands[V], function (id) { return { up: up, dim: up && myTurn && !isLegal(st, V, id) }; }, function (a, b) { return Z.suit(a) !== Z.suit(b); }); + slots = slots.concat(hand.slots); cards = cards.concat(hand.cards); + for (var r = 1; r < st.players; r++) cards = cards.concat(T.fan(g, T.SEAT_POS[st.players][r], st.hands[(V + r) % st.players], false)); + return { height: m.H, slots: slots, cards: cards.concat(T.trickCards(g, st.trick, sweep, function (seat) { return T.SEAT_POS[st.players][rel(seat)]; }, view && view.win)) }; + } + + var api = { + LADDERS: LADDERS, EXACT_BONUS: EXACT_BONUS, dealHand: dealHand, newGame: startGame, nextHand: nextHand, forbiddenBid: forbiddenBid, canBid: canBid, placeBid: placeBid, + legalPlays: legalPlays, isLegal: isLegal, playCard: playCard, trickWinner: trickWinner, resolveTrick: resolveTrick, handPoints: handPoints, winners: winners, + estimate: estimate, aiBid: aiBid, aiPick: aiPick, geo: geo, place: place + }; + root.ZimiOhHell = api; + + // ── The page ──────────────────────────────────────────────────────────── + var AI_MS = 560, HOLD_MS = 1000, SWEEP_MS = 380; + // The seats at the table are made once, so a change to the number applies when the page is next opened: a kept game keeps its own. + function tableSize() { + var kept = root.ZimiShell && root.ZimiShell.saved ? root.ZimiShell.saved() : null; + if (kept && kept.id === 'ohhell' && kept.state && validSize(kept.state.players)) return kept.state.players; + var n = Z.store.get(PLAYERS_KEY, DEFAULT_PLAYERS); + return validSize(n) ? n : DEFAULT_PLAYERS; + } + function boot() { + var t, board, session, view = { sweep: null, flash: '' }, tg, seats, mine, SEATS = tableSize(); + var ladderName = function () { var v = Z.store.get(LADDER_KEY, DEFAULT_LADDER); return LADDERS[v] ? v : DEFAULT_LADDER; }; + var nm = function (seat) { return seats.name(seat); }; + function bidText(b) { return b === null || b === undefined ? '' : String(b); } + + function handSheet(st) { + var V = seats.view(), r = st.result, me = r.points[V]; + var rows = tg.order().map(function (seat) { + return { name: nm(seat), delta: r.points[seat], total: st.scores[seat], note: TX('ohhell.note', { bid: st.bids[seat], took: st.tricks[seat] }), lead: seat === V }; + }); + var head = TX(r.made[V] ? 'ohhell.made' : 'ohhell.missed', { points: Z.plural(me, 'point') }); + T.summarySheet({ title: TX('cards.fact.hand', { n: st.handNo + 1 }), headline: head, rows: rows, actions: [{ label: TX('cards.nextHand'), primary: true, onclick: tg.startNextHand }] }); + } + function finalLines(st) { return [TX('ohhell.final', { list: tg.order().map(function (seat) { return nm(seat) + ' ' + st.scores[seat]; }).join(' · ') })]; } + function hud(st) { + var full = st.trick.length === st.players, V = seats.view(); + var chips = tg.order().map(function (seat) { + var text = st.phase === 'bid' ? bidText(st.bids[seat]) : st.tricks[seat] + '/' + bidText(st.bids[seat]); + return { name: nm(seat), text: text, dealer: seat === st.dealer, turn: (st.phase === 'bid' || st.phase === 'play') && st.turn === seat && !full }; + }); + var out = { chips: chips, fact: TX('ohhell.fact', { n: st.handNo + 1, total: st.sizes.length }), text: '', trump: st.trump }; + if (st.phase === 'bid') { + if (seats.person(st.turn) && st.turn === V) { + var bad = forbiddenBid(st, V); + out.text = TX(seats.hotseat() ? 'ohhell.yourBid.name' : 'ohhell.yourBid', { name: nm(V) }); + if (bad >= 0) out.text = TX('cards.then', { first: out.text, then: TX('ohhell.notBid', { n: bad }) }); + out.choices = []; + for (var n = 0; n <= st.sizes[st.handNo]; n++) out.choices.push(bidChoice(n, n === bad)); + // On a short table (a phone on its side) the tray has no room for the hint line above the bids. + var m = board && board.metrics(); + if (!(m && m.H < T.SHORT_TABLE_H)) out.lines = [{ text: TX('ohhell.estimate', { n: Math.round(estimate(st.hands[V], st.trump, st.players)) }) }]; + } else out.text = TX('cards.bidding', { name: nm(st.turn) }); + } else if (st.phase === 'handEnd') { out.text = TX('cards.handEnd'); out.label = TX('cards.nextHand'); out.action = tg.startNextHand; } + else if (st.phase === 'over') { out.text = TX('shell.end.over'); out.label = TX('shell.menu.new'); out.action = newGame; } + else if (full) out.text = tg.trickText(trickWinner(st.trick, st.trump)); + else out.text = tg.turnText(st.turn); + return out; + } + function bidChoice(n, banned) { return { label: String(n), disabled: banned, onclick: function () { bid(n); } }; } + + function drive() { + var st = session.state; + if (st.phase === 'bid') { if (seats.person(st.turn)) seats.ensure(st.turn, tg.repaint); else session.later(aiBidTurn, AI_MS); return; } + tg.turn(st); + } + function aiBidTurn() { + var st = session.state; + if (st.phase !== 'bid' || seats.person(st.turn)) return; + session.follow(placeBid(st, st.turn, aiBid(st, st.turn))); + drive(); + } + function bid(n) { + var st = session.state; + if (!canBid(st, st.turn, n) || st.turn !== seats.view()) return; + session.commit(placeBid(st, st.turn, n)); + drive(); + } + function gameOver() { + var st = session.state, top = winners(st.scores), V = seats.view(), hot = seats.hotseat(), lines = finalLines(st); + if (hot) session.lose({ name: nm(top[0]) }, lines); + else if (top.length > 1 && top.indexOf(V) >= 0) session.lose('draw', lines, st.scores[V]); + else if (top[0] === V) session.win(st.scores[V]); else session.lose('', lines, st.scores[V]); + } + function deal() { tg.restart(startGame(Z.shuffled(Math.random), SEATS, ladderName(), Math.floor(Math.random() * SEATS))); } + // A new game at a different table size starts the page over, since the seats are made once. + function newGame() { + var want = Z.store.get(PLAYERS_KEY, DEFAULT_PLAYERS); + if (validSize(want) && want !== SEATS && root.ZimiShell && root.ZimiShell.forget) { root.ZimiShell.forget(); root.location.reload(); return; } + deal(); + } + + tg = T.trickGame({ + id: 'ohhell', n: SEATS, view: view, ms: { ai: AI_MS, hold: HOLD_MS, sweep: SWEEP_MS }, drive: drive, handEnd: 'handEnd', + seatOpts: { cpuNames: Array.apply(null, Array(SEATS)).map(function (x, i) { return Seats.cpuName(i); }) }, + winner: function (st) { return trickWinner(st.trick, st.trump); }, resolve: resolveTrick, nextHand: nextHand, handOver: function () { handSheet(session.state); }, gameOver: gameOver, + legal: isLegal, why: whyNot, play: playCard, aiPlay: aiPick + }); + seats = tg.seats; mine = tg.mine; + t = tg.create({ + name: 'Oh Hell', geo: geo, place: place, hud: hud, newGame: newGame, heightShare: 0.13, + stat: function (sec, st) { return Z.fmtTime(sec) + ' · ' + st.scores[seats.view()]; }, + cascadeOrder: function (st) { return st.played.map(function (id) { return { id: id }; }); }, + winLines: function (sec, st) { return finalLines(st); }, + menuExtra: function () { + return [T.choiceRow(TX('cards.seatsAtTable'), PLAYERS_KEY, TABLE_SIZES.map(function (n) { return { value: n, label: String(n) }; }), DEFAULT_PLAYERS, function () {}), + T.choiceRow(TX('ohhell.length'), LADDER_KEY, [{ value: 'short', label: TX('ohhell.short') }, { value: 'full', label: TX('ohhell.full') }], DEFAULT_LADDER, function () {}), + Z.h('p', { class: 'zc-note', text: TX('ce.seatsNote') })]; + }, + rules: TX('ohhell.rules') + }); + board = t.board; session = t.session; + api.session = session; api.board = board; + deal(); + } + + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/oldmaid.html b/zimi/builtin/games/oldmaid.html new file mode 100644 index 000000000..de6e45e8f --- /dev/null +++ b/zimi/builtin/games/oldmaid.html @@ -0,0 +1,31 @@ + + + + + +Old Maid + + + + + + +
+ ‹ +

Old Maid

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/oldmaid.js b/zimi/builtin/games/oldmaid.js new file mode 100644 index 000000000..063adc1de --- /dev/null +++ b/zimi/builtin/games/oldmaid.js @@ -0,0 +1,195 @@ +/* ZimiGames: Old Maid, two to four players: you (south) against the computer players. One queen is taken out, so one queen has + no partner: the Old Maid. Everyone lays down their pairs (two cards of one rank). Then, in turn, you take one card, unseen, + from the next player with cards; if it matches one of yours the pair goes down. A player with no cards is safe. The last + one holding the Old Maid loses. + + State: players, hands[n], pairs[n] (pairs laid down), out (seats in the order they went safe), turn (who takes next), phase + ('play' | 'over'), last (the latest take), result { loser, order }, moves. Pure functions; the page wiring only runs in a browser. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, T = root.ZimiTable, Seats = root.ZimiSeats, TX = root.ZimiCards.T; + + var PLAYERS_KEY = 'oldmaid.players', DEFAULT_PLAYERS = 2, QUEEN = 12, TAKEN_OUT = Z.make(QUEEN, 0); + var rankOf = function (id) { return Z.rank(id); }; + var SUIT_ORDER = [0, 1, 3, 2]; + function sorted(ids) { return ids.slice().sort(function (a, b) { return rankOf(a) - rankOf(b) || SUIT_ORDER.indexOf(Z.suit(a)) - SUIT_ORDER.indexOf(Z.suit(b)); }); } + + // ── Rules ─────────────────────────────────────────────────────────────── + // Pairs by rank leave a hand; a rank held three times keeps one. + function layPairs(hand) { + var byRank = {}, kept = [], pairs = 0; + sorted(hand).forEach(function (c) { + var r = rankOf(c); + if (byRank[r] !== undefined) { kept.splice(kept.indexOf(byRank[r]), 1); delete byRank[r]; pairs++; } else { byRank[r] = c; kept.push(c); } + }); + return { hand: kept, pairs: pairs }; + } + var holders = function (s) { return s.hands.filter(function (h) { return h.length; }).length; }; + // The next seat after `seat` that still holds cards, or -1. + function nextHolder(st, seat) { + for (var i = 1; i < st.players; i++) if (st.hands[(seat + i) % st.players].length) return (seat + i) % st.players; + return -1; + } + // The seat `turn` takes from. + var source = function (st) { return nextHolder(st, st.turn); }; + // A shuffled 52 (the queen of clubs is left out), dealt round the table, the first pairs laid down at once. + function deal(order, players, first) { + var cards = order.filter(function (c) { return c !== TAKEN_OUT; }), hands = [], pairs = [], s; + for (s = 0; s < players; s++) hands.push([]); + cards.forEach(function (c, i) { hands[i % players].push(c); }); + hands = hands.map(function (h, i) { var r = layPairs(h); pairs[i] = r.pairs; return r.hand; }); + var st = { players: players, hands: hands, pairs: pairs, out: [], turn: first || 0, phase: 'play', last: null, result: null, moves: 0 }; + settle(st); + return st; + } + // Anyone left with no cards is safe; one holder left is the loser; the turn moves off a safe seat. + function settle(s) { + s.hands.forEach(function (h, seat) { if (!h.length && s.out.indexOf(seat) < 0) s.out.push(seat); }); + if (holders(s) <= 1) { + var loser = s.hands.findIndex(function (h) { return h.length; }); + s.phase = 'over'; s.result = { loser: loser, order: s.out.slice() }; + return; + } + if (!s.hands[s.turn].length) s.turn = nextHolder(s, s.turn); + } + function canTake(st, seat, idx) { + var from = source(st); + return st.phase === 'play' && st.turn === seat && from >= 0 && idx >= 0 && idx < st.hands[from].length; + } + // `seat` takes the card at `idx` of the next holder's hand; a match goes down with its partner. + function take(st, seat, idx) { + var s = Z.clone(st), from = source(s), card = s.hands[from].splice(idx, 1)[0], last = { seat: seat, from: from, card: card, paired: false }; + var mate = s.hands[seat].filter(function (c) { return rankOf(c) === rankOf(card); })[0]; + if (mate !== undefined) { s.hands[seat].splice(s.hands[seat].indexOf(mate), 1); s.pairs[seat]++; last.paired = true; last.rank = rankOf(card); } else s.hands[seat] = sorted(s.hands[seat].concat([card])); + s.last = last; s.moves++; + // The next to take is the next holder after the taker (who may have just gone safe). + s.turn = seat; + settle(s); + if (s.phase === 'play') s.turn = nextHolder(s, seat); + return s; + } + // The computer takes a card at random: it cannot see them, and it shuffles its own hand so a take tells nothing. + function aiTake(st, seat, rng) { + var from = source(st); + return from < 0 ? -1 : Math.floor((rng || Math.random)() * st.hands[from].length); + } + + // ── Layout ────────────────────────────────────────────────────────────── + function geo(m, st) { return T.geometry(m, T.rowsFor(m, st.hands[0].length)); } + function place(st, m, view) { + var g = geo(m, st), slots = [], cards = [], V = (view && view.viewer) || 0, up = !(view && view.hideHand), r; + var hand = T.handCards(g, st.hands[V], function () { return { up: up }; }, function (a, b) { return rankOf(a) !== rankOf(b); }); + slots = slots.concat(hand.slots); cards = cards.concat(hand.cards); + for (r = 1; r < st.players; r++) { + var seat = (V + r) % st.players, pos = T.SEAT_POS[st.players][r], fanned = T.fan(g, pos, st.hands[seat], false); + cards = cards.concat(fanned); + // One slot over each opponent's fan, named for the take, so the keyboard and a screen reader can draw (no card is named). + if (fanned.length && view && view.takeLabel) { + var x0 = Math.min.apply(null, fanned.map(function (c) { return c.x; })), y0 = Math.min.apply(null, fanned.map(function (c) { return c.y; })); + var x1 = Math.max.apply(null, fanned.map(function (c) { return c.x; })) + g.cw, y1 = Math.max.apply(null, fanned.map(function (c) { return c.y; })) + g.ch; + slots.push({ id: 'p' + pos, x: x0, y: y0, w: x1 - x0, h: y1 - y0, label: view.takeLabel(seat) }); + } + } + return { height: m.H, slots: slots, cards: cards }; + } + + var api = { + TAKEN_OUT: TAKEN_OUT, layPairs: layPairs, deal: deal, nextHolder: nextHolder, source: source, canTake: canTake, take: take, aiTake: aiTake, geo: geo, place: place + }; + root.ZimiOldMaid = api; + + // ── The page ──────────────────────────────────────────────────────────── + var AI_MS = 900; + function boot() { + var t, board, session, view = { flash: '', viewer: 0 }, players = DEFAULT_PLAYERS, seats = {}; + function buildSeats(n) { + var cur = Seats.create({ id: 'oldmaid', seats: n, onChange: function () { if (t) t.paint(); if (board) board.refresh(); } }); + Object.keys(cur).forEach(function (k) { seats[k] = cur[k]; }); + } + buildSeats(players); + var name = function (seat) { return seats.name(seat); }; + view.takeLabel = function (seat) { return TX('oldmaid.take', { from: name(seat) }); }; + function syncView(st) { view.viewer = seats.view(); view.hideHand = seats.hotseat() && st.turn !== view.viewer; } + function repaint() { board.refresh(); t.paint(); } + var rankWord = function (r) { return TX('cards.rank.' + r); }; + + // What the last take was: you see the card when you took it or it was taken from you, and a pair says its rank. + function said(st) { + var l = st.last; + if (!l) return ''; + var me = seats.view(), hot = seats.hotseat(), out; + if (!hot && l.seat === me) out = TX('oldmaid.took.you', { card: Z.cardName(l.card), from: name(l.from) }); + else if (!hot && l.from === me) out = TX('oldmaid.took.ofYou', { name: name(l.seat), card: Z.cardName(l.card) }); + else out = TX('oldmaid.took', { name: name(l.seat), from: name(l.from) }); + return l.paired ? TX('cards.then', { first: out, then: TX('oldmaid.pair', { rank: rankWord(l.rank) }) }) : out; + } + function hud(st) { + var chips = st.hands.map(function (h, seat) { return { name: name(seat), text: st.out.indexOf(seat) >= 0 ? TX('oldmaid.safe') : String(h.length), turn: st.phase === 'play' && st.turn === seat }; }); + var out = { chips: chips, text: '' }, note = said(st), lead = function (text) { return note ? TX('cards.then', { first: note, then: text }) : text; }; + if (st.phase === 'over') { out.text = TX('shell.end.over'); out.label = TX('shell.menu.new'); out.action = newGame; return out; } + if (!seats.person(st.turn)) { out.text = lead(TX('cards.thinking', { name: name(st.turn) })); return out; } + if (st.turn !== seats.view()) { out.text = lead(TX('cards.turn.name', { name: name(st.turn) })); return out; } + out.text = lead(TX('oldmaid.take', { from: name(source(st)) })); + return out; + } + + function drive() { + var st = session.state; + if (st.phase === 'over') { gameOver(); return; } + if (!seats.person(st.turn)) session.later(aiTurn, AI_MS); else seats.ensure(st.turn, repaint); + } + function aiTurn() { + var st = session.state; + if (st.phase !== 'play' || seats.person(st.turn)) return; + session.follow(take(st, st.turn, aiTake(st, st.turn))); + drive(); + } + function gameOver() { + var st = session.state, r = st.result, hot = seats.hotseat(); + var line = TX(seats.isYou(r.loser) ? 'oldmaid.stuck.you' : 'oldmaid.stuck', { name: name(r.loser), card: Z.cardName(st.hands[r.loser][0]) }); + if (hot) session.lose({ name: name(r.order[0]) }, [line], undefined); + else if (seats.isYou(r.loser)) session.lose('', [line], undefined); else session.win(); + } + function takeAt(pile, idx) { + var st = session.state, me = seats.view(); + if (st.phase !== 'play') return false; + if (st.turn !== me) { t.flash(TX('cards.wait.turn')); return false; } + var pos = parseInt(pile.slice(1), 10), seat = -1, r; + for (r = 1; r < st.players; r++) if (T.SEAT_POS[st.players][r] === pos) seat = (me + r) % st.players; + if (seat !== source(st)) { t.flash(TX('oldmaid.fromThem', { from: name(source(st)) })); return false; } + session.commit(take(st, me, Math.max(0, Math.min(st.hands[seat].length - 1, idx)))); + drive(); + return true; + } + function tap(pile, idx) { + if (/^p\d$/.test(pile)) return takeAt(pile, idx); + if (pile.charAt(0) === 'h') { t.flash(TX('oldmaid.notYours')); return false; } + return false; + } + function newGame() { + players = Z.store.get(PLAYERS_KEY, DEFAULT_PLAYERS); + if (players !== 2 && players !== 3 && players !== 4) players = DEFAULT_PLAYERS; + buildSeats(players); + view.flash = ''; + session.reset(deal(Z.shuffled(Math.random), players, Math.floor(Math.random() * players))); + seats.begin(function () { repaint(); drive(); }, session.state.turn); + } + t = T.create({ + id: 'oldmaid', name: 'Old Maid', seats: seats, view: view, geo: geo, place: function (st, m, v) { syncView(st); return place(st, m, v); }, hud: hud, newGame: newGame, tap: tap, + canPick: function () { return false; }, + stat: function (sec, st) { return Z.fmtTime(sec) + ' · ' + st.pairs[seats.view()]; }, + cascadeOrder: function (st) { return st.hands[seats.view()].map(function (id) { return { id: id }; }); }, + winLines: function (sec, st) { return [TX('oldmaid.stuck', { name: name(st.result.loser), card: Z.cardName(st.hands[st.result.loser][0]) })]; }, + menuExtra: function () { + return [T.choiceRow(TX('cards.seatsAtTable'), PLAYERS_KEY, [{ value: 2, label: '2' }, { value: 3, label: '3' }, { value: 4, label: '4' }], DEFAULT_PLAYERS, function () {}), + Z.h('p', { class: 'zc-note', text: TX('ce.seatsNote') })]; + }, + rules: TX('oldmaid.rules') + }); + board = t.board; session = t.session; + api.session = session; api.board = board; + newGame(); + } + + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/scorpion.html b/zimi/builtin/games/scorpion.html new file mode 100644 index 000000000..530adaa23 --- /dev/null +++ b/zimi/builtin/games/scorpion.html @@ -0,0 +1,30 @@ + + + + + +Scorpion + + + + + +
+ ‹ +

Scorpion

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/scorpion.js b/zimi/builtin/games/scorpion.js new file mode 100644 index 000000000..9f2c6b6cf --- /dev/null +++ b/zimi/builtin/games/scorpion.js @@ -0,0 +1,86 @@ +/* ZimiGames: Scorpion. Seven columns of seven cards, the first three of the first four columns face down, and three cards left + over. Build down in one suit, and move any face-up card with every card on it, in order or not. Only a king fills an empty + column. The three left over go one each onto the first three columns, whenever you like. A column that ends in king down to + ace of one suit leaves the table; clear all four suits to win. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, K = root.ZimiSolKit; + + var TABLEAU = ['t0', 't1', 't2', 't3', 't4', 't5', 't6'], DONE = ['d0', 'd1', 'd2', 'd3']; + var COLS = 7, COLUMN_CARDS = 7, DOWN_COLUMNS = 4, DOWN_CARDS = 3, SPARE_CARDS = 3, DONE_COL = 3; + var SUIT_COUNT = 4; + + var sameSuitDown = function (upper, lower) { return Z.suit(upper) === Z.suit(lower) && Z.rank(lower) === Z.rank(upper) - 1; }; + + // A column that ends in a whole suit, king to ace, goes to a pile of its own. + function sweep(s) { + TABLEAU.forEach(function (t) { + var p = s.piles[t], n = p.length, i; + if (n < Z.KING || Z.rank(p[n - Z.KING].id) !== Z.KING) return; + for (i = n - Z.KING; i < n; i++) if (!p[i].up || (i > n - Z.KING && !sameSuitDown(p[i - 1].id, p[i].id))) return; + var run = p.splice(n - Z.KING), d = DONE.filter(function (x) { return !s.piles[x].length; })[0]; + s.piles[d] = run; + if (p.length && !p[p.length - 1].up) p[p.length - 1].up = true; + }); + } + // The spare cards go face up, one on each of the first three columns. + function dealSpare(state) { + if (state.piles.stock.length < SPARE_CARDS) return null; + var s = Z.clone(state); + for (var i = 0; i < SPARE_CARDS; i++) { var c = s.piles.stock.pop(); c.up = true; s.piles[TABLEAU[i]].push(c); } + s.moves++; + sweep(s); + return s; + } + + var R = K.rules({ + tableau: TABLEAU, foundation: [], stock: 'stock', + runOK: function () { return true; }, + builds: sameSuitDown, + emptyOK: function (id) { return Z.rank(id) === Z.KING; }, + isWon: function (state) { return DONE.every(function (d) { return state.piles[d].length === Z.KING; }); }, + whyBuild: 'sol.why.suit', whyEmpty: 'sol.why.king', + draw: dealSpare, settle: sweep + }); + var blank = function () { return K.blankState(['stock'].concat(TABLEAU, DONE)); }; + + function newState(order) { + var s = blank(), k = 0; + TABLEAU.forEach(function (t, n) { + for (var j = 0; j < COLUMN_CARDS; j++) s.piles[t].push(K.card(order[k++], !(n < DOWN_COLUMNS && j < DOWN_CARDS))); + }); + while (k < order.length) s.piles.stock.push(K.card(order[k++], false)); + return s; + } + + var place = K.layout({ + topRows: 1, + items: [{ pile: 'stock', kind: 'stock', col: 0, row: 0 }] + .concat(DONE.map(function (d, n) { return { pile: d, kind: 'foundation', col: DONE_COL + n, row: 0, mark: 'K' }; })) + .concat(TABLEAU.map(function (t, n) { return { pile: t, kind: 'column', col: n, row: 1, n: n + 1 }; })) + }); + + // One move from a win: three suits taken, the fourth's king to deuce in one column and the ace alone on another. + function almostWon() { + var s = blank(), suit, r; + for (suit = 0; suit < SUIT_COUNT - 1; suit++) for (r = Z.KING; r >= 1; r--) s.piles[DONE[suit]].push(K.card(Z.make(r, suit), true)); + for (r = Z.KING; r >= 2; r--) s.piles.t0.push(K.card(Z.make(r, SUIT_COUNT - 1), true)); + s.piles.t1.push(K.card(Z.make(1, SUIT_COUNT - 1), true)); + return s; + } + + function cascade(st) { + var order = [], r; + for (r = 0; r < Z.KING; r++) DONE.forEach(function (d) { if (st.piles[d][r]) order.push({ id: st.piles[d][r].id }); }); + return order; + } + + var api = Object.assign(R, { newState: newState, blankState: blank, place: place, drawStock: dealSpare, sweep: sweep, almostWon: almostWon, DONE: DONE }); + root.ZimiScorpion = api; + + function boot() { + K.page({ rules: R, id: 'scorpion', title: 'Scorpion', cols: COLS, place: place, refuse: 'sol.why.noSpare', cascade: cascade, + deal: function () { return newState(Z.shuffled(Z.random())); }, almostWon: almostWon }); + } + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/snap.css b/zimi/builtin/games/snap.css new file mode 100644 index 000000000..8184fb032 --- /dev/null +++ b/zimi/builtin/games/snap.css @@ -0,0 +1,13 @@ +/* Snap: the big Snap button under the two piles, and the count of cards left in each stack. */ +.sn-snap { position: absolute; z-index: 30; box-sizing: border-box; border: 2px solid rgba(255, 255, 255, 0.55); border-radius: 16px; background: rgba(0, 0, 0, 0.34); color: #fff; font: 700 var(--fs-title) var(--font); letter-spacing: 0.02em; touch-action: manipulation; cursor: pointer; transition: background 120ms ease-out, transform 120ms ease-out; -webkit-tap-highlight-color: transparent; } +.sn-snap:active { transform: scale(0.98); } +.sn-snap:focus-visible { outline: 2px solid var(--select-ring); outline-offset: 2px; } +.sn-snap.sn-hot { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); } +.sn-snap:disabled { opacity: 0.5; cursor: default; } +.sn-count { position: absolute; z-index: 30; transform: translateX(-50%); min-width: 28px; padding: 2px 10px; border-radius: 999px; background: rgba(0, 0, 0, 0.34); color: #fff; font-size: var(--fs-small); line-height: 1.5; text-align: center; font-variant-numeric: tabular-nums; pointer-events: none; } +html[data-anim="off"] .sn-snap { transition: none; } + +/* Red, generated by scripts/games_red.py from the rules above: do not edit. */ +:root.gs.night-red .sn-snap { border: 2px solid rgba(255, 32, 16, 0.55); background: rgba(0, 0, 0, 0.34); color: #ff2010; } +:root.gs.night-red .sn-count { background: rgba(0, 0, 0, 0.34); color: #ff2010; } +/* end Red */ diff --git a/zimi/builtin/games/snap.html b/zimi/builtin/games/snap.html new file mode 100644 index 000000000..18f01a8a1 --- /dev/null +++ b/zimi/builtin/games/snap.html @@ -0,0 +1,32 @@ + + + + + +Snap + + + + + + + +
+ ‹ +

Snap

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/snap.js b/zimi/builtin/games/snap.js new file mode 100644 index 000000000..763b86506 --- /dev/null +++ b/zimi/builtin/games/snap.js @@ -0,0 +1,217 @@ +/* ZimiGames: Snap, you against Zimi, with two decks. Each of you has a face-down stack of 52. In turn you each turn the top card + of your stack onto your own pile. When the tops of the two piles are the same rank, the first to tap Snap takes both piles. + A snap with no match costs you two of the cards you have won. When both stacks are used up, the most cards won wins. + + Zimi reacts like a person: on every level a different spread of reaction times (never quicker than a third of a second), and it + sometimes misses a match altogether. + + State: stacks[2], piles[2] (the face-up cards, top last), won[2] (cards each has taken), turn (who turns next), phase + ('play' | 'over'), note (the latest snap or false snap), moves, flips. Seat 0 is you, seat 1 is Zimi. Pure functions; the + page wiring only runs in a browser. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, T = root.ZimiTable, TX = root.ZimiCards.T; + + var DECKS = 2, CARDS = 52 * DECKS, PENALTY = 2, LEVEL_KEY = 'snap.level', DEFAULT_LEVEL = 'medium'; + // How long a card shows before the next is turned, and how fast Zimi is: a reaction between `from` and `to` ms, missing the match + // `miss` of the time. + var LEVELS = { + easy: { flip: 1700, from: 800, to: 1250, miss: 0.25 }, + medium: { flip: 1300, from: 520, to: 880, miss: 0.12 }, + hard: { flip: 1000, from: 360, to: 600, miss: 0.04 } + }; + var rankOf = function (id) { return Z.rank(id); }; + var top = function (pile) { return pile[pile.length - 1]; }; + + // ── Rules ─────────────────────────────────────────────────────────────── + // `order` is the shuffled double deck (ids 0 to 103; past 51 are copies of the same faces). + function deal(order, first) { + return { stacks: [order.slice(0, CARDS / 2), order.slice(CARDS / 2, CARDS)], piles: [[], []], won: [0, 0], turn: first || 0, phase: 'play', note: null, moves: 0, flips: 0 }; + } + var isMatch = function (st) { return st.piles[0].length > 0 && st.piles[1].length > 0 && rankOf(top(st.piles[0])) === rankOf(top(st.piles[1])); }; + var cardsLeft = function (st) { return st.stacks[0].length + st.stacks[1].length; }; + // The next card is turned by whoever's turn it is who still has cards; the game ends when both stacks are empty. + function flip(st) { + if (st.phase !== 'play' || cardsLeft(st) === 0) return st; + var s = Z.clone(st), seat = s.stacks[s.turn].length ? s.turn : 1 - s.turn; + s.piles[seat].push(s.stacks[seat].pop()); + s.turn = 1 - seat; s.flips++; s.moves++; s.note = null; + if (cardsLeft(s) === 0 && !isMatch(s)) s.phase = 'over'; + return s; + } + // The last card has had its moment: whatever is still on the piles stays there. + function close(st) { var s = Z.clone(st); s.phase = 'over'; return s; } + // A snap: a match takes both piles; no match loses two of your won cards (never below none). + function snap(st, seat) { + if (st.phase !== 'play') return st; + var s = Z.clone(st); + if (isMatch(s)) { + var n = s.piles[0].length + s.piles[1].length; + s.won[seat] += n; s.piles = [[], []]; s.note = { kind: 'snap', seat: seat, n: n }; + } else { + var lost = Math.min(PENALTY, s.won[seat]); + s.won[seat] -= lost; s.note = { kind: 'false', seat: seat, n: lost }; + } + s.moves++; + if (cardsLeft(s) === 0) s.phase = 'over'; + return s; + } + var winner = function (st) { return st.won[0] === st.won[1] ? -1 : st.won[0] > st.won[1] ? 0 : 1; }; + + // ── The computer player ───────────────────────────────────────────────── + // How long Zimi takes to snap a match on this level, or null when it does not see this one. + function reaction(level, rng) { + var L = LEVELS[level] || LEVELS[DEFAULT_LEVEL]; + rng = rng || Math.random; + if (rng() < L.miss) return null; + return Math.round(L.from + rng() * (L.to - L.from)); + } + + // ── Layout ────────────────────────────────────────────────────────────── + var SHOW_STACK = 2, BADGE_RISE = 28; + var who = function (seat) { return seat ? root.ZimiText.ZIMI : TX('cards.you'); }; + function geo(m) { return T.geometry(m, 1); } + // Zimi's stack at the top, yours at the bottom, the two piles side by side between them. + function spots(g) { + var y = Math.round(g.cy - g.ch / 2); + return { stack: [{ x: Math.round(g.cx - g.cw / 2), y: g.southY }, { x: Math.round(g.cx - g.cw / 2), y: g.northY }], pile: [{ x: Math.round(g.cx + g.cw * 0.08), y: y }, { x: Math.round(g.cx - g.cw * 1.08), y: y }] }; + } + function place(st, m) { + var g = geo(m), p = spots(g), slots = [], cards = []; + [0, 1].forEach(function (seat) { + var stack = st.stacks[seat], pile = st.piles[seat]; + slots.push({ id: 'stack' + seat, x: p.stack[seat].x, y: p.stack[seat].y, w: g.cw, h: g.ch, quiet: true, label: TX('snap.stack', { who: who(seat), cards: Z.plural(stack.length, 'card') }) }); + slots.push({ id: 'pile' + seat, x: p.pile[seat].x, y: p.pile[seat].y, w: g.cw, h: g.ch, label: pile.length ? TX('snap.pile', { who: who(seat), card: Z.cardName(top(pile)) }) : TX('snap.pile.empty', { who: who(seat) }) }); + stack.forEach(function (id, k) { cards.push({ id: id, pile: 'stack' + seat, idx: k, x: p.stack[seat].x, y: p.stack[seat].y, up: false, hidden: k < stack.length - SHOW_STACK }); }); + pile.forEach(function (id, k) { cards.push({ id: id, pile: 'pile' + seat, idx: k, x: p.pile[seat].x, y: p.pile[seat].y, up: true, hidden: k < pile.length - 1, glow: isMatch(st) }); }); + }); + return { height: m.H, slots: slots, cards: cards }; + } + + var api = { + CARDS: CARDS, PENALTY: PENALTY, LEVELS: LEVELS, deal: deal, isMatch: isMatch, cardsLeft: cardsLeft, flip: flip, close: close, snap: snap, winner: winner, reaction: reaction, geo: geo, spots: spots, place: place + }; + root.ZimiSnap = api; + + // ── The page ──────────────────────────────────────────────────────────── + var BUTTON_GAP = 22, BUTTON_MAX = 76, BUTTON_MIN = 52, SIDE_GAP = 24, SIDE_BUTTON_FROM = 1.4, NOTE_MS = 1200, OVER_MS = 900, RESUME_MS = 2200; + function boot() { + var d = root.document, t, board, session, view = { flash: '' }, level = DEFAULT_LEVEL, timer = 0, held = false, resumed = false; + var button = Z.h('button', { class: 'sn-snap', type: 'button', text: TX('snap.button') }); + var badges = [Z.h('div', { class: 'sn-count' }), Z.h('div', { class: 'sn-count' })]; + Z.pageEls().table.appendChild(button); badges.forEach(function (b) { Z.pageEls().table.appendChild(b); }); + var clear = function () { if (timer) { root.clearTimeout(timer); timer = 0; } }; + var later = function (fn, ms) { clear(); timer = root.setTimeout(function () { timer = 0; fn(); }, ms); }; + function readLevel() { var v = Z.store.get(LEVEL_KEY, DEFAULT_LEVEL); return LEVELS[v] ? v : DEFAULT_LEVEL; } + + function paintEdges(st) { + var m = board.metrics(); + if (!m) return; + var g = geo(m), p = spots(g), y = g.cy + g.ch / 2 + BUTTON_GAP, room = g.statusY - y - 12; + if (room < BUTTON_MIN) { + // A short table (a phone on its side): no room under the piles, so the button stands to the right of them, as tall as a card. + button.style.left = Math.round(g.cx + g.cw * SIDE_BUTTON_FROM) + 'px'; button.style.right = SIDE_GAP + 'px'; button.style.top = Math.round(g.cy - g.ch / 2) + 'px'; + button.style.height = Math.round(g.ch) + 'px'; + } else { + button.style.left = SIDE_GAP + 'px'; button.style.right = SIDE_GAP + 'px'; button.style.top = Math.round(y) + 'px'; + button.style.height = Math.round(Math.min(BUTTON_MAX, room)) + 'px'; + } + button.disabled = st.phase !== 'play'; + button.classList.toggle('sn-hot', isMatch(st)); + [0, 1].forEach(function (seat) { + badges[seat].style.left = Math.round(p.stack[seat].x + g.cw / 2) + 'px'; + badges[seat].style.top = Math.round(seat ? p.stack[seat].y + g.ch + 4 : p.stack[seat].y - BADGE_RISE) + 'px'; + badges[seat].textContent = String(st.stacks[seat].length); + }); + } + function said(st) { + var n = st.note; + if (!n) return isMatch(st) ? TX('snap.match') : TX('snap.watch'); + var you = n.seat === 0; + return n.kind === 'snap' ? TX(you ? 'snap.won.you' : 'snap.won', { cards: Z.plural(n.n, 'card') }) : TX(you ? 'snap.false.you' : 'snap.false', { cards: Z.plural(n.n, 'card') }); + } + function hud(st) { + paintEdges(st); + var out = { chips: [{ name: TX('cards.you'), text: String(st.won[0]) }, { name: root.ZimiText.ZIMI, text: String(st.won[1]) }], text: '' }; + if (st.phase === 'over') { out.text = TX('shell.end.over'); out.label = TX('shell.menu.new'); out.action = newGame; return out; } + out.text = said(st); + return out; + } + + function arm() { + var st = session.state; + clear(); + if (held || d.hidden || st.phase === 'over') return; + later(flipNow, st.flips === 0 && st.moves === 0 ? OVER_MS : resumed ? RESUME_MS : LEVELS[level].flip); + resumed = false; + } + function flipNow() { + var st = session.state; + if (st.phase !== 'play') return; + session.began(); + if (cardsLeft(st) === 0) { session.follow(close(st)); finish(); return; } + var next = flip(st); + session.follow(next); + if (next.phase === 'over') { finish(); return; } + if (isMatch(next)) { + var wait = reaction(level), at = next.moves; + if (wait !== null) session.later(function () { var now = session.state; if (now.moves === at && isMatch(now) && !held) take(1); }, wait); + } + arm(); + } + // A snap by `seat`: kept in the state, shown a moment, and the next card comes after it. + function take(seat) { + var st = session.state; + if (st.phase === 'over') return; + session.began(); + var next = snap(st, seat); + session.follow(next); + if (next.phase === 'over') { finish(); return; } + later(flipNow, NOTE_MS); + } + function finish() { + clear(); + var st = session.state, w = winner(st); + later(function () { + var line = TX('snap.final', { you: st.won[0], zimi: st.won[1] }); + if (w === 0) session.win(st.won[0]); else session.lose(w < 0 ? 'draw' : '', [line], st.won[0]); + }, OVER_MS); + } + function pressed() { + var st = session.state; + if (st.phase !== 'play' || (held)) return; + take(0); + if (!isMatch(st)) t.flash(TX('snap.noMatch')); + } + button.addEventListener('pointerdown', function (e) { e.preventDefault(); pressed(); }); + button.addEventListener('keydown', function (e) { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); pressed(); } }); + d.addEventListener('keydown', function (e) { if (e.key === ' ' && !d.querySelector('.ar-sheet') && !(e.target && e.target.tagName === 'BUTTON')) { e.preventDefault(); pressed(); } }); + d.addEventListener('visibilitychange', function () { if (d.hidden) clear(); else arm(); }); + if (root.ZimiShell && root.ZimiShell.onHold) root.ZimiShell.onHold(function (on) { held = on; if (on) clear(); else arm(); }); + + function newGame() { + level = readLevel(); clear(); view.flash = ''; + resumed = true; + session.reset(deal(T.shuffleOf(Array.apply(null, Array(CARDS)).map(function (x, i) { return i; }), Math.random), Math.round(Math.random()))); + arm(); + } + t = T.create({ + id: 'snap', name: 'Snap', view: view, geo: geo, place: place, hud: hud, newGame: newGame, + tap: function (pile) { if (pile === 'pile0' || pile === 'pile1') { pressed(); return true; } return false; }, + slotTap: function (pile) { if (/^pile/.test(pile)) pressed(); }, + canPick: function () { return false; }, + stat: function (sec, st) { return Z.fmtTime(sec) + ' · ' + st.won[0]; }, + cascadeOrder: function (st) { return st.piles[0].concat(st.piles[1]).map(function (id) { return { id: id }; }); }, + winLines: function (sec, st) { return [TX('snap.final', { you: st.won[0], zimi: st.won[1] })]; }, + menuExtra: function () { + return [T.choiceRow(TX('board.level'), LEVEL_KEY, [{ value: 'easy', label: TX('board.level.easy') }, { value: 'medium', label: TX('board.level.medium') }, { value: 'hard', label: TX('board.level.hard') }], DEFAULT_LEVEL, function (v) { level = v; arm(); })]; + }, + rules: TX('snap.rules') + }); + board = t.board; session = t.session; + api.session = session; api.board = board; + newGame(); + } + + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/solitaire.js b/zimi/builtin/games/solitaire.js index d8b79287a..137f02ed1 100644 --- a/zimi/builtin/games/solitaire.js +++ b/zimi/builtin/games/solitaire.js @@ -183,54 +183,63 @@ } // ── Layout ────────────────────────────────────────────────────────────── - // Stock, waste and the foundations are one row right under the bar; the columns start under it and fan down through - // all the height that is left (up to a card's height a step). - var DOWN_RATIO = 0.54, MAX_DOWN_RATIO = 1, DOWN_RATIO_STEP = 0.05, UP_STEP_SHARE = Z.FAN_UP_SHARE, MIN_STEP_SHARE = 0.12, WASTE_FAN_SHARE = 0.3, WASTE_NUDGE_SHARE = 0.14; // the waste stands a little off the stock, not against it + // Narrow: stock, waste and the foundations are one row right under the bar (foundations left, stock under the right thumb), the + // columns under it fanning down through the height that is left. Wide (landscape, desktop): stock over waste in a column on the + // left, the foundations two by two on the right, the columns between with the whole height (WIDE: ten card widths). + // A face-down card shows DOWN_SHARE of its height: enough to count them, nothing to read. + var DOWN_SHARE = 0.12, UP_STEP_SHARE = Z.FAN_UP_SHARE, MIN_STEP_SHARE = 0.12, WASTE_FAN_SHARE = 0.3, WASTE_NUDGE_SHARE = 0.14; // the waste stands a little off the stock, not against it + var WIDE = { cols: 10, heightShare: 0.19 }, WIDE_TABLEAU_COL = 1, WIDE_FOUNDATION_COL = 8, WIDE_GROUP_GAP = 0.3; function place(state, m) { - var P = state.piles, cw = m.cw, ch = m.ch, x = function (col) { return m.left + col * m.step; }; - var rows = Z.solitaireRows(m), y1 = rows.top, y2 = rows.cols, slots = [], cards = []; // y1: the top row; y2: the columns - var weight = function (pile, down) { - var w = 0; - for (var i = 0; i < pile.length - 1; i++) w += pile[i].up ? 1 : down; - return w; - }; - var heaviest = function (down) { return Math.max.apply(null, TABLEAU.map(function (t) { return weight(P[t], down); })); }; - var down = Z.openDown(heaviest, rows.room, ch, ch * UP_STEP_SHARE, DOWN_RATIO, MAX_DOWN_RATIO, DOWN_RATIO_STEP); - var step = Z.fanStep(heaviest(down), rows.room, ch, ch * UP_STEP_SHARE, ch * MIN_STEP_SHARE); + // On a wide table the three groups (stock, columns, foundations) stand apart by up to WIDE_GROUP_GAP of a card, out of the spare width. + var group = m.wide ? Math.max(0, Math.min(m.cw * WIDE_GROUP_GAP, (m.W - 2 * m.pad - (WIDE.cols * m.cw + (WIDE.cols - 1) * m.gap)) / 2)) : 0; + var P = state.piles, cw = m.cw, ch = m.ch, x = function (col) { return m.left - group + col * m.step + (col >= WIDE_FOUNDATION_COL ? 2 : col >= WIDE_TABLEAU_COL ? 1 : 0) * group; }; + var rows = Z.solitaireRows(m), slots = [], cards = [], wide = m.wide; + var y1 = rows.top, y2 = wide ? m.pad : rows.cols, room = wide ? m.H - 2 * m.pad : rows.room, tx = function (n) { return x(n + (wide ? WIDE_TABLEAU_COL : 0)); }; + var down = ch * DOWN_SHARE; + // The longest column decides the face-up step: as open as UP_STEP_SHARE, closing up when the columns grow. + var step = Math.max(ch * MIN_STEP_SHARE, Math.min(ch * UP_STEP_SHARE, Math.min.apply(null, TABLEAU.map(function (t) { + var p = P[t], ups = 0, downs = 0; + p.forEach(function (c, i) { if (i < p.length - 1) { if (c.up) ups++; else downs++; } }); + return ups ? (room - ch - downs * down) / ups : Infinity; + })))); var bottom = y2 + ch; var ids = function (pile) { return pile.map(function (c) { return c.id; }); }; - var fan = cw * WASTE_FAN_SHARE, wx = x(1) + cw * WASTE_NUDGE_SHARE; + var fan = (wide ? ch : cw) * WASTE_FAN_SHARE; + var stockX = wide ? x(0) : x(6), stockY = y1; + var wx = wide ? x(0) : x(5) - cw * WASTE_NUDGE_SHARE - fan * (SHOWN_WASTE - 1), wy = wide ? m.pad + ch + 2 * m.gap : y1; + var fx = function (n) { return wide ? x(WIDE_FOUNDATION_COL + n % 2) : x(n); }, fy = function (n) { return wide ? m.pad + (n < 2 ? 0 : ch + 2 * m.gap) : y1; }; + if (wide) stockY = m.pad; // stock: the top two cards drawn, the rest stacked unseen beneath - P.stock.forEach(function (c, i) { cards.push({ id: c.id, pile: 'stock', idx: i, x: x(0), y: y1, up: false, hidden: i < P.stock.length - 2 }); }); - // waste: the last (up to) three cards fanned in draw 3, one in draw 1 + P.stock.forEach(function (c, i) { cards.push({ id: c.id, pile: 'stock', idx: i, x: stockX, y: stockY, up: false, hidden: i < P.stock.length - 2 }); }); + // waste: the last (up to) three cards fanned in draw 3 (to the right, or down on a wide table), one in draw 1 var shown = state.draw === 3 ? SHOWN_WASTE : 1; P.waste.forEach(function (c, i) { - var k = i - (P.waste.length - Math.min(shown, P.waste.length)), seen = k >= 0; - cards.push({ id: c.id, pile: 'waste', idx: i, x: wx + (seen ? k * fan : 0), y: y1, up: true, hidden: !seen }); + var k = i - (P.waste.length - Math.min(shown, P.waste.length)), seen = k >= 0, off = seen ? k * fan : 0; + cards.push({ id: c.id, pile: 'waste', idx: i, x: wide ? wx : wx + off, y: wide ? wy + off : wy, up: true, hidden: !seen }); }); FOUNDATION.forEach(function (f, n) { - P[f].forEach(function (c, i) { cards.push({ id: c.id, pile: f, idx: i, x: x(3 + n), y: y1, up: true, hidden: i < P[f].length - 2 }); }); + P[f].forEach(function (c, i) { cards.push({ id: c.id, pile: f, idx: i, x: fx(n), y: fy(n), up: true, hidden: i < P[f].length - 2 }); }); }); TABLEAU.forEach(function (t, n) { var yy = y2; P[t].forEach(function (c, i) { - cards.push({ id: c.id, pile: t, idx: i, x: x(n), y: yy, up: c.up, hidden: false }); - if (i < P[t].length - 1) yy += c.up ? step : step * down; + cards.push({ id: c.id, pile: t, idx: i, x: tx(n), y: yy, up: c.up, hidden: false }); + if (i < P[t].length - 1) yy += c.up ? step : down; }); bottom = Math.max(bottom, yy + ch); }); var height = Math.max(bottom + m.pad, m.H); - slots.push({ id: 'stock', x: x(0), y: y1, w: cw, h: ch, mark: P.stock.length ? '' : '↻', label: Z.describePile(TX('sol.stock'), ids(P.stock), false) + (P.stock.length ? TX('sol.enterDraw') : TX('sol.enterRecycle')) }); - slots.push({ id: 'waste', x: wx, y: y1, w: cw + fan * (SHOWN_WASTE - 1), h: ch, label: Z.describePile(TX('sol.waste'), ids(P.waste), true) }); + slots.push({ id: 'stock', x: stockX, y: stockY, w: cw, h: ch, mark: P.stock.length ? '' : '↻', label: Z.describePile(TX('sol.stock'), ids(P.stock), false) + (P.stock.length ? TX('sol.enterDraw') : TX('sol.enterRecycle')) }); + slots.push({ id: 'waste', x: wx, y: wy, w: wide ? cw : cw + fan * (SHOWN_WASTE - 1), h: wide ? ch + fan * (SHOWN_WASTE - 1) : ch, label: Z.describePile(TX('sol.waste'), ids(P.waste), true) }); FOUNDATION.forEach(function (f, n) { var t = P[f].length ? top(P[f]).id : null; - slots.push({ id: f, x: x(3 + n), y: y1, w: cw, h: ch, goal: true, mark: t === null ? 'A' : '', label: (t === null ? TX('sol.foundationEmpty') : TX('sol.foundation', { suit: TX('cards.suit.' + ['clubs', 'diamonds', 'hearts', 'spades'][Z.suit(t)]), cards: Z.plural(P[f].length, 'card') })) }); + slots.push({ id: f, x: fx(n), y: fy(n), w: cw, h: ch, goal: true, mark: t === null ? 'A' : '', label: (t === null ? TX('sol.foundationEmpty') : TX('sol.foundation', { suit: TX('cards.suit.' + ['clubs', 'diamonds', 'hearts', 'spades'][Z.suit(t)]), cards: Z.plural(P[f].length, 'card') })) }); }); TABLEAU.forEach(function (t, n) { - slots.push({ id: t, x: x(n), y: y2, w: cw, h: Math.max(ch, height - m.pad - y2), label: Z.describePile(TX('sol.tableau', { n: n + 1 }), ids(P[t]), P[t].length && top(P[t]).up) }); + slots.push({ id: t, x: tx(n), y: y2, w: cw, h: Math.max(ch, height - m.pad - y2), label: Z.describePile(TX('sol.tableau', { n: n + 1 }), ids(P[t]), P[t].length && top(P[t]).up) }); }); return { height: height, slots: slots, cards: cards }; } @@ -275,7 +284,7 @@ page = Z.solitairePage({ rules: api, id: 'solitaire', saveOff: function () { return !!watch; }, blocked: function () { return !!watch; }, - place: place, cols: COLS, newGame: newGame, stock: drawStock, afterStock: false, why: why, + place: place, cols: COLS, wide: WIDE, newGame: newGame, stock: drawStock, afterStock: false, why: why, refuse: function () { page.note(TX('sol.why.stockEmpty')); }, drew: function (before, after) { if (after.passes === before.passes) return; diff --git a/zimi/builtin/games/solkit.js b/zimi/builtin/games/solkit.js new file mode 100644 index 000000000..481b9d55a --- /dev/null +++ b/zimi/builtin/games/solkit.js @@ -0,0 +1,275 @@ +/* ZimiGames: what the tableau solitaires after Klondike share (Yukon, Forty Thieves, Canfield, Scorpion, Beleaguered Castle, + Eight Off): the rules of a game written as a few small facts (what builds on what, what may be picked up, what fills an + empty column), the layout of a row of stock, waste, cells and foundations over fanned columns, and the page. A game is a + file of those facts; the moves, the tap, the hint of why not, the stuck sheet and the win are written here once. + Our own code, GPL-3.0. No network, no modules. + + State: piles { name: [{ id, up }] }, moves. Card ids past 51 are the second deck's copies (ZimiCards treats id % 52 as the face). + + A game's facts S: + tableau, foundation pile names; cells, stock, waste, reserve optional pile names + runOK(ids) the cards from a tapped card down may move together + builds(upper, lower) lower may sit on upper in a column + emptyOK(id) a card may start an empty column (default: any) + fits(id, topId, n) a foundation (top card id or null, its size) takes the card (default: same suit, one up from the ace) + canDrop(state, from, to) false when a card may never go from that pile to that one (Calculation's waste piles take only the deck) + limit(state, to, n) most cards that may move to a column (default: no limit) + draw(state) the next state after a turn of the stock, or null + settle(state) what follows every move by itself (Canfield fills a gap from the reserve) + winCount cards in a finished foundation (default 13) */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, TX = root.ZimiCards.T; + + var SUIT_KEYS = ['clubs', 'diamonds', 'hearts', 'spades']; + var DOWN_RATIO = 0.54, MAX_DOWN_RATIO = 1, DOWN_RATIO_STEP = 0.05, UP_STEP_SHARE = Z.FAN_UP_SHARE, MIN_STEP_SHARE = 0.12; + var ROW_GAP_SHARE = 0.12, WASTE_FAN_SHARE = 0.3, AUTO_STEP_MS = 120, SHOWN_STACK = 2; + + var top = function (pile) { return pile[pile.length - 1]; }; + var card = function (id, up) { return { id: id, up: up }; }; + var ids = Z.idsOf; + function suitName(id) { return TX('cards.suit.' + SUIT_KEYS[Z.suit(id)]); } + + // The ids of `decks` decks, shuffled by rng. + function shuffledDecks(decks, rng) { + var a = [], i, j, t; + for (i = 0; i < decks * Z.DECK; i++) a.push(i); + for (i = a.length - 1; i > 0; i--) { j = Math.floor(rng() * (i + 1)); t = a[i]; a[i] = a[j]; a[j] = t; } + return a; + } + function blankState(names) { + var piles = {}; + names.forEach(function (p) { piles[p] = []; }); + return { piles: piles, moves: 0 }; + } + + // ── Rules ─────────────────────────────────────────────────────────────── + function rules(S) { + var cells = S.cells || [], winCount = S.winCount || Z.KING, emptyOK = S.emptyOK || function () { return true; }; + var fits = S.fits || Z.foundationAccepts; + var kind = function (p) { + return S.foundation.indexOf(p) >= 0 ? 'foundation' : S.tableau.indexOf(p) >= 0 ? 'tableau' : cells.indexOf(p) >= 0 ? 'cell' : p; + }; + var isTableau = function (p) { return S.tableau.indexOf(p) >= 0; }; + var sources = S.tableau.concat(cells, S.waste ? [S.waste] : [], S.reserve ? [S.reserve] : []); + + function canPick(state, pile, idx) { + var p = state.piles[pile], k = kind(pile); + if (!p || idx < 0 || idx >= p.length || !p[idx].up || k === 'stock') return false; + if (k === 'tableau') return S.runOK(ids(p.slice(idx))); + if (k === 'foundation' && S.takeFoundation === false) return false; + return idx === p.length - 1; + } + function legalMove(state, from, idx, to) { + if (from === to || !canPick(state, from, idx) || (S.canDrop && !S.canDrop(state, from, to))) return false; + var P = state.piles, moving = P[from].slice(idx), first = moving[0].id, dest = P[to], k = kind(to); + if (k === 'foundation') return moving.length === 1 && fits(first, dest.length ? top(dest).id : null, dest.length, state, to); + if (k === 'cell') return moving.length === 1 && !dest.length && kind(from) !== 'cell'; + if (k !== 'tableau') return false; + if (S.limit && moving.length > S.limit(state, to)) return false; + return dest.length ? S.builds(top(dest).id, first) : emptyOK(first, state, to); + } + function applyMove(state, from, idx, to) { + var s = Z.clone(state), src = s.piles[from]; + s.piles[to] = s.piles[to].concat(src.splice(idx)); + if (src.length && !top(src).up) top(src).up = true; + s.moves++; + if (S.settle) S.settle(s, from, to); + return s; + } + + // Where a tap sends a card: a foundation (its own suit's pile first), a column with cards, an empty column (never to move a + // column's own bottom card), then a free cell. + function bestMove(state, from, idx) { + if (!canPick(state, from, idx)) return null; + var P = state.piles, first = P[from][idx].id, targets = []; + if (kind(from) !== 'foundation') { + targets = S.foundation.filter(function (f) { return P[f].length && Z.suit(top(P[f]).id) === Z.suit(first); }) + .concat(S.foundation.filter(function (f) { return !P[f].length; })); + } + targets = targets.concat(S.tableau.filter(function (t) { return P[t].length; })); + if (!(isTableau(from) && idx === 0)) targets = targets.concat(S.tableau.filter(function (t) { return !P[t].length; })); + if (P[from].length - idx === 1 && kind(from) !== 'cell') targets = targets.concat(cells); + for (var i = 0; i < targets.length; i++) if (legalMove(state, from, idx, targets[i])) return targets[i]; + return null; + } + + // Any move on the board: a card to a pile that takes it. A column's bottom card to an empty column only shuffles, and a card + // taken back off a foundation is not a way forward. + function boardMove(state) { + var P = state.piles, to = S.foundation.concat(S.tableau, cells), i, j, k; + for (i = 0; i < sources.length; i++) { + for (j = 0; j < P[sources[i]].length; j++) for (k = 0; k < to.length; k++) { + if (j === 0 && isTableau(sources[i]) && isTableau(to[k]) && !P[to[k]].length) continue; + if (legalMove(state, sources[i], j, to[k])) return true; + } + } + return false; + } + // With a stock, the cards it can still turn up are tried too (a pass that repeats itself ends the search). + function hasMove(state) { + var s = state, seen = {}, key; + while (s) { + if (boardMove(s)) return true; + if (!S.draw) return false; + key = ids(s.piles[S.stock]).join() + '|' + (S.waste ? ids(s.piles[S.waste]).join() : ''); + if (seen[key]) return false; + seen[key] = true; + s = S.draw(s); + } + return false; + } + var isWon = S.isWon || function (state) { return S.foundation.every(function (f) { return state.piles[f].length === winCount; }); }; + + // Nothing face down and nothing left to turn: the rest is a formality. + function canAutoFinish(state) { + return (!S.stock || !state.piles[S.stock].length) && S.tableau.every(function (t) { return state.piles[t].every(function (c) { return c.up; }); }); + } + function autoFinishStep(state) { + var i, j, p; + for (i = 0; i < sources.length; i++) { + p = state.piles[sources[i]]; + if (!p.length) continue; + for (j = 0; j < S.foundation.length; j++) if (legalMove(state, sources[i], p.length - 1, S.foundation[j])) return { from: sources[i], idx: p.length - 1, to: S.foundation[j] }; + } + return null; + } + + // The words for a card that would not go: a tap that had nowhere to send it (no `to`), or a drop on a pile that refused it. + function why(state, pile, idx, to) { + var P = state.piles, c = P[pile] && P[pile][idx]; + if (!c) return null; + if (!c.up) return TX('sol.why.facedown'); + if (!canPick(state, pile, idx)) return TX(kind(pile) === 'tableau' && S.whyPick || 'sol.why.nowhere'); + if (to === undefined) return TX('sol.why.nowhere'); + var k = kind(to); + if (k === 'foundation') { + if (P[pile].length - idx > 1) return TX('sol.why.oneCard'); + return typeof S.whyFoundation === 'function' ? S.whyFoundation(state, to) : TX(S.whyFoundation || 'sol.why.foundation'); + } + if (k === 'cell') return TX(P[to].length ? 'fc.why.cells' : 'fc.why.cell'); + if (k === 'tableau') { + if (S.limit && P[pile].length - idx > S.limit(state, to)) return TX(S.whyLimit || 'sol.why.single'); + return TX(P[to].length ? S.whyBuild : S.whyEmpty); + } + return null; + } + + return { S: S, TABLEAU: S.tableau, FOUNDATION: S.foundation, canPick: canPick, legalMove: legalMove, applyMove: applyMove, bestMove: bestMove, + hasMove: hasMove, boardMove: boardMove, isWon: isWon, canAutoFinish: canAutoFinish, autoFinishStep: autoFinishStep, why: why, kind: kind }; + } + + // ── Layout ────────────────────────────────────────────────────────────── + // L.topRows rows of stock, waste, cells and foundations under the bar, then the columns. Each item of L.items: + // { pile, kind: stock|waste|foundation|cell|column|reserve, col, row, shown (a waste's fanned cards), mark (an empty foundation's letter) } + // A column or a reserve fans down from its row (row === L.topRows is the columns' row). + function layout(L) { + var topRows = L.topRows || 1; + return function place(state, m) { + var P = state.piles, cw = m.cw, ch = m.ch, x = function (col) { return m.left + col * m.step; }; + var base = Z.solitaireRows(m), rowStep = Math.round(ch * (1 + ROW_GAP_SHARE)), extra = (topRows - 1) * rowStep; + var y = function (row) { return row < topRows ? base.top + row * rowStep : base.cols + extra; }; + var room = base.room - extra, slots = [], cards = [], bottom = y(topRows) + ch; + var columns = L.items.filter(function (it) { return it.kind === 'column' || it.kind === 'reserve'; }); + var weight = function (pile, down) { + var w = 0; + for (var i = 0; i < pile.length - 1; i++) w += pile[i].up ? 1 : down; + return w; + }; + var heaviest = function (down) { return Math.max.apply(null, columns.map(function (it) { return weight(P[it.pile], down); })); }; + var down = Z.openDown(heaviest, room, ch, ch * UP_STEP_SHARE, DOWN_RATIO, MAX_DOWN_RATIO, DOWN_RATIO_STEP); + var step = Z.growStep(heaviest(down), room, ch, ch * MIN_STEP_SHARE); + var fan = cw * WASTE_FAN_SHARE; + var frames = []; + + L.items.forEach(function (it) { + var p = P[it.pile], px = x(it.col), py = y(it.row || 0), n = p.length, tc = n ? top(p).id : null, label; + if (it.kind === 'column' || it.kind === 'reserve') { + var yy = py; + p.forEach(function (c, i) { + cards.push({ id: c.id, pile: it.pile, idx: i, x: px, y: yy, up: c.up }); + if (i < n - 1) yy += c.up ? step : step * down; + }); + bottom = Math.max(bottom, yy + ch); + frames.push({ it: it, x: px, y: py }); + return; + } + if (it.kind === 'waste') { + var shown = Math.min(it.shown || 1, n); + p.forEach(function (c, i) { + var k = i - (n - shown), seen = k >= 0; + cards.push({ id: c.id, pile: it.pile, idx: i, x: px + (seen ? k * fan : 0), y: py, up: true, hidden: !seen }); + }); + slots.push({ id: it.pile, x: px, y: py, w: cw + fan * ((it.shown || 1) - 1), h: ch, label: Z.describePile(TX(it.label || 'sol.waste'), ids(p), true) }); + return; + } + p.forEach(function (c, i) { cards.push({ id: c.id, pile: it.pile, idx: i, x: px, y: py, up: it.kind !== 'stock' && c.up !== false, hidden: it.kind === 'cell' ? false : i < n - SHOWN_STACK }); }); + if (it.kind === 'stock') { + slots.push({ id: it.pile, x: px, y: py, w: cw, h: ch, mark: n ? '' : (it.mark || ''), label: Z.describePile(TX('sol.stock'), ids(p), false) + (n ? TX('sol.enterDraw') : '') }); + } else if (it.kind === 'cell') { + slots.push({ id: it.pile, x: px, y: py, w: cw, h: ch, label: n ? TX('fc.cell', { n: it.n, card: Z.cardName(tc) }) : TX('fc.cellEmpty', { n: it.n }) }); + } else { + slots.push({ id: it.pile, x: px, y: py, w: cw, h: ch, goal: true, mark: n ? '' : (typeof it.mark === 'function' ? it.mark(state) : it.mark || 'A'), + label: it.label ? TX(it.label, { n: it.n, cards: Z.plural(n, 'card') }) : n ? TX('sol.foundation', { suit: suitName(tc), cards: Z.plural(n, 'card') }) : TX('sol.foundationEmpty') }); + } + }); + var height = Math.max(bottom + m.pad, m.H); + frames.forEach(function (f) { + var it = f.it, p = P[it.pile]; + slots.push({ id: it.pile, x: f.x, y: f.y, w: cw, h: Math.max(ch, height - m.pad - f.y), + label: Z.describePile(it.kind === 'reserve' ? TX('sol.reserve') : TX(it.label || 'sol.tableau', { n: it.n }), ids(p), p.length && top(p).up) }); + }); + return { height: height, slots: slots, cards: cards }; + }; + } + + // ── The page ──────────────────────────────────────────────────────────── + // o: { rules, id, title, cols, heightShare, place, deal (-> a state), draw (a turn of the stock), refuse (words), auto (finish by itself), + // almostWon, cascade (state -> [{ id }]), options (menu rows), onDealt } + function page(o) { + var R = o.rules, S = R.S, pg, session; + function autoFinish() { + if (!o.auto || !R.canAutoFinish(session.state) || !R.autoFinishStep(session.state)) return; + session.later(function () { + var cur = session.state, st = R.autoFinishStep(cur); + if (!st) return; + session.follow(R.applyMove(cur, st.from, st.idx, st.to)); + if (R.isWon(session.state)) session.win(); else autoFinish(); + }, AUTO_STEP_MS); + } + var cfg = { + rules: R, id: o.id, place: o.place, cols: o.cols, heightShare: o.heightShare, why: R.why, + newGame: function () { session.reset(o.deal()); if (o.onDealt) o.onDealt(session.state); }, + stuck: Z.stuckWhen(R, R.hasMove), + after: autoFinish, + statText: function (sec, st) { return Z.fmtTime(sec) + ' · ' + (o.score ? o.score(st) : st.moves); }, + cascadeOrder: o.cascade || function (st) { + var order = [], r; + for (r = Z.KING; r >= 1; r--) S.foundation.forEach(function (f) { if (st.piles[f][r - 1]) order.push({ id: st.piles[f][r - 1].id }); }); + return order; + }, + winLines: function (sec, st) { return [Z.winTime(sec, st)]; }, + openMenu: function () { pg.menu(o.title, o.options ? o.options() : []); } + }; + if (S.draw) { + cfg.stock = S.draw; // a turn of the stock is checked like any move: it can win, auto-finish or leave no moves + cfg.refuse = function () { pg.note(TX(o.refuse || 'sol.why.stockEmpty')); }; + } + pg = Z.solitairePage(cfg); + session = pg.session; + pg.start(null, o.almostWon); + return pg; + } + + // A state one move from a win: every foundation full but for the last king, which waits at the first column. + function almostWon(R, blank) { + var S = R.S, s = blank(), n = S.foundation.length, k, r, id; + for (k = 0; k < n; k++) for (r = 1; r <= Z.KING; r++) { + id = Math.floor(k / 4) * Z.DECK + Z.make(r, k % 4); + if (k === n - 1 && r === Z.KING) s.piles[S.tableau[0]].push(card(id, true)); else s.piles[S.foundation[k]].push(card(id, true)); + } + return s; + } + + root.ZimiSolKit = { rules: rules, layout: layout, page: page, almostWon: almostWon, shuffledDecks: shuffledDecks, blankState: blankState, top: top, card: card, suitName: suitName }; +})(typeof globalThis !== 'undefined' ? globalThis : window); diff --git a/zimi/builtin/games/tablesnap.js b/zimi/builtin/games/tablesnap.js new file mode 100644 index 000000000..fb916082a --- /dev/null +++ b/zimi/builtin/games/tablesnap.js @@ -0,0 +1,131 @@ +/* ZimiGames: the table as a picture. A board game built from page elements (squares, pieces, dice, tiles) is painted as a + small svg of what is on the page: each element's colour and corners as a rectangle, each piece as the svg it is, each + word as text. The shell asks for it when a game is left under way (ZimiTableSnap.picture(), for the shelf's live + tile). Our own code, GPL-3.0. No network, no modules. */ +(function (root) { + 'use strict'; + var W = 320, H = 180, PAD = 6; // the tile's 16 by 9 picture and the margin round the table + var FRAME_GROWTH = 1.2; // a parent this much bigger or less is the table's own frame + var MAX_CHARS = 90000; // a table that paints bigger than this keeps the tile's art + var SVG_NS = 'http://www.w3.org/2000/svg'; + var DEFAULT_PAINT = { fill: 'rgb(0, 0, 0)', stroke: 'none', 'stroke-width': '1px', 'fill-opacity': '1', 'stroke-opacity': '1', 'stroke-linecap': 'butt', 'stroke-linejoin': 'miter' }; + var TEXT_PROPS = ['font-size', 'font-weight', 'font-family', 'text-anchor', 'dominant-baseline']; // the class that sized a label is gone + var INHERITED = Object.keys(DEFAULT_PAINT); + var PAINT_ATTRS = INHERITED.concat(['opacity']); + var DEFINITIONS = 'defs, symbol, clipPath, mask, pattern, marker, linearGradient, radialGradient'; + // What a page's table is called: boards and grids by role or class, and the public middle of a card-less table (a chain, a pool, + // a bid, a score card), never a hand or a secret. + var TABLE_SELECTOR = ['[role="grid"]', '.bg-board', '.wk-board', '.tf-board', '.su-board', '.fl-board', '.cw-grid', '.ms-board', '.sk-board', '.ec-board', + '.dm-table', '.mj-table', '.m4-pool', '#cb-rows', '#yc-card', '.ld-bid', '#stage', 'main > svg', 'main svg.board'].join(', '); + + function num(v) { return Math.round(v * 10) / 10; } + function esc(s) { return String(s).replace(/&/g, '&').replace(/ 3 ? parseFloat(p[3]) : 1; } + // A gradient's one colour: the second it names, which is the body of a lit disc (the first is its highlight). + function gradientColor(image) { + var all = (image || '').match(/rgba?\([^)]*\)/g); + return all ? all[Math.min(1, all.length - 1)] : ''; + } + function visible(cs, r) { return cs.display !== 'none' && cs.visibility !== 'hidden' && parseFloat(cs.opacity) > 0.02 && r.width > 0.5 && r.height > 0.5; } + function radius(cs, r) { + var v = parseFloat(cs.borderTopLeftRadius) || 0; + return /%/.test(cs.borderTopLeftRadius) ? Math.min(r.width, r.height) * v / 100 : Math.min(v, Math.min(r.width, r.height) / 2); + } + + // A piece that is an : its own drawing, with every colour as the page shows it (a var() resolved), at its place. + function pieceSvg(el, r, o) { + var clone = el.cloneNode(true), from = [el].concat([].slice.call(el.querySelectorAll('*'))), to = [clone].concat([].slice.call(clone.querySelectorAll('*'))); + for (var i = 0; i < from.length; i++) { + if (from[i] !== el && from[i].closest(DEFINITIONS)) continue; // what a or a gradient draws from keeps its own paint + var cs = root.getComputedStyle(from[i]), up = i ? root.getComputedStyle(from[i].parentElement) : null, st = ''; + // Only what differs from what the parent already passes down: a drawing's paint is mostly inherited. + INHERITED.forEach(function (p) { var v = cs.getPropertyValue(p); if (v !== (up ? up.getPropertyValue(p) : DEFAULT_PAINT[p])) st += p + ':' + v + ';'; }); + if (cs.opacity !== '1') st += 'opacity:' + cs.opacity + ';'; + if (cs.vectorEffect !== 'none') st += 'vector-effect:' + cs.vectorEffect + ';'; // a hairline that stays a hairline at any scale + if (/^(text|tspan)$/i.test(from[i].tagName)) TEXT_PROPS.forEach(function (p) { st += p + ':' + cs.getPropertyValue(p) + ';'; }); + to[i].removeAttribute('style'); to[i].removeAttribute('class'); + PAINT_ATTRS.forEach(function (a) { to[i].removeAttribute(a); }); // a var() in an attribute means nothing here: the style carries the colour + if (st) to[i].setAttribute('style', st); + } + if (!clone.getAttribute('viewBox')) clone.setAttribute('viewBox', '0 0 ' + (parseFloat(el.getAttribute('width')) || r.width) + ' ' + (parseFloat(el.getAttribute('height')) || r.height)); + clone.setAttribute('x', num(r.left - o.x)); clone.setAttribute('y', num(r.top - o.y)); + clone.setAttribute('width', num(r.width)); clone.setAttribute('height', num(r.height)); + clone.setAttribute('xmlns', SVG_NS); + return new root.XMLSerializer().serializeToString(clone).replace(/ xmlns="[^"]*"/, ''); + } + + function words(el, o) { + var out = ''; + for (var n = el.firstChild; n; n = n.nextSibling) { + if (n.nodeType !== 3 || !n.nodeValue.trim()) continue; + var rg = el.ownerDocument.createRange(); rg.selectNodeContents(n); + var r = rg.getBoundingClientRect(), cs = root.getComputedStyle(el); + if (r.width < 1 || r.height < 1) continue; + out += '' + esc(n.nodeValue.trim()) + ''; + } + return out; + } + + function children(el, o) { + var out = ''; + for (var c = el.firstElementChild; c; c = c.nextElementSibling) out += paint(c, o); + return out; + } + + function paint(el, o) { + var cs = root.getComputedStyle(el), r = el.getBoundingClientRect(); + if (cs.display === 'contents') return children(el, o); // a row that takes no room: its cells are the table's + if (!visible(cs, r) || cs.clip !== 'auto') return ''; // clip: rect(0 0 0 0) hides words kept for a screen reader + var out = '', x = num(r.left - o.x), y = num(r.top - o.y), rx = num(radius(cs, r)); + var shape = ' x="' + x + '" y="' + y + '" width="' + num(r.width) + '" height="' + num(r.height) + '" rx="' + rx + '"'; + var op = parseFloat(cs.opacity); + if (el.namespaceURI === SVG_NS && el.tagName.toLowerCase() === 'svg') return o.coarse ? '' : pieceSvg(el, r, o); // coarse: the bodies without their drawings + var fill = alpha(cs.backgroundColor) > 0 ? cs.backgroundColor : gradientColor(cs.backgroundImage); + if (fill) out += ''; + if (parseFloat(cs.borderTopWidth) > 0 && alpha(cs.borderTopColor) > 0 && cs.borderTopStyle !== 'none') { + var bw = parseFloat(cs.borderTopWidth); + out += ''; + } + out += words(el, o); + out += children(el, o); + return op < 0.98 ? '' + out + '' : out; + } + + function areaOf(e) { var r = e.getBoundingClientRect(); return r.width * r.height; } + // The board's own frame, wood and lines may sit round the element that holds its squares: climb to the outermost + // parent that is barely bigger, never as far as the page's main. + function framed(el) { + var a = areaOf(el); + while (el.parentElement && !/^(main|body|html)$/i.test(el.parentElement.tagName) && areaOf(el.parentElement) <= a * FRAME_GROWTH) el = el.parentElement; + return el; + } + // The element that is the table: the game says (ZimiShell.game({ table })), else the largest board-like thing on the page. + function findTable(doc, hint) { + var named = typeof hint === 'function' ? hint() : typeof hint === 'string' ? doc.querySelector(hint) : hint; + if (named) return named; + var best = null, area = 0; + [].forEach.call(doc.querySelectorAll(TABLE_SELECTOR), function (e) { + var a = areaOf(e); + if (a > area) { best = e; area = a; } + }); + return best && framed(best); + } + + // The table as an svg string 16 by 9, the table fitted whole on the page's own background; null when there is none. + function picture(doc, hint) { + var el = findTable(doc || root.document, hint); + if (!el) return null; + var r = el.getBoundingClientRect(); + if (r.width < 20 || r.height < 20) return null; + var k = Math.min((W - 2 * PAD) / r.width, (H - 2 * PAD) / r.height), o = { x: r.left, y: r.top }; + var bg = root.getComputedStyle(doc.body).backgroundColor, inner = paint(el, o); + if (inner.length > MAX_CHARS) { o.coarse = true; inner = paint(el, o); } // a heap of drawn tiles: keep their bodies and drop the faces + if (!inner || inner.length > MAX_CHARS) return null; + return '' + + '' + inner + ''; + } + + root.ZimiTableSnap = { picture: picture, findTable: findTable }; +})(typeof window !== 'undefined' ? window : this); diff --git a/zimi/builtin/games/yukon.html b/zimi/builtin/games/yukon.html new file mode 100644 index 000000000..b78c60f46 --- /dev/null +++ b/zimi/builtin/games/yukon.html @@ -0,0 +1,30 @@ + + + + + +Yukon + + + + + +
+ ‹ +

Yukon

+ + + + 0:00 +
+
+ + + + + + + + + + diff --git a/zimi/builtin/games/yukon.js b/zimi/builtin/games/yukon.js new file mode 100644 index 000000000..360bfd7a8 --- /dev/null +++ b/zimi/builtin/games/yukon.js @@ -0,0 +1,45 @@ +/* ZimiGames: Yukon. Seven columns: the first has one card, each next one a face-down card more, and five face up on every + column but the first. Build down in alternating colors, and move any face-up card with all the cards on it, in order or not. + Only a king fills an empty column. Four foundations build up by suit from the ace. No stock: every card is on the table. + The rules are the small facts below; ZimiSolKit writes the moves, the layout and the page. */ +(function (root) { + 'use strict'; + var Z = root.ZimiCards, K = root.ZimiSolKit; + + var TABLEAU = ['t0', 't1', 't2', 't3', 't4', 't5', 't6'], FOUNDATION = ['f0', 'f1', 'f2', 'f3']; + var COLS = 7, UP_DEALT = 5, FOUNDATION_COL = 3; + + var R = K.rules({ + tableau: TABLEAU, foundation: FOUNDATION, + runOK: function () { return true; }, + builds: Z.stacksOn, + emptyOK: function (id) { return Z.rank(id) === Z.KING; }, + whyBuild: 'sol.why.build', whyEmpty: 'sol.why.king' + }); + var blank = function () { return K.blankState(TABLEAU.concat(FOUNDATION)); }; + + // Column n gets n cards face down, then five face up (the first column just one). + function newState(order) { + var s = blank(), k = 0; + TABLEAU.forEach(function (t, n) { + var j; + for (j = 0; j < n; j++) s.piles[t].push(K.card(order[k++], false)); + for (j = 0; j < (n ? UP_DEALT : 1); j++) s.piles[t].push(K.card(order[k++], true)); + }); + return s; + } + + var place = K.layout({ + topRows: 1, + items: FOUNDATION.map(function (f, n) { return { pile: f, kind: 'foundation', col: FOUNDATION_COL + n, row: 0 }; }) + .concat(TABLEAU.map(function (t, n) { return { pile: t, kind: 'column', col: n, row: 1, n: n + 1 }; })) + }); + + var api = Object.assign(R, { newState: newState, blankState: blank, place: place, almostWon: function () { return K.almostWon(R, blank); } }); + root.ZimiYukon = api; + + function boot() { + K.page({ rules: R, id: 'yukon', title: 'Yukon', cols: COLS, place: place, auto: true, deal: function () { return newState(Z.shuffled(Z.random())); }, almostWon: api.almostWon }); + } + if (root.document && root.document.getElementById('zc-table')) boot(); +})(typeof globalThis !== 'undefined' ? globalThis : window);