diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index c2ed991..15242fc 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -3,19 +3,21 @@ name: Test and publish game on: push: branches: [main] + pull_request: + branches: [main] workflow_dispatch: permissions: contents: read concurrency: - group: github-pages + group: github-pages-${{ github.ref }} cancel-in-progress: true jobs: build: runs-on: ubuntu-latest - timeout-minutes: 15 + timeout-minutes: 25 steps: - name: Check out game uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 @@ -41,6 +43,7 @@ jobs: path: dist deploy: needs: build + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' runs-on: ubuntu-latest permissions: pages: write diff --git a/CHANGELOG.md b/CHANGELOG.md index d4804c1..b3d6e96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,33 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ## [Unreleased] +## [0.3.0] - 2026-10-05 + +### Added + +- Eighteen independent original puzzle games, each with 48 distinct deterministic levels and complete audited solutions: 864 new puzzles and 21 games on the illustrated home page. +- Atelier (3D screws and color boxes), Bobines (thread collection and waiting slots), and Escapade (creatures guided by either end to matching exits). +- Passages (sliding blocks and matching doors), Voyage (passengers, buses and five waiting seats), Carrousel (pixel cleanup and returning shooters), and Broderie (layered spools and triple-color embroidery). +- Alvéoles (hexagonal stack gathering and six-tile cascades), Potions (capacity-limited color pours), and Liaisons (non-crossing paths filling the grid). +- Nœuds (rope attachments, crossings and fixed anchors) and Gouttes (drawn ramps, gravity-driven water, obstacles and glass filling). +- Écluses (pin openings, ball coloring and bombs), Dunes (granular gravity and color bands spanning a tray), and Fringale (a growing hole, food sizes and narrow passages). +- Récolte (same-color chains and vertical gravity), Dizaines (equal or ten-sum number pairs with free sightlines), and Mosaïque (finite shape trios and simultaneous row/column clearing). +- Four chapter collections, independent validated replay saves, exact undo, restart, verified hints, optional sound, reduced-motion support and native mouse/touch plus alternative controls for every new game. +- Original scenes and home illustrations, reuse of collection art as pixel/cross-stitch pictures, animated boarding and conveyor laps, and water/sand simulations shared by live play and solution audits. +- All 22 HTML entry points included in production and portable builds; resource conservation, collision/failure recovery, malformed-action/save and responsive real-browser gameplay coverage. +- 18 original Colony pictures, bringing its collection to 24 motifs and a 96-puzzle opening journey. +- Five Colony difficulty chapters, larger boards, nested color layers, cooperating teams, paged collections, difficulty badges and seeded reserve variation beyond the opening journey. + +### Changed + +- Pull requests run the full puzzle/browser/build checks without deploying. Branch-specific workflow concurrency keeps reviews from cancelling a live Pages deployment. +- Colony sends one worker for every available matching cube, up to the remaining quota, with no four-worker cap. +- Ants use shared instanced meshes so large swarms keep a small number of draw calls. Colony hint search has a time budget to keep difficult positions responsive. + +### Fixed + +- Colony save migration preserves legacy boards, ongoing trips, undo and completion records when moving to the expanded journey. + ## [0.2.0] - 2026-10-04 ### Changed @@ -66,6 +93,7 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht - Arrows being generated with exits that ran into tunnel walls or other solid geometry. - Asset paths and the home link when hosted under a GitHub Pages repository path. -[Unreleased]: https://github.com/boubou666/CubeCubeCube/compare/v0.2.0...HEAD +[Unreleased]: https://github.com/boubou666/CubeCubeCube/compare/v0.3.0...HEAD +[0.3.0]: https://github.com/boubou666/CubeCubeCube/compare/v0.2.0...v0.3.0 [0.2.0]: https://github.com/boubou666/CubeCubeCube/compare/v0.1.0...v0.2.0 [0.1.0]: https://github.com/boubou666/CubeCubeCube/releases/tag/v0.1.0 diff --git a/README.md b/README.md index 4e69a09..7f1e82d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Cube Cube Cube -A small collection of relaxing browser puzzles, built with Three.js, vanilla JavaScript, and Vite. The home page offers illustrated cards for the 3D cube, 2D picture puzzles, and a 3D ant colony. No account, advertising, timers, or move limits. +A small collection of relaxing browser puzzles, built with Three.js, vanilla JavaScript, and Vite. The home page offers twenty-one illustrated cards: the 3D cube, 2D picture puzzles, a 3D ant colony, Atelier, Bobines, Escapade, Passages, Voyage, Carrousel, Broderie, Alvéoles, Potions, Liaisons, Nœuds, Gouttes, Écluses, Dunes, Fringale, Récolte, Dizaines, and Mosaïque. No account, advertising, timers, or move limits. **[Play online](https://boubou666.github.io/CubeCubeCube/)** · **[Source code](https://github.com/boubou666/CubeCubeCube)** @@ -8,11 +8,15 @@ A small collection of relaxing browser puzzles, built with Three.js, vanilla Jav **[Play the cube](https://boubou666.github.io/CubeCubeCube/cube.html)** · **[Play Colony](https://boubou666.github.io/CubeCubeCube/colony.html)** +**[Play Atelier](https://boubou666.github.io/CubeCubeCube/atelier.html)** · **[Play Bobines](https://boubou666.github.io/CubeCubeCube/bobines.html)** · **[Play Escapade](https://boubou666.github.io/CubeCubeCube/escapade.html)** + +**[Play Passages](https://boubou666.github.io/CubeCubeCube/passages.html)** · **[Play Voyage](https://boubou666.github.io/CubeCubeCube/voyage.html)** · **[Play Carrousel](https://boubou666.github.io/CubeCubeCube/carrousel.html)** · **[Play Broderie](https://boubou666.github.io/CubeCubeCube/broderie.html)** + **[Changelog](CHANGELOG.md)** · **[Releases](https://github.com/boubou666/CubeCubeCube/releases)** ## Publishing -GitHub Pages serves the production build. Every push to `main` runs the puzzle tests and Chromium gameplay tests, then builds and deploys the game through `.github/workflows/pages.yml`. The workflow supplies the repository base path to Vite, so assets and the home link work under `/CubeCubeCube/`. It can also be run manually from GitHub Actions. +GitHub Pages serves the production build. Pull requests run the puzzle tests, Chromium gameplay tests and production build without deploying. Every push to `main` runs those checks, then deploys the game through `.github/workflows/pages.yml`. The workflow supplies the repository base path to Vite, so assets and the home link work under `/CubeCubeCube/`. It can also be run manually from GitHub Actions. ## Releases and changelog @@ -90,6 +94,14 @@ The tests verify the 28 opening solutions and generated samples across early, la ## Structure - `src/home-main.js`, `src/home-style.css`: illustrated home cards and links to each independent game. +- `src/pocket-main.js`, `src/pocket-style.css`: shared shell for Atelier, Bobines, and Escapade, with chapter collections, controls, optional audio, progress, and independent saves. +- `src/pocket-core.js`: deterministic helpers, transactional undo, bounded solution search and validated save replay. +- `src/atelier-puzzle.js`, `src/bobines-puzzle.js`, `src/escapade-puzzle.js`: separate discrete rules and guaranteed-solution construction for 48 levels per game. +- `src/atelier-scene.js`: Three.js stacked assemblies, occlusion-aware screw picking, orbit controls, unscrewing and departing plate animation. +- `src/pocket-canvas.js`, `src/pocket-previews.js`: original thread and creature rendering, touch picking, winding/exit animation and home illustrations. +- `src/suite-main.js`, `src/suite-style.css`, `src/suite-canvas.js`, `src/suite-previews.js`: the next four games' shared interface, Canvas scenes, animations, touch picking and illustrated home cards. +- `src/passages-puzzle.js`, `src/voyage-puzzle.js`, `src/carrousel-puzzle.js`, `src/broderie-puzzle.js`: independent rule models and audited generators for another 192 puzzles. +- `src/picture-art.js`: sampling the project's original collection illustrations and computing outside-connected pixel accessibility. - `src/colony-puzzle.js`: outside-space reachability, color quotas, guaranteed-solution level construction, five-slot simulation, hints, undo, and validated saves. - `src/colony-scene.js`: Three.js pixel cubes, original ant meshes, path-following pickup/return animation, and a garden tray. - `src/colony-main.js`, `src/colony-style.css`: Colony controls, queues, collection, responsive layouts, and independent local-storage progress. @@ -121,10 +133,74 @@ The game implements the described mechanics with its own branding, art, and leve Open `colony.html`, choose **Colony** from either game's navigation, or use its home card. This original implementation takes inspiration from [Colony Flow's color-box and ant collection mechanics](https://play.google.com/store/apps/details?id=com.abi.colony.flow). The artwork, levels, interface and models are created for this project. -Select the top box of one of four queues. It occupies one of five active slots and sends up to four workers to cubes of its color. Only cubes adjacent to outside-connected empty space are accessible; enclosed holes remain blocked. Workers follow those empty corridors, remove a cube on arrival and carry it back. The box counter decreases on delivery, and a filled box releases its slot. Boxes whose color is still buried wait. Five waiting boxes cause a deadlock; undo is always available. +Select the top box of one of four queues. It occupies one of five active slots and sends a worker to every accessible matching cube, up to its remaining quota; there is no fixed worker cap. Only cubes adjacent to outside-connected empty space are accessible; enclosed holes remain blocked. Workers follow those empty corridors, remove a cube on arrival and carry it back. Newly exposed matching cubes receive workers on the next simulation update. The box counter decreases on delivery, and a filled box releases its slot. Boxes whose color is still buried wait. Five waiting boxes cause a deadlock; undo is always available. Shared instanced meshes render large swarms with fourteen ant-part draws instead of one mesh per worker part. -Six 16×16 original pictures introduce the game: a plant, mushroom, fox, rocket, ice cream and flower. Later numbered puzzles add borders and smaller color quotas. Reserves are generated from a complete legal harvest sequence, with exact totals for every color. The collection shows twelve puzzles around the current journey page, and a number field allows jumping up to puzzle 1,000,000. +Twenty-four original pictures include the first six motifs plus a butterfly, fish, bee, cup, strawberry, sailboat, castle, cat, owl, cactus, turtle, balloon, snowflake, crab, bird, lighthouse, cherries and planet. The 96-puzzle opening journey introduces five chapters: Découverte (1–6), Malin (7–24), Corsé (25–48), Difficile (49–72) and Expert (73 onward). Boards grow from 16×16 to 24×24. Nested rings, repeated colors and quotas that span buried regions require teams to wait for other colors; the audited route can coordinate four occupied slots on expert boards. Every reserve is constructed through an actual complete simulation, with exact color totals and at least one legal solution. Later numbered boards use seeded reserve arrangements, mirrored art and expert accents. Collection paging and chapter buttons let players explore twelve puzzles at a time; the number field supports puzzle 1,000,000. Use **Un petit indice** for a move verified by a bounded state search, **Annuler** to restore the complete previous state, and **Recommencer** to reset the same puzzle. Pause and ×2 change the animation pace. H asks for a hint, Enter sends the indicated box, U undoes, R restarts, 1–4 choose a queue, and Space pauses when the canvas is focused. Dialogs and hidden tabs suspend simulation. -Colony uses its own versioned local-storage key. Saves include queue positions, active boxes, trips in progress, undo states, completed puzzles and speed. Invalid saves fall back to the first puzzle. Storage failures do not prevent playing. Cube and picture progress remain independent. The static build includes `index.html`, `cube.html`, `image.html` and `colony.html`, with links compatible with the configured GitHub Pages base path. +Colony uses its own versioned local-storage key. Saves include the generator version, queue positions, active boxes, trips in progress, undo states, completed puzzles and speed. Older saves retain their exact original board and undo history, including after restart. Starting another puzzle uses the new generator. Invalid saves fall back to the first puzzle. Storage failures do not prevent playing. Cube and picture progress remain independent. The static build includes `index.html`, `cube.html`, `image.html` and `colony.html`, with links compatible with the configured GitHub Pages base path. + +## Atelier, Bobines and Escapade + +The three new games have **48 distinct, deterministic puzzles each**, split into four chapters of twelve. All chapters are directly accessible from the collection. Each board is constructed with a complete legal solution; automated tests replay all 144 solutions and verify that difficulty grows through larger assemblies, deeper thread lines, more colors, larger gardens and longer creatures. They are original implementations inspired respectively by [Screwdom 3D](https://play.google.com/store/apps/details?id=com.ig.screwdom), [Knit Out](https://play.google.com/store/apps/details?id=com.sbg.knitout) and [Gecko Out](https://play.google.com/store/apps/details?id=com.dalakgames.slitherrush), with original names, graphics, layouts and levels. + +- **Atelier (`atelier.html`)**: remove the exposed screws from stacked 3D plates. Each plate has three screws; removing them reveals the plate below. Two active boxes collect three screws of their color and advance through a visible reserve. Unmatched screws wait in four or five buffer positions. Waiting screws automatically enter a compatible box as it appears. A move exceeding the buffer capacity is rejected without changing the board. Drag to orbit, scroll to zoom, or use the accessible screw buttons. Assemblies grow from two short stacks to three larger stacks. +- **Bobines (`bobines.html`)**: launch the first bobbin in one of four queues into one of three active slots. It winds accessible knots of its color from the tops of the thread lines, up to its quota. Newly exposed matching knots are wound too. A bobbin whose color is buried waits; filling all three slots with waiting bobbins blocks further launches. Full bobbins release their slots. The generator simulates a complete peeling order, gives each bobbin an exact quota and distributes that proven order across the queues. Boards grow from three short thread lines to six deeper lines and six colors. +- **Escapade (`escapade.html`)**: select a creature's head or tail and drag it through adjacent cells, or click an end then a neighboring cell. The body follows. Reach the matching boundary hole to remove that creature; hedges, other creatures, and other colors' holes block movement. The departing tail cell may be entered on the same move. Click a creature button to select its head; the end-switch button selects its tail. Arrow keys and direction buttons also work. Gardens grow from 6×6 with three creatures to 9×9 with six. Construction grows paths outward from reserved exits, places non-overlapping bodies, then audits the reverse order for a complete route. + +All three support **H** for a hint, **Enter** to execute it, **U** to undo, and **R** to restart. Bobines also accepts **1–4** for the queue. Sounds are optional. There are no timers, lives, ads or paid tools. Hints first reuse the proven route when possible; otherwise they search the current board within a bounded budget and only highlight a move when a full remaining solution is verified. When that search finds no complete route, the hint offers undo instead of an unverified move. This does not claim that the current position is mathematically impossible. + +Each game has its own `cubecubecube--v1` local-storage key, holding the generator version, current level, replayable move history, completion badges and audio setting. Reload restores both the exact board and undo; restart retains the same level. Invalid saves fall back to puzzle 1. Storage failure does not prevent play. Completion badges survive replay and undo. Saves stay local to this browser. + +All twenty-two HTML entry points (home plus twenty-one games) are included in the Vite production build and portable release archive. The Canvas games do not load Three.js; Atelier loads its 3D renderer dynamically. Tests cover all new construction routes, collisions, waiting slots, save corruption, replay, undo, actual pointer play, complete first-level play, collection chapters, reload and 1440px/390px/320px layouts. + +## Passages, Voyage, Carrousel and Broderie + +Four further games add **48 distinct puzzles each** in the same four chapter collections. Along with the first trio, these seven additions contain **336 audited puzzles**. Saves and completion badges remain separate for every game. + +- **Passages (`passages.html`)**, inspired by [Color Block Jam](https://play.google.com/store/apps/details?id=com.GybeGames.ColorBlockJam): slide rectangular blocks in the garden toward their own matching boundary doors. The whole block must fit the opening. Neighbors, hedges and closed boundaries block movement. Choose a block in the scene or sidebar, then drag or use arrows/direction buttons. Construction starts at valid exits, walks each new rectangle through currently free space, then records the reverse placement order as a full solution. Boards grow from three blocks on 6×6 gardens to six larger blocks on 8×8 gardens. Hints search actual rectangle placements and verify that all remaining blocks can exit; if no full route is found, they offer undo. +- **Voyage (`voyage.html`)**, inspired by [Bus Jam](https://play.google.com/store/apps/details?id=com.nt.games.busjam): pick travelers who can reach the bottom platform through empty corridors. The current bus takes its own color; other travelers wait on a five-seat bench. Full buses depart, and waiting travelers automatically board subsequent matching buses. Upcoming color tickets and exact capacities are visible. Each reserve is colored using an actual outside-accessible removal sequence, so every passenger has a boarding route and every color total matches the buses exactly. Larger chapters add longer halls, larger passenger groups, more colors and furniture that shapes the paths. +- **Carrousel (`carrousel.html`)**, inspired by [Pixel Flow!](https://play.google.com/store/apps/details?id=com.loomgames.pixelflow): launch a small shooter from the first position of one of four queues. A discrete lap removes outside-accessible pixels of that color, up to its ammunition and the per-lap shot limit. A shooter with ammunition left returns to one of five waiting slots; click it to send it on another lap once its targets are exposed. A full reserve blocks new launches. Fruitless waiting-shooter relaunches are rejected without changing progress. Pixel and ammunition totals are conserved by color, and every reserve has a complete route including relaunches. Images grow from 10×10 to 16×16, using the project's own original art. +- **Broderie (`broderie.html`)**, inspired by [Thread Jam](https://play.google.com/store/apps/details?id=com.sewing.jam): take exposed spools from a layered pile into a seven-slot workbench. Three spools of one color stitch an exact section of the picture and release their three slots. Covered spools remain unavailable until upper layers are removed. Picture sections form a disjoint partition of every pixel, with one triple per section. Construction colors an audited top-down removal route in triples, guaranteeing a complete arrangement without paid tools. Chapters grow from 24 to 57 spools and deeper piles. Original collection pictures appear as animated cross-stitch illustrations. + +All four accept **H**, **Enter**, **U** and **R** for hint, execute hint, undo and restart. Carrousel also accepts **1–4** for launch queues; Passages accepts arrow keys. They share the same optional sound, reduced-motion support, exact move-replay saves, chapter collection and local progress behavior as the first trio. Tests replay all 192 added solutions, check collisions and outside reachability, conserve passengers/ammunition/stitch patches, reject corrupted saves, and verify actual mouse/touch-sized layouts and complete browser gameplay. + +## Alvéoles, Potions and Liaisons + +Three more independent games provide **48 distinct, deterministic levels each** and four directly accessible chapters. Along with the previous seven additions, they contain **480 audited puzzles**. They use the same independent replay saves, optional sound, undo, restart, completion badges and verified hints. + +- **Alvéoles (`alveoles.html`)**, inspired by [Hexa Sort](https://play.google.com/store/apps/details?id=com.gamebrain.hexasort): choose the head stack of one of three queues, then place it on an empty hexagonal cell. Connected matching top runs gather onto the newly placed stack. Groups of six disappear, potentially revealing further matching layers and causing a cascade. Covered layers remain on their own cells. Use all queued stacks and empty the board. The generator reserves connected placement chains and audits every complete route. Chapters introduce two placements per group, three colored layers, and larger 37-cell hives. **1–3** selects queues; both scene and numbered cell buttons accept placement. +- **Potions (`potions.html`)**, inspired by [Magic Sort!](https://play.google.com/store/apps/details?id=com.grandgames.magicsort): select a source vial, then pour into another vial with the same top color or into an empty one. Each vial holds four doses; a pour transfers the maximal top run that fits. Finish with one full vial per color and empty reserves. Boards grow from three to six colors. Construction reverses only pours whose exact inverse is legal, then trims the audited route at its first solved state. **1–8** selects source/destination vials; invalid pours leave every drop in place. +- **Liaisons (`liaisons.html`)**, inspired by [Flow Free](https://play.google.com/store/apps/details?id=com.bigduckgames.flow): draw orthogonal paths between matching endpoints without crossing other paths or foreign endpoints. Connecting every pair is insufficient unless every cell is also covered. Grids grow from 4×4 with three pairs to 7×7 with six pairs. Randomized Hamiltonian backbite moves build varied full-grid routes, partitioned into colored paths. Mouse/touch strokes support backtracking and are one undoable action; sidebar cells and arrow keys offer alternative tracing. Hints explicitly clear conflicting strokes before suggesting verified complete paths. + +Rule tests audit all 144 routes, color and tile conservation, maximal pours, blocked and crossing moves, full-grid completion, hint edits, corruption and exact replay. Browser tests exercise pointer and native touch input, keyboard tracing, complete games, reload, next levels, all chapter boundaries, and desktop/390px/320px layout checks. + +## Nœuds and Gouttes + +These two games have **48 distinct, deterministic, audited levels each**, for **96 puzzles**. They keep independent replay saves, optional sound, four chapter collections, undo, hints, restart and completion badges. + +- **Nœuds (`noeuds.html`)**, inspired by [Twisted Tangle](https://play.google.com/store/apps/details?id=com.crescivegames.twistedtangle): drag rope attachments between free plots until no two taut cords cross, overlap or touch. Later chapters add more cords, larger gardens and fixed screw attachments. Plot occupancy and fixed anchors are enforced transactionally. The generator builds a separated arrangement, scrambles the movable pins, then audits a complete untangling route. Any crossing-free arrangement wins. Hints can move an occupied target's neighbor into a spare plot before placing the chosen attachment. Scene dragging, click-then-place and numbered sidebar controls all work. Each drag is one undoable move. +- **Gouttes (`gouttes.html`)**, inspired by [Happy Glass](https://play.google.com/store/apps/details?id=com.game5mobile.lineandwater): draw static ramps with the mouse or finger, then choose **Laisser couler** or press **E**. Sixty deterministic water particles fall under gravity, collide with the actual drawn segments and solid obstacles, and slide into the glass. Goals rise from 48 to 54 drops; expert routes reverse direction using two ramps. Every generated solution is audited using the same fixed-step particle simulation used for live play; an empty drawing is also checked to ensure the level needs a ramp. Strokes cannot cross obstacles, leave the drawing area or exceed the ink reserve. Collinear samples are simplified for smooth sliding. An alternative point editor supports drawing without dragging. + +Gouttes animates the same deterministic simulation after committing a verified trial. Drawing is locked while water runs; undo cancels the animation and restores the exact pre-trial drawing. A failed trial can be saved, reloaded, undone or corrected without a life limit. Hidden tabs and open dialogs suspend the visible water simulation; reduced motion shows the result directly. Hints may clear a custom drawing before proposing the audited ramps and opening the tap. Rule tests audit all 96 levels, rope geometry, occupied/fixed plots, water conservation at every tick, actual fluid results, forbidden strokes, ink usage, failed trials, save replay and undo. Browser tests cover real mouse/touch dragging, hand-drawn water success, cancellation during a live stream, point-editor input, expert routes, collections and desktop/390px/320px layouts. + +## Écluses, Dunes and Fringale + +These three games provide **48 distinct, deterministic, audited levels each**, for **144 puzzles**. Every game has four chapters, independent local saves, exact undo, restart, optional sound, reduced-motion support and verified hints. Their names, illustrations and levels are original. + +- **Écluses (`ecluses.html`)**, inspired by [Pull the Pin](https://play.google.com/store/apps/details?id=com.maroieqrwlk.unpin): remove permanent goupilles to drain balls through connected basins. Gray balls acquire color when mixed with colored balls. All ordinary balls must reach the basket intact and colored; premature outlets lose gray balls, and bomb routes destroy their neighbors. Later chapters add parallel feeders, a shared final basin and a tempting bomb opening. Mouse/touch pin picking, numbered sidebar buttons and **1–9** operate the openings. Invalid repeats leave the state intact; a destructive opening remains undoable. +- **Dunes (`dunes.html`)**, inspired by [Sand Blast](https://play.google.com/store/apps/details?id=com.inspiredsquare.sand.blast): choose a queue head and a drop column. Its blocks become grains that fall and slide diagonally around other grains and fixed stones. Any connected region of one color touching both tray edges clears entirely, including curved bands. Chapters add more bands, wider trays, shapes and central stones. Generation audits actual drops using the same fixed-step `SandFlow` simulation as the animation. Input locks during gravity, undo cancels it, and reduced motion resolves the drop immediately. **1–3**, arrow keys and **Space** provide keyboard placement. +- **Fringale (`fringale.html`)**, inspired by [All in Hole](https://play.google.com/store/apps/details?id=com.homagames.studio.allinhole): guide a hole under berries, fruit, cakes and flowerpots. Each swallowed object adds mass and increases the radius; an object must fit fully. Hedges enforce continuous collisions, and growth can prevent returning through narrow gates. Empty the small court before collecting larger food outside. Dragging records one undoable gesture; clicking an object seeks an actual route around walls, and arrow keys offer manual motion. Every level is replayed through real movement and growth, and hints verify a complete remaining tour or suggest undoing a blocked detour. + +Rule tests replay all 144 routes, check deterministic distinctness, preserve balls/grains/food mass, audit live sand steps and rocks, reject malformed actions and saves, verify bomb/loss recovery, and enforce hole size, growth and wall collisions. Browser tests cover actual pointer and native touch play, keyboard alternatives, full first levels, exact reload/undo, animation cancellation, expert collections, navigation and 1440px/390px/320px layouts. Shared rendering, controls and original home previews live in `src/harvest-{canvas,config,style,previews}`; the three puzzle modules remain independent of the DOM. + +## Récolte, Dizaines and Mosaïque + +The remaining trio provides **48 distinct, deterministic, audited levels each**, bringing the collection to **twenty-one games** and the eighteen additions to **864 puzzles**. The same four chapters, independent saves, complete undo, verified hints, optional sound and reduced-motion support remain available. + +- **Récolte (`recolte.html`)**, inspired by [Collect Em All!](https://play.google.com/store/apps/details?id=com.tarboosh.collectemall): trace three or more adjacent balls of one color, including diagonals. Repeated cells are forbidden and backtracking shortens the current stroke. Clearing a chain fills its color basket and makes remaining balls fall vertically; the finite garden has no random refill or move limit. Empty every color quota. Reverse gravity construction adds each connected chain above an already packed garden, proving a complete forward route. Chapters add larger gardens, longer chains and more colors. Mouse/touch strokes count as one move; sidebar tracing, **Enter** and **Escape** offer an alternative. +- **Dizaines (`dizaines.html`)**, inspired by [Woodber](https://play.google.com/store/apps/details?id=and.lihuhu.woober): remove two equal numbers or a pair totaling ten. Their horizontal, vertical or diagonal line must contain only empty cells. Consecutive remaining numbers in reading order may also connect across row boundaries. Empty every tile without adding new rows. Rows keep their positions, making long gaps visible. Reverse pair insertion records a complete audited removal route; larger grids introduce more number combinations. Both the wooden scene and the sidebar support selecting and cancelling a first number. +- **Mosaïque (`mosaique.html`)**, inspired by [Block Blast!](https://play.google.com/store/apps/details?id=com.block.juggle): choose any of three available fixed-orientation shapes and place it on empty cells. Full rows and columns clear simultaneously, with intersection tiles counted once. A new trio unlocks only after all three current pieces have been placed. Use the finite reserve and leave the whole board empty. Audited reserves cover row bands, with wider boards and five-square pieces in later chapters. Drag from the tray or choose a shape and an origin cell; **1–3**, arrow keys and **Space** also place pieces. + +The independent `src/{recolte,dizaines,mosaique}-puzzle.js` modules contain the rules and generators. `src/bounty-{canvas,config,style,previews}` renders the scenes and original home illustrations. Rule checks audit every complete route and chapter hint, preserve balls/numbers/tiles, enforce chain adjacency and number sightlines, verify simultaneous clears and finite trios, and round-trip saves and undo. Browser coverage includes mouse/native touch play, sidebar/keyboard alternatives, first and final-level completion, exact reload, navigation, and 1440px/390px/320px layouts. diff --git a/alveoles.html b/alveoles.html new file mode 100644 index 0000000..74e59f5 --- /dev/null +++ b/alveoles.html @@ -0,0 +1 @@ +Alvéoles — Cube Cube Cube
diff --git a/atelier.html b/atelier.html new file mode 100644 index 0000000..68a2b73 --- /dev/null +++ b/atelier.html @@ -0,0 +1,2 @@ + +Atelier — Cube Cube Cube
diff --git a/bobines.html b/bobines.html new file mode 100644 index 0000000..16dcbc6 --- /dev/null +++ b/bobines.html @@ -0,0 +1,2 @@ + +Bobines — Cube Cube Cube
diff --git a/broderie.html b/broderie.html new file mode 100644 index 0000000..b340628 --- /dev/null +++ b/broderie.html @@ -0,0 +1 @@ +Broderie — Cube Cube Cube
diff --git a/carrousel.html b/carrousel.html new file mode 100644 index 0000000..2d4fd8a --- /dev/null +++ b/carrousel.html @@ -0,0 +1 @@ +Carrousel — Cube Cube Cube
diff --git a/dizaines.html b/dizaines.html new file mode 100644 index 0000000..e3fb77e --- /dev/null +++ b/dizaines.html @@ -0,0 +1 @@ +Dizaines — Cube Cube Cube
diff --git a/dunes.html b/dunes.html new file mode 100644 index 0000000..e3f1a9c --- /dev/null +++ b/dunes.html @@ -0,0 +1 @@ +Dunes — Cube Cube Cube
diff --git a/ecluses.html b/ecluses.html new file mode 100644 index 0000000..1355f20 --- /dev/null +++ b/ecluses.html @@ -0,0 +1 @@ +Écluses — Cube Cube Cube
diff --git a/escapade.html b/escapade.html new file mode 100644 index 0000000..1ecd133 --- /dev/null +++ b/escapade.html @@ -0,0 +1,2 @@ + +Escapade — Cube Cube Cube
diff --git a/fringale.html b/fringale.html new file mode 100644 index 0000000..f501a28 --- /dev/null +++ b/fringale.html @@ -0,0 +1 @@ +Fringale — Cube Cube Cube
diff --git a/gouttes.html b/gouttes.html new file mode 100644 index 0000000..39391b1 --- /dev/null +++ b/gouttes.html @@ -0,0 +1 @@ +Gouttes — Cube Cube Cube
diff --git a/liaisons.html b/liaisons.html new file mode 100644 index 0000000..a1bd1ae --- /dev/null +++ b/liaisons.html @@ -0,0 +1 @@ +Liaisons — Cube Cube Cube
diff --git a/mosaique.html b/mosaique.html new file mode 100644 index 0000000..7584804 --- /dev/null +++ b/mosaique.html @@ -0,0 +1 @@ +Mosaïque — Cube Cube Cube
diff --git a/noeuds.html b/noeuds.html new file mode 100644 index 0000000..69e8dd2 --- /dev/null +++ b/noeuds.html @@ -0,0 +1 @@ +Nœuds — Cube Cube Cube
diff --git a/package-lock.json b/package-lock.json index 6db7ef8..64289ec 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "cubecubecube", - "version": "0.2.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "cubecubecube", - "version": "0.2.0", + "version": "0.3.0", "dependencies": { "three": "0.186.1" }, diff --git a/package.json b/package.json index 49e4b4f..d31477b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cubecubecube", - "version": "0.2.0", + "version": "0.3.0", "private": true, "type": "module", "scripts": { diff --git a/passages.html b/passages.html new file mode 100644 index 0000000..cdd719f --- /dev/null +++ b/passages.html @@ -0,0 +1 @@ +Passages — Cube Cube Cube
diff --git a/potions.html b/potions.html new file mode 100644 index 0000000..d98322d --- /dev/null +++ b/potions.html @@ -0,0 +1 @@ +Potions — Cube Cube Cube
diff --git a/recolte.html b/recolte.html new file mode 100644 index 0000000..08bce6c --- /dev/null +++ b/recolte.html @@ -0,0 +1 @@ +Récolte — Cube Cube Cube
diff --git a/src/alveoles-puzzle.js b/src/alveoles-puzzle.js new file mode 100644 index 0000000..a51a9e0 --- /dev/null +++ b/src/alveoles-puzzle.js @@ -0,0 +1,57 @@ +import { checkIndex, clone, random, shuffle, searchPlan } from './pocket-core.js'; + +const DIRS = [[1,0],[0,1],[-1,1],[-1,0],[0,-1],[1,-1]]; +const TITLES = ['La première ruche','Un peu de miel','Les voisines','La couleur du dessus','Les petites piles','Une place au soleil','Le jardin hexagonal','Sous les couleurs','De proche en proche','Les grandes fusions','Un dernier emplacement','La ruche tranquille']; +export const topRun = stack => {let n=0;for(let i=stack.length-1;i>=0&&stack[i]===stack.at(-1);i--)n++;return n;}; +export function hexNeighbors(level, id) { + const [q,r]=level.cells[id];return DIRS.map(([dq,dr])=>level.cells.findIndex(([x,y])=>x===q+dq&&y===r+dr)).filter(n=>n>=0); +} +function settle(level, stacks, target) { + let cleared=0; + while (stacks[target].length) { + const color=stacks[target].at(-1), seen=new Set([target]), queue=[target]; + for(let n=0;n({stacks:clone(level.stacks),queues:[0,0,0],cleared:0}); +const won=(level,state)=>state.stacks.every(s=>!s.length)&&level.queues.every((q,i)=>state.queues[i]===q.length); +export function createAlveolesLevel(index) { + checkIndex(index);const tier=Math.floor(index/12),radius=tier>1?3:2,rng=random(13967+index*8731),groups=3+tier; + const cells=[];for(let r=-radius;r<=radius;r++)for(let q=-radius;q<=radius;q++)if(Math.abs(q+r)<=radius)cells.push([q,r]); + for(let attempt=0;attempt<200;attempt++) { + const level={index,tier,title:TITLES[index%12],radius,cells,stacks:cells.map(()=>[]),queues:[[],[],[]],solution:[]}; + const reserved=new Set(),colors=shuffle([0,1,2,3,4,5,6,7],rng); + let failed=false; + for(let group=0;group1||tier===1&&group%2===0?2:1,depth=1+Math.min(tier,2),unit=6/(turns+1); + const choices=shuffle(cells.map((_,id)=>id).filter(id=>!reserved.has(id)),rng);let zone; + for(const seed of choices){const a=shuffle(hexNeighbors(level,seed).filter(id=>!reserved.has(id)),rng)[0];if(a===undefined)continue;const b=turns===2?hexNeighbors(level,a).find(id=>id!==seed&&!reserved.has(id)):undefined;if(turns===2&&b===undefined)continue;zone=[seed,a,...(turns===2?[b]:[])];break;} + if(!zone){failed=true;break;}zone.forEach(id=>reserved.add(id)); + const layers=Array.from({length:depth},(_,n)=>colors[(group+depth-1-n)%colors.length]); + const stack=layers.flatMap(color=>Array(unit).fill(color));level.stacks[zone[0]]=[...stack]; + for(const cell of zone.slice(1)){const q=Math.floor(rng()*3);level.queues[q].push([...stack]);level.solution.push({q,cell});} + } + if(failed)continue; + let state=initial(level);for(const action of level.solution){state=move(level,state,action);if(!state)break;} + if(state&&won(level,state))return level; + } + throw new Error('Could not build hexagonal groups'); +} +export const alveolesRules={ + create:createAlveolesLevel,initial,move,won, + actions(level,state){ + const actions=[]; + for(let q=0;q<3;q++){const stack=level.queues[q][state.queues[q]];if(!stack)continue;for(let cell=0;cellstate.stacks[id].at(-1)===stack.at(-1)).length});}} + return actions.sort((a,b)=>b.score-a.score).map(a=>a.action); + }, + plan:(level,state)=>searchPlan(alveolesRules,level,state,15000), +}; diff --git a/src/atelier-puzzle.js b/src/atelier-puzzle.js new file mode 100644 index 0000000..4b095b8 --- /dev/null +++ b/src/atelier-puzzle.js @@ -0,0 +1,58 @@ +import { checkIndex, clone, random, shuffle } from './pocket-core.js'; + +const TITLES = ['Les petites planches', 'Le moulin', 'Le pont', 'Les ailes', 'La maisonnette', 'Le carrousel', 'Le jardin suspendu', 'Les terrasses', 'La cabane', 'Le belvédère', 'Les trois ateliers', 'Le grand assemblage']; +export function createAtelierLevel(index) { + checkIndex(index); const rng = random(18741 + index * 7919), tier = Math.floor(index / 12); + const stacks = tier < 2 ? 2 : 3, count = 4 + tier * 2 + (index % 3 === 2 ? 2 : 0); + const colors = shuffle([0, 1, 2, 3, 4, 5], rng).slice(0, Math.min(3 + tier, 6)); + const plates = [], screws = [], solution = [], boxes = [], heights = Array(stacks).fill(0); + // First construct a legal dismantling order, then stack it in reverse. + const order = Array.from({ length: count }, (_, i) => ({ stack: (i + Math.floor(index / 3)) % stacks, pair: Math.floor(i / 2), half: i % 2 })); + const pairColors = Array.from({ length: count / 2 }, (_, i) => { + const a = colors[(i * 2) % colors.length], b = colors[(i * 2 + 1) % colors.length]; boxes.push(a, b); return [a, b]; + }); + for (let i = count - 1; i >= 0; i--) { + const item = order[i], [a, b] = pairColors[item.pair], plate = { id: i, stack: item.stack, layer: heights[item.stack]++, screws: [], style: (index + i) % 4 }; + const cs = shuffle(item.half ? [b, a, b] : [a, b, a], rng); + for (let j = 0; j < 3; j++) { const id = screws.length; screws.push({ id, plate: i, color: cs[j], position: j }); plate.screws.push(id); } + plates.push(plate); + } + for (let i = 0; i < count; i++) solution.push(...plates.find(p => p.id === i).screws); + return { index, title: TITLES[index % 12], tier, stacks, plates, screws, boxes, solution, bufferSize: tier < 2 ? 5 : 4 }; +} +function settle(level, state) { + let changed = true; + while (changed) { + changed = false; + for (const box of state.trays) { + if (!box) continue; + for (let i = state.buffer.length - 1; i >= 0 && box.count < 3; i--) if (state.buffer[i] === box.color) { state.buffer.splice(i, 1); box.count++; changed = true; } + } + for (let i = 0; i < state.trays.length; i++) if (state.trays[i]?.count === 3) { + state.trays[i] = state.nextBox < level.boxes.length ? { color: level.boxes[state.nextBox++], count: 0 } : null; changed = true; + } + } +} +export function exposedPlate(level, state, plate) { + return !level.plates.some(p => p.stack === plate.stack && p.layer > plate.layer && p.screws.some(id => !state.removed.includes(id))); +} +export const atelierRules = { + create: createAtelierLevel, + initial: level => ({ removed: [], buffer: [], nextBox: 2, trays: level.boxes.slice(0, 2).map(color => ({ color, count: 0 })) }), + won: (level, state) => state.removed.length === level.screws.length && state.buffer.length === 0, + actions(level, state) { + const seen = new Set(); + return level.screws.filter(s => { + const key = `${s.plate}:${s.color}`; + if (state.removed.includes(s.id) || !exposedPlate(level, state, level.plates.find(p => p.id === s.plate)) || seen.has(key)) return false; + seen.add(key); return true; + }).sort((a, b) => Number(state.trays.some(t => t?.color === b.color)) - Number(state.trays.some(t => t?.color === a.color))).map(s => s.id); + }, + move(level, state, id) { + const screw = level.screws[id]; if (!Number.isInteger(id) || !screw || state.removed.includes(id)) return null; + if (!exposedPlate(level, state, level.plates.find(p => p.id === screw.plate))) return null; + const next = clone(state); next.removed.push(id); next.buffer.push(screw.color); settle(level, next); + if (next.buffer.length > level.bufferSize) return null; + return next; + }, +}; diff --git a/src/atelier-scene.js b/src/atelier-scene.js new file mode 100644 index 0000000..029d74e --- /dev/null +++ b/src/atelier-scene.js @@ -0,0 +1,101 @@ +import * as THREE from 'three'; +import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; +import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js'; +import { COLORS } from './pocket-core.js'; + +export class AtelierScene { + constructor(container, callbacks) { + this.callbacks = callbacks; this.renderer = new THREE.WebGLRenderer({ antialias:true, alpha:true }); + this.reduced = matchMedia('(prefers-reduced-motion: reduce)').matches; + this.renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2)); this.renderer.setClearColor(0, 0); this.renderer.shadowMap.enabled = true; + this.canvas = this.renderer.domElement; this.canvas.id = 'pocket-canvas'; this.canvas.tabIndex = 0; this.canvas.setAttribute('aria-label', 'Assemblage 3D : cliquez une vis, faites glisser pour tourner'); container.prepend(this.canvas); + this.scene = new THREE.Scene(); this.camera = new THREE.PerspectiveCamera(34, 1, .1, 100); this.camera.position.set(7, 11, 14); + this.controls = new OrbitControls(this.camera, this.canvas); this.controls.target.set(0, 1, 0); this.controls.enableDamping = true; this.controls.enablePan = false; this.controls.minDistance = 9; this.controls.maxDistance = 26; this.controls.maxPolarAngle = Math.PI * .48; + this.scene.add(new THREE.HemisphereLight(0xfff9e7, 0x6d8868, 2.6)); const light = new THREE.DirectionalLight(0xfff8e8, 3); light.position.set(-5, 12, 7); light.castShadow = true; light.shadow.mapSize.set(1024, 1024); Object.assign(light.shadow.camera, { left:-9, right:9, top:9, bottom:-9 }); this.scene.add(light); + this.root = new THREE.Group(); this.scene.add(this.root); this.raycaster = new THREE.Raycaster(); this.effects = []; this.screws = new Map(); this.plates = new Map(); + this.canvas.addEventListener('pointerdown', e => { this.down = [e.clientX, e.clientY]; this.canvas.focus({ preventScroll:true }); }); + this.canvas.addEventListener('pointerup', e => { + if (!this.down || Math.hypot(e.clientX - this.down[0], e.clientY - this.down[1]) > 6 || !this.callbacks.enabled()) return; + const rect = this.canvas.getBoundingClientRect(); this.raycaster.setFromCamera(new THREE.Vector2((e.clientX - rect.x) / rect.width * 2 - 1, -(e.clientY - rect.y) / rect.height * 2 + 1), this.camera); + const hit = this.raycaster.intersectObjects(this.root.children, true)[0]; let object = hit?.object; + while (object && object.userData.screw === undefined) object = object.parent; + if (object) this.callbacks.screw(object.userData.screw); + }); + this.canvas.addEventListener('pointercancel', () => { this.down = null; }); + this.canvas.addEventListener('webglcontextlost', event => { event.preventDefault(); this.callbacks.error?.(); }); + this.observer = new ResizeObserver(() => this.resize()); this.observer.observe(container); + const loop = () => { + this.frame = requestAnimationFrame(loop); if (document.hidden) return; + const now = performance.now(); + for (const fx of this.effects) { + const t = Math.max(0, Math.min(1, (now - fx.start) / fx.duration)), ease = t * t; + fx.mesh.position.y = fx.y + ease * 3.2; fx.mesh.position.x = fx.x + ease * (fx.plate ? 3.5 : .8); fx.mesh.rotation.y = ease * Math.PI * (fx.plate ? .7 : 7); fx.mesh.scale.setScalar(1 - ease * .8); + if (t === 1) { this.root.remove(fx.mesh); this.disposeObject(fx.mesh); } + } + this.effects = this.effects.filter(fx => now - fx.start < fx.duration); + this.controls.update(); this.renderer.render(this.scene, this.camera); + }; loop(); + } + disposeObject(object) { object.traverse(mesh => { mesh.geometry?.dispose(); if (mesh.material) for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) material.dispose(); }); } + material(color, metalness = 0) { return new THREE.MeshStandardMaterial({ color, roughness: metalness ? .33 : .72, metalness }); } + plateGeometry(index) { + const profile = index % 6; + if (profile === 0) return new RoundedBoxGeometry(3.15, .30, 2.5, 4, .14); + const shape = new THREE.Shape(); + if (profile === 1) shape.absellipse(0, 0, 1.6, 1.30, 0, Math.PI * 2, false, 0); + else if (profile === 5) { + for (let n = 0; n <= 72; n++) { const angle = n / 72 * Math.PI * 2, radius = 1.35 + .13 * Math.cos(angle * 6), x = Math.cos(angle) * radius * 1.1, y = Math.sin(angle) * radius; if (!n) shape.moveTo(x,y); else shape.lineTo(x,y); } + } else { + const points = profile === 2 ? [[-1.6,0],[-.95,-1.25],[.95,-1.25],[1.6,0],[.95,1.25],[-.95,1.25]] : profile === 3 ? [[-1.5,-.85],[1.5,-.85],[1.5,.6],[0,1.4],[-1.5,.6]] : [[-1.6,-.85],[1.6,-.85],[1.2,.8],[0,1.25],[-1.2,.8]]; + points.forEach(([x,y], i) => i ? shape.lineTo(x,y) : shape.moveTo(x,y)); shape.closePath(); + } + const geo = new THREE.ExtrudeGeometry(shape, { depth:.22, bevelEnabled:true, bevelThickness:.04, bevelSize:.06, bevelSegments:3, steps:1, curveSegments:40 }); + geo.rotateX(Math.PI / 2); geo.translate(0,.11,0); return geo; + } + mesh(geometry, material, parent, x=0, y=0, z=0) { const m = new THREE.Mesh(geometry, material); m.position.set(x, y, z); m.castShadow = m.receiveShadow = true; parent.add(m); return m; } + rebuild(level, state) { + for (const child of [...this.root.children]) { this.root.remove(child); this.disposeObject(child); } + this.effects = []; this.screws.clear(); this.plates.clear(); + this.mesh(new RoundedBoxGeometry(level.stacks * 3.5 + .5, .25, 4.1, 3, .13), this.material('#cebd98'), this.root, 0, -.18, 0); + this.mesh(new RoundedBoxGeometry(level.stacks * 3.5 + .2, .07, 3.75, 3, .12), this.material('#e3d6b8'), this.root, 0, 0, 0); + for (const plate of level.plates) { + if (plate.screws.every(id => state.removed.includes(id))) continue; + const group = new THREE.Group(), x = (plate.stack - (level.stacks - 1) / 2) * 3.5, y = .3 + plate.layer * .48; + group.position.set(x, y, 0); this.root.add(group); this.plates.set(plate.id, group); + const body = this.mesh(this.plateGeometry(level.index), this.material(['#b4c6a3', '#e4cf9f', '#b1ccd0', '#c7b3cf'][plate.style]), group); + body.userData.plate = plate.id; + for (let j = 0; j < 3; j++) { + this.mesh(new THREE.CylinderGeometry(.19, .19, .31, 24), this.material('#9aa386'), group, (j - 1) * .92, .01, j % 2 ? .42 : -.42); + } + for (const id of plate.screws) { + if (state.removed.includes(id)) continue; + const screw = level.screws[id], head = new THREE.Group(), sx = x + (screw.position - 1) * .92, sz = screw.position % 2 ? .42 : -.42; + head.position.set(sx, y + .25, sz); head.userData.screw = id; this.root.add(head); this.screws.set(id, head); + this.mesh(new THREE.CylinderGeometry(.12, .12, .40, 16), this.material('#a6a59a', .55), head, 0, -.15, 0); + this.mesh(new THREE.CylinderGeometry(.30, .30, .16, 32), this.material(COLORS[screw.color].hex, .3), head); + this.mesh(new THREE.BoxGeometry(.30, .014, .05), this.material('#456152'), head, 0, .088, 0); + this.mesh(new THREE.BoxGeometry(.05, .014, .30), this.material('#456152'), head, 0, .09, 0); + } + } + this.scene.updateMatrixWorld(true); + } + update(level, state, hint, selected, previous) { + const rebuild = this.reduced || !previous || !this.level || this.level.index !== level.index; this.level = level; this.state = state; + if (rebuild) this.rebuild(level, state); + else { + for (const id of state.removed) if (!previous.removed.includes(id)) { + const head = this.screws.get(id); if (!head) continue; this.screws.delete(id); head.userData = {}; this.effects.push({ mesh:head, x:head.position.x, y:head.position.y, start:performance.now(), duration:500 }); + } + for (const plate of level.plates) if (plate.screws.every(id => state.removed.includes(id)) && this.plates.has(plate.id)) { + const mesh = this.plates.get(plate.id); this.plates.delete(plate.id); this.effects.push({ mesh, plate:true, x:mesh.position.x, y:mesh.position.y, start:performance.now() + 130, duration:650 }); + } + } + for (const [id, group] of this.screws) group.traverse(mesh => { + if (mesh.material) { mesh.material.emissive?.set(hint?.action === id ? '#907f38' : '#000000'); mesh.material.emissiveIntensity = hint?.action === id ? .7 : 0; } + }); + } + resize() { const rect = this.canvas.parentElement.getBoundingClientRect(); this.camera.aspect = rect.width / rect.height; this.camera.updateProjectionMatrix(); this.renderer.setSize(rect.width, rect.height, false); } + resetView() { this.camera.position.set(7, 11, 14); this.controls.target.set(0, 1, 0); this.controls.update(); } + screenPoint(id) { const mesh = this.screws.get(id); if (!mesh) return null; this.scene.updateMatrixWorld(true); this.camera.updateMatrixWorld(); const point = mesh.getWorldPosition(new THREE.Vector3()).project(this.camera), rect = this.canvas.getBoundingClientRect(); return { x:rect.x + (point.x + 1) * rect.width / 2, y:rect.y + (1 - point.y) * rect.height / 2 }; } + dispose() { cancelAnimationFrame(this.frame); this.observer.disconnect(); this.controls.dispose(); this.disposeObject(this.root); this.renderer.dispose(); } +} diff --git a/src/bobines-puzzle.js b/src/bobines-puzzle.js new file mode 100644 index 0000000..1eaa627 --- /dev/null +++ b/src/bobines-puzzle.js @@ -0,0 +1,49 @@ +import { checkIndex, clone, random, shuffle } from './pocket-core.js'; + +const TITLES = ['Un fil à la fois', 'Les rubans', 'Le petit métier', 'Les couleurs du matin', 'Les entrelacs', 'La nappe du jardin', 'Les doux détours', 'Les écheveaux', 'Le tissage', 'La grande bobine', 'Les fils croisés', 'La dernière maille']; +export function createBobinesLevel(index) { + checkIndex(index); const rng = random(91873 + index * 6701), tier = Math.floor(index / 12); + const colors = shuffle([0, 1, 2, 3, 4, 5], rng).slice(0, 3 + tier); + const width = 3 + tier, depth = 4 + tier * 2 + index % 3; + const lines = Array.from({ length: width }, () => Array.from({ length: depth }, () => colors[Math.floor(rng() * colors.length)])); + const cursors = lines.map(() => 0), batches = []; + while (cursors.some((n, i) => n < lines[i].length)) { + const available = [...new Set(lines.map((line, i) => line[cursors[i]]).filter(c => c !== undefined))]; + const color = available[Math.floor(rng() * available.length)]; let count = 0; + for (let i = 0; i < width; i++) while (lines[i][cursors[i]] === color) { count++; cursors[i]++; } + batches.push({ color, count }); + } + const queues = Array.from({ length: 4 }, () => []), solution = []; + // Every reserve has a route proved by the actual peeling order above. + for (const batch of batches) { const q = Math.floor(rng() * 4); queues[q].push(batch); solution.push(q); } + return { index, title: TITLES[index % 12], tier, lines, queues, solution, slotCount: 3 }; +} +function wind(level, state) { + let changed = true; + while (changed) { + changed = false; + for (let slot = 0; slot < state.slots.length; slot++) { + const bobbin = state.slots[slot]; if (!bobbin) continue; + for (let i = 0; i < level.lines.length && bobbin.remaining; i++) { + while (bobbin.remaining && level.lines[i][state.cursors[i]] === bobbin.color) { + state.cursors[i]++; bobbin.remaining--; changed = true; + } + } + if (!bobbin.remaining) { state.slots[slot] = null; changed = true; } + } + } +} +export const bobinesRules = { + create: createBobinesLevel, + initial: level => ({ cursors: level.lines.map(() => 0), queues: level.queues.map(() => 0), slots: Array(level.slotCount).fill(null) }), + won: (level, state) => state.cursors.every((n, i) => n === level.lines[i].length) && state.slots.every(s => !s), + actions: (level, state) => state.slots.includes(null) ? level.queues.map((queue, q) => queue[state.queues[q]] ? q : null).filter(q => q !== null).sort((a, b) => { + const visible = level.lines.map((line, i) => line[state.cursors[i]]); + return Number(visible.includes(level.queues[b][state.queues[b]].color)) - Number(visible.includes(level.queues[a][state.queues[a]].color)); + }) : [], + move(level, state, q) { + if (!Number.isInteger(q) || q < 0 || q >= level.queues.length) return null; + const batch = level.queues[q][state.queues[q]], slot = state.slots.indexOf(null); if (!batch || slot === -1) return null; + const next = clone(state); next.queues[q]++; next.slots[slot] = { ...batch, remaining: batch.count }; wind(level, next); return next; + }, +}; diff --git a/src/bounty-canvas.js b/src/bounty-canvas.js new file mode 100644 index 0000000..2ec5b1a --- /dev/null +++ b/src/bounty-canvas.js @@ -0,0 +1,73 @@ +import {PocketCanvas} from './pocket-canvas.js'; +import {COLORS} from './pocket-core.js'; +import {chainNeighbors} from './recolte-puzzle.js'; +import {activePieces,pieceWidth,pieceHeight,mosaicCells} from './mosaique-puzzle.js'; +const W=640,H=600; +export class BountyCanvas extends PocketCanvas{ + constructor(container,mode,callbacks){ + super(container,mode,callbacks);this.canvas.setAttribute('aria-label',({recolte:'Jardin : tracez une chaîne de trois billes ou plus',dizaines:'Tuiles de bois : choisissez deux nombres identiques ou dont la somme vaut dix',mosaique:'Tableau : faites glisser une pièce dans les cases libres'})[mode]); + this.canvas.addEventListener('pointerdown',event=>{ + if(!callbacks.enabled()||!event.isPrimary)return;this.canvas.focus({preventScroll:true});this.canvas.setPointerCapture(event.pointerId);const p=this.point(event),id=this.boardCell(p); + if(mode==='recolte'&&id!==null&&this.state.field[id]!==null)this.draft=[id]; + if(mode==='dizaines'&&id!==null)callbacks.number(id); + if(mode==='mosaique'){ + if(p.y>512){const pieces=activePieces(this.level,this.state),n=[190,320,450].findIndex(x=>Math.abs(p.x-x)<55),piece=pieces[n];if(!piece)return;callbacks.select(piece.id);const t=this.trayPoint(piece,n),dx=Math.floor((p.x-t.x)/22),dy=Math.floor((p.y-t.y)/22),offset=piece.cells.find(([x,y])=>x===dx&&y===dy)??piece.cells[0];this.grab={id:piece.id,offset};} + else if(id!==null&&this.selected!==null)callbacks.mosaic(id); + } + }); + this.canvas.addEventListener('pointermove',event=>{ + if(!callbacks.enabled())return;const p=this.point(event),id=this.boardCell(p); + if(this.draft&&id!==null){const path=this.draft,last=path.at(-1);if(last===id)return;const previous=path.indexOf(id);if(previous>=0){this.draft=path.slice(0,previous+1);return;} + const size=this.level.size,dx=id%size-last%size,dy=Math.floor(id/size)-Math.floor(last/size),n=Math.max(Math.abs(dx),Math.abs(dy));if(dx&&dy&&Math.abs(dx)!==Math.abs(dy))return; + for(let step=1;step<=n;step++){const cell=(Math.floor(last/size)+Math.sign(dy)*step)*size+last%size+Math.sign(dx)*step;if(this.state.field[cell]!==this.state.field[path[0]]||this.draft.includes(cell)||!chainNeighbors(this.level,this.draft.at(-1),cell))break;this.draft.push(cell);} + } + if(mode==='mosaique'&&id!==null){const offset=this.grab?.offset??[0,0];this.cursor={x:id%this.level.size-offset[0],y:Math.floor(id/this.level.size)-offset[1]};} + }); + this.canvas.addEventListener('pointerup',event=>{ + if(!callbacks.enabled()){this.draft=null;this.grab=null;return;} + if(this.draft){const path=this.draft;this.draft=null;callbacks.play({path});} + if(this.grab){const grab=this.grab,p=this.point(event),id=this.boardCell(p);this.grab=null;if(id!==null)callbacks.play({id:grab.id,x:id%this.level.size-grab.offset[0],y:Math.floor(id/this.level.size)-grab.offset[1]});} + }); + this.canvas.addEventListener('pointercancel',()=>{this.draft=null;this.grab=null;}); + } + point(event){const r=this.canvas.getBoundingClientRect();return{x:(event.clientX-r.x)/r.width*W,y:(event.clientY-r.y)/r.height*H};} + boardGrid(){const cols=this.level.cols??this.level.size,rows=this.level.rows??this.level.size,cell=Math.min((this.mode==='mosaique'?440:480)/cols,(this.mode==='mosaique'?440:470)/rows);return{x:(W-cols*cell)/2,y:this.mode==='mosaique'?59:65,cell,cols,rows};} + boardCell(p){const g=this.boardGrid(),x=Math.floor((p.x-g.x)/g.cell),y=Math.floor((p.y-g.y)/g.cell);return x>=0&&y>=0&&xp.id===value.piece),piece=pieces[n],t=this.trayPoint(piece,n);p={x:t.x+(piece.cells[0][0]+.5)*22,y:t.y+(piece.cells[0][1]+.5)*22};}else p=this.boardPoint(value);const r=this.canvas.getBoundingClientRect();return{x:r.x+p.x/W*r.width,y:r.y+p.y/H*r.height};} + update(level,state,hint,selected,previous,action){ + const changed=level!==this.level||state!==this.state;this.level=level;this.state=state;this.hint=hint;this.selected=selected;if(changed){this.draft=null;this.grab=null;this.cursor=null;this.motion=previous&&!this.reduced?{previous,action,start:performance.now()}:null;}this.draw(); + } + berry(id,color,p,scale=1){const c=this.ctx,g=this.boardGrid(),r=g.cell*.30*scale;c.save();c.fillStyle='#5c794b18';c.beginPath();c.ellipse(p.x+2,p.y+r*.5,r,r*.45,0,0,7);c.fill();c.fillStyle=COLORS[color].hex;c.beginPath();c.arc(p.x,p.y,r,0,7);c.fill();c.fillStyle='#ffffff70';c.beginPath();c.ellipse(p.x-r*.35,p.y-r*.4,r*.17,r*.26,.4,0,7);c.fill();c.fillStyle='#91a975';c.beginPath();c.ellipse(p.x+r*.2,p.y-r*.9,r*.35,r*.12,-.5,0,7);c.fill();if(scale>.8)this.text(COLORS[color].mark,p.x,p.y+1,Math.max(10,g.cell*.13),color===7?'#fff8':'#34564a80');c.restore();} + drawRecolte(){ + const c=this.ctx,g=this.boardGrid(),t=this.motion?Math.min(1,(performance.now()-this.motion.start)/370):1,path=this.draft??(Array.isArray(this.selected)?this.selected:this.hint?.action?.path??[]),previous=this.motion?.previous; + this.round(g.x-14,g.y-14,g.cols*g.cell+28,g.rows*g.cell+28,25,'#e7eddb','#d3dfc7'); + for(let id=0;id{const p=this.boardPoint(id);if(n)c.lineTo(p.x,p.y);else c.moveTo(p.x,p.y);});c.stroke();} + const mappings=new Map();if(previous&&t<1)for(let x=0;x=0;y--){const id=y*g.cols+x;if(previous.field[id]!==null&&!this.motion.action.path.includes(id))old.push(id);}for(let n=0;n{if(color===null)return;const to=this.boardPoint(id),from=this.boardPoint(mappings.get(id)??id);this.berry(id,color,{x:to.x,y:from.y+(to.y-from.y)*t});}); + if(previous&&t<1)for(const id of this.motion.action.path){const p=this.boardPoint(id);c.save();c.globalAlpha=1-t;this.berry(id,previous.field[id],{x:p.x+(320-p.x)*t,y:p.y+(570-p.y)*t},1-t*.65);c.restore();} + path.forEach((id,n)=>{const p=this.boardPoint(id);c.strokeStyle=this.draft?'#789375':'#ae9552';c.lineWidth=2;c.beginPath();c.arc(p.x,p.y,g.cell*.36,0,7);c.stroke();if(this.hint&&!this.draft)this.text(n+1,p.x,p.y+g.cell*.32,10,'#8e794b');});this.text(path.length?`${path.length} BILLES DANS LA CHAÎNE`:'UNE CHAÎNE DE TROIS, OU UN GRAND PANIER',320,572,11,'#849575'); + } + numberTile(id,value,scale=1,alpha=1){const c=this.ctx,g=this.boardGrid(),p=this.boardPoint(id);c.save();c.globalAlpha=alpha;c.translate(p.x,p.y);c.scale(scale,scale);this.round(-g.cell*.43,-g.cell*.40+3,g.cell*.86,g.cell*.80,9,'#aa95682a');this.round(-g.cell*.43,-g.cell*.40,g.cell*.86,g.cell*.80,9,'#e5d1a9','#cdb78d');c.strokeStyle='#c5ad7e40';for(const y of [-.25,.20]){c.beginPath();c.moveTo(-g.cell*.35,g.cell*y);c.bezierCurveTo(-g.cell*.1,g.cell*(y+.05),g.cell*.1,g.cell*(y-.05),g.cell*.35,g.cell*y);c.stroke();}c.fillStyle='#53684f';c.font=`${g.cell*.40}px Georgia,serif`;c.textAlign='center';c.textBaseline='middle';c.fillText(value,0,0);c.restore();} + drawDizaines(){ + const c=this.ctx,g=this.boardGrid(),t=this.motion?Math.min(1,(performance.now()-this.motion.start)/320):1;this.round(g.x-14,g.y-14,g.cols*g.cell+28,g.rows*g.cell+28,22,'#ece7d6','#d7ceb4'); + for(let id=0;idp.id===this.selected),cursor=this.hint?.action??this.cursor; + if(piece&&cursor){const cells=mosaicCells(this.level,piece,cursor.x,cursor.y),valid=cells&&!cells.some(id=>this.state.field[id]!==null);if(cells){for(const id of cells){this.mosaicTile(id,piece.color,valid?.55:.18);const p=this.boardPoint(id);this.round(p.x-g.cell*.45,p.y-g.cell*.45,g.cell*.9,g.cell*.9,6,null,valid?'#ae9552':'#c78970');}}} + pieces.forEach((piece,n)=>{const x=[190,320,450][n],p=this.trayPoint(piece,n);this.round(x-55,515,110,68,14,'#e4ebd8',this.selected===piece.id?'#ae9552':'#d1dcc6');for(const [dx,dy] of piece.cells)this.round(p.x+dx*22,p.y+dy*22,20,20,4,COLORS[piece.color].hex,'#fff8');this.text(n+1,x+44,573,9,'#829575');}); + if(!pieces.length)this.text('TOUTES LES PIÈCES SONT POSÉES',320,546,11,'#849575'); + } + draw(){if(!this.level||!this.canvas.width)return;const c=this.ctx;c.setTransform(this.canvas.width/W,0,0,this.canvas.height/H,0,0);c.clearRect(0,0,W,H);if(this.mode==='recolte')this.drawRecolte();else if(this.mode==='dizaines')this.drawDizaines();else this.drawMosaique();} +} diff --git a/src/bounty-config.js b/src/bounty-config.js new file mode 100644 index 0000000..e4b6e65 --- /dev/null +++ b/src/bounty-config.js @@ -0,0 +1,23 @@ +import {COLORS} from './pocket-core.js'; +import {recolteRules} from './recolte-puzzle.js'; +import {dizainesRules} from './dizaines-puzzle.js'; +import {mosaiqueRules,activePieces,pieceWidth,pieceHeight} from './mosaique-puzzle.js'; +export const mosaicSvg=p=>``; +const cells=(game,mode,selected,hint)=>`
${game.state.field.map((v,id)=>``).join('')}
`; +export const bountyConfigs={ + recolte:{name:'Récolte',rules:recolteRules,eyebrow:'DE PROCHE EN PROCHE, LE PANIER SE REMPLIT',title:'Une baie.
Et toute une récolte.',copy:'Reliez les petites couleurs.
Remplissez vos paniers.',steps:[['Tracez une chaîne.','Reliez au moins trois billes de la même couleur. Les voisines en diagonale comptent aussi.'],['Préparez la suite.','Les billes restantes tombent pour combler les trous. Une petite chaîne peut ouvrir un grand passage.']],note:'Tracez au moins trois billes de même couleur',unit:'billes à récolter',reserve:'Les petits paniers.',reserveCopy:'Chaque couleur a son panier. Récoltez toutes les billes, en gardant assez de voisines pour la suite.',finish:'Le jardin a tout donné.',delay:400,invalid:'Reliez au moins trois billes voisines de la même couleur, sans repasser sur une bille.', + rulesText:['Tracez une chaîne de trois billes ou plus de même couleur, avec la souris ou le doigt. Les voisins horizontaux, verticaux et diagonaux sont autorisés.','Une bille ne peut apparaître qu’une fois dans une chaîne. Revenez sur une bille de votre tracé pour raccourcir la chaîne avant de relâcher.','Les billes récoltées rejoignent leur panier. Les autres tombent verticalement dans les trous ; aucune bille aléatoire ne remplit le jardin. Récoltez tout le plateau.','Vous pouvez aussi choisir les cases dans les commandes, puis valider la chaîne avec le bouton ou Entrée. Échap efface ce tracé. Annulez un geste ou suivez un indice vérifié si des billes restent isolées.'], + total:game=>game.level.total,remaining:game=>game.state.field.filter(v=>v!==null).length, + controls(game,selected,hint){return `
${game.level.quotas.map((n,color)=>n?`
${COLORS[color].mark}${game.state.collected[color]} / ${n}${COLORS[color].name}
`:'').join('')}
UNE AUTRE FAÇON DE TRACER${cells(game,'recolte',selected,hint)}
`;}, + }, + dizaines:{name:'Dizaines',rules:dizainesRules,eyebrow:'DEUX PETITS NOMBRES, UN PEU DE LOGIQUE',title:'Deux nombres.
Et ça fait dix.',copy:'Réunissez les bonnes paires.
Laissez le bois respirer.',steps:[['Choisissez deux nombres.','Ils sont identiques, ou leur somme vaut dix. Ils doivent pouvoir se rejoindre sans chiffre entre les deux.'],['Regardez plus loin.','Les cases vides ouvrent des lignes, des colonnes et des diagonales. La fin d’une rangée rejoint le début de la suivante.']],note:'Choisissez deux nombres identiques, ou qui font dix',unit:'nombres à réunir',reserve:'Les petites paires.',reserveCopy:'Les espaces vides comptent : une paire éloignée peut devenir accessible après quelques retraits.',finish:'Tous les nombres se sont retrouvés.',delay:340,invalid:'Ces nombres ne font pas une paire libre : même nombre ou somme dix, sans chiffre sur le chemin.', + rulesText:['Cliquez deux nombres identiques, ou deux nombres dont la somme vaut dix. Un chiffre sélectionné peut être désélectionné en cliquant dessus.','La paire doit être alignée horizontalement, verticalement ou en diagonale, avec uniquement des cases vides entre ses deux nombres.','Deux nombres consécutifs dans la lecture du plateau peuvent également se rejoindre : à la fin d’une rangée et au début de la suivante, y compris à travers les cases déjà vides.','Retirez tous les nombres. Les cases et rangées restent à leur place, pour garder le chemin lisible. Les 48 plateaux sont finis et disposent chacun d’une solution : aucun ajout de chiffres ni outil payant ne sont nécessaires. Annulation et indices restent disponibles.'], + total:game=>game.level.total,remaining:game=>game.state.field.filter(v=>v!==null).length, + controls(game,selected,hint){return `
${game.state.pairs}Paires réunies
LES NOMBRES DU PLATEAU${cells(game,'dizaines',selected,hint)}

Même nombre, ou une somme de dix.
Horizontale · Verticale · Diagonale · Suite des rangées

`;}, + }, + mosaique:{name:'Mosaïque',rules:mosaiqueRules,eyebrow:'DE PETITES PIÈCES, UN GRAND TABLEAU',title:'Chaque pièce
trouve sa place.',copy:'Complétez les petites lignes.
Retrouvez un tableau vide.',steps:[['Posez une pièce.','Choisissez l’une des trois formes disponibles. Faites-la glisser dans les cases libres du tableau.'],['Préparez les lignes.','Une rangée ou une colonne complète disparaît. Posez les trois pièces avant de recevoir la réserve suivante.']],note:'Choisissez une pièce et posez-la dans les cases libres',unit:'cases à nettoyer',reserve:'Les pièces du tableau.',reserveCopy:'Trois pièces à la fois. Pensez aux espaces que la prochaine ligne fera apparaître.',finish:'Un tableau bien rangé.',delay:420,invalid:'Cette pièce ne tient pas ici : chaque carré doit rester dans une case libre.', + rulesText:['Faites glisser une pièce depuis le bas du tableau. Vous pouvez aussi la sélectionner, puis cliquer sa case de départ sur le plateau ou dans les commandes.','Chaque carré doit tenir dans une case vide. Les pièces gardent leur orientation et ne peuvent ni dépasser le tableau ni recouvrir une case occupée.','Les rangées et colonnes complètes disparaissent ensemble. Un croisement n’est effacé qu’une fois. Les trois pièces disponibles peuvent être posées dans l’ordre de votre choix ; la réserve suivante arrive après les trois placements.','Utilisez toute la réserve et videz entièrement le tableau. Chaque réserve est finie et auditée. Un placement dans un détour reste possible : annulez si nécessaire. 1–3 choisit une pièce ; les flèches déplacent son aperçu et Espace la pose.'], + total:game=>game.level.total,remaining:game=>game.level.total-game.state.cleared, + controls(game,selected,hint){const active=activePieces(game.level,game.state);return `
${game.state.lines}Lignes dégagées · ${game.state.used.length} / ${game.level.pieces.length} pièces
${active.map((p,n)=>``).join('')}
LA CASE DE DÉPART DE LA PIÈCE
${game.state.field.map((v,id)=>``).join('')}
LE PROCHAIN TRIO${game.level.pieces.slice(Math.floor(game.state.used.length/3)*3+3,Math.floor(game.state.used.length/3)*3+6).map(mosaicSvg).join('')||'Les dernières pièces sont sorties.'}
`;}, + }, +}; diff --git a/src/bounty-previews.js b/src/bounty-previews.js new file mode 100644 index 0000000..030980a --- /dev/null +++ b/src/bounty-previews.js @@ -0,0 +1,9 @@ +import {COLORS} from './pocket-core.js'; +import {createRecolteLevel} from './recolte-puzzle.js'; +import {createDizainesLevel} from './dizaines-puzzle.js'; +import {createMosaiqueLevel} from './mosaique-puzzle.js'; +const r=createRecolteLevel(0),d=createDizainesLevel(3),m=createMosaiqueLevel(0); +const rp=id=>[104+(id%r.size+.5)*30,42+(Math.floor(id/r.size)+.5)*30]; +export const recoltePreview=``; +export const dizainesPreview=``; +export const mosaiquePreview=``; diff --git a/src/bounty-style.css b/src/bounty-style.css new file mode 100644 index 0000000..91038ea --- /dev/null +++ b/src/bounty-style.css @@ -0,0 +1,4 @@ +@import './harvest-style.css'; +.bounty-quotas{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin:22px 0;}.bounty-quotas>div{border:1px solid #d4ddcc;background:#fbfcf5;border-radius:12px;padding:12px 3px;text-align:center;}.bounty-quotas span{display:grid;place-items:center;border-radius:50%;width:28px;height:28px;background:var(--color);margin:0 auto 8px;color:#34564a;}.bounty-quotas strong{display:block;font:16px Georgia,serif;}.bounty-quotas small{display:block;font-size:8px;margin-top:5px;color:var(--muted);}.bounty-cells{display:grid;grid-template-columns:repeat(var(--cols),minmax(0,1fr));gap:4px;margin:10px 0;}.bounty-cells button{border:1px solid #d3ddc7;border-radius:6px;min-width:0;min-height:35px;padding:6px 1px;background:#fbfcf5;font:17px Georgia,serif;color:var(--ink);}.bounty-cells span{display:grid;place-items:center;width:22px;height:22px;border-radius:50%;background:var(--color);font:11px 'Segoe UI',sans-serif;margin:auto;}.bounty-cells small{font:8px 'Segoe UI',sans-serif;}.bounty-cells [aria-pressed=true]{box-shadow:0 0 0 2px #789478;}.bounty-cells button:disabled{background:#e8ecdf;}.bounty-actions{display:flex;flex-direction:column;gap:7px;margin:15px 0;}.bounty-actions button{border:1px solid #d3ddc7;border-radius:9px;background:#e4ecda;padding:11px;font-size:10px;}.bounty-actions button+button{background:transparent;}.bounty-note{font-size:10px;line-height:1.8;color:var(--muted);}.bounty-pieces{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin:24px 0;}.bounty-pieces button{border:1px solid #d3ddc7;border-radius:12px;padding:10px 4px;background:#fbfcf5;}.bounty-pieces [aria-pressed=true]{box-shadow:0 0 0 2px #789478;}.bounty-pieces svg{width:100%;height:50px;}.bounty-pieces small{display:block;font-size:8px;margin-top:8px;color:var(--muted);}.bounty-origins button{font:9px 'Segoe UI',sans-serif;min-height:27px;}.bounty-reserve{margin-top:20px;opacity:.7;}.bounty-reserve svg{display:inline-block;width:28%;height:40px;vertical-align:middle;margin:8px 1%;}.bounty-reserve small{font-size:10px;color:var(--muted);} +body[data-pocket=dizaines] .bounty-cells button{background:#e6d2af;border-color:#d4bd91;}body[data-pocket=dizaines] .bounty-cells button:disabled{background:#edeadd;} +@media(max-width:580px){.bounty-cells button{min-height:39px;}.bounty-origins button{min-height:33px;}.bounty-pieces svg{height:62px;}.bounty-quotas{grid-template-columns:repeat(4,minmax(0,1fr));}} diff --git a/src/broderie-puzzle.js b/src/broderie-puzzle.js new file mode 100644 index 0000000..d406ea7 --- /dev/null +++ b/src/broderie-puzzle.js @@ -0,0 +1,39 @@ +import { checkIndex, clone, random, shuffle } from './pocket-core.js'; +import { pictureArt } from './picture-art.js'; +const overlaps=(a,b)=>Math.abs(a.x-b.x)<.96 && Math.abs(a.y-b.y)<.96; +export function accessibleSpools(level,state) {return level.spools.filter(s=>!state.removed.includes(s.id) && !level.spools.some(cover=>cover.layer>s.layer && !state.removed.includes(cover.id) && overlaps(s,cover))).map(s=>s.id);} +export function createBroderieLevel(index) { + checkIndex(index);const rng=random(72971+index*9059),tier=Math.floor(index/12),art=pictureArt(index),count=24+tier*9+(index%3)*3; + const level={index,tier,...art,spools:[],patches:[],solution:[],bufferSize:7}; + for(let layer=0;level.spools.lengthi),rng)) { + level.spools.push({id:level.spools.length,x:id%side+offset,y:Math.floor(id/side)+offset,layer,color:0});if(level.spools.length===count)break; + } + } + const colors=shuffle([...new Set(level.cells)],rng),groups=[...colors],totals=new Map(colors.map(c=>[c,level.cells.filter(n=>n===c).length])); + while(groups.lengthgroups.filter(g=>g===c).lengthc===color?id:null).filter(id=>id!==null),parts=groups.filter(c=>c===color).length; + for(let n=0;n({removed:[],buffer:[],stitched:[]}), + won:(level,state)=>state.removed.length===level.spools.length && !state.buffer.length && state.stitched.length===level.patches.length, + actions:(level,state)=>accessibleSpools(level,state).sort((a,b)=>state.buffer.filter(c=>c===level.spools[b].color).length-state.buffer.filter(c=>c===level.spools[a].color).length), + move(level,state,id) { + if(!Number.isInteger(id) || !accessibleSpools(level,state).includes(id))return null; + const next=clone(state),color=level.spools[id].color;next.removed.push(id);next.buffer.push(color); + if(next.buffer.filter(c=>c===color).length===3) { + next.buffer=next.buffer.filter(c=>c!==color);const patch=level.patches.find(p=>p.color===color && !next.stitched.includes(p.id));if(!patch)return null;next.stitched.push(patch.id); + } + return next.buffer.length>level.bufferSize?null:next; + }, +}; diff --git a/src/carrousel-puzzle.js b/src/carrousel-puzzle.js new file mode 100644 index 0000000..342d904 --- /dev/null +++ b/src/carrousel-puzzle.js @@ -0,0 +1,36 @@ +import { checkIndex, clone, random } from './pocket-core.js'; +import { pictureArt, peelColor, pictureFrontier } from './picture-art.js'; +export function createCarrouselLevel(index) { + checkIndex(index);const rng=random(83911+index*6521),tier=Math.floor(index/12),art=pictureArt(index,10+tier*2); + const level={index,tier,...art,queues:Array.from({length:4},()=>[]),solution:[],lapLimit:5+tier*2,slotCount:5}; + const removed=[]; + while(removed.lengthlevel.cells[id]))],color=colors[Math.floor(rng()*colors.length)]; + const hits=peelColor(level,removed,color,level.lapLimit+Math.floor(rng()*(level.lapLimit+1))),q=Math.floor(rng()*4); + const pig={color,ammo:hits.length};level.queues[q].push(pig);level.solution.push({type:'queue',q}); + for(let left=pig.ammo-level.lapLimit;left>0;left-=level.lapLimit)level.solution.push({type:'waiting',slot:0}); + removed.push(...hits); + } + return level; +} +export const carrouselRules={ + create:createCarrouselLevel, + initial:level=>({removed:[],queues:level.queues.map(()=>0),waiting:Array(level.slotCount).fill(null)}), + won:(level,state)=>state.removed.length===level.cells.length && state.waiting.every(p=>!p) && state.queues.every((n,q)=>n===level.queues[q].length), + actions(level,state) { + const choices=state.waiting.map((pig,slot)=>pig?{type:'waiting',slot}:null).filter(Boolean); + if(state.waiting.includes(null))for(let q=0;qa.type==='queue'?level.queues[a.q][state.queues[a.q]].color:state.waiting[a.slot].color; + const visible=pictureFrontier(level,state.removed).map(id=>level.cells[id]);return choices.sort((a,b)=>Number(visible.includes(color(b)))-Number(visible.includes(color(a)))); + }, + move(level,state,action) { + if(!action || !['queue','waiting'].includes(action.type))return null; + const next=clone(state);let pig,slot; + if(action.type==='queue') {if(!Number.isInteger(action.q) || action.q<0 || action.q>=4)return null;pig=level.queues[action.q][state.queues[action.q]];slot=state.waiting.indexOf(null);if(!pig || slot===-1)return null;next.queues[action.q]++;pig={...pig};} + else {slot=action.slot;if(!Number.isInteger(slot) || slot<0 || slot>=level.slotCount || !state.waiting[slot])return null;pig={...state.waiting[slot]};next.waiting[slot]=null;} + const hits=peelColor(level,state.removed,pig.color,Math.min(pig.ammo,level.lapLimit)); + // A fruitless relaunch cannot make space or reveal anything; reject it. + if(!hits.length && action.type==='waiting')return null; + next.removed.push(...hits);pig.ammo-=hits.length;if(pig.ammo)next.waiting[slot]=pig;return next; + }, +}; diff --git a/src/colony-art.js b/src/colony-art.js new file mode 100644 index 0000000..345b773 --- /dev/null +++ b/src/colony-art.js @@ -0,0 +1,59 @@ +// Original 16px illustrations. Dots are the picture's background. +export const NEW_COLONY_ART = [ + ['Battements d’ailes', 'moss', [ + '................','..ppp......ppp..','.pggpp....ppggp.','.pgggpp..ppgggp.','.ppgggp..pgggpp.','..ppggpiipggpp..','...ppppiipppp...','....pppiippp....','....ccciiccc....','...ccccii cccc..'.replace(' ', ''),'..ccggciicggcc..','..cgggciicgggc..','...cccciicccc...','....ccciiccc....','.......ii.......','................', + ]], + ['Sous la surface', 'sky', [ + '................','................','.....gggg.......','...gggggggg.....','..gggggggggg....','.gggggcgggigg..g','.ggggcccgggggggg','.gggggcggggggggg','..gggggggggggggg','...gggggggg...gg','.....gggg.......','......gg........','................','..mm.......mm...','.mmm......mmm...','mmmm.....mmmm...', + ]], + ['La butineuse', 'moss', [ + '................','.......ii.......','.....ss..ss.....','....ssssssss....','....ssssssss....','.....ss..ss.....','...ggigggiggg...','..gggigggigggi..','..gggigggigggi..','...ggigggiggg...','....gggggggg....','......iiii......','.....i....i.....','................','................','................', + ]], + ['Une tasse de calme', 'plum', [ + '................','....s...s.......','...s...s........','....s...s.......','................','..eeeeeeeeee....','..ecccccceeeeee.','..eccccccee..ee.','..eccccccee..ee.','..ecccccceeeeee.','..eccccccee.....','...eccccc e.....'.replace(' ', ''),'....eeeeee......','..gggggggggg....','................','................', + ]], + ['Rouge fraise', 'cream', [ + '................','......ll........','...ll.llll.ll...','....llllllll....','.....llllll.....','...cccccccccc...','..ccgcccgccccc..','..ccccccccgccc..','..ccccgccccccc..','...ccccccgccc...','...cgcccccccc...','....ccccgccc....','.....cccccc.....','......cccc......','.......cc.......','................', + ]], + ['Au fil de l’eau', 'sky', [ + '................','.......i........','......ei........','.....eei c......'.replace(' ', ''),'....eeei cc.....'.replace(' ', ''),'...eeeei ccc....'.replace(' ', ''),'..eeeeei cccc...'.replace(' ', ''),'.eeeeeei ccccc..'.replace(' ', ''),'.......i........','..gggggggggggg..','...gggggggggg...','....gggggggg....','................','.eeee....eeee...','.....eeee....eee','................', + ]], + ['Le petit château', 'sky', [ + '................','..c.........c...','..cc........cc..','..i.........i...','.p.p.p....p.p.p.','.ppppp....ppppp.','.p e p....p e p.'.replaceAll(' ', 'p'),'.ppppp....ppppp.','.pppppppppppppp.','.pppppppppppppp.','.ppeppppppppepp.','.ppppppii ppppp.'.replace(' ', 'p'),'.pppppiiiippppp.','.pppppiiiippppp.','llllllllllllllll','llllllllllllllll', + ]], + ['Un chat au soleil', 'cream', [ + '................','..pp......pp....','..pcp....pcp....','..pppppppppp....','..pppppppppp....','...pigppgip.....','...pppppppp.....','..eeppccppee....','....pppppp......','....pppppp...p..','...pppppppp..p..','...pppppppp..p..','...ppppppppppp..','...pppppppppp...','...eeeeeeee.....','................', + ]], + ['Veilleur de nuit', 'plum', [ + '................','...l......l.....','...llllllll.....','..llllllllll....','..leee lleee l..'.replaceAll(' ', ''),'..leieleiel.....','..leeeleeeel....','...lllgllll.....','...llllllll.....','..lleelleell....','..lleelleell....','...lleeeell.....','....llllll......','.....g..g.......','...eeeeeeeeee...','................', + ]], + ['Le désert fleuri', 'cream', [ + '................','.......cc.......','......cccc......','.......cc.......','......llll......','..ll..llll......','..ll..llll..ll..','..ll..llll..ll..','..llllllll..ll..','...lllllll..ll..','......llllllll..','......lllllll...','......llll......','......llll......','....gggggggg....','................', + ]], + ['Tout doucement', 'sky', [ + '................','................','.......lll......','.......lil......','.......lll......','.....mmmmmm.....','....mllmllmm....','...mlllmlllmm...','...mmmmmmmmm....','...mlllmlllmm...','....mllmllmm....','.....mmmmmm.....','....ll....ll....','...lll....lll...','................','................', + ]], + ['Prendre de la hauteur', 'sky', [ + '.....ggccgg.....','...ggggccgggg...','..ggppgccgppgg..','..ggppgccgppgg..','..ggppgccgppgg..','..ggppgccgppgg..','...gppgccgppg...','....ppgccgpp....','.....ggccgg.....','......gggg......','......i..i......','......i..i......','......eeee......','......egge......','......eeee......','................', + ]], + ['Un flocon unique', 'plum', [ + '.......ss.......','....s..ss..s....','.....s.ss.s.....','..s...ssss...s..','...s..ssss..s...','....ssssssss....','.....ssssss.....','ssssssssssssssss','ssssssssssssssss','.....ssssss.....','....ssssssss....','...s..ssss..s...','..s...ssss...s..','.....s.ss.s.....','....s..ss..s....','.......ss.......', + ]], + ['À marée basse', 'cream', [ + '................','................','..cc........cc..','.cccc......cccc.','.cccc......cccc.','..cc..e..e..cc..','...c..i..i..c...','...cccccccccc...','....cccccccc....','....cccccccc....','...cccccccccc...','..c..c..c..c.c..','.c..c....c..c.c.','................','ssssssssssssssss','ssssssssssssssss', + ]], + ['Le chant du matin', 'moss', [ + '................','................','.......ssss.....','......ssissg....','.....ssssssgg...','.....ssssss.....','....ssssssss....','...sspppssss....','..ssspppssss....','.sssspppsss.....','..ssssssss......','...ssssss.......','.....g.g........','..eeeeeeeeeeee..','................','................', + ]], + ['Le gardien des vagues', 'sky', [ + '.......gg.......','......gggg......','.....iiiiii.....','.....ieeeei.....','.....iiiiii.....','......eeee......','......cccc......','......cccc......','.....eeeeee.....','.....eeeeee.....','.....cccccc.....','.....cccccc.....','....eeeeeeee....','....eeeii eee...'.replace(' ', ''),'gggggggggggggggg','ssssssssssssssss', + ]], + ['Les deux cerises', 'cream', [ + '................','........lll.....','.......lllll....','......llll......','......l.l.......','.....l...l......','....l.....l.....','..cccc...cccc...','.cccccc.cccccc..','.cecccc.cccecc..','.cccccc.cccccc..','.cccccc.cccccc..','..cccc...cccc...','................','................','................', + ]], + ['Un anneau de poussière', 'ink', [ + '................','..........pp....','......gggpppp...','....ggggppggg...','...ggggppggggg..','..ggggppggggggg.','..gggppgggggggg.','.gggppgggggggggg','.ggppggggggggggg','..ppggggggggggg.','.ppgggggggggggg.','pp.ggggggggggg..','p...ggggggggg...','......ggggg.....','................','................', + ]], +].map(([title, background, rows]) => ({ title, background, rows: rows.map(row => row.padEnd(16, '.')) })); + +export const ART_COLORS = { m: 'moss', e: 'cream', c: 'coral', g: 'gold', p: 'plum', s: 'sky', i: 'ink', l: 'leaf' }; diff --git a/src/colony-main.js b/src/colony-main.js index 87501d3..fe3d5e1 100644 --- a/src/colony-main.js +++ b/src/colony-main.js @@ -1,11 +1,12 @@ import './colony-style.css'; -import { COLORS, MOTIFS, ColonyGame, createColonyLevel, encodeColonySave, decodeColonySave, SAVE_KEY } from './colony-puzzle.js'; +import { COLORS, MOTIFS, COLONY_DIFFICULTIES, colonyDifficulty, ColonyGame, createColonyLevel, encodeColonySave, decodeColonySave, SAVE_KEY } from './colony-puzzle.js'; import { ColonyScene } from './colony-scene.js'; const $ = selector => document.querySelector(selector); let saved; try { saved = decodeColonySave(JSON.parse(localStorage.getItem(SAVE_KEY))); } catch { /* Storage is optional. */ } let game = saved?.game || new ColonyGame(), completed = saved?.completed || [], speed = saved?.speed || 1; let paused = false, hintQueue = null, lastSave = 0, scene, lastTime = 0, frame, statusText = '', wonRecorded = false, queuesSignature = ''; +let collectionPage = 0; const base = import.meta.env.BASE_URL; $('#app').innerHTML = `
@@ -16,7 +17,7 @@ $('#app').innerHTML = `
DE PETITES FOURMIS,
DE GRANDES IDÉES

Un petit
monde
en marche.

Une couleur. Une équipe.
Un aller-retour à la fois.

01
Faites de la place.

Choisissez une boîte. Ses fourmis récoltent les cubes accessibles de la même couleur.

02
Gardez le mouvement.

Cinq places seulement. Une boîte pleine libère sa place ; une couleur enfouie attend.

✳ Pas de chrono. Prenez votre temps.
-

cubes à rapporter
+

cubes à rapporter
La colonie se repose
LES CINQ PLACES0 / 5 occupées
@@ -27,14 +28,14 @@ $('#app').innerHTML = `
Les petits efforts font les belles choses.Une colonie, à votre rythme. ✳
-
VOS PETITS MONDES

La collection.

Six images, puis de nouvelles réserves et des boîtes plus petites.

+
VOS PETITS MONDES

La collection.

24 images, cinq paliers et 96 premiers puzzles, puis une suite de réserves variées.

${COLONY_DIFFICULTIES.map(d => ``).join('')}

Une petite colonie.

  1. Choisissez une boîte. Seule celle du dessus de chaque file est disponible. Son nombre indique les cubes qu'elle doit rapporter.
  2. Regardez les fourmis. Elles atteignent les cubes par l'extérieur et les espaces déjà dégagés, puis les ramènent au nid.
  3. Gérez cinq emplacements. Les boîtes restent jusqu'à leur remplissage. Si leur couleur est enfouie, elles attendent les autres équipes.
  4. Gardez une place libre. Cinq boîtes qui attendent peuvent bloquer la colonie. Annulez un choix ou demandez un indice pour repartir.

H : indice · Entrée : envoyer la boîte indiquée · U : annuler · R : recommencer · Espace : pause.

Votre progression se sauvegarde sur cet appareil.

`; function persist() { try { localStorage.setItem(SAVE_KEY, JSON.stringify(encodeColonySave(game, completed, speed))); } catch { /* Play remains available without storage. */ } } function status(text) { if (statusText !== text) { statusText = text; $('#colony-status').textContent = text; } } function colorStyle(c) { return `--box-color:${COLORS[c].hex}`; } function renderQueues() { - const signature = `${game.level.index}|${game.state.cursors}|${game.state.slots.includes(null)}|${hintQueue}|${game.won}`; + const signature = `${game.level.index}|${game.level.generation}|${game.state.cursors}|${game.state.slots.includes(null)}|${hintQueue}|${game.won}`; if (queuesSignature === signature) return; queuesSignature = signature; $('#colony-queues').innerHTML = game.level.queues.map((queue, q) => `
0${q + 1}${queue.slice(game.state.cursors[q]).map((box, i) => ``).join('') || '✓Tout est parti'}
`).join(''); $('#reserve-count').textContent = `${game.heads.reduce((n, _, q) => n + game.level.queues[q].length - game.state.cursors[q], 0)} boîtes en réserve`; @@ -42,6 +43,9 @@ function renderQueues() { function update() { $('#colony-number').textContent = `PUZZLE ${String(game.level.index + 1).padStart(2, '0')} · ${game.level.index < 6 ? 'LES PREMIERS PAS' : 'UN PEU PLUS LOIN'}`; $('#colony-title').textContent = game.level.title; $('#colony-remaining').textContent = game.remaining; + const classic = game.level.generation === 1 && game.level.index >= 6; + $('#colony-difficulty').textContent = `${classic ? 'Classique' : colonyDifficulty(game.level.index).name} · ${game.level.width} × ${game.level.height} · ${new Set(game.level.cells).size} couleurs`; + $('#colony-difficulty').dataset.tier = classic ? 0 : COLONY_DIFFICULTIES.indexOf(colonyDifficulty(game.level.index)); $('#colony-progress').style.width = `${100 * (1 - game.remaining / game.level.cells.length)}%`; const occupied = game.state.slots.filter(Boolean).length; $('#slot-count').textContent = `${occupied} / 5 occupées`; @@ -67,7 +71,7 @@ function launch(q) { if (!game.launch(q)) { status('Attendez qu’une boîte se remplisse pour libérer une place.'); return; } hintQueue = null; game.advance(0); status('La nouvelle équipe est en route. Observez les couleurs qui se dégagent.'); update(); persist(); } -function start(index) { game = new ColonyGame(createColonyLevel(index)); hintQueue = null; paused = false; wonRecorded = false; scene.setGame(game); status('Choisissez une boîte dans la réserve pour réveiller ses fourmis.'); update(); persist(); } +function start(index, generation = 2) { game = new ColonyGame(createColonyLevel(index, generation)); hintQueue = null; paused = false; wonRecorded = false; scene.setGame(game); status('Choisissez une boîte dans la réserve pour réveiller ses fourmis.'); update(); persist(); } function undo() { if (!game.undo()) return; hintQueue = null; wonRecorded = false; scene.setGame(game); status('Une petite marche arrière. Vous pouvez choisir une autre boîte.'); update(); persist(); } function hint() { const result = game.hint(); hintQueue = result.type === 'box' ? result.queue : null; @@ -76,27 +80,35 @@ function hint() { renderQueues(); } $('#colony-queues').addEventListener('click', event => { const button = event.target.closest('button[data-queue]'); if (button && !button.disabled) launch(Number(button.dataset.queue)); }); -$('#colony-undo').onclick = undo; $('#colony-hint').onclick = hint; $('#colony-restart').onclick = () => start(game.level.index); -$('#colony-next').onclick = () => start(game.level.index < 999999 ? game.level.index + 1 : 0); $('#colony-replay').onclick = () => start(game.level.index); +$('#colony-undo').onclick = undo; $('#colony-hint').onclick = hint; $('#colony-restart').onclick = () => start(game.level.index, game.level.generation); +$('#colony-next').onclick = () => start(game.level.index < 999999 ? game.level.index + 1 : 0); $('#colony-replay').onclick = () => start(game.level.index, game.level.generation); $('#colony-speed').onclick = () => { speed = speed === 1 ? 2 : 1; update(); persist(); }; $('#colony-pause').onclick = () => { paused = !paused; update(); }; $('#colony-help').onclick = () => $('#colony-help-dialog').showModal(); $('#colony-rules').onclick = () => $('#colony-help-dialog').showModal(); -$('#colony-collection').onclick = () => { - const page = Math.floor(game.level.index / 12) * 12; - $('#colony-levels').innerHTML = Array.from({ length: Math.min(12, 1000000 - page) }, (_, n) => { - const index = page + n, level = createColonyLevel(index); - const miniature = ``; - return ``; - }).join(''); $('#colony-level-input').value = game.level.index + 1; $('#colony-collection-dialog').showModal(); -}; +function renderCollection() { + const difficulty = colonyDifficulty(collectionPage); + $('#colony-chapter-copy').textContent = difficulty.copy; + document.querySelectorAll('[data-chapter]').forEach(button => button.setAttribute('aria-pressed', String(Number(button.dataset.chapter) === difficulty.start))); + $('#colony-page-label').textContent = `${collectionPage + 1} – ${Math.min(1000000, collectionPage + 12)}`; + $('#colony-prev-page').disabled = collectionPage === 0; $('#colony-next-page').disabled = collectionPage >= 999996; + $('#colony-levels').innerHTML = Array.from({ length: Math.min(12, 1000000 - collectionPage) }, (_, n) => { + const index = collectionPage + n, level = createColonyLevel(index); + const miniature = ``; + return ``; + }).join(''); +} +$('#colony-collection').onclick = () => { collectionPage = Math.floor(game.level.index / 12) * 12; renderCollection(); $('#colony-level-input').value = game.level.index + 1; $('#colony-collection-dialog').showModal(); }; +$('#colony-chapters').onclick = event => { const button = event.target.closest('[data-chapter]'); if (button) { collectionPage = Number(button.dataset.chapter); renderCollection(); } }; +$('#colony-prev-page').onclick = () => { collectionPage = Math.max(0, collectionPage - 12); renderCollection(); }; +$('#colony-next-page').onclick = () => { collectionPage = Math.min(999996, collectionPage + 12); renderCollection(); }; $('#colony-levels').onclick = event => { const button = event.target.closest('[data-level]'); if (button) { start(Number(button.dataset.level)); $('#colony-collection-dialog').close(); } }; $('#colony-jump').onsubmit = event => { event.preventDefault(); const index = Number($('#colony-level-input').value) - 1; if (Number.isSafeInteger(index) && index >= 0 && index < 1000000) { start(index); $('#colony-collection-dialog').close(); } }; document.querySelectorAll('[data-close]').forEach(button => button.onclick = () => button.closest('dialog').close()); document.addEventListener('keydown', event => { if (document.querySelector('dialog[open]') || /INPUT|SELECT|TEXTAREA/.test(event.target.tagName) || event.ctrlKey || event.metaKey || event.altKey) return; const key = event.key.toLowerCase(); - if (key === 'h') hint(); else if (key === 'u') undo(); else if (key === 'r') start(game.level.index); + if (key === 'h') hint(); else if (key === 'u') undo(); else if (key === 'r') start(game.level.index, game.level.generation); else if (key === 'enter' && hintQueue !== null) { event.preventDefault(); launch(hintQueue); } else if (key === ' ' && !event.target.closest('button,a')) { event.preventDefault(); paused = !paused; update(); } else if (/^[1-4]$/.test(key)) launch(Number(key) - 1); diff --git a/src/colony-puzzle.js b/src/colony-puzzle.js index bbaafc0..d869881 100644 --- a/src/colony-puzzle.js +++ b/src/colony-puzzle.js @@ -1,11 +1,21 @@ // Discrete rules, level construction and saves. No renderer or browser dependencies. +import { NEW_COLONY_ART, ART_COLORS } from './colony-art.js'; export const COLORS = { moss: { name: 'Sauge', hex: '#97b896' }, cream: { name: 'Crème', hex: '#f4dfaa' }, coral: { name: 'Corail', hex: '#e6816c' }, gold: { name: 'Miel', hex: '#efbe57' }, plum: { name: 'Prune', hex: '#77628e' }, sky: { name: 'Azur', hex: '#84b9ce' }, ink: { name: 'Encre', hex: '#344b4a' }, leaf: { name: 'Feuille', hex: '#547f63' }, }; -export const MOTIFS = ['La petite pousse', 'Un coin de forêt', 'À pas de renard', 'Le grand départ', 'La pause sucrée', 'Au cœur du jardin']; +const CLASSIC_MOTIFS = ['La petite pousse', 'Un coin de forêt', 'À pas de renard', 'Le grand départ', 'La pause sucrée', 'Au cœur du jardin']; +export const MOTIFS = [...CLASSIC_MOTIFS, ...NEW_COLONY_ART.map(art => art.title)]; +export const COLONY_DIFFICULTIES = [ + { name: 'Découverte', start: 0, copy: 'Apprenez les couleurs et les cinq places.' }, + { name: 'Malin', start: 6, copy: 'Nouvelles images, couleurs mêlées et premières boîtes à faire patienter.' }, + { name: 'Corsé', start: 24, copy: 'Des couronnes colorées ferment les passages. Coordonnez plusieurs équipes.' }, + { name: 'Difficile', start: 48, copy: 'Plus de couleurs et des boîtes réparties entre plusieurs couches.' }, + { name: 'Expert', start: 72, copy: 'Des réserves entrelacées. Gardez une place pour la couleur qui débloquera les autres.' }, +]; +export const colonyDifficulty = index => COLONY_DIFFICULTIES.findLast(d => index >= d.start); export const SAVE_KEY = 'cubecubecube-colony-v1'; const copy = value => JSON.parse(JSON.stringify(value)); const validIndex = n => Number.isSafeInteger(n) && n >= 0 && n < 1000000; @@ -84,15 +94,15 @@ export function reachable(level, remaining, color, reserved = new Set(), paths = return null; } -export function createColonyLevel(index = 0) { +export function createLegacyColonyLevel(index = 0) { if (!validIndex(index)) throw new RangeError('Invalid colony level'); - const motif = index % MOTIFS.length, tier = Math.floor(index / MOTIFS.length), size = 16; + const motif = index % CLASSIC_MOTIFS.length, tier = Math.floor(index / CLASSIC_MOTIFS.length), size = 16; const cells = Array.from({ length: size * size }, (_, id) => { const x = id % size, y = Math.floor(id / size); // Later journeys add a contrasting border, preserving each picture. return tier > 0 && (x === 0 || y === 0 || x === 15 || y === 15) ? ['gold', 'ink', 'plum'][tier % 3] : pixel(motif, x, y); }); - const level = { index, width: size, height: size, cells, title: MOTIFS[motif], queues: [[], [], [], []], solution: [] }; + const level = { index, generation: 1, width: size, height: size, cells, title: CLASSIC_MOTIFS[motif], queues: [[], [], [], []], solution: [] }; const remaining = cells.map((_, id) => id), quota = Math.max(12, 40 - tier * 4), colors = Object.keys(COLORS); let last = null; while (remaining.length) { @@ -111,6 +121,66 @@ export function createColonyLevel(index = 0) { return level; } +const levelCache = new Map(); +function randomSeed(seed) { + let s = seed >>> 0; + return () => { s = (s + 0x6d2b79f5) >>> 0; let t = Math.imul(s ^ s >>> 15, 1 | s); t ^= t + Math.imul(t ^ t >>> 7, 61 | t); return ((t ^ t >>> 14) >>> 0) / 4294967296; }; +} +function buildReserves(level, rank, random) { + const game = new ColonyGame(level), unassigned = Object.fromEntries(Object.keys(COLORS).map(color => [color, level.cells.filter(c => c === color).length])); + const targetWaiting = rank, quota = [40, 26, 20, 16, 12][rank]; + let waitingMoves = 0, maxOccupied = 0; + while (!game.won) { + const paths = outsidePaths(level, game.state.remaining); + const choices = Object.keys(COLORS).filter(color => unassigned[color] && reachable(level, game.state.remaining, color, new Set(), paths)); + if (!choices.length || !game.state.slots.includes(null)) throw new Error('Invalid reserve construction'); + const color = choices[Math.floor(random() * choices.length)], remaining = [...game.state.remaining]; + let accessible = 0; + while (accessible < unassigned[color]) { + const target = reachable(level, remaining, color); if (!target) break; + remaining.splice(remaining.indexOf(target.id), 1); accessible++; + } + const waiting = game.state.slots.filter(Boolean).length; + // A long quota crosses a colour boundary and waits for another team. + // Once the waiting budget is reached, a safely fillable box keeps a slot free. + const count = waiting < targetWaiting ? Math.min(unassigned[color], accessible + Math.max(1, Math.floor(quota / 3))) : Math.min(unassigned[color], accessible, quota + (rank === 0 ? 0 : Math.floor(random() * 5))); + const shortest = Math.min(...level.queues.map(q => q.length)); + const queues = [0, 1, 2, 3].filter(q => level.queues[q].length <= shortest + 1), queue = rank === 0 ? level.solution.length % 4 : queues[Math.floor(random() * queues.length)]; + const id = level.solution.length; level.queues[queue].push({ id, color, count }); level.solution.push(queue); unassigned[color] -= count; + if (!game.launch(queue)) throw new Error('Invalid reserve launch'); + maxOccupied = Math.max(maxOccupied, game.state.slots.filter(Boolean).length); + game.settle(); if (game.state.slots.some(Boolean)) waitingMoves++; + } + return { waitingMoves, maxOccupied, boxes: level.solution.length, colors: new Set(level.cells).size }; +} +export function createColonyLevel(index = 0, generation = 2) { + if (!validIndex(index)) throw new RangeError('Invalid colony level'); + if (generation === 1) return createLegacyColonyLevel(index); + if (generation !== 2) throw new RangeError('Invalid colony generation'); + if (levelCache.has(index)) return levelCache.get(index); + const motif = index % MOTIFS.length, cycle = Math.floor(index / MOTIFS.length), rank = COLONY_DIFFICULTIES.indexOf(colonyDifficulty(index)); + const random = randomSeed(Math.imul(index + 1, 2654435761)), border = [0, 2, 3, 3, 4][rank], size = 16 + border * 2; + const frameColors = ['ink', 'gold', 'plum', 'sky', 'coral', 'leaf'], offset = Math.floor(random() * frameColors.length); + const picture = Array.from({ length: 256 }, (_, id) => { + const x = id % 16, y = Math.floor(id / 16), px = cycle % 2 ? 15 - x : x; + if (motif < 6) return pixel(motif, px, y); + const art = NEW_COLONY_ART[motif - 6]; return ART_COLORS[art.rows[y][px]] || art.background; + }); + const pictureColors = [...new Set(picture)].sort((a, b) => picture.filter(c => c === b).length - picture.filter(c => c === a).length); + const rings = [pictureColors[0], pictureColors[1], rank < 3 ? pictureColors[0] : pictureColors[2] || frameColors[offset], frameColors.find(c => !pictureColors.slice(0, 3).includes(c))]; + const cells = Array.from({ length: size * size }, (_, id) => { + const x = id % size, y = Math.floor(id / size), depth = Math.min(x, y, size - 1 - x, size - 1 - y); + if (depth < border) return rings[depth]; + // Expert frames can vary their accents without obscuring the illustration. + if (rank === 4 && depth === border && (x + y + index) % 7 === 0) return frameColors[(offset + x + y) % frameColors.length]; + return picture[(y - border) * 16 + x - border]; + }); + const level = { index, generation: 2, width: size, height: size, cells, title: MOTIFS[motif], queues: [[], [], [], []], solution: [] }; + level.pressure = buildReserves(level, rank, random); + levelCache.set(index, level); if (levelCache.size > 36) levelCache.delete(levelCache.keys().next().value); + return level; +} + export class ColonyGame { constructor(level = createColonyLevel(), state = null) { this.level = level; this.history = []; @@ -143,7 +213,7 @@ export class ColonyGame { s.slots.forEach((box, slot) => { if (!box) return; const live = s.jobs.filter(j => j.slot === slot).length; - for (let i = live; i < Math.min(4, box.remaining); i++) { + for (let i = live; i < box.remaining; i++) { const target = reachable(this.level, s.remaining, box.color, reserved, paths); if (!target) break; reserved.add(target.id); @@ -156,13 +226,13 @@ export class ColonyGame { settle() { for (let i = 0; i < this.level.cells.length * 2; i++) { this.advance(100); if (!this.state.jobs.length) break; } return this; } get stalled() { return !this.won && !this.state.jobs.length && this.state.slots.every(Boolean) && !this.state.slots.some(b => reachable(this.level, this.state.remaining, b.color)); } undo() { if (!this.history.length) return false; this.state = this.history.pop(); return true; } - hint(limit = 2500) { + hint(limit = 2500, timeLimit = 300) { const settled = new ColonyGame(this.level, this.state).settle(); if (settled.won) return { type: 'wait' }; - const seen = new Set(); let visited = 0; + const seen = new Set(), deadline = performance.now() + timeLimit; let visited = 0, exhausted = false; const search = game => { if (game.won) return []; - if (++visited > limit) return null; + if (++visited > limit || performance.now() > deadline) { exhausted = true; return null; } const s = game.state, key = `${s.cursors}|${s.slots.map(b => b ? `${b.color}:${b.remaining}` : '-')}|${s.remaining.join(',')}`; if (seen.has(key)) return null; seen.add(key); if (!s.slots.includes(null)) return null; @@ -170,22 +240,23 @@ export class ColonyGame { if (!game.heads[q]) continue; const next = new ColonyGame(this.level, s); next.launch(q); next.settle(); const rest = search(next); if (rest) return [q, ...rest]; + if (exhausted) break; } return null; }; const path = search(settled); if (path?.length) return this.state.slots.includes(null) ? { type: 'box', queue: path[0] } : { type: 'wait' }; - return this.state.jobs.length ? { type: 'wait' } : visited > limit ? { type: 'unknown' } : { type: 'undo' }; + return this.state.jobs.length ? { type: 'wait' } : exhausted ? { type: 'unknown' } : { type: 'undo' }; } } export function encodeColonySave(game, completed = [], speed = 1) { - return { version: 1, index: game.level.index, state: copy(game.state), history: copy(game.history), completed: completed.filter(validIndex), speed: speed === 2 ? 2 : 1 }; + return { version: 2, generation: game.level.generation || 2, index: game.level.index, state: copy(game.state), history: copy(game.history), completed: completed.filter(validIndex), speed: speed === 2 ? 2 : 1 }; } export function decodeColonySave(raw) { try { - if (!raw || raw.version !== 1 || !validIndex(raw.index)) return null; - const level = createColonyLevel(raw.index), game = new ColonyGame(level); + if (!raw || ![1, 2].includes(raw.version) || !validIndex(raw.index) || raw.version === 2 && ![1, 2].includes(raw.generation)) return null; + const level = createColonyLevel(raw.index, raw.version === 1 ? 1 : raw.generation), game = new ColonyGame(level); const validate = state => { if (!state || !Array.isArray(state.remaining) || !Array.isArray(state.cursors) || state.cursors.length !== 4 || !Array.isArray(state.slots) || state.slots.length !== 5 || !Array.isArray(state.jobs) || !Array.isArray(state.launched) || !Number.isSafeInteger(state.serial) || state.serial < 0) return false; if (state.cursors.some((n, q) => !Number.isInteger(n) || n < 0 || n > level.queues[q].length)) return false; diff --git a/src/colony-scene.js b/src/colony-scene.js index 60e1add..41e84fd 100644 --- a/src/colony-scene.js +++ b/src/colony-scene.js @@ -12,7 +12,7 @@ export class ColonyScene { this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); this.renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); this.renderer.setClearColor(0x000000, 0); this.renderer.outputColorSpace = THREE.SRGBColorSpace; - this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; + this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = THREE.PCFShadowMap; const canvas = this.renderer.domElement; canvas.id = 'colony-canvas'; canvas.tabIndex = 0; canvas.setAttribute('aria-label', 'Plateau 3D de la colonie. Les fourmis ramassent les cubes et les rapportent au nid.'); container.append(canvas); @@ -25,6 +25,7 @@ export class ColonyScene { this.cubeGeo = new RoundedBoxGeometry(.45, .37, .45, 2, .035); this.colorMaterials = Object.fromEntries(Object.entries(COLORS).map(([k, c]) => [k, this.material(c.hex)])); this.dark = this.material('#354641'); this.eye = this.material('#fefbe8'); this.legMat = this.material('#344741'); + this.antPaint = this.material('#ffffff'); this.antParts = []; this.tray = new THREE.Group(); this.scene.add(this.tray); const ground = new THREE.Mesh(new THREE.PlaneGeometry(40, 40), this.material('#eff0e3')); ground.rotation.x = -Math.PI / 2; ground.position.y = -.22; ground.receiveShadow = true; this.scene.add(ground); // Small paper-like garden decorations, built from geometry. @@ -45,7 +46,7 @@ export class ColonyScene { box(parent, position, size, mat) { const mesh = new THREE.Mesh(this.rounded, mat); mesh.position.set(...position); mesh.scale.set(...size); mesh.castShadow = true; mesh.receiveShadow = true; parent.add(mesh); return mesh; } - point(x, y) { return new THREE.Vector3((x - 7.5) * .48, .08, (y - 7.5) * .48 - 1); } + point(x, y) { const { width, height } = this.game.level, cell = 7.68 / Math.max(width, height); return new THREE.Vector3((x - (width - 1) / 2) * cell, .08, (y - (height - 1) / 2) * cell - 1); } resize() { const w = this.container.clientWidth, h = this.container.clientHeight; if (!w || !h) return; @@ -54,6 +55,7 @@ export class ColonyScene { } setGame(game) { this.game = game; + this.initAntInstances(game.level.cells.length); for (const { group } of this.ants.values()) this.scene.remove(group); this.ants.clear(); if (this.cubes) { this.scene.remove(this.cubes); this.cubes.dispose(); } for (const child of [...this.tray.children]) { @@ -66,11 +68,11 @@ export class ColonyScene { this.box(this.tray, [0, -.01, -1], [7.83, .12, 7.83], paper); this.box(this.tray, [-4.03, .13, -1], [.16, .38, 8.23], wood); this.box(this.tray, [4.03, .13, -1], [.16, .38, 8.23], wood); this.box(this.tray, [0, .13, -5.03], [8.23, .38, .16], wood); this.box(this.tray, [0, .13, 3.03], [8.23, .38, .16], wood); - const n = game.level.cells.length, matrix = new THREE.Matrix4(); + const n = game.level.cells.length, matrix = new THREE.Matrix4(), cellScale = 16 / game.level.width; const backing = new THREE.InstancedMesh(this.cubeGeo, this.backingMat ||= this.material('#ffffff'), n); game.level.cells.forEach((c, id) => { - const p = this.point(id % 16, Math.floor(id / 16)); p.y = .015; - matrix.compose(p, new THREE.Quaternion(), new THREE.Vector3(1, .03, 1)); backing.setMatrixAt(id, matrix); + const p = this.point(id % game.level.width, Math.floor(id / game.level.width)); p.y = .015; + matrix.compose(p, new THREE.Quaternion(), new THREE.Vector3(cellScale, .03, cellScale)); backing.setMatrixAt(id, matrix); backing.setColorAt(id, new THREE.Color(COLORS[c].hex).lerp(new THREE.Color('#fff5df'), .68)); }); this.tray.add(backing); this.cubes = new THREE.InstancedMesh(this.cubeGeo, this.cubeMat ||= this.material('#ffffff'), n); this.cubes.castShadow = true; this.cubes.receiveShadow = true; @@ -81,34 +83,42 @@ export class ColonyScene { } sync() { if (!this.game) return; - const ids = new Set(this.game.state.remaining), matrix = new THREE.Matrix4(); + const ids = new Set(this.game.state.remaining), matrix = new THREE.Matrix4(), scale = 16 / this.game.level.width; this.game.level.cells.forEach((c, id) => { - const p = this.point(id % 16, Math.floor(id / 16)); p.y = .245; - matrix.compose(p, new THREE.Quaternion(), new THREE.Vector3(ids.has(id) ? 1 : 0, ids.has(id) ? 1 : 0, ids.has(id) ? 1 : 0)); this.cubes.setMatrixAt(id, matrix); + const p = this.point(id % this.game.level.width, Math.floor(id / this.game.level.width)); p.y = .245; + matrix.compose(p, new THREE.Quaternion(), new THREE.Vector3(ids.has(id) ? scale : 0, ids.has(id) ? 1 : 0, ids.has(id) ? scale : 0)); this.cubes.setMatrixAt(id, matrix); }); this.cubes.instanceMatrix.needsUpdate = true; this.cubes.computeBoundingSphere(); } makeAnt(job) { - const group = new THREE.Group(), color = this.colorMaterials[job.color]; - const body = (z, size, material) => { const m = new THREE.Mesh(this.sphere, material); m.position.set(0, .1, z); m.scale.set(...size); m.castShadow = true; group.add(m); return m; }; - body(-.13, [.09, .08, .12], color); body(.01, [.055, .06, .07], color); body(.12, [.08, .065, .075], color); - for (const side of [-1, 1]) body(.16, [.021, .024, .021], this.eye).position.x = side * .041; - const legs = []; - for (const side of [-1, 1]) for (let i = 0; i < 3; i++) { - const leg = new THREE.Mesh(this.legGeo, this.legMat); leg.scale.y = .19; leg.position.set(side * .092, .055, -.08 + i * .075); leg.rotation.z = side * 1.1; leg.rotation.x = (i - 1) * .6; group.add(leg); legs.push(leg); - } - for (const side of [-1, 1]) { - const antenna = new THREE.Mesh(this.legGeo, color); antenna.scale.set(.7, .12, .7); antenna.position.set(side * .046, .12, .215); antenna.rotation.x = .9; antenna.rotation.z = side * .5; group.add(antenna); - } - const cargo = new THREE.Mesh(this.cubeGeo, color); cargo.scale.setScalar(.58); cargo.position.set(0, .28, .1); group.add(cargo); + const group = new THREE.Object3D(); group.scale.setScalar(16 / this.game.level.width); const route = [new THREE.Vector3((job.slot - 2) * .46, .08, 4.5), new THREE.Vector3(0, .08, 4.13), ...job.route.map(p => this.point(...p))]; route.at(-1).y = .4; // Each route follows actual outside-connected empty cells. const lengths = [0]; for (let i = 1; i < route.length; i++) lengths.push(lengths[i - 1] + route[i].distanceTo(route[i - 1])); - this.scene.add(group); return { group, legs, cargo, route, lengths, distance: lengths.at(-1) }; + return { group, route, lengths, distance: lengths.at(-1) }; + } + initAntInstances(capacity) { + for (const part of this.antParts) { this.scene.remove(part.mesh); part.mesh.dispose(); } + this.antParts = []; + const part = (geometry, position, scale, rotation = [0, 0, 0], options = {}) => { + const mesh = new THREE.InstancedMesh(geometry, options.material || this.antPaint, capacity); + mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage); mesh.count = 0; mesh.frustumCulled = false; mesh.castShadow = Boolean(options.shadow); + const transform = new THREE.Object3D(); transform.position.set(...position); transform.scale.set(...scale); transform.rotation.set(...rotation); + if (!options.material) { mesh.setColorAt(0, new THREE.Color('#ffffff')); mesh.instanceColor.setUsage(THREE.DynamicDrawUsage); } + this.scene.add(mesh); this.antParts.push({ mesh, transform, painted: !options.material, ...options }); + }; + part(this.sphere, [0, .1, -.13], [.09, .08, .12], undefined, { shadow: true }); + part(this.sphere, [0, .1, .01], [.055, .06, .07]); part(this.sphere, [0, .1, .12], [.08, .065, .075]); + for (const side of [-1, 1]) part(this.sphere, [side * .041, .1, .16], [.021, .024, .021], undefined, { material: this.eye }); + for (const side of [-1, 1]) for (let i = 0; i < 3; i++) part(this.legGeo, [side * .092, .055, -.08 + i * .075], [1, .19, 1], [(i - 1) * .6, 0, side * 1.1], { material: this.legMat, leg: this.antParts.length }); + for (const side of [-1, 1]) part(this.legGeo, [side * .046, .12, .215], [.7, .12, .7], [.9, 0, side * .5]); + part(this.cubeGeo, [0, .28, .1], [.58, .58, .58], undefined, { cargo: true, shadow: true }); + this.antMatrix ||= new THREE.Matrix4(); } render(time) { const live = new Set(this.game.state.jobs.map(j => j.id)); for (const [id, ant] of this.ants) if (!live.has(id)) { this.scene.remove(ant.group); this.ants.delete(id); } + let instance = 0; for (const job of this.game.state.jobs) { if (!this.ants.has(job.id)) this.ants.set(job.id, this.makeAnt(job)); const ant = this.ants.get(job.id), progress = Math.min(1, job.elapsed / job.duration), returning = progress >= .5; @@ -117,9 +127,16 @@ export class ColonyScene { const t = (distance - ant.lengths[i - 1]) / Math.max(.001, ant.lengths[i] - ant.lengths[i - 1]); ant.group.position.copy(ant.route[i - 1]).lerp(ant.route[i], t); const direction = ant.route[i].clone().sub(ant.route[i - 1]); ant.group.rotation.y = Math.atan2(direction.x, direction.z) + (returning ? Math.PI : 0); - ant.cargo.visible = job.picked; ant.group.position.y += this.reducedMotion ? 0 : Math.sin(time * 22 + job.id) * .012; - ant.legs.forEach((leg, l) => { leg.rotation.x = this.reducedMotion ? 0 : Math.sin(time * 25 + l * Math.PI + job.id) * .4; }); + ant.group.position.y += this.reducedMotion ? 0 : Math.sin(time * 22 + job.id) * .012; ant.group.updateMatrix(); + for (const part of this.antParts) { + if (part.leg !== undefined) part.transform.rotation.x = this.reducedMotion ? 0 : Math.sin(time * 25 + part.leg * Math.PI + job.id) * .4; + if (part.cargo) part.transform.scale.setScalar(job.picked ? .58 : 0); + part.transform.updateMatrix(); this.antMatrix.multiplyMatrices(ant.group.matrix, part.transform.matrix); part.mesh.setMatrixAt(instance, this.antMatrix); + if (part.painted) part.mesh.setColorAt(instance, this.colorMaterials[job.color].color); + } + instance++; } + for (const part of this.antParts) { part.mesh.count = instance; part.mesh.instanceMatrix.needsUpdate = true; if (part.painted) part.mesh.instanceColor.needsUpdate = true; } this.renderer.render(this.scene, this.camera); } dispose() { diff --git a/src/colony-style.css b/src/colony-style.css index b11dcef..a78cc41 100644 --- a/src/colony-style.css +++ b/src/colony-style.css @@ -25,6 +25,8 @@ .colony-heading { display: flex; align-items: center; justify-content: space-between; gap: 15px; margin: 0 3px 15px; } .colony-heading .eyebrow { font-size: 8px; letter-spacing: 1.1px; } .colony-heading h2 { font-size: 22px; font-weight: 500; letter-spacing: -.6px; margin: 6px 0 0; } +.colony-difficulty { display: inline-block; font-size: 8px; color: #697e5a; background: #e8eedf; border-radius: 20px; padding: 5px 9px; margin-top: 9px; } +.colony-difficulty[data-tier="3"], .colony-difficulty[data-tier="4"] { color: #806047; background: #f0e6d6; } .colony-counter { display: flex; align-items: center; flex-direction: column; } .colony-counter strong { font-family: Georgia, serif; font-size: 35px; font-weight: 400; line-height: 1; } .colony-counter > span { font-size: 8px; color: var(--muted); margin-top: 7px; white-space: nowrap; } @@ -108,6 +110,13 @@ #colony-jump { display: flex; align-items: center; gap: 10px; font-size: 11px; flex-wrap: wrap; } #colony-jump input { width: 100px; padding: 9px; border: 1px solid var(--line); border-radius: 7px; background: #fffdf5; color: var(--ink); font: inherit; } #colony-jump button { padding: 10px; background: var(--accent); border-radius: 7px; } +.colony-chapters { display: flex; flex-wrap: wrap; gap: 7px; margin: 20px 0 10px; } +.colony-chapters button { flex: 1; min-width: 88px; border: 1px solid var(--line); border-radius: 9px; padding: 10px 8px; font-size: 10px; } +.colony-chapters small { display: block; font-size: 8px; color: var(--muted); margin-top: 5px; white-space: nowrap; } +.colony-chapters button[aria-pressed="true"] { background: var(--accent); border-color: #9bad8b; } +.colony-pages { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-top: 18px; font-size: 10px; } +.colony-pages button { padding: 8px 0; font-size: 10px; } +.colony-pages > span { font-size: 9px; color: var(--muted); } @media (max-width: 1100px) { .colony-layout { grid-template-columns: minmax(350px, 1fr) 230px; gap: 27px; max-width: 950px; } .colony-intro { display: none; } .colony-header { gap: 12px; } .colony-header nav a { padding: 10px 12px; } #colony-scene { height: 460px; } } @media (max-width: 700px) { .colony-header { padding: 17px 0; flex-wrap: wrap; justify-content: space-between; gap: 15px 8px; width: 92%; } diff --git a/src/dizaines-puzzle.js b/src/dizaines-puzzle.js new file mode 100644 index 0000000..6ff77f7 --- /dev/null +++ b/src/dizaines-puzzle.js @@ -0,0 +1,19 @@ +import {checkIndex,clone,random,shuffle,searchPlan} from './pocket-core.js'; +export function numberLine(level,field,a,b){ + if(!Number.isInteger(a)||!Number.isInteger(b)||a===b||a<0||b<0||a>=field.length||b>=field.length)return false; + const lo=Math.min(a,b),hi=Math.max(a,b);if(field.slice(lo+1,hi).every(v=>v===null))return true; + const ax=a%level.cols,ay=Math.floor(a/level.cols),bx=b%level.cols,by=Math.floor(b/level.cols),dx=bx-ax,dy=by-ay; + if(dx&&dy&&Math.abs(dx)!==Math.abs(dy))return false;const n=Math.max(Math.abs(dx),Math.abs(dy));for(let i=1;iv===null?[id]:[]),rng),candidates=[];for(let a=0;a({field:[...level.field],pairs:0}),move,won:(level,state)=>state.field.every(v=>v===null),actions,plan:(level,state)=>searchPlan(dizainesRules,level,state,5000)}; diff --git a/src/dunes-puzzle.js b/src/dunes-puzzle.js new file mode 100644 index 0000000..d120c5e --- /dev/null +++ b/src/dunes-puzzle.js @@ -0,0 +1,68 @@ +import { checkIndex, clone, random, shuffle, searchPlan } from './pocket-core.js'; +const TITLES=['Un petit tas de sable','Les grains du matin','De bord en bord','Un peu de place','Le pont des couleurs','Une douce cascade','Les petites dunes','Entre les pierres','Le mélange délicat','Les couleurs enfouies','La grande traversée','La dernière dune']; +export const SAND_UNIT=4; +export const SAND_SHAPES=[[[0,0],[1,0],[0,1],[1,1]],[[0,0],[0,1],[1,1]],[[0,0],[1,0],[2,0]],[[0,0],[1,0],[1,1],[2,1]],[[0,0],[1,0],[2,0],[1,1]]]; +export const sandWidth=piece=>(Math.max(...piece.shape.map(p=>p[0]))+1)*SAND_UNIT; +export const sandGrains=piece=>piece.shape.length*SAND_UNIT**2; +export function spanningSand(level,field){ + const seen=new Uint8Array(field.length),components=[]; + for(let start=0;start=level.width||yy<0||yy>=level.height||seen[next]||field[next]!==color)continue;seen[next]=1;ids.push(next);} + } + if(left&&right)components.push({color,ids}); + } + return components; +} +export class SandFlow{ + constructor(level,state,action){ + this.level=level;this.state=clone(state);this.tick=0;this.done=false;this.flash=null; + const piece=level.queues[action.q]?.[state.queues[action.q]]; + if(!piece||!Number.isInteger(action.x)||action.x<0||action.x+sandWidth(piece)>level.width){this.invalid=true;this.done=true;return;} + const ids=[];for(const [sx,sy] of piece.shape)for(let y=0;ythis.state.field[id]!==0)){this.invalid=true;this.done=true;return;} + for(const id of ids)this.state.field[id]=piece.color+1;this.state.queues[action.q]++;this.state.added+=ids.length; + } + step(){ + if(this.done)return; + if(this.flash){if(--this.flash.remaining<=0)this.flash=null;this.tick++;return;} + const {width:w,height:h}=this.level,f=this.state.field;let changed=false; + for(let y=h-2;y>=0;y--)for(let n=0;n=0&&xxc.ids);this.flash={cells:ids.map(id=>({id,color:f[id]-1})),remaining:8};for(const id of ids)f[id]=0;this.state.cleared+=ids.length;this.state.bursts+=spans.length;}else this.done=true;} + if(this.tick>500)throw new Error('Sand did not settle'); + } +} +function move(level,state,action){ + if(!action||!Number.isInteger(action.q)||!level.queues[action.q])return null; + const flow=new SandFlow(level,state,action);if(flow.invalid)return null;while(!flow.done)flow.step();return flow.state; +} +const initial=level=>({field:[...level.field],queues:[0,0,0],added:0,cleared:0,bursts:0}); +const won=(level,state)=>state.bursts>=level.goal; +const cache=new Map(); +export function createDunesLevel(index){ + checkIndex(index);if(cache.has(index))return clone(cache.get(index)); + const tier=Math.floor(index/12),rng=random(98317+index*6173),width=24+(tier>=2?4:0)+(tier===3?4:0),height=40+tier*3,goal=2+tier,colors=shuffle([0,1,2,3,4,5,6,7],rng).slice(0,goal),field=Array(width*height).fill(0); + const heap=5+Math.floor(rng()*3);for(let x=0;x=2)for(let y=height-5-tier;ylevel.queues.flatMap((q,id)=>{const p=q[state.queues[id]];return p?Array.from({length:Math.floor((level.width-sandWidth(p))/4)+1},(_,n)=>({q:id,x:n*4})):[];}).filter(a=>move(level,state,a)), + plan:(level,state)=>searchPlan(dunesRules,level,state,700), +}; diff --git a/src/ecluses-puzzle.js b/src/ecluses-puzzle.js new file mode 100644 index 0000000..0c98f6d --- /dev/null +++ b/src/ecluses-puzzle.js @@ -0,0 +1,56 @@ +import { checkIndex, clone, random, shuffle, searchPlan } from './pocket-core.js'; +const TITLES=['Les petites vannes','Une touche de couleur','Le bassin du jardin','Les deux ruisseaux','Le bon mélange','Les billes du matin','Le détour tranquille','Toutes les couleurs','La réserve du haut','Un passage délicat','Les bassins voisins','La dernière écluse']; +function mix(level,state,room){ + const ids=state.rooms[room],bombs=ids.filter(id=>level.balls[id].bomb),balls=ids.filter(id=>!level.balls[id].bomb); + if(bombs.length&&balls.length){state.lost.push(...balls);state.bombsGone.push(...bombs);state.rooms[room]=[];return;} + const color=balls.map(id=>state.colors[id]).find(c=>c!==null&&c!==undefined); + if(color!==undefined)for(const id of balls)if(state.colors[id]===null)state.colors[id]=color; +} +function move(level,state,pin){ + if(!Number.isInteger(pin)||!level.pins[pin]||state.opened.includes(pin)||state.lost.length)return null; + const next=clone(state);next.opened.push(pin);next.opened.sort((a,b)=>a-b); + for(let guard=0;guardp.from===room&&next.opened.includes(id));if(!gate)continue; + next.rooms[room]=[];changed=true; + if(Number.isInteger(gate.to)){next.rooms[gate.to].push(...ids);mix(level,next,gate.to);} + else if(gate.to==='basket'){ + if(ids.some(id=>level.balls[id].bomb)){next.lost.push(...next.collected,...ids.filter(id=>!level.balls[id].bomb));next.collected=[];next.bombsGone.push(...ids.filter(id=>level.balls[id].bomb));} + else for(const id of ids)(next.colors[id]===null?next.lost:next.collected).push(id); + }else for(const id of ids)(level.balls[id].bomb?next.bombsGone:next.lost).push(id); + } + if(!changed)break; + } + return next; +} +export function createEclusesLevel(index){ + checkIndex(index);const tier=Math.floor(index/12),groups=tier===0?1:tier===3?3:2,rng=random(21563+index*8273),rooms=[],balls=[],pins=[],solution=[],colors=shuffle([0,1,2,3,4,5,6,7],rng); + const addRoom=(x,y,w,h,name)=>{rooms.push({x,y,w,h,name,balls:[]});return rooms.length-1;}; + const addBalls=(room,count,color,bomb=false)=>{for(let n=0;naddRoom(center,275,groups===1?195:groups===2?175:132,106,'Le petit bassin')); + const pool=tier>=2?addRoom(320,425,255,90,'Le grand bassin'):null; + for(let group=0;group=1){const danger=addRoom(tier===3?590:560,pool===null?410:335,54,62,'La petite bombe');addBalls(danger,1,null,true);pins.push({from:danger,to:pool??'basket',name:'La bombe · attention'});} + const level={index,tier,title:TITLES[index%12],rooms,balls,pins,solution,total:balls.filter(b=>!b.bomb).length}; + return level; +} +export const eclusesRules={ + create:createEclusesLevel,initial:level=>({opened:[],rooms:level.rooms.map(r=>[...r.balls]),colors:level.balls.map(b=>b.color),collected:[],lost:[],bombsGone:[]}),move, + won:(level,state)=>state.collected.length===level.total&&!state.lost.length, + actions:(level,state)=>state.lost.length?[]:level.pins.map((_,id)=>id).filter(id=>!state.opened.includes(id)&&!move(level,state,id).lost.length).sort((a,b)=>Number(level.balls[state.rooms[level.pins[b].from][0]]?.color!==null)-Number(level.balls[state.rooms[level.pins[a].from][0]]?.color!==null)), + plan:(level,state)=>state.lost.length?null:searchPlan(eclusesRules,level,state,16000), +}; diff --git a/src/escapade-puzzle.js b/src/escapade-puzzle.js new file mode 100644 index 0000000..5f187d0 --- /dev/null +++ b/src/escapade-puzzle.js @@ -0,0 +1,113 @@ +import { checkIndex, clone, random, shuffle } from './pocket-core.js'; + +const same = (a, b) => a[0] === b[0] && a[1] === b[1]; +const key = p => p.join(','); +const DIRS = [[1, 0], [-1, 0], [0, 1], [0, -1]]; +const TITLES = ['La porte du jardin', 'À petits pas', 'Le sentier', 'Les voisins', 'Le détour fleuri', 'Les allées', 'Cache-cache', 'Les grands chemins', 'Les croisements', 'La ronde', 'Les passages secrets', 'Tout le monde rentre']; +function candidate(index, seed) { + const rng = random(seed), tier = Math.floor(index / 12), size = 6 + tier, count = 3 + tier; + const border = []; + for (let n = 1; n < size - 1; n++) border.push([n, 0], [n, size - 1], [0, n], [size - 1, n]); + const holes = shuffle(border, rng).slice(0, count), colors = shuffle([0, 1, 2, 3, 4, 5], rng); + const used = new Set(), reserved = new Set(holes.map(key)), snakes = [], paths = []; + const walls = shuffle(Array.from({ length: (size - 2) ** 2 }, (_, i) => [i % (size - 2) + 1, Math.floor(i / (size - 2)) + 1]), rng).slice(0, tier + (index % 4 === 3 ? 2 : 0)); + const wallSet = new Set(walls.map(key)); + for (let id = 0; id < count; id++) { + const length = 3 + (id + index) % (2 + Math.min(tier, 1)), desired = length + 2 + tier + index % 3; + let best = [holes[id]], budget = 1500; + function grow(path) { + if (!budget--) return false; + if (path.length > best.length) best = path.map(p => [...p]); + if (path.length === desired) return true; + for (const [dx, dy] of shuffle(DIRS, rng)) { + const p = [path.at(-1)[0] + dx, path.at(-1)[1] + dy]; + if (p.some(n => n < 0 || n >= size) || used.has(key(p)) || wallSet.has(key(p)) || reserved.has(key(p)) || path.some(q => same(p, q))) continue; + path.push(p); if (grow(path)) return true; path.pop(); + } + return false; + } + grow([holes[id]]); if (best.length < length + 1) return null; + const cells = best.slice(-length), route = best.slice(0, best.length - length).reverse(); + cells.forEach(p => used.add(key(p))); snakes.push({ id, color: colors[id], cells, hole: holes[id] }); paths.push(route); + } + let score = 0; + for (let i = 0; i < count; i++) for (let j = i + 1; j < count; j++) score += paths[i].filter(p => snakes[j].cells.some(c => same(c, p))).length * 3; + score += paths.reduce((n, path) => n + path.length, 0); + const solution = []; + for (let id = count - 1; id >= 0; id--) for (const to of paths[id]) solution.push({ id, end: 'head', to }); + return { index, tier, title: TITLES[index % 12], size, walls, snakes, solution, score }; +} +export function createEscapadeLevel(index) { + checkIndex(index); let best = null; + for (let attempt = 0; attempt < 24; attempt++) { + const next = candidate(index, 32719 + index * 92821 + attempt * 1033); + if (next && (!best || next.score > best.score)) best = next; + if (attempt >= 5 && best?.score >= (3 + Math.floor(index / 12)) * 5) break; + } + if (!best) throw new Error('Could not construct escapade'); return best; +} +function step(level, state, action) { + if (!action || !Number.isInteger(action.id) || !['head', 'tail'].includes(action.end) || !Array.isArray(action.to) || action.to.length !== 2 || !action.to.every(Number.isInteger)) return null; + const snake = state.snakes.find(s => s.id === action.id); if (!snake) return null; + const cells = action.end === 'tail' ? [...snake.cells].reverse() : snake.cells; + if (Math.abs(cells[0][0] - action.to[0]) + Math.abs(cells[0][1] - action.to[1]) !== 1) return null; + if (action.to.some(n => n < 0 || n >= level.size) || level.walls.some(w => same(w, action.to))) return null; + if (level.snakes.some(s => s.id !== snake.id && same(s.hole, action.to))) return null; + if (state.snakes.some(s => (s.id === snake.id ? cells.slice(0, -1) : s.cells).some(c => same(c, action.to)))) return null; + const next = clone(state), moved = next.snakes.find(s => s.id === snake.id); + if (same(level.snakes.find(s => s.id === snake.id).hole, action.to)) next.snakes = next.snakes.filter(s => s.id !== snake.id); + else { const body = [action.to, ...cells.slice(0, -1)]; moved.cells = action.end === 'tail' ? body.reverse() : body; } + return next; +} +function escapeRoute(level, state, id, deadline) { + const initial = state.snakes.find(s => s.id === id), queue = [{ cells: initial.cells, actions: [] }], seen = new Set([JSON.stringify(initial.cells)]); + for (let n = 0; n < queue.length && n < 5000 && Date.now() < deadline; n++) { + const { cells, actions } = queue[n], temp = { snakes: state.snakes.map(s => s.id === id ? { ...s, cells } : s) }; + for (const end of ['head', 'tail']) { + const first = end === 'head' ? cells[0] : cells.at(-1); + for (const [dx, dy] of DIRS) { + const action = { id, end, to: [first[0] + dx, first[1] + dy] }, next = step(level, temp, action); if (!next) continue; + const body = next.snakes.find(s => s.id === id); if (!body) return [...actions, action]; + const k = JSON.stringify(body.cells); if (seen.has(k)) continue; seen.add(k); queue.push({ cells: body.cells, actions: [...actions, action] }); + } + } + } + return null; +} +export const escapadeRules = { + create: createEscapadeLevel, + initial: level => ({ snakes: level.snakes.map(({ id, color, cells }) => ({ id, color, cells: clone(cells) })) }), + won: (_, state) => !state.snakes.length, + move: step, + actions(level, state) { + return state.snakes.flatMap(s => ['head', 'tail'].flatMap(end => { + const p = end === 'head' ? s.cells[0] : s.cells.at(-1); + return DIRS.map(([dx, dy]) => ({ id: s.id, end, to: [p[0] + dx, p[1] + dy] })).filter(a => step(level, state, a)); + })); + }, + plan(level, start) { + if (!start.snakes.length) return []; + let prefix = this.initial(level); const startKey = JSON.stringify(start); + for (let i = 0; i <= level.solution.length; i++) { + if (JSON.stringify(prefix) === startKey) return level.solution.slice(i); + if (i < level.solution.length) prefix = step(level, prefix, level.solution[i]); + } + // First try the constructed route. It is instant for an untouched board. + let state = clone(start), canonical = []; + for (const action of level.solution) { + if (!state.snakes.some(s => s.id === action.id)) continue; + const next = step(level, state, action); if (!next) { canonical = null; break; } + canonical.push(action); state = next; + } + if (canonical && !state.snakes.length) return canonical; + // Search real body configurations, then verify that ALL remaining creatures escape. + const deadline = Date.now() + 120; state = clone(start); const result = []; + while (state.snakes.length) { + let route = null; + for (const snake of [...state.snakes].reverse()) { route = escapeRoute(level, state, snake.id, deadline); if (route) break; } + if (!route) return null; + for (const action of route) { state = step(level, state, action); result.push(action); } + } + return result; + }, +}; diff --git a/src/fringale-puzzle.js b/src/fringale-puzzle.js new file mode 100644 index 0000000..e377c12 --- /dev/null +++ b/src/fringale-puzzle.js @@ -0,0 +1,62 @@ +import { checkIndex, clone, random, shuffle } from './pocket-core.js'; +import { distance } from './physics-geometry.js'; +const TITLES=['Une petite faim','Le jardin des baies','Les fruits du matin','Un peu plus grand','Le coin des douceurs','Le passage étroit','Les petites récoltes','Le grand goûter','Avant de grandir','Un jardin gourmand','Les derniers fruits','La grande fringale']; +export const holeRadius=mass=>13+Math.sqrt(mass)*3; +export const itemNames={berry:'Baie',apple:'Pomme',cake:'Petit gâteau',melon:'Melon',pot:'Pot fleuri'}; +const rectDistance=(p,r)=>distance(p,[Math.max(r.x,Math.min(r.x+r.w,p[0])),Math.max(r.y,Math.min(r.y+r.h,p[1]))]); +function penetrations(level,p,radius){return [Math.max(0,50+radius-p[0]),Math.max(0,p[0]+radius-590),Math.max(0,60+radius-p[1]),Math.max(0,p[1]+radius-540),...level.walls.map(r=>Math.max(0,radius-rectDistance(p,r)))];} +export function holeStepAllowed(level,from,to,radius){const before=penetrations(level,from,radius),after=penetrations(level,to,radius);return after.every((p,i)=>p<=1e-6||p<=before[i]+1e-6);} +function clearSegment(level,from,to,radius){const steps=Math.max(1,Math.ceil(distance(from,to)/5));let previous=from;for(let n=1;n<=steps;n++){const p=[from[0]+(to[0]-from[0])*n/steps,from[1]+(to[1]-from[1])*n/steps];if(!holeStepAllowed(level,previous,p,radius))return false;previous=p;}return true;} +export function routeToItem(level,state,id){ + const item=level.items[id];if(!item||state.collected.includes(id)||item.r+3>holeRadius(state.mass))return null; + const radius=holeRadius(state.mass),start=state.hole,target=[item.x,item.y],nodes=[start,target]; + for(const wall of level.walls)for(const x of [wall.x-radius-2,wall.x+wall.w+radius+2])for(const y of [wall.y-radius-2,wall.y+wall.h+radius+2])if(x>=50+radius&&x<=590-radius&&y>=60+radius&&y<=540-radius)nodes.push([x,y]); + const distances=nodes.map(()=>Infinity),previous=nodes.map(()=>-1),visited=new Set();distances[0]=0; + for(let n=0;n=0;id=previous[id])route.unshift(nodes[id]);return route.slice(1);}visited.add(best); + for(let id=1;id0&&action.path.length<=160&&action.path.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&p[0]>=50&&p[0]<=590&&p[1]>=60&&p[1]<=540))path=action.path; + if(!path)return null;const next=clone(state),trail=[];let moved=false,blocked=false; + const collect=()=>{let changed=true;while(changed){changed=false;for(const item of level.items)if(!next.collected.includes(item.id)&&item.r+3<=holeRadius(next.mass)&&distance(next.hole,[item.x,item.y])<=holeRadius(next.mass)-item.r){next.collected.push(item.id);next.mass+=item.mass;changed=true;}}}; + for(const target of path){const from=[...next.hole],steps=Math.max(1,Math.ceil(distance(from,target)/5));for(let n=1;n<=steps;n++){ + const p=[from[0]+(target[0]-from[0])*n/steps,from[1]+(target[1]-from[1])*n/steps];if(!holeStepAllowed(level,next.hole,p,holeRadius(next.mass))){blocked=true;break;} + moved||=distance(next.hole,p)>.01;next.hole=p;collect();if(track)trail.push({hole:[...p],mass:next.mass,collected:[...next.collected]}); + }if(blocked)break;} + if(!moved&&next.collected.length===state.collected.length)return null; + return track?{state:next,trail}:next; +} +const won=(level,state)=>state.collected.length===level.items.length; +export function fringalePlan(level,start){ + if(won(level,start))return []; + let state=clone(start);const route=[],seen=new Set(); + for(let guard=0;guardholeRadius(state.mass))continue;const action={type:'visit',id:item.id},next=moveHole(level,state,action);if(next&&(next.collected.length>state.collected.length||distance(next.hole,state.hole)>1)){chosen={action,next};break;}} + if(!chosen)return null;route.push(chosen.action);state=chosen.next;if(won(level,state))return route; + } + return null; +} +export function createFringaleLevel(index){ + checkIndex(index);const tier=Math.floor(index/12),rng=random(73951+index*9721),mirror=rng()<.5,flip=p=>[mirror?640-p[0]:p[0],p[1]],walls=[],items=[]; + const add=(x,y,r,mass,kind,color)=>{const p=flip([x,y]);items.push({id:items.length,x:p[0],y:p[1],r,mass,kind,color});}; + if(tier>0){const gap=62-tier*3;walls.push({x:mirror?640-218:200,y:60,w:18,h:205-gap/2-60},{x:mirror?640-218:200,y:205+gap/2,w:18,h:540-205-gap/2});} + const pocket=shuffle([[100,110],[155,120],[105,180],[150,220],[105,280],[155,320]],rng).slice(0,tier?4+tier%3:0); + for(const [x,y] of pocket)add(x,y,6,1,'berry',Math.floor(rng()*6)); + const positions=shuffle(Array.from({length:20},(_,id)=>[tier?280+id%4*78:100+id%4*135,110+Math.floor(id/4)*86]),rng); + const small=5+tier,medium=3+tier,large=2+tier; + let cursor=0;for(let n=0;n=2){const [x,y]=positions[cursor++];add(x,y,27,12,'pot',Math.floor(rng()*6));} + const level={index,tier,title:TITLES[index%12],walls,items,start:flip(tier?[125,420]:[320,490]),solution:[]}; + const solution=fringalePlan(level,{hole:[...level.start],mass:0,collected:[]});if(!solution)throw new Error('Could not build a growing-hole route');level.solution=solution;return level; +} +export const fringaleRules={create:createFringaleLevel,initial:level=>({hole:[...level.start],mass:0,collected:[]}),move:(level,state,action)=>moveHole(level,state,action),won,actions:()=>[],plan:fringalePlan}; diff --git a/src/garden-canvas.js b/src/garden-canvas.js new file mode 100644 index 0000000..3c0fad3 --- /dev/null +++ b/src/garden-canvas.js @@ -0,0 +1,104 @@ +import { PocketCanvas } from './pocket-canvas.js'; +import { COLORS } from './pocket-core.js'; +import { topRun } from './alveoles-puzzle.js'; +import { pourAmount, settledBottle } from './potions-puzzle.js'; +import { liaisonsRules, neighbors, connectedPath } from './liaisons-puzzle.js'; + +const W=640,H=600; +export class GardenCanvas extends PocketCanvas { + constructor(container,mode,callbacks) { + super(container,mode,callbacks); + this.canvas.setAttribute('aria-label',({alveoles:'Ruche : choisissez une pile puis une alvéole vide',potions:'Fioles : choisissez une source puis une destination',liaisons:'Jardin : tracez entre les points de même couleur, sans croiser les chemins'})[mode]); + this.canvas.addEventListener('pointerdown',event=>{ + if(!callbacks.enabled())return;this.canvas.focus({preventScroll:true});this.canvas.setPointerCapture(event.pointerId);const point=this.point(event); + if(mode==='potions'){const id=this.state.bottles.findIndex((_,id)=>{const p=this.bottlePosition(id);return Math.abs(point.x-p.x)<47&&point.y>p.y-94&&point.y=0)callbacks.bottle(id);} + if(mode==='alveoles'){ + if(point.y>=486&&point.y<=585){const q=[190,320,450].findIndex(x=>Math.abs(point.x-x)<53);if(q>=0)callbacks.select(q);} + else {const cell=this.level.cells.findIndex((_,id)=>{const p=this.hexPosition(id);return Math.hypot(point.x-p.x,point.y-p.y)=0)callbacks.hex(cell);} + } + if(mode==='liaisons'){ + const cell=this.flowCell(point);if(cell===null)return; + const color=this.level.pairs.findIndex(p=>p.includes(cell)); + if(color>=0){callbacks.select(color);this.draft={color,path:[cell]};} + else {const color=this.state.paths.findIndex(p=>p.includes(cell));if(color>=0){callbacks.select(color);const path=this.state.paths[color];this.draft={color,path:path.slice(0,path.indexOf(cell)+1)};}} + } + }); + this.canvas.addEventListener('pointermove',event=>{ + if(!this.draft||!callbacks.enabled())return; + const cell=this.flowCell(this.point(event)),{color,path}=this.draft; + if(cell===null||cell===path.at(-1))return; + const previous=path.indexOf(cell);if(previous>=0){this.draft.path=path.slice(0,previous+1);return;} + const size=this.level.size,last=path.at(-1),sameRow=Math.floor(last/size)===Math.floor(cell/size),sameColumn=last%size===cell%size; + if(!sameRow&&!sameColumn)return; + const delta=sameRow?Math.sign(cell-last):Math.sign(cell-last)*size; + for(let nextCell=last+delta;;nextCell+=delta){const current=this.draft.path;if(connectedPath(this.level,current,color))break;const next=[...current,nextCell];if(!liaisonsRules.move(this.level,this.state,{color,path:next}))break;this.draft.path=next;if(nextCell===cell)break;} + }); + this.canvas.addEventListener('pointerup',()=>{if(!this.draft)return;const action=this.draft;this.draft=null;if(callbacks.enabled())callbacks.play(action);}); + this.canvas.addEventListener('pointercancel',()=>{this.draft=null;}); + } + point(event){const r=this.canvas.getBoundingClientRect();return{x:(event.clientX-r.x)/r.width*W,y:(event.clientY-r.y)/r.height*H};} + hexSize(){return this.level.radius===2?52:39;} + hexPosition(id){const [q,r]=this.level.cells[id],s=this.hexSize();return{x:320+Math.sqrt(3)*s*(q+r/2),y:261+1.5*s*r};} + bottlePosition(id){const count=this.state.bottles.length,columns=Math.ceil(count/2),row=Math.floor(id/columns),n=Math.min(columns,count-row*columns);return{x:320+(id%columns-(n-1)/2)*118,y:row?409:197};} + flowGrid(){return{x:76,y:63,cell:488/this.level.size};} + flowCell(point){const g=this.flowGrid(),x=Math.floor((point.x-g.x)/g.cell),y=Math.floor((point.y-g.y)/g.cell);return x>=0&&y>=0&&xb.lengthb.length>previous.bottles[i].length); + if(from>=0&&to>=0)this.motion.pour={from,to,color:previous.bottles[from].at(-1)}; + } + if(this.mode==='alveoles'){ + const target=state.stacks.findIndex((b,i)=>b.length>previous.stacks[i].length),q=state.queues.findIndex((n,i)=>n>previous.queues[i]); + for(let id=0;idstate.stacks[id].length)this.effects.push({id,target,color:previous.stacks[id].at(-1),start:performance.now()}); + if(q>=0)this.effects.push({id:target,target,color:level.queues[q][previous.queues[q]].at(-1),q,start:performance.now(),cleared:state.cleared-previous.cleared}); + } + } + this.draw(); + } + hex(x,y,size,fill,stroke='#ffffff70',squash=1){const c=this.ctx;c.beginPath();for(let n=0;n<6;n++){const angle=Math.PI/3*n-Math.PI/2,px=x+Math.cos(angle)*size,py=y+Math.sin(angle)*size*squash;if(!n)c.moveTo(px,py);else c.lineTo(px,py);}c.closePath();c.fillStyle=fill;c.fill();if(stroke){c.strokeStyle=stroke;c.lineWidth=1.5;c.stroke();}} + drawStack(x,y,stack,size){for(let n=0;n=1)continue;c.save();c.globalAlpha=1-t; + if(fx.q!==undefined){this.text(fx.cleared?`−${fx.cleared} ✧`:'✧',320,220-t*50,29,'#9d8951');} + else {const from=this.hexPosition(fx.id),to=fx.target>=0?this.hexPosition(fx.target):{x:320,y:220};this.hex(from.x+(to.x-from.x)*t,from.y+(to.y-from.y)*t-20*Math.sin(t*Math.PI),s*.35,COLORS[fx.color].hex,null,.7);}c.restore(); + } + for(let q=0;q<3;q++){const x=[190,320,450][q],stack=this.level.queues[q][this.state.queues[q]];this.round(x-53,486,106,97,17,'#e3ead8',this.selected===q||this.hint?.action?.q===q?'#aa9553':'#cbd8bf');if(stack)this.drawStack(x,528,stack,34);else this.text('✓',x,528,27,'#8ca27e');this.text(`FILE ${q+1}`,x,570,9);} + } + drawBottle(x,y,bottle,id,tilt=0){const c=this.ctx;c.save();c.translate(x,y-85);c.rotate(tilt); + this.round(-41,190,82,8,5,'#5d76521c'); + c.beginPath();c.moveTo(-18,0);c.lineTo(-18,24);c.quadraticCurveTo(-41,38,-41,52);c.lineTo(-41,145);c.quadraticCurveTo(-41,158,-29,158);c.lineTo(29,158);c.quadraticCurveTo(41,158,41,145);c.lineTo(41,52);c.quadraticCurveTo(41,38,18,24);c.lineTo(18,0);c.closePath();c.fillStyle='#fcfcf5a8';c.fill();c.strokeStyle='#a2b295';c.lineWidth=2.5;c.stroke(); + bottle.forEach((color,n)=>{this.round(-36,129-n*24,72,23,3,COLORS[color].hex);this.text(COLORS[color].mark,0,141-n*24,14,color===7?'#fffaf0':'#34564a');}); + for(let n=1;n<4;n++){c.strokeStyle='#829b733b';c.lineWidth=1;c.beginPath();c.moveTo(30,154-n*24);c.lineTo(37,154-n*24);c.stroke();} + c.strokeStyle='#ffffffb0';c.lineWidth=3;c.lineCap='round';c.beginPath();c.moveTo(-29,55);c.lineTo(-29,140);c.stroke();this.round(-22,-5,44,8,4,'#c8b28b'); + this.text(id+1,0,166,12,'#829575');if(settledBottle(bottle))this.text('✓',0,37,22,'#8da779');c.restore(); + } + drawPotions(){ + const c=this.ctx,time=performance.now(),t=this.motion?Math.min(1,(time-this.motion.start)/360):1,pour=this.motion?.pour; + this.round(58,287,524,9,4,'#d8c7a2');this.round(58,501,524,9,4,'#d8c7a2'); + this.state.bottles.forEach((b,id)=>{const p=this.bottlePosition(id),hinted=this.hint?.action?.from===id||this.hint?.action?.to===id;if(this.selected===id||hinted)this.round(p.x-50,p.y-98,100,190,17,'#e9ddb548','#af9552');else if(this.selected!==null&&pourAmount(this.state,this.selected,id))this.round(p.x-48,p.y-96,96,184,16,'#dce6cf55','#a1b38e');this.drawBottle(p.x,p.y,t<.55?this.motion.previous.bottles[id]:b,id,t<1&&pour?.from===id?Math.sin(t*Math.PI)*.28*(this.bottlePosition(pour.to).xthis.draft?.color===color?this.draft.path:p); + this.round(g.x-13,g.y-13,514,514,23,'#dce5d0','#cbd8c1'); + for(let cell=0;cell{if(!path.length)return;const palette=COLORS[this.level.colors[color]];c.strokeStyle=palette.hex;c.lineWidth=g.cell*.40;c.lineCap=c.lineJoin='round';c.beginPath();path.forEach((cell,n)=>{const p=this.flowPosition(cell);if(!n)c.moveTo(p.x,p.y);else c.lineTo(p.x,p.y);});c.stroke();if(path.length===1){const p=this.flowPosition(path[0]);c.fillStyle=palette.hex;c.beginPath();c.arc(p.x,p.y,g.cell*.2,0,7);c.fill();}c.strokeStyle='#fff8';c.lineWidth=2;c.beginPath();path.forEach((cell,n)=>{const p=this.flowPosition(cell);if(!n)c.moveTo(p.x,p.y-2);else c.lineTo(p.x,p.y-2);});c.stroke();}); + this.level.pairs.forEach((pair,color)=>{const palette=COLORS[this.level.colors[color]];for(const cell of pair){const p=this.flowPosition(cell);c.fillStyle='#56765120';c.beginPath();c.arc(p.x,p.y+3,g.cell*.32,0,7);c.fill();c.fillStyle=palette.hex;c.beginPath();c.arc(p.x,p.y,g.cell*.30,0,7);c.fill();c.strokeStyle='#fffc';c.lineWidth=2;c.stroke();this.text(palette.mark,p.x,p.y,g.cell*.27,this.level.colors[color]===7?'#fffaf0':'#34564a');if(this.selected===color||this.hint?.action?.color===color){c.strokeStyle=this.hint?.action?.color===color?'#af9552':'#789478';c.lineWidth=2;c.setLineDash([4,3]);c.beginPath();c.arc(p.x,p.y,g.cell*.39,0,7);c.stroke();c.setLineDash([]);}}}); + const hint=this.hint?.action;if(hint?.path.length){c.strokeStyle='#b49a55';c.lineWidth=3;c.setLineDash([5,5]);c.beginPath();hint.path.forEach((cell,n)=>{const p=this.flowPosition(cell);if(!n)c.moveTo(p.x,p.y);else c.lineTo(p.x,p.y);});c.stroke();c.setLineDash([]);} + this.text(`${paths.filter((p,color)=>connectedPath(this.level,p,color)).length} / ${this.level.pairs.length} LIENS · TOUTES LES CASES COMPTENT`,320,580,10,'#829575'); + } + draw(){if(!this.level||!this.canvas.width)return;const c=this.ctx;c.setTransform(this.canvas.width/W,0,0,this.canvas.height/H,0,0);c.clearRect(0,0,W,H);this.effects=this.effects.filter(f=>performance.now()-f.start<450);if(this.mode==='alveoles')this.drawAlveoles();else if(this.mode==='potions')this.drawPotions();else this.drawLiaisons();} +} diff --git a/src/garden-config.js b/src/garden-config.js new file mode 100644 index 0000000..5297355 --- /dev/null +++ b/src/garden-config.js @@ -0,0 +1,25 @@ +import { COLORS } from './pocket-core.js'; +import { alveolesRules } from './alveoles-puzzle.js'; +import { potionsRules, settledBottle, pourAmount } from './potions-puzzle.js'; +import { liaisonsRules, connectedPath } from './liaisons-puzzle.js'; + +export const stackSvg = stack => ``; +export const bottleSvg = bottle => ``; +const highlight = test => test ? 'hinted' : ''; +export const gardenConfigs = { + alveoles:{name:'Alvéoles',rules:alveolesRules,eyebrow:'DE PROCHE EN PROCHE, LES COULEURS SE REJOIGNENT',title:'Une pile.
Et tout se rejoint.',copy:'Posez les petits hexagones.
Laissez les couleurs se rassembler.',steps:[['Choisissez une pile.','Prenez la première pile d’une des trois files, puis posez-la sur une alvéole vide.'],['Faites naître les fusions.','Les dessus identiques reliés se rassemblent. Six tuiles de même couleur disparaissent et révèlent la suite.']],note:'Choisissez une pile, puis une alvéole vide',unit:'tuiles à réunir',reserve:'La prochaine petite pile.',reserveCopy:'Le symbole du dessus indique la première couleur à rassembler. Les couches du dessous comptent aussi.',finish:'La ruche respire.',delay:380,invalid:'Cette alvéole est occupée, ou cette file est vide.', + rulesText:['Choisissez la première pile d’une des trois files, puis cliquez une alvéole vide pour la déposer. Les petites piles du plateau montrent toutes leurs couches.','Les couleurs identiques du dessus, reliées de proche en proche, rejoignent la nouvelle pile. Les couches couvertes restent à leur place.','Chaque groupe de six tuiles identiques disparaît. La couleur ainsi découverte peut déclencher une nouvelle fusion sur la pile que vous venez de poser.','Utilisez toutes les piles et videz le plateau. Un placement sans fusion est possible, mais occupe de la place. Vous pouvez toujours annuler et demander un indice.'], + total:game=>game.level.stacks.flat().length+game.level.queues.flat(2).length,remaining:game=>game.level.stacks.flat().length+game.level.queues.flat(2).length-game.state.cleared, + controls(game,selected,hint){return `LES TROIS FILES · CHOISISSEZ UNE PILE
${game.level.queues.map((queue,q)=>`
${queue.slice(game.state.queues[q],game.state.queues[q]+3).map((stack,n)=>``).join('')||'✓'}
`).join('')}
LES ALVÉOLES VIDES
${game.state.stacks.map((stack,cell)=>!stack.length?``:'').join('')}
`;}, + }, + potions:{name:'Potions',rules:potionsRules,eyebrow:'QUELQUES GOUTTES, UNE COULEUR À LA FOIS',title:'Une couleur.
Une petite fiole.',copy:'Versez doucement les couleurs.
Retrouvez les recettes du jardin.',steps:[['Prenez une fiole.','Choisissez la fiole à verser, puis celle qui recevra sa couleur du dessus.'],['Gardez de la place.','Une fiole vide accepte toute couleur. Sinon, seuls les dessus de même couleur se mélangent.']],note:'Choisissez une fiole à verser, puis une destination',unit:'couleurs à trier',reserve:'Les recettes du jardin.',reserveCopy:'Quatre doses de la même couleur font une recette. Le symbole accompagne chaque couleur.',finish:'Toutes les recettes retrouvées.',delay:360,invalid:'Les dessus doivent avoir la même couleur et la fiole d’arrivée doit avoir de la place.', + rulesText:['Cliquez une fiole contenant du liquide, puis une autre pour y verser le groupe de couleur du dessus. Cliquez à nouveau la fiole choisie pour la désélectionner.','Une fiole contient quatre doses. Le versement transfère autant de doses identiques que la place disponible le permet.','Une fiole vide accepte toute couleur. Une fiole qui contient déjà du liquide accepte uniquement la couleur de son dessus.','Pour terminer, chaque couleur doit remplir une fiole entière. Les autres fioles restent vides. Les choix sans issue peuvent être annulés, sans limite de coups.'], + total:game=>game.level.colors.length,remaining:game=>game.level.colors.length-game.state.bottles.filter(settledBottle).length, + controls(game,selected,hint){return `CHOISISSEZ LA SOURCE, PUIS L’ARRIVÉE
${game.state.bottles.map((b,id)=>``).join('')}
${selected===null?'AUCUNE FIOLE CHOISIE':`FIOLE ${selected+1} À VERSER`}
${game.level.colors.map(color=>`${COLORS[color].mark}${game.state.bottles.some(b=>settledBottle(b)&&b[0]===color)?'✓':'4 doses'}`).join('')}
`;}, + }, + liaisons:{name:'Liaisons',rules:liaisonsRules,eyebrow:'CHAQUE PETIT CHEMIN TROUVE SON AUTRE BOUT',title:'Deux points.
Un joli détour.',copy:'Reliez les couleurs.
Faites une place à chaque chemin.',steps:[['Partez d’un point.','Faites glisser le doigt ou la souris jusqu’à son partenaire de même couleur.'],['Remplissez le jardin.','Les chemins restent sur les cases et ne se croisent pas. Aucune case ne doit rester vide.']],note:'Tracez entre les points de même couleur, puis remplissez toutes les cases',unit:'cases à parcourir',reserve:'Les petits chemins.',reserveCopy:'Choisissez un point puis les cases voisines. Les boutons et les flèches du clavier permettent aussi de tracer.',finish:'Tous les chemins se rejoignent.',delay:0,invalid:'Ce chemin croise une autre couleur, un point voisin ou saute une case.', + rulesText:['Partez d’un point coloré et dessinez jusqu’à l’autre point de sa couleur, de case voisine en case voisine, horizontalement ou verticalement.','Les chemins ne se croisent jamais et ne peuvent pas passer par le point d’une autre couleur. Toutes les cases doivent être parcourues pour terminer.','Repartir d’un point redessine sa couleur. Pendant le tracé, revenir sur une case de votre chemin efface la suite. Un trait est un seul coup annulable.','Vous pouvez aussi choisir une couleur dans les commandes puis cliquer les cases voisines, ou utiliser les flèches du clavier. Un indice peut proposer d’effacer un détour avant de tracer une route vérifiée.'], + total:game=>game.level.size**2,remaining:game=>game.level.size**2-game.state.paths.flat().length, + controls(game,selected,hint){const level=game.level;return `LES CASES · POINT PUIS CASES VOISINES
${Array.from({length:level.size**2},(_,cell)=>{const pair=level.pairs.findIndex(p=>p.includes(cell)),path=game.state.paths.findIndex(p=>p.includes(cell)),color=pair>=0?pair:path;return ``;}).join('')}
`;}, + }, +}; diff --git a/src/garden-previews.js b/src/garden-previews.js new file mode 100644 index 0000000..91155f8 --- /dev/null +++ b/src/garden-previews.js @@ -0,0 +1,13 @@ +import { COLORS } from './pocket-core.js'; +import { createAlveolesLevel } from './alveoles-puzzle.js'; +import { createPotionsLevel } from './potions-puzzle.js'; +import { createLiaisonsLevel } from './liaisons-puzzle.js'; +import { stackSvg, bottleSvg } from './garden-config.js'; + +const hex=(x,y,size,fill)=>``; +const hive=createAlveolesLevel(12); +export const alveolesPreview=`
Et tout s’écoule.',copy:'Mélangez les petites billes.
Ouvrez les bons passages.',steps:[['Retirez une goupille.','Les billes descendent vers le prochain bassin, puis continuent à travers les passages déjà ouverts.'],['Colorez avant le départ.','Une bille grise prend la couleur de ses voisines. Toutes doivent arriver colorées dans le panier.']],note:'Retirez une goupille · Colorez les billes avant leur départ',unit:'billes à recueillir',reserve:'Les petits passages.',reserveCopy:'Les ouvertures restent libres. Réunissez les billes grises et les couleurs avant d’ouvrir le dernier bassin.',finish:'Toutes les billes au jardin.',delay:450,invalid:'Cette goupille est déjà retirée, ou des billes se sont perdues. Annulez pour réessayer.', + rulesText:['Cliquez une goupille dans le jardin ou dans les commandes. Elle disparaît et laisse les billes de sa réserve tomber dans le bassin suivant.','Une bille grise devient colorée au contact d’une bille de couleur, dans le même bassin. Les billes continuent automatiquement à travers toutes les vannes déjà ouvertes.','Les billes grises qui arrivent directement au panier sont perdues. Une bombe détruit les billes qu’elle rencontre : les chapitres suivants demandent aussi d’éviter sa goupille.','Toutes les billes doivent rejoindre le panier, colorées et intactes. Une erreur se corrige avec Annuler ; chaque indice vérifie une suite qui termine tout le plateau.'], + total:game=>game.level.total,remaining:game=>game.level.total-game.state.collected.length, + afterStatus:game=>game.state.lost.length?'Des billes se sont perdues. Annulez la dernière ouverture pour réessayer.':null, + controls(game,selected,hint){return `
${game.state.collected.length} / ${game.level.total}Billes au panier${game.state.lost.length?`

${game.state.lost.length} perdues · Annulez pour réessayer

`:''}
LES GOUPILLES À RETIRER
${game.level.pins.map((pin,id)=>``).join('')}
`;}, + }, + dunes:{name:'Dunes',rules:dunesRules,eyebrow:'DE PETITS GRAINS, DE GRANDES CASCADES',title:'Un peu de sable.
Une couleur de moins.',copy:'Posez vos petits blocs.
Regardez les couleurs se rejoindre.',steps:[['Choisissez un bloc.','Prenez le premier d’une des trois files et choisissez sa colonne de chute dans le bac.'],['Reliez les deux bords.','Le bloc devient du sable. Une couleur qui rejoint les deux côtés disparaît et fait descendre les autres grains.']],note:'Choisissez un bloc, puis sa colonne dans le bac',unit:'bandes à dégager',reserve:'Les couleurs à venir.',reserveCopy:'Le sable glisse autour des pierres. Préparez un passage d’un bord à l’autre sans boucher le haut du bac.',finish:'Un dernier souffle de sable.',delay:0,invalid:'Le bloc ne tient pas à cet endroit, ou cette file est vide.', + rulesText:['Choisissez le premier bloc d’une des trois files. Cliquez dans le bac pour définir sa colonne, ou choisissez une position dans les commandes. Le bloc se dépose par le haut.','Chaque case du bloc se transforme en petits grains. Ils tombent et glissent en diagonale, en contournant les grains voisins et les pierres.','Une zone de sable de la même couleur qui relie le bord gauche au bord droit disparaît entièrement. Elle peut être courbe : aucun besoin de faire une ligne droite.','Dégagez le nombre de bandes demandé avec votre réserve. Les chapitres suivants ajoutent davantage de couleurs, un bac plus large et des pierres. Annulation, indices et reprise restent disponibles.'], + total:game=>game.level.goal,remaining:game=>Math.max(0,game.level.goal-game.state.bursts), + controls(game,selected,hint){const piece=selected===null?null:game.level.queues[selected]?.[game.state.queues[selected]];return `
${game.state.bursts} / ${game.level.goal}Bandes de sable dégagées
${game.level.queues.map((queue,q)=>`
0${q+1}${queue.slice(game.state.queues[q],game.state.queues[q]+3).map((p,n)=>``).join('')||'✓'}
`).join('')}
LA POSITION DU BLOC · FLÈCHES PUIS ESPACE
${piece?Array.from({length:game.level.width-sandWidth(piece)+1},(_,x)=>``).join(''):'

Choisissez d’abord un bloc.

'}
`;}, + }, + fringale:{name:'Fringale',rules:fringaleRules,eyebrow:'UNE PETITE FAIM, UN GRAND JARDIN',title:'Encore
une petite bouchée.',copy:'Un trou qui grandit.
Un jardin plein de bonnes choses.',steps:[['Commencez petit.','Guidez le trou sous les baies. Chaque bouchée l’agrandit et lui permet d’avaler des objets plus grands.'],['Pensez au chemin du retour.','Les haies barrent les passages. Un trou devenu grand ne peut plus emprunter une allée étroite.']],note:'Guidez le trou · Avalez les petites choses pour grandir',unit:'choses à avaler',reserve:'Le prochain petit goûter.',reserveCopy:'Faites glisser le trou ou choisissez un objet accessible. Récoltez les petits coins avant de devenir trop grand.',finish:'Un jardin bien rangé.',delay:540,invalid:'Cet objet est trop grand ou inaccessible. Choisissez une petite bouchée ou annulez un détour.', + rulesText:['Faites glisser le trou dans le jardin. Un objet disparaît lorsqu’il tient entièrement dans l’ouverture. Commencez par les petites baies pour agrandir le trou.','Les haies et les limites du jardin empêchent de passer. Un trou qui grandit peut devenir trop large pour une allée : pensez à vider les petites cours avant de sortir.','Vous pouvez aussi cliquer un objet ou son bouton. Le trou cherche alors un chemin autour des haies. Les flèches du clavier permettent de se déplacer.','Avalez tous les objets pour terminer. Un geste entier peut être annulé, avec la taille précédente et tous ses objets. Un indice vérifie une tournée complète ; si elle n’est plus trouvée, il propose d’annuler.'], + total:game=>game.level.items.length,remaining:game=>game.level.items.length-game.state.collected.length, + controls(game,selected,hint){const radius=holeRadius(game.state.mass);return `
${radius<22?'Une petite faim':radius<32?'Un bon appétit':'Une grande fringale'}${game.state.collected.length} / ${game.level.items.length} bouchées
LES BONNES CHOSES DU JARDIN
${game.level.items.filter(p=>!game.state.collected.includes(p.id)).map(p=>``).join('')}
`;}, + }, +}; diff --git a/src/harvest-previews.js b/src/harvest-previews.js new file mode 100644 index 0000000..955cec9 --- /dev/null +++ b/src/harvest-previews.js @@ -0,0 +1,7 @@ +import { COLORS } from './pocket-core.js'; +import { createDunesLevel } from './dunes-puzzle.js'; +import { sandPieceSvg } from './harvest-config.js'; +export const eclusesPreview=``; +const dune=createDunesLevel(0); +export const dunesPreview=`↗cube cube cubeA small escape.Trois petits mondes. Une vraie pause. ✳
UNE PETITE PARENTHÈSE

À quoi on joue
aujourd’hui ?

Des chemins à trouver, des couleurs à récolter.
Choisissez votre petit monde et prenez votre temps.

${games.map(g => ``).join('')}
✳ Pas de chrono.Pas de compte.Votre progression reste ici.
Un petit jeu. Un peu d’air.Fait pour jouer à votre rythme.
`; +document.querySelector('#app').innerHTML = `
↗cube cube cubeA small escape.Vingt et un petits mondes. Une vraie pause. ✳
UNE PETITE PARENTHÈSE

À quoi on joue
aujourd’hui ?

Des chemins à trouver, des couleurs à récolter.
Choisissez votre petit monde et prenez votre temps.

${games.map(g => ``).join('')}
✳ Pas de chrono.Pas de compte.Votre progression reste ici.
Un petit jeu. Un peu d’air.Fait pour jouer à votre rythme.
`; diff --git a/src/home-style.css b/src/home-style.css index 7af7ddf..a5c4900 100644 --- a/src/home-style.css +++ b/src/home-style.css @@ -17,6 +17,13 @@ .game-preview svg { height: 100%; width: 100%; } .game-card.pictures .game-preview { background: #e8eeeb; } .game-card.colony .game-preview { background: #efeddf; } +.game-card.atelier .game-preview { background: #edeadd; } +.game-card.bobines .game-preview { background: #f0e9e4; } +.game-card.escapade .game-preview { background: #e7eddc; } +.game-card.passages .game-preview { background:#e9ecdf; } +.game-card.voyage .game-preview { background:#edf0e5; } +.game-card.carrousel .game-preview { background:#e6ece4; } +.game-card.broderie .game-preview { background:#f0e9e2; } .game-number { position: absolute; top: 20px; left: 21px; color: #879680; font-size: 9px; letter-spacing: 1px; } .game-tag { position: absolute; right: 15px; top: 16px; background: #fffdf6a8; border: 1px solid #d8ddcc; padding: 6px 8px; border-radius: 14px; font-size: 7px; letter-spacing: .6px; color: #6e826f; } .game-card-content { padding: 25px; } diff --git a/src/liaisons-puzzle.js b/src/liaisons-puzzle.js new file mode 100644 index 0000000..f9532ab --- /dev/null +++ b/src/liaisons-puzzle.js @@ -0,0 +1,59 @@ +import { checkIndex, clone, random, shuffle } from './pocket-core.js'; + +const TITLES = ['Deux bouts de chemin','Le jardin des lignes','Un joli détour','Le coin tranquille','Les chemins voisins','Au fil des cases','Une boucle de plus','Les petits croisements','Le chemin long','Tout se rejoint','Un peu de patience','Le dernier lien']; +export const neighbors = (size, a, b) => Math.abs(a % size - b % size) + Math.abs(Math.floor(a / size) - Math.floor(b / size)) === 1; +function move(level, state, action) { + if (!action || !Number.isInteger(action.color) || !level.pairs[action.color] || !Array.isArray(action.path)) return null; + const path = action.path, ends = level.pairs[action.color]; + if (path.length && !ends.includes(path[0])) return null; + const occupied = new Set(state.paths.flatMap((p, color) => color === action.color ? [] : p)); + const forbidden = new Set(level.pairs.flatMap((p, color) => color === action.color ? [] : p)); + const seen = new Set(); + for (let i = 0; i < path.length; i++) { + const cell = path[i]; + if (!Number.isInteger(cell) || cell < 0 || cell >= level.size ** 2 || seen.has(cell) || occupied.has(cell) || forbidden.has(cell) || i && !neighbors(level.size, path[i-1], cell) || i > 0 && ends.includes(cell) && i !== path.length-1) return null; + seen.add(cell); + } + const next = clone(state); next.paths[action.color] = [...path]; + return JSON.stringify(next) === JSON.stringify(state) ? null : next; +} +export const connectedPath = (level, path, color) => path.length > 1 && level.pairs[color].includes(path[0]) && level.pairs[color].includes(path.at(-1)) && path[0] !== path.at(-1); +const won = (level, state) => state.paths.every((p,c) => connectedPath(level,p,c)) && state.paths.reduce((n,p) => n+p.length,0) === level.size ** 2; +export function createLiaisonsLevel(index) { + checkIndex(index); const tier = Math.floor(index / 12), size = 4 + tier, count = 3 + tier, rng = random(29483 + index * 9173); + let best; + for (let attempt = 0; attempt < 12; attempt++) { + let path = Array.from({length:size ** 2}, (_,n) => Math.floor(n/size)*size + (Math.floor(n/size)%2 ? size-1-n%size : n%size)); + // Backbite moves preserve a Hamiltonian path while breaking the row pattern. + for (let step = 0; step < 120 + tier * 100; step++) { + const start = rng() < .5, endpoint = start ? path[0] : path.at(-1); + const choices = path.map((cell,i) => ({cell,i})).filter(({cell,i}) => neighbors(size,endpoint,cell) && (start ? i > 1 : i < path.length-2)); + if (!choices.length) continue; const {i} = choices[Math.floor(rng()*choices.length)]; + path = start ? [...path.slice(0,i).reverse(), ...path.slice(i)] : [...path.slice(0,i+1), ...path.slice(i+1).reverse()]; + } + const lengths = Array(count).fill(4); for (let n=count*4; n {const p=path.slice(cursor,cursor+length);cursor+=length;return p;}),rng); + const score = paths.reduce((n,p) => n+Math.abs(p[0]%size-p.at(-1)%size)+Math.abs(Math.floor(p[0]/size)-Math.floor(p.at(-1)/size)),0); + if (!best || score > best.score) best = {paths,score}; + } + const colors = shuffle([0,1,2,3,4,5,6,7],rng).slice(0,count); + return {index,tier,title:TITLES[index%12],size,colors,pairs:best.paths.map(p=>[p[0],p.at(-1)]),solution:best.paths.map((path,color)=>({color,path}))}; +} +export const liaisonsRules = { + create:createLiaisonsLevel, initial:level => ({paths:level.pairs.map(()=>[])}), move, won, + actions:() => [], + plan(level, state) { + if (won(level,state)) return []; + let next = clone(state); const route = []; + // Keep canonical paths in either direction. Clear conflicting strokes before + // drawing the audited full-grid solution; each suggested edit is transactional. + for (let color=0;colorMath.max(...piece.cells.map(p=>p[0]))+1; +export const pieceHeight=piece=>Math.max(...piece.cells.map(p=>p[1]))+1; +export function activePieces(level,state){const start=Math.floor(state.used.length/3)*3;return level.pieces.slice(start,start+3).filter(p=>!state.used.includes(p.id));} +export function mosaicCells(level,piece,x,y){if(!Number.isInteger(x)||!Number.isInteger(y)||x<0||y<0||x+pieceWidth(piece)>level.size||y+pieceHeight(piece)>level.size)return null;return piece.cells.map(([dx,dy])=>(y+dy)*level.size+x+dx);} +function move(level,state,action){ + const piece=activePieces(level,state).find(p=>p.id===action?.id);if(!piece)return null;const cells=mosaicCells(level,piece,action.x,action.y);if(!cells||cells.some(id=>state.field[id]!==null))return null; + const next=clone(state);for(const id of cells)next.field[id]=piece.color;next.used.push(piece.id);next.used.sort((a,b)=>a-b);next.added+=cells.length; + const cleared=new Set(),rows=[],cols=[];for(let n=0;nn*level.size+x),col=Array.from({length:level.size},(_,y)=>y*level.size+n);if(row.every(id=>next.field[id]!==null)){rows.push(n);row.forEach(id=>cleared.add(id));}if(col.every(id=>next.field[id]!==null)){cols.push(n);col.forEach(id=>cleared.add(id));}} + for(const id of cleared)next.field[id]=null;next.cleared+=cleared.size;next.lines+=rows.length+cols.length;next.last={cells:[...cleared],rows,cols};return next; +} +function actions(level,state){const result=[];for(const p of activePieces(level,state))for(let y=0;y<=level.size-pieceHeight(p);y++)for(let x=0;x<=level.size-pieceWidth(p);x++){const cells=mosaicCells(level,p,x,y);if(cells.every(id=>state.field[id]===null))result.push({id:p.id,x,y});}return result.sort((a,b)=>move(level,state,b).last.cells.length-move(level,state,a).last.cells.length);} +const cache=new Map(); +export function createMosaiqueLevel(index){ + checkIndex(index);if(cache.has(index))return clone(cache.get(index));const tier=Math.floor(index/12),size=tier>=2?8:6,rng=random(95477+index*3571),field=Array.from({length:size**2},(_,id)=>(Math.floor(id/size)+Math.floor(id%size/2)+index)%6),pieces=[],solution=[]; + for(let band=0;bands.some(p=>p[1]===1))):SHAPES.slice(0,tier===3?10:tier?7:4),cells=clone(pool[Math.floor(rng()*pool.length)]),piece={id:pieces.length+n,cells,color:(index+band+n)%6},width=pieceWidth(piece),height=pieceHeight(piece),x=Math.floor(rng()*(size-width+1)),y=band*2+(height===1?Math.floor(rng()*2):0),ids=mosaicCells({size},piece,x,y); + if(ids.some(id=>occupied.has(id)))break;ids.forEach(id=>occupied.add(id));batch.push({piece,x,y}); + } + if(batch.length===3&&(bandid%size)).size===size)){placement=batch;break;} + } + if(!placement)throw new Error('Could not construct a mosaic batch');for(const {piece,x,y} of placement){pieces.push(piece);for(const id of mosaicCells({size},piece,x,y))field[id]=null;solution.push({id:piece.id,x,y});} + } + const level={index,tier,size,field,pieces,total:field.filter(v=>v!==null).length+pieces.reduce((n,p)=>n+p.cells.length,0),solution,title:['Quelques petits carrés','Les pièces du matin','Le petit pavage','Un motif de couleurs','Tout trouve sa place','Les coins du tableau','Un peu de géométrie','Les lignes du jardin','Les pièces cachées','Un tableau bien rempli','La dernière rangée','Une belle mosaïque'][index%12]}; + let state=mosaiqueRules.initial(level);for(const action of solution){state=move(level,state,action);if(!state)throw new Error('Invalid mosaic placement');}if(!mosaiqueRules.won(level,state))throw new Error('Unfinished mosaic');cache.set(index,level);return clone(level); +} +export const mosaiqueRules={create:createMosaiqueLevel,initial:level=>({field:[...level.field],used:[],added:0,cleared:0,lines:0,last:{cells:[],rows:[],cols:[]}}),move,won:(level,state)=>state.used.length===level.pieces.length&&state.field.every(v=>v===null),actions,plan:(level,state)=>searchPlan(mosaiqueRules,level,state,1500)}; diff --git a/src/noeuds-puzzle.js b/src/noeuds-puzzle.js new file mode 100644 index 0000000..3cbefad --- /dev/null +++ b/src/noeuds-puzzle.js @@ -0,0 +1,44 @@ +import { checkIndex, clone, random, shuffle } from './pocket-core.js'; +import { segmentsMeet } from './physics-geometry.js'; +const TITLES=['Les premiers fils','Un joli méli-mélo','La bonne attache','Le petit détour','Entre deux couleurs','Une place de libre','Les fils du jardin','Les points fixes','De fil en aiguille','Une boucle à défaire','Tout se détend','Le dernier nœud']; +export function ropeCrossings(level,state){ + const conflicts=[]; + for(let a=0;aropeCrossings(level,state).length===0; +export function untanglePlan(level,start){ + if(won(level,start))return []; + let state=clone(start);const plan=[]; + for(let guard=0;guard!p.fixed&&state.pins[id]!==level.targets[id]);if(pin<0)return won(level,state)?plan:null; + const target=level.targets[pin],occupant=state.pins.indexOf(target); + if(occupant>=0){if(level.pins[occupant].fixed)return null;const free=level.pegs.findIndex((_,id)=>!state.pins.includes(id)&&!level.targets.includes(id));if(free<0)return null;const action={pin:occupant,peg:free};state=move(level,state,action);if(!state)return null;plan.push(action);if(won(level,state))return plan;} + const action={pin,peg:target};state=move(level,state,action);if(!state)return null;plan.push(action);if(won(level,state))return plan; + } + return null; +} +export function createNoeudsLevel(index){ + checkIndex(index);const tier=Math.floor(index/12),count=3+tier,size=4+tier,rng=random(37619+index*10949),colors=shuffle([0,1,2,3,4,5,6,7],rng); + const rotate=Math.floor(rng()*4),transform=([x,y])=>rotate===0?[x,y]:rotate===1?[size-1-y,x]:rotate===2?[size-1-x,size-1-y]:[y,size-1-x]; + const pegs=Array.from({length:size**2},(_,id)=>transform([id%size,Math.floor(id/size)])),pins=[],ropes=[],targets=[]; + const rows=shuffle(Array.from({length:size},(_,i)=>i),rng).slice(0,count); + for(let rope=0;rope0&&ropepins[id].fixed)),free=shuffle(pegs.map((_,id)=>id).filter(id=>!fixed.has(id)),rng);let cursor=0; + const placements=targets.map((peg,id)=>pins[id].fixed?peg:free[cursor++]),state={pins:placements},crossings=ropeCrossings(level,state).length; + if(crossings>=2+tier&&(!best||crossings>best.crossings)){const solution=untanglePlan(level,state);if(solution?.length>=2)best={placements,crossings,solution};} + } + if(!best)throw new Error('Could not build crossed ropes');return {...level,placements:best.placements,solution:best.solution}; +} +export const noeudsRules={create:createNoeudsLevel,initial:level=>({pins:[...level.placements]}),move,won,actions:()=>[],plan:untanglePlan}; diff --git a/src/passages-puzzle.js b/src/passages-puzzle.js new file mode 100644 index 0000000..50237c4 --- /dev/null +++ b/src/passages-puzzle.js @@ -0,0 +1,96 @@ +import { checkIndex, clone, random, shuffle } from './pocket-core.js'; +const DIRS = [[1,0],[-1,0],[0,1],[0,-1]]; +const TITLES = ['Les portes du matin','Les voisins de palier','Le petit détour','Deux chemins','La cour intérieure','La fenêtre ouverte','Les grandes allées','Le passage étroit','Le jeu des places','Un peu de recul','Les portes croisées','La dernière sortie']; +const overlaps = (a,b) => a.x < b.x+b.w && a.x+a.w > b.x && a.y < b.y+b.h && a.y+a.h > b.y; +function fits(level, blocks, block) { + return block.x >= 0 && block.y >= 0 && block.x+block.w <= level.size && block.y+block.h <= level.size && !blocks.some(b => b.id !== block.id && overlaps(b,block)) && !level.walls.some(([x,y]) => overlaps(block,{x,y,w:1,h:1})); +} +function move(level,state,action) { + if (!action || !Number.isInteger(action.id) || !DIRS.some(([x,y]) => x === action.dx && y === action.dy)) return null; + const block = state.blocks.find(b => b.id === action.id); if (!block) return null; + const next = clone(state), target = next.blocks.find(b => b.id === action.id); target.x += action.dx; target.y += action.dy; + if (target.x < 0 || target.y < 0 || target.x+target.w > level.size || target.y+target.h > level.size) { + const door = level.blocks.find(b => b.id === block.id).door; + const exits = door.side === 'left' && block.x === 0 && action.dx === -1 && block.y === door.at || door.side === 'right' && block.x+block.w === level.size && action.dx === 1 && block.y === door.at || door.side === 'top' && block.y === 0 && action.dy === -1 && block.x === door.at || door.side === 'bottom' && block.y+block.h === level.size && action.dy === 1 && block.x === door.at; + if (!exits) return null; + next.blocks = next.blocks.filter(b => b.id !== block.id); return next; + } + return fits(level,next.blocks,target) ? next : null; +} +function placementRoute(level,blocks,initial) { + const queue = [{block:initial,route:[]}], seen = new Set([`${initial.x},${initial.y}`]); + for (let n=0;n[i%(size-2)+1,Math.floor(i/(size-2))+1]),rng).slice(0,tier); + const level={index,tier,title:TITLES[index%12],size,walls,blocks:[],solution:[]}, paths=[], colors=shuffle([0,1,2,3,4,5],rng); + for (let id=0;id 0 ? [[1,2],[2,1],[1,3],[3,1],[2,2]] : [[1,2],[2,1],[1,1]],rng); + for (const [w,h] of shapes) { + const choices=[]; + for (let at=0;atsize || level.blocks.some(b=>b.door.side===side && at < b.door.at+b.door.span && at+span>b.door.at)) continue; + const x=side==='left'?0:side==='right'?size-w:at, y=side==='top'?0:side==='bottom'?size-h:at; + const initial={id,color:colors[id],w,h,x,y,door:{side,at,span}}; + if (fits(level,level.blocks,initial)) choices.push(initial); + } + for (const initial of shuffle(choices,rng)) { + const reachable=placementRoute(level,level.blocks,initial).filter(p=>p.route.length >= 2); + if (!reachable.length) continue; + reachable.sort((a,b)=>b.route.length-a.route.length); + chosen=reachable[Math.floor(rng()*Math.max(1,Math.ceil(reachable.length/3)))]; break; + } + if (chosen) break; + } + if (!chosen) return null; + level.blocks.push(chosen.block); paths.push(chosen.route); + } + for (let id=count-1;id>=0;id--) { + for (const a of [...paths[id]].reverse()) level.solution.push({id,dx:-a.dx,dy:-a.dy}); + const side=level.blocks[id].door.side, [dx,dy]=({left:[-1,0],right:[1,0],top:[0,-1],bottom:[0,1]})[side]; level.solution.push({id,dx,dy}); + } + let score=level.solution.length; + for(let id=0;ida.id===id)) { block={...block,x:block.x+a.dx,y:block.y+a.dy}; score+=level.blocks.filter(b=>b.id>id && overlaps(b,block)).length*3; } + } + return {...level,score}; +} +export function createPassagesLevel(index) { + checkIndex(index); let best=null; + for(let attempt=0;attempt<12;attempt++) { const level=candidate(index,94721+index*7193+attempt*919); if(level && (!best || level.score>best.score)) best=level; } + if(!best) throw new Error('Could not build passages'); return best; +} +function routeToDoor(level,state,id) { + const start=state.blocks.find(b=>b.id===id), queue=[{block:start,route:[]}], seen=new Set([`${start.x},${start.y}`]); + for(let n=0;nb.id===id?queue[n].block:b)}, next=move(level,temp,action); if(!next) continue; + const block=next.blocks.find(b=>b.id===id); if(!block) return [...queue[n].route,action]; + const key=`${block.x},${block.y}`; if(seen.has(key)) continue; seen.add(key); queue.push({block,route:[...queue[n].route,action]}); + } + return null; +} +export const passagesRules={ + create:createPassagesLevel, + initial:level=>({blocks:clone(level.blocks)}), + won:(_,state)=>!state.blocks.length, + move, + actions:(level,state)=>state.blocks.flatMap(b=>DIRS.map(([dx,dy])=>({id:b.id,dx,dy})).filter(a=>move(level,state,a))), + plan(level,start) { + let state=clone(start), plan=[]; + while(state.blocks.length) { + let route=null; for(const block of [...state.blocks].reverse()) { route=routeToDoor(level,state,block.id); if(route) break; } + if(!route) return null; + for(const action of route) { state=move(level,state,action); plan.push(action); } + } + return plan; + }, +}; diff --git a/src/physics-canvas.js b/src/physics-canvas.js new file mode 100644 index 0000000..c58fdff --- /dev/null +++ b/src/physics-canvas.js @@ -0,0 +1,87 @@ +import { PocketCanvas } from './pocket-canvas.js'; +import { COLORS } from './pocket-core.js'; +import { distance, segmentsMeet } from './physics-geometry.js'; +import { WaterSimulation, WATER_TOTAL } from './gouttes-physics.js'; + +const W=640,H=600; +export class PhysicsCanvas extends PocketCanvas{ + constructor(container,mode,callbacks){ + super(container,mode,callbacks);this.canvas.setAttribute('aria-label',mode==='noeuds'?'Cordes : faites glisser une attache vers un plot libre':'Jardin d’eau : dessinez une rampe, puis cliquez Laisser couler'); + this.canvas.addEventListener('pointerdown',event=>{ + if(!callbacks.enabled())return;this.canvas.focus({preventScroll:true});this.canvas.setPointerCapture(event.pointerId);const p=this.point(event); + if(mode==='noeuds'){ + const pin=this.state.pins.findIndex(peg=>distance(p,this.pegPosition(peg))<27); + if(pin>=0){callbacks.select(pin);if(!this.level.pins[pin].fixed)this.grab={pin,point:p,start:p,moved:false};} + else{const peg=this.nearestPeg(p);if(peg>=0)callbacks.peg(peg);} + }else if(p[0]>=35&&p[0]<=605&&p[1]>=75&&p[1]<=550)this.stroke=[p]; + }); + this.canvas.addEventListener('pointermove',event=>{ + if(!callbacks.enabled())return;const p=this.point(event); + if(this.grab){this.grab.point=p;this.grab.moved||=distance(p,this.grab.start)>8;} + if(this.stroke&&distance(p,this.stroke.at(-1))>4&&this.stroke.length<160)this.stroke.push([Math.max(35,Math.min(605,p[0])),Math.max(75,Math.min(550,p[1]))]); + }); + this.canvas.addEventListener('pointerup',event=>{ + if(this.grab){const grab=this.grab;this.grab=null;const peg=this.nearestPeg(this.point(event));if(grab.moved&&peg>=0&&callbacks.enabled()){this.justDragged=true;callbacks.play({pin:grab.pin,peg});this.justDragged=false;}} + if(this.stroke){const path=this.stroke;this.stroke=null;const p=this.point(event);if(p[0]>=35&&p[0]<=605&&p[1]>=75&&p[1]<=550&&distance(path.at(-1),p)>2&&path.length<160)path.push(p);if(path.length>1&&callbacks.enabled())callbacks.play({type:'draw',path});} + }); + this.canvas.addEventListener('pointercancel',()=>{this.grab=null;this.stroke=null;}); + } + point(event){const r=this.canvas.getBoundingClientRect();return[(event.clientX-r.x)/r.width*W,(event.clientY-r.y)/r.height*H];} + pegPosition(peg){const [x,y]=this.level.pegs[peg],cell=480/this.level.size;return[80+(x+.5)*cell,60+(y+.5)*cell];} + nearestPeg(p){const peg=this.level.pegs.findIndex((_,id)=>distance(p,this.pegPosition(id))<480/this.level.size*.43);return peg;} + screenPoint(value){const [x,y]=this.mode==='noeuds'?this.pegPosition(value.peg??this.state.pins[value.pin]):value;const r=this.canvas.getBoundingClientRect();return{x:r.x+x/W*r.width,y:r.y+y/H*r.height};} + update(level,state,hint,selected,previous){ + const changed=state!==this.state||level!==this.level;this.level=level;this.state=state;this.hint=hint;this.selected=selected; + if(changed){this.grab=null;this.stroke=null;this.assisted=[];this.motion=previous&&!this.reduced&&!this.justDragged?{previous,start:performance.now()}:null; + if(this.mode==='gouttes'){ + this.water=null;this.running=false; + if(previous&&state.trial>previous.trial&&state.result&&!this.reduced){this.water=new WaterSimulation(level,state.lines);this.waterLast=performance.now();this.waterCarry=0;this.running=true;} + } + } + this.draw(); + } + ropePoints(){return this.state.pins.map((peg,pin)=>{const target=this.pegPosition(peg);if(this.grab?.pin===pin)return this.grab.point;const before=this.motion?.previous.pins[pin];if(before===undefined)return target;const t=Math.min(1,(performance.now()-this.motion.start)/220),from=this.pegPosition(before),ease=1-(1-t)**3;return[from[0]+(target[0]-from[0])*ease,from[1]+(target[1]-from[1])*ease];});} + drawNoeuds(){ + const c=this.ctx,points=this.ropePoints(),conflicts=[]; + this.round(60,40,520,520,30,'#e2e8d7','#ced9c2');this.round(73,53,494,494,23,'#f0f3e7'); + this.level.pegs.forEach((_,id)=>{const [x,y]=this.pegPosition(id),occupied=this.state.pins.includes(id);c.fillStyle=occupied?'#abbca1':'#d0dbc4';c.beginPath();c.arc(x,y,occupied?10:6,0,7);c.fill();if(!occupied)this.text(id+1,x,y+18,9,'#a1b293');if(this.hint?.action?.peg===id){c.strokeStyle='#ae9552';c.lineWidth=3;c.beginPath();c.arc(x,y,25,0,7);c.stroke();}}); + this.level.ropes.forEach((rope,id)=>{ + const a=points[rope.a],b=points[rope.b],palette=COLORS[rope.color],length=distance(a,b),angle=Math.atan2(b[1]-a[1],b[0]-a[0]); + c.lineCap='round';c.strokeStyle='#f1f4e8';c.lineWidth=17;c.beginPath();c.moveTo(...a);c.lineTo(...b);c.stroke();c.strokeStyle='#405d3d30';c.lineWidth=13;c.beginPath();c.moveTo(a[0],a[1]+3);c.lineTo(b[0],b[1]+3);c.stroke();c.strokeStyle=palette.hex;c.lineWidth=11;c.beginPath();c.moveTo(...a);c.lineTo(...b);c.stroke(); + c.save();c.translate(...a);c.rotate(angle);c.strokeStyle='#ffffff75';c.lineWidth=1.2;for(let x=12;x{const info=this.level.pins[pin],selected=this.selected===pin||this.hint?.action?.pin===pin;c.fillStyle='#51704330';c.beginPath();c.arc(x,y+4,20,0,7);c.fill();c.fillStyle=COLORS[info.color].hex;c.beginPath();c.arc(x,y,19,0,7);c.fill();c.strokeStyle=selected?'#ae9552':'#fffdf4';c.lineWidth=selected?4:2;c.stroke();this.text(info.fixed?'⊕':pin+1,x,y,info.fixed?22:13,info.color===7?'#fffaf0':'#244c42');}); + if(this.hint?.action){const a=points[this.hint.action.pin],b=this.pegPosition(this.hint.action.peg);c.setLineDash([6,5]);c.strokeStyle='#aa9251';c.lineWidth=2;c.beginPath();c.moveTo(...a);c.lineTo(...b);c.stroke();c.setLineDash([]);} + this.text(`${conflicts.length} CROISEMENT${conflicts.length>1?'S':''} · UNE ATTACHE PUIS UN PLOT VIDE`,320,580,10,'#829575'); + } + advanceWater(){ + if(!this.running)return; + const now=performance.now(),elapsed=Math.min(.05,(now-this.waterLast)/1000);this.waterLast=now; + if(document.querySelector('dialog[open]'))return; + this.waterCarry+=elapsed*120;while(this.waterCarry>=1&&!this.water.done){this.water.step();this.waterCarry--;} + this.callbacks.waterProgress?.(this.water.caught); + if(this.water.done){this.running=false;queueMicrotask(()=>this.callbacks.settled?.());} + } + drawLine(path,color='#899d74',width=6,dashed=false){if(!path?.length)return;const c=this.ctx;c.strokeStyle=color;c.lineWidth=width;c.lineCap=c.lineJoin='round';if(dashed)c.setLineDash([8,7]);c.beginPath();path.forEach((p,n)=>{if(!n)c.moveTo(...p);else c.lineTo(...p);});c.stroke();c.setLineDash([]);} + drawGouttes(){ + this.advanceWater();const c=this.ctx,cup=this.level.cup,caught=this.water?.caught??this.state.result?.caught??0; + this.round(32,48,576,510,26,'#f2f5e8','#dce5d0'); + for(const o of this.level.obstacles){this.round(o.x,o.y+5,o.w,o.h,8,'#566e3e24');this.round(o.x,o.y,o.w,o.h,8,'#c9b78f','#b5a27b');for(let x=o.x+12;x=this.level.goal)c.arc(cup.x,cup.y+cup.h*.63,11,0,Math.PI);else{c.moveTo(cup.x-9,cup.y+cup.h*.73);c.quadraticCurveTo(cup.x,cup.y+cup.h*.64,cup.x+9,cup.y+cup.h*.73);}c.stroke(); + const [sx,sy]=this.level.source;this.round(sx-48,sy-39,52,16,6,'#ceb889');this.round(sx-14,sy-34,28,25,5,'#ceb889');this.round(sx-9,sy-11,18,8,4,'#6c7f64');this.text('✳',sx-28,sy-31,19,'#91a679'); + for(const path of this.state.lines){this.drawLine(path,'#4c654529',10);this.drawLine(path,'#90a478',6);this.drawLine(path,'#dfe9d0',1.5);} + if(this.stroke)this.drawLine(this.stroke,'#b49e5d',5);if(this.assisted?.length)this.drawLine(this.assisted,'#b49e5d',5,true); + if(this.hint?.action?.type==='draw')this.drawLine(this.hint.action.path,'#b49e5d',4,true); + if(this.water)for(const p of this.water.particles){c.fillStyle='#87b4c7';c.beginPath();c.arc(p.x,p.y,3.3,0,7);c.fill();c.fillStyle='#e6f5ef';c.beginPath();c.arc(p.x-.8,p.y-.8,1,0,7);c.fill();} + this.text(this.running?`${caught} / ${this.level.goal} GOUTTES · L’EAU ARRIVE…`:this.state.result?`${caught} / ${this.level.goal} GOUTTES · ${caught>=this.level.goal?'UN VERRE HEUREUX':'AJUSTEZ VOS RAMPES ET RÉESSAYEZ'}`:'DESSINEZ UNE RAMPE, PUIS LAISSEZ COULER',320,578,10,'#829575'); + } + draw(){if(!this.level||!this.canvas.width)return;const c=this.ctx;c.setTransform(this.canvas.width/W,0,0,this.canvas.height/H,0,0);c.clearRect(0,0,W,H);if(this.mode==='noeuds')this.drawNoeuds();else this.drawGouttes();} +} diff --git a/src/physics-config.js b/src/physics-config.js new file mode 100644 index 0000000..b01a735 --- /dev/null +++ b/src/physics-config.js @@ -0,0 +1,16 @@ +import { COLORS } from './pocket-core.js'; +import { noeudsRules, ropeCrossings } from './noeuds-puzzle.js'; +import { gouttesRules, inkUsed, WATER_TOTAL } from './gouttes-puzzle.js'; +const dot=color=>`${COLORS[color].mark}`; +export const physicsConfigs={ + noeuds:{name:'Nœuds',rules:noeudsRules,eyebrow:'UN PETIT MÉLI-MÉLO, UN FIL À LA FOIS',title:'Les fils
se détendent.',copy:'Déplacez les petites attaches.
Retrouvez un jardin sans nœuds.',steps:[['Prenez une attache.','Faites-la glisser vers un plot vide, ou sélectionnez-la puis choisissez son nouvel emplacement.'],['Séparez les fils.','Plus aucune corde ne doit en croiser ou en toucher une autre. Les attaches vissées restent fixes.']],note:'Déplacez une attache vers un plot vide',unit:'croisements à défaire',reserve:'Les petites attaches.',reserveCopy:'Les deux bouts d’une corde portent la même couleur. Les attaches marquées d’une vis sont fixes.',finish:'Tous les fils respirent.',delay:220,invalid:'Ce plot est occupé, ou cette attache est fixe.', + rulesText:['Faites glisser une attache colorée jusqu’à un plot vide. Vous pouvez aussi cliquer l’attache puis le plot, ou utiliser les boutons.','La corde reste reliée à ses deux attaches. Elle se tend entre elles ; les passages et les contacts avec une autre corde comptent comme des croisements.','Les attaches marquées d’une vis ne bougent pas. Les chapitres suivants ajoutent plus de cordes, de plots et de points fixes.','Séparez toutes les cordes pour terminer. Plusieurs dispositions peuvent fonctionner. Un indice vérifie une route complète depuis votre placement actuel, avec des plots libres pour déplacer les voisins.'], + total:game=>game.level.ropes.length*(game.level.ropes.length-1)/2,remaining:game=>ropeCrossings(game.level,game.state).length, + controls(game,selected,hint){return `
${game.level.pins.map((pin,id)=>``).join('')}
${selected===null?'CHOISISSEZ UNE ATTACHE MOBILE':`ATTACHE ${selected+1} · CHOISISSEZ UN PLOT VIDE`}
${game.level.pegs.map((p,peg)=>({p,peg})).sort((a,b)=>a.p[1]-b.p[1]||a.p[0]-b.p[0]).map(({peg})=>``).join('')}
`;}, + }, + gouttes:{name:'Gouttes',rules:gouttesRules,eyebrow:'UN TRAIT, UN DÉTOUR, UN VERRE HEUREUX',title:'L’eau trouve
son chemin.',copy:'Dessinez des petits ponts.
Guidez les gouttes dans le verre.',steps:[['Dessinez avant la pluie.','Tracez vos rampes avec le doigt ou la souris. Un trait posé reste en place pour guider l’eau.'],['Ouvrez le robinet.','Laissez couler les gouttes. La gravité et les obstacles feront le reste. Annulez et ajustez autant que vous voulez.']],note:'Dessinez une rampe, puis laissez couler l’eau',unit:'gouttes à recueillir',reserve:'Un petit trait suffit ?',reserveCopy:'Les traits sont des rampes fixes. Gardez de l’encre pour les virages et laissez une ouverture au-dessus du verre.',finish:'Un verre plein de sourires.',delay:0,invalid:'Ce trait traverse un obstacle, sort du jardin ou dépasse l’encre disponible.', + rulesText:['Faites glisser le doigt ou la souris dans le jardin pour dessiner un trait. Il devient une rampe fixe : les gouttes rebondissent et glissent dessus sous l’effet de la gravité.','Les blocs du jardin sont solides. Votre trait doit rester dans le jardin et ne peut pas traverser un bloc. L’encre disponible indique la longueur totale que vous pouvez dessiner.','Cliquez « Laisser couler » ou appuyez sur E pour libérer 60 gouttes. Le repère du verre indique combien il faut en recueillir. Les chapitres suivants ajoutent des obstacles, des changements de direction et un objectif plus exigeant.','Une tentative ratée ne coûte rien. Annulez le dernier trait ou effacez vos rampes, puis réessayez. Un indice peut effacer vos traits avant de proposer une route vérifiée avec la même simulation d’eau.'], + total:game=>game.level.goal,remaining:game=>Math.max(0,game.level.goal-(game.state.result?.caught??0)), + controls(game){return `
L’ENCRE DU JARDIN

${Math.floor(game.level.ink-inkUsed(game.state.lines))} / ${game.level.ink} unités restantes

LE VERRE ATTEND SES GOUTTES
${game.state.result?.caught??0} / ${game.level.goal}${WATER_TOTAL} gouttes dans le robinet
Tracer avec des points

Choisissez le départ, puis les points suivants. Chaque point est relié au précédent. Terminez pour poser la rampe.

`;}, + }, +}; diff --git a/src/physics-geometry.js b/src/physics-geometry.js new file mode 100644 index 0000000..3aba449 --- /dev/null +++ b/src/physics-geometry.js @@ -0,0 +1,8 @@ +export const cross=(a,b,c)=>(b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]); +const between=(a,b,p)=>Math.min(a[0],b[0])-1e-7<=p[0]&&p[0]<=Math.max(a[0],b[0])+1e-7&&Math.min(a[1],b[1])-1e-7<=p[1]&&p[1]<=Math.max(a[1],b[1])+1e-7; +export function segmentsMeet(a,b,c,d){ + const x=cross(a,b,c),y=cross(a,b,d),z=cross(c,d,a),w=cross(c,d,b); + return x*y<0&&z*w<0||Math.abs(x)<1e-7&&between(a,b,c)||Math.abs(y)<1e-7&&between(a,b,d)||Math.abs(z)<1e-7&&between(c,d,a)||Math.abs(w)<1e-7&&between(c,d,b); +} +export const distance=(a,b)=>Math.hypot(a[0]-b[0],a[1]-b[1]); +export function closestOnSegment(x,y,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],length=dx*dx+dy*dy,t=length?Math.max(0,Math.min(1,((x-a[0])*dx+(y-a[1])*dy)/length)):0;return[a[0]+t*dx,a[1]+t*dy];} diff --git a/src/physics-previews.js b/src/physics-previews.js new file mode 100644 index 0000000..6c514f1 --- /dev/null +++ b/src/physics-previews.js @@ -0,0 +1,7 @@ +import { COLORS } from './pocket-core.js'; +import { createNoeudsLevel } from './noeuds-puzzle.js'; +import { createGouttesLevel } from './gouttes-puzzle.js'; +const knot=createNoeudsLevel(12),peg=id=>{const [x,y]=knot.pegs[id];return[112+x*34,41+y*34];}; +export const noeudsPreview=``; +const water=createGouttesLevel(12),cup=water.cup,point=p=>[52+p[0]*.4,12+p[1]*.4],source=point(water.source),glass=point([cup.x,cup.y]); +export const gouttesPreview=``; diff --git a/src/physics-style.css b/src/physics-style.css new file mode 100644 index 0000000..674eddc --- /dev/null +++ b/src/physics-style.css @@ -0,0 +1,5 @@ +@import './garden-style.css'; +.physics-pins{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:7px;margin:18px 0;}.physics-pins button{border:1px solid #d4ddcc;background:#fcfcf5;border-radius:12px;padding:8px 3px;}.physics-pins .color-dot{margin-bottom:2px;}.physics-pins small{display:block;font-size:9px;}.physics-pins [aria-pressed=true]{box-shadow:0 0 0 2px #789478;}.physics-pegs{display:grid;grid-template-columns:repeat(var(--size),minmax(0,1fr));gap:4px;}.physics-pegs button{font-size:9px;min-width:0;min-height:31px;border:1px solid #d4ddcc;border-radius:7px;padding:4px 1px;background:#f8faf0;}.physics-pegs button:disabled{background:#e0e7d7;} +.physics-water-controls{margin:20px 0;}.physics-water-controls>button{display:block;width:100%;border:1px solid #d4ddcc;padding:13px 7px;border-radius:12px;font-size:11px;margin:8px 0;}.physics-water-controls .water-run{background:#dce8d7;color:#244c42;}.physics-water-controls kbd{margin-left:8px;}.physics-ink{height:6px;border-radius:6px;background:#d9e2ce;overflow:hidden;margin:12px 0;}.physics-ink span{display:block;height:100%;background:#9cac7a;}.physics-water-controls p{font-size:10px;color:var(--muted);line-height:1.8;}.physics-water-result{border:1px solid #d4ddcc;border-radius:17px;background:#fbfcf4;padding:20px;text-align:center;}.physics-water-result strong{display:block;font:32px Georgia,serif;}.physics-water-result small{display:block;font-size:10px;color:var(--muted);margin-top:10px;}.physics-assisted{margin-top:23px;font-size:10px;color:var(--muted);}.physics-assisted summary{cursor:pointer;}.physics-assisted button{padding:9px 6px;border:1px solid #d4ddcc;border-radius:8px;margin:5px 3px 5px 0;font-size:9px;}.physics-assisted small{display:block;font-size:9px;line-height:1.6;}.physics-point-picker{display:flex;gap:8px;margin:10px 0;}.physics-point-picker label{display:flex;flex:1;min-width:0;gap:6px;align-items:center;}.physics-point-picker input{width:100%;min-width:0;border:1px solid #d4ddcc;border-radius:8px;padding:8px;font-size:12px;background:#fcfcf5;color:var(--ink);} +body[data-pocket=gouttes] .pocket-stage canvas{cursor:crosshair;}.physics-water-controls button:disabled{opacity:.5;} +@media(max-width:580px){.physics-pegs button{min-height:37px;}.physics-pins{grid-template-columns:repeat(6,minmax(0,1fr));}.physics-water-controls>button{padding:15px;font-size:12px;}body[data-pocket=gouttes] .pocket-stage-note{top:8px;font-size:7px;}} diff --git a/src/picture-art.js b/src/picture-art.js new file mode 100644 index 0000000..62b9c3b --- /dev/null +++ b/src/picture-art.js @@ -0,0 +1,25 @@ +import { NEW_COLONY_ART } from './colony-art.js'; +const BACKGROUND={moss:0,cream:6,coral:1,gold:3,plum:4,sky:2,ink:7,leaf:0}; +const INK={m:0,e:6,c:1,g:3,p:4,s:2,i:7,l:0}; +// The collection's own original illustrations become paintings and embroidery. +export function pictureArt(index,size=16) { + const art=NEW_COLONY_ART[index%NEW_COLONY_ART.length], mirrored=Math.floor(index/18)%2; + const cells=[]; + for(let y=0;y{if(id<0 || id>=size*size || seen.has(id))return;seen.add(id);if(gone.has(id))queue.push(id);else result.add(id);}; + for(let n=0;na-b); +} +export function peelColor(level,removed,color,quota) { + const next=[...removed], hits=[]; + while(hits.lengthlevel.cells[id]===color);if(id===undefined)break;next.push(id);hits.push(id);} + return hits; +} diff --git a/src/pocket-canvas.js b/src/pocket-canvas.js new file mode 100644 index 0000000..6a3d6ad --- /dev/null +++ b/src/pocket-canvas.js @@ -0,0 +1,129 @@ +import { COLORS } from './pocket-core.js'; +const W = 640, H = 600; +const same = (a, b) => a[0] === b[0] && a[1] === b[1]; +export class PocketCanvas { + constructor(container, mode, callbacks) { + this.mode = mode; this.callbacks = callbacks; this.reduced = matchMedia('(prefers-reduced-motion: reduce)').matches; this.canvas = document.createElement('canvas'); + this.canvas.id = 'pocket-canvas'; this.canvas.tabIndex = 0; this.canvas.setAttribute('aria-label', mode === 'bobines' ? 'Les fils à démêler' : 'Jardin : choisissez une extrémité puis une case voisine, ou faites glisser'); + container.prepend(this.canvas); this.ctx = this.canvas.getContext('2d'); this.effects = []; this.frame = 0; + this.observer = new ResizeObserver(() => this.resize()); this.observer.observe(container); + this.canvas.addEventListener('pointerdown', event => { + if (this.mode !== 'escapade' || !this.callbacks.enabled()) return; + this.canvas.focus({ preventScroll: true }); this.canvas.setPointerCapture(event.pointerId); this.dragging = true; + const cell = this.cell(event); this.lastCell = cell?.join(','); if (cell) this.callbacks.cell(cell, false); + }); + this.canvas.addEventListener('pointermove', event => { + if (!this.dragging || !this.callbacks.enabled()) return; + const cell = this.cell(event); if (cell && cell.join(',') !== this.lastCell) { this.lastCell = cell.join(','); this.callbacks.cell(cell, true); } + }); + const release = () => { this.dragging = false; this.lastCell = null; }; + this.canvas.addEventListener('pointerup', release); this.canvas.addEventListener('pointercancel', release); + const loop = () => { this.frame = requestAnimationFrame(loop); if (!document.hidden) this.draw(); }; loop(); + } + resize() { const rect = this.canvas.parentElement.getBoundingClientRect(), dpr = Math.min(devicePixelRatio || 1, 2); this.canvas.width = Math.round(rect.width * dpr); this.canvas.height = Math.round(rect.height * dpr); this.draw(); } + update(level, state, hint, selected, previous) { + this.level = level; this.state = state; this.hint = hint; this.selected = selected; + if (previous && !this.reduced && this.mode === 'bobines') { + const q = state.queues.findIndex((n, i) => n > previous.queues[i]), slot = previous.slots.indexOf(null), launched = q === -1 ? null : level.queues[q][previous.queues[q]]; + if (launched) this.effects.push({ bobbin:launched, slot, start:performance.now() }); + for (let col = 0; col < level.lines.length; col++) for (let row = previous.cursors[col]; row < state.cursors[col]; row++) { + const color = level.lines[col][row], active = previous.slots.findIndex(s => s?.color === color), target = active === -1 ? slot : active; + this.effects.push({ x: this.threadX(col), y: 100 + (row - previous.cursors[col]) * this.threadStep(), target:205 + Math.max(0, target) * 115, color, start: performance.now() }); + } + } + if (previous && !this.reduced && this.mode === 'escapade') { + this.motion = { previous, start:performance.now() }; + for (const snake of previous.snakes) if (!state.snakes.some(s => s.id === snake.id)) this.effects.push({ snake, start: performance.now() }); + } + if (!previous) { this.effects = []; this.motion = null; } this.draw(); + } + threadX(col) { return 100 + col * (440 / Math.max(1, this.level.lines.length - 1)); } + threadStep() { return Math.min(44, 345 / Math.max(...this.level.lines.map(l => l.length))); } + grid() { const cell = 480 / this.level.size; return { cell, x:80, y:64 }; } + screenPoint(cell) { const g = this.grid(), rect = this.canvas.getBoundingClientRect(); return { x:rect.x + (g.x + (cell[0] + .5) * g.cell) / W * rect.width, y:rect.y + (g.y + (cell[1] + .5) * g.cell) / H * rect.height }; } + cell(event) { if (!this.level) return null; const rect = this.canvas.getBoundingClientRect(), g = this.grid(), x = Math.floor(((event.clientX - rect.left) / rect.width * W - g.x) / g.cell), y = Math.floor(((event.clientY - rect.top) / rect.height * H - g.y) / g.cell); return x >= 0 && y >= 0 && x < this.level.size && y < this.level.size ? [x, y] : null; } + round(x, y, w, h, r, fill, stroke) { const c = this.ctx; c.beginPath(); c.roundRect(x, y, w, h, r); if (fill) { c.fillStyle = fill; c.fill(); } if (stroke) { c.strokeStyle = stroke; c.lineWidth = 1.5; c.stroke(); } } + text(text, x, y, size = 12, color = '#69786d') { const c = this.ctx; c.fillStyle = color; c.font = `${size}px Segoe UI, sans-serif`; c.textAlign = 'center'; c.textBaseline = 'middle'; c.fillText(text, x, y); } + bobbin(x, y, color, scale = 1) { + const c = this.ctx; c.save(); c.translate(x, y); c.scale(scale, scale); + this.round(-25, -27, 50, 10, 5, '#d0b98d'); this.round(-19, -19, 38, 37, 8, COLORS[color].hex); + c.strokeStyle = '#ffffff6a'; c.lineWidth = 1.8; for (let n = -11; n < 18; n += 5) { c.beginPath(); c.moveTo(-16, n); c.quadraticCurveTo(0, n + 4, 16, n); c.stroke(); } + this.round(-25, 18, 50, 10, 5, '#d0b98d'); this.text(COLORS[color].mark, 0, 0, 15, '#244c42'); c.restore(); + } + drawThreads() { + const c = this.ctx, level = this.level, step = this.threadStep(); + this.round(60, 63, 520, 399, 28, '#f7f6ea', '#d8decf'); + this.round(70, 70, 500, 15, 7, '#d6c39e'); this.round(70, 443, 500, 12, 6, '#d6c39e'); + for (let col = 0; col < level.lines.length; col++) { + const x = this.threadX(col), remaining = level.lines[col].slice(this.state.cursors[col]); + c.strokeStyle = '#d6ddcd'; c.lineWidth = 1; c.beginPath(); c.moveTo(x, 82); c.lineTo(x, 441); c.stroke(); + remaining.forEach((color, row) => { + const y = 108 + row * step; + c.strokeStyle = COLORS[color].hex; c.lineWidth = 10; c.lineCap = 'round'; c.beginPath(); c.moveTo(x - 18, y); c.bezierCurveTo(x - 34, y - 18, x + 34, y - 18, x + 18, y); c.bezierCurveTo(x + 34, y + 18, x - 34, y + 18, x - 18, y); c.stroke(); + c.strokeStyle = '#ffffff80'; c.lineWidth = 2; c.beginPath(); c.moveTo(x - 15, y - 6); c.quadraticCurveTo(x, y - 15, x + 14, y - 6); c.stroke(); + this.text(COLORS[color].mark, x, y, 11, '#34594c'); + if (row === 0) { c.strokeStyle = '#889c7c'; c.lineWidth = 1.5; c.beginPath(); c.arc(x, y, 29, 0, Math.PI * 2); c.stroke(); } + }); + if (!remaining.length) this.text('✓', x, 109, 22, '#88a27b'); + } + this.text('LES FILS ACCESSIBLES SONT EN HAUT', 320, 480, 10, '#8b977e'); + for (let slot = 0; slot < 3; slot++) { + const x = 205 + slot * 115, winding = this.effects.find(fx => fx.bobbin && fx.slot === slot && performance.now() - fx.start < 620), bobbin = this.state.slots[slot]; + this.round(x - 37, 504, 74, 72, 16, '#e5ebde', '#d8dfd0'); + if (bobbin) { this.bobbin(x, 534, bobbin.color, .75); this.text(`${bobbin.remaining}`, x, 567, 10); } + else if (winding) { c.save(); c.globalAlpha = 1 - Math.max(0, (performance.now() - winding.start - 460) / 160); this.bobbin(x, 534, winding.bobbin.color, .75 + Math.sin((performance.now() - winding.start) / 70) * .025); this.text('↻', x, 568, 13); c.restore(); } + else this.text('·', x, 541, 32, '#a8b7a0'); + } + for (const fx of this.effects) { + if (fx.bobbin) continue; + const t = Math.min(1, (performance.now() - fx.start) / 620); if (t >= 1) continue; + const x = fx.x + (fx.target - fx.x) * t, y = fx.y + (530 - fx.y) * t; + c.globalAlpha = 1 - t; c.strokeStyle = COLORS[fx.color].hex; c.lineWidth = 5; c.beginPath(); c.moveTo(fx.x, fx.y); c.bezierCurveTo(fx.x + 80 * Math.sin(t * Math.PI), y, x - 45, y + 20, x, y); c.stroke(); c.globalAlpha = 1; + } + } + drawSnake(snake, alpha = 1) { + const c = this.ctx, g = this.grid(), p = cell => [g.x + (cell[0] + .5) * g.cell, g.y + (cell[1] + .5) * g.cell]; + c.save(); c.globalAlpha = alpha; c.strokeStyle = '#39544316'; c.lineWidth = g.cell * .64; c.lineCap = c.lineJoin = 'round'; c.beginPath(); + snake.cells.forEach((cell, i) => { const [x, y] = p(cell); if (!i) c.moveTo(x + 1, y + 4); else c.lineTo(x + 1, y + 4); }); c.stroke(); + c.strokeStyle = COLORS[snake.color].hex; c.lineWidth = g.cell * .57; c.beginPath(); snake.cells.forEach((cell, i) => { const [x, y] = p(cell); if (!i) c.moveTo(x, y); else c.lineTo(x, y); }); c.stroke(); + for (let i = 1; i < snake.cells.length; i++) { const [x, y] = p(snake.cells[i]); c.fillStyle = '#fffaf32d'; c.beginPath(); c.arc(x, y, g.cell * .1, 0, 7); c.fill(); } + for (const cell of [snake.cells[0], snake.cells.at(-1)]) { const [x, y] = p(cell); c.fillStyle = COLORS[snake.color].hex; c.beginPath(); c.arc(x, y, g.cell * .30, 0, 7); c.fill(); } + const [x, y] = p(snake.cells[0]), second = p(snake.cells[1]), angle = Math.atan2(y - second[1], x - second[0]); + c.save(); c.translate(x, y); c.rotate(angle); c.fillStyle = '#fbfcf5'; for (const offset of [-.13, .13]) { c.beginPath(); c.arc(g.cell * .11, g.cell * offset, g.cell * .09, 0, 7); c.fill(); } + c.fillStyle = '#34514a'; for (const offset of [-.13, .13]) { c.beginPath(); c.arc(g.cell * .14, g.cell * offset, g.cell * .045, 0, 7); c.fill(); } c.restore(); + const tail = p(snake.cells.at(-1)); this.text(COLORS[snake.color].mark, tail[0], tail[1], Math.max(11, g.cell * .20), '#34514a'); + if (this.selected?.id === snake.id || this.hint?.action?.id === snake.id) { + const end = this.hint?.action?.id === snake.id ? this.hint.action.end : this.selected.end, cell = end === 'tail' ? snake.cells.at(-1) : snake.cells[0], [hx, hy] = p(cell); + c.strokeStyle = '#ac9250'; c.lineWidth = 3; c.setLineDash([5, 4]); c.beginPath(); c.arc(hx, hy, g.cell * .40, 0, 7); c.stroke(); c.setLineDash([]); + } + c.restore(); + } + drawGarden() { + const c = this.ctx, level = this.level, g = this.grid(); + this.round(g.x - 16, g.y - 16, 512, 512, 28, '#d9e2cd', '#ccd6c1'); + for (let y = 0; y < level.size; y++) for (let x = 0; x < level.size; x++) this.round(g.x + x * g.cell + 2, g.y + y * g.cell + 2, g.cell - 4, g.cell - 4, 9, (x + y) % 2 ? '#f1f3e7' : '#eaf0e0'); + for (const [x, y] of level.walls) { const sx = g.x + x * g.cell, sy = g.y + y * g.cell; this.round(sx + 7, sy + 7, g.cell - 14, g.cell - 14, 12, '#a3b391', '#93a581'); this.text('✳', sx + g.cell / 2, sy + g.cell / 2, 25, '#cad6b9'); } + for (const snake of level.snakes) { + const x = g.x + (snake.hole[0] + .5) * g.cell, y = g.y + (snake.hole[1] + .5) * g.cell; + c.fillStyle = COLORS[snake.color].hex; c.beginPath(); c.arc(x, y, g.cell * .36, 0, 7); c.fill(); + c.fillStyle = '#40534b'; c.beginPath(); c.arc(x, y, g.cell * .25, 0, 7); c.fill(); this.text(this.state.snakes.some(s => s.id === snake.id) ? COLORS[snake.color].mark : '✓', x, y, g.cell * .22, '#fcfcf4'); + } + const t = this.motion ? Math.min(1, (performance.now() - this.motion.start) / 120) : 1; + for (const snake of this.state.snakes) { + const before = this.motion?.previous.snakes.find(s => s.id === snake.id); + this.drawSnake(t < 1 && before ? { ...snake, cells:snake.cells.map((p, i) => [before.cells[i][0] + (p[0] - before.cells[i][0]) * t, before.cells[i][1] + (p[1] - before.cells[i][1]) * t]) } : snake); + } + for (const fx of this.effects) if (fx.snake) { + const t = Math.min(1, (performance.now() - fx.start) / 420); if (t < 1) this.drawSnake(fx.snake, 1 - t); + } + if (this.hint?.action) { const to = this.hint.action.to; this.round(g.x + to[0] * g.cell + 5, g.y + to[1] * g.cell + 5, g.cell - 10, g.cell - 10, 12, '#e9d59475', '#b39b5b'); this.text('→', g.x + (to[0] + .5) * g.cell, g.y + (to[1] + .5) * g.cell, 24, '#786633'); } + this.text('UNE EXTRÉMITÉ, PUIS UNE CASE VOISINE', 320, 571, 10, '#829575'); + } + draw() { + if (!this.level || !this.canvas.width) return; const c = this.ctx; + c.setTransform(this.canvas.width / W, 0, 0, this.canvas.height / H, 0, 0); c.clearRect(0, 0, W, H); + this.effects = this.effects.filter(fx => performance.now() - fx.start < 700); + if (this.mode === 'bobines') this.drawThreads(); else this.drawGarden(); + } + dispose() { cancelAnimationFrame(this.frame); this.observer.disconnect(); } +} diff --git a/src/pocket-core.js b/src/pocket-core.js new file mode 100644 index 0000000..b24a947 --- /dev/null +++ b/src/pocket-core.js @@ -0,0 +1,68 @@ +// Shared deterministic utilities. Every game keeps independent rules and saves. +export const COLORS = [ + { name: 'Sauge', hex: '#88ad91', mark: '●' }, { name: 'Corail', hex: '#df8c77', mark: '◆' }, + { name: 'Azur', hex: '#80afc5', mark: '▲' }, { name: 'Miel', hex: '#dfba65', mark: '★' }, + { name: 'Prune', hex: '#aa8bb6', mark: '✚' }, { name: 'Pétale', hex: '#d8a5bd', mark: '♥' }, + { name: 'Crème', hex: '#efddb2', mark: '◇' }, { name: 'Encre', hex: '#456052', mark: '■' }, +]; +export const CHAPTERS = ['Les premiers pas', 'Un peu de malice', 'Tout se croise', 'Les grands détours']; +export const LEVEL_COUNT = 48; +export const clone = v => JSON.parse(JSON.stringify(v)); +export function random(seed) { + let s = seed >>> 0; + return () => { s += 0x6D2B79F5; let t = Math.imul(s ^ s >>> 15, 1 | s); t ^= t + Math.imul(t ^ t >>> 7, 61 | t); return ((t ^ t >>> 14) >>> 0) / 4294967296; }; +} +export function shuffle(items, rng) { + const result = [...items]; + for (let i = result.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [result[i], result[j]] = [result[j], result[i]]; } + return result; +} +export function checkIndex(index) { + if (!Number.isInteger(index) || index < 0 || index >= LEVEL_COUNT) throw new Error('Invalid puzzle number'); +} +export function searchPlan(rules, level, start, limit = 12000) { + const startKey = JSON.stringify(start); let canonical = rules.initial(level); + for (let i = 0; i <= level.solution.length; i++) { + if (JSON.stringify(canonical) === startKey) return level.solution.slice(i); + if (i < level.solution.length) canonical = rules.move(level, canonical, level.solution[i]); + if (!canonical) break; + } + const visited = new Set(), deadline = Date.now() + 150; let nodes = 0; + const visit = state => { + if (rules.won(level, state)) return []; + if (++nodes > limit || Date.now() > deadline) return null; + const key = JSON.stringify(state); if (visited.has(key)) return null; visited.add(key); + for (const action of rules.actions(level, state)) { + const next = rules.move(level, state, action); if (!next) continue; + const tail = visit(next); if (tail) return [action, ...tail]; + } + return null; + }; + return visit(start); +} +export class PocketGame { + constructor(rules, index = 0) { this.rules = rules; this.level = rules.create(index); this.state = rules.initial(this.level); this.history = []; this.moves = []; } + get won() { return this.rules.won(this.level, this.state); } + play(action) { + if (this.won) return false; + const next = this.rules.move(this.level, this.state, action); if (!next) return false; + this.history.push(clone(this.state)); this.moves.push(clone(action)); this.state = next; return true; + } + undo() { if (!this.history.length) return false; this.state = this.history.pop(); this.moves.pop(); return true; } + restart() { this.state = this.rules.initial(this.level); this.history = []; this.moves = []; } + hint() { + const plan = this.rules.plan ? this.rules.plan(this.level, this.state) : searchPlan(this.rules, this.level, this.state); + return plan?.length ? { action: plan[0] } : this.history.length ? { undo: true } : null; + } +} +export function encodePocket(game, completed, sound = false) { + return { version: 1, generation: 1, index: game.level.index, moves: game.moves, completed: [...completed], sound }; +} +export function decodePocket(rules, value) { + try { + if (!value || value.version !== 1 || value.generation !== 1 || !Array.isArray(value.moves) || value.moves.length > 5000 || !Array.isArray(value.completed)) return null; + checkIndex(value.index); const game = new PocketGame(rules, value.index); + for (const action of value.moves) if (!game.play(action)) return null; + return { game, completed: new Set(value.completed.filter(n => Number.isInteger(n) && n >= 0 && n < LEVEL_COUNT)), sound: value.sound === true }; + } catch { return null; } +} diff --git a/src/pocket-main.js b/src/pocket-main.js new file mode 100644 index 0000000..173a0b2 --- /dev/null +++ b/src/pocket-main.js @@ -0,0 +1,144 @@ +import './pocket-style.css'; +import { COLORS, CHAPTERS, LEVEL_COUNT, PocketGame, clone, encodePocket, decodePocket } from './pocket-core.js'; +import { atelierRules, exposedPlate } from './atelier-puzzle.js'; +import { bobinesRules } from './bobines-puzzle.js'; +import { escapadeRules } from './escapade-puzzle.js'; +import { PocketCanvas } from './pocket-canvas.js'; + +const mode = document.body.dataset.pocket; +const configs = { + atelier: { name:'Atelier', rules:atelierRules, eyebrow:'CHAQUE PIÈCE A SON MOMENT', title:'Un tour.
Et tout se libère.', copy:'De petites vis, de belles couleurs.
Démontez le monde, pièce après pièce.', steps:[['Regardez sous les planches.', 'Une planche supérieure cache les vis du dessous. Retirez ses trois vis pour la libérer.'], ['Triez sans vous coincer.', 'Deux boîtes de trois vis, et quelques places de côté. Choisissez le bon ordre.']], note:'Tournez l’objet · Cliquez une vis', unit:'vis à retirer', reserve:'Les bonnes places.', reserveCopy:'Les vis rejoignent une boîte de leur couleur. Les autres attendent de côté.', finish:'Tout se libère.', rulesText:['Cliquez sur une vis accessible dans l’objet, ou sur son bouton dans la réserve. Faites glisser l’objet pour le tourner ; la molette permet de zoomer.', 'Chaque boîte reçoit trois vis de sa couleur, puis laisse la place à la suivante. Les vis en attente rejoignent automatiquement une boîte compatible.', 'Une planche disparaît quand ses trois vis sont retirées. Ses voisines du dessous deviennent accessibles.', 'Si les places d’attente sont pleines, il faut libérer une boîte ou annuler un choix. Un indice vérifie une suite complète de coups avant de vous guider.'] }, + bobines: { name:'Bobines', rules:bobinesRules, eyebrow:'LE BON FIL, AU BON MOMENT', title:'Un fil.
Puis un autre.', copy:'Des couleurs à démêler.
De petits instants à dérouler.', steps:[['Choisissez votre bobine.', 'La première bobine de chaque file peut rejoindre l’une des trois places du métier.'], ['Laissez les fils venir.', 'Elle enroule les nœuds accessibles de sa couleur. Une couleur cachée attend son tour.']], note:'Choisissez une bobine dans la réserve', unit:'nœuds à démêler', reserve:'La réserve de fils.', reserveCopy:'Le nombre de chaque bobine indique les nœuds qu’elle doit enrouler.', finish:'Plus un seul nœud.', rulesText:['Seule la première bobine de chaque file peut être choisie. Elle occupe une des trois places du métier.', 'Les nœuds entourés en haut de chaque ligne sont accessibles. Les fils de la bonne couleur s’enroulent automatiquement sur les bobines actives.', 'Une bobine pleine disparaît et rend sa place. Si sa couleur est cachée sous une autre, elle patiente.', 'Trois bobines qui attendent peuvent bloquer le métier. Annulez ou demandez un indice pour retrouver une suite gagnante.'] }, + escapade: { name:'Escapade', rules:escapadeRules, eyebrow:'DE PETITS VOISINS, DE GRANDS DÉTOURS', title:'Chacun
son chemin.', copy:'Un jardin plein de petits voisins.
Aidez-les à retrouver leur maison.', steps:[['Prenez une extrémité.', 'Cliquez sur la tête ou la queue, puis sur une case voisine. Vous pouvez aussi faire glisser.'], ['Gardez des passages.', 'Le corps suit votre chemin. Conduisez chaque créature au trou de sa couleur.']], note:'Faites glisser une tête ou une queue', unit:'voisins à guider', reserve:'Les petits voisins.', reserveCopy:'Chaque couleur a sa maison. La tête et la queue peuvent toutes deux mener le chemin.', finish:'Tous à la maison.', rulesText:['Cliquez sur la tête ou la queue d’une créature, puis sur une case voisine, ou faites glisser cette extrémité de case en case.', 'Le corps suit le chemin, une case à la fois. Vous pouvez aussi sélectionner un voisin dans la liste et utiliser les flèches du clavier ou les boutons directionnels.', 'Les haies, les autres créatures et les trous d’une autre couleur bloquent le passage. La dernière case du corps peut être occupée si elle se libère pendant ce même mouvement.', 'Une créature rentre dès qu’une extrémité atteint son trou. Il n’y a aucun chrono. Si l’indice ne trouve pas une suite complète dans son budget de recherche, il propose d’annuler un détour.'] }, +}; +const config = configs[mode], rules = config.rules, $ = selector => document.querySelector(selector), base = import.meta.env.BASE_URL; +config.title = config.title.replace('
', '
'); +const key = `cubecubecube-${mode}-v1`; let saved; +try { saved = decodePocket(rules, JSON.parse(localStorage.getItem(key))); } catch { /* Storage is optional. */ } +let game = saved?.game || new PocketGame(rules), completed = saved?.completed || new Set(), sound = saved?.sound || false; +let scene, hint = null, selected = null, chapter = Math.floor(game.level.index / 12), busyUntil = 0, audioContext, hintTimer; +$('#app').innerHTML = `
↗cube cube cubeA small escape.
+
${config.eyebrow}

${config.title}

${config.copy}

${config.steps.map(([title, text], i) => `
0${i + 1}
${title}

${text}

`).join('')}✳ Pas de chrono. Prenez votre temps.
+

${config.unit}
${config.name.toUpperCase()} · UNE PETITE PAUSE${mode === 'atelier' ? '' : ''}

${config.note}

+
+
Les petites choses font les belles pauses.48 puzzles · Sans publicité · Sauvegardé ici ✳
+

La collection.

48 petits puzzles. Quatre chapitres, de plus en plus malins. Tous sont accessibles.

${CHAPTERS.map((title, i) => ``).join('')}
+

${config.name}.

    ${config.rulesText.map(text => `
  1. ${text}
  2. `).join('')}

H : indice · Entrée : jouer l’indice · U : annuler · R : recommencer.${mode === 'escapade' ? ' Flèches : déplacer l’extrémité choisie.' : ''}

Votre progression reste sur cet appareil. Les sons sont facultatifs.

`; + +function persist() { try { localStorage.setItem(key, JSON.stringify(encodePocket(game, completed, sound))); } catch { /* Gameplay continues if storage is blocked or full. */ } } +function status(text) { $('#pocket-status').textContent = text; } +function remaining() { + if (mode === 'atelier') return game.level.screws.length - game.state.removed.length; + if (mode === 'bobines') return game.level.lines.reduce((n, line, i) => n + line.length - game.state.cursors[i], 0); + return game.state.snakes.length; +} +function total() { return mode === 'atelier' ? game.level.screws.length : mode === 'bobines' ? game.level.lines.reduce((n, l) => n + l.length, 0) : game.level.snakes.length; } +function enabled() { return performance.now() >= busyUntil && !$('dialog[open]') && !game.won; } +function tone() { + if (!sound) return; + try { + audioContext ||= new (window.AudioContext || window.webkitAudioContext)(); audioContext.resume(); + const osc = audioContext.createOscillator(), gain = audioContext.createGain(), now = audioContext.currentTime; + osc.type = 'sine'; osc.frequency.setValueAtTime(game.won ? 660 : 340 + remaining() % 6 * 55, now); gain.gain.setValueAtTime(.035, now); gain.gain.exponentialRampToValueAtTime(.001, now + .15); osc.connect(gain).connect(audioContext.destination); osc.start(now); osc.stop(now + .16); + } catch { /* Audio is optional. */ } +} +const dot = color => `${COLORS[color].mark}`; +function bobbinSvg(color) { return ``; } +function controls() { + if (mode === 'atelier') { + const exposed = game.level.screws.filter(s => !game.state.removed.includes(s.id) && exposedPlate(game.level, game.state, game.level.plates.find(p => p.id === s.plate))); + return `
${game.state.trays.map(box => `
${box ? `${dot(box.color)}${box.count} / 3${COLORS[box.color].name}` : '✓Tout est trié'}
`).join('')}
EN ATTENTE · ${game.state.buffer.length} / ${game.level.bufferSize}
${Array.from({ length:game.level.bufferSize }, (_, i) => game.state.buffer[i] !== undefined ? `${COLORS[game.state.buffer[i]].mark}` : '·').join('')}
LES PROCHAINES BOÎTES
${game.level.boxes.slice(game.state.nextBox).map(color => `${COLORS[color].mark}`).join('') || 'Plus de boîte en réserve'}
VIS ACCESSIBLES · OU CLIQUEZ DANS L’OBJET
${exposed.map(s => ``).join('')}
`; + } + if (mode === 'bobines') { + return `
${game.state.slots.map((bobbin, i) => `
${bobbin ? `${dot(bobbin.color)}${bobbin.remaining}À enrouler` : `+Place ${i + 1}`}
`).join('')}
LA PREMIÈRE BOBINE DE CHAQUE FILE
${game.level.queues.map((queue, q) => `
0${q + 1}${queue.slice(game.state.queues[q], game.state.queues[q] + 3).map((bobbin, i) => ``).join('') || '✓'}${Math.max(0, queue.length - game.state.queues[q] - 3) ? `+${queue.length - game.state.queues[q] - 3}` : ''}
`).join('')}
`; + } + return `
${game.level.snakes.map(s => ``).join('')}

${selected ? `${COLORS[game.level.snakes[selected.id].color].name} · ${selected.end === 'head' ? 'Tête' : 'Queue'} sélectionnée` : 'Choisissez une tête ou une queue dans le jardin.'}

`; +} +function update(previous = null) { + $('#pocket-number').textContent = `PUZZLE ${String(game.level.index + 1).padStart(2, '0')} / 48 · ${config.name.toUpperCase()}`; + $('#pocket-title').textContent = game.level.title; $('#pocket-difficulty').textContent = CHAPTERS[game.level.tier]; + $('#pocket-remaining').textContent = remaining(); $('#pocket-progress').style.width = `${(1 - remaining() / total()) * 100}%`; + $('#pocket-undo').disabled = !game.history.length; $('#pocket-hint').disabled = game.won; + $('#pocket-sound').setAttribute('aria-pressed', String(sound)); $('#pocket-sound').setAttribute('aria-label', sound ? 'Couper le son' : 'Activer le son'); + $('#pocket-controls').innerHTML = controls(); scene?.update(game.level, game.state, hint, selected, previous); + if (game.won) completed.add(game.level.index); $('#pocket-total').textContent = `${completed.size} / 48`; + $('#pocket-finish').hidden = !game.won; + $('#pocket-finish-copy').textContent = completed.size === LEVEL_COUNT ? 'Les 48 puzzles sont dans votre collection. Bravo !' : `${completed.size} puzzle${completed.size > 1 ? 's' : ''} dans votre collection. Prenez le temps de savourer.`; + $('#pocket-next').textContent = game.level.index === LEVEL_COUNT - 1 ? 'Retrouver la collection →' : 'Le prochain puzzle →'; + if (mode === 'escapade') $('#pocket-end').disabled = !selected; + persist(); +} +function play(action) { + if (!enabled()) return false; + const previous = clone(game.state); + if (!game.play(action)) { status(mode === 'atelier' ? 'Cette vis ne peut pas partir : vérifiez les planches et les places en attente.' : mode === 'bobines' ? 'Les trois places sont occupées. Annulez un choix pour faire de la place.' : 'Ce passage est occupé. Essayez une autre case ou l’autre extrémité.'); return false; } + hint = null; if (mode === 'escapade' && selected && !game.state.snakes.some(s => s.id === selected.id)) selected = null; + busyUntil = performance.now() + (matchMedia('(prefers-reduced-motion: reduce)').matches || mode === 'escapade' ? 0 : mode === 'atelier' ? 800 : 650); tone(); + update(previous); status(game.won ? 'Un petit monde de plus dans votre collection.' : mode === 'bobines' && !game.state.slots.includes(null) ? 'Les trois bobines attendent. Annulez un choix ou demandez un indice.' : config.note); return true; +} +function undo() { busyUntil = 0; hint = null; if (game.undo()) { selected = null; update(); status('Votre dernier choix est annulé.'); } } +function restart() { busyUntil = 0; hint = null; selected = null; game.restart(); update(); status('Le même puzzle, une nouvelle tentative.'); } +function load(index) { clearTimeout(hintTimer); game = new PocketGame(rules, index); hint = null; selected = null; busyUntil = 0; update(); status(config.note); } +function showHint() { + if (!enabled()) return; + status('Je cherche une suite qui mène jusqu’au bout…'); + hintTimer = setTimeout(() => { + hint = game.hint(); if (hint?.action !== undefined && mode === 'escapade') selected = { id:hint.action.id, end:hint.action.end }; + update(); status(hint?.undo ? 'Annulez le dernier détour pour retrouver une suite vérifiée. Entrée permet de l’annuler.' : hint ? 'Le prochain choix est indiqué. Cliquez dessus ou appuyez sur Entrée.' : 'Aucun indice trouvé pour ce plateau.'); + $('#pocket-canvas')?.focus({ preventScroll:true }); + }, 20); +} +function cell(to, dragging) { + if (!enabled()) return; + const snake = game.state.snakes.find(s => s.id === selected?.id); + if (snake) { + const from = selected.end === 'tail' ? snake.cells.at(-1) : snake.cells[0]; + if (Math.abs(from[0] - to[0]) + Math.abs(from[1] - to[1]) === 1) { if (play({ ...selected, to })) return; } + } + if (dragging) return; + const hit = game.state.snakes.find(s => s.cells.some(c => c[0] === to[0] && c[1] === to[1])); + if (hit) { selected = { id:hit.id, end:hit.cells.at(-1)[0] === to[0] && hit.cells.at(-1)[1] === to[1] ? 'tail' : 'head' }; hint = null; update(); status('L’extrémité est choisie. Glissez ou choisissez une case voisine.'); } +} +function direction(dx, dy) { const snake = game.state.snakes.find(s => s.id === selected?.id); if (!snake) { status('Choisissez d’abord une petite créature.'); return; } const from = selected.end === 'tail' ? snake.cells.at(-1) : snake.cells[0]; play({ ...selected, to:[from[0] + dx, from[1] + dy] }); } +function collection() { + $('#pocket-chapters').querySelectorAll('button').forEach(b => b.setAttribute('aria-pressed', String(Number(b.dataset.chapter) === chapter))); + $('#pocket-levels').innerHTML = Array.from({ length:12 }, (_, i) => { + const index = chapter * 12 + i, level = rules.create(index); + return ``; + }).join(''); +} +$('#pocket-controls').addEventListener('click', e => { + const target = e.target.closest('button'); if (!target || target.disabled) return; + if (target.dataset.screw !== undefined) play(Number(target.dataset.screw)); + if (target.dataset.queue !== undefined) play(Number(target.dataset.queue)); + if (target.dataset.creature !== undefined) { selected = { id:Number(target.dataset.creature), end:'head' }; hint = null; update(); $('#pocket-canvas').focus({ preventScroll:true }); } + if (target.id === 'pocket-end' && selected) { selected.end = selected.end === 'head' ? 'tail' : 'head'; hint = null; update(); } + if (target.dataset.direction) direction(...target.dataset.direction.split(',').map(Number)); +}); +$('#pocket-undo').addEventListener('click', undo); $('#pocket-restart').addEventListener('click', restart); $('#pocket-replay').addEventListener('click', restart); $('#pocket-hint').addEventListener('click', showHint); +$('#pocket-sound').addEventListener('click', () => { sound = !sound; update(); tone(); }); +$('#pocket-next').addEventListener('click', () => { if (game.level.index < LEVEL_COUNT - 1) load(game.level.index + 1); else { chapter = 0; collection(); $('#pocket-collection-dialog').showModal(); } }); +$('#pocket-collection').addEventListener('click', () => { chapter = Math.floor(game.level.index / 12); collection(); $('#pocket-collection-dialog').showModal(); }); +$('#pocket-help').addEventListener('click', () => $('#pocket-help-dialog').showModal()); +document.querySelectorAll('[data-close]').forEach(button => button.addEventListener('click', () => button.closest('dialog').close())); +$('#pocket-chapters').addEventListener('click', event => { const b = event.target.closest('[data-chapter]'); if (b) { chapter = Number(b.dataset.chapter); collection(); } }); +$('#pocket-levels').addEventListener('click', event => { const b = event.target.closest('[data-level]'); if (b) { $('#pocket-collection-dialog').close(); load(Number(b.dataset.level)); } }); +document.addEventListener('keydown', event => { + if ($('dialog[open]') || ['INPUT', 'TEXTAREA'].includes(event.target.tagName) || event.ctrlKey || event.metaKey || event.altKey) return; + const pressed = event.key.toLowerCase(); + if (pressed === 'h') { event.preventDefault(); showHint(); } + if (pressed === 'u') { event.preventDefault(); undo(); } + if (pressed === 'r') { event.preventDefault(); restart(); } + if (pressed === 'enter' && hint) { event.preventDefault(); if (hint.undo) undo(); else play(hint.action); } + if (mode === 'bobines' && /^[1-4]$/.test(pressed)) { event.preventDefault(); play(Number(pressed) - 1); } + if (mode === 'escapade' && ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(event.key)) { event.preventDefault(); direction(...({ ArrowUp:[0, -1], ArrowDown:[0, 1], ArrowLeft:[-1, 0], ArrowRight:[1, 0] })[event.key]); } +}); +update(); +try { + if (mode === 'atelier') { const { AtelierScene } = await import('./atelier-scene.js'); scene = new AtelierScene($('#pocket-stage'), { enabled, screw:play, error:() => { $('#pocket-error').hidden = false; } }); $('#pocket-view').addEventListener('click', () => scene.resetView()); } + else scene = new PocketCanvas($('#pocket-stage'), mode, { enabled, cell }); + update(); +} catch { $('#pocket-error').hidden = false; } +window.__pocketDebug = { get game() { return game; }, get scene() { return scene; }, get hint() { return hint; }, get selected() { return selected; }, get ready() { return performance.now() >= busyUntil; } }; +window.addEventListener('pagehide', () => { persist(); scene?.dispose(); }); +window.addEventListener('pageshow', event => { if (event.persisted) location.reload(); }); diff --git a/src/pocket-previews.js b/src/pocket-previews.js new file mode 100644 index 0000000..4684ef3 --- /dev/null +++ b/src/pocket-previews.js @@ -0,0 +1,3 @@ +export const atelierPreview = ``; +export const bobinesPreview = ``; +export const escapadePreview = ``; diff --git a/src/pocket-style.css b/src/pocket-style.css new file mode 100644 index 0000000..88438c1 --- /dev/null +++ b/src/pocket-style.css @@ -0,0 +1,92 @@ +@import './style.css'; +.pocket-header { max-width: 1400px; width: 90%; margin: auto; padding: 24px 0; border-bottom: 1px solid var(--line); display:flex; align-items:center; justify-content:space-between; gap:18px; } +.pocket-brand { display:flex; gap:12px; align-items:center; text-decoration:none; color:var(--ink); font-size:12px; font-weight:650; } +.pocket-brand > span { background:var(--ink); color:var(--page); border-radius:10px; padding:5px 10px; font-size:25px; } +.pocket-brand small { display:block; color:var(--muted); font-size:9px; margin-top:4px; font-weight:400; } +.pocket-nav { display:flex; gap:10px; align-items:center; } +.pocket-nav a, .pocket-nav button { font-size:11px; text-decoration:none; color:var(--ink); border:1px solid var(--line); padding:10px 15px; border-radius:22px; } +.pocket-layout { max-width:1380px; width:90%; margin:46px auto; display:grid; grid-template-columns:220px minmax(0, 1fr) 230px; gap:32px; align-items:center; } +.pocket-intro h1 { font-size:48px; margin:22px 0; } +.pocket-intro > p { font-size:12px; color:var(--muted); line-height:1.9; } +.pocket-tip { display:flex; gap:12px; margin:24px 0; font-size:11px; line-height:1.8; } +.pocket-tip > span { color:#97a58e; font-size:10px; padding-top:1px; } +.pocket-tip strong { display:block; font-weight:600; } +.pocket-tip p { color:var(--muted); margin:4px 0; } +.pocket-intro .slow-note { margin-top:26px; } +.pocket-play { min-width:0; } +.pocket-heading { display:flex; justify-content:space-between; gap:10px; align-items:center; } +.pocket-heading h2 { font-family:Georgia, serif; font-size:25px; font-weight:400; margin:8px 0; } +.pocket-count { text-align:right; } +.pocket-count strong { font:34px Georgia, serif; display:block; } +.pocket-count small { color:var(--muted); font-size:9px; } +.pocket-progress { height:3px; background:var(--line); border-radius:3px; margin:18px 0 10px; overflow:hidden; } +.pocket-progress span { display:block; background:#7c9d81; height:100%; transition:width .4s; } +.pocket-stage { position:relative; width:100%; aspect-ratio:1.08; border:1px solid #e0e4d7; border-radius:24px; background:radial-gradient(ellipse at 50% 40%, #fcfcf4, #e9ede0); overflow:hidden; } +.pocket-stage canvas { display:block; width:100%; height:100%; touch-action:none; } +.pocket-stage canvas:focus-visible { outline-offset:-5px; } +.pocket-stage-note { position:absolute; top:16px; left:18px; z-index:1; pointer-events:none; font-size:8px; letter-spacing:1.4px; color:#7b8e76; } +.pocket-view { position:absolute; bottom:14px; right:15px; padding:8px 12px; background:#fffdf4b8; border:1px solid #dce2d3; border-radius:20px; font-size:10px; } +.pocket-toolbar { display:flex; align-items:center; justify-content:center; flex-wrap:wrap; gap:5px; margin:15px 0 6px; } +.pocket-toolbar button { font-size:11px; border-radius:12px; padding:12px; } +.pocket-toolbar #pocket-hint { background:#e2e9da; } +.pocket-toolbar kbd { margin-left:5px; } +#pocket-status { min-height:38px; font-size:11px; line-height:1.7; text-align:center; color:var(--muted); margin:6px 0 0; } +.pocket-aside { min-width:0; align-self:center; } +.pocket-aside h2 { font:28px Georgia, serif; margin:12px 0; } +.pocket-aside > p { font-size:11px; line-height:1.8; color:var(--muted); } +.pocket-trays, .pocket-slots { display:flex; gap:9px; margin:18px 0; } +.pocket-tray, .pocket-slot { flex:1; min-width:0; padding:12px 6px; border:1px solid #dce0d2; border-radius:13px; background:#fcfcf6; text-align:center; } +.color-dot { display:inline-grid; place-items:center; width:25px; height:25px; border-radius:50%; background:var(--color); color:#244c42; font-size:12px; margin-bottom:8px; } +.pocket-tray strong, .pocket-slot strong { font-size:15px; display:block; font-weight:500; } +.pocket-tray small, .pocket-slot small { font-size:8px; color:var(--muted); display:block; margin-top:5px; } +.pocket-reserve-label { font-size:9px; color:var(--muted); margin:17px 0 10px; display:block; } +.pocket-buffer { display:flex; gap:6px; flex-wrap:wrap; } +.pocket-buffer > span { width:30px; height:30px; border-radius:8px; border:1px dashed #cbd5c4; display:grid; place-items:center; font-size:11px; background:var(--color, #ecf0e5); } +.pocket-upcoming { display:flex; flex-wrap:wrap; gap:5px; } +.pocket-upcoming span { width:19px; height:19px; display:grid; place-items:center; font-size:9px; border-radius:6px; background:var(--color); color:#244c42; } +.screw-options { display:grid; grid-template-columns:repeat(3, 1fr); gap:7px; } +.screw-options button { border:1px solid #d6dccf; background:#fcfcf5; border-radius:10px; padding:8px 4px; font-size:9px; } +.screw-options button .color-dot { margin-bottom:3px; } +.bobbin-queues { display:grid; grid-template-columns:repeat(4, 1fr); gap:7px; } +.bobbin-queue { min-width:0; text-align:center; } +.bobbin-button { display:flex; flex-direction:column; width:100%; gap:3px; align-items:center; margin:8px 0; padding:9px 2px; border:1px solid #d5dccd; border-radius:11px; background:#fcfcf5; } +.bobbin-button svg { width:34px; height:39px; } +.bobbin-button strong { font-size:13px; font-weight:500; } +.bobbin-button small { font-size:7px; color:var(--muted); } +.bobbin-button.buried { opacity:.55; cursor:default; } +.hinted { box-shadow:0 0 0 3px #b39b5b !important; } +.creature-list { display:grid; grid-template-columns:1fr 1fr; gap:9px; margin:20px 0; } +.creature-button { border:1px solid #d5ddcf; background:#fcfcf5; padding:11px 5px; border-radius:14px; font-size:10px; } +.creature-button > span { display:block; background:var(--color); width:32px; height:24px; border-radius:14px; margin:0 auto 7px; font-size:15px; } +.creature-button[aria-pressed=true] { box-shadow:0 0 0 2px #789478; } +.pocket-pad { display:grid; grid-template-columns:repeat(3, 37px); justify-content:center; gap:5px; margin:17px 0; } +.pocket-pad button { border:1px solid #d7dfcf; border-radius:8px; background:#fcfcf5; padding:8px; } +.pocket-pad button:first-child { grid-column:2; } +.pocket-pad button:nth-child(2) { grid-column:1; } +.pocket-finish { position:absolute; inset:0; display:flex; flex-direction:column; justify-content:center; align-items:center; gap:12px; background:#f5f6f1ed; z-index:5; text-align:center; padding:22px; } +.pocket-finish[hidden] { display:none; } +.pocket-finish h2 { font:44px Georgia, serif; font-weight:400; margin:10px 0; } +.pocket-finish p { font-size:12px; color:var(--muted); line-height:1.7; } +.pocket-finish button { padding:13px 22px; border-radius:12px; background:var(--ink); color:var(--page); font-size:12px; } +.pocket-finish button.secondary { color:var(--ink); background:none; } +.pocket-dialog { width:min(700px, 92vw); border:1px solid var(--line); border-radius:24px; color:var(--ink); background:var(--page); padding:30px; max-height:88svh; overflow:auto; } +.pocket-dialog::backdrop { background:#244c4266; backdrop-filter:blur(4px); } +.pocket-dialog-head { display:flex; align-items:center; justify-content:space-between; gap:12px; } +.pocket-dialog-head h2 { font:32px Georgia, serif; margin:0; } +.pocket-dialog-head button { font-size:24px; padding:10px; } +.pocket-dialog p, .pocket-dialog li { font-size:12px; color:var(--muted); line-height:1.9; } +.pocket-chapters { display:flex; flex-wrap:wrap; gap:8px; margin:17px 0; } +.pocket-chapters button { border:1px solid var(--line); border-radius:12px; padding:10px; font-size:10px; } +.pocket-chapters button[aria-pressed=true] { background:var(--accent); } +.pocket-levels { display:grid; grid-template-columns:repeat(4, 1fr); gap:10px; } +.pocket-levels button { padding:17px 6px; border:1px solid var(--line); border-radius:12px; text-align:left; background:#fcfcf7; } +.pocket-levels strong { display:block; font:25px Georgia, serif; margin-bottom:8px; } +.pocket-levels small { font-size:9px; line-height:1.5; display:block; } +.pocket-levels button[aria-current=true] { border-color:#6f916f; background:#e7eddf; } +.pocket-footer { width:90%; max-width:1400px; margin:30px auto 0; border-top:1px solid var(--line); padding:22px 0; display:flex; justify-content:space-between; gap:15px; font-size:9px; color:var(--muted); } +.pocket-footer > span:first-child { font:italic 12px Georgia, serif; } +.pocket-error { position:absolute; inset:30%; z-index:6; background:var(--page); padding:20px; border-radius:10px; font-size:12px; } +@media (max-width:1100px) { .pocket-layout { grid-template-columns:175px minmax(0, 1fr) 200px; gap:18px; } .pocket-intro h1 { font-size:39px; } } +@media (max-width:850px) { .pocket-layout { grid-template-columns:minmax(0, 1fr) 220px; gap:22px; margin-top:28px; } .pocket-intro { grid-column:1/-1; display:grid; grid-template-columns:1fr 1fr; gap:0 25px; } .pocket-intro h1 { font-size:40px; margin:12px 0; grid-row:2/4; } .pocket-intro > .eyebrow { grid-column:1/-1; } .pocket-intro > p { margin-top:15px; } .pocket-tip { margin:8px 0; } .pocket-intro .pocket-tip:nth-of-type(2), .pocket-intro .slow-note { display:none; } .pocket-stage { aspect-ratio: .95; } } +@media (max-width:580px) { .pocket-header { padding:17px 0; gap:10px; } .pocket-nav { gap:5px; } .pocket-nav a, .pocket-nav button { font-size:9px; padding:9px; } .pocket-brand { font-size:10px; gap:8px; } .pocket-brand > span { font-size:21px; padding:5px 8px; } .pocket-brand small { font-size:8px; } .pocket-layout { display:flex; flex-direction:column; gap:22px; width:92%; margin-top:24px; } .pocket-intro { display:block; width:100%; } .pocket-intro h1 { font-size:39px; margin:12px 0; } .pocket-intro h1 br { display:none; } .pocket-intro > p { margin:8px 0; } .pocket-intro .pocket-tip { display:none; } .pocket-play { width:100%; } .pocket-heading h2 { font-size:23px; } .pocket-heading .eyebrow { font-size:8px; letter-spacing:1.2px; } .pocket-stage { aspect-ratio:1; } .pocket-toolbar button { font-size:10px; padding:11px 9px; } .pocket-toolbar kbd { display:none; } .pocket-aside { width:100%; align-self:auto; padding:22px; border:1px solid var(--line); background:#f0f2e9; border-radius:20px; } .pocket-trays { margin:15px 0; } .screw-options { grid-template-columns:repeat(4, 1fr); } .creature-list { grid-template-columns:repeat(3, 1fr); } .pocket-dialog { padding:20px; } .pocket-levels { grid-template-columns:repeat(3, 1fr); } .pocket-finish h2 { font-size:35px; } .pocket-finish { gap:6px; } .pocket-footer { margin-top:0; font-size:8px; } } +@media (prefers-reduced-motion:reduce) { .pocket-progress span { transition:none; } } diff --git a/src/potions-puzzle.js b/src/potions-puzzle.js new file mode 100644 index 0000000..6d00f8d --- /dev/null +++ b/src/potions-puzzle.js @@ -0,0 +1,66 @@ +import { checkIndex, clone, random, shuffle, searchPlan } from './pocket-core.js'; + +export const POTION_CAPACITY = 4; +const TITLES = ['La première infusion','Un parfum de sauge','Les fioles du matin','La bonne dose','Un mélange délicat','La réserve du jardin','Deux petites gouttes','Le fond du flacon','La recette oubliée','Les couleurs du soir','Une place précieuse','La dernière potion']; +export function pourAmount(state, from, to) { + if (!Number.isInteger(from) || !Number.isInteger(to) || from === to || !state.bottles[from]?.length || !state.bottles[to] || state.bottles[to].length >= POTION_CAPACITY) return 0; + const source = state.bottles[from], target = state.bottles[to], color = source.at(-1); + if (target.length && target.at(-1) !== color) return 0; + let run = 0; for (let i = source.length - 1; i >= 0 && source[i] === color; i--) run++; + return Math.min(run, POTION_CAPACITY - target.length); +} +function move(_, state, action) { + if (!action) return null; + const amount = pourAmount(state, action.from, action.to); if (!amount) return null; + const next = clone(state); next.bottles[action.to].push(...next.bottles[action.from].splice(-amount)); return next; +} +export const settledBottle = bottle => bottle.length === POTION_CAPACITY && bottle.every(c => c === bottle[0]); +const won = (_, state) => state.bottles.every(b => !b.length || settledBottle(b)); +const disorder = bottles => bottles.reduce((sum, b) => sum + b.slice(1).filter((c, i) => c !== b[i]).length, 0); +export function createPotionsLevel(index) { + checkIndex(index); const tier = Math.floor(index / 12), rng = random(84071 + index * 7529), count = 3 + tier; + const colors = shuffle([0,1,2,3,4,5,6,7], rng).slice(0, count); + let best; + // Reverse only pours whose exact inverse is a legal maximal forward pour. + // The recorded route therefore conserves every drop and always solves the board. + for (let attempt = 0; attempt < 5; attempt++) { + let state = { bottles: [...colors.map(c => Array(4).fill(c)), [], []] }, route = []; + const seen = new Set([JSON.stringify(state)]); + for (let step = 0; step < 16 + tier * 14; step++) { + const choices = []; + for (let from = 0; from < state.bottles.length; from++) for (let to = 0; to < state.bottles.length; to++) { + if (from === to) continue; const source = state.bottles[from], target = state.bottles[to]; + let run = 0; for (let n = source.length - 1; n >= 0 && source[n] === source.at(-1); n--) run++; + for (let amount = 1; amount <= Math.min(run, 4 - target.length); amount++) { + const next = clone(state); next.bottles[to].push(...next.bottles[from].splice(-amount)); + const action = { from: to, to: from }, restored = move(null, next, action), key = JSON.stringify(next); + if (!restored || JSON.stringify(restored) !== JSON.stringify(state) || seen.has(key)) continue; + choices.push({ next, action, key, score: disorder(next.bottles) + rng() * 2 }); + } + } + if (!choices.length) break; + choices.sort((a,b) => b.score - a.score); const choice = choices[Math.floor(rng() * Math.min(5, choices.length))]; + state = choice.next; seen.add(choice.key); route.unshift(choice.action); + if (state.bottles.some(b => !b.length) && disorder(state.bottles) >= 3 + tier && (!best || disorder(state.bottles) > best.score)) best = { bottles:clone(state.bottles), solution:clone(route), score:disorder(state.bottles) }; + } + } + if (!best) throw new Error('Could not build a mixed potion puzzle'); + const level = { index, tier, title:TITLES[index % 12], colors, ...best }; + let audit = {bottles:clone(level.bottles)}; + for(let n=0;n ({ bottles:clone(level.bottles) }), move, won, + actions(level, state) { + const actions = []; + for (let from = 0; from < state.bottles.length; from++) for (let to = 0; to < state.bottles.length; to++) { + const amount = pourAmount(state, from, to); if (!amount) continue; + // Moving a uniform bottle to an empty one only renames its position. + if (!state.bottles[to].length && state.bottles[from].every(c => c === state.bottles[from][0])) continue; + const next = move(level, state, {from,to}); actions.push({from,to,score:(settledBottle(next.bottles[to]) ? 6 : 0) + (next.bottles[from].length ? 0 : 3) + amount}); + } + return actions.sort((a,b) => b.score-a.score).map(({from,to}) => ({from,to})); + }, + plan:(level, state) => searchPlan(potionsRules, level, state, 35000), +}; diff --git a/src/recolte-puzzle.js b/src/recolte-puzzle.js new file mode 100644 index 0000000..d201d98 --- /dev/null +++ b/src/recolte-puzzle.js @@ -0,0 +1,25 @@ +import {checkIndex,clone,random,shuffle,searchPlan} from './pocket-core.js'; +export function chainNeighbors(level,a,b){return a!==b&&Math.abs(a%level.size-b%level.size)<=1&&Math.abs(Math.floor(a/level.size)-Math.floor(b/level.size))<=1;} +export function validChain(level,state,path){return Array.isArray(path)&&path.length>=3&&path.length<=level.size**2&&new Set(path).size===path.length&&path.every((id,n)=>Number.isInteger(id)&&id>=0&&id=0;y--)if(next.field[y*level.size+x]!==null)column.push(next.field[y*level.size+x]);for(let y=level.size-1;y>=0;y--)next.field[y*level.size+x]=column[level.size-1-y]??null;}return next; +} +function actions(level,state){ + const result=[],seen=new Set(); + const visit=path=>{if(path.length>=3){const key=[...path].sort((a,b)=>a-b).join(',');if(!seen.has(key)){seen.add(key);result.push({path:[...path]});}}if(path.length>=8||result.length>700)return; + const last=path.at(-1);for(let id=0;idb.path.length-a.path.length); +} +export function createRecolteLevel(index){ + checkIndex(index);const tier=Math.floor(index/12),size=5+Math.floor((tier+1)/2),rng=random(105731+index*5797),field=Array(size**2).fill(null),heights=Array(size).fill(0),routes=[],colors=shuffle([0,1,2,3,4,5,7],rng).slice(0,3+tier),quotas=Array(8).fill(0),groups=5+tier*2; + for(let group=0;groupx),rng).find(x=>hs[x]v>=0&&vchainNeighbors({size},id,(size-1-hs[v])*size+v));if(!options.length)break;x=options[0];} + if(path.length>best.length)best=path;if(best.length>=length)break; + } + if(best.length<3)break;const color=colors[group%colors.length];for(const id of best){field[id]=color;heights[id%size]++;}quotas[color]+=best.length;routes.unshift({path:best}); + } + return {index,tier,size,field,quotas,total:field.filter(v=>v!==null).length,solution:routes,title:['Les premières baies','Un panier de couleurs','La petite cueillette','Un coin bien rempli','Les couleurs voisines','Le chemin des fruits','De longues récoltes','Le jardin généreux','Encore quelques baies','Les grands paniers','La dernière branche','Toute la récolte'][index%12]}; +} +export const recolteRules={create:createRecolteLevel,initial:level=>({field:[...level.field],collected:Array(8).fill(0)}),move,won:(level,state)=>state.field.every(v=>v===null),actions,plan:(level,state)=>searchPlan(recolteRules,level,state,3500)}; diff --git a/src/suite-canvas.js b/src/suite-canvas.js new file mode 100644 index 0000000..c4c00bd --- /dev/null +++ b/src/suite-canvas.js @@ -0,0 +1,154 @@ +import { PocketCanvas } from './pocket-canvas.js'; +import { COLORS } from './pocket-core.js'; +import { accessiblePassengers } from './voyage-puzzle.js'; +import { accessibleSpools } from './broderie-puzzle.js'; + +const W=640,H=600; +export class SuiteCanvas extends PocketCanvas { + constructor(container,mode,callbacks){ + super(container,mode,callbacks); + this.canvas.setAttribute('aria-label',({passages:'Cour : faites glisser les blocs vers leurs portes',voyage:'Salle d’embarquement : cliquez un voyageur accessible',carrousel:'Convoyeur : cliquez un tireur en attente pour le relancer',broderie:'Métier à broder : cliquez une bobine découverte'})[mode]); + this.canvas.addEventListener('pointerdown',event=>{ + if(!callbacks.enabled())return;this.canvas.focus({preventScroll:true});this.canvas.setPointerCapture(event.pointerId);const point=this.point(event); + if(mode==='passages'){ + const g=this.grid(),cell=[Math.floor((point.x-g.x)/g.cell),Math.floor((point.y-g.y)/g.cell)],block=this.state.blocks.find(b=>cell[0]>=b.x&&cell[0]=b.y&&cell[1]p.x===x&&p.y===y);if(person)callbacks.play(person.id); + }else if(mode==='broderie'){ + const ready=accessibleSpools(this.level,this.state),piece=[...this.level.spools].reverse().find(s=>ready.includes(s.id)&&this.insideSpool(point,s));if(piece)callbacks.play(piece.id); + }else{ + const slot=Math.floor((point.x-99)/88);if(slot>=0&&slot<5&&point.y>502&&point.y<579&&this.state.waiting[slot])callbacks.play({type:'waiting',slot}); + } + }); + this.canvas.addEventListener('pointermove',event=>{ + if(!this.grabbing||!callbacks.enabled())return;const point=this.point(event),g=this.grid(),cell=[Math.floor((point.x-g.x)/g.cell),Math.floor((point.y-g.y)/g.cell)]; + let dx=cell[0]-this.grabbing.cell[0],dy=cell[1]-this.grabbing.cell[1]; + if(Math.abs(dx)>=Math.abs(dy))dy=0;else dx=0; + for(let n=0;n{this.grabbing=null;};this.canvas.addEventListener('pointerup',release);this.canvas.addEventListener('pointercancel',release); + } + point(event){const r=this.canvas.getBoundingClientRect();return{x:(event.clientX-r.x)/r.width*W,y:(event.clientY-r.y)/r.height*H};} + grid(){return {x:80,y:65,cell:480/this.level.size};} + passengerGrid(){return {x:105,y:64,cell:Math.min(430/this.level.width,355/this.level.height)};} + artGrid(){return {x:170,y:134,cell:300/this.level.size};} + spoolPosition(s){return{x:177+s.x*66,y:393+s.y*40-s.layer};} + insideSpool(p,s){const pos=this.spoolPosition(s);return p.x>=pos.x&&p.x<=pos.x+61&&p.y>=pos.y&&p.y<=pos.y+36;} + screenPoint(value){ + let x,y; + if(this.mode==='passages'){const g=this.grid();[x,y]=[g.x+(value[0]+.5)*g.cell,g.y+(value[1]+.5)*g.cell];} + else if(this.mode==='voyage'){const p=this.level.passengers[value],g=this.passengerGrid();[x,y]=[g.x+(p.x+.5)*g.cell,g.y+(p.y+.5)*g.cell];} + else if(this.mode==='broderie'){const p=this.spoolPosition(this.level.spools[value]);[x,y]=[p.x+30,p.y+18];} + else{[x,y]=[143+value.slot*88,542];} + const r=this.canvas.getBoundingClientRect();return{x:r.x+x/W*r.width,y:r.y+y/H*r.height}; + } + update(level,state,hint,selected,previous){ + this.level=level;this.state=state;this.hint=hint;this.selected=selected; + if(!previous){this.effects=[];this.motion=null;}else if(!this.reduced){ + this.motion={previous,start:performance.now()};const start=performance.now(); + if(this.mode==='passages')for(const b of previous.blocks)if(!state.blocks.some(n=>n.id===b.id))this.effects.push({kind:'block',block:b,start}); + if(this.mode==='voyage'){ + for(const id of state.removed)if(!previous.removed.includes(id))this.effects.push({kind:'person',person:level.passengers[id],start}); + if(state.bus>previous.bus)this.effects.push({kind:'bus',bus:level.buses[previous.bus],start}); + } + if(this.mode==='carrousel'){ + const q=state.queues.findIndex((n,i)=>n>previous.queues[i]),slot=q!==-1?previous.waiting.indexOf(null):previous.waiting.findIndex((p,i)=>p&&(!state.waiting[i]||state.waiting[i].ammo!==p.ammo)); + const pig=q!==-1?level.queues[q][previous.queues[q]]:previous.waiting[slot]; + if(pig)this.effects.push({kind:'pig',pig,slot,hits:state.removed.filter(id=>!previous.removed.includes(id)),start}); + } + if(this.mode==='broderie')for(const id of state.removed)if(!previous.removed.includes(id))this.effects.push({kind:'spool',spool:level.spools[id],patch:state.stitched.find(id=>!previous.stitched.includes(id)),start}); + } + this.draw(); + } + person(x,y,color,scale=1,number=null){ + const c=this.ctx;c.save();c.translate(x,y);c.scale(scale,scale);c.fillStyle='#45605218';c.beginPath();c.ellipse(0,18,17,6,0,0,7);c.fill(); + this.round(-15,-1,30,28,13,COLORS[color].hex);c.fillStyle=COLORS[color].hex;c.beginPath();c.arc(0,-12,11,0,7);c.fill();c.fillStyle='#fff9e8';c.beginPath();c.arc(-3,-14,2,0,7);c.arc(3,-14,2,0,7);c.fill(); + this.text(COLORS[color].mark,0,9,13,color===7?'#fffaf0':'#34564a');if(number!==null)this.text(number,0,38,9);c.restore(); + } + pig(x,y,color,ammo,scale=1,angle=0){ + const c=this.ctx;c.save();c.translate(x,y);c.rotate(angle);c.scale(scale,scale);c.fillStyle=COLORS[color].hex;c.beginPath();c.ellipse(0,1,22,17,0,0,7);c.fill(); + c.beginPath();c.moveTo(-12,-8);c.lineTo(-14,-23);c.lineTo(-3,-12);c.moveTo(9,-11);c.lineTo(18,-23);c.lineTo(18,-4);c.fill(); + c.fillStyle='#f4dbc2';c.beginPath();c.ellipse(15,5,12,9,0,0,7);c.fill();c.fillStyle='#6b775b';c.beginPath();c.arc(12,5,1.8,0,7);c.arc(19,5,1.8,0,7);c.fill(); + c.fillStyle='#fffdf2';c.beginPath();c.arc(3,-9,4,0,7);c.fill();c.fillStyle='#375548';c.beginPath();c.arc(4,-9,1.9,0,7);c.fill(); + c.strokeStyle=COLORS[color].hex;c.lineWidth=3;c.beginPath();c.moveTo(-19,6);c.bezierCurveTo(-38,16,-36,-5,-27,1);c.stroke();this.text(ammo,-4,2,13,color===7?'#fffdf1':'#34564a');c.restore(); + } + bus(x,y,bus,count=0,scale=1){ + const c=this.ctx;c.save();c.translate(x,y);c.scale(scale,scale);this.round(-87,-29,174,64,17,COLORS[bus.color].hex,'#60775688');this.round(-71,-18,79,24,6,'#e9f1e5');this.round(16,-18,39,24,6,'#e9f1e5');this.round(60,-18,16,43,5,'#fff9e277'); + for(const xx of [-50,51]){c.fillStyle='#40594e';c.beginPath();c.arc(xx,34,12,0,7);c.fill();c.fillStyle='#a6b298';c.beginPath();c.arc(xx,34,5,0,7);c.fill();} + this.text(`${COLORS[bus.color].mark} ${count} / ${bus.count}`,-30,19,13,bus.color===7?'#fffaf0':'#34564a');c.restore(); + } + arrow(dx,dy,x,y,size=22){this.text(dx===1?'→':dx===-1?'←':dy===1?'↓':'↑',x,y,size,'#655c32');} + drawPassages(){ + const c=this.ctx,g=this.grid(),level=this.level;this.round(g.x-18,g.y-18,516,516,25,'#dbe3cf','#ccd7c2'); + for(let y=0;y{ + const before=this.motion?.previous.blocks.find(n=>n.id===b.id),t=this.motion?Math.min(1,(performance.now()-this.motion.start)/120):1,x=before?before.x+(b.x-before.x)*t:b.x,y=before?before.y+(b.y-before.y)*t:b.y; + c.save();c.globalAlpha=alpha;this.round(g.x+x*g.cell+4,g.y+y*g.cell+8,b.w*g.cell-8,b.h*g.cell-9,12,'#62785733');this.round(g.x+x*g.cell+4,g.y+y*g.cell+3,b.w*g.cell-8,b.h*g.cell-9,12,COLORS[b.color].hex,this.selected===b.id||this.hint?.action?.id===b.id?'#af9552':'#688c6a60'); + c.strokeStyle='#fff9';c.lineWidth=2;c.beginPath();c.moveTo(g.x+x*g.cell+15,g.y+y*g.cell+10);c.lineTo(g.x+(x+b.w)*g.cell-15,g.y+y*g.cell+10);c.stroke();this.text(COLORS[b.color].mark,g.x+(x+b.w/2)*g.cell,g.y+(y+b.h/2)*g.cell,Math.min(23,g.cell*.4),b.color===7?'#fffdf2':'#355647'); + if(this.hint?.action?.id===b.id)this.arrow(this.hint.action.dx,this.hint.action.dy,g.x+(x+b.w/2)*g.cell,g.y+(y+b.h/2)*g.cell+Math.min(21,g.cell*.3),22);c.restore(); + }; + for(const b of this.state.blocks)drawBlock(b); + for(const fx of this.effects)if(fx.kind==='block'){const t=Math.min(1,(performance.now()-fx.start)/250);drawBlock(fx.block,1-t);} + this.text('UN BLOC, UNE PORTE DE SA COULEUR',320,572,10,'#829575'); + } + drawVoyage(){ + const c=this.ctx,g=this.passengerGrid(),level=this.level,ready=accessiblePassengers(level,this.state);const width=level.width*g.cell,height=level.height*g.cell; + this.round(g.x-18,g.y-14,width+36,height+22,22,'#dde5d2','#d0dbc6'); + for(let y=0;yf.kind==='pig'&&performance.now()-f.start<650); + c.strokeStyle='#c2cfb5';c.lineWidth=36;c.beginPath();c.roundRect(91,76,458,398,35);c.stroke();c.strokeStyle='#e1e7d7';c.lineWidth=23;c.stroke(); + for(let i=0;i<34;i++){const p=this.conveyorPoint((i/34+(this.reduced?0:performance.now()/9000))%1);c.save();c.translate(p.x,p.y);c.rotate(p.angle);c.strokeStyle='#b9c7ac';c.lineWidth=1.5;c.beginPath();c.moveTo(0,-9);c.lineTo(0,9);c.stroke();c.restore();} + this.round(g.x-9,g.y-9,318,318,14,'#d6c9a5'); + for(let id=0;id1.3)continue;const id=running.hits[i],tx=g.x+(id%level.size+.5)*g.cell,ty=g.y+(Math.floor(id/level.size)+.5)*g.cell,u=Math.min(1,local);c.fillStyle=COLORS[running.pig.color].hex;c.beginPath();c.arc(p.x+(tx-p.x)*u,p.y+(ty-p.y)*u,4*(1-u)+2,0,7);c.fill();if(u>.8){c.globalAlpha=1-u;c.strokeStyle='#fffdf1';c.lineWidth=2;c.strokeRect(tx-g.cell/2,ty-g.cell/2,g.cell,g.cell);c.globalAlpha=1;}} + } + } + drawBroderie(){ + const c=this.ctx,level=this.level,size=level.size,cell=256/size,x0=192,y0=70,stitched=new Set(); + const recent=this.effects.find(f=>f.kind==='spool'&&f.patch!==undefined&&performance.now()-f.start<430),t=recent?Math.min(1,(performance.now()-recent.start)/430):1; + for(const id of this.state.stitched){const patch=level.patches[id];for(const pixel of patch.pixels.slice(0,recent?.patch===id?Math.ceil(patch.pixels.length*t):patch.pixels.length))stitched.add(pixel);} + this.round(171,49,298,298,20,'#d1b98f','#baa479');this.round(181,59,278,278,13,'#fbf7e8','#e4d5b5'); + for(let id=0;idperformance.now()-f.start<700); + if(this.mode==='passages')this.drawPassages();else if(this.mode==='voyage')this.drawVoyage();else if(this.mode==='carrousel')this.drawCarrousel();else this.drawBroderie(); + } +} diff --git a/src/suite-main.js b/src/suite-main.js new file mode 100644 index 0000000..c3643f8 --- /dev/null +++ b/src/suite-main.js @@ -0,0 +1,136 @@ +import './bounty-style.css'; +import { COLORS, CHAPTERS, LEVEL_COUNT, PocketGame, clone, encodePocket, decodePocket } from './pocket-core.js'; +import { passagesRules } from './passages-puzzle.js'; +import { voyageRules, accessiblePassengers } from './voyage-puzzle.js'; +import { carrouselRules } from './carrousel-puzzle.js'; +import { broderieRules, accessibleSpools } from './broderie-puzzle.js'; +import { SuiteCanvas } from './suite-canvas.js'; +import { GardenCanvas } from './garden-canvas.js'; +import { gardenConfigs } from './garden-config.js'; +import { neighbors } from './liaisons-puzzle.js'; +import { PhysicsCanvas } from './physics-canvas.js'; +import { physicsConfigs } from './physics-config.js'; +import { HarvestCanvas } from './harvest-canvas.js'; +import { harvestConfigs } from './harvest-config.js'; +import { sandWidth } from './dunes-puzzle.js'; +import { BountyCanvas } from './bounty-canvas.js'; +import { bountyConfigs } from './bounty-config.js'; +import { chainNeighbors } from './recolte-puzzle.js'; +import { activePieces, pieceWidth, pieceHeight } from './mosaique-puzzle.js'; + +const mode=document.body.dataset.pocket, $=s=>document.querySelector(s), base=import.meta.env.BASE_URL; +const configs={ + ...gardenConfigs, + ...physicsConfigs, + ...harvestConfigs, + ...bountyConfigs, + passages:{name:'Passages',rules:passagesRules,eyebrow:'UN PEU DE PLACE, UN NOUVEAU CHEMIN',title:'Une porte.
Un passage.',copy:'Faites glisser les couleurs.
Ouvrez les petites portes.',steps:[['Choisissez votre bloc.','Faites-le glisser de case en case, ou sélectionnez-le puis utilisez les flèches.'],['Préparez les passages.','Chaque bloc rejoint sa porte colorée. Déplacez les voisins qui lui barrent la route.']],note:'Faites glisser un bloc · Flèches pour le déplacer',unit:'blocs à libérer',reserve:'Les petites portes.',reserveCopy:'Sélectionnez un bloc, puis guidez-le vers la porte de sa couleur.',finish:'Toutes les portes ouvertes.',delay:0,rulesText:['Cliquez un bloc pour le choisir. Faites-le glisser horizontalement ou verticalement, ou utilisez le clavier et les boutons directionnels.','Les blocs restent entiers : les haies, les autres pièces et les bords fermés empêchent leur déplacement.','Chaque bloc possède une porte de sa couleur. Alignez toute sa largeur avec cette porte, puis poussez-le vers l’extérieur.','Déplacer un voisin peut libérer un passage. Un indice ne propose un coup que lorsqu’une route complète a été vérifiée. Vous pouvez annuler chaque déplacement.']}, + voyage:{name:'Voyage',rules:voyageRules,eyebrow:'LES PETITS DÉPARTS FONT LES GRANDS VOYAGES',title:'Tout le monde
à bord.',copy:'Des voisins à embarquer.
Une couleur, un départ.',steps:[['Libérez l’allée.','Seuls les voyageurs reliés au quai par un passage libre peuvent se lever.'],['Gardez une place.','Le bus prend sa couleur. Les autres voyageurs attendent sur les cinq places du banc.']],note:'Choisissez un voyageur accessible',unit:'voyageurs à embarquer',reserve:'La salle d’attente.',reserveCopy:'Le bus attend sa couleur. Un bus complet part et laisse arriver le suivant.',finish:'Le dernier bus est parti.',delay:420,rulesText:['Cliquez un voyageur accessible dans la salle ou dans la liste. Il doit pouvoir rejoindre le quai du bas par une allée libre.','Le bus actuel embarque les voyageurs de sa couleur. Les autres s’installent sur les cinq places du banc.','Un bus complet part. Les voyageurs du banc rejoignent automatiquement le prochain bus compatible. Les billets indiquent les départs à venir.','Un choix qui dépasserait la capacité du banc est refusé. Annulez ou demandez un indice pour retrouver une suite gagnante.']}, + carrousel:{name:'Carrousel',rules:carrouselRules,eyebrow:'UN PETIT TOUR, UNE COULEUR DE MOINS',title:'Et ça
tourne encore.',copy:'De petits tireurs en promenade.
Des images à faire disparaître.',steps:[['Lancez un petit tireur.','Choisissez le premier d’une file. Il fait un tour du tapis et vise les pixels accessibles de sa couleur.'],['Préparez le prochain tour.','S’il lui reste des billes, il attend sur l’une des cinq places. Relancez-le après avoir dégagé sa couleur.']],note:'Envoyez un petit tireur · Relancez ceux qui attendent',unit:'pixels à dégager',reserve:'Prêts pour un tour ?',reserveCopy:'Chaque nombre indique les billes restantes. Un tour peut en utiliser une partie seulement.',finish:'Un dernier tour de piste.',delay:680,rulesText:['La première créature de chaque file peut partir sur le tapis. Son nombre indique ses billes : une bille retire un pixel de sa couleur.','Seuls les pixels atteignables depuis l’extérieur, à travers les espaces déjà vides, peuvent être touchés. Un tour a un nombre limité de tirs.','Un tireur vide quitte la piste. Avec des billes restantes, il prend une des cinq places d’attente. Cliquez dessus pour le relancer.','Un tireur en attente qui ne peut toucher aucun pixel ne peut pas être relancé. Cinq tireurs en attente bloquent les nouvelles arrivées : annulez ou demandez un indice.']}, + broderie:{name:'Broderie',rules:broderieRules,eyebrow:'LES PETITS FILS FONT LES BELLES IMAGES',title:'Trois fils.
Une image.',copy:'Une bobine, une couleur.
Faites apparaître un petit tableau.',steps:[['Prenez un fil découvert.','Les bobines du dessus cachent celles du dessous. Choisissez parmi celles qui sont libres.'],['Réunissez trois couleurs.','Trois bobines identiques brodent une partie de l’image et libèrent leurs places.']],note:'Choisissez une bobine découverte · Réunissez trois couleurs',unit:'bobines à assembler',reserve:'Les sept petites places.',reserveCopy:'Réunissez trois bobines de la même couleur pour broder un morceau du tableau.',finish:'Un petit tableau terminé.',delay:430,rulesText:['Cliquez une bobine dont aucune autre ne couvre le dessus, dans le tas ou dans la liste. Elle rejoint les sept places de travail.','Trois bobines de la même couleur sont utilisées ensemble. Elles brodent une partie de l’image puis libèrent leurs trois places.','Les emplacements en pointillés attendent vos fils. Chaque tableau comporte plusieurs parties colorées : toutes doivent être brodées.','Gardez assez de places pour compléter vos groupes. Une sélection qui dépasserait les sept places est refusée. Annulation, indices et reprise sont toujours disponibles.']}, +}; +const config=configs[mode],rules=config.rules,key=`cubecubecube-${mode}-v1`;let saved; +try{saved=decodePocket(rules,JSON.parse(localStorage.getItem(key)));}catch{/* Storage is optional. */} +let game=saved?.game||new PocketGame(rules),completed=saved?.completed||new Set(),sound=saved?.sound||false; +let selected=null,hint=null,scene,chapter=Math.floor(game.level.index/12),busyUntil=0,audio,finishTimer,hintTimer; +$('#app').innerHTML=`
↗cube cube cubeA small escape.
+
${config.eyebrow}

${config.title}

${config.copy}

${config.steps.map(([title,text],i)=>`
0${i+1}
${title}

${text}

`).join('')}✳ Pas de chrono. Prenez votre temps.

${config.unit}
${config.name.toUpperCase()} · UNE PETITE PAUSE

${config.note}

+
Les petites choses font les belles pauses.48 puzzles · Sans publicité · Sauvegardé ici ✳

La collection.

48 petits puzzles. Quatre chapitres, de plus en plus malins. Tous sont accessibles.

${CHAPTERS.map((title,i)=>``).join('')}

${config.name}.

    ${config.rulesText.map(text=>`
  1. ${text}
  2. `).join('')}

H : indice · Entrée : jouer l’indice · U : annuler · R : recommencer.${mode==='passages'?' Flèches : déplacer le bloc choisi.':mode==='carrousel'?' 1–4 : lancer une file.':''}

Votre progression reste sur cet appareil. Les sons sont facultatifs.

`; +function persist(){try{localStorage.setItem(key,JSON.stringify(encodePocket(game,completed,sound)));}catch{/* Play remains available without storage. */}} +function status(text){$('#pocket-status').textContent=text;} +function remaining(){return config.remaining?config.remaining(game):mode==='passages'?game.state.blocks.length:mode==='broderie'?game.level.spools.length-game.state.removed.length:(mode==='voyage'?game.level.passengers.length:game.level.cells.length)-game.state.removed.length;} +function total(){return config.total?config.total(game):mode==='passages'?game.level.blocks.length:mode==='broderie'?game.level.spools.length:mode==='voyage'?game.level.passengers.length:game.level.cells.length;} +function enabled(){return performance.now()>=busyUntil&&!scene?.running&&!$('dialog[open]')&&!game.won;} +const dot=color=>`${COLORS[color].mark}`; +const chip=color=>`${COLORS[color].mark}`; +function pigSvg(color){return ``;} +function spoolSvg(color){return ``;} +function controls(){ + if(config.controls)return config.controls(game,selected,hint); + if(mode==='passages')return `
${game.level.blocks.map(b=>``).join('')}

${selected===null?'Choisissez un bloc dans la cour.':`${COLORS[game.level.blocks[selected].color].name} · Bloc sélectionné`}

`; + if(mode==='voyage'){ + const bus=game.level.buses[game.state.bus],ready=accessiblePassengers(game.level,game.state); + return `
LE BUS À QUAI${bus?`${COLORS[bus.color].mark} ${game.state.boarded} / ${bus.count}`:'✓'}${bus?COLORS[bus.color].name:'Tous les bus sont partis'}
LE BANC · ${game.state.buffer.length} / 5
${Array.from({length:5},(_,i)=>game.state.buffer[i]!==undefined?chip(game.level.passengers[game.state.buffer[i]].color):'·').join('')}
LES PROCHAINS BILLETS
${game.level.buses.slice(game.state.bus+1).map(b=>`${COLORS[b.color].mark} ${b.count}`).join('')}
VOYAGEURS ACCESSIBLES
${ready.map(id=>``).join('')}
`; + } + if(mode==='carrousel')return `LES CINQ PLACES · RELANCEZ UN TIREUR
${game.state.waiting.map((pig,slot)=>``).join('')}
LE PREMIER TIREUR DE CHAQUE FILE
${game.level.queues.map((queue,q)=>`
0${q+1}${queue.slice(game.state.queues[q],game.state.queues[q]+3).map((pig,i)=>``).join('')||'✓'}${queue.length-game.state.queues[q]>3?`+${queue.length-game.state.queues[q]-3}`:''}
`).join('')}
`; + const ready=accessibleSpools(game.level,game.state),colors=[...new Set(game.level.cells)]; + return `EN COURS · ${game.state.buffer.length} / 7
${Array.from({length:7},(_,i)=>game.state.buffer[i]!==undefined?chip(game.state.buffer[i]):'·').join('')}
LE TABLEAU · ${game.state.stitched.length} / ${game.level.patches.length} PARTIES
${colors.map(color=>`${dot(color)}${game.level.patches.filter(p=>p.color===color&&!game.state.stitched.includes(p.id)).length} à broder`).join('')}
BOBINES DÉCOUVERTES
${ready.map(id=>``).join('')}
`; +} +function update(previous=null,action=null){ + $('#pocket-number').textContent=`PUZZLE ${String(game.level.index+1).padStart(2,'0')} / 48 · ${config.name.toUpperCase()}`;$('#pocket-title').textContent=game.level.title;$('#pocket-difficulty').textContent=CHAPTERS[game.level.tier];$('#pocket-remaining').textContent=remaining();$('#pocket-progress').style.width=`${100*(1-remaining()/total())}%`; + $('#pocket-undo').disabled=!game.history.length;$('#pocket-hint').disabled=game.won;$('#pocket-sound').setAttribute('aria-pressed',String(sound));$('#pocket-sound').setAttribute('aria-label',sound?'Couper le son':'Activer le son');$('#pocket-controls').innerHTML=controls();scene?.update(game.level,game.state,hint,selected,previous,action); + if((mode==='gouttes'||mode==='dunes')&&(scene?.running||game.won))$('#pocket-controls').querySelectorAll('button').forEach(b=>b.disabled=true); + if(game.won)completed.add(game.level.index);$('#pocket-total').textContent=`${completed.size} / 48`;$('#pocket-finish').hidden=!game.won||performance.now()1?'s':''} dans votre collection. Prenez le temps de savourer.`;$('#pocket-next').textContent=game.level.index===47?'Retrouver la collection →':'Le prochain puzzle →';persist(); +} +function tone(){if(!sound)return;try{audio||=new(window.AudioContext||window.webkitAudioContext)();audio.resume();const osc=audio.createOscillator(),gain=audio.createGain(),now=audio.currentTime;osc.frequency.setValueAtTime(game.won?660:300+remaining()%7*50,now);gain.gain.setValueAtTime(.035,now);gain.gain.exponentialRampToValueAtTime(.001,now+.16);osc.connect(gain).connect(audio.destination);osc.start(now);osc.stop(now+.17);}catch{/* Audio is optional. */}} +function play(action){ + if(!enabled())return false;const previous=clone(game.state); + if(!game.play(action)){status(config.invalid||(mode==='passages'?'Ce passage est occupé ou cette porte ne correspond pas au bloc.':mode==='voyage'?'Ce voyageur est bloqué, ou le banc est plein.':mode==='carrousel'?'Aucun pixel de cette couleur n’est accessible, ou les cinq places sont occupées.':'Cette bobine est couverte, ou les sept places sont pleines.'));return false;} + hint=null;if(mode==='passages'&&!game.state.blocks.some(b=>b.id===selected))selected=null; + if(mode==='potions')selected=null; + if(mode==='alveoles'&&!game.level.queues[selected]?.[game.state.queues[selected]])selected=null; + if(mode==='dunes'&&!game.level.queues[selected]?.[game.state.queues[selected]])selected=null; + if(bountyConfigs[mode])selected=null; + busyUntil=performance.now()+(matchMedia('(prefers-reduced-motion: reduce)').matches?0:config.delay);update(previous,action);tone();status(config.afterStatus?.(game)||(mode==='gouttes'&&action.type==='run'&&scene.running?'L’eau arrive… Regardez vos petites rampes travailler.':game.won?'Une belle chose de plus dans votre collection.':config.note)); + clearTimeout(finishTimer);if(game.won)finishTimer=setTimeout(()=>update(),Math.max(0,busyUntil-performance.now())+10);return true; +} +function cancelPending(){clearTimeout(finishTimer);clearTimeout(hintTimer);busyUntil=0;hint=null;selected=null;} +function undo(){cancelPending();if(game.undo()){update();status('Votre dernier choix est annulé.');}} +function restart(){cancelPending();game.restart();update();status('Le même puzzle, une nouvelle tentative.');} +function load(index){cancelPending();game=new PocketGame(rules,index);update();status(config.note);} +function select(id){if(!enabled())return;if((mode==='alveoles'||mode==='dunes')&&!game.level.queues[id]?.[game.state.queues[id]])return;if(mode==='mosaique'&&!activePieces(game.level,game.state).some(p=>p.id===id))return;if(mode==='noeuds'&&game.level.pins[id]?.fixed){status('Cette attache est vissée. Déplacez les autres bouts.');return;}selected=id;hint=null;update();status(mode==='mosaique'?'La pièce est choisie. Faites-la glisser ou cliquez sa case de départ.':mode==='dunes'?'Le bloc est choisi. Cliquez dans le bac ou choisissez une colonne.':mode==='noeuds'?'L’attache est choisie. Faites-la glisser ou cliquez un plot vide.':mode==='alveoles'?'La pile est choisie. Posez-la dans une alvéole vide.':mode==='liaisons'?'Partez d’un point de cette couleur, puis choisissez les cases voisines.':'Le bloc est choisi. Faites-le glisser ou utilisez les flèches.');} +function chainCell(id){if(!enabled()||game.state.field[id]===null)return;hint=null;const path=Array.isArray(selected)?selected:[],back=path.indexOf(id);if(back>=0)selected=path.slice(0,back+1);else if(!path.length||game.state.field[id]===game.state.field[path[0]]&&chainNeighbors(game.level,path.at(-1),id))selected=[...path,id];else{status('Choisissez une bille voisine de même couleur.');return;}update();status(`${selected.length} bille${selected.length>1?'s':''} choisie${selected.length>1?'s':''}. Validez la chaîne à partir de trois.`);} +function number(id){if(!enabled()||game.state.field[id]===null)return;if(selected===id){selected=null;hint=null;update();}else if(selected===null){selected=id;hint=null;update();status('Le premier nombre est choisi. Cherchez sa paire libre.');}else play({a:selected,b:id});} +function mosaic(id){if(selected===null){status('Choisissez d’abord une pièce.');return;}play({id:selected,x:id%game.level.size,y:Math.floor(id/game.level.size)});} +function sand(x){if(selected===null){status('Choisissez d’abord un bloc dans une des trois files.');return;}play({q:selected,x});} +function holeDirection(dx,dy){play({type:'path',path:[[Math.max(50,Math.min(590,game.state.hole[0]+dx*22)),Math.max(60,Math.min(540,game.state.hole[1]+dy*22))]]});} +function peg(id){if(selected===null){status('Choisissez d’abord une attache mobile.');return;}play({pin:selected,peg:id});} +function waterProgress(caught){if(mode!=='gouttes')return;$('#pocket-remaining').textContent=Math.max(0,game.level.goal-caught);$('#pocket-progress').style.width=`${Math.min(100,caught/game.level.goal*100)}%`;const counter=$('.physics-water-result strong');if(counter)counter.textContent=`${caught} / ${game.level.goal}`;} +function settled(){if(mode!=='gouttes'&&mode!=='dunes')return;update();status(mode==='dunes'?(game.won?'Une dernière dune, une belle chose de plus.':config.note):game.won?'Le verre est heureux. Une belle chose de plus dans votre collection.':'Le verre attend encore quelques gouttes. Annulez, ajustez vos traits et réessayez.');} +function waterPoint(){if(!enabled())return;const x=Number($('#water-x').value),y=Number($('#water-y').value);if(!Number.isFinite(x)||!Number.isFinite(y)||x<35||x>605||y<75||y>550){status('Choisissez un point dans le jardin : X de 35 à 605, Y de 75 à 550.');return;}scene.assisted||=[];if(scene.assisted.length>=160)return;scene.assisted.push([x,y]);$('#water-point-status').textContent=`${scene.assisted.length} point${scene.assisted.length>1?'s':''} · ${scene.assisted.map(p=>p.join(', ')).join(' → ')}`;} +function bottle(id){if(!enabled())return;if(selected===id){selected=null;update();status(config.note);}else if(selected===null){if(!game.state.bottles[id].length){status('Choisissez d’abord une fiole contenant du liquide.');return;}selected=id;hint=null;update();status(`Fiole ${id+1} choisie. Cliquez sa destination.`);}else play({from:selected,to:id});} +function hex(cell){if(selected===null){status('Choisissez d’abord une pile dans une des trois files.');return;}play({q:selected,cell});if(!game.level.queues[selected]?.[game.state.queues[selected]]){selected=null;update();}} +function liaisonCell(cell){ + if(!enabled())return;const color=game.level.pairs.findIndex(p=>p.includes(cell)); + if(color>=0){const path=game.state.paths[color];if(selected===color&&path.length&&path[0]!==cell&&neighbors(game.level.size,path.at(-1),cell)){play({color,path:[...path,cell]});return;}selected=color;if(path.at(-1)===cell&&path.length>1)return;hint=null;play({color,path:[cell]});update();return;} + if(selected===null){status('Choisissez un point ou une couleur pour commencer.');return;} + const path=game.state.paths[selected].length?game.state.paths[selected]:[game.level.pairs[selected][0]],back=path.indexOf(cell); + if(back>=0)play({color:selected,path:path.slice(0,back+1)});else if(neighbors(game.level.size,path.at(-1),cell))play({color:selected,path:[...path,cell]});else status('Choisissez une case voisine du bout de votre chemin.'); +} +function direction(dx,dy){if(selected===null){status('Choisissez d’abord un bloc.');return;}play({id:selected,dx,dy});} +function showHint(){if(!enabled())return;status('Je cherche une suite qui mène jusqu’au bout…');hintTimer=setTimeout(()=>{hint=game.hint();if(mode==='passages'&&hint?.action)selected=hint.action.id;if((mode==='alveoles'||mode==='dunes')&&hint?.action)selected=hint.action.q;if(mode==='mosaique'&&hint?.action)selected=hint.action.id;if(mode==='recolte'&&hint?.action)selected=hint.action.path;if(mode==='potions'&&hint?.action)selected=hint.action.from;if(mode==='liaisons'&&hint?.action)selected=hint.action.color;if(mode==='noeuds'&&hint?.action)selected=hint.action.pin;update();status(hint?.undo?'La recherche ne trouve pas de suite complète. Annulez un détour avec Entrée.':mode==='gouttes'&&hint?.action?.type==='clear'?'Effacez ces rampes pour dessiner une route vérifiée. Entrée exécute l’indice.':mode==='gouttes'&&hint?.action?.type==='run'?'Les rampes sont prêtes. Laissez couler, ou appuyez sur Entrée.':mode==='liaisons'&&hint?.action?.path.length===0?'Effacez ce détour pour ouvrir une route complète. Entrée exécute l’indice.':hint?'Le prochain choix est indiqué. Cliquez dessus ou appuyez sur Entrée.':'Aucun indice trouvé pour ce plateau.');$('#pocket-canvas').focus({preventScroll:true});},20);} +function collection(){ + $('#pocket-chapters').querySelectorAll('button').forEach(b=>b.setAttribute('aria-pressed',String(Number(b.dataset.chapter)===chapter))); + $('#pocket-levels').innerHTML=Array.from({length:12},(_,i)=>{const index=chapter*12+i,level=rules.create(index);return ``;}).join(''); +} +$('#pocket-controls').addEventListener('click',event=>{const b=event.target.closest('button');if(!b||b.disabled)return;if(b.dataset.select!==undefined)select(Number(b.dataset.select));if(b.dataset.piece!==undefined)play(Number(b.dataset.piece));if(b.dataset.queue!==undefined)play({type:'queue',q:Number(b.dataset.queue)});if(b.dataset.waiting!==undefined)play({type:'waiting',slot:Number(b.dataset.waiting)});if(b.dataset.direction)direction(...b.dataset.direction.split(',').map(Number));if(b.dataset.bottle!==undefined)bottle(Number(b.dataset.bottle));if(b.dataset.hex!==undefined)hex(Number(b.dataset.hex));if(b.dataset.cell!==undefined)liaisonCell(Number(b.dataset.cell));if(b.hasAttribute('data-clear')&&selected!==null)play({color:selected,path:[]});}); +$('#pocket-undo').addEventListener('click',undo);$('#pocket-restart').addEventListener('click',restart);$('#pocket-replay').addEventListener('click',restart);$('#pocket-hint').addEventListener('click',showHint);$('#pocket-sound').addEventListener('click',()=>{sound=!sound;update();tone();}); +$('#pocket-next').addEventListener('click',()=>{if(game.level.index<47)load(game.level.index+1);else{chapter=0;collection();$('#pocket-collection-dialog').showModal();}}); +$('#pocket-collection').addEventListener('click',()=>{chapter=Math.floor(game.level.index/12);collection();$('#pocket-collection-dialog').showModal();});$('#pocket-help').addEventListener('click',()=>$('#pocket-help-dialog').showModal());document.querySelectorAll('[data-close]').forEach(b=>b.addEventListener('click',()=>b.closest('dialog').close())); +$('#pocket-chapters').addEventListener('click',event=>{const b=event.target.closest('[data-chapter]');if(b){chapter=Number(b.dataset.chapter);collection();}});$('#pocket-levels').addEventListener('click',event=>{const b=event.target.closest('[data-level]');if(b){$('#pocket-collection-dialog').close();load(Number(b.dataset.level));}}); +document.addEventListener('keydown',event=>{if($('dialog[open]')||['INPUT','TEXTAREA'].includes(event.target.tagName)||event.ctrlKey||event.metaKey||event.altKey)return;const key=event.key.toLowerCase();if(key==='h'){event.preventDefault();showHint();}if(key==='u'){event.preventDefault();undo();}if(key==='r'){event.preventDefault();restart();}if(key==='enter'&&hint){event.preventDefault();if(hint.undo)undo();else play(hint.action);}if(mode==='carrousel'&&/^[1-4]$/.test(key)){event.preventDefault();play({type:'queue',q:Number(key)-1});}if(mode==='passages'&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(event.key)){event.preventDefault();direction(...({ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]})[event.key]);}}); +document.addEventListener('keydown',event=>{if(!gardenConfigs[mode]||$('dialog[open]')||['INPUT','TEXTAREA'].includes(event.target.tagName)||event.ctrlKey||event.metaKey||event.altKey)return;if(mode==='alveoles'&&/^[1-3]$/.test(event.key)){event.preventDefault();select(Number(event.key)-1);}if(mode==='potions'&&/^[1-8]$/.test(event.key)&&Number(event.key)<=game.state.bottles.length){event.preventDefault();bottle(Number(event.key)-1);}if(mode==='liaisons'&&selected!==null&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(event.key)){event.preventDefault();const size=game.level.size,last=game.state.paths[selected].at(-1)??game.level.pairs[selected][0],delta=({ArrowUp:-size,ArrowDown:size,ArrowLeft:-1,ArrowRight:1})[event.key],cell=last+delta;if(cell>=0&&cell{const b=event.target.closest('button');if(!b||b.disabled)return;if(b.dataset.peg!==undefined)peg(Number(b.dataset.peg));if(b.hasAttribute('data-water-run'))play({type:'run'});if(b.hasAttribute('data-water-clear'))play({type:'clear'});if(b.hasAttribute('data-water-point'))waterPoint();if(b.hasAttribute('data-water-place')){if(scene.assisted?.length>=2)play({type:'draw',path:scene.assisted});else status('Ajoutez au moins deux points avant de poser le trait.');}if(b.hasAttribute('data-water-cancel')){scene.assisted=[];$('#water-point-status').textContent='Le tracé est annulé.';}}); +document.addEventListener('keydown',event=>{if(mode!=='gouttes'||$('dialog[open]')||['INPUT','TEXTAREA'].includes(event.target.tagName)||event.ctrlKey||event.metaKey||event.altKey)return;if(event.key.toLowerCase()==='e'){event.preventDefault();play({type:'run'});}}); +$('#pocket-controls').addEventListener('click',event=>{const b=event.target.closest('button');if(!b||b.disabled)return;if(b.dataset.gate!==undefined)play(Number(b.dataset.gate));if(b.dataset.sandX!==undefined)sand(Number(b.dataset.sandX));if(b.dataset.food!==undefined)play({type:'visit',id:Number(b.dataset.food)});if(b.dataset.holeDir)holeDirection(...b.dataset.holeDir.split(',').map(Number));}); +document.addEventListener('keydown',event=>{if(!harvestConfigs[mode]||$('dialog[open]')||['INPUT','TEXTAREA'].includes(event.target.tagName)||event.ctrlKey||event.metaKey||event.altKey)return; + if(mode==='ecluses'&&/^[1-9]$/.test(event.key)){event.preventDefault();play(Number(event.key)-1);} + if(mode==='dunes'){ + if(/^[1-3]$/.test(event.key)){event.preventDefault();select(Number(event.key)-1);} + const piece=selected===null?null:game.level.queues[selected]?.[game.state.queues[selected]]; + if(piece&&['ArrowLeft','ArrowRight',' '].includes(event.key)){event.preventDefault();const max=game.level.width-sandWidth(piece),x=Math.max(0,Math.min(max,scene.cursor??hint?.action?.x??Math.floor(max/2)));if(event.key===' ')sand(x);else{scene.cursor=Math.max(0,Math.min(max,x+(event.key==='ArrowRight'?1:-1)));hint=null;update();}} + } + if(mode==='fringale'&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(event.key)){event.preventDefault();holeDirection(...({ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]})[event.key]);} +}); +$('#pocket-controls').addEventListener('click',event=>{const b=event.target.closest('button');if(!b||b.disabled)return;if(b.dataset.chain!==undefined)chainCell(Number(b.dataset.chain));if(b.hasAttribute('data-chain-commit')&&Array.isArray(selected))play({path:selected});if(b.hasAttribute('data-chain-clear')){selected=null;hint=null;update();status('Le tracé est effacé.');}if(b.dataset.number!==undefined)number(Number(b.dataset.number));if(b.dataset.mosaic!==undefined)mosaic(Number(b.dataset.mosaic));}); +document.addEventListener('keydown',event=>{if(!bountyConfigs[mode]||$('dialog[open]')||['INPUT','TEXTAREA'].includes(event.target.tagName)||event.ctrlKey||event.metaKey||event.altKey)return; + if(mode==='recolte'&&event.key==='Enter'&&Array.isArray(selected)&&!hint){event.preventDefault();play({path:selected});} + if(mode==='recolte'&&event.key==='Escape'){selected=null;hint=null;scene.draft=null;update();} + if(mode==='mosaique'){ + if(/^[1-3]$/.test(event.key)){event.preventDefault();const p=activePieces(game.level,game.state)[Number(event.key)-1];if(p)select(p.id);} + const piece=game.level.pieces[selected];if(piece&&['ArrowUp','ArrowDown','ArrowLeft','ArrowRight',' '].includes(event.key)){event.preventDefault();const cursor=scene.cursor??hint?.action??{x:0,y:0};if(event.key===' ')play({id:selected,...cursor});else{const [dx,dy]=({ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]})[event.key];scene.cursor={x:Math.max(0,Math.min(game.level.size-pieceWidth(piece),cursor.x+dx)),y:Math.max(0,Math.min(game.level.size-pieceHeight(piece),cursor.y+dy))};hint=null;update();}} + } +}); +scene=new (bountyConfigs[mode]?BountyCanvas:harvestConfigs[mode]?HarvestCanvas:physicsConfigs[mode]?PhysicsCanvas:gardenConfigs[mode]?GardenCanvas:SuiteCanvas)($('#pocket-stage'),mode,{enabled,play,select,direction,bottle,hex,peg,waterProgress,settled,sand,number,mosaic});update(); +window.__pocketDebug={get game(){return game;},get scene(){return scene;},get hint(){return hint;},get selected(){return selected;},get ready(){return performance.now()>=busyUntil&&!scene?.running;}}; +window.addEventListener('pagehide',()=>{persist();scene.dispose();});window.addEventListener('pageshow',event=>{if(event.persisted)location.reload();}); diff --git a/src/suite-previews.js b/src/suite-previews.js new file mode 100644 index 0000000..dfa1655 --- /dev/null +++ b/src/suite-previews.js @@ -0,0 +1,10 @@ +import { pictureArt } from './picture-art.js'; +const littlePerson=(x,y,c)=>``; +export const passagesPreview=``; +export const voyagePreview=``; +const palette=['#88ad91','#df8c77','#80afc5','#dfba65','#aa8bb6','#d8a5bd','#efddb2','#456052']; +const picture=pictureArt(0,10); +const pig=(x,y,c)=>``; +export const carrouselPreview=``; +const embroidered=pictureArt(7,10); +export const broderiePreview=``; diff --git a/src/suite-style.css b/src/suite-style.css new file mode 100644 index 0000000..53cde92 --- /dev/null +++ b/src/suite-style.css @@ -0,0 +1,10 @@ +@import './pocket-style.css'; +.suite-options{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:7px;} +.suite-options button{padding:8px 3px;border:1px solid #d4ddce;border-radius:11px;background:#fcfcf5;display:flex;flex-direction:column;align-items:center;gap:2px;} +.suite-options small{font-size:9px;color:var(--muted);}.suite-options .color-dot{margin-bottom:3px;}.suite-options svg{height:35px;width:33px;} +.suite-tickets{display:flex;flex-wrap:wrap;gap:6px;}.suite-tickets span{padding:5px 7px;background:var(--color);border-radius:5px;font-size:9px;border:1px dashed #fff9;color:#244c42;} +.suite-bus{position:relative;background:var(--color);border:1px solid #7a927b66;border-radius:16px 20px 9px 9px;padding:16px;text-align:center;margin:22px 0 27px;color:#244c42;} +.suite-bus>span{font-size:8px;letter-spacing:1px;display:block;}.suite-bus strong{display:block;font:32px Georgia,serif;margin:10px 0 8px;background:#fff8;border-radius:8px;padding:7px;}.suite-bus small{font-size:10px;}.suite-bus i{position:absolute;bottom:-8px;left:25px;width:18px;height:18px;background:#456052;border:4px solid #84917a;border-radius:50%;}.suite-bus i:last-child{left:auto;right:25px;} +.suite-waiting{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:6px;margin:12px 0 22px;}.suite-waiting button{min-width:0;border:1px solid #d5ddcd;border-radius:10px;background:#fcfcf5;padding:6px 1px;font-size:10px;min-height:58px;}.suite-waiting svg{width:100%;height:31px;}.suite-waiting strong{display:block;font-size:11px;}.suite-waiting button:disabled{opacity:.65;}.suite-waiting button>span{font-size:18px;color:#a1b495;} +.suite-patches{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:9px;}.suite-patches>span{text-align:center;display:flex;flex-direction:column;align-items:center;}.suite-patches small{font-size:8px;color:var(--muted);}.creature-button small{display:block;font-size:8px;color:var(--muted);margin-top:5px;} +@media(max-width:580px){.suite-options{grid-template-columns:repeat(5,minmax(0,1fr));}.suite-options.spools{grid-template-columns:repeat(5,minmax(0,1fr));}.suite-waiting svg{height:39px;}.suite-patches{grid-template-columns:repeat(4,minmax(0,1fr));}.suite-bus{max-width:250px;margin:20px auto 27px;}} diff --git a/src/voyage-puzzle.js b/src/voyage-puzzle.js new file mode 100644 index 0000000..1b70997 --- /dev/null +++ b/src/voyage-puzzle.js @@ -0,0 +1,48 @@ +import { checkIndex, clone, random, shuffle } from './pocket-core.js'; +const TITLES=['Le premier départ','La salle d’attente','Un billet pour deux','Les petits groupes','Un voyage ensemble','Le quai du soleil','La correspondance','Les places du fond','La grande traversée','Tout le monde à bord','Les couleurs du soir','Le dernier départ']; +export function accessiblePassengers(level,state) { + const occupied=new Set(level.passengers.filter(p=>!state.removed.includes(p.id)).map(p=>`${p.x},${p.y}`)), walls=new Set(level.walls.map(p=>p.join(','))), reached=new Set(), queue=[]; + for(let x=0;x=level.width || yy<0 || yy>level.height || reached.has(key) || walls.has(key)) continue; + reached.add(key); if(occupied.has(key)) visible.add(key); else queue.push([xx,yy]); + } + } + return level.passengers.filter(p=>!state.removed.includes(p.id) && visible.has(`${p.x},${p.y}`)).map(p=>p.id); +} +export function createVoyageLevel(index) { + checkIndex(index); const rng=random(42871+index*8111), tier=Math.floor(index/12), width=4+Math.min(tier,2), height=4+tier+(index%3===2?1:0); + const walls=shuffle(Array.from({length:(width-2)*(height-2)},(_,i)=>[i%(width-2)+1,Math.floor(i/(width-2))+1]),rng).slice(0,tier); + const wallSet=new Set(walls.map(p=>p.join(','))), passengers=[]; + for(let y=0;yc!==previous),rng)[0], count=Math.min(2+Math.floor(rng()*(2+tier)),passengers.length-state.removed.length); + level.buses.push({color,count}); previous=color; + for(let n=0;n=0 && state.boarded({removed:[],buffer:[],bus:0,boarded:0}), + won:(level,state)=>state.removed.length===level.passengers.length && state.buffer.length===0 && state.bus===level.buses.length, + actions(level,state) { return accessiblePassengers(level,state).sort((a,b)=>Number(level.passengers[b].color===level.buses[state.bus]?.color)-Number(level.passengers[a].color===level.buses[state.bus]?.color)); }, + move(level,state,id) { + if(!Number.isInteger(id) || !accessiblePassengers(level,state).includes(id)) return null; + const next=clone(state);next.removed.push(id);next.buffer.push(id);settle(level,next);return next.buffer.length>level.bufferSize?null:next; + }, +}; diff --git a/tests/bounty.test.js b/tests/bounty.test.js new file mode 100644 index 0000000..4a9b3de --- /dev/null +++ b/tests/bounty.test.js @@ -0,0 +1,35 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {PocketGame,clone,encodePocket,decodePocket} from '../src/pocket-core.js'; +import {recolteRules,validChain,chainNeighbors} from '../src/recolte-puzzle.js'; +import {dizainesRules,numberLine,matchingNumbers} from '../src/dizaines-puzzle.js'; +import {mosaiqueRules,activePieces} from '../src/mosaique-puzzle.js'; +const modes={recolte:recolteRules,dizaines:dizainesRules,mosaique:mosaiqueRules}; +function conservation(name,game){const {level:l,state:s}=game;if(name==='recolte')for(let color=0;color<8;color++)assert.equal(s.field.filter(v=>v===color).length+s.collected[color],l.quotas[color]);if(name==='dizaines')assert.equal(s.field.filter(v=>v!==null).length+s.pairs*2,l.total);if(name==='mosaique')assert.equal(s.field.filter(v=>v!==null).length+s.cleared,l.field.filter(v=>v!==null).length+s.added);} +for(const [name,rules] of Object.entries(modes)){ + test(`${name}: all 48 distinct deterministic levels have complete routes, exact undo and conserved resources`,()=>{ + const unique=new Set();for(let i=0;i<48;i++){const g=new PocketGame(rules,i),before=clone(g.state);assert.deepEqual(g.level,rules.create(i));unique.add(JSON.stringify({...g.level,index:0,title:''}));assert.equal(g.won,false);conservation(name,g);for(const action of g.level.solution){assert.equal(g.won,false);const old=clone(g.state);assert.equal(g.play(action),true);conservation(name,g);assert.equal(g.undo(),true);assert.deepEqual(g.state,old);assert.equal(g.play(action),true);}assert.equal(g.won,true);while(g.undo()){}assert.deepEqual(g.state,before);}assert.equal(unique.size,48); + assert.ok(rules.create(47).total>rules.create(0).total); + }); + test(`${name}: saves restore exact actions, undo history and earned badges; bad moves reject`,()=>{ + const g=new PocketGame(rules,25);for(const a of g.level.solution.slice(0,3))assert.ok(g.play(a));const value=encodePocket(g,new Set([1,47]),true),read=decodePocket(rules,value);assert.deepEqual(read.game.state,g.state);assert.deepEqual(read.game.history,g.history);assert.deepEqual([...read.completed],[1,47]);assert.equal(read.sound,true);read.game.undo();g.undo();assert.deepEqual(read.game.state,g.state);assert.equal(decodePocket(rules,{...value,moves:[{invalid:true}]}),null);assert.equal(decodePocket(rules,{...value,index:48}),null); + }); + test(`${name}: hints finish every chapter boundary and remaining states`,()=>{ + for(const index of [0,11,12,23,24,35,36,47]){const g=new PocketGame(rules,index);let guard=0;while(!g.won&&guard++<100){const hint=g.hint();assert.ok(hint?.action!==undefined,`${name} ${index}`);assert.ok(g.play(hint.action));}assert.ok(g.won);} + }); +} +test('recolte: diagonal chains, minimum length, duplicate rejection, color quotas and vertical gravity',()=>{ + const l={size:3,field:[0,1,2,1,0,2,1,2,0],quotas:[3,3,3,0,0,0,0,0]},s=recolteRules.initial(l),copy=clone(s);assert.ok(chainNeighbors(l,0,4));assert.equal(chainNeighbors(l,2,3),false);assert.ok(validChain(l,s,[0,4,8]));const next=recolteRules.move(l,s,{path:[0,4,8]});assert.equal(next.collected[0],3);assert.deepEqual(next.field,[null,null,null,1,1,2,1,2,2]);for(const path of [[0,4],[0,4,0],[0,4,7],[0,8,4],[0,4,99]])assert.equal(recolteRules.move(l,s,{path}),null);assert.deepEqual(s,copy); +}); +test('dizaines: equal/ten pairs respect occupied lines, diagonal gaps and row wrapping',()=>{ + const l={cols:5,field:[1,null,1,null,7,3,4,null,6,null]},s=dizainesRules.initial(l);assert.ok(matchingNumbers(l,s,0,2));assert.ok(matchingNumbers(l,s,4,5));assert.ok(matchingNumbers(l,s,6,8));assert.equal(matchingNumbers(l,s,0,8),false);assert.equal(matchingNumbers(l,s,0,4),false);assert.equal(numberLine(l,[1,4,1,null,7,3,4,null,6,null],0,2),false);const diagonal={cols:3,field:[3,null,8,null,null,null,null,null,7]};assert.ok(matchingNumbers(diagonal,dizainesRules.initial(diagonal),0,8));assert.equal(matchingNumbers({...diagonal,field:[3,null,8,null,1,null,null,null,7]},dizainesRules.initial({...diagonal,field:[3,null,8,null,1,null,null,null,7]}),0,8),false);assert.equal(dizainesRules.move(l,s,{a:0,b:0}),null);assert.equal(dizainesRules.move(l,s,{a:-1,b:5}),null); +}); +test('mosaique: rows/columns clear simultaneously without double-counting their intersection',()=>{ + const l={size:3,field:[null,1,1,1,null,null,1,null,null],pieces:[{id:0,cells:[[0,0]],color:2}]},s=mosaiqueRules.initial(l),next=mosaiqueRules.move(l,s,{id:0,x:0,y:0});assert.equal(next.cleared,5);assert.equal(next.lines,2);assert.deepEqual(next.last.rows,[0]);assert.deepEqual(next.last.cols,[0]);assert.deepEqual(next.field,Array(9).fill(null));assert.equal(mosaiqueRules.won(l,next),true);assert.equal(mosaiqueRules.move(l,s,{id:0,x:1,y:0}),null);assert.equal(mosaiqueRules.move(l,s,{id:0,x:-1,y:0}),null);assert.equal(mosaiqueRules.move(l,s,{id:0,x:.5,y:0}),null); +}); +test('mosaique: finite trios unlock only after all three pieces; custom placement and undo remain exact',()=>{ + const g=new PocketGame(mosaiqueRules,47);assert.deepEqual(activePieces(g.level,g.state).map(p=>p.id),[0,1,2]);assert.equal(g.play({...g.level.solution[3]}),false);g.play(g.level.solution[1]);assert.deepEqual(activePieces(g.level,g.state).map(p=>p.id),[0,2]);g.play(g.level.solution[0]);g.play(g.level.solution[2]);assert.deepEqual(activePieces(g.level,g.state).map(p=>p.id),[3,4,5]);assert.ok(g.undo());assert.deepEqual(activePieces(g.level,g.state).map(p=>p.id),[2]);assert.ok(g.level.pieces.some(p=>p.cells.length===5)); +}); +test('alternate choices yield a complete verified hint route or an exact undo, never a blind suggestion',()=>{ + for(const [name,rules] of Object.entries(modes))for(const index of [0,12,24,47]){const g=new PocketGame(rules,index),initial=clone(g.state),action=rules.actions(g.level,g.state).find(a=>JSON.stringify(a)!==JSON.stringify(g.level.solution[0]));assert.ok(action,`${name} allows choices`);assert.ok(g.play(action));const hint=g.hint();assert.ok(hint);if(hint.undo){assert.ok(g.undo());assert.deepEqual(g.state,initial);}else{const plan=rules.plan(g.level,g.state);assert.ok(plan?.length);for(const a of plan)assert.ok(g.play(a));assert.ok(g.won);}} +}); diff --git a/tests/browser/bounty.spec.js b/tests/browser/bounty.spec.js new file mode 100644 index 0000000..c046270 --- /dev/null +++ b/tests/browser/bounty.spec.js @@ -0,0 +1,42 @@ +import {test,expect} from '@playwright/test'; +import {mkdir} from 'node:fs/promises'; +const modes=['recolte','dizaines','mosaique']; +async function ready(page){await page.waitForFunction(()=>window.__pocketDebug?.scene&&window.__pocketDebug.ready);} +async function hintStep(page){await ready(page);await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action!==undefined);await page.keyboard.press('Enter');} +async function pointerAction(page,mode,action,touch=false){ + const points=await page.evaluate(({mode,action})=>{const d=window.__pocketDebug;return mode==='recolte'?action.path.map(id=>d.scene.screenPoint(id)):mode==='dizaines'?[d.scene.screenPoint(action.a),d.scene.screenPoint(action.b)]:[d.scene.screenPoint({piece:action.id}),d.scene.screenPoint(action.y*d.game.level.size+action.x)];},{mode,action}); + const session=touch?await page.context().newCDPSession(page):null; + if(mode==='dizaines'){for(const p of points)if(session){await session.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[p]});await session.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});}else await page.mouse.click(p.x,p.y);} + else if(session){await session.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[points[0]]});for(const p of points.slice(1))await session.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[p]});await session.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});} + else{await page.mouse.move(points[0].x,points[0].y);await page.mouse.down();for(const p of points.slice(1))await page.mouse.move(p.x,p.y,{steps:8});await page.mouse.up();}await session?.detach(); +} +for(const mode of modes){ + test(`${mode}: real pointer play, exact save and undo, complete hints and next puzzle`,async({page})=>{ + const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(`/${mode}.html`);await ready(page);const initial=await page.evaluate(()=>window.__pocketDebug.game.state),action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]);await pointerAction(page,mode,action);await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await ready(page);const moved=await page.evaluate(()=>window.__pocketDebug.game.state);await page.reload();await ready(page);expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(moved);await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(initial); + let guard=0;while(!await page.evaluate(()=>window.__pocketDebug.game.won)&&guard++<80)await hintStep(page);await expect(page.locator('#pocket-finish')).toBeVisible();await expect(page.locator('#pocket-total')).toHaveText('1 / 48');await page.locator('#pocket-next').click();await expect(page.locator('#pocket-number')).toContainText('02 / 48');await page.reload();await ready(page);await expect(page.locator('#pocket-total')).toHaveText('1 / 48');expect(errors).toEqual([]); + }); + test(`${mode}: expert chapters, verified hints, desktop and mobile layouts`,async({page})=>{ + await mkdir('.local/screenshots',{recursive:true});const errors=[];page.on('pageerror',e=>errors.push(e.message));for(const width of [1440,390,320]){await page.setViewportSize({width,height:width===1440?1000:844});await page.goto(`/${mode}.html`);await ready(page);await page.locator('#pocket-collection').click();await expect(page.locator('#pocket-levels button')).toHaveCount(12);await page.locator('[data-chapter="3"]').click();await page.locator('[data-level="47"]').click();await ready(page);expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action!==undefined);await page.screenshot({path:`.local/screenshots/${mode}-${width}.png`,fullPage:true});await page.keyboard.press('Enter');await ready(page);await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await page.locator('#pocket-help').click();await expect(page.locator('#pocket-help-dialog')).toBeVisible();await page.getByRole('button',{name:'Fermer les règles',exact:true}).click();await page.locator('#pocket-restart').click();}expect(errors).toEqual([]); + }); + test(`${mode}: native touch gestures on mobile and exact undo`,async({browser})=>{ + const context=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true}),page=await context.newPage();await page.goto(`/${mode}.html`);await ready(page);await page.locator('#pocket-stage').scrollIntoViewIfNeeded();const action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]);await pointerAction(page,mode,action,true);await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await ready(page);await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(0);await context.close(); + }); +} +test('recolte: sidebar tracing and keyboard commit, shortened drag and invalid short chains',async({page})=>{ + await page.emulateMedia({reducedMotion:'reduce'});await page.goto('/recolte.html');await ready(page);const action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]);for(const id of action.path)await page.locator(`[data-chain="${id}"]`).click();await page.keyboard.press('Enter');expect(await page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);expect(await page.evaluate(()=>window.__pocketDebug.game.moves[0])).toEqual(action);await page.locator('#pocket-undo').click(); + await pointerAction(page,'recolte',{path:[action.path[0],action.path[1],action.path[0]]});expect(await page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(0);await expect(page.locator('#pocket-status')).toContainText('trois'); +}); +test('dizaines: selecting the same tile cancels, blocked pairs reject without changing the board',async({page})=>{ + await page.goto('/dizaines.html');await ready(page);const initial=await page.evaluate(()=>window.__pocketDebug.game.state),a=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0].a);await page.locator(`[data-number="${a}"]`).click();expect(await page.evaluate(()=>window.__pocketDebug.selected)).toBe(a);await page.locator(`[data-number="${a}"]`).click();expect(await page.evaluate(()=>window.__pocketDebug.selected)).toBe(null); + const bad=await page.evaluate(async()=>{const {matchingNumbers}=await import('/src/dizaines-puzzle.js'),g=window.__pocketDebug.game;for(let a=0;awindow.__pocketDebug.game.state)).toEqual(initial);expect(await page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(0); +}); +test('mosaique: keyboard placement, finite trios and final expert completion return to the collection',async({page})=>{ + await page.emulateMedia({reducedMotion:'reduce'});await page.goto('/mosaique.html');await ready(page);const action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]);await page.keyboard.press('1');for(let x=0;xwindow.__pocketDebug.game.moves.length)).toBe(1);expect(await page.evaluate(()=>window.__pocketDebug.scene.motion)).toBe(null);await page.locator('#pocket-collection').click();await page.locator('[data-chapter="3"]').click();await page.locator('[data-level="47"]').click();let guard=0;while(!await page.evaluate(()=>window.__pocketDebug.game.won)&&guard++<40)await hintStep(page);await expect(page.locator('#pocket-finish')).toBeVisible();await page.locator('#pocket-next').click();await expect(page.locator('#pocket-collection-dialog')).toBeVisible();await expect(page.locator('#pocket-levels button')).toHaveCount(12); +}); +test('twenty-one illustrated home cards link to the three new collections',async({page})=>{ + await mkdir('.local/screenshots',{recursive:true});for(const width of [1440,390,320]){await page.setViewportSize({width,height:1000});await page.goto('/');await expect(page.locator('.game-card')).toHaveCount(21);expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);if(width!==320)await page.screenshot({path:`.local/screenshots/twenty-one-games-${width}.png`,fullPage:true});} + for(const [mode,name] of [['recolte','Récolte'],['dizaines','Dizaines'],['mosaique','Mosaïque']]){await page.getByRole('link',{name:`Jouer à ${name}`,exact:true}).click();await ready(page);await expect(page).toHaveURL(new RegExp(`/${mode}\\.html$`));await page.getByRole('link',{name:'Les jeux',exact:true}).click();await expect(page.locator('.game-card')).toHaveCount(21);} +}); +test('mosaique: arrows adjust a hinted preview and Space places the visible origin',async({page})=>{ + await page.emulateMedia({reducedMotion:'reduce'});await page.goto('/mosaique.html');await ready(page);await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action);const action=await page.evaluate(()=>window.__pocketDebug.hint.action);await page.keyboard.press('ArrowLeft');expect(await page.evaluate(()=>window.__pocketDebug.hint)).toBe(null);expect(await page.evaluate(()=>window.__pocketDebug.scene.cursor)).toEqual({x:Math.max(0,action.x-1),y:action.y});await page.locator('#pocket-restart').click();await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action);await page.keyboard.press(' ');expect(await page.evaluate(()=>window.__pocketDebug.game.moves[0])).toEqual(action); +}); diff --git a/tests/browser/colony.spec.js b/tests/browser/colony.spec.js index 80bfc5a..2afc574 100644 --- a/tests/browser/colony.spec.js +++ b/tests/browser/colony.spec.js @@ -1,12 +1,13 @@ import { test, expect } from '@playwright/test'; import { mkdir } from 'node:fs/promises'; +import { readFileSync } from 'node:fs'; test('home cards open each game and every game returns home', async ({ page }) => { - await page.goto('/'); await expect(page.locator('.game-card')).toHaveCount(3); + await page.goto('/'); await expect(page.locator('.game-card')).toHaveCount(21); for (const [label, path, ready] of [['The cube', '/cube.html', '#remaining'], ['Picture puzzles', '/image.html', '#picture-canvas'], ['Colony', '/colony.html', '#colony-canvas']]) { await page.getByRole('link', { name: `Jouer à ${label}`, exact: true }).click(); await expect(page).toHaveURL(new RegExp(`${path.replace('.', '\\.')}$$`)); await expect(page.locator(ready)).toBeVisible(); - await page.locator('header a').first().click(); await expect(page.locator('.game-card')).toHaveCount(3); + await page.locator('header a').first().click(); await expect(page.locator('.game-card')).toHaveCount(21); } }); test('real boxes launch workers, transport cubes, pause, save and undo', async ({ page }) => { @@ -53,7 +54,7 @@ test('desktop and mobile layouts retain reachable cards, queues and controls', a await mkdir('.local/screenshots', { recursive: true }); for (const width of [1440, 390, 320]) { await page.setViewportSize({ width, height: width === 1440 ? 1000 : 844 }); - await page.goto('/'); await expect(page.locator('.game-card')).toHaveCount(3); + await page.goto('/'); await expect(page.locator('.game-card')).toHaveCount(21); expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); if (width === 1440) await page.screenshot({ path: '.local/screenshots/home-desktop.png', fullPage: true }); await page.getByRole('link', { name: 'Jouer à Colony' }).click(); await page.waitForFunction(() => Boolean(window.__colonyDebug)); @@ -67,3 +68,38 @@ test('desktop and mobile layouts retain reachable cards, queues and controls', a await page.getByRole('button', { name: 'Fermer les règles' }).click(); } }); + +test('new chapters, collection pages and an expert board remain playable on desktop and mobile', async ({ page }) => { + const errors = []; page.on('pageerror', e => errors.push(e.message)); + await mkdir('.local/screenshots', { recursive: true }); + for (const width of [1440, 390, 320]) { + await page.setViewportSize({ width, height: width === 1440 ? 1000 : 844 }); await page.goto('/colony.html'); + await page.locator('#colony-collection').click(); await page.locator('[data-chapter="72"]').click(); + await expect(page.locator('#colony-page-label')).toHaveText('73 – 84'); + if (width === 1440) await page.screenshot({ path: '.local/screenshots/colony-new-collection.png', fullPage: true }); + await page.getByRole('button', { name: 'Niveaux suivants' }).click(); await expect(page.locator('#colony-page-label')).toHaveText('85 – 96'); + await page.getByRole('button', { name: 'Niveaux précédents' }).click(); await page.locator('[data-level="72"]').click(); + await expect(page.locator('#colony-difficulty')).toContainText('Expert'); await expect(page.locator('#colony-remaining')).toHaveText('576'); + expect(await page.evaluate(() => window.__colonyDebug.game.level.width)).toBe(24); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); + await page.locator('#colony-hint').click(); await page.locator('.ant-box.hinted').click(); + await page.waitForFunction(() => window.__colonyDebug.scene.ants.size > 4); + const stats = await page.evaluate(() => ({ jobs: window.__colonyDebug.game.state.jobs.length, draws: window.__colonyDebug.scene.renderer.info.render.calls, count: window.__colonyDebug.scene.antParts[0].mesh.count })); + expect(stats.jobs).toBeGreaterThan(4); expect(stats.count).toBeGreaterThan(4); expect(stats.draws).toBeLessThan(100); + await page.screenshot({ path: `.local/screenshots/colony-expert-${width}.png`, fullPage: true }); + await page.locator('#colony-pause').click(); + } + expect(errors).toEqual([]); +}); +test('a version-one save keeps its legacy puzzle on reload and restart; a fresh puzzle uses new levels', async ({ page }) => { + const { save } = JSON.parse(readFileSync(new URL('../fixtures/colony-v1.json', import.meta.url), 'utf8')); + await page.addInitScript(value => { localStorage.setItem('cubecubecube-colony-v1', JSON.stringify(value)); }, save); + await page.goto('/colony.html'); await page.waitForFunction(() => Boolean(window.__colonyDebug)); + await expect(page.locator('#colony-difficulty')).toContainText('Classique'); + expect(await page.evaluate(() => window.__colonyDebug.game.level.generation)).toBe(1); + await page.locator('#colony-restart').click(); expect(await page.evaluate(() => window.__colonyDebug.game.level.width)).toBe(16); + await page.locator('#colony-collection').click(); await page.locator('[data-level="27"]').click(); + expect(await page.evaluate(() => window.__colonyDebug.game.level.generation)).toBe(2); + await expect(page.locator('#colony-difficulty')).toContainText('Corsé'); + await expect(page.locator('#collection-total')).toHaveText('3'); +}); diff --git a/tests/browser/garden.spec.js b/tests/browser/garden.spec.js new file mode 100644 index 0000000..f726618 --- /dev/null +++ b/tests/browser/garden.spec.js @@ -0,0 +1,56 @@ +import {test,expect} from '@playwright/test'; +import {mkdir} from 'node:fs/promises'; +const modes=['alveoles','potions','liaisons']; +async function ready(page){await page.waitForFunction(()=>window.__pocketDebug?.scene&&window.__pocketDebug.ready);} +async function hintStep(page){await ready(page);await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action!==undefined);await page.keyboard.press('Enter');} +async function pointerAction(page,mode,action,touch=false){ + if(mode==='alveoles'){ + const points=await page.evaluate(a=>[window.__pocketDebug.scene.screenPoint({q:a.q}),window.__pocketDebug.scene.screenPoint({cell:a.cell})],action); + for(const p of points){if(touch)await page.touchscreen.tap(p.x,p.y);else await page.mouse.click(p.x,p.y);} + }else if(mode==='potions'){ + const points=await page.evaluate(a=>[window.__pocketDebug.scene.screenPoint(a.from),window.__pocketDebug.scene.screenPoint(a.to)],action); + for(const p of points){if(touch)await page.touchscreen.tap(p.x,p.y);else await page.mouse.click(p.x,p.y);} + }else { + const points=await page.evaluate(a=>a.path.map(cell=>window.__pocketDebug.scene.screenPoint(cell)),action); + if(touch){ + // Native touch events exercise the same pointer capture and single-stroke undo. + const session=await page.context().newCDPSession(page);await session.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[points[0]]}); + for(const p of points.slice(1))await session.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[p]}); + await session.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});await session.detach(); + }else {await page.mouse.move(points[0].x,points[0].y);await page.mouse.down();for(const p of points.slice(1))await page.mouse.move(p.x,p.y,{steps:5});await page.mouse.up();} + } +} +for(const mode of modes){ + test(`${mode}: real pointer gameplay, exact reload, undo, verified hints, completion and next puzzle`,async({page})=>{ + const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(`/${mode}.html`);await ready(page); + const original=await page.evaluate(()=>window.__pocketDebug.game.state),action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]);await pointerAction(page,mode,action); + await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);const moved=await page.evaluate(()=>window.__pocketDebug.game.state); + await page.reload();await ready(page);expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(moved);await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(original); + await hintStep(page);await ready(page);await page.locator('#pocket-restart').click();expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(original); + let guard=0;while(!await page.evaluate(()=>window.__pocketDebug.game.won)&&guard++<80)await hintStep(page); + await expect(page.locator('#pocket-finish')).toBeVisible();await expect(page.locator('#pocket-total')).toHaveText('1 / 48');await page.locator('#pocket-next').click();await expect(page.locator('#pocket-number')).toContainText('02 / 48'); + await page.reload();await ready(page);await expect(page.locator('#pocket-total')).toHaveText('1 / 48');await expect(page.locator('#pocket-number')).toContainText('02 / 48');expect(errors).toEqual([]); + }); + test(`${mode}: 48-level collection, expert hints and responsive desktop/mobile controls`,async({page})=>{ + const errors=[];page.on('pageerror',e=>errors.push(e.message));await mkdir('.local/screenshots',{recursive:true}); + for(const width of [1440,390,320]){ + await page.setViewportSize({width,height:width===1440?1000:844});await page.goto(`/${mode}.html`);await ready(page);await page.locator('#pocket-collection').click();await expect(page.locator('#pocket-levels button')).toHaveCount(12);await page.locator('[data-chapter="3"]').click();await page.locator('[data-level="47"]').click();await ready(page); + expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action!==undefined);await page.screenshot({path:`.local/screenshots/${mode}-${width}.png`,fullPage:true}); + await page.keyboard.press('Enter');await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await ready(page);await page.locator('#pocket-help').click();await expect(page.locator('#pocket-help-dialog')).toBeVisible();await page.getByRole('button',{name:'Fermer les règles',exact:true}).click();await page.locator('#pocket-restart').click(); + }expect(errors).toEqual([]); + }); + test(`${mode}: real touch play on a small screen`,async({browser})=>{ + const context=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true}),page=await context.newPage();await page.goto(`/${mode}.html`);await ready(page);await page.locator('#pocket-stage').scrollIntoViewIfNeeded();const action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]);await pointerAction(page,mode,action,true);await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await page.locator('#pocket-undo').click();await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(0);await context.close(); + }); +} +test('liaisons: keyboard connects endpoints and a partial drag is exactly one undoable stroke',async({page})=>{ + await page.goto('/liaisons.html');await ready(page);const action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]); + await page.locator(`[data-select="${action.color}"]`).click();const size=await page.evaluate(()=>window.__pocketDebug.game.level.size); + for(let i=1;iwindow.__pocketDebug.game.state.paths[color],action.color)).toEqual(action.path);await page.locator('#pocket-restart').click(); + await pointerAction(page,'liaisons',{...action,path:action.path.slice(0,3)});await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await hintStep(page);expect(await page.evaluate(()=>window.__pocketDebug.game.state.paths[0])).toEqual([]);await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.game.state.paths[0])).toEqual(action.path.slice(0,3)); +}); +test('twenty-one illustrated home games include Alvéoles, Potions and Liaisons',async({page})=>{ + await mkdir('.local/screenshots',{recursive:true});for(const width of [1440,390,320]){await page.setViewportSize({width,height:1000});await page.goto('/');await expect(page.locator('.game-card')).toHaveCount(21);expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);if(width!==320)await page.screenshot({path:`.local/screenshots/thirteen-games-${width}.png`,fullPage:true});} + for(const [mode,name]of [['alveoles','Alvéoles'],['potions','Potions'],['liaisons','Liaisons']]){await page.getByRole('link',{name:`Jouer à ${name}`,exact:true}).click();await ready(page);await expect(page).toHaveURL(new RegExp(`/${mode}\\.html$`));await page.getByRole('link',{name:'Les jeux',exact:true}).click();await expect(page.locator('.game-card')).toHaveCount(21);} +}); diff --git a/tests/browser/harvest.spec.js b/tests/browser/harvest.spec.js new file mode 100644 index 0000000..ca59a5a --- /dev/null +++ b/tests/browser/harvest.spec.js @@ -0,0 +1,43 @@ +import {test,expect} from '@playwright/test'; +import {mkdir} from 'node:fs/promises'; +const modes=['ecluses','dunes','fringale']; +async function ready(page){await page.waitForFunction(()=>window.__pocketDebug?.scene&&window.__pocketDebug.ready);} +async function hintStep(page){await ready(page);await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action!==undefined);await page.keyboard.press('Enter');} +async function pointerAction(page,mode,action,touch=false){ + const points=await page.evaluate(({mode,action})=>{const d=window.__pocketDebug;return mode==='ecluses'?[d.scene.screenPoint(action)]:mode==='dunes'?[d.scene.screenPoint({q:action.q}),d.scene.screenPoint(action)]:[d.scene.screenPoint(d.game.state.hole),d.scene.screenPoint(action.id)];},{mode,action}); + const session=touch?await page.context().newCDPSession(page):null; + const tap=async p=>{if(session){await session.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[p]});await session.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});}else await page.mouse.click(p.x,p.y);}; + if(mode!=='fringale')for(const p of points)await tap(p); + else if(session){await session.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[points[0]]});for(let n=1;n<=12;n++)await session.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:points[0].x+(points[1].x-points[0].x)*n/12,y:points[0].y+(points[1].y-points[0].y)*n/12}]});await session.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});} + else{await page.mouse.move(points[0].x,points[0].y);await page.mouse.down();await page.mouse.move(points[1].x,points[1].y,{steps:12});await page.mouse.up();} + await session?.detach(); +} +for(const mode of modes){ + test(`${mode}: real pointer play, exact reload and undo, complete hints and next puzzle`,async({page})=>{ + const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(`/${mode}.html`);await ready(page);const initial=await page.evaluate(()=>window.__pocketDebug.game.state),action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]); + await pointerAction(page,mode,action);await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await ready(page);const moved=await page.evaluate(()=>window.__pocketDebug.game.state);if(mode==='fringale')expect(moved.collected.length).toBeGreaterThan(0); + await page.reload();await ready(page);expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(moved);await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(initial); + let guard=0;while(!await page.evaluate(()=>window.__pocketDebug.game.won)&&guard++<80)await hintStep(page);await expect(page.locator('#pocket-finish')).toBeVisible({timeout:10000});await expect(page.locator('#pocket-total')).toHaveText('1 / 48');await page.locator('#pocket-next').click();await expect(page.locator('#pocket-number')).toContainText('02 / 48');await page.reload();await ready(page);await expect(page.locator('#pocket-total')).toHaveText('1 / 48');expect(errors).toEqual([]); + }); + test(`${mode}: expert chapters, verified hints and desktop/mobile layouts`,async({page})=>{ + await mkdir('.local/screenshots',{recursive:true});const errors=[];page.on('pageerror',e=>errors.push(e.message)); + for(const width of [1440,390,320]){await page.setViewportSize({width,height:width===1440?1000:844});await page.goto(`/${mode}.html`);await ready(page);await page.locator('#pocket-collection').click();await expect(page.locator('#pocket-levels button')).toHaveCount(12);await page.locator('[data-chapter="3"]').click();await page.locator('[data-level="47"]').click();await ready(page);expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action!==undefined);await page.screenshot({path:`.local/screenshots/${mode}-${width}.png`,fullPage:true});await page.keyboard.press('Enter');await ready(page);await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await page.locator('#pocket-help').click();await expect(page.locator('#pocket-help-dialog')).toBeVisible();await page.getByRole('button',{name:'Fermer les règles',exact:true}).click();await page.locator('#pocket-restart').click();}expect(errors).toEqual([]); + }); + test(`${mode}: native touch play and undo on mobile`,async({browser})=>{ + const context=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true}),page=await context.newPage();await page.goto(`/${mode}.html`);await ready(page);await page.locator('#pocket-stage').scrollIntoViewIfNeeded();const action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]);await pointerAction(page,mode,action,true);await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await ready(page);if(mode==='fringale')expect(await page.evaluate(()=>window.__pocketDebug.game.state.collected.length)).toBeGreaterThan(0);await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(0);await context.close(); + }); +} +test('ecluses: a wrong outlet loses grey balls and undo recovers the entire board',async({page})=>{ + await page.goto('/ecluses.html');await ready(page);const initial=await page.evaluate(()=>window.__pocketDebug.game.state),pins=await page.evaluate(()=>window.__pocketDebug.game.level.solution);await page.locator(`[data-gate="${pins[0]}"]`).click();await ready(page);await page.locator(`[data-gate="${pins[2]}"]`).click();await ready(page);await expect(page.locator('#pocket-status')).toContainText('perdues');await expect(page.locator('#pocket-finish')).not.toBeVisible();await page.locator('#pocket-undo').click();await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(initial); +}); +test('dunes: animated grains lock extra drops, undo cancels gravity, keyboard works with reduced motion',async({page})=>{ + await page.goto('/dunes.html');await ready(page);const initial=await page.evaluate(()=>window.__pocketDebug.game.state);await hintStep(page);await page.waitForFunction(()=>window.__pocketDebug.scene.running);await page.keyboard.press(' ');expect(await page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.scene.running)).toBe(false);expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(initial); + await page.emulateMedia({reducedMotion:'reduce'});await page.reload();await ready(page);const action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]);await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action);await page.keyboard.press(' ');expect(await page.evaluate(()=>window.__pocketDebug.game.moves[0])).toEqual(action);await page.locator('#pocket-undo').click();await page.keyboard.press(String(action.q+1));await page.keyboard.press('ArrowLeft');await page.keyboard.press(' ');expect(await page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);expect(await page.evaluate(()=>window.__pocketDebug.scene.running)).toBe(false); +}); +test('fringale: keyboard motion, inaccessible large objects, growth and exact undo',async({page})=>{ + await page.emulateMedia({reducedMotion:'reduce'});await page.goto('/fringale.html');await ready(page);const initial=await page.evaluate(()=>window.__pocketDebug.game.state);await expect(page.locator('[data-food]:disabled').first()).toBeVisible();await page.keyboard.press('ArrowLeft');expect(await page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(initial);await hintStep(page);expect(await page.evaluate(()=>window.__pocketDebug.game.state.mass)).toBeGreaterThan(0);await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(initial); +}); +test('twenty-one illustrated home games link to the three new collections',async({page})=>{ + await mkdir('.local/screenshots',{recursive:true});await page.goto('/');await expect(page.locator('.game-card')).toHaveCount(21);await page.screenshot({path:'.local/screenshots/eighteen-games.png',fullPage:true}); + for(const [mode,name] of [['ecluses','Écluses'],['dunes','Dunes'],['fringale','Fringale']]){await page.getByRole('link',{name:`Jouer à ${name}`,exact:true}).click();await ready(page);await expect(page).toHaveURL(new RegExp(`/${mode}\\.html$`));await page.getByRole('link',{name:'Les jeux',exact:true}).click();await expect(page.locator('.game-card')).toHaveCount(21);} +}); diff --git a/tests/browser/physics.spec.js b/tests/browser/physics.spec.js new file mode 100644 index 0000000..58fc6c7 --- /dev/null +++ b/tests/browser/physics.spec.js @@ -0,0 +1,38 @@ +import {test,expect} from '@playwright/test'; +import {mkdir} from 'node:fs/promises'; +const modes=['noeuds','gouttes']; +async function ready(page){await page.waitForFunction(()=>window.__pocketDebug?.scene&&window.__pocketDebug.ready);} +async function hintStep(page){await ready(page);await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action);await page.keyboard.press('Enter');} +async function pointerAction(page,mode,action,touch=false){ + const points=await page.evaluate(({mode,action})=>mode==='noeuds'?[window.__pocketDebug.scene.screenPoint({pin:action.pin}),window.__pocketDebug.scene.screenPoint({peg:action.peg})]:action.path.map(p=>window.__pocketDebug.scene.screenPoint(p)),{mode,action}); + if(touch){const session=await page.context().newCDPSession(page);await session.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[points[0]]});for(const p of points.slice(1))await session.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[p]});await session.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});await session.detach();} + else{await page.mouse.move(points[0].x,points[0].y);await page.mouse.down();for(const p of points.slice(1))await page.mouse.move(p.x,p.y,{steps:12});await page.mouse.up();} +} +for(const mode of modes){ + test(`${mode}: real dragging, exact save reload, undo, hints, completed game and next puzzle`,async({page})=>{ + const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(`/${mode}.html`);await ready(page);const initial=await page.evaluate(()=>window.__pocketDebug.game.state),action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]); + await pointerAction(page,mode,action);await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);const moved=await page.evaluate(()=>window.__pocketDebug.game.state);await page.reload();await ready(page);expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(moved);await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(initial); + let guard=0;while(!await page.evaluate(()=>window.__pocketDebug.game.won)&&guard++<40)await hintStep(page);await expect(page.locator('#pocket-finish')).toBeVisible({timeout:10000});await expect(page.locator('#pocket-total')).toHaveText('1 / 48');await page.locator('#pocket-next').click();await expect(page.locator('#pocket-number')).toContainText('02 / 48');await page.reload();await ready(page);await expect(page.locator('#pocket-total')).toHaveText('1 / 48');expect(errors).toEqual([]); + }); + test(`${mode}: expert collection, verified hints, desktop and small-screen layouts`,async({page})=>{ + await mkdir('.local/screenshots',{recursive:true});const errors=[];page.on('pageerror',e=>errors.push(e.message)); + for(const width of [1440,390,320]){await page.setViewportSize({width,height:width===1440?1000:844});await page.goto(`/${mode}.html`);await ready(page);await page.locator('#pocket-collection').click();await expect(page.locator('#pocket-levels button')).toHaveCount(12);await page.locator('[data-chapter="3"]').click();await page.locator('[data-level="47"]').click();await ready(page);expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action);await page.screenshot({path:`.local/screenshots/${mode}-${width}.png`,fullPage:true});await page.keyboard.press('Enter');await ready(page);await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await page.locator('#pocket-help').click();await expect(page.locator('#pocket-help-dialog')).toBeVisible();await page.getByRole('button',{name:'Fermer les règles',exact:true}).click();await page.locator('#pocket-restart').click();}expect(errors).toEqual([]); + }); + test(`${mode}: native touch dragging on mobile`,async({browser})=>{ + const context=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true}),page=await context.newPage();await page.goto(`/${mode}.html`);await ready(page);await page.locator('#pocket-stage').scrollIntoViewIfNeeded();const action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]);await pointerAction(page,mode,action,true);await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await page.locator('#pocket-undo').click();await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(0);await context.close(); + }); +} +test('gouttes: failed water, direct hand-drawn victory, live animation and exact undo cancellation',async({page})=>{ + await page.goto('/gouttes.html');await ready(page);await page.getByRole('button',{name:/Laisser couler/}).click();await page.waitForFunction(()=>window.__pocketDebug.scene.running);await ready(page);await expect(page.locator('#pocket-status')).toContainText('ajustez');expect(await page.evaluate(()=>window.__pocketDebug.game.won)).toBe(false); + await page.reload();await ready(page);expect(await page.evaluate(()=>window.__pocketDebug.game.state.result.caught)).toBe(0);await page.locator('#pocket-restart').click();const action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]);await pointerAction(page,'gouttes',action);await page.keyboard.press('e');await page.waitForFunction(()=>window.__pocketDebug.scene.running);await page.waitForFunction(()=>window.__pocketDebug.scene.water.particles.length>5);await page.locator('#pocket-stage').screenshot({path:'.local/screenshots/gouttes-playing.png'}); + await expect(page.locator('#pocket-finish')).not.toBeVisible();await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.scene.running)).toBe(false);expect(await page.evaluate(()=>window.__pocketDebug.game.state.result)).toBe(null);await page.waitForTimeout(300);await expect(page.locator('#pocket-finish')).not.toBeVisible();await page.keyboard.press('e');await expect(page.locator('#pocket-finish')).toBeVisible({timeout:10000}); +}); +test('gouttes: accessible point drawing and an expert two-ramp stream work with reduced motion',async({page})=>{ + await page.emulateMedia({reducedMotion:'reduce'});await page.goto('/gouttes.html');await ready(page);await page.locator('#pocket-collection').click();await page.locator('[data-chapter="3"]').click();await page.locator('[data-level="47"]').click();await ready(page);const actions=await page.evaluate(()=>window.__pocketDebug.game.level.solution.filter(a=>a.type==='draw')); + for(const action of actions){await page.locator('.physics-assisted summary').click();for(const [x,y] of action.path){await page.locator('#water-x').fill(String(x));await page.locator('#water-y').fill(String(y));await page.locator('[data-water-point]').click();}await page.locator('[data-water-place]').click();} + await page.getByRole('button',{name:/Laisser couler/}).click();await expect(page.locator('#pocket-finish')).toBeVisible();expect(await page.evaluate(()=>window.__pocketDebug.game.state.result.caught)).toBe(60);expect(await page.evaluate(()=>window.__pocketDebug.scene.running)).toBe(false); +}); +test('twenty-one illustrated home games open Nœuds and Gouttes and return home',async({page})=>{ + await mkdir('.local/screenshots',{recursive:true});for(const width of [1440,390,320]){await page.setViewportSize({width,height:1000});await page.goto('/');await expect(page.locator('.game-card')).toHaveCount(21);expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);if(width!==320)await page.screenshot({path:`.local/screenshots/fifteen-games-${width}.png`,fullPage:true});} + for(const [mode,name] of [['noeuds','Nœuds'],['gouttes','Gouttes']]){await page.getByRole('link',{name:`Jouer à ${name}`,exact:true}).click();await ready(page);await expect(page).toHaveURL(new RegExp(`/${mode}\\.html$`));await page.getByRole('link',{name:'Les jeux',exact:true}).click();await expect(page.locator('.game-card')).toHaveCount(21);} +}); diff --git a/tests/browser/pocket.spec.js b/tests/browser/pocket.spec.js new file mode 100644 index 0000000..61e5c2a --- /dev/null +++ b/tests/browser/pocket.spec.js @@ -0,0 +1,69 @@ +import { test, expect } from '@playwright/test'; +import { mkdir } from 'node:fs/promises'; + +const modes = ['atelier', 'bobines', 'escapade']; +async function ready(page) { await page.waitForFunction(() => window.__pocketDebug?.scene && window.__pocketDebug.ready); } +async function hintStep(page) { + await ready(page); await page.locator('#pocket-hint').click(); + await page.waitForFunction(() => window.__pocketDebug.hint?.action !== undefined); + await page.keyboard.press('Enter'); +} +for (const mode of modes) { + test(`${mode}: real input, hint, exact reload, undo, restart and completed puzzle`, async ({ page }) => { + const errors = []; page.on('pageerror', e => errors.push(e.message)); + await page.goto(`/${mode}.html`); await ready(page); + const initial = await page.evaluate(() => window.__pocketDebug.game.state); + const action = await page.evaluate(() => window.__pocketDebug.game.level.solution[0]); + if (mode === 'atelier') { + const point = await page.evaluate(id => window.__pocketDebug.scene.screenPoint(id), action); + await page.mouse.click(point.x, point.y); + } else if (mode === 'bobines') await page.locator(`.bobbin-button.ready[data-queue="${action}"]`).click(); + else { + const from = await page.evaluate(a => window.__pocketDebug.scene.screenPoint(window.__pocketDebug.game.state.snakes.find(s => s.id === a.id).cells[0]), action); + const to = await page.evaluate(a => window.__pocketDebug.scene.screenPoint(a.to), action); + await page.mouse.move(from.x, from.y); await page.mouse.down(); await page.mouse.move(to.x, to.y, { steps:6 }); await page.mouse.up(); + } + await expect.poll(() => page.evaluate(() => window.__pocketDebug.game.moves.length)).toBe(1); + const moved = await page.evaluate(() => window.__pocketDebug.game.state); + await page.reload(); await ready(page); expect(await page.evaluate(() => window.__pocketDebug.game.state)).toEqual(moved); + await page.locator('#pocket-undo').click(); expect(await page.evaluate(() => window.__pocketDebug.game.state)).toEqual(initial); + await hintStep(page); await ready(page); await page.locator('#pocket-restart').click(); expect(await page.evaluate(() => window.__pocketDebug.game.state)).toEqual(initial); + let guard = 0; + while (!await page.evaluate(() => window.__pocketDebug.game.won) && guard++ < 70) await hintStep(page); + await expect(page.locator('#pocket-finish')).toBeVisible(); await expect(page.locator('#pocket-total')).toHaveText('1 / 48'); + await page.locator('#pocket-next').click(); await expect(page.locator('#pocket-number')).toContainText('PUZZLE 02 / 48'); + await page.reload(); await ready(page); await expect(page.locator('#pocket-number')).toContainText('PUZZLE 02 / 48'); + await expect(page.locator('#pocket-total')).toHaveText('1 / 48'); expect(errors).toEqual([]); + }); + test(`${mode}: all chapters, last level, mobile controls and no overflow`, async ({ page }) => { + const errors = []; page.on('pageerror', e => errors.push(e.message)); await mkdir('.local/screenshots', { recursive:true }); + for (const width of [1440, 390, 320]) { + await page.setViewportSize({ width, height:width === 1440 ? 1000 : 844 }); + await page.goto(`/${mode}.html`); await ready(page); + await page.locator('#pocket-collection').click(); await expect(page.locator('#pocket-levels button')).toHaveCount(12); + await page.locator('[data-chapter="3"]').click(); await page.locator('[data-level="47"]').click(); await ready(page); + await expect(page.locator('#pocket-number')).toContainText('48 / 48'); await expect(page.locator('#pocket-difficulty')).toHaveText('Les grands détours'); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); + await page.locator('#pocket-hint').click(); await page.waitForFunction(() => window.__pocketDebug.hint?.action !== undefined); + await page.screenshot({ path:`.local/screenshots/${mode}-${width}.png`, fullPage:true }); + await page.keyboard.press('Enter'); await expect.poll(() => page.evaluate(() => window.__pocketDebug.game.moves.length)).toBe(1); + await page.locator('#pocket-help').click(); await expect(page.locator('#pocket-help-dialog')).toBeVisible(); + await page.getByRole('button', { name:'Fermer les règles', exact:true }).click(); + await page.locator('#pocket-restart').click(); + } + expect(errors).toEqual([]); + }); +} +test('ten illustrated home cards link to the new games and each returns home', async ({ page }) => { + await mkdir('.local/screenshots', { recursive:true }); + for (const width of [1440, 390, 320]) { + await page.setViewportSize({ width, height:1000 }); await page.goto('/'); await expect(page.locator('.game-card')).toHaveCount(21); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); + if (width !== 320) await page.screenshot({ path:`.local/screenshots/six-games-${width}.png`, fullPage:true }); + } + for (const [name, mode] of [['Atelier', 'atelier'], ['Bobines', 'bobines'], ['Escapade', 'escapade']]) { + await page.getByRole('link', { name:`Jouer à ${name}`, exact:true }).click(); await ready(page); + await expect(page).toHaveURL(new RegExp(`/${mode}\\.html$`)); + await page.getByRole('link', { name:'Les jeux', exact:true }).click(); await expect(page.locator('.game-card')).toHaveCount(21); + } +}); diff --git a/tests/browser/suite.spec.js b/tests/browser/suite.spec.js new file mode 100644 index 0000000..fe16264 --- /dev/null +++ b/tests/browser/suite.spec.js @@ -0,0 +1,37 @@ +import {test,expect} from '@playwright/test'; +import {mkdir} from 'node:fs/promises'; +const modes=['passages','voyage','carrousel','broderie']; +async function ready(page){await page.waitForFunction(()=>window.__pocketDebug?.scene&&window.__pocketDebug.ready);} +async function step(page){await ready(page);await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action!==undefined);await page.keyboard.press('Enter');} +for(const mode of modes){ + test(`${mode}: real pointer play, exact reload, undo, hints, completed puzzle and next level`,async({page})=>{ + const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(`/${mode}.html`);await ready(page); + const original=await page.evaluate(()=>window.__pocketDebug.game.state),action=await page.evaluate(()=>window.__pocketDebug.game.level.solution[0]); + if(mode==='passages'){ + const points=await page.evaluate(a=>{const b=window.__pocketDebug.game.state.blocks.find(b=>b.id===a.id);return[window.__pocketDebug.scene.screenPoint([b.x,b.y]),window.__pocketDebug.scene.screenPoint([b.x+a.dx,b.y+a.dy])];},action); + await page.mouse.move(points[0].x,points[0].y);await page.mouse.down();await page.mouse.move(points[1].x,points[1].y,{steps:8});await page.mouse.up(); + }else if(mode==='carrousel')await page.locator(`.ready[data-queue="${action.q}"]`).click(); + else{const point=await page.evaluate(a=>window.__pocketDebug.scene.screenPoint(a),action);await page.mouse.click(point.x,point.y);} + await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);const moved=await page.evaluate(()=>window.__pocketDebug.game.state); + await page.reload();await ready(page);expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(moved); + await page.locator('#pocket-undo').click();expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(original); + await step(page);await ready(page);await page.locator('#pocket-restart').click();expect(await page.evaluate(()=>window.__pocketDebug.game.state)).toEqual(original); + let guard=0;while(!await page.evaluate(()=>window.__pocketDebug.game.won)&&guard++<100)await step(page); + await expect(page.locator('#pocket-finish')).toBeVisible();await expect(page.locator('#pocket-total')).toHaveText('1 / 48');await page.locator('#pocket-next').click();await expect(page.locator('#pocket-number')).toContainText('PUZZLE 02 / 48'); + await page.reload();await ready(page);await expect(page.locator('#pocket-number')).toContainText('PUZZLE 02 / 48');await expect(page.locator('#pocket-total')).toHaveText('1 / 48');expect(errors).toEqual([]); + }); + test(`${mode}: chapter collection, expert hint and reachable mobile controls`,async({page})=>{ + const errors=[];page.on('pageerror',e=>errors.push(e.message));await mkdir('.local/screenshots',{recursive:true}); + for(const width of [1440,390,320]){ + await page.setViewportSize({width,height:width===1440?1000:844});await page.goto(`/${mode}.html`);await ready(page);await page.locator('#pocket-collection').click();await expect(page.locator('#pocket-levels button')).toHaveCount(12);await page.locator('[data-chapter="3"]').click();await page.locator('[data-level="47"]').click();await ready(page);await expect(page.locator('#pocket-number')).toContainText('48 / 48'); + expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);await page.locator('#pocket-hint').click();await page.waitForFunction(()=>window.__pocketDebug.hint?.action!==undefined); + await page.screenshot({path:`.local/screenshots/${mode}-${width}.png`,fullPage:true});await page.keyboard.press('Enter');await expect.poll(()=>page.evaluate(()=>window.__pocketDebug.game.moves.length)).toBe(1);await ready(page); + await page.locator('#pocket-help').click();await expect(page.locator('#pocket-help-dialog')).toBeVisible();await page.getByRole('button',{name:'Fermer les règles',exact:true}).click();await page.locator('#pocket-restart').click(); + }expect(errors).toEqual([]); + }); +} +test('twenty-one home illustrations open the four additional games and return to the collection',async({page})=>{ + await mkdir('.local/screenshots',{recursive:true}); + for(const width of [1440,390,320]){await page.setViewportSize({width,height:1000});await page.goto('/');await expect(page.locator('.game-card')).toHaveCount(21);expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);if(width!==320)await page.screenshot({path:`.local/screenshots/ten-games-${width}.png`,fullPage:true});} + for(const [name,mode]of [['Passages','passages'],['Voyage','voyage'],['Carrousel','carrousel'],['Broderie','broderie']]){await page.getByRole('link',{name:`Jouer à ${name}`,exact:true}).click();await ready(page);await expect(page).toHaveURL(new RegExp(`/${mode}\\.html$`));await page.getByRole('link',{name:'Les jeux',exact:true}).click();await expect(page.locator('.game-card')).toHaveCount(21);} +}); diff --git a/tests/colony.test.js b/tests/colony.test.js index 51a5e44..d2616a8 100644 --- a/tests/colony.test.js +++ b/tests/colony.test.js @@ -1,6 +1,9 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { createColonyLevel, ColonyGame, reachable, outsidePaths, COLORS, encodeColonySave, decodeColonySave } from '../src/colony-puzzle.js'; +import { readFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { NEW_COLONY_ART, ART_COLORS } from '../src/colony-art.js'; +import { createColonyLevel, createLegacyColonyLevel, ColonyGame, reachable, outsidePaths, COLORS, MOTIFS, colonyDifficulty, encodeColonySave, decodeColonySave } from '../src/colony-puzzle.js'; test('all motifs and later tiers conserve every color and have complete five-slot solutions', () => { for (const index of [0, 1, 2, 3, 4, 5, 6, 17, 39, 99, 999999]) { @@ -57,3 +60,69 @@ test('hints can finish every opening board from its current state', () => { assert.ok(game.won); } }); +test('every available matching block gets a worker, without a four-worker cap', () => { + const level = { width: 8, height: 4, cells: Array(32).fill('coral'), queues: [[{ id: 0, color: 'coral', count: 32 }], [], [], []] }; + const game = new ColonyGame(level); game.launch(0); game.advance(0); + assert.equal(game.state.jobs.length, 20, 'all perimeter cubes are reserved immediately'); + assert.equal(new Set(game.state.jobs.map(j => j.cell)).size, 20); + game.advance(100); assert.equal(game.state.jobs.length, 12, 'newly exposed cubes get workers in the same update'); + game.advance(100); assert.ok(game.won); +}); + +test('the first 96 puzzles have original pictures and verified solutions with conserved quotas', () => { + assert.equal(MOTIFS.length, 24); assert.equal(new Set(MOTIFS).size, 24); + for (const art of NEW_COLONY_ART) { + assert.equal(art.rows.length, 16); + for (const row of art.rows) { assert.equal(row.length, 16); assert.ok([...row].every(c => c === '.' || ART_COLORS[c])); } + } + const pictures = new Set(); + for (let index = 0; index < 96; index++) { + const level = createColonyLevel(index), game = new ColonyGame(level); + if (index < 24) pictures.add(level.cells.join(',')); + for (const color of Object.keys(COLORS)) assert.equal(level.cells.filter(c => c === color).length, level.queues.flat().filter(b => b.color === color).reduce((n, b) => n + b.count, 0)); + for (const q of level.solution) { assert.ok(game.launch(q), `launch ${index}`); game.settle(); } + assert.ok(game.won, `complete ${index}`); + } + assert.equal(pictures.size, 24); +}); +test('difficulty grows through board size, overlapping waiting boxes and more colours', () => { + assert.equal(createColonyLevel(0).width, 16); assert.equal(createColonyLevel(6).width, 20); + assert.equal(createColonyLevel(48).width, 22); assert.equal(createColonyLevel(72).width, 24); + assert.deepEqual([0, 6, 24, 48, 72].map(i => colonyDifficulty(i).name), ['Découverte', 'Malin', 'Corsé', 'Difficile', 'Expert']); + for (const index of [72, 80, 99, 144]) { + const level = createColonyLevel(index); assert.ok(level.pressure.maxOccupied >= 4); assert.ok(level.pressure.waitingMoves >= 3); assert.ok(level.pressure.colors >= 6); + } + const a = createColonyLevel(144), b = createColonyLevel(168); + assert.notDeepEqual(a.queues, b.queues, 'later journeys vary their reserve instead of repeating it'); +}); +test('old saves retain their exact board, ongoing workers, history and earned completions', () => { + const { save, fingerprint } = JSON.parse(readFileSync(new URL('./fixtures/colony-v1.json', import.meta.url), 'utf8')); + const restored = decodeColonySave(save); assert.ok(restored); + assert.equal(createHash('sha256').update(JSON.stringify({ cells: restored.game.level.cells, queues: restored.game.level.queues })).digest('hex'), fingerprint); + assert.deepEqual(restored.game.state, save.state); assert.deepEqual(restored.game.history, save.history); + assert.deepEqual(restored.completed, [0, 3, 20]); assert.equal(restored.speed, 2); assert.equal(restored.game.level.generation, 1); + const migrated = encodeColonySave(restored.game, restored.completed, restored.speed); + assert.equal(migrated.version, 2); assert.equal(migrated.generation, 1); assert.deepEqual(decodeColonySave(migrated).game.state, save.state); + assert.notDeepEqual(createColonyLevel(save.index).cells, restored.game.level.cells); +}); +test('legacy puzzles remain solvable with unrestricted workers using state-aware hints', () => { + for (const index of [0, 1, 2, 3, 4, 5, 27, 80]) { + const game = new ColonyGame(createLegacyColonyLevel(index)); + for (let step = 0; step < 80 && !game.won; step++) { + const hint = game.hint(); assert.equal(hint.type, 'box', `legacy hint ${index}`); game.launch(hint.queue); game.settle(); + } + assert.ok(game.won, `legacy ${index}`); + } +}); +test('larger-board saves preserve return trips and hints handle pending teams', () => { + for (const index of [6, 24, 48, 72, 80]) { + const game = new ColonyGame(createColonyLevel(index)); + for (const q of game.level.solution) { + const hint = game.hint(); assert.ok(['box', 'wait'].includes(hint.type)); + assert.ok(game.launch(q)); game.advance(0); game.advance(.9); + const restored = decodeColonySave(encodeColonySave(game)); assert.ok(restored, `save ${index}`); + assert.deepEqual(restored.game.state, game.state); game.settle(); + } + assert.ok(game.won); + } +}); diff --git a/tests/fixtures/colony-v1.json b/tests/fixtures/colony-v1.json new file mode 100644 index 0000000..ba463f4 --- /dev/null +++ b/tests/fixtures/colony-v1.json @@ -0,0 +1,735 @@ +{ + "save": { + "version": 1, + "index": 27, + "state": { + "remaining": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 107, + 108, + 109, + 110, + 111, + 112, + 113, + 114, + 115, + 116, + 117, + 118, + 119, + 120, + 121, + 122, + 123, + 124, + 125, + 126, + 127, + 128, + 129, + 130, + 131, + 132, + 133, + 134, + 135, + 136, + 137, + 138, + 139, + 140, + 141, + 142, + 143, + 144, + 145, + 146, + 147, + 148, + 149, + 150, + 151, + 152, + 153, + 154, + 155, + 156, + 157, + 158, + 159, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 174, + 175, + 176, + 177, + 178, + 179, + 180, + 181, + 182, + 183, + 184, + 185, + 186, + 187, + 188, + 189, + 190, + 191, + 192, + 193, + 194, + 195, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 210, + 211, + 212, + 213, + 214, + 215, + 216, + 217, + 218, + 219, + 220, + 221, + 222, + 223, + 224, + 225, + 226, + 227, + 228, + 229, + 230, + 231, + 232, + 233, + 234, + 235, + 236, + 237, + 238, + 239, + 240, + 241, + 242, + 243, + 244, + 245, + 246, + 247, + 248, + 249, + 250, + 251 + ], + "cursors": [ + 1, + 0, + 0, + 0 + ], + "slots": [ + { + "id": 0, + "color": "ink", + "count": 24, + "remaining": 24 + }, + null, + null, + null, + null + ], + "jobs": [ + { + "id": 1, + "slot": 0, + "cell": 255, + "color": "ink", + "route": [ + [ + 8, + 16 + ], + [ + 9, + 16 + ], + [ + 10, + 16 + ], + [ + 11, + 16 + ], + [ + 12, + 16 + ], + [ + 13, + 16 + ], + [ + 14, + 16 + ], + [ + 15, + 16 + ], + [ + 15, + 15 + ] + ], + "elapsed": 1, + "duration": 1.555, + "picked": true + }, + { + "id": 2, + "slot": 0, + "cell": 254, + "color": "ink", + "route": [ + [ + 8, + 16 + ], + [ + 9, + 16 + ], + [ + 10, + 16 + ], + [ + 11, + 16 + ], + [ + 12, + 16 + ], + [ + 13, + 16 + ], + [ + 14, + 16 + ], + [ + 14, + 15 + ] + ], + "elapsed": 1, + "duration": 1.5099999999999998, + "picked": true + }, + { + "id": 3, + "slot": 0, + "cell": 253, + "color": "ink", + "route": [ + [ + 8, + 16 + ], + [ + 9, + 16 + ], + [ + 10, + 16 + ], + [ + 11, + 16 + ], + [ + 12, + 16 + ], + [ + 13, + 16 + ], + [ + 13, + 15 + ] + ], + "elapsed": 1, + "duration": 1.4649999999999999, + "picked": true + }, + { + "id": 4, + "slot": 0, + "cell": 252, + "color": "ink", + "route": [ + [ + 8, + 16 + ], + [ + 9, + 16 + ], + [ + 10, + 16 + ], + [ + 11, + 16 + ], + [ + 12, + 16 + ], + [ + 12, + 15 + ] + ], + "elapsed": 1, + "duration": 1.42, + "picked": true + } + ], + "serial": 4, + "launched": [ + 0 + ] + }, + "history": [ + { + "remaining": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 107, + 108, + 109, + 110, + 111, + 112, + 113, + 114, + 115, + 116, + 117, + 118, + 119, + 120, + 121, + 122, + 123, + 124, + 125, + 126, + 127, + 128, + 129, + 130, + 131, + 132, + 133, + 134, + 135, + 136, + 137, + 138, + 139, + 140, + 141, + 142, + 143, + 144, + 145, + 146, + 147, + 148, + 149, + 150, + 151, + 152, + 153, + 154, + 155, + 156, + 157, + 158, + 159, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 174, + 175, + 176, + 177, + 178, + 179, + 180, + 181, + 182, + 183, + 184, + 185, + 186, + 187, + 188, + 189, + 190, + 191, + 192, + 193, + 194, + 195, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 210, + 211, + 212, + 213, + 214, + 215, + 216, + 217, + 218, + 219, + 220, + 221, + 222, + 223, + 224, + 225, + 226, + 227, + 228, + 229, + 230, + 231, + 232, + 233, + 234, + 235, + 236, + 237, + 238, + 239, + 240, + 241, + 242, + 243, + 244, + 245, + 246, + 247, + 248, + 249, + 250, + 251, + 252, + 253, + 254, + 255 + ], + "cursors": [ + 0, + 0, + 0, + 0 + ], + "slots": [ + null, + null, + null, + null, + null + ], + "jobs": [], + "serial": 0, + "launched": [] + } + ], + "completed": [ + 0, + 3, + 20 + ], + "speed": 2 + }, + "fingerprint": "985dd15dc9ab006d9a9079fef4855e5d528db40fb5e454fda516ed198b2779f6" +} diff --git a/tests/garden.test.js b/tests/garden.test.js new file mode 100644 index 0000000..54581e4 --- /dev/null +++ b/tests/garden.test.js @@ -0,0 +1,63 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { PocketGame, encodePocket, decodePocket } from '../src/pocket-core.js'; +import { alveolesRules, hexNeighbors } from '../src/alveoles-puzzle.js'; +import { potionsRules, pourAmount } from '../src/potions-puzzle.js'; +import { liaisonsRules, neighbors } from '../src/liaisons-puzzle.js'; + +const all={alveoles:alveolesRules,potions:potionsRules,liaisons:liaisonsRules}; +function conservation(name,level,state) { + if(name==='alveoles') { + const stock=level.queues.flatMap((q,i)=>q.slice(state.queues[i])).flat().length; + assert.equal(state.stacks.flat().length+stock+state.cleared,level.stacks.flat().length+level.queues.flat(2).length); + assert.equal(state.cleared%6,0); + } + if(name==='potions') {assert.ok(state.bottles.every(b=>b.length<=4));for(const color of level.colors)assert.equal(state.bottles.flat().filter(c=>c===color).length,4);} + if(name==='liaisons') {const cells=state.paths.flat();assert.equal(new Set(cells).size,cells.length);for(const path of state.paths)for(let i=1;i{ + const layouts=new Set();let first,last; + for(let index=0;index<48;index++) { + const level=rules.create(index);assert.deepEqual(level,rules.create(index));const {index:_,title:__,solution:___,...layout}=level;layouts.add(JSON.stringify(layout)); + const game=new PocketGame(rules,index),initial=structuredClone(game.state); + for(const action of level.solution){const before=structuredClone(game.state);assert.ok(game.play(action),`${name} ${index+1} ${JSON.stringify(action)}`);assert.deepEqual(game.history.at(-1),before);conservation(name,level,game.state);} + assert.ok(game.won,`${name} ${index+1}`);assert.equal(game.play(level.solution[0]),false);while(game.history.length)game.undo();assert.deepEqual(game.state,initial); + const difficulty=name==='alveoles'?level.solution.length:name==='potions'?level.colors.length:level.size;if(!index)first=difficulty;if(index===47)last=difficulty; + } + assert.equal(layouts.size,48);assert.ok(last>first);assert.throws(()=>rules.create(-1));assert.throws(()=>rules.create(48)); + }); + test(`${name}: exact replay, undo, completion and sound survive save validation`,()=>{ + const game=new PocketGame(rules,47);for(const action of game.level.solution.slice(0,2))assert.ok(game.play(action)); + const saved=encodePocket(game,new Set([0,12,35]),true),restored=decodePocket(rules,saved);assert.deepEqual(restored.game.state,game.state);assert.deepEqual(restored.game.history,game.history);assert.equal(restored.sound,true);assert.deepEqual([...restored.completed],[0,12,35]); + game.undo();restored.game.undo();assert.deepEqual(game.state,restored.game.state);game.restart();assert.equal(game.moves.length,0); + for(const value of [null,{}, {...saved,index:48},{...saved,generation:999},{...saved,moves:[null]},{...saved,moves:[{from:999,to:0,q:999,cell:0,color:999,path:[0]}]}])assert.equal(decodePocket(rules,value),null); + }); + test(`${name}: hints verify complete remaining solutions across every chapter boundary`,()=>{ + for(const index of [0,11,12,23,24,35,36,47]) {const game=new PocketGame(rules,index);for(const action of game.level.solution.slice(0,1))assert.ok(game.play(action));const plan=rules.plan(game.level,game.state);assert.ok(plan?.length);for(const action of plan)assert.ok(game.play(action));assert.ok(game.won);} + }); +} +test('alveoles: adjacent top colors gather, hidden layers cascade, six-tile thresholds conserve leftovers',()=>{ + const level={cells:[[0,0],[1,0],[2,0],[0,1]],stacks:[[1,1,1,0,0,0],[],[2,2],[]],queues:[[[1,1,1,0,0,0]],[],[]]}; + const state=alveolesRules.initial(level),before=structuredClone(state),next=alveolesRules.move(level,state,{q:0,cell:1});assert.equal(next.cleared,12);assert.deepEqual(next.stacks,[[],[],[2,2],[]]);assert.deepEqual(state,before); + assert.equal(alveolesRules.move(level,state,{q:0,cell:0}),null);assert.equal(alveolesRules.move(level,state,{q:5,cell:1}),null);assert.equal(alveolesRules.move(level,state,{q:0,cell:1.5}),null); + const excess={...level,stacks:[[0,0,0,0,0],[],[],[]],queues:[[[0,0,0]],[],[]]};const merged=alveolesRules.move(excess,alveolesRules.initial(excess),{q:0,cell:1});assert.equal(merged.cleared,6);assert.deepEqual(merged.stacks[1],[0,0]);assert.deepEqual(hexNeighbors(level,0),[1,3]); +}); +test('potions: maximal top-run pours respect space, colors, bottoms and transactionality',()=>{ + const level={},state={bottles:[[2,0,0,0],[1,0,0],[],[1,1,1,1]]},before=structuredClone(state); + assert.equal(pourAmount(state,0,1),1);assert.deepEqual(potionsRules.move(level,state,{from:0,to:1}).bottles,[[2,0,0],[1,0,0,0],[],[1,1,1,1]]); + assert.deepEqual(potionsRules.move(level,state,{from:0,to:2}).bottles,[[2],[1,0,0],[0,0,0],[1,1,1,1]]); + for(const action of [{from:0,to:3},{from:3,to:0},{from:0,to:0},{from:2,to:0},{from:-1,to:0},{from:0,to:1.5}])assert.equal(potionsRules.move(level,state,action),null); + assert.deepEqual(state,before);assert.equal(potionsRules.won(level,{bottles:[[0,0],[0,0],[]]}),false);assert.equal(potionsRules.won(level,{bottles:[[0,0,0,0],[]]}),true); +}); +test('liaisons: strokes cannot cross, visit foreign endpoints, wrap rows or win with empty cells',()=>{ + const level={size:3,pairs:[[0,2],[6,8]]},state={paths:[[0,1,2],[]]},before=structuredClone(state); + for(const action of [{color:1,path:[6,3,0,1,2,5,8]},{color:1,path:[6,7,4,1,2,5,8]},{color:1,path:[6,5,8]},{color:1,path:[6,7,6,3,4,5,8]},{color:1,path:[6,7,8,5]}])assert.equal(liaisonsRules.move(level,state,action),null); + const joined=liaisonsRules.move(level,state,{color:1,path:[6,7,8]});assert.ok(joined);assert.equal(liaisonsRules.won(level,joined),false); + const filled=liaisonsRules.move(level,joined,{color:0,path:[0,3,4,1,2]});assert.ok(filled);assert.equal(liaisonsRules.won(level,filled),false);assert.deepEqual(state,before); +}); +test('liaisons: hints can clear a valid alternate stroke and rebuild a fully filled solution',()=>{ + const game=new PocketGame(liaisonsRules,47),path=game.level.solution[0].path; + assert.ok(game.play({color:0,path:path.slice(0,3)}));const hint=game.hint();assert.deepEqual(hint.action,{color:0,path:[]});assert.ok(game.play(hint.action)); + for(const action of liaisonsRules.plan(game.level,game.state))assert.ok(game.play(action));assert.ok(game.won); +}); diff --git a/tests/harvest.test.js b/tests/harvest.test.js new file mode 100644 index 0000000..12fe3d7 --- /dev/null +++ b/tests/harvest.test.js @@ -0,0 +1,52 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { PocketGame, encodePocket, decodePocket } from '../src/pocket-core.js'; +import { eclusesRules } from '../src/ecluses-puzzle.js'; +import { dunesRules, SandFlow } from '../src/dunes-puzzle.js'; +import { fringaleRules, moveHole, holeRadius } from '../src/fringale-puzzle.js'; +const all={ecluses:eclusesRules,dunes:dunesRules,fringale:fringaleRules}; +function conserved(name,level,state){ + if(name==='ecluses'){const ids=[...state.rooms.flat(),...state.collected,...state.lost,...state.bombsGone];assert.equal(ids.length,level.balls.length);assert.equal(new Set(ids).size,ids.length);assert.ok(state.collected.every(id=>state.colors[id]!==null&&!level.balls[id].bomb));} + if(name==='dunes'){assert.equal(state.field.filter(c=>c>0).length+state.cleared,level.field.filter(c=>c>0).length+state.added);for(let id=0;idn+level.items[id].mass,0));assert.ok(state.hole.every(Number.isFinite));} +} +for(const [name,rules] of Object.entries(all)){ + test(`${name}: 48 distinct deterministic levels have legal complete solutions, conservation and exact undo`,()=>{ + const layouts=new Set();let first,last; + for(let index=0;index<48;index++){ + const level=rules.create(index);assert.deepEqual(level,rules.create(index));const {index:_,title:__,solution:___,...layout}=level;layouts.add(JSON.stringify(layout));const game=new PocketGame(rules,index),initial=structuredClone(game.state); + for(const action of level.solution){const before=structuredClone(game.state);assert.ok(game.play(action),`${name} ${index+1} ${JSON.stringify(action)}`);assert.deepEqual(game.history.at(-1),before);conserved(name,level,game.state);}assert.ok(game.won);assert.equal(game.play(level.solution[0]),false);while(game.history.length)game.undo();assert.deepEqual(game.state,initial); + const complexity=name==='ecluses'?level.total:name==='dunes'?level.goal:level.items.length;if(!index)first=complexity;if(index===47)last=complexity; + }assert.equal(layouts.size,48);assert.ok(last>first);assert.throws(()=>rules.create(-1));assert.throws(()=>rules.create(48)); + }); + test(`${name}: saved replay keeps the exact board, history, sound and completions`,()=>{ + const game=new PocketGame(rules,47);for(const action of game.level.solution.slice(0,3))assert.ok(game.play(action));const save=encodePocket(game,new Set([0,12,35]),true),restore=decodePocket(rules,save);assert.deepEqual(restore.game.state,game.state);assert.deepEqual(restore.game.history,game.history);assert.equal(restore.sound,true);game.undo();restore.game.undo();assert.deepEqual(restore.game.state,game.state); + for(const bad of [null,{}, {...save,index:48},{...save,generation:99},{...save,moves:[null]},{...save,moves:[{q:99,x:0,type:'visit',id:999}]}])assert.equal(decodePocket(rules,bad),null);game.restart();assert.deepEqual(game.state,rules.initial(game.level)); + }); + test(`${name}: hints prove whole remaining routes across the chapter boundaries`,()=>{ + for(const index of [0,11,12,23,24,35,36,47]){const game=new PocketGame(rules,index);assert.ok(game.play(game.level.solution[0]));const route=rules.plan(game.level,game.state);assert.ok(route?.length);for(const action of route)assert.ok(game.play(action));assert.ok(game.won);} + }); +} +test('ecluses: gray balls must mix before entering the basket; wrong openings and bombs are undoable',()=>{ + const game=new PocketGame(eclusesRules,0),initial=structuredClone(game.state);assert.ok(game.play(2));assert.ok(game.play(0));assert.ok(game.state.lost.length);assert.equal(game.won,false);assert.deepEqual(game.hint(),{undo:true});assert.equal(game.play(1),false);game.undo();game.undo();assert.deepEqual(game.state,initial); + assert.ok(game.play(0));assert.ok(game.state.rooms.flat().some(id=>game.state.colors[id]===null));assert.ok(game.play(1));assert.ok(game.state.rooms.flat().every(id=>game.state.colors[id]!==null)); + const bombGame=new PocketGame(eclusesRules,36);assert.ok(bombGame.play(bombGame.level.pins.length-1));assert.ok(bombGame.play(0));assert.ok(bombGame.play(2));assert.ok(bombGame.state.lost.length);conserved('ecluses',bombGame.level,bombGame.state); +}); +test('dunes: live grain stepping matches audited drops and conserves grains at every tick',()=>{ + for(const index of [0,12,24,47]){const level=dunesRules.create(index);let state=dunesRules.initial(level);for(const action of level.solution){const simulation=new SandFlow(level,state,action);assert.equal(simulation.invalid,undefined);while(!simulation.done){simulation.step();conserved('dunes',level,simulation.state);}assert.deepEqual(simulation.state,dunesRules.move(level,state,action));state=simulation.state;}assert.ok(dunesRules.won(level,state));} +}); +test('dunes: occupied spawn cells, bad columns and empty queues reject transactionally',()=>{ + const level=dunesRules.create(0),state=dunesRules.initial(level),action=level.solution[0],before=structuredClone(state); + for(const bad of [null,{q:99,x:0},{q:action.q,x:-1},{q:action.q,x:level.width},{q:action.q,x:.5}])assert.equal(dunesRules.move(level,state,bad),null); + const blocked=structuredClone(state);blocked.field.fill(1,0,level.width*8);assert.equal(dunesRules.move(level,blocked,action),null);assert.deepEqual(state,before); +}); +test('fringale: growth unlocks larger objects and movement cannot teleport through hedges',()=>{ + const level={walls:[{x:250,y:60,w:20,h:320}],items:[{id:0,x:180,y:120,r:6,mass:1},{id:1,x:350,y:150,r:20,mass:7}],start:[100,120]},state={hole:[100,120],mass:0,collected:[]},before=structuredClone(state); + assert.equal(moveHole(level,state,{type:'visit',id:1}),null);const grabbed=moveHole(level,state,{type:'visit',id:0});assert.ok(grabbed.collected.includes(0));assert.equal(grabbed.mass,1);assert.ok(holeRadius(grabbed.mass)>holeRadius(state.mass)); + const stopped=moveHole(level,state,{type:'path',path:[[400,120]]});assert.ok(stopped);assert.ok(stopped.hole[0]<=250-holeRadius(stopped.mass));assert.deepEqual(state,before); + for(const action of [{type:'path',path:[[Infinity,120]]},{type:'path',path:[[0,0]]},{type:'visit',id:99},{type:'path',path:[]}])assert.equal(moveHole(level,state,action),null); +}); +test('fringale: growing outside before clearing a small courtyard creates a real reversible detour',()=>{ + const game=new PocketGame(fringaleRules,36);for(const item of game.level.items.slice(4))if(item.r+3<=holeRadius(game.state.mass))game.play({type:'visit',id:item.id}); + assert.ok(game.state.collected.length>10);assert.ok(game.level.items.slice(0,4).some(p=>!game.state.collected.includes(p.id)));assert.equal(fringaleRules.plan(game.level,game.state),null);assert.deepEqual(game.hint(),{undo:true});const before=structuredClone(game.history.at(-1));assert.ok(game.undo());assert.deepEqual(game.state,before); +}); diff --git a/tests/physics.test.js b/tests/physics.test.js new file mode 100644 index 0000000..9e77041 --- /dev/null +++ b/tests/physics.test.js @@ -0,0 +1,49 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { PocketGame, encodePocket, decodePocket } from '../src/pocket-core.js'; +import { noeudsRules, ropeCrossings } from '../src/noeuds-puzzle.js'; +import { gouttesRules, inkUsed } from '../src/gouttes-puzzle.js'; +import { WaterSimulation, simulateWater, WATER_TOTAL } from '../src/gouttes-physics.js'; +import { segmentsMeet } from '../src/physics-geometry.js'; +for(const [name,rules] of Object.entries({noeuds:noeudsRules,gouttes:gouttesRules})){ + test(`${name}: all 48 distinct seeded levels have complete audited solutions and growing difficulty`,()=>{ + const layouts=new Set();let first,last; + for(let index=0;index<48;index++){ + const level=rules.create(index);assert.deepEqual(level,rules.create(index));const {index:_,title:__,solution:___,...layout}=level;layouts.add(JSON.stringify(layout));const game=new PocketGame(rules,index),initial=structuredClone(game.state); + for(const action of level.solution){const before=structuredClone(game.state);assert.ok(game.play(action),`${name} ${index+1} ${JSON.stringify(action)}`);assert.deepEqual(game.history.at(-1),before);if(name==='noeuds'){assert.equal(new Set(game.state.pins).size,level.pins.length);for(let id=0;idfirst);assert.throws(()=>rules.create(-1));assert.throws(()=>rules.create(48)); + }); + test(`${name}: replay restores exact state, undo, completion badges and optional sound`,()=>{ + const game=new PocketGame(rules,47);assert.ok(game.play(game.level.solution[0]));const save=encodePocket(game,new Set([0,12,35]),true),restore=decodePocket(rules,save);assert.deepEqual(restore.game.state,game.state);assert.deepEqual(restore.game.history,game.history);assert.equal(restore.sound,true);game.undo();restore.game.undo();assert.deepEqual(game.state,restore.game.state); + for(const bad of [null,{}, {...save,generation:99},{...save,index:48},{...save,moves:[null]},{...save,moves:[{type:'draw',path:[[NaN,2],[999,4]],pin:999,peg:1}]}])assert.equal(decodePocket(rules,bad),null); + game.restart();assert.deepEqual(game.state,rules.initial(game.level)); + }); + test(`${name}: hints verify a complete route at each chapter boundary`,()=>{ + for(const index of [0,11,12,23,24,35,36,47]){const game=new PocketGame(rules,index);assert.ok(game.play(game.level.solution[0]));if(game.won)continue;const route=rules.plan(game.level,game.state);assert.ok(route?.length);for(const action of route)assert.ok(game.play(action));assert.ok(game.won);} + }); +} +test('noeuds: proper crossings, endpoint touches and overlapping ropes count; separated cords do not',()=>{ + assert.equal(segmentsMeet([0,0],[4,4],[0,4],[4,0]),true);assert.equal(segmentsMeet([0,0],[4,0],[2,0],[6,0]),true);assert.equal(segmentsMeet([0,0],[4,0],[4,0],[4,4]),true);assert.equal(segmentsMeet([0,0],[4,0],[0,1],[4,1]),false); + const level={pegs:[[0,0],[4,4],[0,4],[4,0],[5,5]],pins:[{fixed:false},{fixed:false},{fixed:false},{fixed:true}],ropes:[{a:0,b:1},{a:2,b:3}]},state={pins:[0,1,2,3]},before=structuredClone(state);assert.deepEqual(ropeCrossings(level,state),[[0,1]]); + for(const action of [{pin:0,peg:1},{pin:3,peg:4},{pin:0,peg:99},{pin:.5,peg:4}])assert.equal(noeudsRules.move(level,state,action),null);assert.deepEqual(state,before); +}); +test('noeuds: arbitrary legal detours remain solvable with fixed pins and occupied target plots',()=>{ + for(const index of [12,24,36,47]){const game=new PocketGame(noeudsRules,index);for(let i=0;i<8&&!game.won;i++){const pin=game.level.pins.findIndex((p,id)=>!p.fixed&&id>=i%game.level.pins.length),peg=game.level.pegs.findIndex((_,id)=>!game.state.pins.includes(id));if(pin>=0)game.play({pin,peg});}if(game.won)continue;const plan=noeudsRules.plan(game.level,game.state);assert.ok(plan?.length);for(const action of plan)assert.ok(game.play(action));assert.ok(game.won);} +}); +test('gouttes: every emitted drop is conserved at every simulation tick; live physics matches audited results',()=>{ + for(const index of [0,12,24,47]){const level=gouttesRules.create(index),lines=level.solution.filter(a=>a.type==='draw').map(a=>a.path),sim=new WaterSimulation(level,lines); + while(!sim.done){sim.step();assert.equal(sim.caught+sim.lost+sim.particles.length+WATER_TOTAL-sim.emitted,WATER_TOTAL);assert.ok(sim.particles.every(p=>Number.isFinite(p.x)&&Number.isFinite(p.y)&&Math.abs(p.vx)<=480&&Math.abs(p.vy)<=481));} + assert.deepEqual(sim.result(),simulateWater(level,lines));assert.ok(sim.caught>=level.goal);assert.ok(simulateWater(level,[]).caught{ + const level={...gouttesRules.create(12),obstacles:[{x:200,y:200,w:40,h:40}],ink:300},state=gouttesRules.initial(level),before=structuredClone(state); + for(const path of [[[100,220],[300,220]],[[210,210],[220,230]],[[0,100],[100,120]],[[100,100]],[[100,100],[101,101]],[[100,100],[500,100]],[[100,100],[Infinity,200]]])assert.equal(gouttesRules.move(level,state,{type:'draw',path}),null); + assert.deepEqual(state,before);assert.ok(gouttesRules.move(level,state,{type:'draw',path:[[100,180],[300,180]]})); +}); +test('gouttes: failed trials can be saved, undone, cleared and corrected through verified hints',()=>{ + const game=new PocketGame(gouttesRules,47);assert.ok(game.play({type:'run'}));assert.equal(game.won,false);assert.equal(game.state.result.caught,0);const saved=decodePocket(gouttesRules,encodePocket(game,new Set(),false));assert.deepEqual(saved.game.state,game.state);assert.ok(game.undo());assert.equal(game.state.result,null); + assert.ok(game.play({type:'draw',path:[[80,500],[140,520]]}));assert.equal(game.hint().action.type,'clear');const plan=gouttesRules.plan(game.level,game.state);for(const action of plan)assert.ok(game.play(action));assert.ok(game.won);assert.ok(game.undo());assert.equal(game.state.result,null);assert.ok(game.state.lines.length>0); +}); diff --git a/tests/pocket.test.js b/tests/pocket.test.js new file mode 100644 index 0000000..6e39d22 --- /dev/null +++ b/tests/pocket.test.js @@ -0,0 +1,80 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { PocketGame, encodePocket, decodePocket, searchPlan } from '../src/pocket-core.js'; +import { atelierRules, exposedPlate } from '../src/atelier-puzzle.js'; +import { bobinesRules } from '../src/bobines-puzzle.js'; +import { escapadeRules } from '../src/escapade-puzzle.js'; + +const all = { atelier:atelierRules, bobines:bobinesRules, escapade:escapadeRules }; +for (const [name, rules] of Object.entries(all)) { + test(`${name}: 48 distinct deterministic boards have complete legal solutions and rising sizes`, () => { + const layouts = new Set(); let firstSize, lastSize; + for (let index = 0; index < 48; index++) { + const level = rules.create(index); assert.deepEqual(level, rules.create(index)); + layouts.add(JSON.stringify(name === 'atelier' ? [level.plates, level.screws, level.boxes] : name === 'bobines' ? [level.lines, level.queues] : [level.snakes, level.walls])); + const game = new PocketGame(rules, index), original = structuredClone(game.state); + const size = name === 'atelier' ? level.screws.length : name === 'bobines' ? level.lines.flat().length : level.size * level.snakes.length; + if (index === 0) firstSize = size; if (index === 47) lastSize = size; + for (const action of level.solution) { + const before = structuredClone(game.state); assert.equal(game.play(action), true, `${name} ${index + 1} ${JSON.stringify(action)}`); + assert.deepEqual(game.history.at(-1), before); + } + assert.equal(game.won, true, `Puzzle ${index + 1}`); + while (game.history.length) game.undo(); assert.deepEqual(game.state, original); + } + assert.equal(layouts.size, 48); assert.ok(lastSize > firstSize); + assert.throws(() => rules.create(48)); assert.throws(() => rules.create(-1)); assert.throws(() => rules.create(1.5)); + }); + test(`${name}: save replay retains exact state and undo; invalid saves fail safely`, () => { + const game = new PocketGame(rules, 39); + for (const action of game.level.solution.slice(0, 5)) assert.ok(game.play(action)); + const saved = encodePocket(game, new Set([0, 1, 47]), true), restored = decodePocket(rules, saved); + assert.ok(restored); assert.deepEqual(restored.game.state, game.state); assert.deepEqual(restored.game.history, game.history); assert.equal(restored.sound, true); + game.undo(); restored.game.undo(); assert.deepEqual(restored.game.state, game.state); + for (const invalid of [null, {}, { ...saved, version:9 }, { ...saved, index:48 }, { ...saved, moves:[null] }, { ...saved, moves:[{ id:99, to:[0,0] }] }]) assert.equal(decodePocket(rules, invalid), null); + game.restart(); assert.deepEqual(game.state, rules.initial(game.level)); assert.equal(game.history.length, 0); + }); + test(`${name}: hints prove a complete route from canonical partial states`, () => { + for (const index of [0, 11, 12, 23, 24, 35, 36, 47]) { + const game = new PocketGame(rules, index); + for (const action of game.level.solution.slice(0, Math.floor(game.level.solution.length / 2))) assert.ok(game.play(action)); + const plan = rules.plan ? rules.plan(game.level, game.state) : searchPlan(rules, game.level, game.state); + assert.ok(plan?.length, `${name} ${index}`); for (const action of plan) assert.ok(game.play(action)); assert.ok(game.won); + } + }); +} +test('atelier: covered screws cannot be removed and matching boxes consume exactly three', () => { + const game = new PocketGame(atelierRules, 24); + const buried = game.level.plates.find(p => !exposedPlate(game.level, game.state, p)); + const before = structuredClone(game.state); assert.equal(game.play(buried.screws[0]), false); assert.deepEqual(game.state, before); + for (const action of game.level.solution) { + assert.ok(game.play(action)); assert.ok(game.state.buffer.length <= game.level.bufferSize); assert.ok(game.state.trays.every(t => !t || t.count < 3)); + } + assert.ok(game.won); assert.ok(!game.state.trays.some(Boolean)); +}); +test('bobines: buried colors wait and a full reserve blocks new launches without changing state', () => { + let deadlock; + for (let index = 12; index < 48 && !deadlock; index++) { + const level = bobinesRules.create(index), queue = [{ state:bobinesRules.initial(level), moves:[] }], seen = new Set(); + for (let n = 0; n < queue.length && n < 1000; n++) { + const { state, moves } = queue[n]; + if (!state.slots.includes(null) && !bobinesRules.won(level, state)) { deadlock = { level, state, moves }; break; } + for (const action of bobinesRules.actions(level, state)) { const next = bobinesRules.move(level, state, action), key = JSON.stringify(next); if (!seen.has(key)) { seen.add(key); queue.push({ state:next, moves:[...moves, action] }); } } + } + } + assert.ok(deadlock); const game = new PocketGame(bobinesRules, deadlock.level.index); + for (const move of deadlock.moves) game.play(move); + const before = structuredClone(game.state); assert.equal(game.play(0), false); assert.deepEqual(game.state, before); assert.deepEqual(game.hint(), { undo:true }); assert.ok(game.undo()); assert.ok(game.state.slots.includes(null)); +}); +test('escapade: walls, bodies, wrong holes, nonadjacent moves and malformed coordinates block', () => { + const game = new PocketGame(escapadeRules, 47), initial = structuredClone(game.state); + for (const action of [{ id:0, end:'head', to:[99, 99] }, { id:0, end:'foot', to:[0, 0] }, { id:0, end:'head', to:[NaN, 0] }, { id:0, end:'head', to:[1.5, 1] }]) assert.equal(game.play(action), false); + const snake = game.state.snakes[0]; assert.equal(game.play({ id:snake.id, end:'head', to:snake.cells[1] }), false); assert.deepEqual(game.state, initial); + for (const snake of game.state.snakes) for (const end of ['head', 'tail']) { + const head = end === 'head' ? snake.cells[0] : snake.cells.at(-1); + for (const to of [...game.level.walls, ...game.level.snakes.filter(s => s.id !== snake.id).map(s => s.hole)]) { + if (Math.abs(head[0] - to[0]) + Math.abs(head[1] - to[1]) === 1) assert.equal(escapadeRules.move(game.level, game.state, { id:snake.id, end, to }), null); + } + } + const first = game.level.solution[0]; assert.ok(game.play(first)); const plan = escapadeRules.plan(game.level, game.state); assert.ok(plan?.length); +}); diff --git a/tests/suite.test.js b/tests/suite.test.js new file mode 100644 index 0000000..38c7bed --- /dev/null +++ b/tests/suite.test.js @@ -0,0 +1,69 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { PocketGame, encodePocket, decodePocket, searchPlan } from '../src/pocket-core.js'; +import { passagesRules } from '../src/passages-puzzle.js'; +import { voyageRules, accessiblePassengers } from '../src/voyage-puzzle.js'; +import { carrouselRules } from '../src/carrousel-puzzle.js'; +import { broderieRules, accessibleSpools } from '../src/broderie-puzzle.js'; +import { peelColor } from '../src/picture-art.js'; + +const all={passages:passagesRules,voyage:voyageRules,carrousel:carrouselRules,broderie:broderieRules}; +function conservation(name,level,state){ + if(name==='carrousel')for(const color of new Set(level.cells)){ + const pixels=level.cells.filter((c,id)=>c===color&&!state.removed.includes(id)).length; + const ammunition=state.waiting.reduce((n,p)=>n+(p?.color===color?p.ammo:0),0)+level.queues.reduce((n,q,i)=>n+q.slice(state.queues[i]).filter(p=>p.color===color).reduce((n,p)=>n+p.ammo,0),0); + assert.equal(pixels,ammunition);assert.ok(state.waiting.filter(Boolean).length<=5); + } + if(name==='broderie'){assert.ok(state.buffer.length<=7);assert.ok(new Set(state.removed).size===state.removed.length);assert.ok(state.buffer.every(c=>state.buffer.filter(n=>n===c).length<3));} + if(name==='voyage'){assert.ok(state.buffer.length<=5);assert.ok(state.boarded<(level.buses[state.bus]?.count??1));assert.ok(state.buffer.every(id=>state.removed.includes(id)));} +} +for(const [name,rules]of Object.entries(all)){ + test(`${name}: 48 distinct deterministic levels have legal complete solutions, undo and growing difficulty`,()=>{ + const layouts=new Set();let first,last; + for(let index=0;index<48;index++){ + const level=rules.create(index);assert.deepEqual(level,rules.create(index)); + const {index:_,title:__,solution:___,score:____,...layout}=level;layouts.add(JSON.stringify(layout)); + const game=new PocketGame(rules,index),original=structuredClone(game.state); + const size=name==='passages'?level.blocks.length:name==='voyage'?level.passengers.length:name==='carrousel'?level.cells.length:level.spools.length;if(!index)first=size;if(index===47)last=size; + for(const action of level.solution){const before=structuredClone(game.state);assert.ok(game.play(action),`${name} puzzle ${index+1}, ${JSON.stringify(action)}`);assert.deepEqual(game.history.at(-1),before);conservation(name,level,game.state);} + assert.ok(game.won);while(game.history.length)game.undo();assert.deepEqual(game.state,original); + } + assert.equal(layouts.size,48);assert.ok(last>first);assert.throws(()=>rules.create(-1));assert.throws(()=>rules.create(48)); + }); + test(`${name}: exact save replay and history survive reload; malformed moves fail safely`,()=>{ + const game=new PocketGame(rules,47);for(const action of game.level.solution.slice(0,6))assert.ok(game.play(action)); + const saved=encodePocket(game,new Set([0,12,35]),true),restored=decodePocket(rules,saved);assert.ok(restored);assert.deepEqual(restored.game.state,game.state);assert.deepEqual(restored.game.history,game.history);assert.equal(restored.sound,true); + game.undo();restored.game.undo();assert.deepEqual(game.state,restored.game.state); + for(const bad of [null,{}, {...saved,generation:99},{...saved,index:48},{...saved,moves:[null]},{...saved,moves:[{id:9000,type:'waiting',slot:9000,dx:9,dy:9}]}])assert.equal(decodePocket(rules,bad),null); + game.restart();assert.deepEqual(game.state,rules.initial(game.level));assert.equal(game.history.length,0); + }); + test(`${name}: hints verify whole remaining routes through all chapter boundaries`,()=>{ + for(const index of [0,11,12,23,24,35,36,47]){ + const game=new PocketGame(rules,index);for(const action of game.level.solution.slice(0,Math.floor(game.level.solution.length/2)))assert.ok(game.play(action)); + const plan=rules.plan?rules.plan(game.level,game.state):searchPlan(rules,game.level,game.state);assert.ok(plan?.length,`${name} ${index+1}`);for(const action of plan)assert.ok(game.play(action));assert.ok(game.won); + } + }); +} +test('passages: rectangles cannot cross neighbors or walls, or exit through an unaligned door',()=>{ + const level={size:4,walls:[[2,2]],blocks:[{id:0,color:0,x:0,y:1,w:2,h:1,door:{side:'left',at:2,span:1}},{id:1,color:1,x:2,y:0,w:1,h:2,door:{side:'top',at:2,span:1}}]}; + const state=passagesRules.initial(level),before=structuredClone(state); + for(const action of [{id:0,dx:1,dy:0},{id:0,dx:-1,dy:0},{id:0,dx:1,dy:1},{id:1,dx:0,dy:1}])assert.equal(passagesRules.move(level,state,action),null); + assert.deepEqual(state,before);const aligned=passagesRules.move(level,state,{id:0,dx:0,dy:1});assert.ok(aligned);const exited=passagesRules.move(level,aligned,{id:0,dx:-1,dy:0});assert.equal(exited.blocks.length,1); +}); +test('voyage: only the outside-connected front is selectable and buses conserve every passenger color',()=>{ + const game=new PocketGame(voyageRules,0);assert.equal(accessiblePassengers(game.level,game.state).length,game.level.width);assert.equal(game.play(0),false); + for(const color of new Set(game.level.passengers.map(p=>p.color)))assert.equal(game.level.buses.filter(b=>b.color===color).reduce((n,b)=>n+b.count,0),game.level.passengers.filter(p=>p.color===color).length); + const level={width:3,height:3,walls:[[0,1],[1,1],[2,1]],passengers:[{id:0,x:1,y:0,color:0},{id:1,x:1,y:2,color:1}]};assert.deepEqual(accessiblePassengers(level,{removed:[]}),[1]);assert.deepEqual(accessiblePassengers(level,{removed:[1]}),[]); +}); +test('carrousel: buried colors can wait, full waiting slots reject launches, and fruitless relaunches are transactional',()=>{ + let game,q; + for(let index=0;index<48&&!game;index++){const candidate=new PocketGame(carrouselRules,index);for(let n=0;n<4;n++){const pig=candidate.level.queues[n][0];if(pig&&!peelColor(candidate.level,[],pig.color,pig.ammo).length){game=candidate;q=n;break;}}} + assert.ok(game);assert.ok(game.play({type:'queue',q}));assert.equal(game.state.removed.length,0);const before=structuredClone(game.state);assert.equal(game.play({type:'waiting',slot:0}),false);assert.deepEqual(game.state,before); + const full={...game.state,waiting:Array.from({length:5},()=>({color:0,ammo:1}))};assert.equal(carrouselRules.move(game.level,full,{type:'queue',q}),null); +}); +test('broderie: covered bobbins reject selection; triplets stitch disjoint patches covering the whole picture',()=>{ + const game=new PocketGame(broderieRules,0),ready=accessibleSpools(game.level,game.state),covered=game.level.spools.find(s=>!ready.includes(s.id));assert.ok(covered);assert.equal(game.play(covered.id),false); + for(const action of game.level.solution.slice(0,2))assert.ok(game.play(action));assert.equal(game.state.buffer.length,2);assert.equal(game.state.stitched.length,0);assert.ok(game.play(game.level.solution[2]));assert.equal(game.state.buffer.length,0);assert.equal(game.state.stitched.length,1); + const pixels=game.level.patches.flatMap(p=>p.pixels);assert.equal(pixels.length,game.level.cells.length);assert.equal(new Set(pixels).size,game.level.cells.length); + for(const p of game.level.patches)assert.ok(p.pixels.every(id=>game.level.cells[id]===p.color)); +}); diff --git a/vite.config.js b/vite.config.js index f816dc2..22a6174 100644 --- a/vite.config.js +++ b/vite.config.js @@ -2,5 +2,5 @@ import { defineConfig } from 'vite'; export default defineConfig({ base: process.env.PAGES_BASE_PATH || '/', - build: { rolldownOptions: { input: { main: 'index.html', cube: 'cube.html', image: 'image.html', colony: 'colony.html' } } }, + build: { rolldownOptions: { input: { main: 'index.html', cube: 'cube.html', image: 'image.html', colony: 'colony.html', atelier: 'atelier.html', bobines: 'bobines.html', escapade: 'escapade.html', passages:'passages.html', voyage:'voyage.html', carrousel:'carrousel.html', broderie:'broderie.html', alveoles:'alveoles.html', potions:'potions.html', liaisons:'liaisons.html', noeuds:'noeuds.html', gouttes:'gouttes.html', ecluses:'ecluses.html', dunes:'dunes.html', fringale:'fringale.html', recolte:'recolte.html', dizaines:'dizaines.html', mosaique:'mosaique.html' } } }, }); diff --git a/voyage.html b/voyage.html new file mode 100644 index 0000000..102f86e --- /dev/null +++ b/voyage.html @@ -0,0 +1 @@ +Voyage — Cube Cube Cube