commit 07e9253663c7b3eef021e4eed92c521192400bf8 Author: Hadrian Burkhardt Date: Sat Oct 31 03:28:48 2026 +0100 Initial commit: Lumen Android puzzle notebook v1.7 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..87bfa98 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.gradle/ +local.properties +**/build/ +*.jks +*.keystore +artifacts/ +__pycache__/ +.venv/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..ccd98d9 --- /dev/null +++ b/README.md @@ -0,0 +1,106 @@ +# Lumen — The Last Light (Android 1.7) + +A native Android 7.0+ app styled as a lightkeeper’s family notebook: faded blue cloth, stitched binding, warm ruled paper, a ribbon bookmark and pressed heather. A hand-drawn twilight harbour connects the home screen to the island story. No account or game backend. Players restore a darkened island through picture puzzles, or play generated 5×5 daily and classic grids. + +The opening six-leaf storybook prototype is implemented. The wider [product roadmap](ROADMAP.md) describes the next chapters and further exploration features. + +## Opening notebook prototype + +Open Mara’s notebook from the home screen. The opening trail contains: + +1. Gran’s handwritten dedication. +2. A cottage entry with an original watercolour illustration. +3. The existing match puzzle, using its original save key. +4. A match sketch and a personal memory. +5. A folded note that can be opened and kept. +6. A lantern illustration with a repair detail to inspect. + +Use the corner arrows or swipe horizontally from a page margin. Gestures starting inside the grid cannot turn the page. Navigation stays fixed below the reading area; text can overflow-scroll for larger fonts or landscape. A short fade/slide respects disabled system animations. Contents links to these leaves, a ribbon bookmark, and the existing three-chapter campaign. The final lantern leaf links to the next existing entry; the rest of the campaign still uses the earlier screens. + +Five pre-rendered readings ship as lossless FLAC files, with editable 24 kHz mono WAV masters in `assets/narration/wav/`. Android MediaPlayer provides play, pause, exact-position resume, stop and replay, optional speed settings, and passage highlighting. There is no Android text-to-speech service, runtime synthesis, voice download, or per-listen network request. These are synthetic British-English readings rendered during development, not a human actor’s performance. Playback stops on page changes and when the app backgrounds. See [audio provenance and regeneration](assets/narration/README.md). + +The last leaf, explicit ribbon bookmark, opened note, inspected handle and viewed-page flags are saved independently of puzzle completion. Closing the app in the notebook restores the same leaf. Reading ahead from an unsolved puzzle asks once per attempted turn and keeps all marks without awarding completion. Existing campaign grids and counts are preserved; the original match can be revisited if already solved. The opening prototype contains no interstitials, and narration/discoveries require no ad. + +The cottage and lantern PNGs were generated using the built-in image tool with alpha backgrounds. Originals and exact prompts are in `assets/artwork/`; sampled decoded copies are used for the small on-page illustrations. + +For isolated tablet smoke tests: + +```sh +JAVA_HOME=/path/to/jdk-21 ./gradlew :app:assembleDebug -PqaBuild=true +adb -s YOUR_SERIAL install -r app/build/outputs/apk/debug/app-debug.apk +python3 scripts/check_storybook.py --serial YOUR_SERIAL +``` + +The test script enforces a `.qa` package because it writes disposable fixtures. It checks edge swipes, bundled recording playback, pause/resume and speed settings, grid gesture isolation, read-ahead, folded-note persistence, bookmarks, process restart, completion without duplicate awards, and rotation. It restores the tablet’s original rotation settings. Screenshots and results go to `artifacts/storybook-check/`. + +## The Last Light + +Twelve 7×7 picture puzzles across three chapters: the keeper’s cottage, the tidal crossing, and the lighthouse. Follow grandmother Mara’s notebook to recover a match, lantern, key, compass, boat, anchor, bridge, bell, gear, lens, lighthouse and home. Each solution is the actual pictured object, shown as clean pixel art after completion. Story pages appear before and after each puzzle; recovered pictures remain in the notebook. Everything ships in the APK. + +The first two patterns teach row and column totals. Patterns 3–12 add three overlapping rectangular areas. Select A, B or C to highlight its cells; shared cells count in both totals. Later puzzles **cannot** be completed by line saturation alone. Subtracting overlapping constraints resolves cells outside their overlap; tests verify this technique is necessary and sufficient, without branching/guessing. These are introductory area puzzles, not a promise of expert-level challenge. + +Campaign completion unlocks the next page, increments the existing solved counter once, and preserves all prior classic/daily data. Campaign progress is separate from the daily streak. Every fourth story page can show an interstitial when turning to the next chapter, once per chapter transition; re-reading never repeats it. No ad interrupts a story reveal. Campaign replay currently means re-reading recovered pages, not resetting puzzles. + +Hints now explain a forced line or area deduction and mark one cell. If an earlier player mark is wrong, a hint corrects one such cell first. Each puzzle has one free hint, with additional hints requiring the AdMob reward callback. + +## Notebook theme + +The home screen now uses newly generated watercolour harbour and faded-blue notebook-cover PNGs (`HomeArtwork.java`), with a native handwritten cover label. All app-created headings, passages, menus, captions, puzzle clues and dialogs use the cursive handwriting family; system consent screens retain their provider styling. Recovered objects sit on taped paper keepsakes. The lighthouse app icon uses a vector drawable. + +The book cover on the home screen opens a generated 1024×1536 single diary page, bundled without density scaling. `NotebookPage.java` positions transparent content directly on its blank writing area, with no floating panel. Portrait shows the whole page; landscape crops vertically through the blank paper, retaining the binding. Handwritten menu actions have a fine ink underline, and empty puzzle cells have thin pencil outlines so the paper stays visible. The grid sizes to available width and scrolls into view on entry. Source artwork and the exact generation prompt are in `assets/artwork/`. All drawings are static apart from the existing short picture fade; paper texture work is limited to the visible part of the page. Existing puzzle definitions and save keys are unchanged. + +## Classic and daily modes + +- Deterministic generated practice levels and a date-seeded daily puzzle. +- Easy, Medium, and Hard practice, with independent saved progress and a remembered selection. +- Solver checks uniqueness and rates boards by simultaneous deduction rounds: Easy 1–2, Medium 3–4, Hard 5. A round fills lines where all unknown cells must be lit or all must be crossed out; later rounds use those deductions. No guessing is needed. +- Generation tries up to 256 deterministic candidates, then uses a permuted known board of the requested grade. These are relative chain-depth ratings, not a calibrated measure of solve time. +- Existing daily grids retain their original generation. Earlier in-progress practice is accessible through “Continue earlier puzzle.” +- Saved boards, level progress, daily streaks and completion counts on device. +- Undo, one free explained hint per board, then optional rewarded hints. +- Interstitials at a natural transition after every fourth practice completion across all difficulties. No ads during a board or when returning home. +- AdMob and UMP consent flow; ads only requested when consent information permits. +- Google test IDs by default. Games remain playable without connectivity or ad availability. + +Campaign grids use fixed `story_v1_…` save keys. Preserve the order, pictures, givens and area layouts of existing entries when adding future pages; changing an existing puzzle requires a new save-key version. + +## Build + +Requires JDK 17–24 (JDK 21 recommended) and Android SDK 36. Set `sdk.dir` in your own `local.properties` or configure `ANDROID_HOME`. + +```sh +JAVA_HOME=/path/to/jdk-21 ./gradlew :app:testDebugUnitTest :app:assembleDebug +``` + +Debug APK: `app/build/outputs/apk/debug/app-debug.apk`. A shareable copy of version 1.7 is in `artifacts/lumen-1.7.apk`. + +For an isolated device test build, add `-PqaBuild=true` to `assembleDebug`; it installs as `com.lumen.daily.qa`, with independent progress. Build without that property for the normal app. Device smoke-test screenshots and results are under `artifacts/`. + +## Before publishing on Google Play + +1. Choose a permanent application ID in `app/build.gradle` (currently `com.lumen.daily`). +2. Create the Android app and rewarded/interstitial ad units in AdMob. Configure Privacy & messaging for the markets you serve. +3. Supply production IDs via Gradle properties `ADMOB_APP_ID`, `ADMOB_REWARDED_ID`, and `ADMOB_INTERSTITIAL_ID`. Keep Google test IDs in development builds. +4. Configure your private upload signing key outside version control, then build a signed release AAB. Release signing is intentionally not supplied by this repository. +5. Supply a public privacy policy, store artwork, support contact, content rating, target audience, ads declaration and accurate Data safety answers based on the Google ads SDK and your final configuration. The in-app privacy summary is not a replacement for a published policy. +6. Test consent (including refusal/revocation), reward completion/cancellation, no-fill, offline play, process restart, device rotation and small screens on physical devices. Complete Play testing requirements for your developer account. + +The daily date uses the device’s local calendar. Progress and streaks are local, not protected against clock changes or restored after uninstall. A daily puzzle remains available to replay after completion; a solved practice board advances the practice counter. Puzzle generation guarantees a unique answer and grades deduction depth. + +## Source map + +- `Campaign.java`: authored story, 7×7 pixel patterns, precomputed fixed clues and area layouts. +- `LogicSolver.java`: count-constraint search, line/area deductions and explained hints. +- `CampaignTest.java`: all twelve unique pictures; necessary area deductions on pages 3–12; hint completion and restoration checks. +- `LogicSolverTest.java`: deductions and solution counts compared with exhaustive enumeration over 1,000 small overlapping constraint systems. +- `Puzzle.java`: seeded classic generation, general constraints, solution counting, deduction grading, completion validation. +- `Difficulty.java`: difficulty names, descriptions and grade thresholds. +- `DifficultyTest.java`: 1,500 generated boards checked for requested grades and uniqueness, deterministic regeneration, legacy compatibility and ambiguous-board rejection. +- `StoryBook.java`: stable six-leaf story records and narration sentence boundaries. +- `StoryNotebook.java`: page layouts, fixed navigation, folded note and inspection interaction. +- `StoryNarrator.java`: bundled recording playback, passage progress, audio focus and speed settings. +- `PageTurnGesture.java`: page-margin gesture recognition, tested against grid drags. +- `MainActivity.java`: notebook routing, puzzle completion, local progress, streaks, hints. +- `Ads.java`: consent, ad loading and presentation. +- `PuzzleTest.java`: uniqueness, determinism and completion across 500 seeds. +- `DailyStreakTest.java`: consecutive days, replay handling and missed-day reset. diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..1f74d2c --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,160 @@ +# Lumen — a notebook worth exploring + +Status: opening slice updated in Android version 1.7. The six-leaf opening slice below is implemented and ready for review: page-margin swipes, arrows, five bundled recorded readings, two on-page illustrations and refreshed home art, a saved ribbon bookmark, a folded note, a lantern inspection, and the existing match puzzle/reveal. Full chapter pagination, the larger 30–40-leaf story and later exploration features remain proposed. There are no delivery dates yet; review the opening slice before expanding it. + +## The experience we are building + +Lumen is an illustrated story notebook about Mara, her grandchild, and the island they call home. The pleasure of opening the notebook should come from wondering what is on the next page. Puzzles are one way to uncover its memories, alongside reading, listening, examining drawings, and finding things tucked between the leaves. + +The central promise: **every page offers something worth noticing, and every discovery brings the story a little closer.** + +Keep the existing gentle tone and the three-chapter journey to restore the lighthouse. Make the relationship with Gran more tangible through her own words, everyday habits, small jokes, repairs, and things she chose to keep. Let the player learn about her gradually. Preserve the current reunion with Mara; do not introduce a bereavement twist simply to manufacture emotion. + +Success is the player wanting to turn another page, remember a detail, or return to a favourite passage. Completing grids and maintaining a streak remain secondary activities. + +## What exists today + +- Three chapters with twelve authored picture puzzles and short passages before and after them. +- A single-page diary background, handwriting, recovered pixel pictures, and saved local progress. +- Explained puzzle hints, generated classic practice, and a daily challenge. +- Six opening leaves with edge swipes and corner arrows, optional bundled recordings, cottage and lantern illustrations, a folded note, inspection, and independent reading bookmarks. +- Existing campaign pages beyond this prototype retain their previous navigation. Overflow scrolling remains for large text and shorter viewports. + +## Phase 1 — make it a book + +First milestone: a small, complete slice of the cottage chapter that can be read and played by turning pages. + +- Replace the long chapter list with a contents leaf for each chapter, showing four entries and a ribbon marking the current place. +- Give story entries, illustrations, puzzles, and discoveries their own pages. Split long passages at natural sentence or paragraph boundaries. +- Turn pages with horizontal swipes near the edges and small corner arrows. Provide a contents shortcut and a bookmark action. +- Keep page-turn gestures outside the active puzzle grid and narration controls. An attempted mark must never turn the page. +- Use a short paper-turn animation, with an instant or reduced-motion alternative. Backtracking should feel immediate. +- Return to the exact page the player left, including an unfinished puzzle. Support returning to an earlier discovery without changing completion counts. +- Keep vertical scrolling as an accessibility fallback when large text cannot fit on a leaf. Never shrink text just to preserve a page layout. +- Lay out landscape content on the same sheet or repaginate it; do not move the game into a separate floating panel. + +**Ready when:** the first chapter can be traversed forward and backward, the full puzzle and its essential controls are usable, accidental page turns do not occur during grid input, and restarting or rotating the app restores the correct place. Existing saved puzzles still load. + +## Phase 2 — let Gran’s entries be heard + +Every diary entry pairs a short passage with a small original illustration and an optional listen control. + +- Bundle prerecorded WAV or lossless FLAC passages; never depend on the Android reader or a device-installed voice. The opening prototype now has five pre-rendered synthetic readings, WAV masters and FLAC playback assets. +- Review the warm, unhurried delivery before expanding production. Consider a recorded actor performance for Mara; keep synthetic prototype recordings clearly identified in the asset provenance. +- Distinguish Mara’s first-person diary entries from present-day narration and the grandchild’s annotations. Make the speaker clear in the writing and listen control. +- Offer play, pause, exact-position resume, stop and replay. Keep narration opt-in, without autoplay on page entry. +- Highlight the current passage using timing cues while keeping all text accessible. +- Stop playback when a page is turned or the app backgrounds; pause on audio interruption. Never overlap recordings. +- Keep reading available if an asset cannot be played. Audio requires no download, game backend or per-listen server call. +- Match each recording to its stable page ID and exact script, preserve uncompressed masters, and verify bundled FLACs against them. + +Review pronunciation, pacing, emotional tone, and the experience with sound turned off before recording the remaining chapters. Tide and reunion passages still need recordings when their new notebook leaves are authored. + +**Ready when:** the five opening readings play offline, pause/resume and speed settings work, navigation stops playback, and the voice has been reviewed on the tablet. Technical playback is implemented; the final narrative performance remains an art decision. + +## Phase 3 — every leaf has its own identity + +Each page should have a distinct composition and a specific narrative detail. Variety should come from what Mara kept and what happened there, rather than random decoration. + +| Page type | What makes the player curious | Small interaction | +| --- | --- | --- | +| A handwritten entry | An unfinished thought beside a little cottage sketch | Listen to the entry or examine the sketch | +| A taped illustration | A boat, key, or lantern drawn larger than the solved pixel pattern | Tap to see a short handwritten caption | +| A folded letter | A greeting peeking from an envelope | Unfold it and read the message | +| A harbour map | Mara’s pencilled route and a mark near the bridge | Trace the route between already discovered places | +| A pressed-flower leaf | Heather gathered on a day the player has just read about | Lift its label to find the remembered date or place | +| A repair note | A gear sketch with arrows and a practical aside from Gran | Compare it with a recovered puzzle object | +| A weather entry | A rain stain, a tide observation, and a sketch of the sea | Reveal a short note beneath a paper flap | +| A quiet domestic page | A tea stain, shopping scrap, or recipe note | Read a small optional memory with no puzzle attached | +| A puzzle leaf | A pattern that matters to the current scene | Restore it with logic, then see the object illustrated | +| A closing leaf | A drawing and a new note from the grandchild | Revisit the memories collected along the way | + +Visual rules: + +- Keep one consistent diary, ink palette, and handwriting family. Vary the placement of text, the kind of illustration, the paper scraps, and the use of blank space. +- Give every authored story leaf at least one unique illustration or meaningful detail. Do not count a changed page number or stain as sufficient variety. +- Compose in defined writing and illustration areas. Keep decorative art outside puzzle clues, text, navigation, and touch targets. +- Render readable text in the app, not baked into generated images. This allows narration, translation, larger fonts, and screen-reader access. +- Let illustrations invite inspection, but keep the main story readable without finding tiny hidden targets. +- Use small motions sparingly: a flap opening, a ribbon moving, or a lantern warming after a discovery. The notebook should also work with motion and sound disabled. +- Reuse a few base paper textures and layout families to keep production manageable. Give each leaf its own small illustration and writing rather than generating a whole new background for every screen. +- Keep each page’s design stable across visits. Do not randomly rearrange objects that the player has learned to recognise. + +**Ready when:** six consecutive prototype leaves are recognisably different, all remain part of the same notebook, and a reader can explain what each picture contributes to the story. + +## Phase 4 — connect discoveries into a story + +Expand the twelve puzzle beats into a proposed 30–40-leaf first notebook. Confirm the exact count after editing and accessibility pagination. Reading and exploration leaves should appear between puzzles, so another grid is not the only reward for finishing one. + +Chapter direction: + +| Chapter | Emotional purpose | Visual language | Discoveries to develop | +| --- | --- | --- | --- | +| I · The keeper’s cottage | Establish affection and familiar routines | Warm ink, cloth repairs, indoor sketches | A dedication, a lantern drawing, the key’s label, a tucked-away letter | +| II · Across the tide | Build curiosity and a sense of distance | Sea-blue washes, maps, tide marks | Mara’s crossing notes, a boat sketch, bridge annotations, the meaning of the bell signal | +| III · The last light | Bring earlier details together through shared work | Mechanical pencil drawings, glass, amber light | A repair diagram, the lens, Mara’s reply, the grandchild’s final entry | + +Story principles: + +- Establish a small question before a discovery and answer or deepen it afterward. Who repaired the lantern? Why does Mara ring twice? What did she leave under the floorboard? +- Revisit earlier details with new meaning. A casual bell note in the cottage can pay off when someone answers from the hill. +- Write some entries in Gran’s own voice, including ordinary details rather than only wisdom and instructions. +- Include calm pages with no task at all. Listening to a memory or looking at a sketch is a valid part of play. +- Allow free exploration of discovered pages and optional leaves within the current chapter. Use clear bookmarks for the main thread, rather than a maze of locks. +- Keep puzzles tied to the scene and reward them with a picture, a memory, or a change in understanding. Avoid presenting them as unrelated tolls between paragraphs. +- Prototype a story-first option: offer a guided solution or a way to continue the narrative when a player is stuck. Preserve the unsolved puzzle for later, and distinguish viewed story progress from solved-puzzle progress. +- Require neither a rewarded ad nor a streak to read an entry, hear its narration, or reach the next essential story beat. + +**Ready when:** someone can enjoy the cottage chapter primarily as a story, describe their relationship with Mara, and identify a reason to explore the next chapter beyond receiving another puzzle. + +## Phase 5 — make the notebook rewarding to revisit + +After the first chapter proves the direction: + +- Add ribbon bookmarks, a pocket of collected scraps, and a small illustrated island index linking to discovered memories. +- Let players replay narration and re-examine recovered objects without replaying puzzles or seeing repeated ads. +- Add optional margin notes that become understandable after later discoveries. Keep the original writing intact, so the change feels like an annotation rather than a rewritten memory. +- Consider very quiet optional ambience: sea outside the window, a kettle, or a lighthouse mechanism. Give ambience, narration, and page sounds separate controls, and lower ambience during speech. +- Make daily puzzles feel like spare pages at the back of the book. Keep them available without interrupting the authored story or requiring daily attendance. +- Offer optional puzzle replay with its own state, preserving the notebook’s discovered memories and completion history. +- Consider another notebook only after this one has a satisfying ending. Reuse the page system rather than committing to a continuous stream of new story content. + +## Monetization that respects exploration + +Keep optional rewarded hints. Review moving campaign interstitials out of the story flow: the preferred direction is to keep diary reading, narration, page turns, and re-reading uninterrupted. Occasional ads can remain at natural breaks in classic practice. Assess the revenue tradeoff before a public release; do not turn every page into an ad opportunity. + +## Production approach + +Keep the first notebook finite, authored, bundled, and playable offline. Generated classic and daily puzzles provide replayability without continual campaign maintenance. + +Move toward stable page records instead of treating each puzzle level as an entire story unit. Proposed fields: + +`pageId`, `chapterId`, `type`, `speaker`, `text`, `illustrationAsset`, `layoutId`, `narrationText`, `puzzleId`, `discoveryId`, and `unlockCondition`. + +Store the current bookmark, viewed pages, discoveries, and puzzle solutions separately. Preserve existing `story_v1_…` puzzle keys and completion counts when migrating. Splitting a passage or adding an optional leaf must not erase an existing solution or mark an unseen entry as read. + +Create a page checklist for each authored leaf: its story purpose, unique visual detail, reading order, optional audio, interaction, and what it reveals. Maintain one art guide and an asset list with prompts and intended placement. Check every generated illustration in the real page layout before accepting it. + +## First implementation slice + +Build and review this sequence before producing the full notebook: + +1. A dedication leaf with Gran’s signature and optional narration. +2. A short cottage entry with a small illustration and listen control. +3. The existing match puzzle on its own leaf, with all essential controls visible. +4. A recovered-match illustration and a personal memory that rewards completion. +5. A folded note that the player opens without solving a puzzle. +6. A lantern sketch that raises a question answered on a later leaf. + +Use this slice to judge page turning, narration, visual variety, readability, and curiosity together. Expand the rest of the story only after these leaves feel worth exploring in their own right. + +## Review questions + +- Does each page give the reader a reason to look, listen, or turn the next leaf? +- Can the player describe Mara as a person, beyond knowing that she gives puzzle instructions? +- Are the picture and interaction relevant to the passage, or merely decorative? +- Is the notebook comfortable with sound off, larger text, reduced motion, or a screen reader? +- Can players return to a favourite memory and resume their current place without friction? +- Do puzzles support discovery without becoming compulsory obstacles to enjoying the story? + +For optional playtests, collect answers and observations with the player’s knowledge. No analytics service or backend is required for this roadmap. diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..43ea133 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,26 @@ +plugins { id 'com.android.application' } +android { + namespace 'com.lumen.daily' + compileSdk 36 + defaultConfig { + applicationId 'com.lumen.daily' + minSdk 24 + targetSdk 36 + versionCode 8 + versionName '1.7' + manifestPlaceholders = [admobAppId: providers.gradleProperty('ADMOB_APP_ID').getOrElse('ca-app-pub-3940256099942544~3347511713')] + buildConfigField 'String', 'REWARDED_ID', '"' + providers.gradleProperty('ADMOB_REWARDED_ID').getOrElse('ca-app-pub-3940256099942544/5224354917') + '"' + buildConfigField 'String', 'INTERSTITIAL_ID', '"' + providers.gradleProperty('ADMOB_INTERSTITIAL_ID').getOrElse('ca-app-pub-3940256099942544/1033173712') + '"' + } + buildTypes { debug { if (providers.gradleProperty("qaBuild").getOrElse("false") == "true") applicationIdSuffix ".qa" } } + androidResources { noCompress += ['flac'] } + buildFeatures { buildConfig true } + compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17; coreLibraryDesugaringEnabled true } +} +dependencies { + implementation 'androidx.activity:activity:1.12.4' + implementation 'com.google.android.gms:play-services-ads:25.5.0' + implementation 'com.google.android.ump:user-messaging-platform:4.0.0' + coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.1.5' + testImplementation 'junit:junit:4.13.2' +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..d2fcb6a --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/com/lumen/daily/Ads.java b/app/src/main/java/com/lumen/daily/Ads.java new file mode 100644 index 0000000..27f987b --- /dev/null +++ b/app/src/main/java/com/lumen/daily/Ads.java @@ -0,0 +1,20 @@ +package com.lumen.daily; +import android.app.Activity; +import com.google.android.gms.ads.*; +import com.google.android.gms.ads.rewarded.*; +import com.google.android.gms.ads.interstitial.*; +import com.google.android.ump.*; +final class Ads { + final Activity activity; final ConsentInformation consent; + RewardedAd reward; InterstitialAd interstitial; boolean initialized, loadingReward, loadingInterstitial; long rewardAt, interstitialAt; + Ads(Activity a){activity=a;consent=UserMessagingPlatform.getConsentInformation(a);consent.requestConsentInfoUpdate(a,new ConsentRequestParameters.Builder().build(),()->UserMessagingPlatform.loadAndShowConsentFormIfRequired(a,e->start()),e->start());} + void start(){if(!consent.canRequestAds()||initialized)return;initialized=true;MobileAds.initialize(activity,s->activity.runOnUiThread(this::load));} + void load(){ + if(!consent.canRequestAds())return; + if(!loadingReward&&reward==null){loadingReward=true;RewardedAd.load(activity,BuildConfig.REWARDED_ID,new AdRequest.Builder().build(),new RewardedAdLoadCallback(){public void onAdLoaded(RewardedAd a){reward=a;rewardAt=android.os.SystemClock.elapsedRealtime();loadingReward=false;} public void onAdFailedToLoad(LoadAdError e){loadingReward=false;}});} + if(!loadingInterstitial&&interstitial==null){loadingInterstitial=true;InterstitialAd.load(activity,BuildConfig.INTERSTITIAL_ID,new AdRequest.Builder().build(),new InterstitialAdLoadCallback(){public void onAdLoaded(InterstitialAd a){interstitial=a;interstitialAt=android.os.SystemClock.elapsedRealtime();loadingInterstitial=false;} public void onAdFailedToLoad(LoadAdError e){loadingInterstitial=false;}});} + } + boolean hint(Runnable earned){if(android.os.SystemClock.elapsedRealtime()-rewardAt>3500000)reward=null;if(reward==null||!consent.canRequestAds()){load();return false;}RewardedAd a=reward;reward=null;a.setFullScreenContentCallback(new FullScreenContentCallback(){public void onAdDismissedFullScreenContent(){load();}public void onAdFailedToShowFullScreenContent(AdError e){load();}});a.show(activity,r->earned.run());return true;} + void between(Runnable next){if(android.os.SystemClock.elapsedRealtime()-interstitialAt>3500000)interstitial=null;if(interstitial==null||!consent.canRequestAds()){next.run();load();return;}InterstitialAd a=interstitial;interstitial=null;a.setFullScreenContentCallback(new FullScreenContentCallback(){public void onAdDismissedFullScreenContent(){next.run();load();}public void onAdFailedToShowFullScreenContent(AdError e){next.run();load();}});a.show(activity);} + void privacy(){if(consent.getPrivacyOptionsRequirementStatus()==ConsentInformation.PrivacyOptionsRequirementStatus.REQUIRED)UserMessagingPlatform.showPrivacyOptionsForm(activity,e->{});else new android.app.AlertDialog.Builder(activity).setMessage("No advertising privacy options are currently required for your region. Game progress stays on this device. Google advertising services may process device and ad interaction data when ads are available.").setPositiveButton("OK",null).show();} +} diff --git a/app/src/main/java/com/lumen/daily/Campaign.java b/app/src/main/java/com/lumen/daily/Campaign.java new file mode 100644 index 0000000..cf67ab1 --- /dev/null +++ b/app/src/main/java/com/lumen/daily/Campaign.java @@ -0,0 +1,119 @@ +package com.lumen.daily; + +/** An offline, authored story. The pictures are the actual puzzle solutions. */ +public final class Campaign { + public static final String TITLE = "The Last Light"; + public static final String PREMISE = "The storm has passed, but the island is still dark. In your grandmother Mara’s notebook, you find a promise: no one comes home to an unlit shore. Recover what the storm scattered. Bring the lighthouse back to life."; + + public static final class Level { + public final String chapter, title, object, before, after; + public final int[] picture; + Level(String chapter, String title, String object, String before, String after, String... rows) { + this.chapter = chapter; this.title = title; this.object = object; + this.before = before; this.after = after; + if (rows.length != 7) throw new IllegalArgumentException("Picture must have seven rows"); + picture = new int[49]; + for (int r = 0; r < 7; r++) { + if (rows[r].length() != 7) throw new IllegalArgumentException("Picture must have seven columns"); + for (int c = 0; c < 7; c++) picture[r * 7 + c] = rows[r].charAt(c) == '1' ? 1 : 0; + } + } + } + + public static final Level[] LEVELS = { + new Level("I · The keeper’s cottage", "A spark in the drawer", "A match", + "You find Mara’s cottage with its windows shuttered. On the table is her notebook: ‘Start with one small light.’ The first page is water-stained. Restore its pattern.", + "A dry match, hidden in a tin. You strike it against the hearth. For a moment, the cottage feels like it remembers you.", + "0011000", "0111100", "0011000", "0001000", "0001000", "0001000", "0001000"), + new Level("I · The keeper’s cottage", "Something to carry the flame", "The lantern", + "A small flame will not survive the wind. Mara’s next page shows what she carried on her evening rounds.", + "The lantern is soot-black but sound. Its warm circle of light reaches the cottage door. Beneath the handle, Mara has scratched your initials.", + "0011100", "0010100", "0111110", "0100010", "0101010", "0100010", "0111110"), + new Level("I · The keeper’s cottage", "Under the loose floorboard", "The brass key", + "‘Some clues belong to more than one place,’ Mara wrote. Compare the overlapping areas on this page; a shared cell counts in both. A loose floorboard waits by the door.", + "A brass key turns up beneath the board. The tag reads ‘harbour store’. Someone prepared for a journey and never quite made it out of the cottage.", + "0011100", "0100010", "0100010", "0011100", "0001000", "0001100", "0001000"), + new Level("I · The keeper’s cottage", "A direction in the dark", "Mara’s compass", + "The lane has vanished beneath fallen branches. One last page in the cottage points you towards the harbour. Use what the areas share to work out what lies outside them.", + "The compass needle settles towards the sea. Tucked inside its lid is a note: ‘When the path disappears, keep your bearings.’ You step into the rain.", + "0001000", "0011100", "0101010", "1111111", "0101010", "0011100", "0001000"), + new Level("II · Across the tide", "At the water’s edge", "The little boat", + "The tide has covered the causeway. A shape knocks gently against the harbour steps. Mara’s notebook has a page for this crossing too.", + "The little boat is still tied fast. You bail out the rainwater, set the lantern in the bow, and push away from the steps.", + "0001000", "0001100", "0001110", "0001000", "1111111", "0111110", "1000001"), + new Level("II · Across the tide", "What holds us steady", "The anchor", + "The current tugs you towards the outer rocks. Something heavy is tangled beneath the seat. The pattern tells you what to reach for.", + "The anchor catches. The boat swings into calmer water. In the pause, you hear a bell somewhere beyond the fog.", + "0011100", "0010100", "0011100", "0001000", "1001001", "0101010", "0011100"), + new Level("II · Across the tide", "The old crossing", "The stone bridge", + "You land beneath the lighthouse hill. The old crossing is hidden by reeds. Mara marked its outline long before the storm.", + "The bridge is intact. You cross with the lantern held high. On the far bank, a fresh bootprint tells you someone else has passed this way.", + "0000000", "0111110", "1100011", "1000001", "1000001", "1111111", "0000000"), + new Level("II · Across the tide", "An answer through the fog", "The harbour bell", + "A rope hangs from a timber frame. The bell above it has fallen silent. Restore the pattern before you call out across the water.", + "One clear note travels into the fog. Two notes answer from the hill. Someone is waiting at the lighthouse.", + "0001000", "0011100", "0010100", "0100010", "0100010", "1111111", "0001000"), + new Level("III · The last light", "Inside the turning room", "The missing gear", + "Mara opens the lighthouse door. ‘I knew you’d find the notebook,’ she says. The storm stopped the turning mechanism. Together, you lay out its scattered parts.", + "The missing gear slips into place. You turn the handle; the mechanism answers with a familiar, steady ticking. Mara smiles without looking up.", + "0010100", "0111110", "1100011", "0101010", "1100011", "0111110", "0010100"), + new Level("III · The last light", "A circle of glass", "The beacon lens", + "The great lens is clouded with salt. Mara holds the lantern while you work. The areas overlap like the rings in the glass; compare them carefully.", + "You wipe the last salt from the lens. The lantern’s tiny flame stretches into a bright arc across the walls. Everything is ready.", + "0011100", "0100010", "1001001", "1001101", "1001001", "0100010", "0011100"), + new Level("III · The last light", "No unlit shore", "The lighthouse", + "Mara gives you the handle. Below the windows, the island lies dark. This is the pattern all the other pages were leading towards.", + "The beacon turns. Its light sweeps the harbour, the bridge, the little boat. Far offshore, a ship sounds its horn. The island has its light again.", + "0001000", "0011100", "1111111", "0011100", "0010100", "0110110", "1111111"), + new Level("III · The last light", "A light in the window", "Home", + "Dawn finds you walking back with Mara. There is one blank page at the end of the notebook. ‘That one is yours,’ she says.", + "You light the cottage window. Mara puts the kettle on. Beneath your new drawing, you write: ‘No one comes home to an unlit shore.’ The notebook closes. Your watch has begun.", + "0001000", "0011100", "0111110", "1111111", "0100010", "0101010", "0111110") + }; + + private static final String[] CLUES = { + "", + "1,5,9,11", + "", + "15,36", + "", + "11,36,40", + "", + "2", + "9,24", + "7,13,36,40", + "", + "" + }; + private static final String[] AREAS = { + "", + "", + "1,2,4,3;3,2,2,4;3,2,2,3", + "1,3,2,2;3,2,3,3;2,0,3,5", + "0,3,5,2;3,1,3,3;2,2,4,4", + "2,3,3,3;2,1,4,2;1,1,3,4", + "2,1,3,5;0,2,5,3;2,3,2,2", + "3,2,3,3;2,0,4,4;0,3,5,2", + "2,3,3,3;1,3,5,3;1,2,4,3", + "1,2,5,3;2,3,3,2;2,2,3,2", + "1,3,4,2;0,3,2,2;2,2,4,2", + "0,1,6,2;2,3,4,3;0,2,4,3" + }; + + public static Puzzle puzzle(int index) { + if (index < 0 || index >= LEVELS.length) throw new IllegalArgumentException("Unknown chapter"); + Puzzle puzzle = new Puzzle(7, LEVELS[index].picture); + if (!CLUES[index].isEmpty()) for (String cell : CLUES[index].split(",")) puzzle.given[Integer.parseInt(cell)] = true; + if (!AREAS[index].isEmpty()) { + String[] regions = AREAS[index].split(";"); + for (int i = 0; i < regions.length; i++) { + String[] values = regions[i].split(","); + puzzle.regions.add(new Puzzle.Region("" + (char) ('A' + i), Integer.parseInt(values[0]), Integer.parseInt(values[1]), Integer.parseInt(values[2]), Integer.parseInt(values[3]))); + } + } + return puzzle; + } + + public static int unlocked(int stored) { return Math.max(0, Math.min(LEVELS.length - 1, stored)); } + private Campaign() {} +} diff --git a/app/src/main/java/com/lumen/daily/DailyStreak.java b/app/src/main/java/com/lumen/daily/DailyStreak.java new file mode 100644 index 0000000..2f9e401 --- /dev/null +++ b/app/src/main/java/com/lumen/daily/DailyStreak.java @@ -0,0 +1,6 @@ +package com.lumen.daily; +/** Local calendar-day streak rules; replaying a day cannot increment a streak. */ +final class DailyStreak { + static int visible(long last, int count, long today){return last>=today-1?count:0;} + static int afterCompletion(long last, int count, long day){return day<=last?count:last==day-1?count+1:1;} +} diff --git a/app/src/main/java/com/lumen/daily/Difficulty.java b/app/src/main/java/com/lumen/daily/Difficulty.java new file mode 100644 index 0000000..fb8f1bd --- /dev/null +++ b/app/src/main/java/com/lumen/daily/Difficulty.java @@ -0,0 +1,29 @@ +package com.lumen.daily; + +public enum Difficulty { + EASY("Easy", "Short deductions. A gentle place to begin."), + MEDIUM("Medium", "Link deductions across rows and columns."), + HARD("Hard", "Follow longer chains to uncover the pattern."); + + public final String label; + public final String description; + + Difficulty(String label, String description) { + this.label = label; + this.description = description; + } + + public static Difficulty fromRounds(int rounds) { + if (rounds <= 2) return EASY; + if (rounds <= 4) return MEDIUM; + return HARD; + } + + public static Difficulty fromStored(String value) { + try { + return valueOf(value); + } catch (IllegalArgumentException e) { + return EASY; + } + } +} diff --git a/app/src/main/java/com/lumen/daily/HomeArtwork.java b/app/src/main/java/com/lumen/daily/HomeArtwork.java new file mode 100644 index 0000000..ef9742d --- /dev/null +++ b/app/src/main/java/com/lumen/daily/HomeArtwork.java @@ -0,0 +1,54 @@ +package com.lumen.daily; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.view.Gravity; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +/** Original watercolour assets with crisp native handwriting on the cover label. */ +final class HomeArtwork { + private static Bitmap harbour, cover; + private static Bitmap load(Context context, int resource) { + BitmapFactory.Options options=new BitmapFactory.Options(); options.inScaled=false; options.inSampleSize=2; + return BitmapFactory.decodeResource(context.getResources(),resource,options); + } + static ImageView harbour(Context context) { + if(harbour==null)harbour=load(context,R.drawable.home_harbour); + ImageView image=new ImageView(context);image.setImageBitmap(harbour);image.setScaleType(ImageView.ScaleType.FIT_CENTER); + image.setContentDescription("Watercolour of the island at dusk, the lighthouse beam crossing the bay to Gran’s cottage."); + return image; + } + static final class Cover extends ViewGroup { + private final ImageView picture; + private final TextView label; + private int imageLeft,imageTop,imageWidth,imageHeight; + Cover(Context context) { + super(context); + if(cover==null)cover=load(context,R.drawable.home_notebook_cover); + picture=new ImageView(context);picture.setImageBitmap(cover);picture.setScaleType(ImageView.ScaleType.FIT_CENTER); + picture.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO); + label=new TextView(context);label.setText("Mara’s\nisland notebook");label.setTypeface(JournalArt.HAND);label.setTextSize(25); + label.setRotation(-2.5f); + label.setTextColor(JournalArt.INK);label.setGravity(Gravity.CENTER);label.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO); + addView(picture);addView(label); + } + @Override protected void onMeasure(int widthSpec,int heightSpec) { + int w=MeasureSpec.getSize(widthSpec),h=MeasureSpec.getSize(heightSpec);setMeasuredDimension(w,h); + float scale=Math.min(w/(float)cover.getWidth(),h/(float)cover.getHeight()); + imageWidth=Math.round(cover.getWidth()*scale);imageHeight=Math.round(cover.getHeight()*scale); + imageLeft=(w-imageWidth)/2;imageTop=(h-imageHeight)/2; + picture.measure(MeasureSpec.makeMeasureSpec(w,MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec(h,MeasureSpec.EXACTLY)); + label.measure(MeasureSpec.makeMeasureSpec(Math.round(imageWidth*.49f),MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(Math.round(imageHeight*.34f),MeasureSpec.EXACTLY)); + } + @Override protected void onLayout(boolean changed,int left,int top,int right,int bottom) { + picture.layout(0,0,getWidth(),getHeight()); + int x=imageLeft+Math.round(imageWidth*.27f),y=imageTop+Math.round(imageHeight*.32f); + label.layout(x,y,x+label.getMeasuredWidth(),y+label.getMeasuredHeight()); + } + } + private HomeArtwork(){} +} diff --git a/app/src/main/java/com/lumen/daily/JournalArt.java b/app/src/main/java/com/lumen/daily/JournalArt.java new file mode 100644 index 0000000..b8244c2 --- /dev/null +++ b/app/src/main/java/com/lumen/daily/JournalArt.java @@ -0,0 +1,185 @@ +package com.lumen.daily; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.ColorFilter; +import android.graphics.LinearGradient; +import android.graphics.Paint; +import android.graphics.Path; +import android.graphics.PixelFormat; +import android.graphics.Rect; +import android.graphics.Shader; +import android.graphics.Typeface; +import android.graphics.drawable.Drawable; +import android.view.View; + +/** Small, offline illustrations drawn at device resolution, without image downloads. */ +final class JournalArt { + static final int PAPER = Color.rgb(243, 231, 204); + static final int INK = Color.rgb(57, 65, 63); + static final int BLUE = Color.rgb(39, 73, 86); + static final int FADED = Color.rgb(112, 96, 75); + static final Typeface HAND = Typeface.create("cursive", Typeface.NORMAL); + static final Typeface SERIF = Typeface.create("serif", Typeface.NORMAL); + + static final class Paper extends Drawable { + private final Paint paint = new Paint(3); + private final float density; + private final boolean ruled; + Paper(Context context, boolean ruled) { density = context.getResources().getDisplayMetrics().density; this.ruled = ruled; } + @Override public void draw(Canvas canvas) { + Rect b = getBounds(); + paint.setShader(new LinearGradient(b.left, 0, b.right, 0, + new int[]{0xffd2bd94, PAPER, 0xfff8efd9, 0xffe0cda8}, new float[]{0, .035f, .9f, 1}, Shader.TileMode.CLAMP)); + canvas.drawRect(b, paint); paint.setShader(null); + Rect clip = canvas.getClipBounds(); + // Stable paper fibres, limited to the visible page. + paint.setColor(0x166b583d); paint.setStrokeWidth(density * .45f); + int step = Math.max(4, (int)(density * 6)); + for (int y = Math.max(0, clip.top / step * step); y < Math.min(b.bottom, clip.bottom) + step; y += step) { + for (int x = b.left + step; x < b.right; x += step * 3) { + int offset = Math.floorMod(x * 73 + y * 19, step * 2); + canvas.drawLine(x + offset, y, x + offset + density * 1.8f, y + density * .5f, paint); + } + } + if (ruled) { + paint.setColor(0x226b8990); paint.setStrokeWidth(density * .5f); + float spacing = density * 32; + float start = (float)Math.floor(clip.top / spacing) * spacing; + for (float y = start; y < Math.min(b.bottom, clip.bottom); y += spacing) canvas.drawLine(density * 24, y, b.right - density * 13, y, paint); + paint.setColor(0x458f5543); canvas.drawLine(density * 20, b.top, density * 20, b.bottom, paint); + } + paint.setColor(0x465c4935); paint.setStrokeWidth(density * .7f); + canvas.drawLine(b.right - density * 4, b.top, b.right - density * 4, b.bottom, paint); + canvas.drawLine(density * 8, b.top, density * 8, b.bottom, paint); + paint.setColor(0xffbba77f); + for (float y = density * 54; y < b.bottom; y += density * 138) { + if (y > clip.top - density * 20 && y < clip.bottom + density * 20) { + canvas.drawOval(density * 5, y, density * 11, y + density * 5, paint); + paint.setColor(0xfff6ecd4); paint.setStrokeWidth(density); + canvas.drawLine(density * 7, y - density * 8, density * 9, y + density * 14, paint); + paint.setColor(0xffbba77f); + } + } + } + @Override public void setAlpha(int alpha) {} + @Override public void setColorFilter(ColorFilter filter) {} + @Override public int getOpacity() { return PixelFormat.OPAQUE; } + } + + /** A pencil rule under a handwritten action, without a floating button card. */ + static final class InkLine extends Drawable { + private final Paint paint = new Paint(3); + private final int color; + private final float density; + InkLine(Context context, int color) { this.color = color; density = context.getResources().getDisplayMetrics().density; } + @Override public void draw(Canvas canvas) { + Rect bounds = getBounds(); + paint.setColor(color); paint.setAlpha(105); paint.setStrokeWidth(density * .65f); + canvas.drawLine(bounds.left + density * 2, bounds.bottom - density * 2, + bounds.right - density * 5, bounds.bottom - density * 3, paint); + } + @Override public void setAlpha(int alpha) { paint.setAlpha(alpha); } + @Override public void setColorFilter(ColorFilter filter) { paint.setColorFilter(filter); } + @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } + } + + static final class Cover extends View { + private final Paint p = new Paint(3); + Cover(Context context) { super(context); setContentDescription("Mara’s weathered blue cloth notebook, with a handwritten label, stitched spine and a pressed sprig of heather."); } + @Override protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + float w = Math.min(getWidth() - 12, getHeight() * 1.72f), h = getHeight() - 18; + float x = (getWidth() - w) / 2, y = 4; + canvas.save(); canvas.translate(x, y); + p.setColor(0x25583e27); canvas.drawRoundRect(6, 10, w + 4, h + 8, 8, 8, p); + p.setColor(0xffd1bd93); canvas.drawRoundRect(7, 5, w, h + 3, 7, 7, p); + p.setColor(0xffe8d8b6); + for (int i = 0; i < 3; i++) canvas.drawLine(12, h - 2 + i * 2, w - 4, h - 2 + i * 2, p); + p.setColor(BLUE); canvas.drawRoundRect(0, 0, w - 3, h - 3, 9, 9, p); + canvas.save(); canvas.clipRect(0, 0, w - 3, h - 3); + p.setStrokeWidth(.6f); p.setColor(0x247e9b9d); + for (float line = 0; line < w; line += 5) canvas.drawLine(line, 0, line, h, p); + for (float line = 0; line < h; line += 5) canvas.drawLine(0, line, w, line, p); + canvas.restore(); + p.setShader(new LinearGradient(0, 0, w * .08f, 0, 0xff162f3a, 0xff395b65, Shader.TileMode.CLAMP)); + canvas.drawRect(0, 5, w * .065f, h - 8, p); p.setShader(null); + p.setColor(0xff9b9276); p.setStrokeWidth(1.5f); + for (float stitch = 12; stitch < h - 12; stitch += 14) canvas.drawLine(w * .075f, stitch, w * .075f, stitch + 5, p); + p.setColor(0x779eaf9e); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(1); + canvas.drawRoundRect(w * .11f, h * .07f, w * .93f, h * .92f, 4, 4, p); p.setStyle(Paint.Style.FILL); + // An old label, slightly crooked rather than a digital card. + canvas.save(); canvas.rotate(-2, w * .47f, h * .49f); + p.setColor(0x32533b27); canvas.drawRect(w * .18f + 2, h * .18f + 3, w * .78f + 2, h * .76f + 3, p); + p.setColor(0xffeaddbc); canvas.drawRect(w * .18f, h * .18f, w * .78f, h * .76f, p); + p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(1); p.setColor(0xffae9c77); + canvas.drawRect(w * .20f, h * .21f, w * .76f, h * .73f, p); p.setStyle(Paint.Style.FILL); + p.setColor(INK); p.setTextAlign(Paint.Align.CENTER); p.setTypeface(HAND); p.setTextSize(h * .17f); + canvas.drawText("Mara’s", w * .48f, h * .41f, p); + p.setTypeface(SERIF); p.setTextSize(h * .095f); canvas.drawText("island notebook", w * .48f, h * .55f, p); + p.setTypeface(HAND); p.setTextSize(h * .071f); p.setColor(FADED); canvas.drawText("a few things worth keeping", w * .48f, h * .66f, p); + canvas.restore(); + // Faded ribbon poking out of the lower edge. + p.setColor(0xffa35c48); Path ribbon = new Path(); ribbon.moveTo(w * .83f, h * .68f); ribbon.lineTo(w * .89f, h * .68f); ribbon.lineTo(w * .89f, h + 7); ribbon.lineTo(w * .86f, h - 1); ribbon.lineTo(w * .83f, h + 7); ribbon.close(); canvas.drawPath(ribbon, p); + canvas.save(); canvas.translate(w * .80f, h * .20f); canvas.scale(h / 210, h / 210); flower(canvas, p); canvas.restore(); + p.setTextAlign(Paint.Align.LEFT); canvas.restore(); + } + } + + static final class Flower extends View { + private final Paint p = new Paint(3); + Flower(Context context) { super(context); setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); } + @Override protected void onDraw(Canvas canvas) { + float scale = getHeight() / 150f; + canvas.save(); canvas.translate(getWidth() - 80 * scale, 0); canvas.scale(scale, scale); flower(canvas, p); canvas.restore(); + p.setColor(0x586f7154); p.setStrokeWidth(1); + canvas.drawLine(0, getHeight() * .7f, getWidth() - 65 * scale, getHeight() * .7f, p); + } + } + + private static void flower(Canvas c, Paint p) { + p.setColor(0xff68765c); p.setStrokeWidth(2.2f); p.setStyle(Paint.Style.STROKE); + Path stem = new Path(); stem.moveTo(12, 137); stem.cubicTo(48, 100, 32, 58, 49, 6); c.drawPath(stem, p); + p.setStyle(Paint.Style.FILL); + for (int i = 0; i < 7; i++) { + float y = 23 + i * 13, x = 47 - i * 2; + p.setColor(i < 4 ? 0xff937f86 : 0xffa59598); + c.save(); c.rotate(i % 2 == 0 ? -35 : 35, x, y); + c.drawOval(x - 9, y - 5, x + 1, y + 5, p); c.drawOval(x + 1, y - 8, x + 10, y + 1, p); c.restore(); + } + p.setColor(0xff7e8764); c.save(); c.rotate(-35, 29, 112); c.drawOval(14, 107, 39, 115, p); c.restore(); + p.setColor(0x99c5aa77); c.drawRect(12, 118, 52, 132, p); + } + + static final class Harbour extends View { + private final Paint p = new Paint(3); + Harbour(Context context) { super(context); setContentDescription("Evening on Mara’s island: a cottage window and a lighthouse beam above the sea."); } + @Override protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + canvas.save(); canvas.scale(getWidth() / 600f, getHeight() / 200f); + p.setShader(new LinearGradient(0, 0, 0, 200, new int[]{0xff243f50, 0xff5b7b83, 0xffbbac8f}, null, Shader.TileMode.CLAMP)); + canvas.drawRect(0, 0, 600, 200, p); p.setShader(null); + p.setColor(0xffe5d6aa); canvas.drawCircle(111, 37, 10, p); + p.setColor(0xffe9dcb4); for (int i = 0; i < 12; i++) canvas.drawCircle(25 + (i * 71) % 550, 13 + (i * 19) % 65, i % 3 == 0 ? 1.1f : .6f, p); + p.setColor(0xff486772); canvas.drawRect(0, 118, 600, 200, p); + p.setStrokeWidth(.7f); p.setColor(0x686f9698); + for (int i = 0; i < 16; i++) canvas.drawLine((i * 47) % 600, 128 + i * 4, (i * 47) % 600 + 40, 128 + i * 4, p); + p.setColor(0xff233e42); Path land = new Path(); land.moveTo(280, 200); land.cubicTo(330, 150, 375, 166, 408, 127); land.cubicTo(460, 103, 503, 156, 600, 140); land.lineTo(600, 200); land.close(); canvas.drawPath(land, p); + p.setShader(new LinearGradient(430, 78, 80, 91, 0x99f2d88e, 0x00f2d88e, Shader.TileMode.CLAMP)); + Path beam = new Path(); beam.moveTo(434, 75); beam.lineTo(35, 44); beam.lineTo(35, 110); beam.close(); canvas.drawPath(beam, p); p.setShader(null); + p.setColor(0xffe6dcc1); Path tower = new Path(); tower.moveTo(426, 89); tower.lineTo(443, 89); tower.lineTo(451, 136); tower.lineTo(419, 136); tower.close(); canvas.drawPath(tower, p); + p.setColor(0xff9c5b43); canvas.drawRect(422, 104, 448, 112, p); + p.setColor(0xffeac577); canvas.drawRect(424, 72, 445, 84, p); + p.setColor(0xff273f47); canvas.drawRect(419, 84, 450, 89, p); Path roof = new Path(); roof.moveTo(419, 72); roof.lineTo(435, 61); roof.lineTo(450, 72); roof.close(); canvas.drawPath(roof, p); + canvas.drawRect(431, 121, 439, 136, p); + p.setColor(0xff927a5c); canvas.drawRect(519, 142, 561, 166, p); + p.setColor(0xff263f42); Path cottage = new Path(); cottage.moveTo(513, 143); cottage.lineTo(541, 123); cottage.lineTo(567, 143); cottage.close(); canvas.drawPath(cottage, p); + p.setColor(0xffe7bf70); canvas.drawRect(529, 148, 537, 157, p); canvas.drawRect(545, 148, 553, 157, p); + p.setColor(0xff203c40); Path front = new Path(); front.moveTo(0, 182); front.cubicTo(90, 158, 175, 175, 255, 200); front.lineTo(0, 200); front.close(); canvas.drawPath(front, p); + canvas.restore(); + } + } + + private JournalArt() {} +} diff --git a/app/src/main/java/com/lumen/daily/LogicSolver.java b/app/src/main/java/com/lumen/daily/LogicSolver.java new file mode 100644 index 0000000..968ebfc --- /dev/null +++ b/app/src/main/java/com/lumen/daily/LogicSolver.java @@ -0,0 +1,181 @@ +package com.lumen.daily; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** Count constraints, including overlapping areas. Does not know the hidden picture. */ +public final class LogicSolver { + public static final class Constraint { + public final int[] cells; + public final int total; + public final String name; + public Constraint(int[] cells, int total) { + this(cells,total,"Clue"); + } + public Constraint(int[] cells,int total,String name) { + this.name = name; + this.cells = cells.clone(); + this.total = total; + } + } + + public static final class Analysis { + public final boolean solved; + public final int areaDeductions; + public final int[] cells; + Analysis(boolean solved, int areaDeductions, int[] cells) { + this.solved = solved; + this.areaDeductions = areaDeductions; + this.cells = cells.clone(); + } + } + + private final int cellCount; + private final List constraints; + private final int[] degree; + + public LogicSolver(int cellCount, List constraints) { + this.cellCount = cellCount; + this.constraints = new ArrayList<>(constraints); + degree = new int[cellCount]; + for (Constraint c : constraints) for (int i : c.cells) degree[i]++; + } + + private int remaining(Constraint c, int[] known) { + int total = c.total; + for (int i : c.cells) if (known[i] == 1) total--; + return total; + } + + private int unknown(Constraint c, int[] known) { + int count = 0; + for (int i : c.cells) if (known[i] < 0) count++; + return count; + } + + /** Returns -1 for a contradiction, otherwise number of newly fixed cells. */ + private int singles(int[] known) { + int changes = 0; + for (Constraint c : constraints) { + int need = remaining(c, known), count = unknown(c, known); + if (need < 0 || need > count) return -1; + if (count == 0 || (need != 0 && need != count)) continue; + for (int i : c.cells) if (known[i] < 0) { + known[i] = need == 0 ? 0 : 1; + changes++; + } + } + return changes; + } + + private boolean contains(int[] cells, int index) { + for (int i : cells) if (i == index) return true; + return false; + } + + /** + * Subtract two overlapping constraints. Shared unknown cells cancel. + * If A-only minus B-only reaches a bound, those cells are all forced. + */ + private int differences(int[] known) { + int changes = 0; + for (int a = 0; a < constraints.size(); a++) { + Constraint first = constraints.get(a); + for (int b = a + 1; b < constraints.size(); b++) { + Constraint second = constraints.get(b); + int onlyA = 0, onlyB = 0; + for (int i : first.cells) if (known[i] < 0 && !contains(second.cells, i)) onlyA++; + for (int i : second.cells) if (known[i] < 0 && !contains(first.cells, i)) onlyB++; + int difference = remaining(first, known) - remaining(second, known); + if (difference > onlyA || difference < -onlyB) return -1; + if (onlyA + onlyB == 0 || (difference != onlyA && difference != -onlyB)) continue; + int valueA = difference == onlyA ? 1 : 0; + for (int i : first.cells) if (known[i] < 0 && !contains(second.cells, i)) { + known[i] = valueA; + changes++; + } + for (int i : second.cells) if (known[i] < 0 && !contains(first.cells, i)) { + known[i] = 1 - valueA; + changes++; + } + } + } + return changes; + } + + public static final class Hint { + public final int cell, value; + public final String explanation; + Hint(int cell, int value, String explanation) { + this.cell = cell; this.value = value; this.explanation = explanation; + } + } + + public Hint nextHint(int[] known) { + for (Constraint c : constraints) { + int need = remaining(c, known), count = unknown(c, known); + if (need < 0 || need > count) return null; + if (count == 0 || (need != 0 && need != count)) continue; + for (int cell : c.cells) if (known[cell] < 0) return new Hint(cell, need == 0 ? 0 : 1, + c.name + (need == 0 ? " already has all its lights. Every remaining cell in it must be crossed out." + : " needs " + need + " more lights and has exactly " + count + " empty cells. They must all be lit.")); + } + for (int a = 0; a < constraints.size(); a++) for (int b = a + 1; b < constraints.size(); b++) { + Constraint first = constraints.get(a), second = constraints.get(b); + int onlyA = 0, onlyB = 0; + for (int i : first.cells) if (known[i] < 0 && !contains(second.cells, i)) onlyA++; + for (int i : second.cells) if (known[i] < 0 && !contains(first.cells, i)) onlyB++; + int needA = remaining(first, known), needB = remaining(second, known), difference = needA - needB; + if (onlyA + onlyB == 0 || (difference != onlyA && difference != -onlyB)) continue; + int valueA = difference == onlyA ? 1 : 0; + String explanation = "Compare " + first.name + " (" + needA + " more lights) with " + second.name + + " (" + needB + " more). Shared empty cells cancel. The difference forces the cells outside their overlap."; + for (int i : first.cells) if (known[i] < 0 && !contains(second.cells, i)) return new Hint(i, valueA, explanation); + for (int i : second.cells) if (known[i] < 0 && !contains(first.cells, i)) return new Hint(i, 1 - valueA, explanation); + } + return null; + } + + public Analysis analyze(int[] initial, boolean useAreas) { + int[] known = initial.clone(); + int areaDeductions = 0; + while (true) { + int changed = singles(known); + if (changed < 0) return new Analysis(false, areaDeductions, known); + if (changed > 0) continue; + if (useAreas) { + changed = differences(known); + if (changed < 0) return new Analysis(false, areaDeductions, known); + if (changed > 0) { areaDeductions += changed; continue; } + } + for (int i : known) if (i < 0) return new Analysis(false, areaDeductions, known); + return new Analysis(true, areaDeductions, known); + } + } + + public int countSolutions(int[] initial) { return search(initial.clone()); } + + private int search(int[] known) { + int changed; + do { changed = singles(known); if (changed < 0) return 0; } while (changed > 0); + int choice = -1; + for (int i = 0; i < cellCount; i++) { + if (known[i] < 0 && (choice < 0 || degree[i] > degree[choice])) choice = i; + } + if (choice < 0) return 1; + int[] branch = known.clone(); + branch[choice] = 0; + int count = search(branch); + if (count >= 2) return 2; + known[choice] = 1; + return Math.min(2, count + search(known)); + } + + public static int[] initial(Puzzle puzzle) { + int[] known = new int[puzzle.solution.length]; + Arrays.fill(known, -1); + for (int i = 0; i < known.length; i++) if (puzzle.given[i]) known[i] = puzzle.solution[i]; + return known; + } +} diff --git a/app/src/main/java/com/lumen/daily/MainActivity.java b/app/src/main/java/com/lumen/daily/MainActivity.java new file mode 100644 index 0000000..2e3e732 --- /dev/null +++ b/app/src/main/java/com/lumen/daily/MainActivity.java @@ -0,0 +1,851 @@ +package com.lumen.daily; + +import androidx.activity.ComponentActivity; +import androidx.activity.OnBackPressedCallback; +import android.app.AlertDialog; +import android.content.SharedPreferences; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Rect; +import android.graphics.Typeface; +import android.graphics.drawable.GradientDrawable; +import android.os.Bundle; +import android.view.MotionEvent; +import android.view.View; +import android.view.accessibility.AccessibilityEvent; +import android.view.accessibility.AccessibilityNodeInfo; +import android.view.accessibility.AccessibilityNodeProvider; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.Space; +import android.widget.TextView; +import android.widget.Toast; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +public class MainActivity extends ComponentActivity { + private static final int BG = JournalArt.PAPER; + private static final int INK = JournalArt.INK; + private static final int GREEN = JournalArt.BLUE; + private static final int MUTED = Color.rgb(111, 98, 79); + private static final int GOLD = Color.rgb(224, 181, 104); + private static final int AREA = Color.rgb(170, 91, 42); + private enum Mode { DAILY, CLASSIC, CAMPAIGN } + private enum Screen { HOME, MAP, BRIEFING, GAME, REVEAL, STORY } + + private SharedPreferences prefs; + private Ads ads; + private StoryNarrator narrator; + private int storyIndex; + private boolean inStoryPuzzle; + private final OnBackPressedCallback back = new OnBackPressedCallback(false) { + @Override public void handleOnBackPressed() { navigateBack(); } + }; + private LinearLayout root; + private Puzzle puzzle; + private int[] cells; + private boolean won, legacyPractice; + private Difficulty selected; + private int playingLevel, campaignIndex, selectedArea; + private String key; + private LocalDate date; + private Mode mode = Mode.CLASSIC; + private Screen screen = Screen.HOME; + private Board board; + private final ArrayDeque undo = new ArrayDeque<>(); + private final List