Files
mayi_coco/assets/scripts/ui/PlayView.ts
T

1503 lines
56 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Component, EventTouch, Graphics, Label, Node, Sprite, UITransform, Vec3, _decorator } from 'cc';
import { AtelierService } from '../core/AtelierService';
import { CHAPTERS, CHAPTER_UNLOCK_STARS, formatLength, formatShort, HOOP_HEIGHT, HOOP_WIDTH, LEVELS, NEST, YARN_COLORS } from '../core/LevelData';
import {
ANT_SPEED,
checkSegmentBlock,
createEmptyRoute,
dispatchWarning,
distance,
effectiveBudget,
findNextHint,
interpolate,
isButtonEvent,
isDeliveryEvent,
isDyeEvent,
isGateEvent,
isPickEvent,
isSpoolEvent,
passedGateIds,
planStops,
prepareRouteForRun,
scoreForLength,
segmentCost,
STITCH_TIME,
threadedButtonIds,
totalLength,
tryBacktrack,
} from '../core/RouteEngine';
import { SoundService } from '../core/SoundService';
import { StorageService } from '../core/StorageService';
import { BlockReason, GameState, LevelDef, Point2D, RouteState, TargetColor } from '../core/Types';
import { EmbroideryRenderer } from '../render/EmbroideryRenderer';
import { AtelierTab } from './AtelierModal';
import { applyCoverBackground, applySafeContentTransform, ScreenMetrics } from './ScreenAdapter';
import {
ArtButton,
createArtButton,
createArtSprite,
createAtelierTableSpriteFrame,
createBackdropSprite,
createButton,
createLabel,
createPanel,
createUINode,
drawPadlockIcon,
drawRoundedBox,
hex,
stretchToParent,
StyledButton,
} from './UiBuilder';
const { ccclass } = _decorator;
const HOOP_DISPLAY_W = 708;
const HOOP_DISPLAY_H = Math.round((HOOP_DISPLAY_W * HOOP_HEIGHT) / HOOP_WIDTH);
const RELATIVE_GAIN = 1.42;
const CHIP_STYLES: Record<TargetColor, { icon: string; dot: string; fill: string; stroke: string; text: string }> = {
gold: { icon: '✿', dot: '#d89a2c', fill: '#fbf0d4', stroke: '#d9b574', text: '#6a410b' },
green: { icon: '◈', dot: '#6e8c4c', fill: '#e8f0dd', stroke: '#9eb684', text: '#314925' },
rose: { icon: '✿', dot: '#cc6c86', fill: '#fae6ec', stroke: '#d89db0', text: '#753149' },
sky: { icon: '✦', dot: '#578ea9', fill: '#e4f1f8', stroke: '#95bcd1', text: '#284f66' },
coral: { icon: '♥', dot: '#d66e4a', fill: '#fbe9e0', stroke: '#dfa086', text: '#7d3620' },
lavender: { icon: '❀', dot: '#8c74b0', fill: '#efeaf9', stroke: '#b9a6d8', text: '#4c3a6b' },
cream: { icon: '●', dot: '#c2b294', fill: '#f6f0e3', stroke: '#cbbda2', text: '#5c4e38' },
cocoa: { icon: '◆', dot: '#8d5b3e', fill: '#f1e5d9', stroke: '#bfa085', text: '#573723' },
};
const CHAPTER_BADGE_COLORS = ['#6d8a55', '#4c7b91', '#b46a47', '#4e786c', '#9c564a', '#9c5972'];
interface DragPointer {
id: number;
relative: boolean;
nest: Point2D;
startUI: Point2D;
startPt: Point2D;
}
@ccclass('PlayView')
export class PlayView extends Component {
private storage!: StorageService;
private sound!: SoundService;
private atelier!: AtelierService;
private renderer!: EmbroideryRenderer;
private onBackLobby!: () => void;
private onOpenAtelier?: (tab: AtelierTab, chapterIndex: number, focusLevelIndex?: number) => void;
private currentIndex = 0;
private level: LevelDef = LEVELS[0];
private activeNestIndex = 0;
private targetCounts: Record<TargetColor, number> = {
gold: 0,
green: 0,
rose: 0,
sky: 0,
coral: 0,
lavender: 0,
cream: 0,
cocoa: 0,
};
private pointer: DragPointer | null = null;
private demoStart = 0;
private demoIndex = 0;
private demoPoint = 1;
private readonly state: GameState = {
time: 0,
lines: [],
drawing: null,
complete: false,
completedAt: 0,
demo: false,
assisted: false,
hintCapped: false,
demoWatched: false,
hint: null,
};
// HUD & UI 节点引用
private titleLabel!: Label;
private soundBtn!: ArtButton;
private loupeBtn!: ArtButton;
private loupeEnabled = true;
private chips: Record<TargetColor, { root: Node; bg: Graphics; dotBg: Graphics; label: Label }> = {} as any;
private dispatchNode!: Node;
private dispatchBg!: Graphics;
private dispatchLabel!: Label;
private mechanicNode!: Node;
private mechanicBg!: Graphics;
private mechanicLabel!: Label;
private mechanicLockNode!: Node;
private mechanicLockGfx!: Graphics;
private meterTitleLabel!: Label;
private meterTargetLabel!: Label;
private meterFillBg!: Graphics;
private meterStarTick!: Node;
private meterTwoStarTick!: Node;
private statusLabel!: Label;
private tutorialOverlay!: Node;
private tutorialTextLabel!: Label;
private tutorialBtn!: StyledButton;
private stageNode!: Node;
private stageTransform!: UITransform;
private hoopShadowNode!: Node;
private hoopNode!: Node;
private hoopTransform!: UITransform;
private dragSurfaceNode!: Node;
private topBarNode!: Node;
private missionRowNode!: Node;
private whisperRibbonNode!: Node;
private resultFrameNode!: Node;
private relativeAnchorNode!: Node;
private relativeThumbNode!: Node;
private hintBtn!: ArtButton;
private hintHalo!: Node;
private demoBtn!: ArtButton;
private undoBtn!: ArtButton;
private restartBtn!: ArtButton;
private dockTrayNode!: Node;
private resultOverlay!: Node;
private resultStarsLabel!: Label;
private resultTitleLabel!: Label;
private resultLengthLabel!: Label;
private nextBtn!: ArtButton;
private saveBtn!: StyledButton;
private againBtn!: StyledButton;
private atelierShortcutBtn!: StyledButton;
private lobbyBtn!: StyledButton;
private bgArtNode!: Node;
private safeRoot!: Node;
private safeContentScale = 1;
public init(
storage: StorageService,
sound: SoundService,
atelier: AtelierService,
renderer: EmbroideryRenderer,
onBackLobby: () => void,
onOpenAtelier?: (tab: AtelierTab, chapterIndex: number, focusLevelIndex?: number) => void,
): void {
this.storage = storage;
this.sound = sound;
this.atelier = atelier;
this.renderer = renderer;
this.onBackLobby = onBackLobby;
this.onOpenAtelier = onOpenAtelier;
this.loupeEnabled = storage.readLoupeEnabled();
this.buildUI();
}
private buildUI(): void {
stretchToParent(this.node);
// 0. 宽屏/超长屏外延暗木桌底(确保 iPad / 全面屏 / 桌面预览四周无白边或米色网页留白)
createPanel('OuterDeskSurround', 3200, 3200, { fill: '#2c382c', radius: 0 }, this.node);
// 1. 底层兜底 + Meowa 精绘「阳光刺绣工坊桌面」(按屏占比 Cover 铺满,消除全面屏黑边)
createBackdropSprite('AtelierTableFallback', createAtelierTableSpriteFrame(), this.node);
const bgArt = createArtSprite('MeowaPlayBg', 'ui/bg_play_atelier', 750, 1334, this.node);
this.bgArtNode = bgArt.node;
// 安全区主内容容器(自动避让微信右上角胶囊、灵动岛与底部 Home 手势条)
this.safeRoot = createUINode('PlaySafeRoot', 750, 1334, this.node);
// 2. 全桌交互舞台层(触控热区 + 绣绷桌面柔影 + 中央大绣绷 + 隐形遥控指示环)
this.stageNode = createUINode('StageLayer', 750, 1334, this.safeRoot);
this.stageTransform = this.stageNode.getComponent(UITransform)!;
// 触控层覆盖中央桌面(位于顶部 HUD、底部木托盘与结算浮层之下,绝不拦截按钮)
this.dragSurfaceNode = createUINode('DragSurface', 740, 940, this.stageNode);
this.dragSurfaceNode.setPosition(0, 12, 0);
// 绣绷落在亚麻桌垫上的真实地面柔影
const hoopShadow = createPanel('HoopTableShadow', 636, 636, {
fill: '#1b261a44', radius: 318,
}, this.stageNode);
hoopShadow.node.setPosition(4, 2, 0);
this.hoopShadowNode = hoopShadow.node;
// 中央主角大绣绷(直接落在 sunlit 桌面上)
this.hoopNode = createUINode('HoopSprite', HOOP_DISPLAY_W, HOOP_DISPLAY_H, this.stageNode);
this.hoopNode.setPosition(0, -24, 0);
this.hoopTransform = this.hoopNode.getComponent(UITransform)!;
const hoopSprite = this.hoopNode.addComponent(Sprite);
hoopSprite.sizeMode = Sprite.SizeMode.CUSTOM;
hoopSprite.spriteFrame = this.renderer.getSpriteFrame();
// 隐形相对滑动轻提示环(松手即隐)
const relAnchor = createPanel('RelativeAnchor', 58, 58, {
fill: '#f7e7c426', stroke: '#fff7e082', strokeWidth: 2, radius: 29,
}, this.stageNode);
createPanel('RelativeAnchorDot', 10, 10, { fill: '#fff8e3aa', radius: 5 }, relAnchor.node);
this.relativeAnchorNode = relAnchor.node;
this.relativeAnchorNode.active = false;
const relThumb = createPanel('RelativeThumb', 40, 40, {
fill: '#f7e7c448', stroke: '#fff8e2d4', strokeWidth: 2.5, radius: 20,
}, this.stageNode);
this.relativeThumbNode = relThumb.node;
this.relativeThumbNode.active = false;
// 3. 顶部浮空 Meowa 雕花实木 HUD(木质圆首页钮 + 樱桃木雕花关卡铭牌 + 放大镜/音效双木圆钮)
const topBar = createUINode('TopGameBar', 720, 110, this.safeRoot);
topBar.setPosition(0, 611, 0);
this.topBarNode = topBar;
const homeBtn = createArtButton({
name: 'HomeBtn',
resourcePath: 'ui/ui_wood_round',
text: '⌂',
w: 64,
h: 64,
textColor: '#fff5d8',
fontSize: 31,
textOffsetY: 5,
onClick: () => {
this.cancelDrag(false);
this.onBackLobby();
},
}, topBar);
homeBtn.node.setPosition(-318, 2, 0);
// Meowa 樱桃木铜钉雕花关卡铭牌(编号与关名整体严格居中于左右雕花之间)
const plaque = createArtSprite('StagePlaque', 'ui/ui_wood_plaque', 404, 108, topBar);
plaque.node.setPosition(-26, 2, 0);
this.titleLabel = createLabel('LevelTitle', '01 金色向日葵', 274, 44, {
size: 27, color: '#fff6de', bold: true, align: Label.HorizontalAlign.CENTER, overflow: Label.Overflow.SHRINK,
}, plaque.node);
this.titleLabel.node.setPosition(0, 1, 0);
// 放大镜与音效双雕花木圆钮
this.loupeBtn = createArtButton({
name: 'LoupeToggleBtn',
resourcePath: 'ui/ui_wood_round',
text: '镜',
w: 60,
h: 60,
textColor: '#ffe79e',
fontSize: 22,
onClick: () => {
this.sound.unlock();
this.loupeEnabled = !this.loupeEnabled;
this.storage.saveLoupeEnabled(this.loupeEnabled);
if (this.state.drawing) this.state.drawing.loupeEnabled = this.loupeEnabled;
this.syncLoupeButton();
this.setStatus(this.loupeEnabled ? '已开启拖动放大镜(自动避让手指)。' : '已关闭放大镜,当前为纯净拖线视角。');
},
}, topBar);
this.loupeBtn.node.setPosition(244, 2, 0);
this.syncLoupeButton();
this.soundBtn = createArtButton({
name: 'SoundBtn',
resourcePath: 'ui/ui_wood_round',
text: '♪',
w: 60,
h: 60,
textColor: '#fff5d8',
fontSize: 27,
onClick: () => {
this.sound.toggle();
this.syncSoundButton();
},
}, topBar);
this.soundBtn.node.setPosition(316, 2, 0);
// 4. 第二行:统一胡桃木铜边材质的任务色球徽章 + 用线星级量尺
const missionRow = createUINode('MissionStrip', 706, 56, this.safeRoot);
missionRow.setPosition(0, 523, 0);
this.missionRowNode = missionRow;
YARN_COLORS.forEach(color => {
const st = CHIP_STYLES[color];
const chip = createPanel(`Chip_${color}`, 84, 40, {
fill: '#3c2615e8',
stroke: '#cca15a',
strokeWidth: 1.8,
radius: 20,
depth: 3,
depthColor: '#221409',
shadow: 2,
highlight: '#ffe8b82e',
}, missionRow);
const dot = createPanel('YarnDot', 16, 16, {
fill: st.dot, stroke: '#fff5d8cc', strokeWidth: 1.6, radius: 8,
}, chip.node);
dot.node.setPosition(-23, 0, 0);
const label = createLabel('Text', '0/1', 46, 32, {
size: 17, color: '#fff5dc', bold: true, align: Label.HorizontalAlign.CENTER, overflow: Label.Overflow.SHRINK,
}, chip.node);
label.node.setPosition(11, 0, 0);
this.chips[color] = { root: chip.node, bg: chip.graphics, dotBg: dot.graphics, label };
});
const disp = createPanel('DispatchPill', 84, 40, {
fill: '#3c2615e8', stroke: '#d4aa60', strokeWidth: 1.8, radius: 20, depth: 3, depthColor: '#221409', shadow: 2, highlight: '#ffe8b82e',
}, missionRow);
this.dispatchNode = disp.node;
this.dispatchBg = disp.graphics;
this.dispatchLabel = createLabel('Text', '剩2笔', 76, 32, {
size: 16, color: '#ffe8a3', bold: true, overflow: Label.Overflow.SHRINK,
}, disp.node);
const mech = createPanel('MechanicPill', 86, 40, {
fill: '#5c2d23eb', stroke: '#dfa086', strokeWidth: 1.8, radius: 20, depth: 3, depthColor: '#361710', shadow: 2, highlight: '#ffe8b82e',
}, missionRow);
this.mechanicNode = mech.node;
this.mechanicBg = mech.graphics;
this.mechanicLockNode = createUINode('MechanicLockIcon', 18, 18, mech.node);
this.mechanicLockNode.setPosition(-21, 0, 0);
this.mechanicLockGfx = this.mechanicLockNode.addComponent(Graphics);
drawPadlockIcon(this.mechanicLockGfx, 0.88, '#f0cc7a', '#fff0c4', '#402712');
this.mechanicLockNode.active = false;
this.mechanicLabel = createLabel('Text', '不交叉', 78, 32, {
size: 16, color: '#ffebd8', bold: true, overflow: Label.Overflow.SHRINK,
}, mech.node);
// 同材质胡桃木铜边用线星级量尺(内部上下留白舒朗,右边缘严格对齐桌框内侧)
const meter = createPanel('YarnMeter', 252, 52, {
fill: '#3c2615eb',
stroke: '#d4ab62',
strokeWidth: 2,
radius: 17,
depth: 4,
depthColor: '#221409',
shadow: 3,
highlight: '#ffe8b832',
}, missionRow);
meter.node.setPosition(218, 0, 0);
this.meterTitleLabel = createLabel('Used', '用线 0.0 / 9.0', 148, 22, {
size: 16, color: '#fff6df', bold: true, align: Label.HorizontalAlign.LEFT, overflow: Label.Overflow.SHRINK,
}, meter.node);
this.meterTitleLabel.node.setPosition(-38, 10, 0);
this.meterTargetLabel = createLabel('Target', '★★★', 76, 22, {
size: 17, color: '#ffd966', bold: true, align: Label.HorizontalAlign.RIGHT, overflow: Label.Overflow.SHRINK,
}, meter.node);
this.meterTargetLabel.node.setPosition(74, 10, 0);
const track = createPanel('TrackBg', 220, 9, { fill: '#22140a', stroke: '#745630', strokeWidth: 1.2, radius: 4.5 }, meter.node);
track.node.setPosition(0, -11, 0);
const fillNode = createUINode('TrackFill', 220, 9, track.node);
this.meterFillBg = fillNode.addComponent(Graphics);
// 三星金标 & 二星暖标分界刻度
const starTick = createPanel('StarTick', 4, 14, { fill: '#ffd863', radius: 2 }, track.node);
this.meterStarTick = starTick.node;
this.meterStarTick.active = false;
const twoTick = createPanel('TwoStarTick', 3, 11, { fill: '#e8a656cc', radius: 1.5 }, track.node);
this.meterTwoStarTick = twoTick.node;
this.meterTwoStarTick.active = false;
// 5. 绣绷上方轻纱耳语提示条(半透明墨绿绸带,不占实体排版块)
const toastBar = createPanel('WhisperRibbon', 636, 40, {
fill: '#232d1cb8',
stroke: '#e3cd9555',
strokeWidth: 1.5,
radius: 20,
}, this.safeRoot);
toastBar.node.setPosition(0, 455, 0);
this.whisperRibbonNode = toastBar.node;
this.statusLabel = createLabel('Status', '按住蚁巢拖线,或在桌面空白处滑动遥控。', 606, 34, {
size: 19, color: '#fff6de', overflow: Label.Overflow.SHRINK,
}, toastBar.node);
// 6. 底部 Meowa 樱桃木雕花针线盒托盘 + 4 枚同材质雕花实木铜边工具钮
const dockTray = createUINode('WoodToolDock', 724, 152, this.safeRoot);
dockTray.setPosition(0, -583, 0);
this.dockTrayNode = dockTray;
// 柔和桌面落影
const dockShadow = createPanel('DockShadow', 694, 88, { fill: '#1a110966', radius: 24 }, dockTray);
dockShadow.node.setPosition(0, -24, 0);
// Meowa 手绘雕花木槽托盘
const dockArt = createArtSprite('MeowaWoodDock', 'ui/ui_wood_dock', 724, 118, dockTray);
dockArt.node.setPosition(0, -18, 0);
const makeWoodTool = (name: string, resPath: string, title: string, x: number, onClick: () => void): ArtButton => {
const btn = createArtButton({
name,
resourcePath: resPath,
w: 94,
h: 94,
onClick,
}, dockTray);
btn.node.setPosition(x, 12, 0);
const pill = createPanel('TagPill', 88, 28, {
fill: '#fbf1d9f5', stroke: '#c6984d', strokeWidth: 1.8, radius: 14,
}, btn.node);
pill.node.setPosition(0, -49, 0);
const lbl = createLabel('Label', title, 82, 26, {
size: 16, color: '#452b12', bold: true, overflow: Label.Overflow.SHRINK,
}, pill.node);
btn.label = lbl;
return btn;
};
const hintHalo = createPanel('HintActiveHalo', 106, 106, {
fill: '#ffde7d33', stroke: '#ffd966', strokeWidth: 3.5, radius: 26,
}, dockTray);
hintHalo.node.setPosition(-219, 12, 0);
hintHalo.node.active = false;
this.hintHalo = hintHalo.node;
this.hintBtn = makeWoodTool('HintBtn', 'ui/btn_dock_hint', '提示', -219, () => {
this.sound.unlock();
this.toggleHint();
});
this.demoBtn = makeWoodTool('DemoBtn', 'ui/btn_dock_demo', '演示', -73, () => {
this.sound.unlock();
this.startDemo();
});
this.undoBtn = makeWoodTool('UndoBtn', 'ui/btn_dock_undo', '撤销', 73, () => {
this.sound.unlock();
this.undoLastLine();
});
this.restartBtn = makeWoodTool('RestartBtn', 'ui/btn_dock_restart', '重来', 219, () => {
this.sound.unlock();
this.resetLevel();
});
// 7. Meowa 雕花木框手缝亚麻通关庆典弹板(上方留出完整绣绷展示)
const overlayScrim = createPanel('ResultOverlay', 3200, 3200, {
fill: '#161f1466', radius: 0,
}, this.safeRoot);
this.resultOverlay = overlayScrim.node;
const resultFrame = createArtSprite('ResultLinenModal', 'ui/ui_linen_modal', 626, 514, overlayScrim.node);
resultFrame.node.setPosition(0, -381, 0);
this.resultFrameNode = resultFrame.node;
this.resultStarsLabel = createLabel('Stars', '★★★', 300, 56, {
size: 46, color: '#d88c1a', bold: true,
}, resultFrame.node);
this.resultStarsLabel.node.setPosition(0, 102, 0);
this.resultTitleLabel = createLabel('Done', '绣成佳作!', 420, 44, {
size: 32, color: '#3b2814', bold: true,
}, resultFrame.node);
this.resultTitleLabel.node.setPosition(0, 48, 0);
const statPill = createPanel('StatPill', 434, 36, {
fill: '#e8d7b3', stroke: '#cfb482', strokeWidth: 1.4, radius: 18,
}, resultFrame.node);
statPill.node.setPosition(0, 0, 0);
this.resultLengthLabel = createLabel('Len', '用线 3.4 cm', 414, 30, {
size: 19, color: '#5b4528', bold: true, overflow: Label.Overflow.SHRINK,
}, statPill.node);
// 第一排:Meowa 蜜糖金大按钮(下一关)+ 翠绿立体钮(保存绣画)
this.nextBtn = createArtButton({
name: 'NextBtn',
resourcePath: 'ui/ui_gold_btn',
text: '下一关',
w: 248,
h: 82,
textColor: '#452408',
fontSize: 27,
textOffsetY: 2,
onClick: () => {
this.sound.unlock();
const gate = this.getNextChapterGate();
if (this.currentIndex + 1 < LEVELS.length && !gate.locked) {
this.loadLevel(this.currentIndex + 1);
} else {
this.onBackLobby();
}
},
}, resultFrame.node);
this.nextBtn.node.setPosition(-126, -72, 0);
this.saveBtn = createButton({
name: 'SaveBtn',
text: '保存绣画',
w: 234,
h: 66,
radius: 26,
fill: '#4d7247',
stroke: '#8ab082',
depth: 6,
depthColor: '#2d4729',
shadow: 4,
textColor: '#fff9e8',
fontSize: 25,
onClick: () => {
const rawStars = scoreForLength(this.level, totalLength(this.state.lines));
const cappedStars = this.state.hintCapped ? Math.min(2, rawStars) : rawStars;
const chapterName = CHAPTERS[this.level.chapter]?.name ?? '蚂蚁织画';
const en = this.storage.readLanguage() === 'en';
const quoteDef = this.atelier.getQuoteDef();
this.renderer.exportArtwork(
this.state,
{
stars: cappedStars,
lengthText: formatLength(totalLength(this.state.lines)),
chapterName,
levelNumber: this.currentIndex + 1,
frame: this.atelier.getFrameDef(),
quoteText: en ? quoteDef.en : quoteDef.zh,
},
msg => this.setStatus(msg),
);
},
}, resultFrame.node);
this.saveBtn.node.setPosition(128, -70, 0);
// 第二排:次级轻按钮(重绣本关 + 直达展柜/读回信 + 返回大厅)
this.againBtn = createButton({
name: 'AgainBtn',
text: '重绣本关',
w: 150,
h: 46,
radius: 18,
fill: '#ead9b6',
stroke: '#cfb588',
depth: 4,
depthColor: '#ae9468',
shadow: 2,
textColor: '#4f3d24',
fontSize: 18,
onClick: () => {
this.sound.unlock();
this.resetLevel();
},
}, resultFrame.node);
this.againBtn.node.setPosition(-166, -150, 0);
this.atelierShortcutBtn = createButton({
name: 'ResultAtelierBtn',
text: '进绣品展柜',
w: 168,
h: 46,
radius: 18,
fill: '#f6e1b2',
stroke: '#d6a44e',
depth: 4,
depthColor: '#b5832e',
shadow: 2,
textColor: '#56310a',
fontSize: 18,
onClick: () => {
this.sound.unlock();
if (!this.onOpenAtelier) {
this.onBackLobby();
return;
}
const openReply = this.currentIndex === 0 && !this.state.assisted;
this.onOpenAtelier(openReply ? 'letters' : 'gallery', this.level.chapter, this.currentIndex);
},
}, resultFrame.node);
this.atelierShortcutBtn.node.setPosition(0, -150, 0);
this.lobbyBtn = createButton({
name: 'LobbyBtn',
text: '返回大厅',
w: 150,
h: 46,
radius: 18,
fill: '#ead9b6',
stroke: '#cfb588',
depth: 4,
depthColor: '#ae9468',
shadow: 2,
textColor: '#4f3d24',
fontSize: 18,
onClick: () => this.onBackLobby(),
}, resultFrame.node);
this.lobbyBtn.node.setPosition(166, -150, 0);
this.resultOverlay.active = false;
// 8. 第 1 关首次进入轻遮罩起手教学浮卡(置于绣绷上方不挡蚁巢,点按钮或直接拖线均可立即开始)
const tutBanner = createPanel('FirstRunTutorial', 610, 142, {
fill: '#3c2614f0',
stroke: '#e3b868',
strokeWidth: 2.5,
radius: 24,
depth: 5,
depthColor: '#221409',
shadow: 8,
rivets: true,
rivetColor: '#e2ba6d',
}, this.safeRoot);
tutBanner.node.setPosition(0, 326, 0);
this.tutorialOverlay = tutBanner.node;
this.tutorialTextLabel = createLabel(
'TutText',
'跟着小蚂蚁画这条线!\n按住下方「蚁巢」拖过毛线球送进花瓣,用线越短星越多 ★',
422,
106,
{ size: 19, lineHeight: 28, color: '#fff6de', bold: true, align: Label.HorizontalAlign.LEFT, overflow: Label.Overflow.SHRINK },
tutBanner.node,
);
this.tutorialTextLabel.node.setPosition(-68, 0, 0);
this.tutorialBtn = createButton({
name: 'TutDismissBtn',
text: '知道了',
w: 118,
h: 48,
radius: 20,
fill: '#e6a840',
stroke: '#f8d284',
depth: 4,
depthColor: '#a26a18',
textColor: '#3b2207',
fontSize: 19,
onClick: () => {
this.dismissTutorial();
},
}, tutBanner.node);
this.tutorialBtn.node.setPosition(218, 0, 0);
this.tutorialOverlay.active = false;
// 绑定整块桌面触控事件
this.dragSurfaceNode.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
this.dragSurfaceNode.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
this.dragSurfaceNode.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
this.dragSurfaceNode.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
}
public applyScreenMetrics(m: ScreenMetrics): void {
this.safeContentScale = Math.max(0.5, m.contentScale);
if (this.bgArtNode) applyCoverBackground(this.bgArtNode, m);
if (this.safeRoot) applySafeContentTransform(this.safeRoot, m);
if (!this.topBarNode) return;
// 全面屏动态贴顶/贴底锚定并拉宽 HUD 与绣绷上下呼吸感,消除大块死空白
const h = m.safeHalfH;
const e = m.extraH;
const topBarY = h - 56;
const missionY = topBarY - 88 - e * 0.08;
const ribbonY = missionY - 68 - e * 0.08;
const dockY = -h + 84;
const hoopY = ((ribbonY - 20) + (dockY + 76)) / 2 + 8;
this.topBarNode.setPosition(0, topBarY, 0);
this.missionRowNode.setPosition(0, missionY, 0);
this.whisperRibbonNode.setPosition(0, ribbonY, 0);
this.dockTrayNode.setPosition(0, dockY, 0);
this.hoopNode.setPosition(0, hoopY, 0);
this.hoopShadowNode.setPosition(4, hoopY - 22, 0);
this.dragSurfaceNode.setPosition(0, hoopY - 10, 0);
this.resultFrameNode.setPosition(0, -h + 286, 0);
this.tutorialOverlay.setPosition(0, ribbonY - 94, 0);
}
private syncLoupeButton(): void {
if (this.loupeBtn.label) {
this.loupeBtn.label.string = this.loupeEnabled ? '镜' : '关';
this.loupeBtn.label.color = hex(this.loupeEnabled ? '#ffe79e' : '#b7aa96');
}
this.loupeBtn.sprite.color = hex(this.loupeEnabled ? '#ffffff' : '#b5aa9c');
}
private touchToHoop(event: EventTouch): Point2D {
const uiLoc = event.getUILocation();
const local = this.hoopTransform.convertToNodeSpaceAR(new Vec3(uiLoc.x, uiLoc.y, 0));
return {
x: (local.x / HOOP_DISPLAY_W + 0.5) * HOOP_WIDTH,
y: (0.5 - local.y / HOOP_DISPLAY_H) * HOOP_HEIGHT,
};
}
private updateRelativeIndicator(uiLoc: Point2D, isStart: boolean): void {
const local = this.stageTransform.convertToNodeSpaceAR(new Vec3(uiLoc.x, uiLoc.y, 0));
const clampedX = Math.max(-342, Math.min(342, local.x));
const clampedY = Math.max(-455, Math.min(420, local.y));
if (isStart) {
this.relativeAnchorNode.setPosition(clampedX, clampedY, 0);
this.relativeAnchorNode.active = true;
}
this.relativeThumbNode.setPosition(clampedX, clampedY, 0);
this.relativeThumbNode.active = true;
}
private hideRelativeIndicator(): void {
this.relativeAnchorNode.active = false;
this.relativeThumbNode.active = false;
}
private dragPoint(event: EventTouch): Point2D {
if (!this.pointer) return this.touchToHoop(event);
if (this.pointer.relative) {
const uiLoc = event.getUILocation();
this.updateRelativeIndicator(uiLoc, false);
const scaleInv = 1 / this.safeContentScale;
const dx = (uiLoc.x - this.pointer.startUI.x) * scaleInv * (HOOP_WIDTH / HOOP_DISPLAY_W) * RELATIVE_GAIN;
const dy = -(uiLoc.y - this.pointer.startUI.y) * scaleInv * (HOOP_HEIGHT / HOOP_DISPLAY_H) * RELATIVE_GAIN;
if (this.state.drawing) this.state.drawing.fingerTip = null;
return { x: this.pointer.nest.x + dx, y: this.pointer.nest.y + dy };
}
// 直拖蚁巢保持 1:1 跟手(配合顶部自动避让放大镜看清落针点,避免线条突然上漂 96px 导致与引导线/顶巢操作割裂)
const pt = this.touchToHoop(event);
if (this.state.drawing) this.state.drawing.fingerTip = null;
return pt;
}
private onTouchStart(event: EventTouch): void {
this.sound.unlock();
if (this.tutorialOverlay.active) this.dismissTutorial();
if (this.state.complete || this.state.demo || this.pointer !== null) return;
const warn = dispatchWarning(this.level, this.state.lines);
if (warn) {
this.setStatus(warn);
this.sound.block();
return;
}
if (this.level.maxDispatches && this.state.lines.length >= this.level.maxDispatches) {
this.setStatus(`${this.level.maxDispatches} 笔都已出发,等蚂蚁送达。`);
return;
}
const uiLoc = event.getUILocation();
const pt = this.touchToHoop(event);
// 多蚁巢:找出距离落指最近的蚁巢;72px 内视为直拖该蚁巢,范围外则隐形遥控最近蚁巢
let bestNestIdx = 0;
let bestDist = Infinity;
this.level.nests.forEach((n, idx) => {
const d = distance(pt, n);
if (d < bestDist) {
bestDist = d;
bestNestIdx = idx;
}
});
const chosenNest = this.level.nests[bestNestIdx] ?? NEST;
this.activeNestIndex = bestNestIdx;
const relative = bestDist > 96;
this.pointer = {
id: event.getID(),
relative,
nest: { ...chosenNest },
startUI: { x: uiLoc.x, y: uiLoc.y },
startPt: pt,
};
const route = createEmptyRoute(true, chosenNest);
route.loupeEnabled = this.loupeEnabled;
this.state.drawing = route;
if (relative) this.updateRelativeIndicator(uiLoc, true);
this.setStatus(relative ? '隐形遥控中:滑动穿过毛线球,往回可回撤。' : '穿过毛线球,蚂蚁会把它带走。');
this.updateHud();
}
private onTouchMove(event: EventTouch): void {
if (!this.pointer || event.getID() !== this.pointer.id) return;
this.appendPoint(this.dragPoint(event), false);
}
private onTouchEnd(event: EventTouch): void {
if (!this.pointer || event.getID() !== this.pointer.id) return;
this.appendPoint(this.dragPoint(event), false);
this.pointer = null;
this.hideRelativeIndicator();
this.submitDrawing();
}
private onTouchCancel(event: EventTouch): void {
if (!this.pointer || event.getID() !== this.pointer.id) return;
this.cancelDrag(true);
}
public cancelDrag(showMessage = true): void {
if (!this.pointer) return;
this.pointer = null;
this.state.drawing = null;
this.hideRelativeIndicator();
if (showMessage) this.setStatus('这笔已收回,可以再画一次。');
this.updateHud();
}
public syncSoundButton(): void {
const on = this.sound.isEnabled();
if (this.soundBtn.label) {
this.soundBtn.label.string = on ? '♪' : '✕';
this.soundBtn.label.color = hex(on ? '#fff5d8' : '#b7aa96');
}
this.soundBtn.sprite.color = hex(on ? '#ffffff' : '#b5aa9c');
}
public loadLevel(index: number): void {
this.currentIndex = index;
this.level = LEVELS[index];
this.targetCounts = {
gold: 0,
green: 0,
rose: 0,
sky: 0,
coral: 0,
lavender: 0,
cream: 0,
cocoa: 0,
};
for (const color of YARN_COLORS) {
this.targetCounts[color] = this.level.targets.filter(t => t.color === color).length;
}
this.renderer.selectLevel(this.level);
const numStr = index + 1 < 10 ? '0' + (index + 1) : String(index + 1);
this.titleLabel.string = `${numStr} ${this.level.name}`;
if (this.nextBtn.label) this.nextBtn.label.string = index + 1 < LEVELS.length ? '下一关' : '返回大厅';
this.layoutTopChips();
this.syncSoundButton();
this.syncLanguageChrome();
this.state.demoWatched = false;
this.resetLevel();
if (index === 0 && !this.storage.hasSeenTutorial()) {
this.tutorialOverlay.active = true;
} else {
this.tutorialOverlay.active = false;
}
}
private dismissTutorial(): void {
this.tutorialOverlay.active = false;
this.storage.markTutorialSeen();
}
private syncLanguageChrome(): void {
const en = this.storage.readLanguage() === 'en';
if (this.demoBtn.label) this.demoBtn.label.string = en ? 'Demo' : '演示';
if (this.undoBtn.label) this.undoBtn.label.string = en ? 'Undo' : '撤销';
if (this.restartBtn.label) this.restartBtn.label.string = en ? 'Reset' : '重来';
this.saveBtn.label.string = en ? 'Save Art' : '保存绣画';
this.againBtn.label.string = en ? 'Replay' : '重绣本关';
this.lobbyBtn.label.string = en ? 'Home' : '返回大厅';
this.tutorialBtn.label.string = en ? 'Got it' : '知道了';
this.tutorialTextLabel.string = en
? 'Grandma Lin’s Request: Stitch a sunny sunflower!\nDrag from the pulsing Nest through the Yarn into the flower ★'
: '林阿婆委托:替窗台绣一朵永不低头的向日葵!\n按住下方「蚁巢」拖过黄球送进花心,即可显影成画 ★';
}
private layoutTopChips(): void {
let cursorX = -302;
for (const color of YARN_COLORS) {
const active = this.targetCounts[color] > 0;
this.chips[color].root.active = active;
if (active) {
this.chips[color].root.setPosition(cursorX, 0, 0);
cursorX += 90;
}
}
this.dispatchNode.active = Boolean(this.level.maxDispatches);
if (this.level.maxDispatches) {
this.dispatchNode.setPosition(cursorX, 0, 0);
cursorX += 90;
}
const hasMech =
this.level.buttons.length > 0 ||
this.level.gates.length > 0 ||
Boolean(this.level.locks && Object.keys(this.level.locks).length > 0) ||
Boolean(this.level.noCross);
this.mechanicNode.active = hasMech && cursorX <= 46;
if (this.mechanicNode.active) {
this.mechanicNode.setPosition(cursorX + 2, 0, 0);
}
}
private resetLevel(): void {
this.state.lines = [];
this.state.drawing = null;
this.state.complete = false;
this.state.demo = false;
this.state.assisted = false;
this.state.hintCapped = this.state.demoWatched;
this.state.hint = null;
this.pointer = null;
this.activeNestIndex = 0;
this.hideRelativeIndicator();
this.setStatus(
this.state.demoWatched
? '已看过本关演示(本局最高 2 ★,换关后可重新挑战三星)。'
: this.level.goal,
);
this.updateHud();
this.renderer.renderFrame(this.state, this.activeNestIndex);
}
private toggleHint(): void {
if (this.state.demo || this.state.complete) return;
const curTier = this.state.hint?.tier ?? 0;
if (curTier >= 3) {
this.state.hint = null;
this.setStatus(
this.state.demoWatched
? '已看过本关演示(本局最高 2 ★,换关后可重新挑战三星)。'
: this.level.goal,
);
} else {
const nextTier = (curTier + 1) as 1 | 2 | 3;
this.state.hint = findNextHint(this.level, this.state.lines, nextTier);
if (nextTier >= 2) this.state.hintCapped = true;
const tipMsg =
nextTier === 1
? '提示 1/3:已标出起手毛线球与目标方向(不扣星,再点看半程)。'
: nextTier === 2
? '提示 2/3:已显示前半程路线(使用路线提示本局最高 2 星)。'
: '提示 3/3:已显示本笔完整路线(使用路线提示本局最高 2 星)。';
this.setStatus(tipMsg);
}
this.updateHud();
}
private startDemo(): void {
this.state.demoWatched = true;
this.resetLevel();
this.state.demo = true;
this.state.assisted = true;
this.state.hintCapped = true;
this.demoIndex = 0;
this.demoPoint = 1;
this.demoStart = this.state.time;
const firstPath = this.level.demo[0];
const startNest = firstPath && firstPath.length > 0 ? { x: firstPath[0][0], y: firstPath[0][1] } : (this.level.nests[0] ?? NEST);
this.state.drawing = createEmptyRoute(false, startNest);
this.updateHud();
}
private undoLastLine(): void {
if (!this.state.lines.length || this.state.complete || this.state.demo) return;
this.state.lines.pop();
if (!this.state.lines.length) this.state.assisted = false;
this.sound.undo();
this.setStatus(dispatchWarning(this.level, this.state.lines) || '毛线已收回,可以重新铺这一笔。');
this.updateHud();
}
private setStatus(msg: string): void {
if (this.statusLabel.string !== msg) this.statusLabel.string = msg;
}
private updateDrawingStatus(route: RouteState): void {
const picked = route.picks.length;
const marked = route.deliveries.length;
if (route.color === 'white' && picked > 0) {
this.setStatus('白球需先经过染缸染色,才能落针!');
return;
}
if (picked === 2 && marked === 1) {
const hasOverride = this.level.dyes.some(d => d.override);
this.setStatus(
hasOverride
? '已标记 1/2,可继续送同色针位,或过「覆染」缸半途变色!'
: '已标记 1/2,继续拖向另一个同色针位。',
);
} else if (picked === 2 && marked === 0) this.setStatus('已串两颗球,依次经过两个同色针位。');
else if (marked === 2) this.setStatus('已标记 2/2,松手出发。');
else if (marked && this.level.maxDispatches) this.setStatus('已标记一处,松手会用掉一次出发。');
else if (marked) this.setStatus('已标记针位,松手即可出发。');
else if (picked) this.setStatus('拖过一个同色针位,标记送达位置。');
else this.setStatus('穿过毛线球,蚂蚁会把它带走。');
}
private appendPoint(point: Point2D, isDemo: boolean): void {
const route = this.state.drawing;
if (!route) return;
if (!isDemo && tryBacktrack(route, point)) {
route.blocked = null;
this.updateDrawingStatus(route);
this.updateHud();
}
const startTip = route.points[route.points.length - 1];
const totalDist = distance(point, startTip);
if (totalDist < (isDemo ? 2 : 5)) return;
const subSteps = isDemo ? 1 : Math.max(1, Math.ceil(totalDist / 14));
let specialMsg: string | null = null;
for (let s = 1; s <= subSteps; s++) {
const subPt = subSteps === 1 ? point : interpolate(startTip, point, s / subSteps);
const prev = route.points[route.points.length - 1];
const segLen = distance(subPt, prev);
if (segLen < (isDemo ? 2 : 3)) continue;
const blocked = checkSegmentBlock(this.level, this.state.lines, route, prev, subPt, segLen);
if (blocked) {
route.blocked = blocked;
const msgMap: Record<BlockReason, string> = {
pond: '这里有水,往回退绕开或先绣片搭桥。',
rim: '已到绣布边缘,往回拖即可继续。',
budget: '已达剩余线量上限,可回拖缩短或绕开粗布。',
cross: '本关毛线不可交叉,往回退绕开已铺线路。',
gate: '请顺着穿针眼的箭头方向穿过。',
ball: '异色毛线球挡住了去路,需绕行或先搬走它!',
};
this.setStatus(msgMap[blocked]);
if (!isDemo) this.sound.block();
this.updateHud();
return;
}
route.blocked = null;
route.points.push(subPt);
const startLen = route.len;
const costAdd = segmentCost(this.level, prev, subPt, segLen);
route.len += segLen;
route.cost += costAdd;
route.cum.push(route.len);
route.costCum.push(route.cost);
planStops(this.level, this.state.lines, route, prev, subPt, startLen, segLen, {
onPick: c => { if (!isDemo) this.sound.pick(c); },
onMark: c => { if (!isDemo) this.sound.mark(c); },
onLocked: () => {
if (!isDemo) this.sound.block();
specialMsg = '此针位已上锁,需先绣完相连的前置针位!';
},
onSpool: bonus => {
if (!isDemo) this.sound.bonus();
specialMsg = `捡到线轴,毛线上限 +${formatLength(bonus)}!`;
},
onButton: () => {
if (!isDemo) this.sound.button();
specialMsg = '已穿过纽扣锚点!';
},
onDye: color => {
if (!isDemo) this.sound.dye();
const names: Record<TargetColor, string> = {
gold: '金色',
green: '松绿色',
rose: '樱粉色',
sky: '青瓷蓝',
coral: '珊瑚橘',
lavender: '丁香紫',
cream: '月白色',
cocoa: '焦糖棕',
};
specialMsg = `毛线已染成${names[color]},可送进同色针位!`;
},
onGate: () => {
if (!isDemo) this.sound.button();
specialMsg = '顺向穿过单向针眼!';
},
});
}
if (specialMsg) this.setStatus(specialMsg);
else this.updateDrawingStatus(route);
this.updateHud();
}
private submitDrawing(): boolean {
const route = this.state.drawing;
this.state.drawing = null;
if (!route) return false;
const missing = route.picks.length - route.deliveries.length;
if (!route.picks.length || missing) {
const blockedMsg = route.blocked
? {
pond: '绕开水洼,再试一次。',
rim: '把线留在绣布内。',
budget: '毛线不够,试试更短路线、捡线轴或撤销上一笔。',
cross: '不能压过已有毛线,换条互不交叉的路线。',
gate: '需顺着针眼箭头方向穿过。',
ball: '不能穿过挡路的异色球,请换顺序或绕行。',
}[route.blocked]
: null;
const whiteTip = route.color === 'white' ? '白球要先经过染缸染色,再送进同色针位。' : null;
const msg = blockedMsg ?? whiteTip ?? (route.picks.length ? `还差 ${missing} 个同色针位,拖过去再松手。` : '要先穿过一颗毛线球。');
this.setStatus('这笔已收回。' + msg);
this.updateHud();
return false;
}
prepareRouteForRun(route, this.state.time);
this.state.lines.push(route);
this.state.hint = null;
this.setStatus(dispatchWarning(this.level, this.state.lines) || (route.picks.length > 1 ? '两颗球一起出发。' : '蚂蚁出发了,也可继续画下一笔。'));
this.updateHud();
return true;
}
private runDemo(now: number): void {
if (this.demoIndex >= this.level.demo.length) return;
const route = this.level.demo[this.demoIndex];
if (now < this.demoStart) return;
if (!this.state.drawing) {
const startNest = route.length > 0 ? { x: route[0][0], y: route[0][1] } : (this.level.nests[0] ?? NEST);
this.state.drawing = createEmptyRoute(false, startNest);
}
const progress = Math.min(route.length - 1, Math.max(0, (now - this.demoStart) / 190));
while (this.demoPoint <= Math.floor(progress)) {
const [x, y] = route[this.demoPoint++];
this.appendPoint({ x, y }, true);
}
if (this.demoPoint < route.length) {
const [sx, sy] = route[this.demoPoint - 1];
const [x, y] = route[this.demoPoint];
this.appendPoint(interpolate({ x: sx, y: sy }, { x, y }, progress % 1), true);
} else {
if (!this.submitDrawing()) {
this.state.demo = false;
this.updateHud();
return;
}
this.demoIndex++;
this.demoPoint = 1;
this.demoStart = now + 680;
}
}
private animateRoute(route: RouteState, now: number): void {
const elapsed = now - route.startedAt;
let pause = 0;
let delivered = false;
for (let i = 0; i < route.events.length; i++) {
const ev = route.events[i];
const ms = ev.ms ?? 0;
const hold = ev.hold ?? 0;
if (elapsed < ms) break;
pause += Math.min(hold, elapsed - ms);
if (i < route.nextEvent) continue;
route.nextEvent++;
if (isPickEvent(ev)) {
ev.pickedAt = now;
route.carry.push({ ...ev.ball, pickedAt: now });
this.sound.pickup();
} else if (isDeliveryEvent(ev)) {
route.carry.shift();
ev.arrivedAt = now;
delivered = true;
this.sound.deliver();
} else if (isSpoolEvent(ev)) {
ev.collectedAt = now;
this.sound.bonus();
} else if (isButtonEvent(ev)) {
ev.threadedAt = now;
this.sound.button();
} else if (isDyeEvent(ev)) {
ev.dyedAt = now;
for (const ball of route.carry) ball.color = ev.dye.color;
this.sound.dye();
} else if (isGateEvent(ev)) {
ev.passedAt = now;
this.sound.button();
}
}
const traveled = Math.min(route.len, Math.max(0, elapsed - pause) * ANT_SPEED);
route.traveled = traveled;
while (route.segment < route.cum.length - 1 && route.cum[route.segment] < traveled) route.segment++;
const end = route.segment;
const start = route.points[end - 1];
const finish = route.points[end];
const span = route.cum[end] - route.cum[end - 1];
const part = span > 0 ? (traveled - route.cum[end - 1]) / span : 1;
const pt = interpolate(start, finish, Math.min(1, Math.max(0, part)));
const goalAngle = Math.atan2(finish.y - start.y, finish.x - start.x);
const turn = Math.atan2(Math.sin(goalAngle - route.ant.angle), Math.cos(goalAngle - route.ant.angle));
const latest = route.events[route.nextEvent - 1];
const walking = !latest || elapsed >= (latest.ms ?? 0) + (latest.hold ?? 0);
route.ant.x = pt.x;
route.ant.y = pt.y;
route.ant.angle += turn * 0.29;
route.ant.walk = walking;
if (delivered) {
if (!this.state.drawing) this.setStatus(dispatchWarning(this.level, this.state.lines) || '送达落针!');
this.updateHud();
}
if (elapsed >= route.duration) {
route.finished = true;
route.arrivedAt = now;
}
}
private updateHud(): void {
const deliveredTargets: typeof this.level.targets = [];
for (const line of this.state.lines) {
for (const stop of line.deliveries) {
if (stop.arrivedAt !== undefined) deliveredTargets.push(stop.target);
}
}
for (const color of YARN_COLORS) {
const total = this.targetCounts[color];
if (!total) continue;
const done = deliveredTargets.filter(t => t.color === color).length;
const completed = done >= total;
const st = CHIP_STYLES[color];
this.chips[color].label.string = completed ? `✓ ${done}/${total}` : `${done}/${total}`;
this.chips[color].label.color = hex(completed ? '#dff5c6' : '#fff5dc');
drawRoundedBox(this.chips[color].bg, 84, 40, {
fill: completed ? '#375431eb' : '#3c2615e8',
stroke: completed ? '#9bc284' : '#cca15a',
strokeWidth: 1.8,
radius: 20,
depth: 3,
depthColor: completed ? '#20331c' : '#221409',
shadow: 2,
highlight: '#ffe8b82e',
});
drawRoundedBox(this.chips[color].dotBg, 16, 16, {
fill: st.dot, stroke: completed ? '#d8f2be' : '#fff5d8cc', strokeWidth: 1.6, radius: 8,
});
}
const used = totalLength(this.state.lines) + (this.state.drawing?.cost ?? 0);
const curBudget = effectiveBudget(this.level, this.state.lines, this.state.drawing);
const limit = curBudget ?? Math.max(this.level.twoStar * 1.18, used);
const ratio = Math.min(1, used / Math.max(1, limit));
const liveStars = scoreForLength(this.level, used);
const effectiveStars = this.state.hintCapped ? Math.min(2, liveStars) : liveStars;
const en = this.storage.readLanguage() === 'en';
const budgetSuffix = curBudget !== undefined ? ` / ${formatShort(curBudget)}` : ' cm';
this.meterTitleLabel.string = `${en ? 'Yarn' : '用线'} ${formatShort(used)}${budgetSuffix}`;
this.meterTargetLabel.string = '★'.repeat(effectiveStars) + '☆'.repeat(3 - effectiveStars);
this.meterTargetLabel.color = hex(
effectiveStars === 3 ? '#ffdc6b' : effectiveStars === 2 ? '#f3b25a' : '#e87e5c',
);
this.meterFillBg.clear();
const fillW = Math.round(220 * ratio);
if (fillW > 2) {
this.meterFillBg.fillColor = hex(
effectiveStars === 3 ? '#8ec462' : effectiveStars === 2 ? '#e6a642' : '#e26c48',
);
this.meterFillBg.roundRect(-110, -4.5, fillW, 9, 4.5);
this.meterFillBg.fill();
}
if (limit > 0 && this.level.threeStar < limit) {
const tickRatio = Math.min(0.95, Math.max(0.08, this.level.threeStar / limit));
this.meterStarTick.setPosition(-110 + 220 * tickRatio, 0, 0);
this.meterStarTick.active = true;
} else {
this.meterStarTick.active = false;
}
if (limit > 0 && this.level.twoStar > this.level.threeStar && this.level.twoStar < limit) {
const tick2Ratio = Math.min(0.96, Math.max(0.14, this.level.twoStar / limit));
this.meterTwoStarTick.setPosition(-110 + 220 * tick2Ratio, 0, 0);
this.meterTwoStarTick.active = true;
} else {
this.meterTwoStarTick.active = false;
}
if (this.level.maxDispatches) {
const left = this.level.maxDispatches - this.state.lines.length;
const exhausted = Boolean(dispatchWarning(this.level, this.state.lines));
this.dispatchLabel.string = `剩${left}笔`;
this.dispatchLabel.color = hex(exhausted ? '#ffd4c7' : '#ffe8a3');
drawRoundedBox(this.dispatchBg, 84, 40, {
fill: exhausted ? '#6e2920f0' : '#3c2615e8',
stroke: exhausted ? '#eb9b84' : '#d4aa60',
strokeWidth: 1.8,
radius: 20,
depth: 3,
depthColor: exhausted ? '#42150f' : '#221409',
shadow: 2,
highlight: '#ffe8b82e',
});
}
if (this.mechanicNode.active) {
this.mechanicLockNode.active = false;
this.mechanicLabel.node.setPosition(0, 0, 0);
if (this.level.buttons.length > 0) {
const done = threadedButtonIds(this.state.lines, this.state.drawing).size;
const ok = done >= this.level.buttons.length;
this.mechanicLabel.string = `◎ ${done}/${this.level.buttons.length}`;
this.mechanicLabel.color = hex(ok ? '#dff5c6' : '#ffe8a3');
drawRoundedBox(this.mechanicBg, 86, 40, {
fill: ok ? '#375431eb' : '#3c2615e8',
stroke: ok ? '#9bc284' : '#d4aa60',
strokeWidth: 1.8,
radius: 20,
depth: 3,
depthColor: ok ? '#20331c' : '#221409',
shadow: 2,
highlight: '#ffe8b82e',
});
} else if (this.level.gates.length > 0) {
const done = passedGateIds(this.state.lines, this.state.drawing).size;
const ok = done >= this.level.gates.length;
this.mechanicLabel.string = `➤ ${done}/${this.level.gates.length}`;
this.mechanicLabel.color = hex(ok ? '#dff5c6' : '#ffe8a3');
drawRoundedBox(this.mechanicBg, 86, 40, {
fill: ok ? '#375431eb' : '#3c2615e8',
stroke: ok ? '#9bc284' : '#d4aa60',
strokeWidth: 1.8,
radius: 20,
depth: 3,
depthColor: ok ? '#20331c' : '#221409',
shadow: 2,
highlight: '#ffe8b82e',
});
} else if (this.level.locks && Object.keys(this.level.locks).length > 0) {
const lockKeys = Object.keys(this.level.locks);
const delivered = new Set<string>();
for (const l of this.state.lines) for (const d of l.deliveries) delivered.add(d.target.id);
const unlocked = lockKeys.filter(k => delivered.has(this.level.locks![k])).length;
const ok = unlocked >= lockKeys.length;
this.mechanicLockNode.active = true;
drawPadlockIcon(
this.mechanicLockGfx,
0.88,
ok ? '#b5e395' : '#f0cc7a',
ok ? '#e3f9ce' : '#fff0c4',
ok ? '#2b4724' : '#402712',
);
this.mechanicLabel.node.setPosition(11, 0, 0);
this.mechanicLabel.string = `${unlocked}/${lockKeys.length}`;
this.mechanicLabel.color = hex(ok ? '#dff5c6' : '#ffe8a3');
drawRoundedBox(this.mechanicBg, 86, 40, {
fill: ok ? '#375431eb' : '#3c2615e8',
stroke: ok ? '#9bc284' : '#d4aa60',
strokeWidth: 1.8,
radius: 20,
depth: 3,
depthColor: ok ? '#20331c' : '#221409',
shadow: 2,
highlight: '#ffe8b82e',
});
} else if (this.level.noCross) {
this.mechanicLabel.string = '不交叉';
this.mechanicLabel.color = hex('#ffebd8');
drawRoundedBox(this.mechanicBg, 86, 40, {
fill: '#5c2d23eb',
stroke: '#dfa086',
strokeWidth: 1.8,
radius: 20,
depth: 3,
depthColor: '#361710',
shadow: 2,
highlight: '#ffe8b82e',
});
}
}
this.undoBtn.setEnabled(!this.state.demo && !this.state.complete && this.state.lines.length > 0);
this.demoBtn.setEnabled(!this.state.demo);
this.hintBtn.setEnabled(!this.state.demo && !this.state.complete);
this.hintHalo.active = Boolean(this.state.hint);
if (this.hintBtn.label) {
this.hintBtn.label.string = this.state.hint ? `提示 ${this.state.hint.tier}/3` : '提示';
this.hintBtn.label.color = hex(this.state.hint ? '#9a4f0a' : '#452b12');
}
this.loupeBtn.setEnabled(!this.state.complete && !this.state.demo);
this.syncLoupeButton();
this.dockTrayNode.active = !this.state.complete;
this.resultOverlay.active = this.state.complete;
if (this.state.complete) {
const rawStars = scoreForLength(this.level, totalLength(this.state.lines));
const stars = this.state.hintCapped ? Math.min(2, rawStars) : rawStars;
this.resultStarsLabel.string = '★'.repeat(stars) + '☆'.repeat(3 - stars);
this.resultTitleLabel.string = this.state.assisted
? '演示完成'
: stars === 3
? '满星佳作!'
: '绣成佳作!';
const suffix = this.state.assisted
? ' · 演示模式'
: this.state.hintCapped
? (this.state.demoWatched ? ' · 看过演示最高 2 ★' : ' · 提示最高 2 ★')
: stars === 3
? ' · 达成三星'
: ` · 三星 ≤ ${formatLength(this.level.threeStar)}`;
this.resultLengthLabel.string = '用线 ' + formatLength(totalLength(this.state.lines)) + suffix;
if (this.nextBtn.label) {
const gate = this.getNextChapterGate();
if (this.currentIndex + 1 >= LEVELS.length) {
this.nextBtn.label.string = en ? 'Lobby' : '返回大厅';
} else if (gate.locked) {
this.nextBtn.label.string = en ? `Need ${gate.req}★` : `集满${gate.req}★解锁下章`;
} else {
this.nextBtn.label.string = en ? 'Next Stage' : '下一关';
}
}
if (this.atelierShortcutBtn?.label) {
if (this.currentIndex === 0 && !this.state.assisted) {
this.atelierShortcutBtn.label.string = en ? 'Read Reply' : '读阿婆回信';
} else {
this.atelierShortcutBtn.label.string = en ? 'Gallery' : '进绣品展柜';
}
}
}
}
private getNextChapterGate(): { locked: boolean; req: number; cur: number } {
const nextEntry = LEVELS[this.currentIndex + 1];
if (!nextEntry || nextEntry.chapter <= 0) return { locked: false, req: 0, cur: 0 };
const req = CHAPTER_UNLOCK_STARS[nextEntry.chapter] ?? 0;
const cur = LEVELS.reduce((sum, entry) => sum + (this.storage.getRecord(entry)?.stars ?? 0), 0);
return { locked: cur < req, req, cur };
}
protected update(dt: number): void {
if (!this.node.active) return;
const clampedMs = Math.min(50, Math.max(0, dt * 1000));
this.state.time += clampedMs;
if (this.state.demo) this.runDemo(this.state.time);
for (const line of this.state.lines) {
if (!line.finished) this.animateRoute(line, this.state.time);
}
let finishedStops = 0;
for (const route of this.state.lines) {
for (const stop of route.deliveries) {
if (stop.arrivedAt !== undefined && this.state.time - stop.arrivedAt >= STITCH_TIME) {
finishedStops++;
}
}
}
const buttonsOk = threadedButtonIds(this.state.lines).size >= this.level.buttons.length;
const gatesOk = passedGateIds(this.state.lines).size >= this.level.gates.length;
if (
finishedStops === this.level.targets.length &&
buttonsOk &&
gatesOk &&
!this.state.complete &&
this.state.lines.every(r => r.finished)
) {
this.state.drawing = null;
this.state.hint = null;
this.pointer = null;
this.hideRelativeIndicator();
this.state.completedAt = this.state.time;
this.state.complete = true;
this.state.demo = false;
this.setStatus(this.state.assisted ? '演示完成,点「重绣本关」自己试一试。' : '这一幅绣好啦,可以保存绣画留念!');
if (!this.state.assisted) {
const len = totalLength(this.state.lines);
const rawStars = scoreForLength(this.level, len);
const earnedStars = this.state.hintCapped ? Math.min(2, rawStars) : rawStars;
const improved = this.storage.saveRecord(this.level, earnedStars, len);
const bonusThreads = this.atelier.recordCompletedArtwork(this.currentIndex, this.level, earnedStars, len, improved);
this.setStatus(
this.currentIndex === 0
? `已收入展柜(+${bonusThreads} 线头)!收到林阿婆回信,点下方「读阿婆回信」拆阅~`
: `绣画已收入展柜,并获得 +${bonusThreads} 束工坊线头!`,
);
}
this.sound.win();
this.updateHud();
} else if (
finishedStops === this.level.targets.length &&
(!buttonsOk || !gatesOk) &&
!this.state.complete &&
!this.state.drawing &&
this.state.lines.length > 0 &&
this.state.lines.every(r => r.finished)
) {
this.setStatus(!buttonsOk ? '针位已满,但还有纽扣未穿过,点「撤销」绕扣重画。' : '针位已满,但还有单向针眼未穿过,点「撤销」重画。');
}
this.renderer.renderFrame(this.state, this.activeNestIndex);
}
}