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)); } }