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

+123
View File
@@ -0,0 +1,123 @@
import { Component, Game, game, Node, view, _decorator } from 'cc';
import { AtelierService } from './core/AtelierService';
import { SoundService } from './core/SoundService';
import { StorageService } from './core/StorageService';
import { EmbroideryRenderer } from './render/EmbroideryRenderer';
import { LobbyView } from './ui/LobbyView';
import { PlayView } from './ui/PlayView';
import { applyResponsivePolicy, computeScreenMetrics, ScreenMetrics } from './ui/ScreenAdapter';
import { createLabel, createPanel, createUINode } from './ui/UiBuilder';
const { ccclass } = _decorator;
@ccclass('MainController')
export class MainController extends Component {
private storage!: StorageService;
private sound!: SoundService;
private atelier!: AtelierService;
private renderer!: EmbroideryRenderer;
private lobbyView!: LobbyView;
private playView!: PlayView;
private mockCapsuleNode: Node | null = null;
protected onLoad(): void {
applyResponsivePolicy();
this.storage = new StorageService();
this.sound = new SoundService(this.storage);
this.atelier = new AtelierService(
() => this.storage.readAtelierRaw(),
raw => this.storage.saveAtelierRaw(raw),
);
this.atelier.syncFromLegacyRecords(lv => this.storage.getRecord(lv));
this.renderer = new EmbroideryRenderer(1.5);
const lobbyNode = createUINode('LobbyView', 750, 1334, this.node);
this.lobbyView = lobbyNode.addComponent(LobbyView);
this.lobbyView.init(this.storage, this.sound, this.atelier, this.renderer, index => this.enterLevel(index));
const playNode = createUINode('PlayView', 750, 1334, this.node);
this.playView = playNode.addComponent(PlayView);
this.playView.init(
this.storage,
this.sound,
this.atelier,
this.renderer,
() => this.showLobby(),
(tab, chapterIndex, focusLevelIndex) => {
this.showLobby();
this.lobbyView.openAtelier(tab, chapterIndex, focusLevelIndex);
},
);
game.on(Game.EVENT_HIDE, this.onAppHide, this);
game.on(Game.EVENT_SHOW, this.onAppShow, this);
view.on('canvas-resize', this.onCanvasResize, this);
this.applyLayoutMetrics();
this.showLobby();
}
protected onDestroy(): void {
game.off(Game.EVENT_HIDE, this.onAppHide, this);
game.off(Game.EVENT_SHOW, this.onAppShow, this);
view.off('canvas-resize', this.onCanvasResize, this);
}
private onCanvasResize(): void {
applyResponsivePolicy();
this.applyLayoutMetrics();
}
private applyLayoutMetrics(): void {
const metrics = computeScreenMetrics();
this.lobbyView?.applyScreenMetrics(metrics);
this.playView?.applyScreenMetrics(metrics);
this.syncMockWeChatCapsule(metrics);
}
/** 仅在浏览器 URL 带 ?wxsim=iphone15 或 ?wxsim=iphonese 时绘制模拟微信胶囊,方便真机前目视验收 */
private syncMockWeChatCapsule(m: ScreenMetrics): void {
if (!m.mockCapsule) {
if (this.mockCapsuleNode) this.mockCapsuleNode.active = false;
return;
}
const { top, height, width, right } = m.mockCapsule;
if (!this.mockCapsuleNode) {
const cap = createPanel('MockWeChatCapsule', width, height, {
fill: '#00000088', stroke: '#ffffff88', strokeWidth: 2, radius: height / 2,
}, this.node);
createLabel('CapGlyph', '••• | ◎', width - 14, height - 8, {
size: 22, color: '#ffffff', bold: true,
}, cap.node);
this.mockCapsuleNode = cap.node;
}
this.mockCapsuleNode.active = true;
this.mockCapsuleNode.setPosition(
m.visibleW / 2 - right - width / 2,
m.visibleH / 2 - top - height / 2,
0,
);
}
private onAppHide(): void {
this.playView?.cancelDrag(false);
}
private onAppShow(): void {
this.atelier?.settleIdle(Date.now());
this.applyLayoutMetrics();
if (this.lobbyView?.node.active) this.lobbyView.refresh();
}
private showLobby(): void {
this.atelier?.settleIdle(Date.now());
this.playView.node.active = false;
this.lobbyView.node.active = true;
this.lobbyView.refresh();
}
private enterLevel(index: number): void {
this.lobbyView.node.active = false;
this.playView.node.active = true;
this.playView.loadLevel(index);
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "2ffbda50-8319-4a8e-84f8-f21fde11f128",
"files": [],
"subMetas": {},
"userData": {}
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.2.0",
"importer": "directory",
"imported": true,
"uuid": "796c0e40-4f92-4b2b-8bba-238c9c8d88ae",
"files": [],
"subMetas": {},
"userData": {}
}
+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": {}
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.2.0",
"importer": "directory",
"imported": true,
"uuid": "b3fa63e3-0773-4f1e-af5b-c35b2ea80490",
"files": [],
"subMetas": {},
"userData": {}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "e3874383-1a6b-495c-ab42-36d52333b3fd",
"files": [],
"subMetas": {},
"userData": {}
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "1.2.0",
"importer": "directory",
"imported": true,
"uuid": "a1efed9a-a10c-4c78-8ec3-82de9d522bcf",
"files": [],
"subMetas": {},
"userData": {}
}
+815
View File
@@ -0,0 +1,815 @@
import { Component, Graphics, Label, Node, Sprite, SpriteFrame, _decorator } from 'cc';
import {
ANT_DIARIES,
AtelierService,
IDLE_MAX_THREADS,
POSTER_FRAMES,
POSTER_QUOTES,
PosterFrameId,
} from '../core/AtelierService';
import { CHAPTERS, CHAPTER_UNLOCK_STARS, formatLength, LEVELS } from '../core/LevelData';
import { SoundService } from '../core/SoundService';
import { StorageService } from '../core/StorageService';
import { EmbroideryRenderer } from '../render/EmbroideryRenderer';
import {
createArtSprite,
createButton,
createLabel,
createPanel,
createUINode,
drawPadlockIcon,
drawRoundedBox,
hex,
stretchToParent,
StyledButton,
} from './UiBuilder';
const { ccclass } = _decorator;
export type AtelierTab = 'workshop' | 'gallery' | 'letters';
const CHAPTER_SHORT_ZH = ['繁花', '灵禽', '萌宠', '山水', '筑影', '甜物'];
const CHAPTER_SHORT_EN = ['Flora', 'Birds', 'Pets', 'Hills', 'Villas', 'Sweets'];
@ccclass('AtelierModal')
export class AtelierModal extends Component {
private storage!: StorageService;
private sound!: SoundService;
private atelier!: AtelierService;
private renderer!: EmbroideryRenderer;
private getThumbnail!: (levelIndex: number) => SpriteFrame;
private onChanged?: () => void;
private activeTab: AtelierTab = 'workshop';
private tabBtns: Record<AtelierTab, StyledButton> = {} as any;
private tabGroups: Record<AtelierTab, Node> = {} as any;
private closeBtn!: StyledButton;
// Tab 1: 蚂蚁工坊
private wsThreadsLabel!: Label;
private wsPendingLabel!: Label;
private wsStageSprite!: Sprite;
private wsCollectBtn!: StyledButton;
private wsDiaryHeaderLabel!: Label;
private wsDiaryMoodLabel!: Label;
private wsDiaryMoodBg!: Graphics;
private wsDiaryBodyLabel!: Label;
private wsToastLabel!: Label;
private diaryIndex = 0;
private workshopTimeMs = 0;
// Tab 2: 绣品展柜
private galEmptyNode!: Node;
private galContentNode!: Node;
private galPreviewCardBg!: Graphics;
private galPreviewSprite!: Sprite;
private galPreviewTitle!: Label;
private galPreviewMeta!: Label;
private galCounterLabel!: Label;
private galThreadsLabel!: Label;
private galFrameBtns: { id: PosterFrameId; btn: StyledButton }[] = [];
private galQuoteBtn!: StyledButton;
private galQuotePreview!: Label;
private galExportBtn!: StyledButton;
private galToastLabel!: Label;
private galleryCursor = 0;
// Tab 3: 委托信箱
private letterChapter = 0;
private letterTabs: { btn: StyledButton; lockNode: Node }[] = [];
private letterReqHeader!: Label;
private letterReqBody!: Label;
private letterReplyBg!: Graphics;
private letterReplyLockNode!: Node;
private letterReplyHeader!: Label;
private letterReplyBody!: Label;
public init(
storage: StorageService,
sound: SoundService,
atelier: AtelierService,
renderer: EmbroideryRenderer,
getThumbnail: (levelIndex: number) => SpriteFrame,
onChanged?: () => void,
): void {
this.storage = storage;
this.sound = sound;
this.atelier = atelier;
this.renderer = renderer;
this.getThumbnail = getThumbnail;
this.onChanged = onChanged;
this.buildUI();
this.node.active = false;
}
private isEn(): boolean {
return this.storage.readLanguage() === 'en';
}
private getTotalStars(): number {
return LEVELS.reduce((sum, entry) => sum + (this.storage.getRecord(entry)?.stars ?? 0), 0);
}
private isChapterUnlocked(idx: number): boolean {
if (idx <= 0) return true;
return this.getTotalStars() >= (CHAPTER_UNLOCK_STARS[idx] ?? 0);
}
public open(tab: AtelierTab, chapterIndex = 0, focusLevelIndex?: number): void {
this.atelier.settleIdle(Date.now());
this.atelier.syncFromLegacyRecords(lv => this.storage.getRecord(lv));
this.activeTab = tab;
this.letterChapter = this.isChapterUnlocked(chapterIndex) ? chapterIndex : 0;
const diaries = this.atelier.getUnlockedDiaries();
this.diaryIndex = Math.max(0, diaries.length - 1);
const gallery = this.atelier.getState().gallery;
if (focusLevelIndex !== undefined) {
const idx = gallery.findIndex(item => item.levelIndex === focusLevelIndex);
if (idx >= 0) this.galleryCursor = idx;
}
if (this.galleryCursor >= gallery.length) {
this.galleryCursor = Math.max(0, gallery.length - 1);
}
this.wsToastLabel.string = '';
this.galToastLabel.string = '';
this.node.active = true;
this.refreshUI();
}
public close(): void {
this.node.active = false;
this.onChanged?.();
}
public refreshCurrentTab(): void {
if (!this.node.active) return;
this.refreshUI();
}
private buildUI(): void {
const scrim = createPanel('AtelierScrim', 3200, 3200, { fill: '#18120cc4', radius: 0 }, this.node);
const frame = createArtSprite('AtelierLinenFrame', 'ui/ui_linen_modal', 688, 790, scrim.node);
frame.node.setPosition(0, 6, 0);
// 顶部三页签切换栏(位于雕花拱顶下方留白区,避免与木雕花叶重叠)
const tabsBar = createUINode('AtelierTabs', 536, 40, frame.node);
tabsBar.setPosition(0, 146, 0);
const tabDefs: { id: AtelierTab; zh: string; x: number }[] = [
{ id: 'workshop', zh: '蚂蚁工坊', x: -178 },
{ id: 'gallery', zh: '绣品展柜', x: 0 },
{ id: 'letters', zh: '委托信箱', x: 178 },
];
for (const def of tabDefs) {
const btn = createButton({
name: `Tab_${def.id}`,
text: def.zh,
w: 168,
h: 38,
radius: 19,
fill: '#ead9b8',
stroke: '#c8ab77',
depth: 3,
depthColor: '#b5945e',
textColor: '#4e371e',
fontSize: 18,
onClick: () => {
this.sound.unlock();
this.activeTab = def.id;
this.wsToastLabel.string = '';
this.galToastLabel.string = '';
this.refreshUI();
},
}, tabsBar);
btn.node.setPosition(def.x, 0, 0);
this.tabBtns[def.id] = btn;
}
// 三个子页容器(上移留足底部提示与返回按钮的舒适间距)
this.tabGroups.workshop = createUINode('WorkshopGroup', 540, 360, frame.node);
this.tabGroups.workshop.setPosition(0, -40, 0);
this.buildWorkshopTab(this.tabGroups.workshop);
this.tabGroups.gallery = createUINode('GalleryGroup', 540, 360, frame.node);
this.tabGroups.gallery.setPosition(0, -40, 0);
this.buildGalleryTab(this.tabGroups.gallery);
this.tabGroups.letters = createUINode('LettersGroup', 540, 360, frame.node);
this.tabGroups.letters.setPosition(0, -40, 0);
this.buildLettersTab(this.tabGroups.letters);
this.closeBtn = createButton({
name: 'AtelierCloseBtn',
text: '返 回',
w: 220,
h: 48,
radius: 22,
fill: '#4d6f49',
stroke: '#8ab084',
depth: 4,
depthColor: '#2e472b',
textColor: '#fff9e8',
fontSize: 21,
onClick: () => {
this.sound.unlock();
this.close();
},
}, frame.node);
this.closeBtn.node.setPosition(0, -296, 0);
}
private buildWorkshopTab(parent: Node): void {
// 顶部状态条:当前持有线头 + 待领线头
const leftStat = createPanel('OwnedThreadsPill', 236, 34, {
fill: '#4b311c', stroke: '#d6ae63', strokeWidth: 1.6, radius: 17,
}, parent);
leftStat.node.setPosition(-128, 146, 0);
this.wsThreadsLabel = createLabel('Text', '柔丝线头:15 束', 220, 28, {
size: 16, color: '#fff4d6', bold: true, overflow: Label.Overflow.SHRINK,
}, leftStat.node);
const rightStat = createPanel('PendingThreadsPill', 246, 34, {
fill: '#3c5938', stroke: '#9cc286', strokeWidth: 1.6, radius: 17,
}, parent);
rightStat.node.setPosition(124, 146, 0);
this.wsPendingLabel = createLabel('Text', '待领:+4 束(最多8h)', 232, 28, {
size: 15, color: '#e9f9d8', bold: true, overflow: Label.Overflow.SHRINK,
}, rightStat.node);
// 实时动态小蚂蚁工作舞台
const stageNode = createUINode('AntWorkshopStage', 492, 152, parent);
stageNode.setPosition(0, 48, 0);
this.wsStageSprite = stageNode.addComponent(Sprite);
this.wsStageSprite.sizeMode = Sprite.SizeMode.CUSTOM;
this.wsStageSprite.spriteFrame = this.renderer.getWorkshopSpriteFrame();
// 收下线头按钮
this.wsCollectBtn = createButton({
name: 'CollectThreadsBtn',
text: '收下线头 (+4 束)',
w: 292,
h: 44,
radius: 22,
fill: '#df9c34',
stroke: '#fae09e',
depth: 4,
depthColor: '#996012',
textColor: '#3f2207',
fontSize: 19,
onClick: () => {
this.sound.unlock();
const res = this.atelier.collectPending(Date.now());
if (res.threads > 0) {
this.sound.bonus();
const diaries = this.atelier.getUnlockedDiaries();
if (res.newDiary) {
this.diaryIndex = Math.max(0, diaries.length - 1);
const title = this.isEn() ? res.newDiary.titleEn : res.newDiary.titleZh;
this.wsToastLabel.string = this.isEn()
? `Collected +${res.threads} threads & new diary: ${title}!`
: `收下 +${res.threads} 束线头!小蚂蚁带回新日记《${title}》`;
} else {
this.wsToastLabel.string = this.isEn()
? `Collected +${res.threads} threads! Use them in the Gallery.`
: `已收下 +${res.threads} 束线头,可去「绣品展柜」换装裱与落款!`;
}
this.refreshUI();
this.onChanged?.();
} else {
const mins = this.atelier.getNextThreadMinutes(Date.now());
this.wsToastLabel.string = this.isEn()
? `Ants are spinning... next thread in ~${mins} min.`
: `小蚂蚁正在勤快理线,约 ${mins} 分钟后产出新线头~`;
}
},
}, parent);
this.wsCollectBtn.node.setPosition(0, -56, 0);
// 底部:蚂蚁日记明信片
const diaryCard = createPanel('AntDiaryCard', 504, 102, {
fill: '#f7edd7', stroke: '#d2b682', strokeWidth: 1.8, radius: 16, stitchColor: '#d7be9099', stitchInset: 6,
}, parent);
diaryCard.node.setPosition(0, -138, 0);
this.wsDiaryHeaderLabel = createLabel('DiaryHeader', '蚂蚁日记 1/12 · 第一缕晨光', 310, 26, {
size: 16, color: '#472f18', bold: true, align: Label.HorizontalAlign.LEFT, overflow: Label.Overflow.SHRINK,
}, diaryCard.node);
this.wsDiaryHeaderLabel.node.setPosition(-74, 28, 0);
const moodPill = createPanel('DiaryMood', 78, 24, {
fill: '#c87e2d', radius: 12,
}, diaryCard.node);
moodPill.node.setPosition(116, 28, 0);
this.wsDiaryMoodBg = moodPill.graphics;
this.wsDiaryMoodLabel = createLabel('Text', '搬线中', 70, 22, {
size: 13, color: '#fff9ec', bold: true, overflow: Label.Overflow.SHRINK,
}, moodPill.node);
const prevDiary = createButton({
name: 'PrevDiaryBtn',
text: '‹',
w: 30,
h: 28,
radius: 14,
fill: '#e7d5b0',
stroke: '#c6a76e',
textColor: '#4c341a',
fontSize: 20,
onClick: () => {
const list = this.atelier.getUnlockedDiaries();
if (list.length <= 1) return;
this.diaryIndex = (this.diaryIndex - 1 + list.length) % list.length;
this.refreshWorkshop();
},
}, diaryCard.node);
prevDiary.node.setPosition(186, 28, 0);
const nextDiary = createButton({
name: 'NextDiaryBtn',
text: '›',
w: 30,
h: 28,
radius: 14,
fill: '#e7d5b0',
stroke: '#c6a76e',
textColor: '#4c341a',
fontSize: 20,
onClick: () => {
const list = this.atelier.getUnlockedDiaries();
if (list.length <= 1) return;
this.diaryIndex = (this.diaryIndex + 1) % list.length;
this.refreshWorkshop();
},
}, diaryCard.node);
nextDiary.node.setPosition(222, 28, 0);
this.wsDiaryBodyLabel = createLabel('DiaryBody', '', 462, 54, {
size: 15, color: '#5d472b', align: Label.HorizontalAlign.LEFT, overflow: Label.Overflow.SHRINK,
}, diaryCard.node);
this.wsDiaryBodyLabel.node.setPosition(0, -14, 0);
this.wsToastLabel = createLabel('WorkshopToast', '', 504, 24, {
size: 14, color: '#7a4f1b', bold: true, overflow: Label.Overflow.SHRINK,
}, parent);
this.wsToastLabel.node.setPosition(0, -200, 0);
}
private buildGalleryTab(parent: Node): void {
// 空展柜状态
this.galEmptyNode = createPanel('GalleryEmpty', 488, 220, {
fill: '#f4e8ce', stroke: '#d4b988', strokeWidth: 1.8, radius: 20,
}, parent).node;
this.galEmptyNode.setPosition(0, 10, 0);
createLabel('EmptyText', '绣成任意一幅作品后\n你的手绣藏品会自动陈列于此,并可换装裱导出海报。', 440, 90, {
size: 19, color: '#614a2c', bold: true, overflow: Label.Overflow.SHRINK,
}, this.galEmptyNode);
// 展柜主视图
this.galContentNode = createUINode('GalleryContent', 520, 356, parent);
// 左侧:装裱预览画框
const previewCard = createPanel('PosterPreviewCard', 222, 256, {
fill: '#627052', stroke: '#efe0bd', strokeWidth: 2.2, radius: 18, shadow: 4,
}, this.galContentNode);
previewCard.node.setPosition(-136, 30, 0);
this.galPreviewCardBg = previewCard.graphics;
const thumbNode = createUINode('GalleryThumb', 176, 176, previewCard.node);
thumbNode.setPosition(0, 22, 0);
this.galPreviewSprite = thumbNode.addComponent(Sprite);
this.galPreviewSprite.sizeMode = Sprite.SizeMode.CUSTOM;
this.galPreviewTitle = createLabel('ThumbTitle', '《金色向日葵》', 198, 26, {
size: 16, color: '#fff7e0', bold: true, overflow: Label.Overflow.SHRINK,
}, previewCard.node);
this.galPreviewTitle.node.setPosition(0, -82, 0);
this.galPreviewMeta = createLabel('ThumbMeta', '★★★ · 3.4 cm', 198, 22, {
size: 14, color: '#f4dc9e', bold: true, overflow: Label.Overflow.SHRINK,
}, previewCard.node);
this.galPreviewMeta.node.setPosition(0, -106, 0);
// 左侧底部翻页
const prevGal = createButton({
name: 'PrevGalleryBtn',
text: '‹',
w: 44,
h: 34,
radius: 17,
fill: '#e6d3ad',
stroke: '#c6a66c',
depth: 2,
depthColor: '#ad8d55',
textColor: '#483018',
fontSize: 24,
onClick: () => {
const list = this.atelier.getState().gallery;
if (list.length <= 1) return;
this.galleryCursor = (this.galleryCursor - 1 + list.length) % list.length;
this.refreshGallery();
},
}, this.galContentNode);
prevGal.node.setPosition(-208, -124, 0);
this.galCounterLabel = createLabel('GalCounter', '1 / 1', 90, 28, {
size: 16, color: '#4d361d', bold: true,
}, this.galContentNode);
this.galCounterLabel.node.setPosition(-136, -124, 0);
const nextGal = createButton({
name: 'NextGalleryBtn',
text: '›',
w: 44,
h: 34,
radius: 17,
fill: '#e6d3ad',
stroke: '#c6a66c',
depth: 2,
depthColor: '#ad8d55',
textColor: '#483018',
fontSize: 24,
onClick: () => {
const list = this.atelier.getState().gallery;
if (list.length <= 1) return;
this.galleryCursor = (this.galleryCursor + 1) % list.length;
this.refreshGallery();
},
}, this.galContentNode);
nextGal.node.setPosition(-64, -124, 0);
// 右侧:定制装裱 + 落款 + 导出按钮
const threadPill = createPanel('GalThreadPill', 250, 32, {
fill: '#4b311c', stroke: '#d6ae63', strokeWidth: 1.5, radius: 16,
}, this.galContentNode);
threadPill.node.setPosition(122, 138, 0);
this.galThreadsLabel = createLabel('Text', '柔丝线头:15 束', 236, 26, {
size: 15, color: '#fff3d4', bold: true, overflow: Label.Overflow.SHRINK,
}, threadPill.node);
createLabel('FrameHeading', '装裱风格', 248, 22, {
size: 15, color: '#584126', bold: true, align: Label.HorizontalAlign.LEFT,
}, this.galContentNode).node.setPosition(122, 104, 0);
this.galFrameBtns = POSTER_FRAMES.map((f, idx) => {
const col = idx % 2;
const row = Math.floor(idx / 2);
const btn = createButton({
name: `Frame_${f.id}`,
text: f.nameZh,
w: 120,
h: 38,
radius: 14,
fill: '#ead8b6',
stroke: '#c8ab77',
depth: 3,
depthColor: '#ad8e59',
textColor: '#4a321a',
fontSize: 15,
onClick: () => {
this.sound.unlock();
const res = this.atelier.selectOrUnlockFrame(f.id);
if (res.ok) {
this.sound.bonus();
this.galToastLabel.string = res.unlockedNow
? `已用 ${f.cost} 束线头解锁「${f.nameZh}」装裱!`
: `已切换为「${f.nameZh}」装裱风格`;
this.refreshGallery();
} else {
this.sound.block();
this.galToastLabel.string = `还差 ${res.need} 束线头(去「蚂蚁工坊」收线头或通关获取)`;
}
},
}, this.galContentNode);
btn.node.setPosition(58 + col * 128, 66 - row * 46, 0);
return { id: f.id, btn };
});
createLabel('QuoteHeading', '藏品落款(点击切换 / 解锁)', 248, 22, {
size: 14, color: '#584126', bold: true, align: Label.HorizontalAlign.LEFT,
}, this.galContentNode).node.setPosition(122, -16, 0);
this.galQuoteBtn = createButton({
name: 'QuoteCycleBtn',
text: '一针一线 · 慢享手作好时光',
w: 250,
h: 44,
radius: 14,
fill: '#f5ead2',
stroke: '#cca96e',
depth: 3,
depthColor: '#b3915a',
textColor: '#4c3318',
fontSize: 14,
onClick: () => {
this.sound.unlock();
const state = this.atelier.getState();
const curIdx = POSTER_QUOTES.findIndex(q => q.id === state.activeQuote);
const nextQuote = POSTER_QUOTES[(curIdx + 1) % POSTER_QUOTES.length];
const res = this.atelier.selectOrUnlockQuote(nextQuote.id);
if (res.ok) {
this.sound.bonus();
this.galToastLabel.string = res.unlockedNow
? `已用 ${nextQuote.cost} 束线头解锁新落款!`
: `已切换落款:「${nextQuote.zh}」`;
this.refreshGallery();
} else {
// 线头不够解锁下一条时,轮换已解锁落款并提示
const unlocked = state.unlockedQuotes;
const nextUnlocked = unlocked[(unlocked.indexOf(state.activeQuote) + 1) % unlocked.length];
this.atelier.selectOrUnlockQuote(nextUnlocked);
this.galToastLabel.string = `下条落款需 ${nextQuote.cost} 束线头(还差 ${res.need} 束)`;
this.refreshGallery();
}
},
}, this.galContentNode);
this.galQuoteBtn.node.setPosition(122, -56, 0);
this.galQuotePreview = this.galQuoteBtn.label;
this.galExportBtn = createButton({
name: 'ExportGalleryBtn',
text: '导出藏品海报',
w: 250,
h: 46,
radius: 22,
fill: '#4d7247',
stroke: '#8ab082',
depth: 4,
depthColor: '#2d4729',
textColor: '#fff9e8',
fontSize: 19,
onClick: () => {
this.sound.unlock();
const list = this.atelier.getState().gallery;
const item = list[this.galleryCursor];
if (!item) return;
const lv = LEVELS[item.levelIndex];
const chName = CHAPTERS[lv.chapter]?.name ?? '蚂蚁织画';
const qDef = this.atelier.getQuoteDef();
this.renderer.exportGalleryArtwork(
lv,
{
stars: item.stars,
lengthText: formatLength(item.length),
chapterName: chName,
levelNumber: item.levelIndex + 1,
frame: this.atelier.getFrameDef(),
quoteText: this.isEn() ? qDef.en : qDef.zh,
},
msg => {
this.galToastLabel.string = msg;
},
);
},
}, this.galContentNode);
this.galExportBtn.node.setPosition(122, -118, 0);
this.galToastLabel = createLabel('GalleryToast', '', 504, 24, {
size: 14, color: '#7a4f1b', bold: true, overflow: Label.Overflow.SHRINK,
}, parent);
this.galToastLabel.node.setPosition(0, -196, 0);
}
private buildLettersTab(parent: Node): void {
// 顶部 6 章信件切换条
const strip = createUINode('LetterChapterStrip', 516, 34, parent);
strip.setPosition(0, 142, 0);
this.letterTabs = CHAPTERS.map((_, idx) => {
const btn = createButton({
name: `LetterCh_${idx + 1}`,
text: CHAPTER_SHORT_ZH[idx],
w: 80,
h: 32,
radius: 16,
fill: '#ead8b6',
stroke: '#c8ab77',
depth: 2,
depthColor: '#b0915c',
textColor: '#4c3318',
fontSize: 14,
onClick: () => {
this.sound.unlock();
if (!this.isChapterUnlocked(idx)) {
this.sound.block();
return;
}
this.letterChapter = idx;
this.refreshLetters();
},
}, strip);
btn.node.setPosition((idx - 2.5) * 86, 0, 0);
const lockNode = createUINode('Lock', 16, 16, btn.node);
lockNode.setPosition(-21, 0, 0);
drawPadlockIcon(lockNode.addComponent(Graphics), 0.78, '#b89b6a', '#d7bd8e', '#46311f');
lockNode.active = false;
return { btn, lockNode };
});
// 上半卡:客人委托来信(舒朗间距)
const reqCard = createPanel('RequestLetterCard', 506, 138, {
fill: '#f9f0dc', stroke: '#d2b47d', strokeWidth: 1.8, radius: 18, stitchColor: '#d9bf8e99', stitchInset: 7,
}, parent);
reqCard.node.setPosition(0, 42, 0);
const waxDot = createPanel('ReqWax', 18, 18, { fill: '#c85450', stroke: '#f4d39c', strokeWidth: 1.5, radius: 9 }, reqCard.node);
waxDot.node.setPosition(-224, 42, 0);
this.letterReqHeader = createLabel('ReqHeader', '', 436, 28, {
size: 17, color: '#452c15', bold: true, align: Label.HorizontalAlign.LEFT, overflow: Label.Overflow.SHRINK,
}, reqCard.node);
this.letterReqHeader.node.setPosition(10, 42, 0);
this.letterReqBody = createLabel('ReqBody', '', 462, 80, {
size: 16, color: '#5c462b', align: Label.HorizontalAlign.LEFT, overflow: Label.Overflow.SHRINK,
}, reqCard.node);
this.letterReqBody.node.setPosition(0, -14, 0);
// 下半卡:成画回信(与委托卡保持舒适留白)
const replyCard = createPanel('ReplyLetterCard', 506, 138, {
fill: '#eaf1e1', stroke: '#9ab785', strokeWidth: 1.8, radius: 18, stitchColor: '#9ab78588', stitchInset: 7,
}, parent);
replyCard.node.setPosition(0, -118, 0);
this.letterReplyBg = replyCard.graphics;
this.letterReplyLockNode = createUINode('ReplyLock', 28, 28, replyCard.node);
this.letterReplyLockNode.setPosition(0, 32, 0);
drawPadlockIcon(this.letterReplyLockNode.addComponent(Graphics), 1.35, '#bfa06a', '#e3ca97', '#4a321b');
this.letterReplyHeader = createLabel('ReplyHeader', '', 450, 28, {
size: 17, color: '#33542d', bold: true, align: Label.HorizontalAlign.LEFT, overflow: Label.Overflow.SHRINK,
}, replyCard.node);
this.letterReplyHeader.node.setPosition(0, 42, 0);
this.letterReplyBody = createLabel('ReplyBody', '', 462, 80, {
size: 16, color: '#43583c', align: Label.HorizontalAlign.LEFT, overflow: Label.Overflow.SHRINK,
}, replyCard.node);
this.letterReplyBody.node.setPosition(0, -14, 0);
}
private refreshUI(): void {
const en = this.isEn();
this.tabBtns.workshop.label.string = en ? 'Ant Craft' : '蚂蚁工坊';
this.tabBtns.gallery.label.string = en ? 'Gallery' : '绣品展柜';
this.tabBtns.letters.label.string = en ? 'Letters' : '委托信箱';
this.closeBtn.label.string = en ? 'Back' : '返 回';
(['workshop', 'gallery', 'letters'] as AtelierTab[]).forEach(tab => {
const active = tab === this.activeTab;
this.tabGroups[tab].active = active;
this.tabBtns[tab].setStyle(
active ? '#c85b56' : '#ead9b8',
active ? '#f7d58b' : '#c8ab77',
active ? '#fff9eb' : '#4e371e',
active ? '#823430' : '#b5945e',
);
});
if (this.activeTab === 'workshop') this.refreshWorkshop();
else if (this.activeTab === 'gallery') this.refreshGallery();
else this.refreshLetters();
}
private refreshWorkshop(): void {
const en = this.isEn();
const st = this.atelier.getState();
this.wsThreadsLabel.string = en ? `Threads: ${st.yarnThreads}` : `柔丝线头:${st.yarnThreads} 束`;
this.wsPendingLabel.string = en
? `Ready: +${st.pendingThreads}/${IDLE_MAX_THREADS}`
: `待领:+${st.pendingThreads} 束(8h封顶)`;
if (st.pendingThreads > 0) {
this.wsCollectBtn.label.string = en
? `Collect Threads (+${st.pendingThreads})`
: `收下线头 (+${st.pendingThreads} 束)`;
this.wsCollectBtn.setStyle('#df9c34', '#fae09e', '#3f2207', '#996012');
} else {
const mins = this.atelier.getNextThreadMinutes(Date.now());
this.wsCollectBtn.label.string = en
? `Spinning... +1 in ${mins}m`
: `工坊织线中 · ${mins} 分钟后 +1`;
this.wsCollectBtn.setStyle('#d9c8a5', '#bca479', '#6c573c', '#a89066');
}
const diaries = this.atelier.getUnlockedDiaries();
const idx = Math.min(this.diaryIndex, Math.max(0, diaries.length - 1));
const diary = diaries[idx] ?? ANT_DIARIES[0];
this.wsDiaryHeaderLabel.string = en
? `Diary ${idx + 1}/${ANT_DIARIES.length} · ${diary.titleEn}`
: `蚂蚁日记 ${idx + 1}/${ANT_DIARIES.length} · ${diary.titleZh}`;
this.wsDiaryMoodLabel.string = en ? diary.moodEn : diary.moodZh;
drawRoundedBox(this.wsDiaryMoodBg, 78, 24, { fill: diary.accentColor, radius: 12 });
this.wsDiaryBodyLabel.string = en ? diary.bodyEn : diary.bodyZh;
this.renderer.renderWorkshopFrame(this.workshopTimeMs, st.pendingThreads);
}
private refreshGallery(): void {
const en = this.isEn();
const st = this.atelier.getState();
const hasItems = st.gallery.length > 0;
this.galEmptyNode.active = !hasItems;
this.galContentNode.active = hasItems;
if (!hasItems) return;
if (this.galleryCursor >= st.gallery.length) this.galleryCursor = st.gallery.length - 1;
const item = st.gallery[this.galleryCursor];
const lv = LEVELS[item.levelIndex];
const frameDef = this.atelier.getFrameDef();
const quoteDef = this.atelier.getQuoteDef();
drawRoundedBox(this.galPreviewCardBg, 222, 256, {
fill: frameDef.bgTop,
stroke: frameDef.accent,
strokeWidth: 2.4,
radius: 18,
shadow: 4,
});
this.galPreviewSprite.spriteFrame = this.getThumbnail(item.levelIndex);
this.galPreviewTitle.string = en ? lv.name : `《${lv.name}》`;
this.galPreviewTitle.color = hex(frameDef.accent);
this.galPreviewMeta.string = `${'★'.repeat(item.stars)}${'☆'.repeat(3 - item.stars)} · ${formatLength(item.length)}`;
this.galCounterLabel.string = `${this.galleryCursor + 1} / ${st.gallery.length}`;
this.galThreadsLabel.string = en ? `Threads: ${st.yarnThreads}` : `柔丝线头:${st.yarnThreads} 束`;
for (const entry of this.galFrameBtns) {
const def = POSTER_FRAMES.find(f => f.id === entry.id)!;
const unlocked = st.unlockedFrames.includes(entry.id);
const active = st.activeFrame === entry.id;
const baseName = en ? def.nameEn : def.nameZh;
entry.btn.label.string = unlocked ? baseName : `${baseName}(${def.cost})`;
entry.btn.setStyle(
active ? '#c85b56' : unlocked ? '#ead8b6' : '#ddd0b7',
active ? '#f7d58b' : unlocked ? '#c8ab77' : '#b2a184',
active ? '#fff9eb' : unlocked ? '#4a321a' : '#7b684e',
active ? '#823430' : '#ad8e59',
);
}
this.galQuotePreview.string = en ? quoteDef.en : quoteDef.zh;
this.galExportBtn.label.string = en ? 'Export Poster' : '导出藏品海报';
}
private refreshLetters(): void {
const en = this.isEn();
const shortList = en ? CHAPTER_SHORT_EN : CHAPTER_SHORT_ZH;
this.letterTabs.forEach((tab, idx) => {
const unlocked = this.isChapterUnlocked(idx);
const active = idx === this.letterChapter;
tab.btn.label.string = shortList[idx];
tab.lockNode.active = !unlocked;
tab.btn.label.node.setPosition(unlocked ? 0 : 8, 1, 0);
tab.btn.setStyle(
active ? '#c85b56' : unlocked ? '#ead8b6' : '#d6cab4',
active ? '#f7d58b' : unlocked ? '#c8ab77' : '#aea08a',
active ? '#fff9eb' : unlocked ? '#4c3318' : '#857763',
active ? '#823430' : '#ad8e59',
);
});
const letter = this.atelier.getLetter(this.letterChapter);
this.letterReqHeader.string = en
? `${letter.senderEn} · ${letter.titleEn}`
: `委托人:${letter.senderZh} · 《${letter.titleZh}》`;
this.letterReqBody.string = en ? letter.requestEn : letter.requestZh;
const replyUnlocked = this.atelier.isChapterReplyUnlocked(this.letterChapter, lv => this.storage.getRecord(lv));
const ch = CHAPTERS[this.letterChapter];
const chStars = LEVELS.slice(ch.startIndex, ch.startIndex + ch.count).reduce(
(sum, lv) => sum + (this.storage.getRecord(lv)?.stars ?? 0),
0,
);
this.letterReplyLockNode.active = !replyUnlocked;
if (replyUnlocked) {
drawRoundedBox(this.letterReplyBg, 506, 138, {
fill: '#eaf1e1', stroke: '#8fb27a', strokeWidth: 1.8, radius: 18, stitchColor: '#8fb27a88', stitchInset: 7,
});
this.letterReplyHeader.node.active = true;
this.letterReplyHeader.string = en ? `✦ ${letter.replyTitleEn}` : `✦ ${letter.replyTitleZh}`;
this.letterReplyBody.color = hex('#3a5433');
this.letterReplyBody.horizontalAlign = Label.HorizontalAlign.LEFT;
this.letterReplyBody.node.setPosition(0, -14, 0);
this.letterReplyBody.string = en ? letter.replyEn : letter.replyZh;
} else {
drawRoundedBox(this.letterReplyBg, 506, 138, {
fill: '#efe5d0', stroke: '#cbb48a', strokeWidth: 1.6, radius: 18, stitchColor: '#cbb48a80', stitchInset: 7,
});
this.letterReplyHeader.node.active = false;
this.letterReplyBody.color = hex('#755f42');
this.letterReplyBody.horizontalAlign = Label.HorizontalAlign.CENTER;
this.letterReplyBody.node.setPosition(0, -16, 0);
this.letterReplyBody.string = this.letterChapter === 0
? (en
? 'Finish Stage 1 (Golden Sunflower) to read Grandma Lin’s reply!'
: '绣完第 1 关《金色向日葵》,即可立刻拆阅林阿婆的暖心回信!')
: (en
? `Clear Chapter Boss or earn 15 ★ in this chapter to open the reply (${chStars} / 15 ★).`
: `通关本章终考关,或本章集满 15 ★ 即可拆阅客人回信\n(当前本章已获 ${chStars} / 15 ★)`);
}
}
protected update(dt: number): void {
if (!this.node.active || this.activeTab !== 'workshop') return;
this.workshopTimeMs += Math.min(50, Math.max(0, dt * 1000));
this.renderer.renderWorkshopFrame(this.workshopTimeMs, this.atelier.getState().pendingThreads);
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "9dc539ef-2450-466e-a081-e730151809b3",
"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": "80a6df9c-75ae-44b3-b21e-b0f999a50a37",
"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": "a0eaa4b4-714c-4e00-9412-68230ed12d7e",
"files": [],
"subMetas": {},
"userData": {}
}
+179
View File
@@ -0,0 +1,179 @@
import { Node, ResolutionPolicy, screen, UITransform, Vec3, view } from 'cc';
declare const wx: any;
export const DESIGN_W = 750;
export const DESIGN_H = 1334;
export interface ScreenMetrics {
visibleW: number;
visibleH: number;
/** 顶部安全区高度(含刘海/灵动岛,设计坐标) */
topInset: number;
/** 微信右上角胶囊下沿距屏幕顶部的安全距离(设计坐标) */
capsuleBottom: number;
/** 底部安全区高度(含 iPhone Home 手势条,设计坐标) */
bottomInset: number;
/** 安全区实际可用高度(safeRoot 局部坐标系中 >= 1334,全面屏自动舒展消除上下大空白) */
safeHeight: number;
/** 安全区半高:safeRoot 内顶安全边 = +safeHalfH,底安全边 = -safeHalfH */
safeHalfH: number;
/** 超出 1334 基准的额外垂直空间(用于均匀拉宽中间板块间距) */
extraH: number;
/** 主内容区整体缩放系数(仅超短屏 + 胶囊时自动收拢防裁切) */
contentScale: number;
/** safeRoot 中心在屏幕中的 Y 偏移 */
contentOffsetY: number;
/** 背景图全屏铺满(cover)所需缩放系数 */
bgCoverScale: number;
isWeChat: boolean;
/** 浏览器预览调试参数 ?wxsim=iphone15 / ?wxsim=iphonese 时的模拟胶囊信息 */
mockCapsule?: { top: number; height: number; width: number; right: number };
}
function getWeChatSimMode(): 'iphone15' | 'iphonese' | null {
try {
if (typeof window === 'undefined' || !window.location?.search) return null;
const params = new URLSearchParams(window.location.search);
const val = (params.get('wxsim') || '').toLowerCase();
if (val === 'iphone15' || val === '15') return 'iphone15';
if (val === 'iphonese' || val === 'se') return 'iphonese';
} catch {
// Ignore non-browser environments.
}
return null;
}
/**
* 自适应分辨率策略:
* - 竖屏手机(比例 <= 9:16,如 16:9 / 19.5:9 / 20:9)使用 FIXED_WIDTH,消除全面屏上下黑边;
* - 平板 / 折叠屏展开 / 桌面横屏预览(比例 > 9:16)使用 FIXED_HEIGHT,确保上下完整不裁切。
*/
export function applyResponsivePolicy(): void {
const frame = screen.windowSize;
if (!frame || frame.width <= 0 || frame.height <= 0) return;
const aspect = frame.width / frame.height;
const designAspect = DESIGN_W / DESIGN_H;
const policy = aspect <= designAspect + 0.005 ? ResolutionPolicy.FIXED_WIDTH : ResolutionPolicy.FIXED_HEIGHT;
view.setDesignResolutionSize(DESIGN_W, DESIGN_H, policy);
}
/**
* 统一读取微信小游戏胶囊按钮(getMenuButtonBoundingClientRect)与安全区(getWindowInfo / getSystemInfoSync),
* 并换算为 Cocos 设计分辨率坐标系。
*/
export function computeScreenMetrics(): ScreenMetrics {
const vis = view.getVisibleSize();
const visibleW = Math.max(DESIGN_W, vis.width || DESIGN_W);
const visibleH = Math.max(DESIGN_H, vis.height || DESIGN_H);
let topInset = 0;
let capsuleBottom = 0;
let bottomInset = 0;
let isWeChat = false;
let mockCapsule: ScreenMetrics['mockCapsule'];
if (typeof wx !== 'undefined') {
isWeChat = true;
try {
const winInfo =
typeof wx.getWindowInfo === 'function'
? wx.getWindowInfo()
: typeof wx.getSystemInfoSync === 'function'
? wx.getSystemInfoSync()
: null;
const winH = Number(winInfo?.windowHeight) || Number(winInfo?.screenHeight) || 0;
const scaleY = winH > 0 ? visibleH / winH : visibleW / (Number(winInfo?.windowWidth) || 375);
const safe = winInfo?.safeArea;
if (safe && winH > 0) {
topInset = Math.max(0, Number(safe.top) || 0) * scaleY;
const rawBottom = winH - (Number(safe.bottom) || winH);
bottomInset = Math.max(0, rawBottom) * scaleY;
} else if (winInfo?.statusBarHeight) {
topInset = Math.max(0, Number(winInfo.statusBarHeight) || 0) * scaleY;
}
if (typeof wx.getMenuButtonBoundingClientRect === 'function') {
const menu = wx.getMenuButtonBoundingClientRect();
if (menu && Number(menu.bottom) > 0) {
// 紧贴胶囊下沿留 10px 轻呼吸距,避免顶部出现大块空白
capsuleBottom = Number(menu.bottom) * scaleY + 10;
}
}
if (capsuleBottom <= 0) {
capsuleBottom = Math.max(topInset + 76, 108);
}
} catch {
capsuleBottom = 112;
bottomInset = 32;
}
} else {
const sim = getWeChatSimMode();
if (sim === 'iphone15') {
isWeChat = true;
topInset = 98;
capsuleBottom = 172;
bottomInset = 52;
mockCapsule = { top: 98, height: 62, width: 168, right: 20 };
} else if (sim === 'iphonese') {
isWeChat = true;
topInset = 38;
capsuleBottom = 112;
bottomInset = 0;
mockCapsule = { top: 38, height: 64, width: 174, right: 18 };
}
}
const effectiveTop = Math.max(topInset, capsuleBottom);
// 底部手势条只保留必要安全高度(上限 54px),避免底部产生大块空木板
const effectiveBottom = Math.min(54, Math.max(0, bottomInset));
const availableH = Math.max(640, visibleH - effectiveTop - effectiveBottom);
const contentScale = availableH < DESIGN_H ? Math.max(0.78, availableH / DESIGN_H) : 1;
const safeHeight = availableH >= DESIGN_H ? Math.min(1560, availableH) : DESIGN_H;
const safeHalfH = safeHeight / 2;
const extraH = Math.max(0, safeHeight - DESIGN_H);
const safeTopY = visibleH / 2 - effectiveTop;
const safeBottomY = -visibleH / 2 + effectiveBottom;
const contentOffsetY = (safeTopY + safeBottomY) / 2;
const bgCoverScale = Math.max(visibleW / DESIGN_W, visibleH / DESIGN_H);
return {
visibleW,
visibleH,
topInset,
capsuleBottom,
bottomInset,
safeHeight,
safeHalfH,
extraH,
contentScale,
contentOffsetY,
bgCoverScale,
isWeChat,
mockCapsule,
};
}
/** 将主内容容器精准居中并缩放到安全区(避开微信胶囊 + 刘海 + 底部手势条) */
export function applySafeContentTransform(contentRoot: Node, m: ScreenMetrics): void {
const ui = contentRoot.getComponent(UITransform);
if (ui) ui.setContentSize(DESIGN_W, m.safeHeight);
contentRoot.setPosition(0, m.contentOffsetY, 0);
contentRoot.setScale(new Vec3(m.contentScale, m.contentScale, 1));
}
/** 将背景精灵按屏幕比例等比铺满(cover),消除全面屏上下黑边 */
export function applyCoverBackground(bgNode: Node, m: ScreenMetrics): void {
bgNode.setPosition(0, 0, 0);
bgNode.setScale(new Vec3(m.bgCoverScale, m.bgCoverScale, 1));
}
/** 将遮罩节点铺满全屏(兼容任意长宽比) */
export function applyFullScrimSize(scrimNode: Node, m: ScreenMetrics): void {
const ui = scrimNode.getComponent(UITransform);
if (ui) ui.setContentSize(Math.max(2400, m.visibleW + 40), Math.max(2400, m.visibleH + 40));
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "a8021e06-ffa1-41ce-bd82-0ac950fbd90f",
"files": [],
"subMetas": {},
"userData": {}
}
+853
View File
@@ -0,0 +1,853 @@
import { Button, Color, Graphics, ImageAsset, Label, Layers, Node, resources, Sprite, SpriteFrame, Texture2D, UITransform, Widget } from 'cc';
declare const wx: any;
export const UI_LAYER = Layers.Enum.UI_2D;
export function hex(code: string): Color {
const c = new Color();
Color.fromHEX(c, code);
return c;
}
export interface BoxStyle {
fill?: string;
stroke?: string;
strokeWidth?: number;
radius?: number;
/** 3D 底部厚边(实体按键/木牌立体感) */
depth?: number;
depthColor?: string;
/** 柔和落影偏移 */
shadow?: number;
shadowColor?: string;
/** 顶部高光细线 */
highlight?: string;
/** 内侧虚线手缝线装饰 */
stitchColor?: string;
stitchInset?: number;
/** 四角黄铜铆钉装饰 */
rivets?: boolean;
rivetColor?: string;
}
export function createUINode(name: string, w: number, h: number, parent?: Node): Node {
const node = new Node(name);
node.layer = UI_LAYER;
const ui = node.addComponent(UITransform);
ui.setContentSize(w, h);
if (parent) parent.addChild(node);
return node;
}
function drawDashedRect(g: Graphics, x: number, y: number, w: number, h: number, color: string): void {
g.strokeColor = hex(color);
g.lineWidth = 1.6;
const dash = 7;
const gap = 5;
const drawEdge = (x1: number, y1: number, x2: number, y2: number) => {
const dist = Math.hypot(x2 - x1, y2 - y1);
const ux = (x2 - x1) / dist;
const uy = (y2 - y1) / dist;
let pos = 4;
while (pos < dist - 4) {
const end = Math.min(dist - 4, pos + dash);
g.moveTo(x1 + ux * pos, y1 + uy * pos);
g.lineTo(x1 + ux * end, y1 + uy * end);
pos = end + gap;
}
};
drawEdge(x, y + h, x + w, y + h);
drawEdge(x + w, y + h, x + w, y);
drawEdge(x + w, y, x, y);
drawEdge(x, y, x, y + h);
g.stroke();
}
export function drawPadlockIcon(
g: Graphics,
scale = 1,
bodyColor = '#d6b67d',
shackleColor = '#ecd2a2',
keyholeColor = '#46311f',
): void {
g.clear();
const s = scale;
const r = 3.7 * s;
const archY = 3.2 * s;
// 锁梁(U 型圆弧,手动采样保证各端方向一致)
g.strokeColor = hex(shackleColor);
g.lineWidth = Math.max(1.5, 2.0 * s);
g.moveTo(-r, 0.2 * s);
g.lineTo(-r, archY);
const steps = 12;
for (let i = 1; i <= steps; i++) {
const t = Math.PI - (Math.PI * i) / steps;
g.lineTo(Math.cos(t) * r, archY + Math.sin(t) * r);
}
g.lineTo(r, 0.2 * s);
g.stroke();
// 锁身(倒角金属块)
const bw = 11.4 * s;
const bh = 8.6 * s;
g.fillColor = hex(bodyColor);
g.roundRect(-bw / 2, -6.8 * s, bw, bh, 2.2 * s);
g.fill();
// 锁孔
g.fillColor = hex(keyholeColor);
g.circle(0, -1.7 * s, 1.45 * s);
g.fill();
g.rect(-0.68 * s, -4.6 * s, 1.36 * s, 2.7 * s);
g.fill();
}
export function drawEnvelopeIcon(g: Graphics, scale = 1, color = '#fff2cf', sealColor = '#d45a52'): void {
g.clear();
const s = scale;
const w = 22 * s;
const h = 15 * s;
g.strokeColor = hex(color);
g.lineWidth = Math.max(1.6, 2.1 * s);
g.roundRect(-w / 2, -h / 2, w, h, 2.4 * s);
g.stroke();
g.moveTo(-w / 2 + 1.5 * s, h / 2 - 1.5 * s);
g.lineTo(0, -1.2 * s);
g.lineTo(w / 2 - 1.5 * s, h / 2 - 1.5 * s);
g.stroke();
g.fillColor = hex(sealColor);
g.circle(0, -1.6 * s, 3.0 * s);
g.fill();
}
export function drawSpoolIcon(g: Graphics, scale = 1, woodColor = '#f4d694', threadColor = '#93be76'): void {
g.clear();
const s = scale;
// 绕线身
g.fillColor = hex(threadColor);
g.roundRect(-7 * s, -7 * s, 14 * s, 14 * s, 2.5 * s);
g.fill();
// 几道柔和丝线横纹
g.strokeColor = hex('#eef7dc99');
g.lineWidth = 1.3 * s;
for (const ry of [-3.4, 0, 3.4]) {
g.moveTo(-6.2 * s, ry * s);
g.lineTo(6.2 * s, ry * s);
}
g.stroke();
// 上下木挡片
g.fillColor = hex(woodColor);
g.roundRect(-10.5 * s, 6.2 * s, 21 * s, 4.4 * s, 2 * s);
g.roundRect(-10.5 * s, -10.6 * s, 21 * s, 4.4 * s, 2 * s);
g.fill();
}
export function drawGalleryFrameIcon(g: Graphics, scale = 1, frameColor = '#fff0c8', accentColor = '#e6b14c'): void {
g.clear();
const s = scale;
const w = 20 * s;
const h = 22 * s;
g.strokeColor = hex(frameColor);
g.lineWidth = Math.max(1.8, 2.2 * s);
g.roundRect(-w / 2, -h / 2, w, h, 3 * s);
g.stroke();
// 内绣绷圆环 + 小花点缀
g.strokeColor = hex(accentColor);
g.lineWidth = 1.6 * s;
g.circle(0, 1.5 * s, 5.4 * s);
g.stroke();
g.fillColor = hex(accentColor);
g.circle(0, 1.5 * s, 2.2 * s);
g.fill();
g.strokeColor = hex(frameColor);
g.lineWidth = 1.5 * s;
g.moveTo(-5.5 * s, -6.8 * s);
g.lineTo(5.5 * s, -6.8 * s);
g.stroke();
}
export function drawRoundedBox(g: Graphics, w: number, h: number, style: BoxStyle): void {
g.clear();
const r = Math.min(style.radius ?? 16, w / 2, h / 2);
const x = -w / 2;
const y = -h / 2;
const depth = style.depth ?? 0;
const shadow = style.shadow ?? 0;
// 1. 柔和地面投影
if (shadow > 0) {
g.fillColor = hex(style.shadowColor ?? '#1b211438');
const sy = y - depth - shadow;
if (r > 0) g.roundRect(x + 1, sy, w - 2, h, r);
else g.rect(x + 1, sy, w - 2, h);
g.fill();
}
// 2. 实体 3D 底座厚边
if (depth > 0) {
g.fillColor = hex(style.depthColor ?? '#3b4530');
if (r > 0) g.roundRect(x, y - depth, w, h, r);
else g.rect(x, y - depth, w, h);
g.fill();
}
// 3. 主面板填充
if (style.fill) {
g.fillColor = hex(style.fill);
if (r > 0) g.roundRect(x, y, w, h, r);
else g.rect(x, y, w, h);
g.fill();
}
// 4. 顶部微光高光带(让按钮/木牌有温润手作光泽)
if (style.highlight && w > 24 && h > 16) {
const inset = Math.max(4, Math.min(r * 0.65, 16));
g.strokeColor = hex(style.highlight);
g.lineWidth = 2;
g.moveTo(x + inset, y + h - 2.5);
g.lineTo(x + w - inset, y + h - 2.5);
g.stroke();
}
// 5. 外描边
if (style.stroke) {
g.strokeColor = hex(style.stroke);
g.lineWidth = style.strokeWidth ?? 2;
if (r > 0) g.roundRect(x, y, w, h, r);
else g.rect(x, y, w, h);
g.stroke();
}
// 6. 内侧手缝虚线
if (style.stitchColor) {
const inset = style.stitchInset ?? 8;
if (w > inset * 2 + 16 && h > inset * 2 + 16) {
drawDashedRect(g, x + inset, y + inset, w - inset * 2, h - inset * 2, style.stitchColor);
}
}
// 7. 四角黄铜铆钉
if (style.rivets && w > 48 && h > 40) {
const pad = Math.max(12, Math.min(18, r * 0.65));
const pts = [
[x + pad, y + h - pad],
[x + w - pad, y + h - pad],
[x + pad, y + pad],
[x + w - pad, y + pad],
];
for (const [rx, ry] of pts) {
g.fillColor = hex('#2c1e1255');
g.circle(rx, ry - 1.2, 3.6);
g.fill();
g.fillColor = hex(style.rivetColor ?? '#d9ad62');
g.circle(rx, ry, 3.2);
g.fill();
g.fillColor = hex('#fff2cfcc');
g.circle(rx - 0.9, ry + 0.9, 1.1);
g.fill();
}
}
}
export function createPanel(name: string, w: number, h: number, style: BoxStyle, parent?: Node): { node: Node; graphics: Graphics } {
const node = createUINode(name, w, h, parent);
const graphics = node.addComponent(Graphics);
drawRoundedBox(graphics, w, h, style);
return { node, graphics };
}
export interface LabelStyle {
size?: number;
lineHeight?: number;
color?: string;
bold?: boolean;
align?: number;
verticalAlign?: number;
overflow?: number;
}
export function createLabel(name: string, text: string, w: number, h: number, style: LabelStyle = {}, parent?: Node): Label {
const node = createUINode(name, w, h, parent);
const label = node.addComponent(Label);
label.string = text;
label.fontSize = style.size ?? 24;
label.lineHeight = style.lineHeight ?? Math.round((style.size ?? 24) * 1.25);
label.color = hex(style.color ?? '#302e22');
label.isBold = Boolean(style.bold);
label.horizontalAlign = style.align ?? Label.HorizontalAlign.CENTER;
label.verticalAlign = style.verticalAlign ?? Label.VerticalAlign.CENTER;
if (style.overflow !== undefined) label.overflow = style.overflow;
return label;
}
export interface ButtonSpec {
name: string;
text: string;
w: number;
h: number;
fill: string;
stroke?: string;
depth?: number;
depthColor?: string;
shadow?: number;
highlight?: string;
stitchColor?: string;
textColor?: string;
fontSize?: number;
radius?: number;
bold?: boolean;
onClick: () => void;
}
export interface StyledButton {
node: Node;
button: Button;
label: Label;
graphics: Graphics;
setStyle: (fill: string, stroke: string | undefined, textColor: string, depthColor?: string) => void;
setEnabled: (enabled: boolean) => void;
}
export function createButton(spec: ButtonSpec, parent?: Node): StyledButton {
const radius = spec.radius ?? Math.min(22, spec.h / 2);
const depth = spec.depth ?? 5;
const shadow = spec.shadow ?? 3;
const highlight = spec.highlight ?? '#ffffff55';
const defaultDepth = spec.depthColor ?? spec.stroke ?? '#3c4530';
const { node, graphics } = createPanel(
spec.name,
spec.w,
spec.h,
{
fill: spec.fill,
stroke: spec.stroke,
strokeWidth: 2,
radius,
depth,
depthColor: defaultDepth,
shadow,
highlight,
stitchColor: spec.stitchColor,
stitchInset: 6,
},
parent,
);
const label = createLabel(
'Label',
spec.text,
spec.w - 14,
spec.h,
{
size: spec.fontSize ?? 24,
color: spec.textColor ?? '#302e22',
bold: spec.bold ?? true,
overflow: Label.Overflow.SHRINK,
},
node,
);
const button = node.addComponent(Button);
button.transition = Button.Transition.SCALE;
button.zoomScale = 0.93;
node.on(Button.EventType.CLICK, () => {
if (button.interactable) spec.onClick();
});
return {
node,
button,
label,
graphics,
setStyle(fill: string, stroke: string | undefined, textColor: string, depthColor?: string) {
drawRoundedBox(graphics, spec.w, spec.h, {
fill,
stroke,
strokeWidth: 2,
radius,
depth,
depthColor: depthColor ?? stroke ?? defaultDepth,
shadow,
highlight,
stitchColor: spec.stitchColor,
stitchInset: 6,
});
label.color = hex(textColor);
},
setEnabled(enabled: boolean) {
button.interactable = enabled;
const base = label.color.clone();
base.a = enabled ? 255 : 115;
label.color = base;
},
};
}
export interface DockButtonSpec {
name: string;
icon: string;
text: string;
w: number;
h: number;
fill: string;
stroke: string;
depthColor: string;
iconBg: string;
iconColor: string;
textColor: string;
onClick: () => void;
}
export interface DockButton extends StyledButton {
iconLabel: Label;
iconBgGraphics: Graphics;
setDockStyle: (fill: string, stroke: string, depthColor: string, iconBg: string, iconColor: string, textColor: string) => void;
}
/** 底部游戏工具栏专用:上图标徽章 + 下短文字 + 3D 实体木/陶按压底座 */
export function createDockButton(spec: DockButtonSpec, parent?: Node): DockButton {
const radius = 20;
const { node, graphics } = createPanel(
spec.name,
spec.w,
spec.h,
{
fill: spec.fill,
stroke: spec.stroke,
strokeWidth: 2,
radius,
depth: 6,
depthColor: spec.depthColor,
shadow: 4,
highlight: '#fffdf466',
},
parent,
);
const badge = createPanel('IconBadge', 44, 44, { fill: spec.iconBg, radius: 22 }, node);
badge.node.setPosition(0, 14, 0);
const iconLabel = createLabel('Icon', spec.icon, 44, 44, { size: 25, color: spec.iconColor, bold: true }, badge.node);
const label = createLabel(
'Label',
spec.text,
spec.w - 10,
26,
{ size: 18, color: spec.textColor, bold: true, overflow: Label.Overflow.SHRINK },
node,
);
label.node.setPosition(0, -25, 0);
const button = node.addComponent(Button);
button.transition = Button.Transition.SCALE;
button.zoomScale = 0.91;
node.on(Button.EventType.CLICK, () => {
if (button.interactable) spec.onClick();
});
const applyDock = (fill: string, stroke: string, depthColor: string, iconBg: string, iconColor: string, textColor: string) => {
drawRoundedBox(graphics, spec.w, spec.h, {
fill,
stroke,
strokeWidth: 2,
radius,
depth: 6,
depthColor,
shadow: 4,
highlight: '#fffdf466',
});
drawRoundedBox(badge.graphics, 44, 44, { fill: iconBg, radius: 22 });
iconLabel.color = hex(iconColor);
label.color = hex(textColor);
};
return {
node,
button,
label,
graphics,
iconLabel,
iconBgGraphics: badge.graphics,
setStyle(fill: string, stroke: string | undefined, textColor: string, depthColor?: string) {
applyDock(fill, stroke ?? spec.stroke, depthColor ?? stroke ?? spec.depthColor, spec.iconBg, spec.iconColor, textColor);
},
setDockStyle: applyDock,
setEnabled(enabled: boolean) {
button.interactable = enabled;
const tc = label.color.clone();
tc.a = enabled ? 255 : 110;
label.color = tc;
const ic = iconLabel.color.clone();
ic.a = enabled ? 255 : 110;
iconLabel.color = ic;
},
};
}
function makeOffscreenCanvas(w: number, h: number): any {
const c = typeof wx !== 'undefined' && typeof wx.createCanvas === 'function'
? wx.createCanvas()
: document.createElement('canvas');
c.width = w;
c.height = h;
return c;
}
function canvasToSpriteFrame(canvas: any): SpriteFrame {
const img = new ImageAsset(canvas);
const tex = new Texture2D();
tex.image = img;
const sf = new SpriteFrame();
sf.texture = tex;
return sf;
}
let cachedPlayBg: SpriteFrame | null = null;
let cachedLobbyBg: SpriteFrame | null = null;
/** 生成对局场景全屏「手作刺绣工坊桌面」纹理(苔绿麻布台垫 + 暖光斜照 + 木桌边沿 + 角落小道具) */
export function createAtelierTableSpriteFrame(): SpriteFrame {
if (cachedPlayBg) return cachedPlayBg;
const W = 750;
const H = 1334;
const canvas = makeOffscreenCanvas(W, H);
const ctx: CanvasRenderingContext2D = canvas.getContext('2d');
// 1. 基底:苔藓绿手作亚麻桌垫渐变(模拟从左上方洒下的自然窗光)
const baseGrad = ctx.createRadialGradient(210, 260, 40, W * 0.52, H * 0.48, 860);
baseGrad.addColorStop(0, '#728562');
baseGrad.addColorStop(0.42, '#5c6e4f');
baseGrad.addColorStop(0.82, '#47573d');
baseGrad.addColorStop(1, '#36432e');
ctx.fillStyle = baseGrad;
ctx.fillRect(0, 0, W, H);
// 2. 亚麻细密织纹
ctx.save();
ctx.strokeStyle = 'rgba(255, 248, 226, 0.045)';
ctx.lineWidth = 1;
for (let x = 0; x < W; x += 6) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, H);
ctx.stroke();
}
ctx.strokeStyle = 'rgba(20, 28, 16, 0.05)';
for (let y = 0; y < H; y += 6) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(W, y);
ctx.stroke();
}
ctx.restore();
// 3. 左右极细原木桌沿(带来真实桌面的边界感,但绝不挤占空间)
const drawWoodTrim = (x0: number, w: number) => {
const g = ctx.createLinearGradient(x0, 0, x0 + w, 0);
g.addColorStop(0, '#6e492b');
g.addColorStop(0.5, '#8c603c');
g.addColorStop(1, '#583920');
ctx.fillStyle = g;
ctx.fillRect(x0, 0, w, H);
};
drawWoodTrim(0, 10);
drawWoodTrim(W - 10, 10);
// 4. 内侧细金线压边(刺绣桌垫滚边)
ctx.save();
ctx.strokeStyle = 'rgba(244, 224, 174, 0.24)';
ctx.lineWidth = 2;
ctx.setLineDash([8, 6]);
ctx.strokeRect(20, 20, W - 40, H - 40);
ctx.restore();
// 5. 柔和斜射日光斑(氛围层次)
ctx.save();
const sunGrad = ctx.createLinearGradient(0, 0, 560, 620);
sunGrad.addColorStop(0, 'rgba(255, 245, 212, 0.14)');
sunGrad.addColorStop(0.5, 'rgba(255, 245, 212, 0.03)');
sunGrad.addColorStop(1, 'rgba(255, 245, 212, 0)');
ctx.fillStyle = sunGrad;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(520, 0);
ctx.lineTo(750, 480);
ctx.lineTo(750, 720);
ctx.lineTo(0, 240);
ctx.closePath();
ctx.fill();
ctx.restore();
// 6. 绣绷底座大柔影(让中央木绣绷宛如真实搁在桌面上)
ctx.save();
const hoopShadow = ctx.createRadialGradient(W / 2, 654, 240, W / 2, 668, 368);
hoopShadow.addColorStop(0, 'rgba(18, 25, 14, 0.42)');
hoopShadow.addColorStop(0.72, 'rgba(18, 25, 14, 0.18)');
hoopShadow.addColorStop(1, 'rgba(18, 25, 14, 0)');
ctx.fillStyle = hoopShadow;
ctx.beginPath();
ctx.arc(W / 2, 658, 368, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
// 7. 桌面四角低调手作装饰(角落暗纹藤叶 + 右下角小木线轴剪影,绝不抢戏)
ctx.save();
ctx.strokeStyle = 'rgba(240, 224, 182, 0.14)';
ctx.lineWidth = 2;
const drawCornerLeaf = (cx: number, cy: number, sx: number, sy: number) => {
ctx.save();
ctx.translate(cx, cy);
ctx.scale(sx, sy);
ctx.beginPath();
ctx.moveTo(0, 48);
ctx.quadraticCurveTo(6, 6, 48, 0);
ctx.stroke();
ctx.beginPath();
ctx.ellipse(22, 16, 10, 4.5, -0.5, 0, Math.PI * 2);
ctx.stroke();
ctx.beginPath();
ctx.ellipse(14, 30, 9, 4, -1.0, 0, Math.PI * 2);
ctx.stroke();
ctx.restore();
};
drawCornerLeaf(32, 232, 1, 1);
drawCornerLeaf(W - 32, 232, -1, 1);
drawCornerLeaf(32, 1142, 1, -1);
drawCornerLeaf(W - 32, 1142, -1, -1);
ctx.restore();
// 8. 底部深暗脚垫渐变(托举底部木质工具盘)
const bottomGrad = ctx.createLinearGradient(0, H - 240, 0, H);
bottomGrad.addColorStop(0, 'rgba(24, 31, 19, 0)');
bottomGrad.addColorStop(1, 'rgba(22, 29, 17, 0.42)');
ctx.fillStyle = bottomGrad;
ctx.fillRect(0, H - 240, W, 240);
cachedPlayBg = canvasToSpriteFrame(canvas);
return cachedPlayBg;
}
/** 生成大厅场景全屏「温暖原木手作书案」纹理(暖橡木桌底 + 苔绿亚麻桌旗 + 阳光光晕) */
export function createLobbyDeskSpriteFrame(): SpriteFrame {
if (cachedLobbyBg) return cachedLobbyBg;
const W = 750;
const H = 1334;
const canvas = makeOffscreenCanvas(W, H);
const ctx: CanvasRenderingContext2D = canvas.getContext('2d');
// 1. 暖杏色手工木案渐变
const deskGrad = ctx.createLinearGradient(0, 0, 0, H);
deskGrad.addColorStop(0, '#627354');
deskGrad.addColorStop(0.24, '#56674a');
deskGrad.addColorStop(0.242, '#eadbc0');
deskGrad.addColorStop(0.55, '#f2e6cf');
deskGrad.addColorStop(1, '#dfd0b1');
ctx.fillStyle = deskGrad;
ctx.fillRect(0, 0, W, H);
// 2. 顶部苔绿工坊幕布区域(给游戏标题与今日绣绷展示台营造景深)
const topCloth = ctx.createRadialGradient(W * 0.35, 110, 30, W * 0.5, 190, 520);
topCloth.addColorStop(0, '#6f825e');
topCloth.addColorStop(0.55, '#546548');
topCloth.addColorStop(1, '#3f4e36');
ctx.fillStyle = topCloth;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(W, 0);
ctx.lineTo(W, 338);
ctx.quadraticCurveTo(W / 2, 372, 0, 338);
ctx.closePath();
ctx.fill();
// 3. 顶部幕布金线滚边与波浪收口
ctx.save();
ctx.strokeStyle = 'rgba(244, 221, 168, 0.55)';
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(0, 338);
ctx.quadraticCurveTo(W / 2, 372, W, 338);
ctx.stroke();
ctx.strokeStyle = 'rgba(255, 245, 218, 0.25)';
ctx.lineWidth = 1.6;
ctx.setLineDash([7, 6]);
ctx.beginPath();
ctx.moveTo(18, 326);
ctx.quadraticCurveTo(W / 2, 358, W - 18, 326);
ctx.stroke();
ctx.restore();
// 4. 下半部分亚麻纸/木纹细肌理
ctx.save();
ctx.strokeStyle = 'rgba(138, 112, 74, 0.045)';
ctx.lineWidth = 1;
for (let y = 360; y < H; y += 7) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(W, y);
ctx.stroke();
}
ctx.strokeStyle = 'rgba(255, 250, 238, 0.14)';
for (let x = 0; x < W; x += 9) {
ctx.beginPath();
ctx.moveTo(x, 360);
ctx.lineTo(x, H);
ctx.stroke();
}
ctx.restore();
// 5. 左右原木桌框边条
const drawSideWood = (x0: number, w: number) => {
const g = ctx.createLinearGradient(x0, 0, x0 + w, 0);
g.addColorStop(0, '#7c5534');
g.addColorStop(0.5, '#9d7048');
g.addColorStop(1, '#684528');
ctx.fillStyle = g;
ctx.fillRect(x0, 0, w, H);
};
drawSideWood(0, 8);
drawSideWood(W - 8, 8);
// 6. 顶部柔光粒子光晕(手作温暖感)
ctx.save();
const glow = ctx.createRadialGradient(140, 80, 10, 140, 80, 260);
glow.addColorStop(0, 'rgba(255, 244, 206, 0.18)');
glow.addColorStop(1, 'rgba(255, 244, 206, 0)');
ctx.fillStyle = glow;
ctx.fillRect(0, 0, 420, 340);
ctx.restore();
cachedLobbyBg = canvasToSpriteFrame(canvas);
return cachedLobbyBg;
}
/** 创建全屏纹理背景精灵 */
export function createBackdropSprite(name: string, frame: SpriteFrame, parent: Node): Node {
const node = createUINode(name, 750, 1334, parent);
const sp = node.addComponent(Sprite);
sp.sizeMode = Sprite.SizeMode.CUSTOM;
sp.spriteFrame = frame;
stretchToParent(node);
return node;
}
const uiSpriteCache = new Map<string, SpriteFrame>();
/** 从 assets/resources/<path> 异步加载 Meowa 生成的精绘游戏 UI 精灵(自动兼容 SpriteFrame 与 ImageAsset) */
export function loadUiSprite(resourcePath: string, sprite: Sprite): void {
const cached = uiSpriteCache.get(resourcePath);
if (cached) {
if (sprite.isValid) sprite.spriteFrame = cached;
return;
}
resources.load(`${resourcePath}/spriteFrame`, SpriteFrame, (err, sf) => {
if (!err && sf) {
uiSpriteCache.set(resourcePath, sf);
if (sprite.isValid) sprite.spriteFrame = sf;
return;
}
resources.load(resourcePath, ImageAsset, (imgErr, img) => {
if (imgErr || !img) return;
const tex = new Texture2D();
tex.image = img;
const fallbackSf = new SpriteFrame();
fallbackSf.texture = tex;
uiSpriteCache.set(resourcePath, fallbackSf);
if (sprite.isValid) sprite.spriteFrame = fallbackSf;
});
});
}
/** 创建加载 Meowa 美术贴图的精灵节点 */
export function createArtSprite(name: string, resourcePath: string, w: number, h: number, parent: Node): { node: Node; sprite: Sprite } {
const node = createUINode(name, w, h, parent);
const sprite = node.addComponent(Sprite);
sprite.sizeMode = Sprite.SizeMode.CUSTOM;
loadUiSprite(resourcePath, sprite);
return { node, sprite };
}
export interface ArtButtonSpec {
name: string;
resourcePath: string;
text?: string;
w: number;
h: number;
textColor?: string;
fontSize?: number;
textOffsetY?: number;
bold?: boolean;
onClick: () => void;
}
export interface ArtButton {
node: Node;
button: Button;
sprite: Sprite;
label?: Label;
setEnabled: (enabled: boolean) => void;
}
/** 创建基于 Meowa 手绘贴图的实体按压按钮 */
export function createArtButton(spec: ArtButtonSpec, parent: Node): ArtButton {
const { node, sprite } = createArtSprite(spec.name, spec.resourcePath, spec.w, spec.h, parent);
let label: Label | undefined;
if (spec.text !== undefined) {
label = createLabel(
'Label',
spec.text,
spec.w - 28,
spec.h - 8,
{
size: spec.fontSize ?? 26,
color: spec.textColor ?? '#3b240a',
bold: spec.bold ?? true,
overflow: Label.Overflow.SHRINK,
},
node,
);
if (spec.textOffsetY) label.node.setPosition(0, spec.textOffsetY, 0);
}
const button = node.addComponent(Button);
button.transition = Button.Transition.SCALE;
button.zoomScale = 0.92;
node.on(Button.EventType.CLICK, () => {
if (button.interactable) spec.onClick();
});
const res: ArtButton = {
node,
button,
sprite,
label,
setEnabled(enabled: boolean) {
button.interactable = enabled;
sprite.color = enabled ? hex('#ffffff') : hex('#c2b8a8');
if (res.label) {
const c = res.label.color.clone();
c.a = enabled ? 255 : 155;
res.label.color = c;
}
},
};
return res;
}
export function stretchToParent(node: Node): Widget {
const widget = node.addComponent(Widget);
widget.isAlignTop = true;
widget.isAlignBottom = true;
widget.isAlignLeft = true;
widget.isAlignRight = true;
widget.top = 0;
widget.bottom = 0;
widget.left = 0;
widget.right = 0;
widget.alignMode = Widget.AlignMode.ON_WINDOW_RESIZE;
return widget;
}
+9
View File
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "88e02ada-30d0-40d3-bed4-28c125a80104",
"files": [],
"subMetas": {},
"userData": {}
}