chore: freeze v1.1.3 filing submission build (60 levels, full-screen safe layout)

This commit is contained in:
fannyxl committed 2026-11-25 23:14:45 +08:00
commit 96c19dca82
174 files changed
+37935

No files matched your search

+601
View File
@@ -0,0 +1,601 @@
import { CHAPTERS, LEVELS, recordKey } from './LevelData';
import { LevelDef } from './Types';
export type PosterFrameId = 'celadon' | 'walnut' | 'rouge' | 'gilded';
export type PosterQuoteId = 'craft' | 'breeze' | 'meeting' | 'blossom';
export interface ChapterLetterDef {
chapter: number;
senderZh: string;
senderEn: string;
titleZh: string;
titleEn: string;
requestZh: string;
requestEn: string;
replyTitleZh: string;
replyTitleEn: string;
replyZh: string;
replyEn: string;
}
export interface PosterFrameDef {
id: PosterFrameId;
nameZh: string;
nameEn: string;
cost: number;
bgTop: string;
bgBottom: string;
border: string;
accent: string;
cardBg: string;
cardStroke: string;
}
export interface PosterQuoteDef {
id: PosterQuoteId;
zh: string;
en: string;
cost: number;
}
export interface GalleryItem {
levelIndex: number;
levelId: string;
stars: number;
length: number;
frameId: PosterFrameId;
quoteId: PosterQuoteId;
savedAt: number;
}
export interface AntDiaryDef {
id: string;
titleZh: string;
titleEn: string;
moodZh: string;
moodEn: string;
bodyZh: string;
bodyEn: string;
accentColor: string;
}
export interface AtelierSaveData {
yarnThreads: number;
pendingThreads: number;
lastTickAt: number;
unlockedFrames: PosterFrameId[];
unlockedQuotes: PosterQuoteId[];
activeFrame: PosterFrameId;
activeQuote: PosterQuoteId;
unlockedDiaries: string[];
gallery: GalleryItem[];
welcomed: boolean;
}
export const IDLE_MINUTES_PER_THREAD = 10;
export const IDLE_MAX_THREADS = 48; // 8 小时封顶,不清零,零焦虑
export const POSTER_FRAMES: PosterFrameDef[] = [
{
id: 'celadon',
nameZh: '青瓷松绿',
nameEn: 'Celadon Linen',
cost: 0,
bgTop: '#627052',
bgBottom: '#4e5c41',
border: 'rgba(246, 232, 198, 0.34)',
accent: '#efe0bd',
cardBg: '#f8f1df',
cardStroke: '#d7c297',
},
{
id: 'walnut',
nameZh: '温润胡桃',
nameEn: 'Warm Walnut',
cost: 20,
bgTop: '#5b3f28',
bgBottom: '#422c1b',
border: 'rgba(242, 206, 132, 0.42)',
accent: '#f6d899',
cardBg: '#faf2e1',
cardStroke: '#cca35e',
},
{
id: 'rouge',
nameZh: '山茶胭脂',
nameEn: 'Camellia Rouge',
cost: 40,
bgTop: '#7d4547',
bgBottom: '#5e3134',
border: 'rgba(255, 226, 204, 0.38)',
accent: '#fde3cc',
cardBg: '#fdf4ea',
cardStroke: '#d8a69d',
},
{
id: 'gilded',
nameZh: '宋韵描金',
nameEn: 'Gilded Song',
cost: 70,
bgTop: '#314449',
bgBottom: '#213035',
border: 'rgba(248, 211, 118, 0.56)',
accent: '#f9d87d',
cardBg: '#fbf5e4',
cardStroke: '#d9b059',
},
];
export const POSTER_QUOTES: PosterQuoteDef[] = [
{ id: 'craft', zh: '一针一线 · 慢享手作好时光', en: 'Stitch by stitch · Slow cozy craft', cost: 0 },
{ id: 'breeze', zh: '愿此间清风,伴君岁岁安好', en: 'May gentle breeze keep every season bright', cost: 15 },
{ id: 'meeting', zh: '拾光入绣,见画如晤', en: 'Woven sunlight, warm as meeting again', cost: 30 },
{ id: 'blossom', zh: '繁花入梦,针脚生香', en: 'Blossoms in dreams, fragrance in thread', cost: 45 },
];
export const CHAPTER_LETTERS: ChapterLetterDef[] = [
{
chapter: 0,
senderZh: '窗台养花的林阿婆',
senderEn: 'Grandma Lin',
titleZh: '给阳台的向日葵',
titleEn: 'Sunflowers for the Window',
requestZh: '小绣娘安好:今秋连绵阴雨,阳台的向日葵垂了头。想请你和工坊的小蚂蚁,替我绣一束永不低头的暖黄繁花,挂在茶几旁添点晴色。',
requestEn: 'Dear stitcher, autumn rain bowed my balcony sunflowers. Could you and your little ants stitch a sunny bouquet that never fades?',
replyTitleZh: '林阿婆的回信',
replyTitleEn: 'Reply from Grandma Lin',
replyZh: '绣画挂上墙的那一刻,整间茶室都亮堂起来!老邻居们来喝茶,都夸这针脚细密又暖心,连小蚂蚁搬线的模样都讨人喜欢。',
replyEn: 'The moment we hung your embroidery, the whole tea room brightened! Every neighbor admired the neat golden stitches.',
},
{
chapter: 1,
senderZh: '观鸟手账画师 · 苏禾',
senderEn: 'Suhe the Birdwatcher',
titleZh: '林间一抹翠羽',
titleEn: 'A Flash of Kingfisher Blue',
requestZh: '上月在溪畔偶遇一只俯冲的蓝翠鸟,快门慢了半拍没留住。听闻蚂蚁织画馆善绣灵禽,能否替我把那抹湖蓝留在手帕上?',
requestEn: 'I spotted a kingfisher diving by the creek last month, too fast for my camera. Could you capture that flash of lake-blue in silk?',
replyTitleZh: '苏禾的回信',
replyTitleEn: 'Reply from Suhe',
replyZh: '太灵动了!这抹翠羽蓝竟和我记忆里一模一样,我已经夹进观鸟手账扉页,以后每次翻开都能听见溪水声。',
replyEn: 'So vivid! That exact feather blue now rests on the opening page of my field journal.',
},
{
chapter: 2,
senderZh: '爱猫的插画生 · 小柚',
senderEn: 'Youyou the Cat Lover',
titleZh: '午后打盹的橘团子',
titleEn: 'Napping Ginger Cat',
requestZh: '我家橘猫团子最爱蜷在暖气片旁呼噜噜睡大觉。想订一幅软绵绵的萌宠手绣,寄给远方念书的姐姐解解馋。',
requestEn: 'My ginger cat loves curling up in afternoon sunbeams. I want to mail a cozy embroidered portrait to my sister studying abroad.',
replyTitleZh: '小柚的回信',
replyTitleEn: 'Reply from Youyou',
replyZh: '姐姐收到当天就拍了合照!她说摸着绒绒的橘色绣线,就像真的撸到了团子软乎乎的小肚皮。',
replyEn: 'My sister hugged it the day it arrived—she says the plush orange threads feel just like petting our cat!',
},
{
chapter: 3,
senderZh: '远行建筑师 · 沈砚',
senderEn: 'Shen Yan the Traveler',
titleZh: '梦里的江南石桥',
titleEn: 'Jiangnan Stone Bridge',
requestZh: '在北方奔波三年,夜里总想起故乡青瓦白墙与弯弯石桥。烦请以青绿丝线入画,替我绣一方可随身携带的烟雨江南。',
requestEn: 'After three years up north, I still dream of home—white walls and an arched stone bridge. Stitch a pocket of Jiangnan for me?',
replyTitleZh: '沈砚的回信',
replyTitleEn: 'Reply from Shen Yan',
replyZh: '桥影流水层次分明,真有水墨晕染之韵。出差的行囊里多了这幅绣片,走到哪儿都像带着故乡的风。',
replyEn: 'The layered greens and arching bridge feel like ink painting in silk. Wherever I travel now, home comes along.',
},
{
chapter: 4,
senderZh: '刚搬新家的温宁',
senderEn: 'Wenning’s New Home',
titleZh: '红顶小屋乔迁礼',
titleEn: 'Red-Roof Cottage Gift',
requestZh: '终于攒够钱买下了带小院的新家!玄关还空着一面暖白墙,想请你们绣一栋亮着暖灯的红顶童话屋,当作家里的第一件藏品。',
requestEn: 'We finally moved into a little house with a yard! Could you stitch a warm red-roof cottage as our very first entryway piece?',
replyTitleZh: '温宁的回信',
replyTitleEn: 'Reply from Wenning',
replyZh: '昨晚装框挂在玄关,回家推开门第一眼就看见窗格里的暖光,疲惫一下子散了一半,谢谢你们的一针一线!',
replyEn: 'Framed by the front door—seeing those warm stitched windows every evening melts the day’s fatigue right away.',
},
{
chapter: 5,
senderZh: '巷口甜品店主 · 夏茉',
senderEn: 'Xiamo the Pastry Chef',
titleZh: '周年纪念草莓蛋糕',
titleEn: 'Anniversary Shortcake',
requestZh: '小店开张满一周年啦!想请蚂蚁工坊把招牌草莓奶油蛋糕绣成精致桌旗,放在收银台边见证每一个甜甜的午后。',
requestEn: 'Our little bakery turns one this week! Would your ant atelier stitch our signature strawberry shortcake for the counter?',
replyTitleZh: '夏茉的回信',
replyTitleEn: 'Reply from Xiamo',
replyZh: '客人们进门先对着这幅草莓蛋糕拍照!奶油的蓬松和草莓红太逼真了,下次你来小店,红茶和蛋糕一律免单!',
replyEn: 'Every customer snaps a photo of the stitched cake first! Tea and shortcake are on the house whenever you visit!',
},
];
export const ANT_DIARIES: AntDiaryDef[] = [
{
id: 'dawn-thread',
titleZh: '第一缕晨光',
titleEn: 'First Morning Thread',
moodZh: '搬线中',
moodEn: 'Carrying',
bodyZh: '今天刚开门,领头小蚁就挑了一根最亮的金丝线,在阳光晒暖的亚麻布上试走了三圈。',
bodyEn: 'At sunrise, our lead ant picked the brightest gold thread and marched three cheerful laps across warm linen.',
accentColor: '#d99a2e',
},
{
id: 'tea-steam',
titleZh: '抹茶雾气里的打盹',
titleEn: 'Nap by Matcha Steam',
moodZh: '打盹中',
moodEn: 'Napping',
bodyZh: '午后茶杯飘来淡淡茶香,两只小工蚁靠着线轴眯了十分钟,触角还一翘一翘地数针脚。',
bodyEn: 'Warm tea steam drifted across the desk. Two helper ants napped against a spool, antennae twitching in rhythm.',
accentColor: '#6f9454',
},
{
id: 'spool-parade',
titleZh: '圆滚滚的线球体操',
titleEn: 'Yarn Ball Parade',
moodZh: '列队中',
moodEn: 'Parading',
bodyZh: '三只小蚂蚁排成一字长蛇把玫瑰粉毛线球推回木槽,走过的地方留下了一串歪歪扭扭的小脚印。',
bodyEn: 'Three ants formed a tidy parade rolling a rose yarn ball back into the tray, leaving tiny proud footprints.',
accentColor: '#cc6c86',
},
{
id: 'brass-scissors',
titleZh: '鹤嘴剪上的倒影',
titleEn: 'Mirror on Brass Scissors',
moodZh: '臭美中',
moodEn: 'Admiring',
bodyZh: '最小的那只蚂蚁爬上黄铜鹤嘴剪照了半天镜子,认真理了理两根金尖触角才肯继续开工。',
bodyEn: 'The smallest ant checked its reflection on the brass crane scissors and tidied both antennae before working.',
accentColor: '#b98b3f',
},
{
id: 'chamomile-petal',
titleZh: '一片洋甘菊花瓣',
titleEn: 'A Chamomile Petal',
moodZh: '拾荒中',
moodEn: 'Gathering',
bodyZh: '风吹落了一片洋甘菊花瓣在绣绷边缘,小蚂蚁们合力把它做成午休小凉伞。',
bodyEn: 'A breeze dropped a chamomile petal by the hoop; the ants turned it into a cozy sunshade for break time.',
accentColor: '#d6a444',
},
{
id: 'indigo-dye',
titleZh: '沾到天青色的脚丫',
titleEn: 'Sky-Blue Paws',
moodZh: '染线中',
moodEn: 'Dyeing',
bodyZh: '调色染缸刚开盖,贪玩的小蚁踩了一点天青色,在废布角上歪歪斜斜印出一朵小蓝花。',
bodyEn: 'One curious ant stepped into sky-blue dye and accidentally stamped a tiny blue blossom on scrap linen.',
accentColor: '#578ea9',
},
{
id: 'rainy-hoop',
titleZh: '雨声与八音盒',
titleEn: 'Raindrops & Music Box',
moodZh: '听雨中',
moodEn: 'Listening',
bodyZh: '窗外下起淅沥小雨,工坊里叮咚的八音盒配着穿针沙沙声,连打结的毛线都顺滑起来。',
bodyEn: 'Soft rain tapped outside while the music box chimed—even the tangled skeins untied themselves smoothly.',
accentColor: '#6f8799',
},
{
id: 'button-bridge',
titleZh: '木纽扣小桥',
titleEn: 'Wooden Button Bridge',
moodZh: '搭桥中',
moodEn: 'Building',
bodyZh: '小蚂蚁把四眼木纽扣当成转盘练习绕线,今天一次都没打结,集体奖励半颗松仁碎!',
bodyEn: 'They practiced looping thread around a wooden button with zero tangles—everyone earned a pine-nut crumb!',
accentColor: '#9c6b43',
},
{
id: 'lavender-sachet',
titleZh: '薰衣草香囊边角料',
titleEn: 'Lavender Sachet Scraps',
moodZh: '理线中',
moodEn: 'Sorting',
bodyZh: '收拾针线盒时翻出一小截薰衣草紫线头,工坊今天一整天都香喷喷的。',
bodyEn: 'Found a snip of lavender silk while tidying the sewing box—the whole workshop smelled dreamy all afternoon.',
accentColor: '#8c74b0',
},
{
id: 'sunset-gold',
titleZh: '落日洒在樱桃木上',
titleEn: 'Sunset on Cherry Wood',
moodZh: '收工中',
moodEn: 'Wrapping up',
bodyZh: '傍晚的斜阳把绣绷照得像一块蜜糖饼,小蚂蚁们把剪齐的线头码得整整齐齐等你回来。',
bodyEn: 'Evening light turned the hoop honey-gold. The ants stacked every trimmed thread neatly waiting for you.',
accentColor: '#d67a3e',
},
{
id: 'wax-seal-stamp',
titleZh: '山茶红火漆的秘密',
titleEn: 'Secret of the Wax Seal',
moodZh: '寄信中',
moodEn: 'Mailing',
bodyZh: '每逢绣成新作品,工坊都要盖一枚山茶红火漆。小蚂蚁悄悄说:热乎乎的蜡香最好闻了。',
bodyEn: 'Every finished piece earns a camellia wax seal. The ants whisper that warm sealing wax is their favorite scent.',
accentColor: '#c4524c',
},
{
id: 'starry-atelier',
titleZh: '星光下的守夜蚁',
titleEn: 'Starlight Night Watch',
moodZh: '值班中',
moodEn: 'Guarding',
bodyZh: '夜深了,一盏小暖灯亮在绣绷旁。别担心线头会丢,工坊小队会乖乖替你攒到明天。',
bodyEn: 'A tiny warm lamp glows beside the hoop tonight. Rest easy—the ant crew will keep every thread safe until tomorrow.',
accentColor: '#b3893c',
},
];
function createDefaultSave(nowMs: number): AtelierSaveData {
return {
yarnThreads: 16,
pendingThreads: 4,
lastTickAt: nowMs,
unlockedFrames: ['celadon'],
unlockedQuotes: ['craft'],
activeFrame: 'celadon',
activeQuote: 'craft',
unlockedDiaries: [ANT_DIARIES[0].id],
gallery: [],
welcomed: true,
};
}
export class AtelierService {
private data: AtelierSaveData;
private readonly persist: (raw: string) => void;
constructor(loadRaw: () => string | null, saveRaw: (raw: string) => void) {
this.persist = saveRaw;
this.data = this.parse(loadRaw(), Date.now());
this.settleIdle(Date.now());
}
private parse(raw: string | null, nowMs: number): AtelierSaveData {
const base = createDefaultSave(nowMs);
if (!raw) return base;
try {
const p = JSON.parse(raw);
if (!p || typeof p !== 'object') return base;
const validFrames = new Set(POSTER_FRAMES.map(f => f.id));
const validQuotes = new Set(POSTER_QUOTES.map(q => q.id));
const validDiaries = new Set(ANT_DIARIES.map(d => d.id));
const unlockedFrames: PosterFrameId[] = Array.isArray(p.unlockedFrames)
? p.unlockedFrames.filter((id: any) => validFrames.has(id))
: ['celadon'];
if (!unlockedFrames.includes('celadon')) unlockedFrames.unshift('celadon');
const unlockedQuotes: PosterQuoteId[] = Array.isArray(p.unlockedQuotes)
? p.unlockedQuotes.filter((id: any) => validQuotes.has(id))
: ['craft'];
if (!unlockedQuotes.includes('craft')) unlockedQuotes.unshift('craft');
const unlockedDiaries: string[] = Array.isArray(p.unlockedDiaries)
? p.unlockedDiaries.filter((id: any) => validDiaries.has(id))
: [ANT_DIARIES[0].id];
if (!unlockedDiaries.length) unlockedDiaries.push(ANT_DIARIES[0].id);
const gallery: GalleryItem[] = Array.isArray(p.gallery)
? p.gallery
.filter((g: any) => g && Number.isInteger(g.levelIndex) && g.levelIndex >= 0 && g.levelIndex < LEVELS.length)
.slice(0, 60)
.map((g: any) => ({
levelIndex: g.levelIndex,
levelId: String(g.levelId ?? LEVELS[g.levelIndex].id),
stars: Math.min(3, Math.max(1, Math.round(Number(g.stars) || 1))),
length: Math.max(1, Number(g.length) || 100),
frameId: validFrames.has(g.frameId) ? g.frameId : 'celadon',
quoteId: validQuotes.has(g.quoteId) ? g.quoteId : 'craft',
savedAt: Number(g.savedAt) || nowMs,
}))
: [];
return {
yarnThreads: Math.max(0, Math.floor(Number(p.yarnThreads) || 0)),
pendingThreads: Math.min(IDLE_MAX_THREADS, Math.max(0, Math.floor(Number(p.pendingThreads) || 0))),
lastTickAt: Number.isFinite(Number(p.lastTickAt)) ? Number(p.lastTickAt) : nowMs,
unlockedFrames,
unlockedQuotes,
activeFrame: validFrames.has(p.activeFrame) && unlockedFrames.includes(p.activeFrame) ? p.activeFrame : 'celadon',
activeQuote: validQuotes.has(p.activeQuote) && unlockedQuotes.includes(p.activeQuote) ? p.activeQuote : 'craft',
unlockedDiaries,
gallery,
welcomed: true,
};
} catch {
return base;
}
}
private save(): void {
this.persist(JSON.stringify(this.data));
}
public getState(): AtelierSaveData {
return this.data;
}
/** 按墙钟时间结算离线线头(最多累积 8 小时 = 48 束,永不清零、幂等防溢出) */
public settleIdle(nowMs = Date.now()): number {
if (nowMs <= this.data.lastTickAt) return 0;
const elapsedMin = Math.floor((nowMs - this.data.lastTickAt) / 60000);
const gained = Math.floor(elapsedMin / IDLE_MINUTES_PER_THREAD);
if (gained <= 0) return 0;
const room = Math.max(0, IDLE_MAX_THREADS - this.data.pendingThreads);
const added = Math.min(room, gained);
this.data.pendingThreads += added;
// 只推进整周期,保留余数分钟,绝不吞时间
this.data.lastTickAt =
this.data.pendingThreads >= IDLE_MAX_THREADS
? nowMs
: this.data.lastTickAt + gained * IDLE_MINUTES_PER_THREAD * 60000;
this.save();
return added;
}
public getNextThreadMinutes(nowMs = Date.now()): number {
if (this.data.pendingThreads >= IDLE_MAX_THREADS) return 0;
const elapsedMin = Math.max(0, (nowMs - this.data.lastTickAt) / 60000);
return Math.max(1, Math.ceil(IDLE_MINUTES_PER_THREAD - (elapsedMin % IDLE_MINUTES_PER_THREAD)));
}
/** 收下工坊待领线头,每满 3 束(或首次领取)有机会带回一篇新的蚂蚁日记 */
public collectPending(nowMs = Date.now()): { threads: number; newDiary: AntDiaryDef | null } {
this.settleIdle(nowMs);
const threads = this.data.pendingThreads;
if (threads <= 0) return { threads: 0, newDiary: null };
this.data.yarnThreads += threads;
this.data.pendingThreads = 0;
this.data.lastTickAt = nowMs;
let newDiary: AntDiaryDef | null = null;
const locked = ANT_DIARIES.filter(d => !this.data.unlockedDiaries.includes(d.id));
if (locked.length > 0 && (threads >= 2 || this.data.unlockedDiaries.length < 3)) {
const idx = (Math.floor(nowMs / 60000) + this.data.yarnThreads) % locked.length;
newDiary = locked[idx];
this.data.unlockedDiaries.push(newDiary.id);
}
this.save();
return { threads, newDiary };
}
/** 通关奖励:首次/提升星级送少量线头,同时把作品沉淀进轻量展柜(不存大图) */
public recordCompletedArtwork(levelIndex: number, level: LevelDef, stars: number, length: number, improved: boolean): number {
const bonus = improved ? stars + 2 : 1;
this.data.yarnThreads += bonus;
const existing = this.data.gallery.find(item => item.levelIndex === levelIndex);
if (existing) {
if (stars > existing.stars || (stars === existing.stars && length < existing.length)) {
existing.stars = stars;
existing.length = length;
}
existing.frameId = this.data.activeFrame;
existing.quoteId = this.data.activeQuote;
existing.savedAt = Date.now();
} else {
this.data.gallery.unshift({
levelIndex,
levelId: recordKey(level),
stars,
length,
frameId: this.data.activeFrame,
quoteId: this.data.activeQuote,
savedAt: Date.now(),
});
}
this.data.gallery.sort((a, b) => a.levelIndex - b.levelIndex);
this.save();
return bonus;
}
/** 将旧存档中已通关但未进展柜的作品同步补齐,保证老玩家打开展柜即有藏品 */
public syncFromLegacyRecords(getRecord: (lv: LevelDef) => { stars: number; length: number } | undefined): void {
let changed = false;
for (let i = 0; i < LEVELS.length; i++) {
const rec = getRecord(LEVELS[i]);
if (!rec || rec.stars <= 0) continue;
const hit = this.data.gallery.find(g => g.levelIndex === i);
if (!hit) {
this.data.gallery.push({
levelIndex: i,
levelId: recordKey(LEVELS[i]),
stars: rec.stars,
length: rec.length,
frameId: this.data.activeFrame,
quoteId: this.data.activeQuote,
savedAt: Date.now(),
});
changed = true;
} else if (rec.stars > hit.stars) {
hit.stars = rec.stars;
hit.length = rec.length;
changed = true;
}
}
if (changed) {
this.data.gallery.sort((a, b) => a.levelIndex - b.levelIndex);
this.save();
}
}
public getFrameDef(id: PosterFrameId = this.data.activeFrame): PosterFrameDef {
return POSTER_FRAMES.find(f => f.id === id) ?? POSTER_FRAMES[0];
}
public getQuoteDef(id: PosterQuoteId = this.data.activeQuote): PosterQuoteDef {
return POSTER_QUOTES.find(q => q.id === id) ?? POSTER_QUOTES[0];
}
public selectOrUnlockFrame(id: PosterFrameId): { ok: boolean; unlockedNow: boolean; need?: number } {
const def = this.getFrameDef(id);
if (this.data.unlockedFrames.includes(id)) {
this.data.activeFrame = id;
this.save();
return { ok: true, unlockedNow: false };
}
if (this.data.yarnThreads < def.cost) {
return { ok: false, unlockedNow: false, need: def.cost - this.data.yarnThreads };
}
this.data.yarnThreads -= def.cost;
this.data.unlockedFrames.push(id);
this.data.activeFrame = id;
this.save();
return { ok: true, unlockedNow: true };
}
public selectOrUnlockQuote(id: PosterQuoteId): { ok: boolean; unlockedNow: boolean; need?: number } {
const def = this.getQuoteDef(id);
if (this.data.unlockedQuotes.includes(id)) {
this.data.activeQuote = id;
this.save();
return { ok: true, unlockedNow: false };
}
if (this.data.yarnThreads < def.cost) {
return { ok: false, unlockedNow: false, need: def.cost - this.data.yarnThreads };
}
this.data.yarnThreads -= def.cost;
this.data.unlockedQuotes.push(id);
this.data.activeQuote = id;
this.save();
return { ok: true, unlockedNow: true };
}
public isChapterReplyUnlocked(
chapterIndex: number,
getRecord: (lv: LevelDef) => { stars: number; length: number } | undefined,
): boolean {
const ch = CHAPTERS[chapterIndex];
if (!ch) return false;
// 第一章完成第 1 关向日葵即拆阅林阿婆回信,让首局立刻闭环「委托 → 织画 → 入柜 → 回信」
if (chapterIndex === 0) {
return Boolean(getRecord(LEVELS[0])?.stars);
}
const slice = LEVELS.slice(ch.startIndex, ch.startIndex + ch.count);
const chStars = slice.reduce((sum, lv) => sum + (getRecord(lv)?.stars ?? 0), 0);
const bossCleared = Boolean(getRecord(slice[slice.length - 1])?.stars);
return bossCleared || chStars >= 15;
}
public getLetter(chapterIndex: number): ChapterLetterDef {
return CHAPTER_LETTERS[chapterIndex] ?? CHAPTER_LETTERS[0];
}
public getUnlockedDiaries(): AntDiaryDef[] {
return ANT_DIARIES.filter(d => this.data.unlockedDiaries.includes(d.id));
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "f77d2130-97db-4b99-badc-688e99c8480e",
"files": [],
"subMetas": {},
"userData": {}
}
File diff suppressed because it is too large. Load diff
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "970b0916-4b65-4081-8775-a00e35b1257e",
"files": [],
"subMetas": {},
"userData": {}
}
+730
View File
@@ -0,0 +1,730 @@
import { HOOP_CENTER, NEST, RIM_LIMIT, YARN_COLORS } from './LevelData';
import {
BallDef,
BlockReason,
ButtonAnchorDef,
ButtonEvent,
DeliveryEvent,
DyeEvent,
DyeVatDef,
GateDef,
GateEvent,
HintState,
LevelDef,
PickEvent,
Point2D,
PondDef,
RouteEvent,
RouteState,
SectionDef,
SpoolDef,
SpoolEvent,
TargetColor,
YarnColor,
} from './Types';
export const ANT_SPEED = 0.264;
export const STITCH_TIME = 710;
export function isPickEvent(event: RouteEvent): event is PickEvent {
return event.kind === 'pick';
}
export function isDeliveryEvent(event: RouteEvent): event is DeliveryEvent {
return event.kind === 'delivery';
}
export function isSpoolEvent(event: RouteEvent): event is SpoolEvent {
return event.kind === 'spool';
}
export function isButtonEvent(event: RouteEvent): event is ButtonEvent {
return event.kind === 'button';
}
export function isDyeEvent(event: RouteEvent): event is DyeEvent {
return event.kind === 'dye';
}
export function isGateEvent(event: RouteEvent): event is GateEvent {
return event.kind === 'gate';
}
export function distance(a: Point2D, b: Point2D): number {
return Math.hypot(a.x - b.x, a.y - b.y);
}
export function interpolate(a: Point2D, b: Point2D, t: number): Point2D {
return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
}
export function closestFraction(start: Point2D, end: Point2D, point: Point2D, scaleX = 1, scaleY = 1): number {
const dx = (end.x - start.x) / scaleX;
const dy = (end.y - start.y) / scaleY;
const fx = (point.x - start.x) / scaleX;
const fy = (point.y - start.y) / scaleY;
const length = dx * dx + dy * dy;
return length ? Math.max(0, Math.min(1, (fx * dx + fy * dy) / length)) : 0;
}
export function intersectsPond(start: Point2D, end: Point2D, pond: PondDef): boolean {
const t = closestFraction(start, end, pond, pond.rx, pond.ry);
const point = interpolate(start, end, t);
return Math.hypot((point.x - pond.x) / pond.rx, (point.y - pond.y) / pond.ry) < 1;
}
export function hitSpan(from: Point2D, to: Point2D, center: Point2D, rx: number, ry: number): { enter: number; leave: number } | null {
const x = (from.x - center.x) / rx;
const y = (from.y - center.y) / ry;
const dx = (to.x - from.x) / rx;
const dy = (to.y - from.y) / ry;
const a = dx * dx + dy * dy;
if (a < 1e-8) {
return x * x + y * y <= 1 ? { enter: 0, leave: 1 } : null;
}
const b = x * dx + y * dy;
const d = b * b - a * (x * x + y * y - 1);
if (d < 0) return null;
const root = Math.sqrt(d);
const enter = Math.max(0, (-b - root) / a);
const leave = Math.min(1, (-b + root) / a);
return enter <= leave ? { enter, leave } : null;
}
function orient(a: Point2D, b: Point2D, c: Point2D): number {
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
export function segmentsIntersect(a: Point2D, b: Point2D, c: Point2D, d: Point2D): boolean {
const minAx = Math.min(a.x, b.x) - 1;
const maxAx = Math.max(a.x, b.x) + 1;
const minAy = Math.min(a.y, b.y) - 1;
const maxAy = Math.max(a.y, b.y) + 1;
const minCx = Math.min(c.x, d.x) - 1;
const maxCx = Math.max(c.x, d.x) + 1;
const minCy = Math.min(c.y, d.y) - 1;
const maxCy = Math.max(c.y, d.y) + 1;
if (maxAx < minCx || maxCx < minAx || maxAy < minCy || maxCy < minAy) return false;
const o1 = orient(a, b, c);
const o2 = orient(a, b, d);
const o3 = orient(c, d, a);
const o4 = orient(c, d, b);
return (o1 * o2 < 0) && (o3 * o4 < 0);
}
export function segmentCost(level: LevelDef, from: Point2D, to: Point2D, segLen: number): number {
if (!level.roughZones.length || segLen <= 0) return segLen;
let extraFactor = 0;
for (const zone of level.roughZones) {
const span = hitSpan(from, to, zone, zone.rx, zone.ry);
if (span && span.leave > span.enter) {
const overlap = span.leave - span.enter;
const zoneExtra = Math.max(0, (zone.factor ?? 1.8) - 1) * overlap;
if (zoneExtra > extraFactor) extraFactor = zoneExtra;
}
}
return segLen * (1 + extraFactor);
}
export function createEmptyRoute(showTip = false, nest: Point2D = NEST): RouteState {
return {
nest: { ...nest },
points: [{ ...nest }],
cum: [0],
costCum: [0],
len: 0,
cost: 0,
picks: [],
deliveries: [],
spools: [],
buttons: [],
dyes: [],
gates: [],
events: [],
color: null,
blocked: null,
showTip,
startedAt: 0,
carry: [],
ant: { ...nest, angle: -Math.PI / 2, carry: [], walk: true },
finished: false,
arrivedAt: 0,
segment: 1,
nextEvent: 0,
duration: 0,
};
}
export function totalLength(lines: RouteState[]): number {
return lines.reduce((sum, line) => sum + line.cost, 0);
}
export function collectedSpoolBonus(lines: RouteState[], drawing?: RouteState | null): number {
let bonus = 0;
for (const line of lines) {
for (const sp of line.spools) bonus += sp.spool.bonus;
}
if (drawing) {
for (const sp of drawing.spools) bonus += sp.spool.bonus;
}
return bonus;
}
export function effectiveBudget(level: LevelDef, lines: RouteState[], drawing?: RouteState | null): number | undefined {
if (!level.budget) return undefined;
return level.budget + collectedSpoolBonus(lines, drawing);
}
export function isPondBridged(pond: PondDef, lines: RouteState[]): boolean {
if (!pond.bridgeSectionId) return false;
for (const line of lines) {
if (line.deliveries.some(d => d.target.id === pond.bridgeSectionId)) return true;
}
return false;
}
export function isTargetLocked(
level: LevelDef,
targetId: string,
lines: RouteState[],
drawing?: RouteState | null,
): boolean {
const reqId = level.locks?.[targetId];
if (!reqId) return false;
for (const line of lines) {
if (line.deliveries.some(d => d.target.id === reqId)) return false;
}
if (drawing && drawing.deliveries.some(d => d.target.id === reqId)) return false;
return true;
}
export function dyeUsedCount(dyeId: number, lines: RouteState[], drawing?: RouteState | null): number {
let count = 0;
for (const line of lines) {
for (const ev of line.dyes) if (ev.dye.id === dyeId) count++;
}
if (drawing) {
for (const ev of drawing.dyes) if (ev.dye.id === dyeId) count++;
}
return count;
}
export function dyeRemainingUses(dye: DyeVatDef, lines: RouteState[], drawing?: RouteState | null): number {
if (dye.uses === undefined) return Infinity;
return Math.max(0, dye.uses - dyeUsedCount(dye.id, lines, drawing));
}
export function availableTargets(level: LevelDef, lines: RouteState[], color?: YarnColor | null): SectionDef[] {
const used = new Set<string>();
for (const line of lines) {
for (const d of line.deliveries) used.add(d.target.id);
}
return level.targets.filter(target => (!color || target.color === color) && !used.has(target.id));
}
export function threadedButtonIds(lines: RouteState[], drawing?: RouteState | null): Set<number> {
const ids = new Set<number>();
for (const line of lines) for (const b of line.buttons) ids.add(b.button.id);
if (drawing) for (const b of drawing.buttons) ids.add(b.button.id);
return ids;
}
export function passedGateIds(lines: RouteState[], drawing?: RouteState | null): Set<number> {
const ids = new Set<number>();
for (const line of lines) for (const g of line.gates) ids.add(g.gate.id);
if (drawing) for (const g of drawing.gates) ids.add(g.gate.id);
return ids;
}
export function dispatchWarning(level: LevelDef, lines: RouteState[]): string {
if (!level.maxDispatches) return '';
const remaining = level.maxDispatches - lines.length;
const targets = availableTargets(level, lines);
const hasOverrideDye = level.dyes.some(d => d.override && dyeRemainingUses(d, lines) > 0);
const trips = hasOverrideDye
? Math.ceil(targets.length / 2)
: YARN_COLORS.reduce(
(sum, color) => sum + Math.ceil(targets.filter(t => t.color === color).length / 2),
0,
);
if (trips > remaining) {
return `剩 ${remaining} 笔、${targets.length} 个针位,撤销一笔把球串起来。`;
}
const missingButtons = level.buttons.filter(b => !threadedButtonIds(lines).has(b.id)).length;
const missingGates = level.gates.filter(g => !passedGateIds(lines).has(g.id)).length;
if (remaining === 0 && (missingButtons > 0 || missingGates > 0)) {
return missingButtons > 0
? `还有 ${missingButtons} 颗纽扣未穿过,请撤销重画。`
: `还有 ${missingGates} 处穿针眼未穿过,请撤销重画。`;
}
return '';
}
export function scoreForLength(level: LevelDef, used: number): number {
return used <= level.threeStar ? 3 : used <= level.twoStar ? 2 : 1;
}
export function rollbackToLength(route: RouteState, newLen: number, newCost: number): void {
route.len = newLen;
route.cost = newCost;
route.picks = route.picks.filter(e => e.at <= newLen);
route.deliveries = route.deliveries.filter(e => e.at <= newLen);
route.spools = route.spools.filter(e => e.at <= newLen);
route.buttons = route.buttons.filter(e => e.at <= newLen);
route.dyes = route.dyes.filter(e => e.at <= newLen);
route.gates = route.gates.filter(e => e.at <= newLen);
route.events = route.events.filter(e => e.at <= newLen);
// 根据保留的事件重算当前毛线颜色(支持白球染色后回退还原成白色)
let color: YarnColor | null = null;
for (const ev of route.events) {
if (isPickEvent(ev) && color === null) {
color = ev.ball.color;
} else if (isDyeEvent(ev) && color !== null) {
color = ev.dye.color;
}
}
route.color = color;
}
export function tryBacktrack(route: RouteState, point: Point2D): boolean {
let retracted = false;
while (route.points.length >= 2) {
const tip = route.points[route.points.length - 1];
const prev = route.points[route.points.length - 2];
const segLen = distance(prev, tip);
const dPrev = distance(point, prev);
const dTip = distance(point, tip);
if (dPrev + 1.5 < dTip && dPrev <= Math.max(segLen * 1.1, 14)) {
route.points.pop();
route.cum.pop();
route.costCum.pop();
rollbackToLength(route, route.cum[route.cum.length - 1], route.costCum[route.costCum.length - 1]);
retracted = true;
} else {
break;
}
}
return retracted;
}
export interface PlanCallbacks {
onPick?: (count: number) => void;
onMark?: (count: number) => void;
onLocked?: () => void;
onSpool?: (bonus: number) => void;
onButton?: () => void;
onDye?: (color: TargetColor) => void;
onGate?: () => void;
}
type HitCandidate =
| { kind: 'pick'; ball: BallDef; span: { enter: number; leave: number } }
| { kind: 'delivery'; target: SectionDef; span: { enter: number; leave: number } }
| { kind: 'spool'; spool: SpoolDef; span: { enter: number; leave: number } }
| { kind: 'button'; button: ButtonAnchorDef; span: { enter: number; leave: number } }
| { kind: 'dye'; dye: DyeVatDef; span: { enter: number; leave: number } }
| { kind: 'gate'; gate: GateDef; span: { enter: number; leave: number } };
export function planStops(
level: LevelDef,
lines: RouteState[],
route: RouteState,
from: Point2D,
to: Point2D,
startLength: number,
length: number,
cb?: PlanCallbacks,
): void {
const takenBalls = new Set<number>();
for (const line of lines) for (const p of line.picks) takenBalls.add(p.ball.id);
for (const p of route.picks) takenBalls.add(p.ball.id);
const takenSpools = new Set<number>();
for (const line of lines) for (const s of line.spools) takenSpools.add(s.spool.id);
for (const s of route.spools) takenSpools.add(s.spool.id);
const takenButtons = threadedButtonIds(lines, route);
const takenGates = passedGateIds(lines, route);
const candidates: HitCandidate[] = [];
for (const ball of level.balls) {
if (takenBalls.has(ball.id)) continue;
const span = hitSpan(from, to, ball, 28, 28);
if (span) candidates.push({ kind: 'pick', ball, span });
}
for (const spool of level.spools) {
if (takenSpools.has(spool.id)) continue;
const span = hitSpan(from, to, spool, 26, 26);
if (span) candidates.push({ kind: 'spool', spool, span });
}
for (const button of level.buttons) {
if (takenButtons.has(button.id)) continue;
const span = hitSpan(from, to, button, 26, 26);
if (span) candidates.push({ kind: 'button', button, span });
}
for (const dye of level.dyes) {
const span = hitSpan(from, to, dye, 28, 28);
if (span) candidates.push({ kind: 'dye', dye, span });
}
for (const gate of level.gates) {
if (takenGates.has(gate.id)) continue;
const r = gate.radius ?? 25;
const span = hitSpan(from, to, gate, r, r);
if (span) candidates.push({ kind: 'gate', gate, span });
}
const marked = new Set(route.deliveries.map(stop => stop.target.id));
const targetHits: { target: SectionDef; span: { enter: number; leave: number } }[] = [];
for (const target of availableTargets(level, lines)) {
if (marked.has(target.id)) continue;
const span = hitSpan(from, to, target, target.rx, target.ry);
if (span) {
targetHits.push({ target, span });
candidates.push({ kind: 'delivery', target, span });
}
}
candidates.sort((a, b) => a.span.enter - b.span.enter);
const markDelivery = (target: SectionDef, t: number) => {
if (!route.color || route.color === 'white') return;
if (target.color !== route.color || marked.has(target.id) || route.deliveries.length === route.picks.length) return;
if (isTargetLocked(level, target.id, lines, route)) {
cb?.onLocked?.();
return;
}
const stop: DeliveryEvent = { kind: 'delivery', target, at: startLength + length * t, origin: interpolate(from, to, t) };
marked.add(target.id);
route.deliveries.push(stop);
route.events.push(stop);
cb?.onMark?.(route.deliveries.length);
};
for (const entry of candidates) {
const enter = entry.span.enter;
if (entry.kind === 'delivery') {
markDelivery(entry.target, enter);
continue;
}
if (entry.kind === 'spool') {
if (takenSpools.has(entry.spool.id)) continue;
takenSpools.add(entry.spool.id);
const ev: SpoolEvent = { kind: 'spool', spool: entry.spool, at: startLength + length * enter };
route.spools.push(ev);
route.events.push(ev);
cb?.onSpool?.(entry.spool.bonus);
continue;
}
if (entry.kind === 'button') {
if (takenButtons.has(entry.button.id)) continue;
takenButtons.add(entry.button.id);
const ev: ButtonEvent = { kind: 'button', button: entry.button, at: startLength + length * enter };
route.buttons.push(ev);
route.events.push(ev);
cb?.onButton?.();
continue;
}
if (entry.kind === 'gate') {
if (takenGates.has(entry.gate.id)) continue;
takenGates.add(entry.gate.id);
const ev: GateEvent = { kind: 'gate', gate: entry.gate, at: startLength + length * enter };
route.gates.push(ev);
route.events.push(ev);
cb?.onGate?.();
continue;
}
if (entry.kind === 'dye') {
if (dyeRemainingUses(entry.dye, lines, route) <= 0) continue;
// 染缸:手上有球且未全部落针时染色;普通染缸只染白球,覆色染缸可强行改色
const canDye =
route.picks.length > 0 &&
route.deliveries.length < route.picks.length &&
route.color !== entry.dye.color &&
(route.color === 'white' || Boolean(entry.dye.override));
if (canDye) {
route.color = entry.dye.color;
const ev: DyeEvent = { kind: 'dye', dye: entry.dye, at: startLength + length * enter };
route.dyes.push(ev);
route.events.push(ev);
cb?.onDye?.(entry.dye.color);
for (const hit of targetHits) {
if (hit.span.enter <= enter && enter <= hit.span.leave) markDelivery(hit.target, enter);
}
}
continue;
}
// pick
const ball = entry.ball;
if (route.picks.length >= 2) continue;
if (route.color && route.color !== ball.color) continue;
if (!route.color) route.color = ball.color;
const pick: PickEvent = { kind: 'pick', ball, at: startLength + length * enter };
route.picks.push(pick);
route.events.push(pick);
cb?.onPick?.(route.picks.length);
for (const hit of targetHits) {
if (hit.span.enter <= enter && enter <= hit.span.leave) markDelivery(hit.target, enter);
}
}
}
export function checkSegmentBlock(
level: LevelDef,
lines: RouteState[],
route: RouteState,
from: Point2D,
to: Point2D,
segLen: number,
): BlockReason | null {
if (level.ponds.some(pond => !isPondBridged(pond, lines) && intersectsPond(from, to, pond))) return 'pond';
if (
Math.hypot(from.x - HOOP_CENTER.x, from.y - HOOP_CENTER.y) > RIM_LIMIT ||
Math.hypot(to.x - HOOP_CENTER.x, to.y - HOOP_CENTER.y) > RIM_LIMIT
) {
return 'rim';
}
// 实体毛线球阻挡:不可穿过异色或已满载时的未拾毛线球
if (level.solidBalls) {
const takenBalls = new Set<number>();
for (const line of lines) for (const p of line.picks) takenBalls.add(p.ball.id);
for (const p of route.picks) takenBalls.add(p.ball.id);
for (const ball of level.balls) {
if (takenBalls.has(ball.id)) continue;
const cannotPick = route.picks.length >= 2 || (route.color !== null && route.color !== ball.color);
if (cannotPick && hitSpan(from, to, ball, 22, 22)) return 'ball';
}
}
// 单向穿针眼校验:碰到未穿过的针眼时,行进方向必须与箭头夹角 < ~80°
if (level.gates.length > 0 && segLen > 0.5) {
const dirX = (to.x - from.x) / segLen;
const dirY = (to.y - from.y) / segLen;
const passed = passedGateIds(lines, route);
for (const gate of level.gates) {
if (passed.has(gate.id)) continue;
const r = gate.radius ?? 25;
if (hitSpan(from, to, gate, r, r)) {
const dot = dirX * Math.cos(gate.angle) + dirY * Math.sin(gate.angle);
if (dot < 0.15) return 'gate';
}
}
}
// 不可交叉校验:禁止压过任何已提交毛线的线段(共享蚁巢出口 24px 内豁免)
if (level.noCross && lines.length > 0) {
const nearAnyNest = level.nests.some(n => distance(from, n) < 24 && distance(to, n) < 24);
if (!nearAnyNest) {
for (const prevLine of lines) {
const pts = prevLine.points;
for (let i = 1; i < pts.length; i++) {
const a = pts[i - 1];
const b = pts[i];
if (level.nests.some(n => distance(a, n) < 24 && distance(b, n) < 24)) continue;
if (segmentsIntersect(from, to, a, b)) return 'cross';
}
}
}
}
const budget = effectiveBudget(level, lines, route);
if (budget !== undefined) {
const costAdd = segmentCost(level, from, to, segLen);
if (totalLength(lines) + route.cost + costAdd > budget) return 'budget';
}
return null;
}
export function trimRouteTail(route: RouteState): void {
const lastEvent = route.events[route.events.length - 1];
if (!lastEvent || lastEvent.at >= route.len - 0.5) return;
const cutAt = lastEvent.at;
let seg = 1;
while (seg < route.cum.length - 1 && route.cum[seg] < cutAt) seg++;
const prevLen = route.cum[seg - 1];
const nextLen = route.cum[seg];
const t = nextLen > prevLen ? Math.max(0, Math.min(1, (cutAt - prevLen) / (nextLen - prevLen))) : 0;
const endPoint = interpolate(route.points[seg - 1], route.points[seg], t);
const prevCost = route.costCum[seg - 1];
const nextCost = route.costCum[seg];
const endCost = prevCost + (nextCost - prevCost) * t;
route.points = [...route.points.slice(0, seg), endPoint];
route.cum = [...route.cum.slice(0, seg), cutAt];
route.costCum = [...route.costCum.slice(0, seg), endCost];
route.len = cutAt;
route.cost = endCost;
}
export function prepareRouteForRun(route: RouteState, startedAt: number): void {
route.blocked = null;
route.startedAt = startedAt;
route.carry = [];
route.ant = { ...route.nest, angle: -Math.PI / 2, carry: route.carry, walk: true };
route.finished = false;
route.arrivedAt = 0;
route.segment = 1;
route.nextEvent = 0;
let stopTime = 0;
for (const event of route.events) {
event.ms = event.at / ANT_SPEED + stopTime;
event.hold = isPickEvent(event) ? 135 : isDeliveryEvent(event) ? 160 : 75;
stopTime += event.hold;
}
route.duration = route.len / ANT_SPEED + stopTime;
}
export function findNextHint(level: LevelDef, lines: RouteState[], tier: 1 | 2 | 3 = 1): HintState {
const takenBalls = new Set<number>();
for (const line of lines) for (const p of line.picks) takenBalls.add(p.ball.id);
const remainingBalls = level.balls.filter(b => !takenBalls.has(b.id));
const remTargets = availableTargets(level, lines);
let chosen = level.demo[Math.min(lines.length, level.demo.length - 1)];
let firstBall: BallDef | null = null;
let firstBallIndex = 1;
for (const path of level.demo) {
let hit: BallDef | undefined;
let hitIdx = 1;
for (let i = 1; i < path.length; i++) {
const [x, y] = path[i];
hit = remainingBalls.find(ball => Math.hypot(x - ball.x, y - ball.y) < 34);
if (hit) {
hitIdx = i;
break;
}
const prev = { x: path[i - 1][0], y: path[i - 1][1] };
const cur = { x, y };
hit = remainingBalls.find(ball => hitSpan(prev, cur, ball, 28, 28) !== null);
if (hit) {
hitIdx = i;
break;
}
}
if (hit) {
chosen = path;
firstBall = hit;
firstBallIndex = hitIdx;
break;
}
}
const fullPts = (chosen ?? level.demo[0] ?? []).map(([x, y]) => ({ x, y }));
let firstTarget: SectionDef | null = null;
for (let i = 1; i < fullPts.length; i++) {
const pt = fullPts[i];
const hit = remTargets.find(t => Math.hypot((pt.x - t.x) / t.rx, (pt.y - t.y) / t.ry) <= 1.05);
if (hit) {
firstTarget = hit;
break;
}
}
let points = fullPts;
if (tier === 1) {
// 1 级提示:沿真实 demo 折线截取到第一颗球,保留绕开水洼的中间拐点(避免直线穿水洼)
points = fullPts.length >= 2 ? fullPts.slice(0, Math.min(fullPts.length, firstBallIndex + 1)) : fullPts;
} else if (tier === 2 && fullPts.length >= 2) {
// 2 级提示:截取该笔折线的前半程(按长度 52%)
let total = 0;
for (let i = 1; i < fullPts.length; i++) total += distance(fullPts[i - 1], fullPts[i]);
const halfLen = total * 0.52;
const sliced: Point2D[] = [fullPts[0]];
let acc = 0;
for (let i = 1; i < fullPts.length; i++) {
const seg = distance(fullPts[i - 1], fullPts[i]);
if (acc + seg >= halfLen) {
const t = seg > 0 ? (halfLen - acc) / seg : 0;
sliced.push(interpolate(fullPts[i - 1], fullPts[i], Math.max(0, Math.min(1, t))));
break;
}
sliced.push(fullPts[i]);
acc += seg;
}
points = sliced;
}
return { tier, points, ball: firstBall, target: firstTarget };
}
/** 自动化验关器:用真实引擎规则跑完整关 demo,返回是否通关、总耗线与失败原因 */
export function validateLevelDemo(level: LevelDef): { ok: boolean; cost: number; error?: string } {
const lines: RouteState[] = [];
for (let d = 0; d < level.demo.length; d++) {
const raw = level.demo[d];
if (!raw || raw.length < 2) {
return { ok: false, cost: 0, error: `demo[${d}] 点数不足` };
}
const startPt: Point2D = { x: raw[0][0], y: raw[0][1] };
const matchedNest = level.nests.find(n => distance(n, startPt) < 4);
if (!matchedNest) {
return { ok: false, cost: 0, error: `demo[${d}] 起点 (${startPt.x},${startPt.y}) 不在任何蚁巢上` };
}
const route = createEmptyRoute(false, matchedNest);
for (let i = 1; i < raw.length; i++) {
const fromPt = { x: raw[i - 1][0], y: raw[i - 1][1] };
const toPt = { x: raw[i][0], y: raw[i][1] };
const dist = distance(fromPt, toPt);
const steps = Math.max(1, Math.ceil(dist / 6));
for (let s = 1; s <= steps; s++) {
const pt = interpolate(fromPt, toPt, s / steps);
const prev = route.points[route.points.length - 1];
const segLen = distance(prev, pt);
if (segLen < 1.5) continue;
const blocked = checkSegmentBlock(level, lines, route, prev, pt, segLen);
if (blocked) {
return {
ok: false,
cost: totalLength(lines) + route.cost,
error: `demo[${d}] 第 ${i} 段在 (${pt.x.toFixed(1)},${pt.y.toFixed(1)}) 触发阻挡: ${blocked}`,
};
}
const costAdd = segmentCost(level, prev, pt, segLen);
route.points.push(pt);
const startLen = route.len;
route.len += segLen;
route.cost += costAdd;
route.cum.push(route.len);
route.costCum.push(route.cost);
planStops(level, lines, route, prev, pt, startLen, segLen);
}
}
if (!route.picks.length || route.picks.length !== route.deliveries.length) {
return {
ok: false,
cost: totalLength(lines) + route.cost,
error: `demo[${d}] 未完成配对: picks=${route.picks.length}, deliveries=${route.deliveries.length}, color=${route.color}`,
};
}
prepareRouteForRun(route, 0);
lines.push(route);
}
if (level.maxDispatches && lines.length > level.maxDispatches) {
return { ok: false, cost: totalLength(lines), error: `出发笔数 ${lines.length} 超过限笔 ${level.maxDispatches}` };
}
const remTargets = availableTargets(level, lines);
if (remTargets.length > 0) {
return { ok: false, cost: totalLength(lines), error: `尚有未绣针位: ${remTargets.map(t => t.id).join(',')}` };
}
const doneButtons = threadedButtonIds(lines);
if (level.buttons.some(b => !doneButtons.has(b.id))) {
return { ok: false, cost: totalLength(lines), error: `尚有纽扣未穿过` };
}
const doneGates = passedGateIds(lines);
if (level.gates.some(g => !doneGates.has(g.id))) {
return { ok: false, cost: totalLength(lines), error: `尚有单向针眼未穿过` };
}
const finalCost = totalLength(lines);
const maxBudget = effectiveBudget(level, lines);
if (maxBudget !== undefined && finalCost > maxBudget) {
return { ok: false, cost: finalCost, error: `总耗线 ${finalCost.toFixed(1)} 超出限额 ${maxBudget}` };
}
return { ok: true, cost: finalCost };
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "797ea493-d04e-49a8-b775-3d88ea5e9afb",
"files": [],
"subMetas": {},
"userData": {}
}
+169
View File
@@ -0,0 +1,169 @@
import { StorageService } from './StorageService';
declare const wx: any;
interface ToneOptions {
type?: OscillatorType;
volume?: number;
slideTo?: number | null;
}
export class SoundService {
private ctx: any = null;
private enabled: boolean;
private bgmEnabled: boolean;
private bgmTimer: any = null;
private bgmStep = 0;
private lastBlockAt = 0;
// 舒缓手作五声八音盒旋律(C 大调五声:C5 D5 E5 G5 A5 C6)
private readonly bgmNotes = [523.25, 659.25, 783.99, 659.25, 587.33, 659.25, 880.0, 783.99, 523.25, 587.33, 659.25, 440.0];
constructor(private readonly storage: StorageService) {
this.enabled = storage.readSoundEnabled();
this.bgmEnabled = storage.readBgmEnabled();
}
public isEnabled(): boolean {
return this.enabled;
}
public isBgmEnabled(): boolean {
return this.bgmEnabled;
}
public toggle(): boolean {
this.enabled = !this.enabled;
this.storage.saveSoundEnabled(this.enabled);
if (this.enabled) {
this.unlock();
this.playTone(620, 0.06, 0.02, { volume: 0.055 });
}
return this.enabled;
}
public toggleBgm(): boolean {
this.bgmEnabled = !this.bgmEnabled;
this.storage.saveBgmEnabled(this.bgmEnabled);
if (this.bgmEnabled) {
this.unlock();
this.startBgmLoop();
} else {
this.stopBgmLoop();
}
return this.bgmEnabled;
}
private startBgmLoop(): void {
if (!this.bgmEnabled || this.bgmTimer !== null) return;
if (typeof setInterval !== 'function') return;
this.bgmTimer = setInterval(() => {
if (!this.bgmEnabled || !this.ctx || this.ctx.state !== 'running') return;
const freq = this.bgmNotes[this.bgmStep % this.bgmNotes.length];
this.bgmStep++;
this.playRawTone(freq, 0.42, 0, { type: 'sine', volume: 0.018 });
if (this.bgmStep % 4 === 1) {
this.playRawTone(freq * 0.5, 0.72, 0.02, { type: 'triangle', volume: 0.011 });
}
}, 920);
}
public stopBgmLoop(): void {
if (this.bgmTimer !== null && typeof clearInterval === 'function') {
clearInterval(this.bgmTimer);
this.bgmTimer = null;
}
}
public unlock(): void {
if (!this.enabled && !this.bgmEnabled) return;
if (!this.ctx) {
if (typeof wx !== 'undefined' && typeof wx.createWebAudioContext === 'function') {
this.ctx = wx.createWebAudioContext();
} else if (typeof window !== 'undefined') {
const AudioCtx = (window as any).AudioContext || (window as any).webkitAudioContext;
if (AudioCtx) this.ctx = new AudioCtx();
}
}
if (this.ctx && this.ctx.state === 'suspended' && typeof this.ctx.resume === 'function') {
try {
const res = this.ctx.resume();
if (res && typeof res.catch === 'function') res.catch(() => {});
} catch {
// Ignore autoplay restrictions until next gesture.
}
}
if (this.bgmEnabled) this.startBgmLoop();
}
private playRawTone(freq: number, duration: number, delay = 0, opts: ToneOptions = {}): void {
if (!this.ctx || this.ctx.state !== 'running') return;
const { type = 'triangle', volume = 0.065, slideTo = null } = opts;
try {
const osc = this.ctx.createOscillator();
const gain = this.ctx.createGain();
const start = this.ctx.currentTime + delay;
osc.type = type;
osc.frequency.setValueAtTime(freq, start);
if (slideTo) osc.frequency.exponentialRampToValueAtTime(slideTo, start + duration);
gain.gain.setValueAtTime(0.0008, start);
gain.gain.exponentialRampToValueAtTime(volume, start + 0.012);
gain.gain.exponentialRampToValueAtTime(0.0008, start + duration + 0.035);
osc.connect(gain);
gain.connect(this.ctx.destination);
osc.start(start);
osc.stop(start + duration + 0.04);
} catch {
// Ignore transient WebAudio errors.
}
}
private playTone(freq: number, duration: number, delay = 0, opts: ToneOptions = {}): void {
if (!this.enabled) return;
this.playRawTone(freq, duration, delay, opts);
}
public pick(count: number): void {
this.playTone(count > 1 ? 659 : 523, 0.065, 0, { volume: 0.06 });
}
public mark(count: number): void {
this.playTone(count > 1 ? 880 : 740, 0.06, 0, { volume: 0.055 });
}
public pickup(): void {
this.playTone(494, 0.06, 0, { volume: 0.05 });
}
public deliver(): void {
this.playTone(659, 0.085, 0, { volume: 0.065 });
this.playTone(988, 0.09, 0.09, { volume: 0.06 });
}
public block(): void {
const now = Date.now();
if (now - this.lastBlockAt < 320) return;
this.lastBlockAt = now;
this.playTone(230, 0.09, 0, { type: 'sine', volume: 0.055, slideTo: 145 });
}
public undo(): void {
this.playTone(440, 0.06, 0, { volume: 0.045, slideTo: 330 });
}
public bonus(): void {
this.playTone(698, 0.07, 0, { volume: 0.055, slideTo: 932 });
}
public dye(): void {
this.playTone(587, 0.08, 0, { type: 'sine', volume: 0.06, slideTo: 880 });
}
public button(): void {
this.playTone(784, 0.055, 0, { volume: 0.05 });
}
public win(): void {
[523, 659, 784, 1046].forEach((freq, i) => this.playTone(freq, 0.14, i * 0.085, { volume: 0.065 }));
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "b7281e35-228d-4d00-b1c6-118316441f21",
"files": [],
"subMetas": {},
"userData": {}
}
+136
View File
@@ -0,0 +1,136 @@
import { sys } from 'cc';
import { LevelDef, RecordMap } from './Types';
import { recordKey } from './LevelData';
const RECORDS_KEY = 'ant-embroidery-best-v1';
const SOUND_KEY = 'ant-embroidery-sound-v1';
const BGM_KEY = 'ant-embroidery-bgm-v1';
const LOUPE_KEY = 'ant-embroidery-loupe-v1';
const LANG_KEY = 'ant-embroidery-lang-v1';
const TUTORIAL_KEY = 'ant-embroidery-tut-v1';
const ATELIER_KEY = 'ant-embroidery-atelier-v1';
export type AppLang = 'zh' | 'en';
declare const wx: any;
function getRaw(key: string): string | null {
try {
if (typeof wx !== 'undefined' && typeof wx.getStorageSync === 'function') {
const val = wx.getStorageSync(key);
return val === '' || val === undefined || val === null ? null : String(val);
}
return sys.localStorage.getItem(key);
} catch {
return null;
}
}
function setRaw(key: string, value: string): void {
try {
if (typeof wx !== 'undefined' && typeof wx.setStorageSync === 'function') {
wx.setStorageSync(key, value);
return;
}
sys.localStorage.setItem(key, value);
} catch {
// Ignore storage errors on restricted environments.
}
}
export class StorageService {
private records: RecordMap = {};
constructor() {
this.records = this.loadRecords();
}
private loadRecords(): RecordMap {
try {
const raw = getRaw(RECORDS_KEY);
const parsed = raw ? JSON.parse(raw) : {};
const valid: RecordMap = {};
if (parsed && typeof parsed === 'object') {
for (const k of Object.keys(parsed)) {
const rec = parsed[k];
if (
Number.isInteger(rec?.stars) && rec.stars >= 1 && rec.stars <= 3 &&
Number.isFinite(rec?.length) && rec.length > 0
) {
valid[k] = { stars: rec.stars, length: rec.length };
}
}
}
return valid;
} catch {
return {};
}
}
public getRecord(level: LevelDef) {
return this.records[recordKey(level)];
}
public saveRecord(level: LevelDef, stars: number, length: number): boolean {
const key = recordKey(level);
const prev = this.records[key];
if (prev && (stars < prev.stars || (stars === prev.stars && length >= prev.length))) {
return false;
}
this.records[key] = { stars, length };
setRaw(RECORDS_KEY, JSON.stringify(this.records));
return true;
}
public readSoundEnabled(): boolean {
const raw = getRaw(SOUND_KEY);
return raw === null ? true : raw === '1';
}
public saveSoundEnabled(enabled: boolean): void {
setRaw(SOUND_KEY, enabled ? '1' : '0');
}
public readBgmEnabled(): boolean {
const raw = getRaw(BGM_KEY);
return raw === null ? true : raw === '1';
}
public saveBgmEnabled(enabled: boolean): void {
setRaw(BGM_KEY, enabled ? '1' : '0');
}
public readLoupeEnabled(): boolean {
const raw = getRaw(LOUPE_KEY);
return raw === null ? true : raw === '1';
}
public saveLoupeEnabled(enabled: boolean): void {
setRaw(LOUPE_KEY, enabled ? '1' : '0');
}
public readLanguage(): AppLang {
const raw = getRaw(LANG_KEY);
return raw === 'en' ? 'en' : 'zh';
}
public saveLanguage(lang: AppLang): void {
setRaw(LANG_KEY, lang);
}
public hasSeenTutorial(): boolean {
return getRaw(TUTORIAL_KEY) === '1';
}
public markTutorialSeen(): void {
setRaw(TUTORIAL_KEY, '1');
}
public readAtelierRaw(): string | null {
return getRaw(ATELIER_KEY);
}
public saveAtelierRaw(raw: string): void {
setRaw(ATELIER_KEY, raw);
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "e984a08f-a1e2-4210-af6d-dc00d166892a",
"files": [],
"subMetas": {},
"userData": {}
}
+260
View File
@@ -0,0 +1,260 @@
export type TargetColor =
| 'gold'
| 'green'
| 'rose'
| 'sky'
| 'coral'
| 'lavender'
| 'cream'
| 'cocoa';
export type YarnColor = TargetColor | 'white';
export type MotifId = 'sunflower' | 'lotus' | 'sakura' | 'garden' | 'custom';
export type BlockReason = 'pond' | 'rim' | 'budget' | 'cross' | 'gate' | 'ball';
export interface Point2D {
x: number;
y: number;
}
export interface SectionDef {
id: string;
x: number;
y: number;
rx: number;
ry: number;
color: TargetColor;
petals?: number[];
side?: number;
lotus?: 'bloom' | 'bud' | 'pad-left' | 'pad-right';
sakura?: 'left' | 'top' | 'right' | 'bird' | 'leaf';
garden?: 'gold-floret' | 'rose-peony' | 'leaf-l' | 'leaf-r';
}
export interface BallDef {
id: number;
x: number;
y: number;
color: YarnColor;
}
export interface PondDef {
x: number;
y: number;
rx: number;
ry: number;
/** 若指定了针位 ID,当该针位绣好后此水洼被绣片搭桥覆盖、可通行 */
bridgeSectionId?: string;
}
export interface SpoolDef {
id: number;
x: number;
y: number;
bonus: number;
}
export interface ButtonAnchorDef {
id: number;
x: number;
y: number;
}
export interface DyeVatDef {
id: number;
x: number;
y: number;
color: TargetColor;
/** 可用次数(不填表示无限;填 1 表示单次干涸染缸) */
uses?: number;
/** 是否对已染色毛线强制覆色 */
override?: boolean;
}
export interface GateDef {
id: number;
x: number;
y: number;
/** 允许穿过的方向角(弧度,0 为向右,-PI/2 为向上) */
angle: number;
radius?: number;
}
export interface RoughZoneDef {
x: number;
y: number;
rx: number;
ry: number;
factor?: number;
}
export interface ChapterDef {
id: string;
index: number;
name: string;
subtitle: string;
motif: MotifId;
startIndex: number;
count: number;
}
export interface LevelDef {
id: string;
recordId?: string;
chapter: number;
name: string;
difficulty: string;
lesson: string;
goal: string;
ruleTag: string;
motif: MotifId;
/** 可选高精刺绣贴图资源名(位于 assets/resources/artworks/<name>) */
artworkImage?: string;
budget?: number;
maxDispatches?: number;
noCross?: boolean;
/** 不可穿过不同色未拾毛线球(形成物理堵路) */
solidBalls?: boolean;
/** 机关顺序锁:key 为被锁针位 ID,value 为必须先绣完的前置针位 ID */
locks?: Record<string, string>;
nests: Point2D[];
targets: SectionDef[];
balls: BallDef[];
ponds: PondDef[];
spools: SpoolDef[];
buttons: ButtonAnchorDef[];
dyes: DyeVatDef[];
gates: GateDef[];
roughZones: RoughZoneDef[];
threeStar: number;
twoStar: number;
/** 每笔演示折线(首点必须是某个蚁巢坐标) */
demo: [number, number][][];
}
export interface PickEvent {
kind: 'pick';
ball: BallDef;
at: number;
ms?: number;
hold?: number;
pickedAt?: number;
}
export interface DeliveryEvent {
kind: 'delivery';
target: SectionDef;
at: number;
origin: Point2D;
ms?: number;
hold?: number;
arrivedAt?: number;
}
export interface SpoolEvent {
kind: 'spool';
spool: SpoolDef;
at: number;
ms?: number;
hold?: number;
collectedAt?: number;
}
export interface ButtonEvent {
kind: 'button';
button: ButtonAnchorDef;
at: number;
ms?: number;
hold?: number;
threadedAt?: number;
}
export interface DyeEvent {
kind: 'dye';
dye: DyeVatDef;
at: number;
ms?: number;
hold?: number;
dyedAt?: number;
}
export interface GateEvent {
kind: 'gate';
gate: GateDef;
at: number;
ms?: number;
hold?: number;
passedAt?: number;
}
export type RouteEvent = PickEvent | DeliveryEvent | SpoolEvent | ButtonEvent | DyeEvent | GateEvent;
export interface CarryBall extends BallDef {
pickedAt: number;
}
export interface AntState {
x: number;
y: number;
angle: number;
carry: CarryBall[];
walk: boolean;
}
export interface RouteState {
nest: Point2D;
points: Point2D[];
cum: number[];
costCum: number[];
len: number;
cost: number;
picks: PickEvent[];
deliveries: DeliveryEvent[];
spools: SpoolEvent[];
buttons: ButtonEvent[];
dyes: DyeEvent[];
gates: GateEvent[];
events: RouteEvent[];
color: YarnColor | null;
blocked: BlockReason | null;
showTip: boolean;
fingerTip?: Point2D | null;
loupeEnabled?: boolean;
startedAt: number;
carry: CarryBall[];
ant: AntState;
finished: boolean;
arrivedAt: number;
traveled?: number;
segment: number;
nextEvent: number;
duration: number;
}
export interface HintState {
tier: 1 | 2 | 3;
points: Point2D[];
ball: BallDef | null;
target: SectionDef | null;
}
export interface GameState {
time: number;
lines: RouteState[];
drawing: RouteState | null;
complete: boolean;
completedAt: number;
demo: boolean;
assisted: boolean;
/** 用过 2/3 级路线提示或看过演示时,通关存档星级封顶为 2 星 */
hintCapped: boolean;
/** 本关是否看过演示(重来/重绣不清空,仅换关时重置) */
demoWatched: boolean;
hint: HintState | null;
}
export interface RecordEntry {
stars: number;
length: number;
}
export type RecordMap = Record<string, RecordEntry>;
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "c8ca71e2-d2c9-4c45-b475-7592d4b13fdd",
"files": [],
"subMetas": {},
"userData": {}
}