Initial commit: Lumen Android puzzle notebook v1.7

This commit is contained in:
Hadrian Burkhardt
2026-10-31 03:28:48 +01:00
commit 07e9253663
76 changed files with 3770 additions and 0 deletions
+26
View File
@@ -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'
}
+7
View File
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application android:theme="@style/AppTheme" android:label="Lumen" android:icon="@drawable/ic_launcher" android:allowBackup="false" android:fullBackupContent="false" android:dataExtractionRules="@xml/data_extraction_rules" android:supportsRtl="true">
<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="${admobAppId}"/>
<activity android:name=".MainActivity" android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity>
</application>
</manifest>
@@ -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();}
}
@@ -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() {}
}
@@ -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;}
}
@@ -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;
}
}
}
@@ -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(){}
}
@@ -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() {}
}
@@ -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<Constraint> constraints;
private final int[] degree;
public LogicSolver(int cellCount, List<Constraint> 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;
}
}
@@ -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<int[]> undo = new ArrayDeque<>();
private final List<Button> areaButtons = new ArrayList<>();
@Override public void onCreate(Bundle state) {
super.onCreate(state);
prefs = getSharedPreferences("lumen", 0);
selected = Difficulty.fromStored(prefs.getString("difficulty", "EASY"));
ads = new Ads(this);
narrator = new StoryNarrator(this, prefs);
getOnBackPressedDispatcher().addCallback(this, back);
if (state == null) {
if (prefs.getBoolean("notebook_open", false)) openNotebook(); else home();
return;
}
campaignIndex = Math.max(0, Math.min(Campaign.LEVELS.length - 1, state.getInt("campaign", 0)));
String savedScreen = state.getString("screen", "HOME");
if (savedScreen.equals("STORY")) showStory(StoryBook.indexOf(state.getString("storyPage", StoryBook.PAGES[0].id)));
else if (savedScreen.equals("MAP")) campaignMap();
else if (savedScreen.equals("BRIEFING")) briefing(campaignIndex);
else if (savedScreen.equals("REVEAL")) campaignReveal(campaignIndex);
else if (savedScreen.equals("GAME")) {
String savedMode = state.getString("mode", "CLASSIC");
if (savedMode.equals("CAMPAIGN")) startCampaign(campaignIndex);
else if (savedMode.equals("DAILY")) startDaily(LocalDate.parse(state.getString("date", LocalDate.now().toString())));
else startClassic(state.getBoolean("legacy", false), state.getInt("level", 1));
} else home();
}
@Override protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putString("screen", screen.name());
state.putString("storyPage", StoryBook.PAGES[storyIndex].id);
state.putString("mode", mode.name());
state.putInt("campaign", campaignIndex);
state.putInt("level", playingLevel);
state.putBoolean("legacy", legacyPractice);
if (date != null) state.putString("date", date.toString());
}
private void navigateBack() {
if (screen == Screen.STORY) { if (storyIndex > 0) turnStory(-1); else home(); return; }
if (screen == Screen.MAP) home();
else if (screen == Screen.BRIEFING || screen == Screen.REVEAL || mode == Mode.CAMPAIGN) campaignMap();
else home();
}
@Override protected void onPause() {
if (narrator != null) narrator.stop();
super.onPause();
}
@Override protected void onDestroy() {
if (narrator != null) narrator.close();
super.onDestroy();
}
private int accessibleCampaign() { return Math.max(campaignUnlocked(), Campaign.unlocked(prefs.getInt("story_access_level", 0))); }
private void openNotebook() {
showStory(StoryBook.indexOf(prefs.getString("notebook_last_page", StoryBook.PAGES[0].id)));
}
private void showStory(int index) {
index = Math.max(0, Math.min(StoryBook.PAGES.length - 1, index));
boolean retainPuzzle = inStoryPuzzle && index == 2 && puzzle != null && "story_v1_0".equals(key);
narrator.bind(null); narrator.stop();
storyIndex = index;
inStoryPuzzle = index == 2;
mode = Mode.CAMPAIGN;
campaignIndex = 0;
screen = Screen.STORY;
back.setEnabled(true);
board = null; areaButtons.clear();
if (inStoryPuzzle && !retainPuzzle) readPuzzle(Campaign.puzzle(0), campaignKey(0));
prefs.edit().putString("notebook_last_page", StoryBook.PAGES[index].id)
.putBoolean("notebook_open", true).putBoolean("viewed_" + StoryBook.PAGES[index].id, true).apply();
StoryNotebook notebook = new StoryNotebook(this, prefs, narrator, index, new StoryNotebook.Actions() {
@Override public void turn(int direction) { turnStory(direction); }
@Override public void contents() { storyContents(); }
@Override public void home() { MainActivity.this.home(); }
@Override public void refresh() { showStory(storyIndex); }
@Override public View puzzle() { return storyPuzzleView(); }
@Override public void continueCampaign() {
prefs.edit().putInt("story_access_level", Math.max(1, prefs.getInt("story_access_level", 0))).apply();
briefing(1);
}
});
setContentView(notebook.view);
}
private void turnStory(int direction) {
int next = StoryBook.turn(storyIndex, direction);
if (next == storyIndex) return;
if (storyIndex == 2 && direction > 0 && !won) {
narrator.stop();
new AlertDialog.Builder(this).setTitle("Leave a ribbon here?")
.setMessage("Your puzzle marks are saved. You can read the memory now and come back to solve the pattern whenever you like.")
.setNegativeButton("Keep solving", null).setPositiveButton("Read ahead", (dialog, which) -> {
prefs.edit().putBoolean("notebook_read_ahead", true).apply(); showStory(next);
}).show();
} else showStory(next);
}
private void storyContents() {
narrator.stop();
String[] titles = new String[StoryBook.PAGES.length + 3];
for (int i = 0; i < StoryBook.PAGES.length; i++) titles[i] = (i + 1) + " · " + StoryBook.PAGES[i].title;
titles[6] = "Return to my ribbon bookmark";
titles[7] = "All three chapters";
titles[8] = "Close the notebook";
new AlertDialog.Builder(this).setTitle("The cottage · opening leaves").setItems(titles, (dialog, which) -> {
if (which < StoryBook.PAGES.length) showStory(which);
else if (which == 6) showStory(StoryBook.indexOf(prefs.getString("notebook_manual_bookmark", StoryBook.PAGES[0].id)));
else if (which == 7) campaignMap();
else home();
}).setNegativeButton("Keep reading", null).show();
}
private View storyPuzzleView() {
LinearLayout body = new LinearLayout(this); body.setOrientation(LinearLayout.VERTICAL);
board = new Board();
body.addView(board, new LinearLayout.LayoutParams(-1, -2));
body.addView(text(won ? "Already restored. Turn the leaf to revisit the memory." : "Tap: light → cross → clear. Mark every cell.", 12, MUTED));
if (!won) {
LinearLayout controls = new LinearLayout(this);
for (int i = 0; i < 2; i++) {
final boolean isHint = i == 1;
Button control = new Button(this);
control.setAllCaps(false); control.setTextSize(20); control.setTypeface(JournalArt.HAND);
control.setTextColor(GREEN); control.setStateListAnimator(null); control.setElevation(0);
control.setBackground(new JournalArt.InkLine(this, MUTED));
control.setText(isHint ? prefs.getBoolean("hint_" + key, false) ? "Hint · rewarded ad" : "Hint · free" : "Undo a mark");
control.setOnClickListener(v -> { if (isHint) hint(); else if (!undo.isEmpty()) { cells = undo.pop(); save(); refreshBoard(); } });
controls.addView(control, new LinearLayout.LayoutParams(0, dp(48), 1));
}
body.addView(controls);
}
return body;
}
private int dp(float n) { return (int) (n * getResources().getDisplayMetrics().density + .5f); }
private TextView text(String value, int size, int color) {
TextView view = new TextView(this);
view.setText(value);
view.setTextSize(size <= 12 ? 14 : size);
view.setTextColor(color);
view.setTypeface(JournalArt.HAND);
view.setLineSpacing(dp(2), 1.07f);
view.setPadding(0, dp(5), 0, dp(5));
return view;
}
private void base(Screen nextScreen) {
if (narrator != null) { narrator.bind(null); narrator.stop(); }
inStoryPuzzle = false;
prefs.edit().putBoolean("notebook_open", false).apply();
screen = nextScreen;
back.setEnabled(screen != Screen.HOME);
board = null;
areaButtons.clear();
ScrollView scroll = new ScrollView(this);
scroll.setFillViewport(true);
root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
if (nextScreen != Screen.HOME) {
root.setPadding(dp(10), dp(12), dp(10), dp(20));
root.setBackgroundColor(Color.TRANSPARENT);
scroll.addView(root);
setContentView(new NotebookPage(this, scroll));
return;
}
root.setPadding(dp(30), dp(26), dp(24), dp(34));
root.setBackground(new JournalArt.Paper(this, nextScreen != Screen.HOME));
scroll.setBackgroundColor(Color.rgb(49, 67, 69));
scroll.addView(root);
scroll.setOnApplyWindowInsetsListener((v, insets) -> {
v.setPadding(insets.getSystemWindowInsetLeft() + dp(8), insets.getSystemWindowInsetTop(),
insets.getSystemWindowInsetRight() + dp(8), insets.getSystemWindowInsetBottom());
return insets;
});
setContentView(scroll);
}
private void gap(int size) { root.addView(new Space(this), new LinearLayout.LayoutParams(1, dp(size))); }
private GradientDrawable background(int color, int stroke) {
GradientDrawable result = new GradientDrawable();
result.setColor(color);
result.setCornerRadius(dp(4));
if (stroke != 0) result.setStroke(dp(2), stroke);
return result;
}
private Button button(String title, boolean primary, Runnable action) {
Button view = new Button(this);
view.setText(title);
view.setAllCaps(false);
view.setTextSize(22);
view.setTypeface(JournalArt.HAND);
view.setStateListAnimator(null);
view.setElevation(0);
view.setTextColor(primary ? Color.WHITE : GREEN);
view.setBackground(background(primary ? GREEN : Color.rgb(235, 220, 189), primary ? 0 : Color.rgb(178, 158, 124)));
view.setMinHeight(dp(56));
view.setPadding(dp(14), dp(8), dp(14), dp(8));
if (screen != Screen.HOME) {
view.setTypeface(JournalArt.HAND);
view.setTextSize(primary ? 25 : 22);
view.setTextColor(primary ? GREEN : INK);
view.setGravity(android.view.Gravity.START | android.view.Gravity.CENTER_VERTICAL);
view.setPadding(dp(3), dp(8), dp(3), dp(8));
view.setBackground(new JournalArt.InkLine(this, primary ? GREEN : MUTED));
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2);
params.setMargins(0, dp(8), 0, 0);
root.addView(view, params);
view.setOnClickListener(v -> action.run());
return view;
}
private TextView handwritten(String value) {
TextView note = text(value, 23, Color.rgb(111, 78, 57));
note.setTypeface(JournalArt.HAND);
note.setLineSpacing(dp(3), 1.08f);
return note;
}
private void flowerDivider() {
root.addView(new JournalArt.Flower(this), new LinearLayout.LayoutParams(-1, dp(58)));
}
private void folio(int index) {
TextView page = text("MARA’S NOTEBOOK / LEAF " + String.format(Locale.ROOT, "%02d", index + 1), 10, MUTED);
root.addView(page);
}
private String granNote(int index) {
String[] notes = {
"My dear, begin with the smallest light.\nThe rest will follow. — Gran",
"A little warmth goes a long way. — M.",
"I always kept a spare here.\nYou never know when it might be needed. — M.",
"Trust your bearings, love. — M.",
"Mind the tide. And take the lantern. — M.",
"There is no shame in stopping a while. — M.",
"The old stones will hold.\nThey have carried us before. — M.",
"If you need me, ring twice. — M.",
"Small things keep the great things turning. — M.",
"A soft cloth, patience, and a steady hand. — M.",
"No one comes home to an unlit shore. — M.",
"This last page is yours, my dear.\nWith all my love, Gran"
};
return notes[index];
}
private int streak() {
return DailyStreak.visible(prefs.getLong("lastDaily", -99999), prefs.getInt("streak", 0), LocalDate.now().toEpochDay());
}
private String campaignKey(int index) { return "story_v1_" + index; }
private boolean recovered(int index) { return prefs.getBoolean("done_" + campaignKey(index), false); }
private int campaignUnlocked() { return Campaign.unlocked(prefs.getInt("campaignUnlocked", 0)); }
private int recoveredCount() {
int count = 0;
for (int i = 0; i < Campaign.LEVELS.length; i++) if (recovered(i)) count++;
return count;
}
private void home() {
base(Screen.HOME);
root.addView(text("L U M E N / AN ISLAND STORY", 11, GREEN));
root.addView(text("A light to come\nhome to.", 36, INK));
root.addView(HomeArtwork.harbour(this), new LinearLayout.LayoutParams(-1, dp(220)));
gap(10);
root.addView(handwritten("Some things are worth keeping. — Gran"));
gap(8);
HomeArtwork.Cover cover = new HomeArtwork.Cover(this);
cover.setFocusable(true);
cover.setOnClickListener(v -> openNotebook());
cover.setContentDescription("Open Mara’s cloth-bound island notebook. " + recoveredCount() + " of 12 memories recovered.");
root.addView(cover, new LinearLayout.LayoutParams(-1, dp(218)));
button(recoveredCount() == Campaign.LEVELS.length ? "Open the keepsake notebook ✓" : "Open Mara’s notebook · " + recoveredCount() + " / 12", true, this::openNotebook);
gap(14);
LinearLayout stats = new LinearLayout(this);
for (String value : new String[]{streak() + "\nDAY STREAK", prefs.getInt("solved", 0) + "\nPATTERNS FOUND"}) {
TextView view = text(value, 14, GREEN);
view.setGravity(android.view.Gravity.CENTER);
stats.addView(view, new LinearLayout.LayoutParams(0, dp(70), 1));
}
root.addView(stats);
flowerDivider();
root.addView(text("A SMALL DAILY RITUAL", 11, MUTED));
root.addView(text(LocalDate.now().format(DateTimeFormatter.ofPattern("EEEE, d MMMM", Locale.getDefault())), 22, INK));
boolean done = prefs.getBoolean("done_d" + LocalDate.now(), false);
button(done ? "Revisit today’s puzzle ✓" : "Play today’s puzzle →", false, () -> startDaily(LocalDate.now()));
gap(18);
root.addView(text("BY THE COTTAGE WINDOW", 11, MUTED));
root.addView(text("A few spare pages for practice. For overlapping-area puzzles, follow the notebook’s story.", 16, MUTED));
button("Difficulty · " + selected.label + " ▾", false, this::chooseDifficulty);
button("Practice · " + selected.label + " · Level " + practiceLevel(), false, () -> startClassic(false, practiceLevel()));
String old = "p" + prefs.getInt("level", 1);
if (prefs.contains("grid_" + old) && !prefs.getBoolean("done_" + old, false)) {
button("Continue earlier puzzle", false, () -> startClassic(true, prefs.getInt("level", 1)));
}
gap(12);
button("How to play", false, this::rules);
button("Privacy & advertising", false, () -> ads.privacy());
gap(12);
root.addView(handwritten("Leave a light in the window."));
}
private void campaignMap() {
base(Screen.MAP);
root.addView(text("THE NOTEBOOK BELONGS TO", 10, MUTED));
TextView owner = handwritten("Mara Wren");
owner.setTextSize(38);
root.addView(owner);
root.addView(text("The Last Light", 28, INK));
root.addView(handwritten("For you, when you are ready.\nWith all my love, Gran."));
flowerDivider();
root.addView(text(Campaign.PREMISE, 16, INK));
gap(10);
root.addView(text(recoveredCount() + " / 12 memories tucked between these pages", 13, MUTED));
for (int i = 0; i < Campaign.LEVELS.length; i++) {
final int index = i;
Campaign.Level level = Campaign.LEVELS[i];
if (i % 4 == 0) { gap(24); root.addView(text(level.chapter, 24, GREEN)); root.addView(handwritten(i < 4 ? "Begin here, my dear." : i < 8 ? "Take care on the crossing." : "I will keep the kettle warm.")); }
boolean done = recovered(i), unlocked = i <= accessibleCampaign();
String label = String.format(Locale.ROOT, "%02d", i + 1) + " · " + (done ? level.object + " ✓" : level.title);
Button entry = button(unlocked ? label : label + " · not yet", false, () -> {
if (recovered(index)) campaignReveal(index); else briefing(index);
});
entry.setTypeface(JournalArt.HAND);
entry.setTextSize(23);
entry.setGravity(android.view.Gravity.START | android.view.Gravity.CENTER_VERTICAL);
entry.setPadding(dp(12), dp(14), dp(12), dp(14));
entry.setBackground(new JournalArt.InkLine(this, unlocked && !done ? GREEN : MUTED));
entry.setEnabled(unlocked);
entry.setTextColor(unlocked ? INK : MUTED);
if (done) {
PictureView miniature = new PictureView(level.picture, 7);
miniature.setContentDescription("Recovered pixel picture: " + level.object);
root.addView(miniature, new LinearLayout.LayoutParams(-1, dp(92)));
}
}
gap(16);
button("Back to home", false, this::home);
}
private void briefing(int index) {
if (index > accessibleCampaign()) { campaignMap(); return; }
campaignIndex = index;
mode = Mode.CAMPAIGN;
base(Screen.BRIEFING);
Campaign.Level level = Campaign.LEVELS[index];
folio(index);
root.addView(text(level.chapter, 13, GREEN));
root.addView(text(level.title, 32, INK));
gap(12);
root.addView(text(level.before, 19, INK));
flowerDivider();
root.addView(handwritten(granNote(index)));
gap(18);
if (index < 2) {
root.addView(text("READ THE NOTEBOOK", 12, GREEN));
root.addView(text("Light the cells to match each row and column total. Cross out the cells that stay dark. The finished 7 × 7 grid is a picture from the story.", 16, MUTED));
} else {
root.addView(text(index == 2 ? "NEW · OVERLAPPING AREAS" : "COMPARE WHAT THE CLUES SHARE", 12, AREA));
root.addView(text("A, B and C are outlined areas with their own light totals. Tap an area’s button to see its boundary. Shared cells count in each area they belong to.", 16, MUTED));
if (index == 2) root.addView(text("Compare two clues: if one area lies inside another, subtract their totals to find the lights outside the smaller area. Rows and columns can be compared with areas too. Every puzzle can be solved without guessing.", 16, INK));
}
button(prefs.contains("grid_" + campaignKey(index)) ? "Continue this pattern →" : "Restore the pattern →", true, () -> startCampaign(index));
button("Back to notebook", false, this::campaignMap);
}
private void campaignReveal(int index) {
if (!recovered(index)) { briefing(index); return; }
campaignIndex = index;
mode = Mode.CAMPAIGN;
base(Screen.REVEAL);
Campaign.Level level = Campaign.LEVELS[index];
folio(index);
root.addView(handwritten("Something found. Something remembered."));
root.addView(text(level.object, 34, INK));
PictureView picture = new PictureView(level.picture, 7);
picture.setContentDescription("Recovered pixel picture: " + level.object);
root.addView(picture, new LinearLayout.LayoutParams(-1, dp(260)));
picture.setAlpha(0f);
picture.animate().alpha(1f).setDuration(850).start();
gap(10);
root.addView(text(level.after, 19, INK));
gap(10);
root.addView(handwritten("Kept safe, between these pages. — M."));
flowerDivider();
if (index == Campaign.LEVELS.length - 1) {
root.addView(text("THE END · YOUR WATCH HAS BEGUN", 12, GREEN));
root.addView(text("Twelve patterns. One light brought home. The daily puzzle will be here whenever you return.", 16, MUTED));
button("Return to the notebook", true, this::campaignMap);
button("Today’s puzzle", false, () -> startDaily(LocalDate.now()));
} else {
button("Turn the page →", true, () -> {
Runnable nextPage = () -> briefing(index + 1);
if ((index + 1) % 4 == 0 && !prefs.getBoolean("storyAd_" + index, false)) {
prefs.edit().putBoolean("storyAd_" + index, true).apply();
ads.between(nextPage);
} else nextPage.run();
});
button("Back to notebook", false, this::campaignMap);
}
}
private void rules() {
new AlertDialog.Builder(this).setTitle("Find the light").setMessage(
"Light exactly as many cells as the number beside each row and above each column.\n\nTap to cycle: empty → light → crossed out → empty. Mark every cell to finish. Small dots mark fixed clues.\n\nIn the story, A, B and C are overlapping areas with their own totals. Tap their buttons to see each boundary. Shared cells count in both areas. Compare clues and subtract their shared parts to find new deductions.\n\nEvery story grid reveals an object. Later pages require area comparisons; all are solvable without guessing. Classic practice grades the length of simpler row and column chains.\n\nOne free explained hint per puzzle, then optional rewarded hints. Streaks count consecutive daily-puzzle completions on this device.")
.setPositiveButton("Got it", null).show();
}
private int practiceLevel() { return prefs.getInt("level_" + selected.name(), 1); }
private void chooseDifficulty() {
String[] labels = new String[3];
for (Difficulty d : Difficulty.values()) labels[d.ordinal()] = d.label + " — " + d.description;
new AlertDialog.Builder(this).setTitle("Classic practice pace").setSingleChoiceItems(labels, selected.ordinal(), (dialog, which) -> {
selected = Difficulty.values()[which];
prefs.edit().putString("difficulty", selected.name()).apply();
dialog.dismiss();
home();
}).setNegativeButton("Cancel", null).show();
}
private void startDaily(LocalDate day) {
mode = Mode.DAILY;
date = day;
legacyPractice = false;
load(new Puzzle(date.toEpochDay() * 7919L), "d" + date);
}
private void startClassic(boolean legacy, int level) {
mode = Mode.CLASSIC;
legacyPractice = legacy;
playingLevel = level;
load(legacy ? new Puzzle(1000000L + level) : Puzzle.generate(1000000L + level, selected),
legacy ? "p" + level : "v2_" + selected.name() + "_" + level);
}
private void startCampaign(int index) {
if (index > accessibleCampaign()) { campaignMap(); return; }
mode = Mode.CAMPAIGN;
campaignIndex = index;
legacyPractice = false;
if (recovered(index)) { campaignReveal(index); return; }
load(Campaign.puzzle(index), campaignKey(index));
}
private void load(Puzzle nextPuzzle, String nextKey) {
inStoryPuzzle = false;
readPuzzle(nextPuzzle, nextKey);
game();
}
private void readPuzzle(Puzzle nextPuzzle, String nextKey) {
puzzle = nextPuzzle;
key = nextKey;
cells = new int[puzzle.solution.length];
String saved = prefs.getString("grid_" + key, "");
for (int i = 0; i < cells.length; i++) {
int value = saved.length() == cells.length ? saved.charAt(i) - '0' : 0;
cells[i] = value >= 0 && value <= 2 ? value : 0;
if (puzzle.given[i]) cells[i] = puzzle.solution[i] == 1 ? 1 : 2;
}
won = prefs.getBoolean("done_" + key, false);
selectedArea = 0;
undo.clear();
save();
}
private void save() {
StringBuilder value = new StringBuilder();
for (int cell : cells) value.append(cell);
prefs.edit().putString("grid_" + key, value.toString()).apply();
}
private void game() {
base(Screen.GAME);
String heading = mode == Mode.DAILY ? "DAILY / " + date.format(DateTimeFormatter.ofPattern("dd MMM"))
: mode == Mode.CAMPAIGN ? "THE LAST LIGHT / " + (campaignIndex + 1) + " OF 12"
: "CLASSIC / " + puzzle.difficulty().label.toUpperCase(Locale.ROOT) + " / LEVEL " + playingLevel;
root.addView(text(heading, 12, GREEN));
root.addView(text(mode == Mode.CAMPAIGN ? Campaign.LEVELS[campaignIndex].title : "Find the light.", 30, INK));
root.addView(text(puzzle.regions.isEmpty() ? "Match the totals. Let the pattern emerge." : "Compare rows, columns and overlapping areas.", 15, MUTED));
if (!puzzle.regions.isEmpty()) {
LinearLayout areas = new LinearLayout(this);
for (int i = 0; i < puzzle.regions.size(); i++) {
final int region = i;
Button chip = new Button(this);
chip.setAllCaps(false);
chip.setTextSize(15);
chip.setMinHeight(dp(52));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, dp(56), 1);
if (i > 0) params.setMargins(dp(6), 0, 0, 0);
areas.addView(chip, params);
chip.setOnClickListener(v -> { selectedArea = region; updateAreas(); if (board != null) board.invalidate(); });
areaButtons.add(chip);
}
root.addView(areas);
root.addView(text("Tap A, B or C to highlight its area · lit / required", 12, AREA));
updateAreas();
}
gap(8);
board = new Board();
root.addView(board, new LinearLayout.LayoutParams(-1, -2));
root.addView(text(won ? "Beautifully solved. Take a breath." : "Tap: light → cross → clear • dots are fixed", 13, MUTED));
if (!won) {
button("Undo last move", false, () -> {
if (!undo.isEmpty()) { cells = undo.pop(); save(); refreshBoard(); }
});
button(prefs.getBoolean("hint_" + key, false) ? "Watch an ad · explained hint" : "One explained hint · free", true, this::hint);
} else button(mode == Mode.DAILY ? "Back to today" : "Next puzzle →", true, this::next);
button(mode == Mode.CAMPAIGN ? "Back to notebook" : "Back to home", false, mode == Mode.CAMPAIGN ? this::campaignMap : this::home);
Board visibleBoard = board;
visibleBoard.post(() -> {
if (visibleBoard.isAttachedToWindow()) visibleBoard.requestRectangleOnScreen(
new Rect(0, 0, visibleBoard.getWidth(), visibleBoard.getHeight()), true);
});
}
private void updateAreas() {
for (int i = 0; i < areaButtons.size(); i++) {
Puzzle.Region region = puzzle.regions.get(i);
int lit = 0;
for (int cell = 0; cell < cells.length; cell++) if (cells[cell] == 1 && region.contains(cell, puzzle.size)) lit++;
Button chip = areaButtons.get(i);
chip.setText(String.format(Locale.getDefault(), "%s %d / %d", region.label, lit, puzzle.regionTotal(region)));
chip.setTextColor(AREA);
chip.setTypeface(JournalArt.HAND, i == selectedArea ? Typeface.BOLD : Typeface.NORMAL);
chip.setStateListAnimator(null);
chip.setElevation(0);
chip.setBackground(new JournalArt.InkLine(this, i == selectedArea ? AREA : MUTED));
chip.setContentDescription("Area " + region.label + ", " + lit + " lit out of " + puzzle.regionTotal(region) + " required. Tap to highlight its boundary.");
}
}
private void refreshBoard() { updateAreas(); if (board != null) board.invalidate(); }
private void hint() {
if (won) return;
if (!prefs.getBoolean("hint_" + key, false)) {
prefs.edit().putBoolean("hint_" + key, true).apply();
explainHint();
} else {
new AlertDialog.Builder(this).setTitle("A little nudge?").setMessage("Watch a rewarded ad for one explained hint.")
.setNegativeButton("Keep thinking", null).setPositiveButton("Watch ad", (dialog, which) -> {
String requested = key;
if (!ads.hint(() -> { if (key.equals(requested) && (screen == Screen.GAME || screen == Screen.STORY && inStoryPuzzle) && !won) explainHint(); })) {
Toast.makeText(this, "No ad available. Please try again later.", Toast.LENGTH_LONG).show();
}
}).show();
}
}
private void explainHint() {
int cell = -1, value = -1;
String explanation = "";
for (int i = 0; i < cells.length; i++) {
if (cells[i] != 0 && cells[i] != (puzzle.solution[i] == 1 ? 1 : 2)) {
cell = i; value = puzzle.solution[i];
explanation = "An earlier mark at this cell conflicts with the clues. Correct it, then continue comparing the totals.";
break;
}
}
if (cell < 0) {
int[] known = new int[cells.length];
for (int i = 0; i < cells.length; i++) known[i] = cells[i] == 0 ? -1 : cells[i] == 1 ? 1 : 0;
LogicSolver.Hint hint = new LogicSolver(cells.length, puzzle.constraints()).nextHint(known);
if (hint != null) { cell = hint.cell; value = hint.value; explanation = hint.explanation; }
}
if (cell < 0) return;
undo.push(cells.clone());
cells[cell] = value == 1 ? 1 : 2;
save();
refreshBoard();
String title = "Row " + (cell / puzzle.size + 1) + ", column " + (cell % puzzle.size + 1);
String action = value == 1 ? "This cell is lit." : "This cell stays dark.";
if (inStoryPuzzle) showStory(2); else game();
new AlertDialog.Builder(this).setTitle(title).setMessage(explanation + "\n\n" + action)
.setPositiveButton("Keep going", (dialog, which) -> check()).show();
}
private void check() {
if (won || !puzzle.solved(cells)) return;
won = true;
SharedPreferences.Editor edit = prefs.edit().putBoolean("done_" + key, true).putInt("solved", prefs.getInt("solved", 0) + 1);
if (mode == Mode.DAILY) {
long day = date.toEpochDay(), last = prefs.getLong("lastDaily", -99999);
if (day > last) edit.putLong("lastDaily", day).putInt("streak", DailyStreak.afterCompletion(last, prefs.getInt("streak", 0), day));
} else if (mode == Mode.CAMPAIGN) {
edit.putInt("campaignUnlocked", Math.max(campaignUnlocked(), Math.min(Campaign.LEVELS.length - 1, campaignIndex + 1)));
} else {
edit.putInt(legacyPractice ? "level" : "level_" + selected.name(), playingLevel + 1);
edit.putInt("practiceCompleted", prefs.getInt("practiceCompleted", 0) + 1);
}
edit.apply();
if (mode == Mode.CAMPAIGN) { if (inStoryPuzzle) showStory(3); else campaignReveal(campaignIndex); return; }
game();
new AlertDialog.Builder(this).setTitle("A moment of clarity.")
.setMessage(mode == Mode.DAILY ? "Today’s grid is complete. Come back tomorrow for a fresh challenge." : "Another pattern found. Ready for the next one?")
.setPositiveButton(mode == Mode.DAILY ? "Lovely" : "Next puzzle", (dialog, which) -> next())
.setNegativeButton("Stay here", null).show();
}
private void next() {
if (mode == Mode.DAILY) { home(); return; }
Runnable nextBoard = () -> startClassic(false, practiceLevel());
if (prefs.getInt("practiceCompleted", 0) > 0 && prefs.getInt("practiceCompleted", 0) % 4 == 0) ads.between(nextBoard);
else nextBoard.run();
}
private final class PictureView extends View {
private final int[] pixels;
private final int size;
private final Paint paint = new Paint(3);
PictureView(int[] pixels, int size) { super(MainActivity.this); this.pixels = pixels; this.size = size; }
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float unit = Math.min(getWidth(), getHeight()) / (size + 2f);
float left = (getWidth() - size * unit) / 2, top = (getHeight() - size * unit) / 2;
float cardLeft = left - unit * .55f, cardTop = top - unit * .55f;
float cardRight = left + unit * (size + .55f), cardBottom = top + unit * (size + .55f);
paint.setColor(0x285d4930);
canvas.drawRect(cardLeft + dp(3), cardTop + dp(4), cardRight + dp(3), cardBottom + dp(4), paint);
paint.setColor(Color.rgb(250, 241, 216));
canvas.drawRect(cardLeft, cardTop, cardRight, cardBottom, paint);
paint.setColor(0x90c5ae7e);
canvas.save(); canvas.rotate(-18, cardLeft + unit, cardTop);
canvas.drawRect(cardLeft, cardTop - unit * .2f, cardLeft + unit * 2, cardTop + unit * .25f, paint); canvas.restore();
canvas.save(); canvas.rotate(15, cardRight - unit, cardTop);
canvas.drawRect(cardRight - unit * 2, cardTop - unit * .2f, cardRight, cardTop + unit * .25f, paint); canvas.restore();
paint.setColor(GREEN);
for (int i = 0; i < pixels.length; i++) if (pixels[i] == 1) {
float x = left + i % size * unit, y = top + i / size * unit;
canvas.drawRect(x, y, x + unit + .5f, y + unit + .5f, paint);
}
}
}
private final class Board extends View {
private final Paint paint = new Paint(3);
private float unit, left, top;
private int accessibilityFocus = -1;
Board() {
super(MainActivity.this);
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
setContentDescription("Puzzle grid. Row and column numbers show required lit cells. Tap each cell to change it.");
}
@Override protected void onMeasure(int widthSpec, int heightSpec) {
int width = MeasureSpec.getSize(widthSpec);
int desiredHeight = Math.min(width, dp(inStoryPuzzle ? 350 : puzzle.size == 7 ? 414 : 350));
setMeasuredDimension(width, resolveSize(desiredHeight, heightSpec));
}
private void label(Canvas canvas, String value, float x, float y, int color, float size) {
paint.setColor(color);
paint.setTypeface(JournalArt.HAND);
paint.setTextSize(size);
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(value, x, y, paint);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int n = puzzle.size;
unit = Math.min(getWidth() / (n + 1f), getHeight() / (n + 1f));
left = (getWidth() - unit * (n + 1)) / 2;
top = (getHeight() - unit * (n + 1)) / 2;
for (int row = 0; row < n; row++) {
int lit = 0; for (int col = 0; col < n; col++) if (cells[row * n + col] == 1) lit++;
label(canvas, "" + puzzle.rows[row], left + unit * .4f, top + unit * (row + 1.64f), lit == puzzle.rows[row] ? GREEN : MUTED, unit * .33f);
}
for (int col = 0; col < n; col++) {
int lit = 0; for (int row = 0; row < n; row++) if (cells[row * n + col] == 1) lit++;
label(canvas, "" + puzzle.cols[col], left + unit * (col + 1.5f), top + unit * .64f, lit == puzzle.cols[col] ? GREEN : MUTED, unit * .33f);
}
Puzzle.Region active = puzzle.regions.isEmpty() ? null : puzzle.regions.get(selectedArea);
for (int i = 0; i < cells.length; i++) {
float x = left + unit * (i % n + 1), y = top + unit * (i / n + 1), pad = unit * .055f;
boolean highlighted = active != null && active.contains(i, n);
paint.setColor(cells[i] == 1 ? GREEN : highlighted ? 0x259F6335 : 0x076A6045);
canvas.drawRoundRect(x + pad, y + pad, x + unit - pad, y + unit - pad, unit * .055f, unit * .055f, paint);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(dp(.7f));
paint.setColor(cells[i] == 1 ? GREEN : 0xAA8C8064);
canvas.drawRoundRect(x + pad, y + pad, x + unit - pad, y + unit - pad, unit * .055f, unit * .055f, paint);
paint.setStyle(Paint.Style.FILL);
if (cells[i] == 1) { paint.setColor(GOLD); canvas.drawCircle(x + unit * .5f, y + unit * .5f, unit * .14f, paint); }
if (cells[i] == 2) {
paint.setColor(MUTED); paint.setStrokeWidth(dp(1.5f));
canvas.drawLine(x + unit * .4f, y + unit * .4f, x + unit * .6f, y + unit * .6f, paint);
canvas.drawLine(x + unit * .6f, y + unit * .4f, x + unit * .4f, y + unit * .6f, paint);
}
if (puzzle.given[i]) { paint.setColor(cells[i] == 1 ? Color.WHITE : MUTED); canvas.drawCircle(x + unit * .78f, y + unit * .22f, unit * .035f, paint); }
}
if (active != null) {
paint.setColor(AREA); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(dp(2.5f));
float x = left + unit * (active.left + 1), y = top + unit * (active.top + 1);
canvas.drawRoundRect(x + 1, y + 1, x + unit * active.width - 1, y + unit * active.height - 1, unit * .12f, unit * .12f, paint);
paint.setStyle(Paint.Style.FILL);
}
if (accessibilityFocus >= 0) {
int row = accessibilityFocus / n, col = accessibilityFocus % n;
paint.setColor(INK); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(dp(2));
canvas.drawRect(left + unit * (col + 1), top + unit * (row + 1), left + unit * (col + 2), top + unit * (row + 2), paint);
paint.setStyle(Paint.Style.FILL);
}
}
private int cellAt(float x, float y) {
if (unit <= 0) return -1;
int col = (int) Math.floor((x - left) / unit) - 1, row = (int) Math.floor((y - top) / unit) - 1;
return row >= 0 && row < puzzle.size && col >= 0 && col < puzzle.size ? row * puzzle.size + col : -1;
}
private void changeCell(int cell) {
if (cell < 0 || cell >= cells.length || won || puzzle.given[cell]) return;
undo.push(cells.clone());
cells[cell] = (cells[cell] + 1) % 3;
save(); refreshBoard(); check();
}
@Override public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) { changeCell(cellAt(event.getX(), event.getY())); performClick(); }
return true;
}
@Override public boolean performClick() { super.performClick(); return true; }
private void focusEvent(int cell, int type) {
AccessibilityEvent event = AccessibilityEvent.obtain(type);
event.setSource(this, cell);
event.setPackageName(getPackageName());
event.setClassName("android.widget.Button");
if (getParent() != null) getParent().requestSendAccessibilityEvent(this, event);
}
@Override public boolean dispatchHoverEvent(MotionEvent event) {
android.view.accessibility.AccessibilityManager manager = (android.view.accessibility.AccessibilityManager) getSystemService(ACCESSIBILITY_SERVICE);
if (manager != null && manager.isTouchExplorationEnabled()) {
int cell = cellAt(event.getX(), event.getY());
if (cell >= 0 && event.getAction() != MotionEvent.ACTION_HOVER_EXIT) {
focusEvent(cell, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
return true;
}
if (accessibilityFocus >= 0) focusEvent(accessibilityFocus, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
}
return super.dispatchHoverEvent(event);
}
@Override public AccessibilityNodeProvider getAccessibilityNodeProvider() {
return new AccessibilityNodeProvider() {
@Override public AccessibilityNodeInfo createAccessibilityNodeInfo(int id) {
if (id == View.NO_ID) {
AccessibilityNodeInfo node = AccessibilityNodeInfo.obtain(Board.this);
onInitializeAccessibilityNodeInfo(node);
for (int i = 0; i < cells.length; i++) node.addChild(Board.this, i);
return node;
}
if (id < 0 || id >= cells.length) return null;
AccessibilityNodeInfo node = AccessibilityNodeInfo.obtain();
node.setSource(Board.this, id); node.setParent(Board.this); node.setPackageName(getPackageName());
node.setClassName("android.widget.Button"); node.setEnabled(true); node.setVisibleToUser(isShown()); node.setFocusable(true);
node.setClickable(!won && !puzzle.given[id]);
node.setAccessibilityFocused(accessibilityFocus == id);
String description = "Row " + (id / puzzle.size + 1) + ", column " + (id % puzzle.size + 1) + ", "
+ (cells[id] == 1 ? "lit" : cells[id] == 2 ? "crossed out" : "empty") + (puzzle.given[id] ? ", fixed clue" : "")
+ ". Row needs " + puzzle.rows[id / puzzle.size] + ", column needs " + puzzle.cols[id % puzzle.size];
for (Puzzle.Region region : puzzle.regions) if (region.contains(id, puzzle.size)) description += ". In area " + region.label + ", total " + puzzle.regionTotal(region);
node.setContentDescription(description);
int x = (int) (left + unit * (id % puzzle.size + 1)), y = (int) (top + unit * (id / puzzle.size + 1));
Rect bounds = new Rect(x, y, (int) (x + unit), (int) (y + unit));
node.setBoundsInParent(bounds);
int[] location = new int[2]; getLocationOnScreen(location); bounds.offset(location[0], location[1]); node.setBoundsInScreen(bounds);
if (!won && !puzzle.given[id]) node.addAction(AccessibilityNodeInfo.ACTION_CLICK);
node.addAction(accessibilityFocus == id ? AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS : AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
return node;
}
@Override public boolean performAction(int id, int action, Bundle arguments) {
if (id < 0 || id >= cells.length) return false;
if (action == AccessibilityNodeInfo.ACTION_CLICK && !won && !puzzle.given[id]) { changeCell(id); return true; }
if (action == AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS) {
accessibilityFocus = id; invalidate(); focusEvent(id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); return true;
}
if (action == AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS) {
accessibilityFocus = -1; invalidate(); focusEvent(id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); return true;
}
return false;
}
};
}
}
}
@@ -0,0 +1,114 @@
package com.lumen.daily;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.view.View;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
/** Positions actual writing on one continuous diary page. */
final class NotebookPage extends ViewGroup {
private static Bitmap artwork;
private final ImageView image;
private final View content;
interface PageTurn { void turn(int direction); }
private PageTurn pageTurn;
private final PageTurnGesture gesture = new PageTurnGesture();
void setPageTurn(PageTurn listener) { pageTurn = listener; }
private final Rect imageBounds = new Rect();
private final Rect contentBounds = new Rect();
private final float density;
NotebookPage(Context context, View content) {
super(context);
this.content = content;
density = getResources().getDisplayMetrics().density;
setBackgroundColor(Color.rgb(64, 49, 35));
if (artwork == null) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
artwork = BitmapFactory.decodeResource(getResources(), R.drawable.mara_diary_page, options);
}
image = new ImageView(context);
image.setImageBitmap(artwork);
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
image.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
addView(image);
addView(content);
setOnApplyWindowInsetsListener((view, insets) -> {
setPadding(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(),
insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom());
return insets;
});
}
@Override public boolean onInterceptTouchEvent(MotionEvent event) {
if (pageTurn == null) return false;
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
gesture.begin(event.getX(),event.getY(),contentBounds.left,contentBounds.right,22*density);
} else if (event.getActionMasked() == MotionEvent.ACTION_MOVE) {
return gesture.intercept(event.getX(),event.getY(),28*density);
} else if (event.getActionMasked() == MotionEvent.ACTION_CANCEL) gesture.cancel();
return false;
}
@Override public boolean onTouchEvent(MotionEvent event) {
if (pageTurn == null) return super.onTouchEvent(event);
if (event.getActionMasked() == MotionEvent.ACTION_DOWN)
return gesture.begin(event.getX(),event.getY(),contentBounds.left,contentBounds.right,22*density);
if (!gesture.active()) return false;
if (event.getActionMasked() == MotionEvent.ACTION_UP) {
int direction=gesture.finish(event.getX(),event.getY(),48*density);
if(direction!=0){pageTurn.turn(direction);performClick();}
} else if (event.getActionMasked() == MotionEvent.ACTION_CANCEL) gesture.cancel();
return true;
}
@Override public boolean performClick() { super.performClick(); return true; }
private void arrange(int width, int height) {
int x = getPaddingLeft(), y = getPaddingTop();
int w = Math.max(1, width - x - getPaddingRight());
int h = Math.max(1, height - y - getPaddingBottom());
if (w > h * 1.15f) {
// Crop the blank middle of the same sheet in landscape, keeping text on paper.
// Crop only vertically: the left-edge binding remains visible.
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageBounds.set(x, y, x + w, y + h);
int writingWidth = Math.min(Math.round(w * .78f), Math.round(640 * density));
int writingLeft = x + (w - writingWidth) / 2;
contentBounds.set(writingLeft, y + Math.round(h * .06f),
writingLeft + writingWidth, y + Math.round(h * .94f));
} else {
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
float scale = Math.min(w / (float)artwork.getWidth(), h / (float)artwork.getHeight());
int bookWidth = Math.round(artwork.getWidth() * scale), bookHeight = Math.round(artwork.getHeight() * scale);
int left = x + (w - bookWidth) / 2, top = y + (h - bookHeight) / 2;
imageBounds.set(left, top, left + bookWidth, top + bookHeight);
// The single page has no centre gutter. Leave the right margin for heather.
boolean narrow = w / density < 480;
contentBounds.set(left + Math.round(bookWidth * (narrow ? .08f : .11f)), top + Math.round(bookHeight * .12f),
left + Math.round(bookWidth * (narrow ? .91f : .83f)), top + Math.round(bookHeight * .91f));
}
}
@Override protected void onMeasure(int widthSpec, int heightSpec) {
int width = MeasureSpec.getSize(widthSpec), height = MeasureSpec.getSize(heightSpec);
setMeasuredDimension(width, height);
arrange(width, height);
image.measure(MeasureSpec.makeMeasureSpec(imageBounds.width(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(imageBounds.height(), MeasureSpec.EXACTLY));
content.measure(MeasureSpec.makeMeasureSpec(contentBounds.width(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(contentBounds.height(), MeasureSpec.EXACTLY));
}
@Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
image.layout(imageBounds.left, imageBounds.top, imageBounds.right, imageBounds.bottom);
content.layout(contentBounds.left, contentBounds.top, contentBounds.right, contentBounds.bottom);
}
}
@@ -0,0 +1,20 @@
package com.lumen.daily;
/** Only gestures starting in a page margin can become page turns. */
final class PageTurnGesture {
private float startX, startY;
private boolean active;
boolean begin(float x,float y,float left,float right,float margin) {
startX=x;startY=y;active=x<left+margin||x>right-margin;return active;
}
boolean intercept(float x,float y,float threshold) {
float dx=x-startX,dy=y-startY;
return active&&Math.abs(dx)>threshold&&Math.abs(dx)>Math.abs(dy)*1.5f;
}
int finish(float x,float y,float threshold) {
boolean turn=intercept(x,y,threshold);active=false;
return turn?(x<startX?1:-1):0;
}
void cancel(){active=false;}
boolean active(){return active;}
}
@@ -0,0 +1,118 @@
package com.lumen.daily;
import java.util.*;
/** Binary grid constrained by row/column totals and immutable given cells. */
public final class Puzzle {
public final int size;
public final int[] solution, rows, cols;
public final boolean[] given;
public final List<Region> regions = new ArrayList<>();
public static final class Region {
public final String label;
public final int top, left, height, width;
public Region(String label,int top,int left,int height,int width){this.label=label;this.top=top;this.left=left;this.height=height;this.width=width;}
public boolean contains(int index,int size){int r=index/size,c=index%size;return r>=top&&r<top+height&&c>=left&&c<left+width;}
}
public Puzzle(int size,int[] picture){
this.size=size;solution=picture.clone();rows=new int[size];cols=new int[size];given=new boolean[size*size];
if(picture.length!=size*size)throw new IllegalArgumentException("Wrong picture size");
for(int i=0;i<solution.length;i++){if(solution[i]!=0&&solution[i]!=1)throw new IllegalArgumentException("Non-binary picture");rows[i/size]+=solution[i];cols[i%size]+=solution[i];}
}
public int regionTotal(Region region){int total=0;for(int i=0;i<solution.length;i++)if(region.contains(i,size))total+=solution[i];return total;}
public List<LogicSolver.Constraint> constraints(){
List<LogicSolver.Constraint> result=new ArrayList<>();
for(int line=0;line<size;line++){int[] row=new int[size],col=new int[size];for(int pos=0;pos<size;pos++){row[pos]=line*size+pos;col[pos]=pos*size+line;}result.add(new LogicSolver.Constraint(row,rows[line],"Row "+(line+1)));result.add(new LogicSolver.Constraint(col,cols[line],"Column "+(line+1)));}
for(Region region:regions){int[] indices=new int[region.height*region.width];int at=0;for(int r=region.top;r<region.top+region.height;r++)for(int c=region.left;c<region.left+region.width;c++)indices[at++]=r*size+c;result.add(new LogicSolver.Constraint(indices,regionTotal(region),"Area "+region.label));}return result;
}
public Puzzle(long seed) {
size=5;solution=new int[25];rows=new int[5];cols=new int[5];given=new boolean[25];
Random random = new Random(seed);
for(int i=0;i<25;i++){ solution[i]=random.nextBoolean()?1:0; rows[i/5]+=solution[i]; cols[i%5]+=solution[i]; }
List<Integer> order=new ArrayList<>(); for(int i=0;i<25;i++)order.add(i); Collections.shuffle(order,random);
for(int i:order){ if(countSolutions()==1)break; given[i]=true; }
}
/** Keep the original constructor stable so existing saved grids remain valid. */
public static Puzzle generate(long seed, Difficulty difficulty) {
Random seeds = new Random(seed);
for (int attempt = 0; attempt < 256; attempt++) {
Puzzle candidate = new Puzzle(seeds.nextLong());
if (difficulty != Difficulty.EASY) candidate.removeRedundantClues();
if (candidate.difficulty() == difficulty) return candidate;
}
// Bounded generation: known graded boards, varied by row/column permutations.
Puzzle fallback = new Puzzle(difficulty == Difficulty.HARD ? 2L : 0L);
if (difficulty != Difficulty.EASY) fallback.removeRedundantClues();
fallback.permute(seeds);
return fallback;
}
private void removeRedundantClues() {
for (int i = 0; i < 25; i++) {
if (!given[i]) continue;
given[i] = false;
if (countSolutions() != 1) given[i] = true;
}
}
private void permute(Random random) {
List<Integer> r = new ArrayList<>(), c = new ArrayList<>();
for (int i = 0; i < 5; i++) { r.add(i); c.add(i); }
Collections.shuffle(r, random); Collections.shuffle(c, random);
int[] oldSolution = solution.clone(); boolean[] oldGiven = given.clone();
Arrays.fill(rows, 0); Arrays.fill(cols, 0);
for (int i = 0; i < 25; i++) {
int from = r.get(i / 5) * 5 + c.get(i % 5);
solution[i] = oldSolution[from]; given[i] = oldGiven[from];
rows[i / 5] += solution[i]; cols[i % 5] += solution[i];
}
}
/**
* Count simultaneous rounds of human deductions. A line is forced when its
* remaining total is zero or equals its unknown cells. Each round reads only
* the previous round's state, so scan order cannot affect the rating.
* The solution is deliberately not consulted except to read the printed clues.
*/
public int deductionRounds() {
int[] known = new int[solution.length]; Arrays.fill(known, -1);
for (int i = 0; i < solution.length; i++) if (given[i]) known[i] = solution[i];
int rounds = 0;
while (true) {
int remaining = 0; for (int value : known) if (value < 0) remaining++;
if (remaining == 0) return rounds;
int[] next = known.clone(); boolean changed = false;
for (int axis = 0; axis < 2; axis++) for (int line = 0; line < size; line++) {
int lit = 0, unknown = 0;
for (int pos = 0; pos < size; pos++) {
int index = axis == 0 ? line * size + pos : pos * size + line;
if (known[index] < 0) unknown++; else lit += known[index];
}
int need = (axis == 0 ? rows[line] : cols[line]) - lit;
if (need < 0 || need > unknown) throw new IllegalStateException("Contradictory puzzle");
if (unknown == 0 || (need != 0 && need != unknown)) continue;
for (int pos = 0; pos < size; pos++) {
int index = axis == 0 ? line * size + pos : pos * size + line;
if (known[index] < 0) { next[index] = need == 0 ? 0 : 1; changed = true; }
}
}
if (!changed) throw new IllegalStateException("Puzzle requires guessing");
known = next; rounds++;
}
}
public Difficulty difficulty() { return Difficulty.fromRounds(deductionRounds()); }
public int countSolutions(){return size==5&&regions.isEmpty()?search(0,new int[5]):new LogicSolver(solution.length,constraints()).countSolutions(LogicSolver.initial(this));}
private int search(int row,int[] totals){
if(row==5)return Arrays.equals(totals,cols)?1:0;
int count=0;
for(int mask=0;mask<32;mask++){
if(Integer.bitCount(mask)!=rows[row])continue;
boolean ok=true; int[] next=totals.clone();
for(int c=0;c<5;c++){int v=(mask>>c)&1; int i=row*5+c; next[c]+=v;
if((given[i]&&solution[i]!=v)||next[c]>cols[c]||next[c]+4-row<cols[c])ok=false;
}
if(ok)count+=search(row+1,next); if(count>=2)return 2;
}return count;
}
public boolean solved(int[] cells){if(cells==null||cells.length!=solution.length)return false;for(int i=0;i<solution.length;i++)if(cells[i]!=(solution[i]==1?1:2))return false;return true;}
}
@@ -0,0 +1,36 @@
package com.lumen.daily;
/** Stable, authored page records. Puzzle save IDs remain independent of reading progress. */
final class StoryBook {
enum Kind { DEDICATION, ENTRY, PUZZLE, MEMORY, LETTER, LANTERN }
static final class Page {
final String id, title, speaker, text;
final Kind kind;
Page(String id, Kind kind, String title, String speaker, String text) {
this.id = id; this.kind = kind; this.title = title; this.speaker = speaker; this.text = text;
}
}
static final Page[] PAGES = {
new Page("cottage.dedication", Kind.DEDICATION, "For you, when you are ready", "Mara",
"My dear,\n\nI never could keep a proper diary. I wrote down the tides, the things that needed mending, and whatever I was afraid I might forget.\n\nYou will find a little of all three in here. Take your time. There is no right way to turn these pages.\n\nWith all my love,\nGran"),
new Page("cottage.window", Kind.ENTRY, "By the cottage window", "Mara",
"The wind has finally gone quiet. I have put the blue cup by the window, where you always liked to sit.\n\nThe latch still sticks. Lift it a little before you turn it. Some things on this island need a gentle hand, not a stronger one.\n\nIf you arrive after dark, there is something in the little drawer beside the hearth."),
new Page("cottage.match.puzzle", Kind.PUZZLE, "A spark in the drawer", "Notebook",
"Restore the small pattern on this page. Match the row and column totals, and mark every cell. You can also leave it for later and read on."),
new Page("cottage.match.memory", Kind.MEMORY, "One small light", "Mara",
"You used to insist on lighting the evening lantern yourself. I held the matchbox, and you held your breath.\n\nOnce, you asked how such a little flame could help anyone out at sea.\n\nIt cannot, I told you. But it can help us find the next light.\n\nI kept one dry match in a tin after that. Just in case."),
new Page("cottage.folded.note", Kind.LETTER, "A note I nearly forgot", "Mara",
"If the tide has covered the causeway, use the little boat by the harbour steps. The knot looks worse than it is.\n\nTake the lantern. When you reach the bell, ring twice. I will know it is you.\n\nAnd do not let the tea go cold while you are deciding.\n\nLove, Gran"),
new Page("cottage.lantern.sketch", Kind.LANTERN, "The handle, carefully mended", "Mara",
"Your grandfather repaired this handle with a piece of wire and far too much confidence. I wrapped the join so it would not catch your fingers.\n\nPeople notice the flame first. I tend to notice the things that let us carry it.")
};
static int indexOf(String id) {
for (int i = 0; i < PAGES.length; i++) if (PAGES[i].id.equals(id)) return i;
return 0;
}
static int turn(int index, int direction) { return Math.max(0, Math.min(PAGES.length - 1, index + direction)); }
static String[] sentences(String text) {
return text.trim().split("(?<=[.!?])\\s+|\\n+");
}
private StoryBook() {}
}
@@ -0,0 +1,156 @@
package com.lumen.daily;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.json.JSONArray;
import org.json.JSONObject;
/** Plays bundled, pre-rendered FLAC recordings. No text-to-speech service is used. */
final class StoryNarrator {
private final Activity activity;
private final SharedPreferences prefs;
private final AudioManager audio;
private final Handler handler = new Handler(Looper.getMainLooper());
private final AudioManager.OnAudioFocusChangeListener focus;
private JSONObject tracks = new JSONObject();
private MediaPlayer player;
private Runnable changed;
private String pageId = "", error = "";
private boolean loading, prepared, playing, paused, finished;
private final Runnable tick = new Runnable() {
@Override public void run() {
if (playing) { notifyChanged(); handler.postDelayed(this, 200); }
}
};
StoryNarrator(Activity activity, SharedPreferences prefs) {
this.activity = activity; this.prefs = prefs;
audio = (AudioManager)activity.getSystemService(Activity.AUDIO_SERVICE);
focus = change -> { if (change < 0) handler.post(this::pause); };
try (InputStream input = activity.getResources().openRawResource(R.raw.narration_manifest);
ByteArrayOutputStream bytes = new ByteArrayOutputStream()) {
byte[] buffer = new byte[4096]; int count;
while ((count = input.read(buffer)) != -1) bytes.write(buffer, 0, count);
tracks = new JSONObject(new String(bytes.toByteArray(), StandardCharsets.UTF_8)).getJSONObject("tracks");
} catch (Exception e) { error = "The recorded readings could not be opened."; }
}
void bind(Runnable listener) { changed = listener; notifyChanged(); }
boolean isPlaying() { return playing; }
boolean isPaused() { return paused; }
boolean isLoading() { return loading; }
boolean hasRecording(String id) { return resource(id) != 0; }
String controlLabel() { return loading ? "Opening recording…" : playing ? "Pause recording" : paused ? "Resume recording" : finished ? "Replay recording" : "Play this reading"; }
String status() {
if (!error.isEmpty()) return error;
if (loading) return "Opening the reading kept with this page…";
if (playing || paused) return (paused ? "Paused · " : "Playing · ") + time(position()) + " / " + time(duration());
return finished ? "End of the reading · listen again whenever you like" : "A recorded reading, kept with this page";
}
private String time(int milliseconds) { int s = milliseconds / 1000; return (s / 60) + ":" + (s % 60 < 10 ? "0" : "") + s % 60; }
private int position() { try { return player != null && prepared ? player.getCurrentPosition() : 0; } catch (IllegalStateException e) { return 0; } }
private int duration() { try { return player != null && prepared ? player.getDuration() : 0; } catch (IllegalStateException e) { return 0; } }
String currentPassage() {
if (!playing && !paused) return "";
JSONObject track = tracks.optJSONObject(pageId);
JSONArray cues = track == null ? null : track.optJSONArray("cues");
int at = position();
if (cues != null) for (int i = 0; i < cues.length(); i++) {
JSONObject cue = cues.optJSONObject(i);
if (cue != null && at >= cue.optInt("startMs") && at < cue.optInt("endMs")) return cue.optString("text");
}
return "";
}
private int resource(String id) {
JSONObject track = tracks.optJSONObject(id);
return track == null ? 0 : activity.getResources().getIdentifier(track.optString("resource"), "raw", activity.getPackageName());
}
void toggle(String id) {
if (loading) return;
if (playing && pageId.equals(id)) { pause(); return; }
if (paused && pageId.equals(id) && prepared) { start(); return; }
int source = resource(id);
if (source == 0) { Toast.makeText(activity,"This page has no recording yet. Its text is always available.",Toast.LENGTH_LONG).show(); return; }
stop(); pageId = id; error = ""; loading = true;
MediaPlayer current = new MediaPlayer(); player = current;
current.setAudioAttributes(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build());
current.setOnPreparedListener(p -> {
if (p != player) return;
loading = false; prepared = true; start();
});
current.setOnCompletionListener(p -> {
if (p != player) return;
playing = false; paused = false; finished = true;
handler.removeCallbacks(tick); releaseFocus(); notifyChanged();
});
current.setOnErrorListener((p, what, extra) -> {
if (p == player) fail();
return true;
});
try (AssetFileDescriptor file = activity.getResources().openRawResourceFd(source)) {
if (file == null) throw new IllegalStateException("Recording unavailable");
current.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
current.prepareAsync(); notifyChanged();
} catch (Exception e) { fail(); }
}
private void start() {
if (player == null || !prepared) return;
if (audio != null && audio.requestAudioFocus(focus, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
!= AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
paused = true; notifyChanged();
Toast.makeText(activity,"Another app is using the audio. Try again when it finishes.",Toast.LENGTH_SHORT).show(); return;
}
try {
applySpeed(); player.start(); playing = true; paused = false; finished = false;
handler.removeCallbacks(tick); handler.post(tick); notifyChanged();
} catch (IllegalStateException e) { fail(); }
}
private void applySpeed() {
if (player == null || !prepared) return;
float speed = prefs.getFloat("recording_speed", 1f);
try { player.setPlaybackParams(new PlaybackParams().setPitch(1f).setSpeed(speed)); }
catch (IllegalArgumentException | IllegalStateException e) {
Toast.makeText(activity,"This device plays the recording at its original speed.",Toast.LENGTH_SHORT).show();
}
}
void pause() {
if (!playing || player == null) return;
try { player.pause(); } catch (IllegalStateException e) { fail(); return; }
playing = false; paused = true; handler.removeCallbacks(tick); releaseFocus(); notifyChanged();
}
void stop() {
playing = false; paused = false; loading = false; prepared = false; finished = false;
handler.removeCallbacks(tick);
MediaPlayer previous = player; player = null;
if (previous != null) previous.release();
pageId = ""; releaseFocus(); notifyChanged();
}
private void fail() { stop(); error = "This recording could not be played. You can still read the entry."; notifyChanged(); }
private void releaseFocus() { if (audio != null) audio.abandonAudioFocus(focus); }
private void notifyChanged() { if (changed != null) changed.run(); }
void close() { changed = null; stop(); }
void settings() {
pause();
float speed = prefs.getFloat("recording_speed", 1f);
new AlertDialog.Builder(activity).setTitle("Recording speed")
.setSingleChoiceItems(new String[]{"Unhurried · 0.85×", "Original reading · 1.0×", "A little faster · 1.15×"},
speed < .95f ? 0 : speed > 1.05f ? 2 : 1, (dialog, which) -> {
prefs.edit().putFloat("recording_speed", new float[]{.85f,1f,1.15f}[which]).apply(); dialog.dismiss();
}).setNegativeButton("Keep this speed",null).show();
}
}
@@ -0,0 +1,210 @@
package com.lumen.daily;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Typeface;
import android.os.Build;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
/** Six opening leaves, with fixed navigation and overflow scrolling for larger text. */
final class StoryNotebook {
interface Actions {
void turn(int direction);
void contents();
void home();
void refresh();
void continueCampaign();
View puzzle();
}
final NotebookPage view;
private final Activity activity;
private final SharedPreferences prefs;
private final StoryNarrator narrator;
private final Actions actions;
private final StoryBook.Page page;
private final LinearLayout body;
private TextView narrationText;
private static Bitmap cottage, lantern;
StoryNotebook(Activity activity, SharedPreferences prefs, StoryNarrator narrator, int index, Actions actions) {
this.activity = activity; this.prefs = prefs; this.narrator = narrator; this.actions = actions;
page = StoryBook.PAGES[index];
LinearLayout sheet = column();
sheet.setPadding(dp(10), dp(8), dp(10), dp(6));
ScrollView reader = new ScrollView(activity);
reader.setFillViewport(false);
body = column();
reader.addView(body);
sheet.addView(reader, new LinearLayout.LayoutParams(-1, 0, 1));
addLabel("MARA’S NOTEBOOK / " + (index + 1) + " OF 6", 10, JournalArt.BLUE, false);
addLabel(page.title, page.kind == StoryBook.Kind.DEDICATION ? 29 : 25, JournalArt.INK, false);
buildPage();
navigation(sheet, index);
view = new NotebookPage(activity, sheet);
view.setPageTurn(actions::turn);
if (Build.VERSION.SDK_INT >= 26 && android.animation.ValueAnimator.areAnimatorsEnabled()) {
sheet.setAlpha(.35f); sheet.setTranslationX(dp(12));
sheet.animate().alpha(1f).translationX(0).setDuration(180).start();
}
}
private int dp(float value) { return (int)(value * activity.getResources().getDisplayMetrics().density + .5f); }
private LinearLayout column() { LinearLayout v = new LinearLayout(activity); v.setOrientation(LinearLayout.VERTICAL); return v; }
private TextView label(String value, int size, int color, boolean hand) {
TextView v = new TextView(activity); v.setText(value); v.setTextSize(size <= 11 ? 13 : size == 18 ? 21 : size < 18 ? 18 : size >= 25 ? 29 : size); v.setTextColor(color);
v.setTypeface(JournalArt.HAND);
v.setLineSpacing(dp(2), 1.03f); v.setPadding(0, dp(5), 0, dp(5)); return v;
}
private TextView addLabel(String value, int size, int color, boolean hand) { TextView v = label(value,size,color,hand);body.addView(v);return v; }
private Button action(String title, Runnable run) {
Button v = new Button(activity); v.setText(title);v.setAllCaps(false);v.setTextSize(19);v.setTypeface(JournalArt.HAND);
v.setTextColor(JournalArt.BLUE);v.setStateListAnimator(null);v.setElevation(0);v.setMinHeight(dp(48));
v.setPadding(dp(3),dp(3),dp(3),dp(3));v.setBackground(new JournalArt.InkLine(activity,JournalArt.FADED));
v.setOnClickListener(w -> run.run());return v;
}
private void narration(String text) {
LinearLayout controls = new LinearLayout(activity);
Button play = action(narrator.controlLabel(), () -> narrator.toggle(page.id));
Button stop = action("Stop", narrator::stop);
Button settings = action("Speed", narrator::settings);
controls.addView(play,new LinearLayout.LayoutParams(0,-2,2.7f));
controls.addView(stop,new LinearLayout.LayoutParams(0,-2,1));
controls.addView(settings,new LinearLayout.LayoutParams(0,-2,1));
body.addView(controls);
TextView state=addLabel("A reading kept with this page",10,JournalArt.FADED,false);
final String[] lastPassage = {null};
narrator.bind(() -> {
play.setText(narrator.controlLabel());
String status = narrator.status();
state.setText(status);
play.setEnabled(!narrator.isLoading() && narrator.hasRecording(page.id));
if (narrationText != null) {
SpannableString highlighted=new SpannableString(text);
String current=narrator.currentPassage();
if (current.equals(lastPassage[0])) return;
lastPassage[0] = current;
int at=text.indexOf(current);
if ((narrator.isPlaying()||narrator.isPaused())&&!current.isEmpty()&&at>=0)
highlighted.setSpan(new BackgroundColorSpan(0x55E0B568),at,at+current.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
narrationText.setText(highlighted);
}
});
}
private ImageView illustration(boolean isLantern,int height,String description) {
if (isLantern && lantern==null || !isLantern && cottage==null) {
BitmapFactory.Options options=new BitmapFactory.Options();options.inScaled=false;options.inSampleSize=2;
Bitmap bitmap=BitmapFactory.decodeResource(activity.getResources(),isLantern?R.drawable.story_lantern:R.drawable.story_cottage,options);
if(isLantern)lantern=bitmap;else cottage=bitmap;
}
ImageView image=new ImageView(activity);image.setImageBitmap(isLantern?lantern:cottage);
image.setScaleType(ImageView.ScaleType.FIT_CENTER);image.setContentDescription(description);
body.addView(image,new LinearLayout.LayoutParams(-1,dp(height)));return image;
}
private void buildPage() {
switch(page.kind) {
case DEDICATION:
addLabel("A few things worth keeping",17,JournalArt.FADED,true);
body.addView(new JournalArt.Flower(activity),new LinearLayout.LayoutParams(-1,dp(46)));
narrationText=addLabel(page.text,22,0xff70503b,true);
narration(page.text);
break;
case ENTRY:
illustration(false,155,"Watercolour of Gran’s stone cottage, blue door and a warm window.");
addLabel("A note beside the window · Mara",11,JournalArt.FADED,false);
narrationText=addLabel(page.text,18,JournalArt.INK,false);
narration(page.text);
break;
case PUZZLE:
addLabel("Restore a small light, or leave a bookmark and read on.",14,JournalArt.FADED,false);
body.addView(actions.puzzle());
break;
case MEMORY:
MatchSketch match=new MatchSketch(activity);match.setContentDescription("A pencil sketch of a single match and a small amber flame.");
body.addView(match,new LinearLayout.LayoutParams(-1,dp(140)));
addLabel(prefs.getBoolean("done_story_v1_0",false)?"A pattern restored · a memory kept":"A memory to read · your puzzle can wait",11,JournalArt.FADED,false);
narrationText=addLabel(page.text,18,JournalArt.INK,false);
narration(page.text);
break;
case LETTER:
boolean open=prefs.getBoolean("notebook_note_open",false);
if(!open) {
addLabel("A folded scrap, tucked between the leaves.",19,JournalArt.INK,true);
Envelope envelope=new Envelope(activity);envelope.setContentDescription("Folded note with a wax seal. Double tap to unfold Gran’s note.");
envelope.setFocusable(true);envelope.setOnClickListener(v -> openLetter());
body.addView(envelope,new LinearLayout.LayoutParams(-1,dp(190)));
body.addView(action("Unfold Gran’s note",this::openLetter));
addLabel("You don’t have to solve anything to discover this.",15,JournalArt.FADED,false);
} else {
addLabel("For the crossing",25,0xff70503b,true);
narrationText=addLabel(page.text,20,0xff70503b,true);
narration(page.text);
body.addView(action("Fold the note again",() -> {prefs.edit().putBoolean("notebook_note_open",false).apply();actions.refresh();}));
}
break;
case LANTERN:
ImageView image=illustration(true,155,"Watercolour of Mara’s blue storm lantern. Tap to examine the repaired handle.");
image.setFocusable(true);image.setOnClickListener(v -> inspectLantern());
addLabel(prefs.getBoolean("notebook_handle_seen",false)?"A repair made to keep small fingers safe.":"Tap the lantern to look a little closer.",15,JournalArt.FADED,true);
narrationText=addLabel(page.text,18,JournalArt.INK,false);
narration(page.text);
body.addView(action("Follow the lantern into the next entry →",actions::continueCampaign));
break;
}
}
private void openLetter(){prefs.edit().putBoolean("notebook_note_open",true).apply();actions.refresh();}
private void inspectLantern(){
prefs.edit().putBoolean("notebook_handle_seen",true).apply();
new android.app.AlertDialog.Builder(activity).setTitle("A careful repair")
.setMessage("The wire is hidden under a strip of cloth. In the margin, Gran has written: ‘The light matters. So do the hands carrying it.’")
.setPositiveButton("Keep that thought",(d,w)->actions.refresh()).show();
}
private void navigation(LinearLayout sheet,int index) {
LinearLayout tools=new LinearLayout(activity);
Button contents=action("Contents",actions::contents);
Button mark=action("Bookmark",()->{prefs.edit().putString("notebook_manual_bookmark",page.id).apply();Toast.makeText(activity,"A ribbon marks this page.",Toast.LENGTH_SHORT).show();});
Button home=action("Close book",actions::home);
for(Button button:new Button[]{contents,mark,home})tools.addView(button,new LinearLayout.LayoutParams(0,-2,1));
sheet.addView(tools);
LinearLayout turns=new LinearLayout(activity);
Button previous=action("← Previous leaf",()->actions.turn(-1));previous.setEnabled(index>0);previous.setAlpha(index>0?1f:.35f);
Button next=action(index==StoryBook.PAGES.length-1?"End of this trail":"Next leaf →",()->actions.turn(1));
next.setEnabled(index<StoryBook.PAGES.length-1);next.setAlpha(index<StoryBook.PAGES.length-1?1f:.35f);
turns.addView(previous,new LinearLayout.LayoutParams(0,-2,1));turns.addView(next,new LinearLayout.LayoutParams(0,-2,1));sheet.addView(turns);
}
private static final class MatchSketch extends View {
private final Paint p=new Paint(3);
MatchSketch(Activity c){super(c);}
@Override protected void onDraw(Canvas c){float h=getHeight(),x=getWidth()*.51f;
p.setColor(0xff997445);p.setStrokeWidth(h*.045f);c.drawLine(x-25,h*.88f,x+12,h*.36f,p);
p.setColor(0xff654539);c.drawOval(x+2,h*.27f,x+26,h*.41f,p);
p.setColor(0xAADEA94C);Path f=new Path();f.moveTo(x+12,h*.33f);f.cubicTo(x-24,h*.17f,x+30,h*.19f,x+17,h*.05f);f.cubicTo(x+56,h*.20f,x+32,h*.33f,x+12,h*.33f);c.drawPath(f,p);
p.setColor(0xff7d7360);p.setStrokeWidth(1);c.drawLine(x-85,h*.91f,x+80,h*.91f,p);
}
}
private static final class Envelope extends View {
private final Paint p=new Paint(3);
Envelope(Activity c){super(c);}
@Override protected void onDraw(Canvas c){float w=getWidth(),h=getHeight(),l=w*.1f,r=w*.9f,t=h*.15f,b=h*.86f;
p.setColor(0x255D4930);c.drawRect(l+4,t+5,r+4,b+5,p);p.setColor(0xffead9b2);c.drawRect(l,t,r,b,p);
p.setColor(0xffb8a17c);p.setStrokeWidth(2);p.setStyle(Paint.Style.STROKE);c.drawRect(l,t,r,b,p);
c.drawLine(l,t,w*.5f,h*.59f,p);c.drawLine(r,t,w*.5f,h*.59f,p);c.drawLine(l,b,w*.40f,h*.50f,p);c.drawLine(r,b,w*.60f,h*.50f,p);p.setStyle(Paint.Style.FILL);
p.setColor(0xff9e5f49);c.drawCircle(w*.5f,h*.57f,h*.075f,p);
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
<path android:fillColor="#274956" android:pathData="M0,0h108v108h-108z"/>
<path android:fillColor="#E0B568" android:fillAlpha="0.5" android:pathData="M58,34L7,19L7,49z"/>
<path android:fillColor="#F3E7CC" android:pathData="M53,45L68,45L76,87L45,87z"/>
<path android:fillColor="#A35C48" android:pathData="M49,65L72,65L73,73L48,73z"/>
<path android:fillColor="#E0B568" android:pathData="M51,31h19v12h-19z"/>
<path android:fillColor="#172F3A" android:pathData="M46,30L61,18L76,30z M47,43h27v5h-27z M57,77h8v10h-8z"/>
<path android:fillColor="#8A9F9B" android:pathData="M14,92h80v2h-80z M19,98h38v1h-38z M68,98h22v1h-22z"/>
</vector>
Binary file not shown.
@@ -0,0 +1,144 @@
{
"tracks": {
"cottage.dedication": {
"pageId": "cottage.dedication",
"resource": "narration_cottage_dedication",
"text": "My dear,\n\nI never could keep a proper diary. I wrote down the tides, the things that needed mending, and whatever I was afraid I might forget.\n\nYou will find a little of all three in here. Take your time. There is no right way to turn these pages.\n\nWith all my love,\nGran",
"file": "narration_cottage_dedication.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 441184,
"durationMs": 18383,
"textSha256": "7ecbea473a70ab48a49861535bf30a3909005ce5735dcd048bc6abe576b1e017",
"flacSha256": "7606f2ea97386ed864155438d2785f6d8e6593fc04d785d432dfceb07bff52b7",
"cues": [
{
"startMs": 180,
"endMs": 9268,
"text": "My dear,\n\nI never could keep a proper diary. I wrote down the tides, the things that needed mending, and whatever I was afraid I might forget."
},
{
"startMs": 9868,
"endMs": 17783,
"text": "You will find a little of all three in here. Take your time. There is no right way to turn these pages.\n\nWith all my love,\nGran"
}
]
},
"cottage.window": {
"pageId": "cottage.window",
"resource": "narration_cottage_window",
"text": "The wind has finally gone quiet. I have put the blue cup by the window, where you always liked to sit.\n\nThe latch still sticks. Lift it a little before you turn it. Some things on this island need a gentle hand, not a stronger one.\n\nIf you arrive after dark, there is something in the little drawer beside the hearth.",
"file": "narration_cottage_window.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 499104,
"durationMs": 20796,
"textSha256": "10b04750290618c667a1ab3e92247d59ea6796ac33c910906b292b6735da204c",
"flacSha256": "01864da94337c06445b60694faf2484c4a59f5f11fabc0f8d8b87a620ee09193",
"cues": [
{
"startMs": 180,
"endMs": 6473,
"text": "The wind has finally gone quiet. I have put the blue cup by the window, where you always liked to sit."
},
{
"startMs": 7073,
"endMs": 15009,
"text": "The latch still sticks. Lift it a little before you turn it. Some things on this island need a gentle hand, not a stronger one."
},
{
"startMs": 15609,
"endMs": 20196,
"text": "If you arrive after dark, there is something in the little drawer beside the hearth."
}
]
},
"cottage.match.memory": {
"pageId": "cottage.match.memory",
"resource": "narration_cottage_match_memory",
"text": "You used to insist on lighting the evening lantern yourself. I held the matchbox, and you held your breath.\n\nOnce, you asked how such a little flame could help anyone out at sea.\n\nIt cannot, I told you. But it can help us find the next light.\n\nI kept one dry match in a tin after that. Just in case.",
"file": "narration_cottage_match_memory.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 506848,
"durationMs": 21119,
"textSha256": "b047af77227d4084883babe2d7bec9cbebf8a3d807cf8d45b72e76f72db9eac5",
"flacSha256": "6cd5fadf22ce6f8ebc6a9c8968e87fb1b31a0f1e52693c7e942d8498691a533c",
"cues": [
{
"startMs": 180,
"endMs": 6644,
"text": "You used to insist on lighting the evening lantern yourself. I held the matchbox, and you held your breath."
},
{
"startMs": 7244,
"endMs": 11212,
"text": "Once, you asked how such a little flame could help anyone out at sea."
},
{
"startMs": 11812,
"endMs": 15801,
"text": "It cannot, I told you. But it can help us find the next light."
},
{
"startMs": 16401,
"endMs": 20519,
"text": "I kept one dry match in a tin after that. Just in case."
}
]
},
"cottage.folded.note": {
"pageId": "cottage.folded.note",
"resource": "narration_cottage_folded_note",
"text": "If the tide has covered the causeway, use the little boat by the harbour steps. The knot looks worse than it is.\n\nTake the lantern. When you reach the bell, ring twice. I will know it is you.\n\nAnd do not let the tea go cold while you are deciding.\n\nLove, Gran",
"file": "narration_cottage_folded_note.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 425888,
"durationMs": 17745,
"textSha256": "2101efa580ab39cff6956a3e0011d5399e820aca79f9f60a25848487c6bcb9ad",
"flacSha256": "3675b260102c1b157e8741ff6ed9d062735860d33a15d1bbe397d997e91a2403",
"cues": [
{
"startMs": 180,
"endMs": 6964,
"text": "If the tide has covered the causeway, use the little boat by the harbour steps. The knot looks worse than it is."
},
{
"startMs": 7564,
"endMs": 12108,
"text": "Take the lantern. When you reach the bell, ring twice. I will know it is you."
},
{
"startMs": 12708,
"endMs": 17145,
"text": "And do not let the tea go cold while you are deciding.\n\nLove, Gran"
}
]
},
"cottage.lantern.sketch": {
"pageId": "cottage.lantern.sketch",
"resource": "narration_cottage_lantern_sketch",
"text": "Your grandfather repaired this handle with a piece of wire and far too much confidence. I wrapped the join so it would not catch your fingers.\n\nPeople notice the flame first. I tend to notice the things that let us carry it.",
"file": "narration_cottage_lantern_sketch.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 366944,
"durationMs": 15289,
"textSha256": "fbfc663172995a1beb20b48e65b8f469b44b7bf26609721fe34b158ecc9bdf97",
"flacSha256": "60a823473a66b1ea4c5156889f66fe276bc103db475a3e6c831cd41649d7cbd3",
"cues": [
{
"startMs": 180,
"endMs": 8735,
"text": "Your grandfather repaired this handle with a piece of wire and far too much confidence. I wrapped the join so it would not catch your fingers."
},
{
"startMs": 9335,
"endMs": 14689,
"text": "People notice the flame first. I tend to notice the things that let us carry it."
}
]
}
}
}
+1
View File
@@ -0,0 +1 @@
<resources><style name="AppTheme" parent="BaseAppTheme"><item name="android:navigationBarColor">#F3E7CC</item><item name="android:windowLightNavigationBar">true</item></style></resources>
+1
View File
@@ -0,0 +1 @@
<resources><style name="BaseAppTheme" parent="android:style/Theme.Material.Light.NoActionBar"><item name="android:fontFamily">cursive</item><item name="android:colorAccent">#274956</item><item name="android:windowLightStatusBar">true</item><item name="android:statusBarColor">#F3E7CC</item><item name="android:navigationBarColor">#314345</item></style><style name="AppTheme" parent="BaseAppTheme"/></resources>
@@ -0,0 +1 @@
<data-extraction-rules><cloud-backup><exclude domain="root" path="."/><exclude domain="sharedpref" path="."/><exclude domain="database" path="."/><exclude domain="file" path="."/></cloud-backup><device-transfer><exclude domain="root" path="."/><exclude domain="sharedpref" path="."/><exclude domain="database" path="."/><exclude domain="file" path="."/></device-transfer></data-extraction-rules>
@@ -0,0 +1,76 @@
package com.lumen.daily;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.*;
public class CampaignTest {
@Test public void everyPictureIsUniqueAndSolvableWithoutSearch() {
Set<String> pictures = new HashSet<>();
assertEquals(12, Campaign.LEVELS.length);
for (int level = 0; level < Campaign.LEVELS.length; level++) {
Puzzle p = Campaign.puzzle(level);
assertEquals(7, p.size);
assertEquals(49, p.solution.length);
assertTrue(pictures.add(java.util.Arrays.toString(p.solution)));
assertEquals("level " + level, 1, p.countSolutions());
LogicSolver solver = new LogicSolver(49, p.constraints());
LogicSolver.Analysis a = solver.analyze(LogicSolver.initial(p), true);
assertTrue("level " + level, a.solved);
assertArrayEquals(p.solution, a.cells);
if (level >= 2) {
assertEquals(3, p.regions.size());
assertFalse("Area comparisons must actually be required at level " + level,
solver.analyze(LogicSolver.initial(p), false).solved);
assertTrue(a.areaDeductions > 0);
// The added areas genuinely resolve ambiguity in the original rules.
Puzzle rowsOnly = new Puzzle(7, p.solution);
System.arraycopy(p.given, 0, rowsOnly.given, 0, p.given.length);
assertEquals(2, rowsOnly.countSolutions());
}
for (Puzzle.Region r : p.regions) {
assertTrue(r.top >= 0 && r.left >= 0 && r.top + r.height <= 7 && r.left + r.width <= 7);
int sum = 0;
for (int cell = 0; cell < 49; cell++) if (r.contains(cell, 7)) sum += p.solution[cell];
assertEquals(sum, p.regionTotal(r));
}
}
}
@Test public void explainedHintsCanCompleteEveryStoryBoard() {
for (int level = 0; level < 12; level++) {
Puzzle p = Campaign.puzzle(level);
LogicSolver solver = new LogicSolver(49, p.constraints());
int[] known = LogicSolver.initial(p);
for (int step = 0; step < 49; step++) {
LogicSolver.Hint hint = solver.nextHint(known);
if (hint == null) break;
assertEquals(-1, known[hint.cell]);
assertEquals(p.solution[hint.cell], hint.value);
assertFalse(hint.explanation.isEmpty());
known[hint.cell] = hint.value;
}
assertArrayEquals("level " + level, p.solution, known);
}
}
@Test public void completionRequiresEveryMarkAndRegenerationIsStable() {
for (int level = 0; level < 12; level++) {
Puzzle p = Campaign.puzzle(level), q = Campaign.puzzle(level);
assertArrayEquals(p.solution, q.solution);
assertArrayEquals(p.given, q.given);
int[] marks = new int[49];
for (int i = 0; i < 49; i++) marks[i] = p.solution[i] == 1 ? 1 : 2;
assertTrue(p.solved(marks));
marks[48] = 0;
assertFalse(p.solved(marks));
}
}
@Test public void restoredProgressIsClamped() {
assertEquals(0, Campaign.unlocked(-2));
assertEquals(11, Campaign.unlocked(12));
assertEquals(5, Campaign.unlocked(5));
}
}
@@ -0,0 +1,6 @@
package com.lumen.daily;
import org.junit.Test;import static org.junit.Assert.*;
public class DailyStreakTest {
@Test public void consecutiveDaysAndReplay(){assertEquals(1,DailyStreak.afterCompletion(-99999,0,20000));assertEquals(4,DailyStreak.afterCompletion(20000,3,20001));assertEquals(3,DailyStreak.afterCompletion(20000,3,20000));}
@Test public void missedDayResetsAndGraceLastsThroughNextDay(){assertEquals(1,DailyStreak.afterCompletion(20000,3,20002));assertEquals(3,DailyStreak.visible(20000,3,20001));assertEquals(0,DailyStreak.visible(20000,3,20002));}
}
@@ -0,0 +1,49 @@
package com.lumen.daily;
import org.junit.Test;
import static org.junit.Assert.*;
public class DifficultyTest {
@Test public void everyModeMatchesItsGradeWithoutGuessing() {
for (Difficulty difficulty : Difficulty.values()) {
for (long seed = 0; seed < 500; seed++) {
Puzzle p = Puzzle.generate(seed, difficulty);
assertEquals("seed " + seed, difficulty, p.difficulty());
assertEquals(1, p.countSolutions());
int rounds = p.deductionRounds();
if (difficulty == Difficulty.EASY) assertTrue(rounds <= 2);
if (difficulty == Difficulty.MEDIUM) assertTrue(rounds >= 3 && rounds <= 4);
if (difficulty == Difficulty.HARD) assertEquals(5, rounds);
}
}
}
@Test public void generationIsStableForSavedBoards() {
for (Difficulty d : Difficulty.values()) for (int seed = 0; seed < 30; seed++) {
Puzzle a = Puzzle.generate(seed, d), b = Puzzle.generate(seed, d);
assertArrayEquals(a.solution, b.solution);
assertArrayEquals(a.given, b.given);
assertArrayEquals(a.rows, b.rows);
assertArrayEquals(a.cols, b.cols);
}
}
@Test public void graderUsesOnlyCluesAndRejectsAmbiguousBoards() {
Puzzle p = new Puzzle(0);
java.util.Arrays.fill(p.given, false);
java.util.Arrays.fill(p.rows, 2);
java.util.Arrays.fill(p.cols, 2);
try { p.deductionRounds(); fail("Ambiguous board must not receive a grade"); }
catch (IllegalStateException expected) { assertEquals("Puzzle requires guessing", expected.getMessage()); }
}
@Test public void originalBoardsStayCompatible() {
Puzzle p = new Puzzle(0);
assertArrayEquals(new int[]{1,1,0,1,1,0,1,0,1,1,0,0,0,1,1,1,1,0,1,0,0,0,0,0,0},p.solution);
}
@Test public void invalidStoredSelectionFallsBackToEasy() {
assertEquals(Difficulty.EASY, Difficulty.fromStored("UNKNOWN"));
assertEquals(Difficulty.HARD, Difficulty.fromStored("HARD"));
}
}
@@ -0,0 +1,64 @@
package com.lumen.daily;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import static org.junit.Assert.*;
public class LogicSolverTest {
@Test public void overlappingDifferenceFindsWhatSingleTotalsCannot() {
List<LogicSolver.Constraint> constraints = Arrays.asList(
new LogicSolver.Constraint(new int[]{0, 1, 2}, 1, "Area A"),
new LogicSolver.Constraint(new int[]{1, 2}, 1, "Area B"));
LogicSolver solver = new LogicSolver(3, constraints);
int[] initial = {-1, -1, -1};
assertArrayEquals(initial, solver.analyze(initial, false).cells);
LogicSolver.Hint hint = solver.nextHint(initial);
assertNotNull(hint);
assertEquals(0, hint.cell);
assertEquals(0, hint.value);
assertTrue(hint.explanation.contains("Shared"));
assertEquals(0, solver.analyze(initial, true).cells[0]);
}
@Test public void searchAndDeductionsAgreeWithExhaustiveEnumeration() {
Random random = new Random(18273);
for (int trial = 0; trial < 1000; trial++) {
List<LogicSolver.Constraint> constraints = new ArrayList<>();
for (int c = 0; c < 5; c++) {
List<Integer> indices = new ArrayList<>();
for (int i = 0; i < 6; i++) if (random.nextBoolean()) indices.add(i);
int[] cells = new int[indices.size()];
for (int i = 0; i < cells.length; i++) cells[i] = indices.get(i);
constraints.add(new LogicSolver.Constraint(cells, random.nextInt(cells.length + 1)));
}
int[] initial = {-1, -1, -1, -1, -1, -1};
if (random.nextBoolean()) initial[random.nextInt(6)] = random.nextInt(2);
List<int[]> solutions = new ArrayList<>();
for (int mask = 0; mask < 64; mask++) {
int[] values = new int[6]; boolean valid = true;
for (int i = 0; i < 6; i++) {
values[i] = (mask >> i) & 1;
if (initial[i] >= 0 && initial[i] != values[i]) valid = false;
}
for (LogicSolver.Constraint c : constraints) {
int sum = 0; for (int i : c.cells) sum += values[i];
if (sum != c.total) valid = false;
}
if (valid) solutions.add(values);
}
LogicSolver solver = new LogicSolver(6, constraints);
assertEquals(Math.min(2, solutions.size()), solver.countSolutions(initial));
if (!solutions.isEmpty()) {
LogicSolver.Hint hint = solver.nextHint(initial);
LogicSolver.Analysis analysis = solver.analyze(initial, true);
for (int[] solution : solutions) {
if (hint != null) assertEquals(solution[hint.cell], hint.value);
for (int i = 0; i < 6; i++) if (analysis.cells[i] >= 0) assertEquals(solution[i], analysis.cells[i]);
}
}
}
}
}
@@ -0,0 +1,8 @@
package com.lumen.daily;
import org.junit.Test;
import static org.junit.Assert.*;
public class PageTurnGestureTest {
@Test public void gridDragCannotBecomeAPageTurn(){PageTurnGesture g=new PageTurnGesture();assertFalse(g.begin(300,400,100,700,22));assertFalse(g.intercept(650,400,28));assertEquals(0,g.finish(650,400,48));}
@Test public void marginsTurnInBothDirections(){PageTurnGesture g=new PageTurnGesture();assertTrue(g.begin(690,400,100,700,22));assertTrue(g.intercept(600,401,28));assertEquals(1,g.finish(500,403,48));assertTrue(g.begin(110,400,100,700,22));assertEquals(-1,g.finish(300,410,48));}
@Test public void verticalScrollTinyMovesAndCancellationDoNotTurn(){PageTurnGesture g=new PageTurnGesture();g.begin(110,400,100,700,22);assertEquals(0,g.finish(120,650,48));g.begin(110,400,100,700,22);assertEquals(0,g.finish(135,402,48));g.begin(110,400,100,700,22);g.cancel();assertEquals(0,g.finish(300,400,48));}
}
@@ -0,0 +1,5 @@
package com.lumen.daily;
import org.junit.Test; import static org.junit.Assert.*;
public class PuzzleTest {
@Test public void generatedBoardsAreUniqueAndDeterministic(){for(long seed=0;seed<500;seed++){Puzzle p=new Puzzle(seed), q=new Puzzle(seed); assertEquals(1,p.countSolutions());assertArrayEquals(p.solution,q.solution);assertArrayEquals(p.given,q.given);int[] cells=new int[25];for(int i=0;i<25;i++)cells[i]=p.solution[i]==1?1:2;assertTrue(p.solved(cells));cells[0]=0;assertFalse(p.solved(cells));}}
}
@@ -0,0 +1,16 @@
package com.lumen.daily;
import org.junit.Test;
import static org.junit.Assert.*;
public class StoryBookTest {
@Test public void bookmarksResolveStableIdsAndUnknownIdsRecover(){
String[] ids={"cottage.dedication","cottage.window","cottage.match.puzzle","cottage.match.memory","cottage.folded.note","cottage.lantern.sketch"};
assertEquals(ids.length,StoryBook.PAGES.length);
for(int i=0;i<ids.length;i++){assertEquals(ids[i],StoryBook.PAGES[i].id);assertEquals(i,StoryBook.indexOf(ids[i]));}
assertEquals(0,StoryBook.indexOf("removed.page"));assertEquals(0,StoryBook.indexOf(null));
}
@Test public void pageBoundariesCannotEscapeTheBook(){assertEquals(0,StoryBook.turn(0,-1));assertEquals(5,StoryBook.turn(5,1));assertEquals(3,StoryBook.turn(2,1));}
@Test public void spokenPassagesKeepSentenceBoundaries(){
assertArrayEquals(new String[]{"My dear,","Come home.","Is the lamp lit?","Yes!"},StoryBook.sentences("My dear,\n\nCome home. Is the lamp lit? Yes!"));
for(StoryBook.Page page:StoryBook.PAGES)for(String sentence:StoryBook.sentences(page.text))assertFalse(sentence.trim().isEmpty());
}
}