(() => { 'use strict'; const data = JSON.parse(document.getElementById('offline-data').textContent); const extraFields = window.LevelExtraFields; const levelSettings = window.MainlineWorkspace.settings, settingsOptions = data.settingsCatalog; const factories = {"assets/Logic/Scripts/YnykContentConfig.ts":function(module,exports,load){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.YnykContentCatalog = exports.MONSTER_TYPE_BOSS = exports.MONSTER_TYPE_NORMAL = exports.createYnykContentCatalog = void 0; // Evidence-derived module. Babel class/type recovery is tracked in recovery/scripts-manifest.json. const rollupPluginModLoBabelHelpers_1 = load("assets/Scripts/Scripts/rollupPluginModLoBabelHelpers.ts"); const ArtifactFootprint_1 = load("assets/Logic/Scripts/ArtifactFootprint.ts"); var createYnykContentCatalog = function (e, t, i, n) { return new c(e, t, i, n); }; exports.createYnykContentCatalog = createYnykContentCatalog; var MONSTER_TYPE_NORMAL = 1; exports.MONSTER_TYPE_NORMAL = MONSTER_TYPE_NORMAL; var n = MONSTER_TYPE_NORMAL; var MONSTER_TYPE_BOSS = 2; exports.MONSTER_TYPE_BOSS = MONSTER_TYPE_BOSS; var r = MONSTER_TYPE_BOSS; function o(e, t) { var i = Number(e); if (!Number.isInteger(i) || i < 1) throw new Error(t + ":" + String(e)); return i; } var a = new Set(["standard", "collisionBomb", "automaticExit", "countdownBomb", "movingHazard", "sealedUntilCollision", "charmLeader", "bounceBack", "fenceBreaker", "limitedStep", "burrowingBlocker", "teamLeader", "teamMember"]); function l(e) { return typeof e == "string" && e.trim().length > 0; } function s(e) { var i = e.bossSkill; if (i) { if (i.skillId !== "flipMovableArtifact" && i.skillId !== "attachStepBomb" && i.skillId !== "attachCountdownBomb" && i.skillId !== "shuffleAndFlipRegion" && i.skillId !== "placeGhostFire" && i.skillId !== "attachStepLock" && i.skillId !== "healBossAndNearestMinions" && i.skillId !== "placeFog" && i.skillId !== "reflectShield") throw new Error("MONSTER_BOSS_SKILL_UNKNOWN:" + e.id + ":" + String(i.skillId)); if (i.triggerType !== "bossUnattacked") throw new Error("MONSTER_BOSS_SKILL_TRIGGER_INVALID:" + e.id); if (!Number.isFinite(i.castDurationSeconds) || i.castDurationSeconds <= 0) throw new Error("MONSTER_BOSS_SKILL_CAST_DURATION_INVALID:" + e.id); if (i.skillId === "flipMovableArtifact") { var n, r; if (((n = i.parameters) == null ? undefined : n.targetType) !== "movableArtifact" || ((r = i.parameters) == null ? undefined : r.targetSelection) !== "random") throw new Error("MONSTER_BOSS_SKILL_TARGET_INVALID:" + e.id); if (i.parameters.flipCount !== 1) throw new Error("MONSTER_BOSS_SKILL_FLIP_COUNT_INVALID:" + e.id); var o = i.parameters.flipDelaySeconds, a = i.parameters.flipDurationSeconds; if (!Number.isFinite(o) || o < 0 || !Number.isFinite(a) || a <= 0 || o + a > i.castDurationSeconds) throw new Error("MONSTER_BOSS_SKILL_FLIP_TIMING_INVALID:" + e.id); var s = i.parameters.targetEffectDelaySeconds; if (!Number.isFinite(s) || s < 0 || s > o || s >= i.castDurationSeconds) throw new Error("MONSTER_BOSS_SKILL_TARGET_EFFECT_TIMING_INVALID:" + e.id); if (i.parameters.allowUnsolvableBoard !== true) throw new Error("MONSTER_BOSS_SKILL_UNSOLVABLE_INVALID:" + e.id); } else if (i.skillId === "attachStepBomb") { var u = i.parameters, c = u.combatEffect; if (c && (c.type !== "forward-chain" || !Number.isInteger(c.targetCount) || c.targetCount < 1 || !Number.isFinite(c.damageMultiplier) || c.damageMultiplier <= 0)) throw new Error("MONSTER_BOSS_SKILL_STEP_BOMB_COMBAT_INVALID:" + e.id); if (u.boardArea !== "center" || u.targetSelection !== "random" || u.targetMustHaveNoAttachment !== true || u.missingTargetBehavior !== "waitForNextTrigger") throw new Error("MONSTER_BOSS_SKILL_TARGET_INVALID:" + e.id); if (!Number.isInteger(u.targetArtifactId) || u.targetArtifactId < 1 || u.attachmentType !== "stepBomb" || !l(u.attachmentPrefabId) || !l(u.overlaySprite) || !Number.isFinite(u.overlayScale) || u.overlayScale <= 0 || !Number.isInteger(u.stepCount) || u.stepCount < 1 || u.attachmentStacking !== false || u.placementEffectNodeName !== "Selection3" || !Number.isFinite(u.targetEffectDelaySeconds) || u.targetEffectDelaySeconds < 0 || u.targetEffectDelaySeconds >= i.castDurationSeconds) throw new Error("MONSTER_BOSS_SKILL_STEP_BOMB_INVALID:" + e.id); if (u.allowUnsolvableBoard !== true) throw new Error("MONSTER_BOSS_SKILL_UNSOLVABLE_INVALID:" + e.id); } else if (i.skillId === "attachCountdownBomb") { var d, h = i.parameters; if (h.boardArea !== "center" || h.targetSelection !== "deepestThenRandom" || h.targetMustHaveNoAttachment !== true || h.targetMustNotExitImmediately !== true || h.missingTargetBehavior !== "waitForNextTrigger") throw new Error("MONSTER_BOSS_SKILL_TARGET_INVALID:" + e.id); if (!Number.isInteger(h.targetArtifactId) || h.targetArtifactId < 1 || h.attachmentType !== "countdownBomb" || !l(h.attachmentPrefabId) || !l(h.overlaySprite) || !Number.isFinite(h.overlayScale) || h.overlayScale <= 0 || h.attachmentStacking !== false || h.placementEffectNodeName !== "Selection3" || !Number.isFinite(h.targetEffectDelaySeconds) || h.targetEffectDelaySeconds < 0 || h.targetEffectDelaySeconds >= i.castDurationSeconds || h.timerActivation !== "afterPlacementEffect" || h.targetInteractionDuringCast !== "locked" || ((d = h.combatEffect) == null ? undefined : d.type) !== "timer-blast" || !Number.isFinite(h.combatEffect.radius) || h.combatEffect.radius < 0 || !Number.isFinite(h.combatEffect.bossMultiplier) || h.combatEffect.bossMultiplier <= 0) throw new Error("MONSTER_BOSS_SKILL_COUNTDOWN_BOMB_INVALID:" + e.id); if (h.allowUnsolvableBoard !== true) throw new Error("MONSTER_BOSS_SKILL_UNSOLVABLE_INVALID:" + e.id); } else if (i.skillId === "shuffleAndFlipRegion") { var f = i.parameters, p = new Set(Array.isArray(f.avoidMechanismTypes) ? f.avoidMechanismTypes : []); if (f.regionColumns !== 4 || f.regionRows !== 4 || f.minimumArtifactCount !== 4 || f.targetSelection !== "deadlockPreferred" || f.attachmentsFollowArtifact !== true || !Number.isFinite(f.deadlockAttemptChance) || f.deadlockAttemptChance < 0 || f.deadlockAttemptChance > 1 || f.requireDeadlockValidation !== true || f.allowUnsolvableBoard !== true || !Array.isArray(f.avoidMechanismTypes) || p.size !== 2 || !p.has("burrowingBlocker") || !p.has("fence") || !l(f.effectPrefabPath) || !Number.isFinite(f.layoutApplyDelaySeconds) || f.layoutApplyDelaySeconds !== i.castDurationSeconds || f.lockScope !== "region") throw new Error("MONSTER_BOSS_SKILL_SHUFFLE_REGION_INVALID:" + e.id); } else if (i.skillId === "placeGhostFire") { var v = i.parameters, g = Array.isArray(v.groupShapes) ? v.groupShapes : [], m = new Set(g.map(function (e) { return (e == null ? undefined : e.columns) + "x" + (e == null ? undefined : e.rows); })); if (i.castDurationSeconds !== 1 || v.boardArea !== "perimeter" || v.groupsPerCast !== 1 || g.length !== 2 || m.size !== 2 || !m.has("2x1") || !m.has("1x2") || v.minimumStraightEmptyCells !== 6 || v.ghostFireArtifactId !== 6 || v.ghostFirePrefabId !== "guihuo" || !Number.isFinite(v.ghostFireMoveSpeed) || v.ghostFireMoveSpeed <= 0 || v.obstacleDuration !== "permanent" || v.missingTargetBehavior !== "waitForNextTrigger" || v.allowUnsolvableBoard !== true) throw new Error("MONSTER_BOSS_SKILL_GHOST_FIRE_INVALID:" + e.id); } else if (i.skillId === "attachStepLock") { var y = i.parameters; if (i.castDurationSeconds !== 1 || y.boardArea !== "center" || y.regionColumns !== 2 || y.regionRows !== 2 || y.preferredArtifactCountMin !== 2 || y.preferredArtifactCountMax !== 4 || y.targetMustHaveNoAttachment !== true || y.targetSelection !== "filledRegionThenSingleRandom" || y.attachmentType !== "stepLock" || y.mechanismId !== 103 || !l(y.mechanismPrefabPath) || !l(y.placementEffectPrefabPath) || !Number.isFinite(y.lockApplyDelaySeconds) || y.lockApplyDelaySeconds !== .6 || y.lockApplyDelaySeconds >= i.castDurationSeconds || y.targetInteractionDuringCast !== "locked" || y.attachmentStacking !== false || y.missingTargetBehavior !== "waitForNextTrigger" || y.allowUnsolvableBoard !== true) throw new Error("MONSTER_BOSS_SKILL_STEP_LOCK_INVALID:" + e.id); } else if (i.skillId === "healBossAndNearestMinions") { var b = i.parameters; if (i.castDurationSeconds !== 1 || !Number.isFinite(b.healthAddAmount) || b.healthAddAmount <= 0 || b.bossCanIncreaseMaximumHealth !== true || !Number.isFinite(b.minionHealthAddAmount) || b.minionHealthAddAmount <= 0 || b.minionTargetRule !== "allAlive" || b.minionsCanIncreaseMaximumHealth !== true || b.reviveDeadMinions !== false || !l(b.effectPrefabPath) || !Number.isFinite(b.healthAddDelaySeconds) || b.healthAddDelaySeconds < 0 || b.healthAddDelaySeconds >= i.castDurationSeconds) throw new Error("MONSTER_BOSS_SKILL_HEALTH_ADD_INVALID:" + e.id); } else if (i.skillId === "placeFog") { var w = i.parameters; if (i.castDurationSeconds !== 1 || w.regionColumns !== 5 || w.regionRows !== 5 || w.targetSelection !== "random" || w.preferArtifactCoverage !== true || w.preferNonOverlapping !== true || w.overlapFallback !== "minimumOverlap" || !Number.isFinite(w.durationSeconds) || w.durationSeconds <= 0 || w.bindTo !== "boardCell" || w.overlapDurationMode !== "independent" || w.hidesArtifact !== true || w.blocksClick !== true || w.blocksMove !== true || !l(w.effectPrefabPath) || !Number.isFinite(w.fogApplyDelaySeconds) || w.fogApplyDelaySeconds !== .2 || w.fogApplyDelaySeconds >= i.castDurationSeconds || w.missingTargetBehavior !== "waitForNextTrigger" || w.allowUnsolvableBoard !== true) throw new Error("MONSTER_BOSS_SKILL_FOG_INVALID:" + e.id); } else { var S = i.parameters, I = Array.isArray(S.shieldBypassArtifactIds) ? S.shieldBypassArtifactIds : [], M = Array.isArray(S.shieldBypassEffectIds) ? S.shieldBypassEffectIds : []; if (S.blockedDamageType !== "normal" || !Number.isFinite(S.shieldApplyDelaySeconds) || S.shieldApplyDelaySeconds < 0 || S.shieldApplyDelaySeconds >= i.castDurationSeconds || S.reflectedArtifactLeavesBattle !== true || S.reflectedArtifactCanAttackMinions !== false || I.length === 0 || I.some(function (e) { return !Number.isInteger(e) || e < 1; }) || new Set(I).size !== I.length || M.length === 0 || M.some(function (e) { return !l(e); }) || new Set(M).size !== M.length || S.specialEffectsConsumeShield !== false) throw new Error("MONSTER_BOSS_SKILL_REFLECT_SHIELD_INVALID:" + e.id); } if (!Array.isArray(i.difficultyParameters) || i.difficultyParameters.length === 0) throw new Error("MONSTER_BOSS_SKILL_DIFFICULTIES_MISSING:" + e.id); var k = new Set(); for (const R of i.difficultyParameters) { if (!Number.isInteger(R.difficultyId) || R.difficultyId < 1 || R.difficultyId > 5) throw new Error("MONSTER_BOSS_SKILL_DIFFICULTY_INVALID:" + e.id + ":" + R.difficultyId); if (k.has(R.difficultyId)) throw new Error("MONSTER_BOSS_SKILL_DIFFICULTY_DUPLICATE:" + e.id + ":" + R.difficultyId); if (i.skillId === "attachCountdownBomb") { var x = R; if (!Number.isFinite(x.countdownSeconds) || x.countdownSeconds <= 0) throw new Error("MONSTER_BOSS_SKILL_COUNTDOWN_BOMB_INVALID:" + e.id); } if (i.skillId === "attachStepLock") { var P = R; if (!Number.isInteger(P.lockStepCount) || P.lockStepCount < 1) throw new Error("MONSTER_BOSS_SKILL_STEP_LOCK_INVALID:" + e.id); } if (i.skillId === "reflectShield") { var A = R; if (!Number.isInteger(A.blockedHitCount) || A.blockedHitCount < 1) throw new Error("MONSTER_BOSS_SKILL_REFLECT_SHIELD_INVALID:" + e.id); } if (k.add(R.difficultyId), !Number.isFinite(R.triggerSeconds) || R.triggerSeconds <= 0) throw new Error("MONSTER_BOSS_SKILL_TRIGGER_SECONDS_INVALID:" + e.id + ":" + R.difficultyId); if (!Number.isInteger(R.maxCastCount) || R.maxCastCount < 0) throw new Error("MONSTER_BOSS_SKILL_MAX_CAST_COUNT_INVALID:" + e.id + ":" + R.difficultyId); } } } function u(e, t, i) { for (var n = 0, r = ["1", "2", "3", "4"]; n < r.length; n++) { var o = r[n], a = i == null ? undefined : i[o]; if (!a) throw new Error(e + "_FOOTPRINT_MISSING:" + t + ":" + o); if (!Number.isInteger(a.width) || a.width < 1 || !Number.isInteger(a.height) || a.height < 1 || !Array.isArray(a.cells) || a.cells.length < 1 || a.cells.some(function (e) { return !Array.isArray(e) || e.length !== 2 || !e.every(Number.isInteger); })) throw new Error(e + "_FOOTPRINT_INVALID:" + t + ":" + o); } } class YnykContentCatalog { constructor(e, i, c, d) { var h = this; if (this.levelCount = undefined, this.artifacts = undefined, this.mechanisms = undefined, this.monsters = undefined, this.scenes = undefined, this.artifactById = new Map(), this.mechanismById = new Map(), this.monsterById = new Map(), this.sceneById = new Map(), this.encounterByLevel = new Map(), ![1, 2].includes(e == null ? undefined : e.schemaVersion) || !Array.isArray(e.artifacts) || !Array.isArray(e.mechanisms)) throw new Error("军械配置格式无效"); if (!Array.isArray(i == null ? undefined : i.monsters)) throw new Error("MONSTER_CONFIG_INVALID"); if (!Array.isArray(c == null ? undefined : c.scenes)) throw new Error("SCENE_CONFIG_INVALID"); if (d == null || !d.levels || typeof d.levels != "object") throw new Error("MAINLINE_ENCOUNTER_CONFIG_INVALID"); this.artifacts = (0, ArtifactFootprint_1.normalizeFootprintDefinitions)(e, 'artifacts'); this.mechanisms = (0, ArtifactFootprint_1.normalizeFootprintDefinitions)(e, 'mechanisms'); for (const v of this.artifacts) { var g = o(v.id, "ARTIFACT_ID_INVALID"); if (g >= 100) throw new Error("ARTIFACT_ID_RANGE_INVALID:" + g); if (this.artifactById.has(g)) throw new Error("ARTIFACT_ID_DUPLICATE:" + g); if (v.type !== 1 && v.type !== 2) throw new Error("ARTIFACT_TYPE_INVALID:" + g); if (!l(v.name) || !l(v.prefabId)) throw new Error("ARTIFACT_PREFAB_ID_MISSING:" + g); if (!Number.isInteger(v.unlockLevel) || v.unlockLevel < 1 || !Number.isFinite(v.moveSpeed) || v.moveSpeed < 0 || !Number.isFinite(v.attack) || v.attack < 0) throw new Error("ARTIFACT_NUMERIC_VALUE_INVALID:" + g); if (!a.has(v.boardBehavior)) throw new Error("ARTIFACT_BEHAVIOR_INVALID:" + g); if (u("ARTIFACT", g, v.footprintsByOrientation), !v.visual || !Number.isFinite(v.visual.spriteForwardOffsetDeg) || !Number.isFinite(v.visual.spriteScale) || v.visual.spriteScale <= 0) throw new Error("ARTIFACT_VISUAL_INVALID:" + g); if (!Number.isInteger(v.galleryOrder) || v.galleryOrder < 1 || !l(v.galleryAbilityText) || !l(v.galleryDescription)) throw new Error("ARTIFACT_GALLERY_INVALID:" + g); if (v.visual.horizontalRouteOffset != null && (!Number.isFinite(v.visual.horizontalRouteOffset) || v.visual.horizontalRouteOffset < 0)) throw new Error("军械轨道偏移必须是非负数:" + g); this.artifactById.set(g, v); } for (var m, y = function () { var e = m.value, t = o(e.id, "MECHANISM_ID_INVALID"); if (t < 100 || t >= 200) throw new Error("MECHANISM_ID_RANGE_INVALID:" + t); if (h.mechanismById.has(t)) throw new Error("MECHANISM_ID_DUPLICATE:" + t); if (e.type !== 1 && e.type !== 2) throw new Error("MECHANISM_TYPE_INVALID:" + t); if (!l(e.name) || !e.prefabIds || !Object.keys(e.prefabIds).some(function (t) { return l(e.prefabIds[t]); })) throw new Error("MECHANISM_PREFAB_MISSING:" + t); if (e.boardBehavior !== "fence" && e.boardBehavior !== "cage") throw new Error("MECHANISM_BEHAVIOR_INVALID:" + t); if (!l(e.galleryDisplayName) || !Number.isInteger(e.unlockLevel) || e.unlockLevel < 1 || !Number.isInteger(e.galleryOrder) || e.galleryOrder < 1 || !l(e.galleryAbilityText) || !l(e.galleryDescription)) throw new Error("MECHANISM_GALLERY_INVALID:" + t); u("MECHANISM", t, e.footprintsByOrientation); h.mechanismById.set(t, e); }, b = (0, rollupPluginModLoBabelHelpers_1.createForOfIteratorHelperLoose)(this.mechanisms); !(m = b()).done;) y(); this.monsters = i.monsters.slice(); this.scenes = c.scenes.slice(); for (const I of this.monsters) { var M = o(I.id, "MONSTER_ID_INVALID"); if (this.monsterById.has(M)) throw new Error("MONSTER_ID_DUPLICATE:" + M); if (I.type !== n && I.type !== r) throw new Error("MONSTER_TYPE_INVALID:" + M); if (!String(I.prefabId || "").trim()) throw new Error("MONSTER_PREFAB_ID_MISSING:" + M); if (undefined !== I.voiceRepeatIntervalSeconds && (!Number.isFinite(I.voiceRepeatIntervalSeconds) || I.voiceRepeatIntervalSeconds < 0)) throw new Error("MONSTER_VOICE_REPEAT_INTERVAL_INVALID:" + M); if (undefined !== I.galleryVisible && typeof I.galleryVisible !== "boolean") throw new Error("怪物图鉴显示配置必须为布尔值:" + M); s(I); this.monsterById.set(M, I); } for (const T of this.scenes) { var R = o(T.id, "SCENE_ID_INVALID"); if (this.sceneById.has(R)) throw new Error("SCENE_ID_DUPLICATE:" + R); if (!String(T.prefabId || "").trim()) throw new Error("SCENE_PREFAB_ID_MISSING:" + R); this.sceneById.set(R, T); } for (const A of this.monsters) { if (!Array.isArray(A.sceneIds) || A.sceneIds.length === 0) throw new Error("MONSTER_SCENES_MISSING:" + A.id); for (const N of A.sceneIds) { if (!this.sceneById.has(N)) throw new Error("MONSTER_SCENE_NOT_FOUND:" + A.id + ":" + N); } } for (var B = 0, _ = Object.keys(d.levels); B < _.length; B++) { var D = _[B], F = d.levels[D], V = o(D, "LEVEL_ID_INVALID"), O = this.sceneById.get(F.sceneId); if (!O) throw new Error("LEVEL_" + V + "_SCENE_NOT_FOUND:" + F.sceneId); var z = this.monsterById.get(F.bossId); if (!z) throw new Error("LEVEL_" + V + "_BOSS_NOT_FOUND:" + F.bossId); if (z.type !== r) throw new Error("LEVEL_" + V + "_BOSS_TYPE_INVALID:" + z.id); if (!z.sceneIds.contains(O.id)) throw new Error("LEVEL_" + V + "_BOSS_SCENE_MISMATCH:" + z.id); if (z.unlockLevel > V) throw new Error("LEVEL_" + V + "_BOSS_LOCKED:" + z.id); if (!Array.isArray(F.monsterIds) || F.monsterIds.length === 0) throw new Error("LEVEL_" + V + "_MONSTERS_MISSING"); if (new Set(F.monsterIds).size !== F.monsterIds.length) throw new Error("LEVEL_" + V + "_MONSTER_DUPLICATE"); for (const H of F.monsterIds) { var K = this.monsterById.get(H); if (!K) throw new Error("LEVEL_" + V + "_MONSTER_NOT_FOUND:" + H); if (K.type !== n) throw new Error("LEVEL_" + V + "_MONSTER_TYPE_INVALID:" + H); if (!K.sceneIds.contains(O.id)) throw new Error("LEVEL_" + V + "_MONSTER_SCENE_MISMATCH:" + H); if (K.unlockLevel > V) throw new Error("LEVEL_" + V + "_MONSTER_LOCKED:" + H); } this.encounterByLevel.set(V, F); } this.levelCount = this.encounterByLevel.size; for (var Y = 1; Y <= this.levelCount; Y += 1) if (!this.encounterByLevel.has(Y)) throw new Error("LEVEL_ENCOUNTER_GAP:" + Y); } getMonster(e) { var t = this.monsterById.get(e); if (!t) throw new Error("MONSTER_NOT_FOUND:" + e); return t; } getArtifact(e) { var t = this.artifactById.get(e); if (!t) throw new Error("ARTIFACT_NOT_FOUND:" + e); return t; } getMechanism(e) { var t = this.mechanismById.get(e); if (!t) throw new Error("MECHANISM_NOT_FOUND:" + e); return t; } getScene(e) { var t = this.sceneById.get(e); if (!t) throw new Error("SCENE_NOT_FOUND:" + e); return t; } getEncounter(e) { var t = this.encounterByLevel.get(e); if (!t) throw new Error("LEVEL_ENCOUNTER_NOT_FOUND:" + e); return t; } getSceneForLevel(e) { return this.getScene(this.getEncounter(e).sceneId); } resolveEncounter(e) { var t = this, i = this.getEncounter(e); return { levelId: e, scene: this.getScene(i.sceneId), boss: this.getMonster(i.bossId), monsters: i.monsterIds.map(function (e) { return t.getMonster(e); }) }; } scenePrefabPathForLevel(e) { return "prefabs/Ynyk/" + this.getSceneForLevel(e).prefabId; } monsterPrefabPath(e) { var t = this.getMonster(e).prefabId; return "prefabs/Enemy/" + t + "/" + t; } artifactPrefabPath(e) { return "Ynyk/Props/" + this.getArtifact(e).prefabId + "/spriteFrame"; } mechanismPrefabPath(e, t) { var i, n = this.getMechanism(e), r = n.boardBehavior === "fence" || t === 2 || t === 4 ? "horizontal" : "vertical", o = (i = n.prefabIds.default) != null ? i : n.prefabIds[r]; if (!o) throw new Error("MECHANISM_PREFAB_MISSING:" + e + ":" + t); return "prefabs/Mechanisms/" + o; } } exports.YnykContentCatalog = YnykContentCatalog; var c = YnykContentCatalog; }, "assets/Scripts/Scripts/rollupPluginModLoBabelHelpers.ts":function(module,exports,load){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.unsupportedIterableToArray = exports.toPropertyKey = exports.toPrimitive = exports.objectWithoutPropertiesLoose = exports.initializerDefineProperty = exports.inheritsLoose = exports.createForOfIteratorHelperLoose = exports.createClass = exports.asyncToGenerator = exports.assertThisInitialized = exports.arrayLikeToArray = exports.applyDecoratedDescriptor = exports.setPrototypeOf = exports.extends = void 0; var Exportextends; var setPrototypeOf; function t(e, t, n, r, i, a, u) { try { var s = e[a](u), f = s.value; } catch (e) { return void n(e); } s.done ? t(f) : Promise.resolve(f).then(r, i); } function n(e, t) { for (var n = 0; n < t.length; n++) { var r = t[n]; r.enumerable = r.enumerable || false; r.configurable = true; "value" in r && (r.writable = true); Object.defineProperty(e, f(r.key), r); } } function r(..._extraArguments) { return (r = exports.extends = Exportextends = Object.assign ? Object.assign.bind() : function (e, ..._extraArguments2) { for (var t = 1; t < arguments.length; t++) { var n = arguments[t]; for (var r in n) Object.prototype.hasOwnProperty.call(n, r) && (e[r] = n[r]); } return e; }).apply(this, arguments); } function i(t, n) { return (i = exports.setPrototypeOf = setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (e, t) { e.__proto__ = t; return e; })(t, n); } function a(e, t) { if (e) { if (typeof e == "string") return u(e, t); var n = Object.prototype.toString.call(e).slice(8, -1); n === "Object" && e.constructor && (n = e.constructor.name); return n === "Map" || n === "Set" ? Array.from(e) : n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n) ? u(e, t) : undefined; } } function u(e, t) { (t == null || t > e.length) && (t = e.length); for (var n = 0, r = new Array(t); n < t; n++) r[n] = e[n]; return r; } function s(e, t) { if (typeof e != "object" || e === null) return e; var n = e[Symbol.toPrimitive]; if (undefined !== n) { var r = n.call(e, t || "default"); if (typeof r != "object") return r; throw new TypeError("@@toPrimitive must return a primitive value."); } return (t === "string" ? String : Number)(e); } function f(e) { var t = s(e, "string"); return typeof t == "symbol" ? t : String(t); } var applyDecoratedDescriptor = function (e, t, n, r, o) { var i = {}; Object.keys(r).forEach(function (e) { i[e] = r[e]; }); i.enumerable = !!i.enumerable; i.configurable = !!i.configurable; ("value" in i || i.initializer) && (i.writable = true); i = n.slice().reverse().reduce(function (n, r) { return r(e, t, n) || n; }, i); o && undefined !== i.initializer && (i.value = i.initializer ? i.initializer.call(o) : undefined, i.initializer = undefined); undefined === i.initializer && (Object.defineProperty(e, t, i), i = null); return i; }; exports.applyDecoratedDescriptor = applyDecoratedDescriptor; var arrayLikeToArray = u; exports.arrayLikeToArray = arrayLikeToArray; var assertThisInitialized = function (e) { if (undefined === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }; exports.assertThisInitialized = assertThisInitialized; var asyncToGenerator = function (e) { return function (..._extraArguments3) { var n = this, r = arguments; return new Promise(function (o, i) { var a = e.apply(n, r); function u(e) { t(a, o, i, u, s, "next", e); } function s(e) { t(a, o, i, u, s, "throw", e); } u(undefined); }); }; }; exports.asyncToGenerator = asyncToGenerator; var createClass = function (e, t, r) { t && n(e.prototype, t); r && n(e, r); Object.defineProperty(e, "prototype", { writable: false }); return e; }; exports.createClass = createClass; var createForOfIteratorHelperLoose = function (e, t) { var n = typeof Symbol != "undefined" && e[Symbol.iterator] || e["@@iterator"]; if (n) return (n = n.call(e)).next.bind(n); if (Array.isArray(e) || (n = a(e)) || t && e && typeof e.length == "number") { n && (e = n); var r = 0; return function () { return r >= e.length ? { done: true } : { done: false, value: e[r++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }; exports.createForOfIteratorHelperLoose = createForOfIteratorHelperLoose; exports.extends = Exportextends = r; var inheritsLoose = function (e, t) { e.prototype = Object.create(t.prototype); e.prototype.constructor = e; i(e, t); }; exports.inheritsLoose = inheritsLoose; var initializerDefineProperty = function (e, t, n, r) { n && Object.defineProperty(e, t, { enumerable: n.enumerable, configurable: n.configurable, writable: n.writable, value: n.initializer ? n.initializer.call(r) : undefined }); }; exports.initializerDefineProperty = initializerDefineProperty; var objectWithoutPropertiesLoose = function (e, t) { if (e == null) return {}; var n, r, o = {}, i = Object.keys(e); for (r = 0; r < i.length; r++) { n = i[r]; t.indexOf(n) >= 0 || (o[n] = e[n]); } return o; }; exports.objectWithoutPropertiesLoose = objectWithoutPropertiesLoose; exports.setPrototypeOf = setPrototypeOf = i; var toPrimitive = s; exports.toPrimitive = toPrimitive; var toPropertyKey = f; exports.toPropertyKey = toPropertyKey; var unsupportedIterableToArray = a; exports.unsupportedIterableToArray = unsupportedIterableToArray; ({ "applyDecoratedDescriptor": applyDecoratedDescriptor, "arrayLikeToArray": arrayLikeToArray, "assertThisInitialized": assertThisInitialized, "asyncToGenerator": asyncToGenerator, "createClass": createClass, "createForOfIteratorHelperLoose": createForOfIteratorHelperLoose, "extends": Exportextends, "inheritsLoose": inheritsLoose, "initializerDefineProperty": initializerDefineProperty, "objectWithoutPropertiesLoose": objectWithoutPropertiesLoose, "setPrototypeOf": setPrototypeOf, "toPrimitive": toPrimitive, "toPropertyKey": toPropertyKey, "unsupportedIterableToArray": unsupportedIterableToArray }); }, "assets/Logic/Scripts/ArtifactFootprint.ts":function(module,exports,load){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createArtifactFootprints = createArtifactFootprints; exports.normalizeFootprintDefinitions = normalizeFootprintDefinitions; const ORIENTATION_DIRECTIONS = { "1": "south", "2": "east", "3": "north", "4": "west", }; function createArtifactFootprints(cells) { if (!Array.isArray(cells) || cells.length === 0 || cells.some((cell) => !Array.isArray(cell) || cell.length !== 2 || !cell.every(Number.isSafeInteger))) { throw new Error("军械占格必须是非空的整数坐标列表"); } if (new Set(cells.map((cell) => cell.join(","))).size !== cells.length) { throw new Error("军械占格不能包含重复坐标"); } const result = {}; for (const orientation of Object.keys(ORIENTATION_DIRECTIONS)) { const rotated = cells.map(([col, row]) => { if (orientation === "1") return [-row, col]; if (orientation === "3") return [row, -col]; if (orientation === "4") return [-col, -row]; return [col, row]; }); const minCol = Math.min(...rotated.map((cell) => cell[0])); const minRow = Math.min(...rotated.map((cell) => cell[1])); const normalized = rotated .map((cell) => [cell[0] - minCol, cell[1] - minRow]) .sort((left, right) => left[1] - right[1] || left[0] - right[0]); result[orientation] = { direction: ORIENTATION_DIRECTIONS[orientation], width: Math.max(...normalized.map((cell) => cell[0])) + 1, height: Math.max(...normalized.map((cell) => cell[1])) + 1, cells: normalized, }; } return result; } function normalizeFootprintDefinitions(config, collection) { if (!config || !Array.isArray(config[collection])) throw new Error("占格配置缺少对象列表:" + collection); if (config.schemaVersion === 1) return config[collection].map((definition) => ({ ...definition })); if (config.schemaVersion !== 2) throw new Error("不支持的军械配置版本"); if (config.baseDirection !== "east") throw new Error("军械配置的基准方向必须为 east(向右)"); return config[collection].map((definition) => ({ ...definition, footprintsByOrientation: createArtifactFootprints(definition.footprint?.cells), })); } }, "assets/Logic/Scripts/LevelAdapter.ts":function(module,exports,load){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FLIGHT_PIXELS_PER_SOURCE_SPEED = exports.BOARD_ROTATION_DEG = exports.BOARD_CENTER = exports.REFERENCE_BOARD_HEIGHT = exports.REFERENCE_BOARD_WIDTH = exports.DIRECTIONS = void 0; exports.fullRectangleCells = fullRectangleCells; exports.geometryFor = geometryFor; exports.deriveBoard = deriveBoard; exports.occupiedCells = occupiedCells; exports.selectBoard = selectBoard; exports.adaptLevel = adaptLevel; /** * 主线关卡适配层:把关卡 JSON(法器/机制物数组)转成可运行的棋盘状态。 * * 由 Babel 编译产物人工恢复:导出名称、报错文案与运行行为与原文件完全等价。 * 主要还原点: * - createForOfIteratorHelperLoose → 原生 for...of(该 helper 优先走迭代器协议,语义一致); * - extends helper → 对象展开(其定义即 Object.assign); * - void 0 === x 判断 → 默认参数; * - 适配过程中的几个匿名 IIFE → 命名函数(参数原本就是显式传递的)。 */ const DataContracts_1 = load("assets/Logic/Scripts/DataContracts.ts"); /** 源数据朝向编号 → 方向名。 */ exports.DIRECTIONS = Object.freeze({ 1: "south", 2: "east", 3: "north", 4: "west", }); /** 参考棋盘像素宽(源关卡坐标的归一基准)。 */ exports.REFERENCE_BOARD_WIDTH = 431.717798051349; /** 参考棋盘像素高。 */ exports.REFERENCE_BOARD_HEIGHT = 710.275; /** 棋盘像素中心。 */ exports.BOARD_CENTER = Object.freeze({ x: 365.03791527777776, y: 811.9960472222222, }); /** 棋盘整体旋转角。 */ exports.BOARD_ROTATION_DEG = -15.04; /** 源速度 → 飞行像素速度的换算系数。 */ exports.FLIGHT_PIXELS_PER_SOURCE_SPEED = 32; /** 浮点比较容差。 */ const EPSILON = 1e-9; /** 倒计时炸弹按难度等级的覆盖时长(仅当源时长 >= 180 时生效)。 */ const DIFFICULTY_BOMB_DURATION = Object.freeze({ 1: 160, 2: 180, 3: 200, 4: 220, 5: 220, }); /** JSON 深拷贝(关卡数据只含可序列化值)。 */ function deepClone(value) { return JSON.parse(JSON.stringify(value)); } /** 生成 columns×rows 的完整矩形格键列表。 */ function fullRectangleCells(columns, rows) { const cells = []; for (let row = 0; row < rows; row += 1) { for (let col = 0; col < columns; col += 1) cells.push(col + "," + row); } return cells; } /** 按列数/行数构造矩形棋盘几何。 */ function geometryFor(columns, rows) { if (!Number.isInteger(columns) || columns <= 0 || !Number.isInteger(rows) || rows <= 0) { throw new TypeError("INVALID_SHEEP_BOARD_DIMENSIONS"); } return { columns, rows, center: deepClone(exports.BOARD_CENTER), cellSize: exports.REFERENCE_BOARD_WIDTH / columns, rotationDeg: exports.BOARD_ROTATION_DEG, }; } /** 点是否在线段上(含端点,带容差)。 */ function pointOnSegment(point, segStart, segEnd) { const cross = (point.x - segStart.x) * (segEnd.y - segStart.y) - (point.y - segStart.y) * (segEnd.x - segStart.x); if (Math.abs(cross) > EPSILON) return false; return (point.x >= Math.min(segStart.x, segEnd.x) - EPSILON && point.x <= Math.max(segStart.x, segEnd.x) + EPSILON && point.y >= Math.min(segStart.y, segEnd.y) - EPSILON && point.y <= Math.max(segStart.y, segEnd.y) + EPSILON); } /** 射线法点在多边形内判定;落在边界上也算在内。 */ function pointInPolygon(point, polygon) { let inside = false; for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i, i += 1) { const prev = polygon[j]; const curr = polygon[i]; if (pointOnSegment(point, prev, curr)) return true; if (prev.y > point.y !== curr.y > point.y) { const intersectX = ((curr.x - prev.x) * (point.y - prev.y)) / (curr.y - prev.y) + prev.x; if (point.x < intersectX) inside = !inside; } } return inside; } /** 计算某格旋转后的四个像素角点。 */ function cellCorners(geometry, col, row) { const rad = (geometry.rotationDeg * Math.PI) / 180; const cos = Math.cos(rad); const sin = Math.sin(rad); const left = (col - geometry.columns / 2) * geometry.cellSize; const right = left + geometry.cellSize; const top = (row - geometry.rows / 2) * geometry.cellSize; const bottom = top + geometry.cellSize; return [ [left, top], [right, top], [right, bottom], [left, bottom], ].map(([dx, dy]) => ({ x: geometry.center.x + dx * cos - dy * sin, y: geometry.center.y + dx * sin + dy * cos, })); } /** * 按路线内边界多边形推导棋盘:列数给定,行数由像素高/格宽取整, * 四角都在多边形内的格子为可行走格。 */ function deriveBoard(columns, routeData, rotationDeg = exports.BOARD_ROTATION_DEG) { const innerBoundary = routeData && routeData.walkable_area && routeData.walkable_area.inner_boundary; if (!Array.isArray(innerBoundary) || innerBoundary.length < 3) { throw new TypeError("SHEEP_ROUTE_INNER_BOUNDARY_REQUIRED"); } const cellSize = exports.REFERENCE_BOARD_WIDTH / columns; const geometry = { columns, rows: Math.floor(exports.REFERENCE_BOARD_HEIGHT / cellSize), center: deepClone(exports.BOARD_CENTER), cellSize, rotationDeg, }; const validCells = []; for (let row = 0; row < geometry.rows; row += 1) { for (let col = 0; col < geometry.columns; col += 1) { if (cellCorners(geometry, col, row).every((corner) => pointInPolygon(corner, innerBoundary))) { validCells.push(col + "," + row); } } } return { geometry, validCells }; } /** 解析 "col,row" 格键,非法返回 null。 */ function parseCellKey(cellKey) { const parts = String(cellKey || "").split(",").map(Number); return parts.length === 2 && parts.every(Number.isFinite) ? { col: parts[0], row: parts[1] } : null; } /** 在 extra.addBuff 中按 buffId 找第一个匹配。 */ function findBuff(extra, buffId) { return (extra.addBuff || []).find((buff) => buff && buff.buffId === buffId); } /** 实体的全部占位格(使用自身 col/row)。 */ function occupiedCells(entity) { return entity.occupiedOffsets.map((offset) => ({ col: entity.col + offset[0], row: entity.row + offset[1], })); } /** * 搜索摆放偏移:要求全部占位格平移后都落在可行走格内, * 候选按"离棋盘中心最近"排序(同距时 |dy|、|dx|、dy、dx 依次决胜)。 */ function findPlacementOffset(blockedCells, board, width, height) { const validSet = new Set(board.validCells); const parsed = board.validCells.map((cell) => cell.split(",").map(Number)); const midCol = (Math.min(...parsed.map((p) => p[0])) + Math.max(...parsed.map((p) => p[0])) + 1) / 2; const midRow = (Math.min(...parsed.map((p) => p[1])) + Math.max(...parsed.map((p) => p[1])) + 1) / 2; const candidates = []; for (let dy = -height; dy <= board.geometry.rows; dy += 1) { for (let dx = -width; dx <= board.geometry.columns; dx += 1) { const fits = blockedCells.every((cell) => validSet.has(cell.col + dx + "," + (cell.row + dy))); if (fits) { candidates.push({ dx, dy, centerDistance: Math.hypot(dx + width / 2 - midCol, dy + height / 2 - midRow), }); } } } candidates.sort((a, b) => a.centerDistance - b.centerDistance || Math.abs(a.dy) - Math.abs(b.dy) || Math.abs(a.dx) - Math.abs(b.dx) || a.dy - b.dy || a.dx - b.dx); return candidates.length ? { dx: candidates[0].dx, dy: candidates[0].dy } : null; } /** 收集全部占位格;movingHazard 还会把路径沿途的插值格一并计入。 */ function collectBlockedCells(units, aoes) { // 注:等价于 [...units, ...aoes].flatMap(occupiedCells),项目 lib 低于 es2019 故展开写 const blocked = []; for (const entity of [...units, ...aoes]) blocked.push(...occupiedCells(entity)); const hazards = units.filter((unit) => unit.boardBehavior === "movingHazard" && unit.path?.length); for (const hazard of hazards) { for (let segment = 0; segment < hazard.path.length - 1; segment += 1) { let col = hazard.path[segment].col; let row = hazard.path[segment].row; const next = hazard.path[segment + 1]; // 每步先记录当前占位,再向下一路径点走一格(横竖优先于斜) for (let guard = 0; guard < 1024 && (blocked.push(...hazard.occupiedOffsets.map((offset) => ({ col: col + offset[0], row: row + offset[1] }))), col !== next.col || row !== next.row); guard += 1) { const dCol = Math.sign(next.col - col); const dRow = dCol === 0 ? Math.sign(next.row - row) : 0; col += dCol; row += dRow; } } } return blocked; } /** * 选出能容纳本关布局的棋盘:宽 8 的关卡只试 8 列,其余试 12/13/14 列; * 第一个能找到合法摆放偏移的候选胜出。 */ function selectBoard(level, units, aoes, routeData, rotationDeg = exports.BOARD_ROTATION_DEG) { const candidateColumns = level.width === 8 ? [8] : [12, 13, 14]; const blockedCells = collectBlockedCells(units, aoes); for (const columns of candidateColumns) { const board = deriveBoard(columns, routeData, rotationDeg); const offset = findPlacementOffset(blockedCells, board, level.width, level.height); if (offset) return { ...board, offset }; } throw new Error("SHEEP_LAYOUT_CANNOT_FIT_ROUTE:" + level.displayLevel); } /** 从 extra.aiClips 中提取第一段 movePath 指令的路径点(>=2 点才有效)。 */ function extractMovePath(extra) { const aiClips = Array.isArray(extra.aiClips) ? extra.aiClips : []; for (const clip of aiClips) { for (const action of clip.actions || []) { if (action.method === "movePath") { const points = (action.params || []).map(parseCellKey).filter((point) => point !== null); if (points.length >= 2) return points; } } } return []; } /** * 把源角色数组 [artifactId, col, row, orientation, extra?] 适配成棋盘单位。 * attackByArtifactId 可按难度记录覆盖源攻击力。 */ function adaptUnitFromSource(character, index, catalog, attackByArtifactId) { if (!Array.isArray(character) || character.length < 4) throw new TypeError("INVALID_SHEEP_CHARACTER"); const artifactId = character[0]; const col = character[1]; const row = character[2]; const orientation = character[3]; const artifact = catalog.getArtifact(artifactId); const footprint = artifact.footprintsByOrientation[String(orientation)]; if (!footprint || !exports.DIRECTIONS[orientation]) { throw new Error("UNKNOWN_ARTIFACT_ORIENTATION:" + artifactId + ":" + orientation); } const extra = character.length >= 5 && character[4] && typeof character[4] === "object" ? deepClone(character[4]) : {}; const attackOverride = attackByArtifactId ? attackByArtifactId[artifactId] : undefined; const attack = Number(attackOverride != null ? attackOverride : artifact.attack); if (!Number.isFinite(attack) || attack < 0) throw new TypeError("INVALID_ARTIFACT_ATTACK:" + artifactId); const speedBuff = findBuff(extra, "speed"); const buffSpeed = Number(speedBuff?.buffParam?.speed); const moveSpeed = Number.isFinite(buffSpeed) && buffSpeed > 0 ? buffSpeed : artifact.moveSpeed; const visual = artifact.visual; const unit = { id: "u-" + String(index + 1).padStart(6, "0"), artifactId, name: artifact.name, col, row, sourceOrientation: orientation, direction: exports.DIRECTIONS[orientation], width: footprint.width, height: footprint.height, occupiedOffsets: footprint.cells.map((cell) => cell.slice()), tags: ["standard", "collisionBomb", "countdownBomb"].includes(artifact.boardBehavior) ? ["chain-move"] : [], moveSpeed, flightSpeed: moveSpeed * exports.FLIGHT_PIXELS_PER_SOURCE_SPEED, attack, artifactName: artifact.name, boardBehavior: artifact.boardBehavior, behaviorParams: deepClone(artifact.behaviorParams || {}), trackEffect: artifact.combatEffect ? deepClone(artifact.combatEffect) : null, sprite: "assets/props/" + artifact.prefabId + ".png", undergroundSprite: artifact.statePrefabIds && artifact.statePrefabIds.underground ? "assets/props/" + artifact.statePrefabIds.underground + ".png" : null, overlaySprite: artifact.overlayPrefabId ? "assets/props/" + artifact.overlayPrefabId + ".png" : null, overlayScale: Number(visual.overlayScale || 0), spriteRotationMode: visual.spriteRotationMode, gameplayAttachmentIds: artifact.overlayPrefabId ? [artifact.overlayPrefabId] : [], spriteForwardOffsetDeg: Number(visual.spriteForwardOffsetDeg || 0), spriteScale: Number(visual.spriteScale || 1), routeScaleMax: visual.routeScaleMax, routeScaleDistanceCells: visual.routeScaleDistanceCells, horizontalRouteOffset: visual.horizontalRouteOffset, canClick: artifact.clickable, requiredForClear: artifact.requiredForClear, createsAttack: artifact.createsAttack, state: "stand", selectionEffectSequence: 0, selectionEffectUntil: 0, sourceExtra: extra, }; if (artifact.boardBehavior === "collisionBomb") { unit.collisionHp = Number(artifact.behaviorParams?.collisionHp || 0); } if (artifact.boardBehavior === "limitedStep") { unit.maximumSteps = Number(artifact.behaviorParams?.maximumSteps || 0); } if (artifact.boardBehavior === "sealedUntilCollision") { unit.sleeping = true; } if (artifact.boardBehavior === "burrowingBlocker") { // 注意:源实现里 some() 与 find() 是两次独立查找,多条同名 buff 时以 find 的第一条为准 const hasPopDownUp = (extra.addBuff || []).some((buff) => buff && buff.buffId === "pop-down-up"); unit.underground = hasPopDownUp && findBuff(extra, "pop-down-up")?.buffParam?.down === true; } if (artifact.boardBehavior === "automaticExit") { unit.automatic = true; } if (artifact.boardBehavior === "movingHazard") { unit.path = extractMovePath(extra); unit.pathProgress = 0; unit.pathDirection = 1; } return unit; } /** * 把源机制物数组 [mechanismId, col, row, orientation, extra?] 适配成 aoe。 * cage 血量按出现顺序依次取 caveHpList(cageCounter 跨调用累计)。 */ function adaptAoeFromSource(entry, index, catalog, caveHpList, cageCounter) { if (!Array.isArray(entry) || entry.length < 4) throw new TypeError("INVALID_SHEEP_AOE"); const mechanismId = entry[0]; const col = entry[1]; const row = entry[2]; const orientation = entry[3]; const extra = entry[4] && typeof entry[4] === "object" ? deepClone(entry[4]) : {}; const mechanism = catalog.getMechanism(mechanismId); const footprint = mechanism.footprintsByOrientation[String(orientation)]; if (!footprint || !exports.DIRECTIONS[orientation]) { throw new Error("UNKNOWN_MECHANISM_ORIENTATION:" + mechanismId + ":" + orientation); } const aoe = { id: "aoe-" + String(index + 1).padStart(4, "0"), mechanismId, name: mechanism.name, boardBehavior: mechanism.boardBehavior, col, row, sourceOrientation: orientation, direction: exports.DIRECTIONS[orientation], width: footprint.width, height: footprint.height, occupiedOffsets: footprint.cells.map((cell) => cell.slice()), active: true, blocksMovement: mechanism.blocksMovement, destructible: mechanism.destructible, prefabPath: catalog.mechanismPrefabPath(mechanismId, orientation), }; if (mechanism.boardBehavior === "cage") { const hp = caveHpList[cageCounter.count] ?? extra.hp ?? mechanism.defaultHp ?? 3; cageCounter.count += 1; aoe.hp = Math.max(0, Number(hp)); aoe.maxHp = aoe.hp; } return aoe; } /** 把单位/aoe(含移动路径点)整体平移 (dx,dy)。 */ function offsetEntities(units, aoes, offset) { const all = [...units, ...aoes]; for (let i = 0; i < all.length; i++) { all[i].col += offset.dx; all[i].row += offset.dy; } for (const unit of units.filter((candidate) => Array.isArray(candidate.path))) { unit.path = unit.path.map((point) => ({ col: point.col + offset.dx, row: point.row + offset.dy, })); } } /** 四邻偏移。 */ const NEIGHBOR_OFFSETS = [ [1, 0], [-1, 0], [0, 1], [0, -1], ]; /** * 组队:把相邻的 teamLeader/teamMember 用洪水填充划成一队, * 然后对每个领队再做一次 BFS,记录成员加入顺序与上级(teamLeaderId)。 */ function assignTeams(units) { const teamUnits = units.filter((unit) => unit.boardBehavior === "teamLeader" || unit.boardBehavior === "teamMember"); const unitByCell = new Map(teamUnits.map((unit) => [unit.col + "," + unit.row, unit])); const visited = new Set(); let teamCounter = 0; for (const seed of teamUnits) { if (visited.has(seed.id)) continue; // 洪水填充出一个连通分量 const component = []; const queue = [seed]; visited.add(seed.id); while (queue.length) { const current = queue.shift(); component.push(current); for (const [dCol, dRow] of NEIGHBOR_OFFSETS) { const neighbor = unitByCell.get(current.col + dCol + "," + (current.row + dRow)); if (neighbor && !visited.has(neighbor.id)) { visited.add(neighbor.id); queue.push(neighbor); } } } const teamId = "goose-team-" + (teamCounter += 1); const leaders = component.filter((unit) => unit.boardBehavior === "teamLeader"); const head = leaders[0] || null; for (const member of component) { member.teamId = teamId; member.teamHeadId = head && head.id; } // 每个领队:BFS 记录成员顺序与直接上级 for (const leader of leaders) { const componentIds = new Set(component.map((unit) => unit.id)); const neighborsOf = (origin) => NEIGHBOR_OFFSETS.map(([dCol, dRow]) => unitByCell.get(origin.col + dCol + "," + (origin.row + dRow))) .filter((unit) => !!unit && componentIds.has(unit.id)); const joinOrder = [leader]; const joined = new Set([leader.id]); const parentById = new Map(); for (let i = 0; i < joinOrder.length; i += 1) { for (const neighbor of neighborsOf(joinOrder[i])) { if (!joined.has(neighbor.id)) { joined.add(neighbor.id); parentById.set(neighbor.id, joinOrder[i].id); joinOrder.push(neighbor); } } } leader.teamMemberIds = joinOrder .slice(1) .filter((unit) => unit.boardBehavior === "teamMember") .map((unit) => unit.id); leader.teamMemberIds.forEach((memberId) => { const member = units.find((unit) => unit.id === memberId); if (member) member.teamLeaderId = parentById.get(memberId) || leader.id; }); } } } /** 给 countdownBomb 单位按"行从大到小、行同列小优先"顺序分配倒计时。 */ function assignCountdownTimers(level, units, difficultyRank = 0) { const boomTimes = Array.isArray(level.progression && level.progression.boomTime) ? level.progression.boomTime.map(Number) : []; units .filter((unit) => unit.boardBehavior === "countdownBomb") .sort((a, b) => b.row - a.row || a.col - b.col) .forEach((unit, index) => { const coolDownBuff = findBuff(unit.sourceExtra, "cool-down"); const sourceDuration = Number(boomTimes[index] ?? coolDownBuff?.buffParam?.duration ?? 180); const difficultyCap = DIFFICULTY_BOMB_DURATION[difficultyRank]; const duration = sourceDuration >= 180 && Number.isFinite(difficultyCap) ? difficultyCap : sourceDuration; unit.timer = { duration: Math.max(0, Number(duration)), remaining: Math.max(0, Number(duration)), started: false, }; }); } /** 摆放校验:单位占位必须在可行走格内且互不重叠。 */ function validateBoardPlacement(board) { const occupiedBy = new Map(); const validSet = new Set(board.validCells); for (const unit of board.units) { for (const cell of occupiedCells(unit)) { if (!validSet.has(cell.col + "," + cell.row)) { throw new Error("SHEEP_UNIT_OUT_OF_BOUNDS:" + board.sourceId + ":" + unit.id); } const cellKey = cell.col + "," + cell.row; if (occupiedBy.has(cellKey)) { throw new Error("SHEEP_UNIT_OVERLAP:" + board.sourceId + ":" + occupiedBy.get(cellKey) + ":" + unit.id); } occupiedBy.set(cellKey, unit.id); } } } /** * 主线关卡适配入口:源关卡 JSON + 内容目录 → 完整棋盘状态。 * 流程:校验 → 适配单位/aoe → 选板定偏移 → 平移 → 组队 → 倒计时 → 组装校验。 */ function adaptLevel(level, catalog, options) { if (!level || !Number.isInteger(level.displayLevel) || !level.sourceId) { throw new TypeError("INVALID_SHEEP_MAINLINE_LEVEL"); } if (!catalog || typeof catalog.getArtifact !== "function" || typeof catalog.getMechanism !== "function") { throw new TypeError("INVALID_YNYK_CONTENT_CATALOG"); } const difficultyRecord = options && (options.difficultyRecord || (options.difficultyConfig ? (0, DataContracts_1.resolveMainlineDifficultyRecord)(options.difficultyConfig, level.displayLevel, level.sourceId, level.sourceUuid) : null)); if (difficultyRecord && (difficultyRecord.displayLevel !== level.displayLevel || difficultyRecord.sourceId !== level.sourceId || difficultyRecord.sourceUuid !== level.sourceUuid)) { throw new TypeError("SHEEP_DIFFICULTY_RECORD_MISMATCH:" + level.displayLevel); } const units = (level.characters || []).map((character, index) => adaptUnitFromSource(character, index, catalog, options && options.attackByArtifactId)); const caveHpList = Array.isArray(level.progression && level.progression.caveDesNum) ? level.progression.caveDesNum.map(Number) : []; const cageCounter = { count: 0 }; const aoes = (level.aoes || []).map((entry, index) => adaptAoeFromSource(entry, index, catalog, caveHpList, cageCounter)); const rotationOffset = Number(options?.boardRotationOffsetDeg || 0); const board = selectBoard(level, units, aoes, options && options.routeData, exports.BOARD_ROTATION_DEG + rotationOffset); offsetEntities(units, aoes, board.offset); assignTeams(units); assignCountdownTimers(level, units, Number(difficultyRecord?.effectiveDifficulty?.rank || 0)); const state = { id: "sheep-mainline-" + level.displayLevel, levelType: "sheep-mainline", displayLevel: level.displayLevel, sceneTitle: options?.sceneTitle || catalog.getSceneForLevel(level.displayLevel).name, sourceId: level.sourceId, sourceUuid: level.sourceUuid, sourcePath: level.sourcePath, title: "第" + level.displayLevel + "关", completionTitle: "第" + level.displayLevel + "关完成", initialHint: "点击军械,沿当前朝向清理解谜棋盘。", geometry: board.geometry, validCells: board.validCells, units, aoes, sourceOffset: deepClone(board.offset), sourceGeometry: { columns: level.width, rows: level.height, }, progression: deepClone(level.progression || {}), sourceRightCharacter: deepClone(level.rightCharacter != null ? level.rightCharacter : null), attackField: "attack", difficultySource: difficultyRecord ? difficultyRecord.difficultySource : null, difficulty: difficultyRecord ? deepClone(difficultyRecord.effectiveDifficulty) : null, combatDifficulty: difficultyRecord ? deepClone(difficultyRecord.computedDifficulty) : null, difficultyReasons: difficultyRecord ? deepClone(difficultyRecord.reasons || []) : [], combatBalance: difficultyRecord ? deepClone(difficultyRecord.combatBalance) : null, }; validateBoardPlacement(state); return state; } exports.default = { DIRECTIONS: exports.DIRECTIONS, REFERENCE_BOARD_WIDTH: exports.REFERENCE_BOARD_WIDTH, REFERENCE_BOARD_HEIGHT: exports.REFERENCE_BOARD_HEIGHT, BOARD_CENTER: exports.BOARD_CENTER, BOARD_ROTATION_DEG: exports.BOARD_ROTATION_DEG, FLIGHT_PIXELS_PER_SOURCE_SPEED: exports.FLIGHT_PIXELS_PER_SOURCE_SPEED, fullRectangleCells, geometryFor, deriveBoard, selectBoard, occupiedCells, adaptLevel, }; }, "assets/Logic/Scripts/DataContracts.ts":function(module,exports,load){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveMainlineDifficultyRecord = exports.assertRouteData = exports.assertRouteBoundaryData = exports.assertMainlineIndex = exports.assertMainlineDifficultyConfig = exports.assertMainlineChunk = void 0; function i(e) { return typeof e == "number" && Number.isFinite(e) && e > 0; } function n(e) { return typeof e == "number" && Number.isFinite(e) && e >= 0 && e <= 1; } function r(e) { var t = e; return Boolean(t) && Number.isFinite(t.x) && Number.isFinite(t.y); } var assertMainlineChunk = function (e, t) { var i = e; if (!i || i.schemaVersion !== 2 || i.chunkId !== t || !Array.isArray(i.levels) || i.levels.length === 0 || i.levels.some(function (e) { return !Number.isInteger(e.displayLevel) || !e.sourceId || !Array.isArray(e.characters) || !Array.isArray(e.aoes) || e.characters.some(function (e) { return !Array.isArray(e) || e.length < 4 || !Number.isInteger(e[0]) || e[0] < 1 || e[0] > 99; }) || e.aoes.some(function (e) { return !Array.isArray(e) || e.length < 4 || !Number.isInteger(e[0]) || e[0] < 100 || e[0] > 199; }); })) throw new TypeError("INVALID_YNYK_CHUNK:" + t); return i; }; exports.assertMainlineChunk = assertMainlineChunk; var assertMainlineDifficultyConfig = function (e) { var t = e, r = t == null ? undefined : t.combatDefaults; if (!(t && t.schemaVersion === 2 && Number.isInteger(t.levelCount) && !(t.levelCount < 1) && t.difficultyTiers && typeof t.difficultyTiers == "object" && r && i(r.minionHpUnit) && i(r.boostSpeedMultiplier) && n(r.openingDistanceRatio) && i(r.openingSpeed) && t.levels && typeof t.levels == "object")) throw new TypeError("INVALID_YNYK_DIFFICULTY_CONFIG"); if (Object.keys(t.levels).length !== t.levelCount) throw new TypeError("INVALID_YNYK_DIFFICULTY_LEVEL_COUNT"); for (var o = 1; o <= t.levelCount; o += 1) { var a = t.levels[String(o)]; if (!a || !t.difficultyTiers[String(a.effectiveDifficultyId)] || !t.difficultyTiers[String(a.computedDifficultyId)] || !i(a.bossHp) || !i(a.minionHpMultiplier) || undefined !== a.minionHpUnit && !i(a.minionHpUnit) || undefined !== a.minionHpStageOffsets && (!Array.isArray(a.minionHpStageOffsets) || a.minionHpStageOffsets.length < 2 || a.minionHpStageOffsets[0] !== 0 || a.minionHpStageOffsets.some(function (e) { return !Number.isInteger(e) || e < 0; })) || !Number.isInteger(a.minionGroupSeed) || a.minionGroupSeed < 0 || !i(a.targetLeaderTime) || !i(a.monsterMoveSpeed) || !n(a.twoStarDamageRatio) || !n(a.threeStarDamageRatio) || a.twoStarDamageRatio > a.threeStarDamageRatio) throw new TypeError("INVALID_YNYK_DIFFICULTY_LEVEL:" + o); } return t; }; exports.assertMainlineDifficultyConfig = assertMainlineDifficultyConfig; var assertMainlineIndex = function (e) { var t = e; if (!t || t.schemaVersion !== 2 || t.groupId !== "100" || !Number.isSafeInteger(t.levelCount) || t.levelCount < 1 || !Array.isArray(t.chunks) || !t.chunks.length || t.chunks.some(function (e, i) { return !e || !/^\d{3}$/.test(e.chunkId) || t.chunks.findIndex(function (chunk) { return chunk.chunkId === e.chunkId; }) !== i || !Number.isInteger(e.firstDisplayLevel) || !Number.isInteger(e.lastDisplayLevel) || e.firstDisplayLevel !== (i ? t.chunks[i - 1].lastDisplayLevel + 1 : 1) || e.lastDisplayLevel < e.firstDisplayLevel || e.lastDisplayLevel > t.levelCount; }) || t.chunks[t.chunks.length - 1].lastDisplayLevel !== t.levelCount) throw new TypeError("主线索引格式或分块范围无效"); return t; }; exports.assertMainlineIndex = assertMainlineIndex; var assertRouteBoundaryData = function (e) { var t, i = e, n = i == null || (t = i.walkable_area) == null ? undefined : t.inner_boundary; if (!Array.isArray(n) || n.length < 3 || n.some(function (e) { return !r(e); })) throw new TypeError("INVALID_YNYK_ROUTE_BOUNDARY"); return i; }; exports.assertRouteBoundaryData = assertRouteBoundaryData; var assertRouteData = function (e) { var t, i, n = e; if (!n || !Array.isArray(n.enemy_path) || n.enemy_path.length < 2 || !Array.isArray((t = n.route) == null || (t = t.enemy_path) == null ? undefined : t.points) || n.enemy_path.some(function (e) { return !r(e); }) || n.route.enemy_path.points.length < 2 || n.route.enemy_path.points.some(function (e) { return !r(e); }) || !Array.isArray((i = n.walkable_area) == null ? undefined : i.inner_boundary) || n.walkable_area.inner_boundary.length < 3 || n.walkable_area.inner_boundary.some(function (e) { return !r(e); })) throw new TypeError("INVALID_YNYK_ROUTE"); return n; }; exports.assertRouteData = assertRouteData; var resolveMainlineDifficultyRecord = function (e, t, i, n) { var r, o = e.levels[String(t)]; if (!o) throw new TypeError("YNYK_DIFFICULTY_LEVEL_NOT_FOUND:" + t); var a = e.difficultyTiers[String(o.effectiveDifficultyId)], l = e.difficultyTiers[String(o.computedDifficultyId)]; if (!a || !l) throw new TypeError("YNYK_DIFFICULTY_TIER_NOT_FOUND:" + t); var s = e.combatDefaults, u = (r = o.minionHpUnit) != null ? r : s.minionHpUnit, c = { displayLevel: t, sourceId: i, sourceUuid: n, difficultySource: null, effectiveDifficulty: { id: "ui_" + o.effectiveDifficultyId, label: a, rank: o.effectiveDifficultyId }, computedDifficulty: { id: "ui_" + o.computedDifficultyId, label: l, rank: o.computedDifficultyId }, reasons: [], combatBalance: { bossHp: o.bossHp, maxReachableBossDamage: o.bossHp, bossDamageBudget: o.bossHp, minionHpUnit: u, initialMinionHpMultiplier: o.minionHpMultiplier, initialMinionHp: u * o.minionHpMultiplier, minionGroupSeed: o.minionGroupSeed, targetLeaderTime: o.targetLeaderTime, boostSpeedMultiplier: s.boostSpeedMultiplier, openingDistanceRatio: s.openingDistanceRatio, openingSpeed: s.openingSpeed, difficultySpeed: o.monsterMoveSpeed, starDamageThresholds: { two: o.twoStarDamageRatio, three: o.threeStarDamageRatio } } }; undefined !== o.minionHpStageOffsets && (c.combatBalance.minionHpStageOffsets = o.minionHpStageOffsets.slice()); return c; }; exports.resolveMainlineDifficultyRecord = resolveMainlineDifficultyRecord; ({ "assertMainlineChunk": assertMainlineChunk, "assertMainlineDifficultyConfig": assertMainlineDifficultyConfig, "assertMainlineIndex": assertMainlineIndex, "assertRouteBoundaryData": assertRouteBoundaryData, "assertRouteData": assertRouteData, "resolveMainlineDifficultyRecord": resolveMainlineDifficultyRecord }); }, "assets/Logic/Scripts/BoardLayoutOptimizer.ts":function(module,exports,load){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.optimizeLevel = exports.fitBoardToBoundary = exports.analyzePadding = void 0; // Evidence-derived module. Babel class/type recovery is tracked in recovery/scripts-manifest.json. const rollupPluginModLoBabelHelpers_1 = load("assets/Scripts/Scripts/rollupPluginModLoBabelHelpers.ts"); const LevelAdapter_1 = load("assets/Logic/Scripts/LevelAdapter.ts"); const BoardRules_1 = load("assets/Logic/Scripts/BoardRules.ts"); var analyzePadding = g; exports.analyzePadding = analyzePadding; var fitBoardToBoundary = p; exports.fitBoardToBoundary = fitBoardToBoundary; var optimizeLevel = w; exports.optimizeLevel = optimizeLevel; ({ "analyzePadding": analyzePadding, "fitBoardToBoundary": fitBoardToBoundary, "optimizeLevel": optimizeLevel }); var a = 1e-9; function l(e) { return JSON.parse(JSON.stringify(e)); } function s(e, t) { for (var i = false, n = 0, r = t.length - 1; n < t.length; r = n, n += 1) { var o = t[r], l = t[n]; if (c = o, d = l, h = undefined, h = ((u = e).x - c.x) * (d.y - c.y) - (u.y - c.y) * (d.x - c.x), !(Math.abs(h) > a) && u.x >= Math.min(c.x, d.x) - a && u.x <= Math.max(c.x, d.x) + a && u.y >= Math.min(c.y, d.y) - a && u.y <= Math.max(c.y, d.y) + a) return true; if (o.y > e.y != l.y > e.y) { var s = (l.x - o.x) * (e.y - o.y) / (l.y - o.y) + o.x; e.x < s && (i = !i); } } var u, c, d, h; return i; } function u(e, t, i) { var n = Number(e.rotationDeg || 0) * Math.PI / 180, r = Math.cos(n), o = Math.sin(n), a = (t - e.columns / 2) * e.cellSize, l = a + e.cellSize, s = (i - e.rows / 2) * e.cellSize, u = s + e.cellSize; return [[a, s], [l, s], [l, u], [a, u]].map(function (t) { var i = t[0], n = t[1]; return { x: e.center.x + i * r - n * o, y: e.center.y + i * o + n * r }; }); } function c(e) { return (e.occupiedOffsets || []).map(function (t) { var i = t[0], n = t[1]; return { col: Number(e.col) + i, row: Number(e.row) + n }; }); } function d(e, t) { for (var n, r = [].concat(e, t).flatMap(c), o = (0, rollupPluginModLoBabelHelpers_1.createForOfIteratorHelperLoose)(e.filter(function (e) { return Array.isArray(e.path); })); !(n = o()).done;) for (var a = n.value, l = function () { for (var e = Number(a.path[s].col), t = Number(a.path[s].row), i = a.path[s + 1], n = 0; n < 1024 && (r.push.apply(r, a.occupiedOffsets.map(function (i) { var n = i[0], r = i[1]; return { col: e + n, row: t + r }; })), e !== i.col || t !== i.row); n += 1) { var o = Math.sign(Number(i.col) - e), l = o === 0 ? Math.sign(Number(i.row) - t) : 0; e += o; t += l; } }, s = 0; s < a.path.length - 1; s += 1) l(); return r; } function h(e, t, i) { return t.every(function (t) { return u(e, t.col, t.row).every(function (e) { return s(e, i); }); }); } function f(e, i, n, o, a, s, u) { var c, h, f = d(i, n); if (f.some(function (e) { return !Number.isInteger(e.col) || !Number.isInteger(e.row) || e.col < 0 || e.row < 0 || e.col >= o || e.row >= a; })) return null; var v = p({ columns: o, rows: a, center: l(u), cellSize: 0, rotationDeg: Number((c = (h = e.geometry) == null ? undefined : h.rotationDeg) != null ? c : LevelAdapter_1.default.BOARD_ROTATION_DEG) }, f, s); return v ? (0, rollupPluginModLoBabelHelpers_1.extends)({}, v, { units: i, aoes: n }) : null; } function p(e, i, n) { if (!i.length || n.length < 3) return null; var r = (0, rollupPluginModLoBabelHelpers_1.extends)({}, e, { center: (0, rollupPluginModLoBabelHelpers_1.extends)({}, e.center) }); r.cellSize = function (e, t, i) { for (var n = 0, r = 64, o = 0; o < 24; o += 1) { var a = (n + r) / 2; e.cellSize = a; h(e, t, i) ? n = a : r = a; } return Math.max(1, n - .25); }(r, i, n); var o = function (e, t) { for (var i = [], n = 0; n < e.rows; n += 1) for (var r = 0; r < e.columns; r += 1) u(e, r, n).every(function (e) { return s(e, t); }) && i.push(r + "," + n); return i; }(r, n), a = new Set(o); return i.some(function (e) { return !a.has(e.col + "," + e.row); }) ? null : { geometry: r, validCells: o }; } function v(e, i) { return (0, rollupPluginModLoBabelHelpers_1.extends)({}, l(e), { geometry: i.geometry, validCells: i.validCells, units: i.units, aoes: i.aoes, sourceOffset: { dx: 0, dy: 0 } }); } function g(e) { var t, i, n, r, o, a, l, s, u = Number((e == null || (t = e.sourceGeometry) == null ? undefined : t.columns) || (e == null || (i = e.geometry) == null ? undefined : i.columns) || 0), c = Number((e == null || (n = e.sourceGeometry) == null ? undefined : n.rows) || (e == null || (r = e.geometry) == null ? undefined : r.rows) || 0), d = Number((e == null || (o = e.geometry) == null ? undefined : o.columns) || u), h = Number((e == null || (a = e.geometry) == null ? undefined : a.rows) || c), f = Math.max(0, d - u), p = Math.max(0, h - c), v = Math.max(0, Math.min(f, Number((e == null || (l = e.sourceOffset) == null ? undefined : l.dx) || 0))), g = Math.max(0, Math.min(p, Number((e == null || (s = e.sourceOffset) == null ? undefined : s.dy) || 0))); return { sourceColumns: u, sourceRows: c, adaptedColumns: d, adaptedRows: h, leftColumns: v, rightColumns: f - v, bottomRows: g, topRows: p - g, isLarge: f >= 2 || p >= 2 }; } function m(e) { var t = (e == null ? undefined : e.collision) || {}; return { type: (e == null ? undefined : e.type) || null, direction: (e == null ? undefined : e.direction) || null, reverseDirection: (e == null ? undefined : e.reverseDirection) || null, unitIds: (t.units || []).map(function (e) { return e.id; }).sort(), aoeIds: (t.aoes || []).map(function (e) { return e.id; }).sort(), fenceIds: ((e == null ? undefined : e.fenceIds) || []).slice().sort() }; } function y(e) { return (0, rollupPluginModLoBabelHelpers_1.extends)({}, e, { units: l(e.units || []), aoes: l(e.aoes || []), validCellSet: new Set(e.validCells || []) }); } function b(e, t) { var r = y(e), a = y(t); for (const s of r.units) { var u = BoardRules_1.default.planMove(r, s.id), c = BoardRules_1.default.planMove(a, s.id); if (JSON.stringify(m(u)) !== JSON.stringify(m(c))) return false; if (s.boardBehavior === "automaticExit") { var d = BoardRules_1.default.findAutomaticExitPath(r, s.id), h = BoardRules_1.default.findAutomaticExitPath(a, s.id); if (Boolean(d) !== Boolean(h)) return false; if (d && h && d.direction !== h.direction) return false; } } return true; } function w(e, t) { var n, o, a, s, u; if ((e == null ? undefined : e.levelType) !== "sheep-mainline") return e; var c = Number((n = e.sourceGeometry) == null ? undefined : n.columns), p = Number((o = e.sourceGeometry) == null ? undefined : o.rows); if (!Number.isInteger(c) || !Number.isInteger(p) || c <= 0 || p <= 0) return e; var g = t == null || (a = t.walkable_area) == null ? undefined : a.inner_boundary; if (!Array.isArray(g) || g.length < 3) return e; var m = function (e) { for (var t, n, r = l(e.units || []), o = l(e.aoes || []), a = Number(((t = e.sourceOffset) == null ? undefined : t.dx) || 0), s = Number(((n = e.sourceOffset) == null ? undefined : n.dy) || 0), u = 0, c = [].concat(r, o); u < c.length; u++) { var d = c[u]; d.col -= a; d.row -= s; } for (const p of r.filter(function (e) { return Array.isArray(e.path); })) { p.path = p.path.map(function (e) { return { col: e.col - a, row: e.row - s }; }); } return { units: r, aoes: o }; }(e), y = m.units, w = m.aoes, S = f(e, y, w, c, p, g, LevelAdapter_1.default.BOARD_CENTER), I = function (t) { var i; if (!t || t.geometry.cellSize <= Number(((i = S) == null || (i = i.geometry) == null ? undefined : i.cellSize) || 0)) return false; var n = v(e, t); return !!b(e, n) && (S = t, true); }; if (Number(((s = S) == null || (s = s.geometry) == null ? undefined : s.cellSize) || 0) < 38) { var C = d(y, w); for (const M of function () { for (var e = [], t = 1; t <= 2; t += 1) for (var i = -t; i <= t; i += 1) for (var n = -t; n <= t; n += 1) Math.max(Math.abs(n), Math.abs(i)) === t && e.push({ x: 8 * n, y: 8 * i }); return e; }()) { { var T, R, x, P = M, A = { x: LevelAdapter_1.default.BOARD_CENTER.x + P.x, y: LevelAdapter_1.default.BOARD_CENTER.y + P.y }; if (h({ columns: c, rows: p, center: A, cellSize: 38, rotationDeg: Number((T = (R = e.geometry) == null ? undefined : R.rotationDeg) != null ? T : LevelAdapter_1.default.BOARD_ROTATION_DEG) }, C, g) && (I(f(e, y, w, c, p, g, A)), Number(((x = S) == null || (x = x.geometry) == null ? undefined : x.cellSize) || 0) >= 38)) break; } } } if (!S || S.geometry.cellSize <= 1.02 * Number(((u = e.geometry) == null ? undefined : u.cellSize) || 0)) return e; var E = v(e, S); return b(e, E) ? E : e; } var Exportdefault = { analyzePadding: g, optimizeLevel: w }; exports.default = Exportdefault; }, "assets/Logic/Scripts/BoardRules.ts":function(module,exports,load){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getBoardOccupancyStatsForTests = exports.BoardOccupancyIndex = exports.OPPOSITE = exports.STEPS = void 0; exports.key = key; exports.occupiedCells = occupiedCells; exports.inside = inside; exports.collisionAtInto = collisionAtInto; exports.collisionAt = collisionAt; exports.allOutside = allOutside; exports.findAutomaticExitPath = findAutomaticExitPath; exports.planMove = planMove; exports.planFenceTraversal = planFenceTraversal; exports.applyMove = applyMove; /** 四方向单位步进。 */ exports.STEPS = Object.freeze({ north: Object.freeze({ col: 0, row: -1 }), east: Object.freeze({ col: 1, row: 0 }), south: Object.freeze({ col: 0, row: 1 }), west: Object.freeze({ col: -1, row: 0 }), }); /** 反向映射。 */ exports.OPPOSITE = Object.freeze({ north: "south", south: "north", east: "west", west: "east", }); /** 未提供 occupiedOffsets 时按单格处理。 */ const SINGLE_CELL_OFFSET = Object.freeze([Object.freeze([0, 0])]); /** "col,row" 字符串键。 */ function key(col, row) { return col + "," + row; } /** 实体在指定锚点(默认自身 col/row)下的全部占位格。 */ function occupiedCells(entity, baseCol = entity.col, baseRow = entity.row) { return entity.occupiedOffsets.map((offset) => ({ col: baseCol + offset[0], row: baseRow + offset[1], })); } /** 把 (col,row) 编码成单个数字键(偏移 32768 避免负数)。 */ function encodeCellKey(col, row) { return 65536 * (col + 32768) + row + 32768; } /** encodeCellKey 的逆运算。 */ function decodeCellKey(cellKey) { return { col: Math.floor(cellKey / 65536) - 32768, row: cellKey - 65536 * Math.floor(cellKey / 65536) - 32768, }; } /** validCells 解析缓存:按棋盘对象弱引用,源或规模变化时重建。 */ const validCellCache = new WeakMap(); /** 格子是否落在棋盘可行走范围内。 */ function cellInsideBoard(board, col, row) { const validSource = board.validCellSet instanceof Set ? board.validCellSet : Array.isArray(board.validCells) ? board.validCells : null; if (validSource) { const sourceSize = validSource instanceof Set ? validSource.size : validSource.length; let cached = validCellCache.get(board); if (!cached || cached.source !== validSource || cached.size !== sourceSize) { const cells = cached?.cells || new Set(); cells.clear(); for (const cellKey of validSource) { const commaIndex = cellKey.indexOf(","); if (commaIndex >= 0) { cells.add(encodeCellKey(Number(cellKey.slice(0, commaIndex)), Number(cellKey.slice(commaIndex + 1)))); } } cached = { source: validSource, size: sourceSize, cells }; validCellCache.set(board, cached); } return cached.cells.has(encodeCellKey(col, row)); } return col >= 0 && row >= 0 && col < board.geometry.columns && row < board.geometry.rows; } /** pos 是否在棋盘内。 */ function inside(board, pos) { return cellInsideBoard(board, pos.col, pos.row); } /** build 调用计数(仅测试统计用)。 */ let occupancyBuildCount = 0; /** * 棋盘占位索引:把单位/aoe 的占位格映射到桶数组, * 支撑碰撞查询 O(占位格数)。桶用池复用,避免频繁分配。 */ class BoardOccupancyIndex { constructor() { this.state = null; this.unitCells = new Map(); this.aoeCells = new Map(); this.unitBucketPool = []; this.aoeBucketPool = []; } /** 重建索引:跳过已离场/入地/被魅惑牵头的单位与不可阻挡的 aoe。 */ build(board) { this.state = board; this.releaseBuckets(this.unitCells, this.unitBucketPool); this.releaseBuckets(this.aoeCells, this.aoeBucketPool); occupancyBuildCount += 1; for (let i = 0; i < board.units.length; i += 1) { const unit = board.units[i]; if (unit.state !== "exited" && unit.state !== "removed" && !unit.underground && !unit.charmLeaderId) { this.addEntity(this.unitCells, this.unitBucketPool, unit); } } const aoes = board.aoes || []; for (let i = 0; i < aoes.length; i += 1) { const aoe = aoes[i]; if (aoe.active && aoe.blocksMovement) this.addEntity(this.aoeCells, this.aoeBucketPool, aoe); } return this; } /** 查询 unit 位于 (col,row) 时与谁相撞,结果写入 out 并返回。 */ query(unit, col, row, ignoredUnitIds, out) { out.units.length = 0; out.aoes.length = 0; const offsets = unit.occupiedOffsets || SINGLE_CELL_OFFSET; for (let i = 0; i < offsets.length; i += 1) { const cellCol = col + offsets[i][0]; const cellRow = row + offsets[i][1]; if (cellInsideBoard(this.state, cellCol, cellRow)) { const cellKey = encodeCellKey(cellCol, cellRow); const unitBucket = this.unitCells.get(cellKey); if (unitBucket) { for (let j = 0; j < unitBucket.length; j += 1) { const other = unitBucket[j]; if (other.id !== unit.id && !(ignoredUnitIds != null && ignoredUnitIds.has(other.id))) { this.appendUnique(out.units, other); } } } const aoeBucket = this.aoeCells.get(cellKey); if (aoeBucket) { for (let j = 0; j < aoeBucket.length; j += 1) this.appendUnique(out.aoes, aoeBucket[j]); } } } return out; } /** 单位从 (fromCol,fromRow) 移到其当前 col/row 后刷新索引。 */ moveUnit(unit, fromCol, fromRow) { this.removeEntityAt(this.unitCells, this.unitBucketPool, unit, fromCol, fromRow); if (unit.state !== "exited" && unit.state !== "removed" && !unit.underground && !unit.charmLeaderId) { this.addEntity(this.unitCells, this.unitBucketPool, unit); } } removeUnit(unit) { this.removeEntity(this.unitCells, this.unitBucketPool, unit); } updateAoe(aoe) { this.removeEntity(this.aoeCells, this.aoeBucketPool, aoe); if (aoe.active && aoe.blocksMovement) this.addEntity(this.aoeCells, this.aoeBucketPool, aoe); } clear() { this.state = null; this.releaseBuckets(this.unitCells, this.unitBucketPool); this.releaseBuckets(this.aoeCells, this.aoeBucketPool); } addEntity(cells, pool, entity) { const offsets = entity.occupiedOffsets || SINGLE_CELL_OFFSET; for (let i = 0; i < offsets.length; i += 1) { const cellKey = encodeCellKey(entity.col + offsets[i][0], entity.row + offsets[i][1]); let bucket = cells.get(cellKey); if (!bucket) { bucket = pool.pop() || []; cells.set(cellKey, bucket); } bucket.push(entity); } } removeEntityAt(cells, pool, entity, col, row) { const offsets = entity.occupiedOffsets || SINGLE_CELL_OFFSET; for (let i = 0; i < offsets.length; i += 1) { const cellKey = encodeCellKey(col + offsets[i][0], row + offsets[i][1]); const bucket = cells.get(cellKey); if (bucket) { this.removeFromBucket(bucket, entity); if (bucket.length === 0) { cells.delete(cellKey); pool.push(bucket); } } } } removeEntity(cells, pool, entity) { for (const [cellKey, bucket] of cells) { this.removeFromBucket(bucket, entity); if (bucket.length === 0) { cells.delete(cellKey); pool.push(bucket); } } } /** 桶内按引用删除(手写移位,保持原实现的删除顺序语义)。 */ removeFromBucket(bucket, entity) { for (let i = bucket.length - 1; i >= 0; i -= 1) { if (bucket[i] === entity) { for (let j = i + 1; j < bucket.length; j += 1) bucket[j - 1] = bucket[j]; bucket.length -= 1; } } } releaseBuckets(cells, pool) { for (const bucket of cells.values()) { bucket.length = 0; pool.push(bucket); } cells.clear(); } appendUnique(list, entity) { for (let i = 0; i < list.length; i += 1) if (list[i].id === entity.id) return; list.push(entity); } } exports.BoardOccupancyIndex = BoardOccupancyIndex; /** * 碰撞查询(写入 outResult)。 * 额外处理 Boss 技能 shuffleAndFlipRegion 的锁区:单位未锁定目标且 * 占位与目标区域重叠时,注入一个伪 aoe 阻挡移动。 */ function collisionAtInto(board, unit, col, row, ignoredUnitIds, occupancyIndex, outResult) { const result = occupancyIndex.query(unit, col, row, ignoredUnitIds, outResult); const bossSkill = board?.bossSkill; const lockRegion = bossSkill?.phase === "casting" && bossSkill.skillId === "shuffleAndFlipRegion" ? bossSkill.targetRegion : null; if (lockRegion && !(unit != null && unit.bossSkillTargetLocked)) { const offsets = unit?.occupiedOffsets || SINGLE_CELL_OFFSET; const overlapsRegion = offsets.some((offset) => { const cellCol = col + offset[0]; const cellRow = row + offset[1]; return cellCol >= lockRegion.col && cellCol < lockRegion.col + lockRegion.columns && cellRow >= lockRegion.row && cellRow < lockRegion.row + lockRegion.rows; }); if (overlapsRegion) { // 伪 aoe:只有阻挡语义,无实体数据 result.aoes.push({ id: "boss-skill-region-lock", boardBehavior: "bossSkillRegionLock", blocksMovement: true, }); } } return result; } /** 碰撞查询(可复用外部索引与结果对象,否则临时新建)。 */ function collisionAt(board, unit, col, row, ignoredUnitIds = null, occupancyIndex = null, outResult = null) { return collisionAtInto(board, unit, col, row, ignoredUnitIds, occupancyIndex || new BoardOccupancyIndex().build(board), outResult || { units: [], aoes: [] }); } /** 实体的全部占位格都在棋盘外(即已完全离场)。 */ function allOutside(board, entity, col, row) { const offsets = entity.occupiedOffsets || SINGLE_CELL_OFFSET; for (let i = 0; i < offsets.length; i += 1) { if (cellInsideBoard(board, col + offsets[i][0], row + offsets[i][1])) return false; } return true; } /** 实体能否整体落在 (col,row):全格在界内且无碰撞。 */ function canOccupy(board, unit, col, row, occupancyIndex, outResult) { const offsets = unit.occupiedOffsets || SINGLE_CELL_OFFSET; for (let i = 0; i < offsets.length; i += 1) { if (!cellInsideBoard(board, col + offsets[i][0], row + offsets[i][1])) return false; } const collision = collisionAtInto(board, unit, col, row, null, occupancyIndex, outResult); return collision.units.length === 0 && collision.aoes.length === 0; } /** 从 (col,row) 沿 direction 直线探测离场路径,撞墙返回 null。 */ function findExitPathFrom(board, unit, col, row, direction, occupancyIndex, outResult) { const step = exports.STEPS[direction]; if (!step) return null; const path = []; const maxSteps = Math.max(2, unit.width || 1, unit.height || 1) + 2; for (let distance = 1; distance <= maxSteps; distance += 1) { const nextCol = col + step.col * distance; const nextRow = row + step.row * distance; const collision = collisionAtInto(board, unit, nextCol, nextRow, null, occupancyIndex, outResult); if (collision.units.length || collision.aoes.length) return null; path.push({ col: nextCol, row: nextRow }); if (allOutside(board, unit, nextCol, nextRow)) return path; } return null; } /** * 为 automaticExit 单位 BFS 一条离场路径: * 优先沿当前朝向,其次东/西/北/南(去重后的顺序)。 */ function findAutomaticExitPath(board, unitId) { const unit = board.units.find((candidate) => candidate.id === unitId); if (!unit || unit.state === "exited" || unit.state === "removed" || unit.lockedByCage) return null; const start = { col: unit.col, row: unit.row }; const startKey = encodeCellKey(start.col, start.row); const queue = [start]; const cameFrom = new Map([[startKey, null]]); const directions = [unit.direction, ...["east", "west", "north", "south"]].filter((dir, index, all) => exports.STEPS[dir] && all.indexOf(dir) === index); const occupancyIndex = new BoardOccupancyIndex().build(board); const outResult = { units: [], aoes: [] }; for (let head = 0; head < queue.length; head += 1) { const current = queue[head]; const currentKey = encodeCellKey(current.col, current.row); // 先试每个方向能否直接离场 for (const direction of directions) { const exitTail = findExitPathFrom(board, unit, current.col, current.row, direction, occupancyIndex, outResult); if (exitTail) { const pathSoFar = []; let cursor = currentKey; while (cursor != null) { pathSoFar.push(decodeCellKey(cursor)); cursor = cameFrom.get(cursor) ?? null; } pathSoFar.reverse(); return { type: "exit-path", unitId, direction, steps: pathSoFar.length + exitTail.length - 1, path: [...pathSoFar, ...exitTail], }; } } // 再扩展可整体落入的相邻格 for (const direction of directions) { const step = exports.STEPS[direction]; const next = { col: current.col + step.col, row: current.row + step.row }; const nextKey = encodeCellKey(next.col, next.row); if (!cameFrom.has(nextKey) && canOccupy(board, unit, next.col, next.row, occupancyIndex, outResult)) { cameFrom.set(nextKey, currentKey); queue.push(next); } } } return null; } /** 把栅栏命中记录包装成 break-fence 结果;无命中时原样返回。 */ function attachFenceHits(plan, unitId, direction, fenceHits) { if (!fenceHits || !fenceHits.length) return plan; const fenceIds = []; for (let i = 0; i < fenceHits.length; i += 1) { for (let j = 0; j < fenceHits[i].fenceIds.length; j += 1) fenceIds.push(fenceHits[i].fenceIds[j]); } return { type: "break-fence", unitId, direction, steps: Number(plan.steps || 0), col: plan.col, row: plan.row, finalType: plan.type, stepsBeforeFence: fenceHits[0].step - 1, fenceIds, fenceHits, }; } /** * 点击单位的移动计划:沿朝向直行,撞到东西为止。 * limitedStep 行为限制最大步数;fenceBreaker 撞纯栅栏直接破栏; * bounceBack 行为撞后反向。 */ function planMove(board, unitId, options = null) { const unit = board.units.find((candidate) => candidate.id === unitId); if (!unit || unit.state === "exited" || unit.state === "removed") return { type: "missing", unitId }; if (!unit.canClick) return { type: "not-clickable", unitId }; if (unit.lockedByCage) return { type: "locked-by-cage", unitId }; if (unit.sleeping) return { type: "sleeping", unitId }; const direction = options?.direction || unit.direction; const step = exports.STEPS[direction]; if (!step) return { type: "invalid-direction", unitId }; const maxSteps = unit.boardBehavior === "limitedStep" ? Math.max(0, Number(unit.maximumSteps || unit.behaviorParams?.maximumSteps || 0)) : 512; const occupancyIndex = options?.occupancyIndex || new BoardOccupancyIndex().build(board); const outResult = options?.collisionResult || { units: [], aoes: [] }; let lastFreeCol = unit.col; let lastFreeRow = unit.row; let lastFreeSteps = 0; for (let distance = 1; distance <= maxSteps; distance += 1) { const targetCol = unit.col + step.col * distance; const targetRow = unit.row + step.row * distance; if (allOutside(board, unit, targetCol, targetRow)) { return { type: "exit", unitId, direction, steps: distance }; } const collision = collisionAtInto(board, unit, targetCol, targetRow, options?.ignoredUnitIds, occupancyIndex, outResult); if (collision.aoes.length) { const fences = collision.aoes.filter((aoe) => aoe.boardBehavior === "fence"); if (unit.boardBehavior === "fenceBreaker" && fences.length === collision.aoes.length) { return { type: "break-fence", unitId, direction, stepsBeforeFence: distance - 1, fenceIds: fences.map((fence) => fence.id), }; } } if (collision.units.length || collision.aoes.length) { if (unit.boardBehavior === "bounceBack") { return { type: "bounce", unitId, direction, reverseDirection: exports.OPPOSITE[direction], travelledSteps: distance - 1, collision, }; } return lastFreeSteps > 0 ? { type: "move", unitId, direction, col: lastFreeCol, row: lastFreeRow, steps: lastFreeSteps, collision } : { type: "blocked", unitId, direction, collision }; } lastFreeCol = targetCol; lastFreeRow = targetRow; lastFreeSteps = distance; } return lastFreeSteps > 0 ? { type: "move", unitId, direction, col: lastFreeCol, row: lastFreeRow, steps: lastFreeSteps } : { type: "blocked", unitId, direction }; } /** * fenceBreaker 的穿栏移动计划:栅栏可连续穿过(同栏不重复计), * 撞到非栅栏障碍或离场时收尾,并附带全部破栏记录。 */ function planFenceTraversal(board, unitId, options = null) { const unit = board.units.find((candidate) => candidate.id === unitId); if (!unit || unit.state === "exited" || unit.state === "removed" || unit.boardBehavior !== "fenceBreaker") { return { type: "missing", unitId }; } const direction = options?.direction || unit.direction; const step = exports.STEPS[direction]; if (!step) return { type: "invalid-direction", unitId }; const occupancyIndex = options?.occupancyIndex || new BoardOccupancyIndex().build(board); const outResult = options?.collisionResult || { units: [], aoes: [] }; const brokenFenceIds = new Set(); const fenceHits = []; let lastFreeCol = unit.col; let lastFreeRow = unit.row; let lastFreeSteps = 0; for (let distance = 1; distance <= 512; distance += 1) { const targetCol = unit.col + step.col * distance; const targetRow = unit.row + step.row * distance; if (allOutside(board, unit, targetCol, targetRow)) { return attachFenceHits({ type: "exit", unitId, direction, steps: distance }, unitId, direction, fenceHits); } const collision = collisionAtInto(board, unit, targetCol, targetRow, options?.ignoredUnitIds, occupancyIndex, outResult); const newBlockingAoes = collision.aoes.filter((aoe) => !brokenFenceIds.has(aoe.id)); if (!collision.units.length && newBlockingAoes.length) { const newFences = newBlockingAoes.filter((aoe) => aoe.boardBehavior === "fence"); if (newFences.length === newBlockingAoes.length) { const hitIds = []; for (let i = 0; i < newFences.length; i += 1) { brokenFenceIds.add(newFences[i].id); hitIds.push(newFences[i].id); } if (hitIds.length) fenceHits.push({ step: distance, fenceIds: hitIds }); } } const stillBlocking = newBlockingAoes.filter((aoe) => !brokenFenceIds.has(aoe.id)); if (collision.units.length || stillBlocking.length) { return attachFenceHits(lastFreeSteps > 0 ? { type: "move", unitId, direction, col: lastFreeCol, row: lastFreeRow, steps: lastFreeSteps, collision } : { type: "blocked", unitId, direction, collision }, unitId, direction, fenceHits); } lastFreeCol = targetCol; lastFreeRow = targetRow; lastFreeSteps = distance; } return attachFenceHits(lastFreeSteps > 0 ? { type: "move", unitId, direction, col: lastFreeCol, row: lastFreeRow, steps: lastFreeSteps } : { type: "blocked", unitId, direction }, unitId, direction, fenceHits); } /** 把移动计划落地到棋盘状态(move 改坐标 / exit 置离场 / bounce 换向)。 */ function applyMove(board, plan) { const unit = board.units.find((candidate) => candidate.id === plan.unitId); if (!unit) return plan; if (plan.type === "move") { unit.col = plan.col; unit.row = plan.row; } else if (plan.type === "exit") { unit.state = "exited"; } else if (plan.type === "bounce") { unit.direction = plan.reverseDirection; } else if (plan.type === "break-fence") { return plan; } return plan; } /** 测试用:占位索引 build 次数统计。 */ const getBoardOccupancyStatsForTests = function () { return { buildCount: occupancyBuildCount }; }; exports.getBoardOccupancyStatsForTests = getBoardOccupancyStatsForTests; exports.default = { STEPS: exports.STEPS, OPPOSITE: exports.OPPOSITE, key, occupiedCells, inside, allOutside, collisionAt, findAutomaticExitPath, planMove, planFenceTraversal, applyMove, }; }, "assets/Framework/Scripts/MainlineLevelOrder.ts":function(module,exports,load){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CONTENT_SOURCE_LEVELS = exports.MAINLINE_LEVEL_COUNT = exports.PREVIOUS_MAINLINE_SOURCE_LEVELS = exports.MAINLINE_SOURCE_LEVELS = exports.PREVIOUS_REMOVED_MAINLINE_LEVELS = exports.MAINLINE_TEMPLATE_SOURCES = void 0; exports.configureMainlineSequence = configureMainlineSequence; exports.contentDisplayLevel = contentDisplayLevel; exports.mainlineDisplayLevel = mainlineDisplayLevel; exports.mainlineUnlockLevel = mainlineUnlockLevel; exports.mapMainlineUnlockLevel = mapMainlineUnlockLevel; exports.remapMainlineRecords = remapMainlineRecords; exports.remapMainlineIndex = remapMainlineIndex; exports.remapContentUnlocks = remapContentUnlocks; // 启动前的兼容初值;正式启动和工具读取均由 LevelSequence.json 覆盖。 exports.MAINLINE_TEMPLATE_SOURCES = {}; exports.PREVIOUS_REMOVED_MAINLINE_LEVELS = new Set([ 90, 103, 120, 144, 152, 160, 175, 185, 202, 210, 225, 240, 253, 272, 291, 310, 329, 348, 360, 374, 388, 413, 427, 445, 462, 472, 477, 490, 506, 521, 534, 547, 558, 570, 599, 605, 635, 649, 662, 676, 687, 705, 727, 739, 753, 767, 778, 794, 808, 819, 832, 849, 866, 881, 894, 917, 930, 944, 958, 973, 981, 995, 1010, 1018, 1034, 1041, 1052, ]); exports.MAINLINE_SOURCE_LEVELS = Object.freeze(Array.from({ length: 1070 }, (_, index) => index + 1)); exports.PREVIOUS_MAINLINE_SOURCE_LEVELS = Object.freeze(Array.from({ length: 1070 }, (_, index) => index + 1).filter((level) => !exports.PREVIOUS_REMOVED_MAINLINE_LEVELS.has(level))); exports.MAINLINE_LEVEL_COUNT = exports.MAINLINE_SOURCE_LEVELS.length; // 主线之外的来源追加在内部读取序列末尾,供逐鹿继续读取;不计入主线关数。 exports.CONTENT_SOURCE_LEVELS = exports.MAINLINE_SOURCE_LEVELS; function configureMainlineSequence(order, templates, sourceCount = order.length) { exports.MAINLINE_SOURCE_LEVELS = Object.freeze([...order]); exports.MAINLINE_TEMPLATE_SOURCES = Object.freeze({ ...templates }); exports.MAINLINE_LEVEL_COUNT = order.length; const active = new Set(order); exports.CONTENT_SOURCE_LEVELS = Object.freeze([ ...order, ...Array.from({ length: sourceCount }, (_, i) => i + 1).filter((id) => !active.has(id)), ]); } function contentDisplayLevel(source) { const index = exports.CONTENT_SOURCE_LEVELS.indexOf(source); if (index < 0) throw new Error("关卡来源不存在:" + source); return index + 1; } function mainlineDisplayLevel(source) { const index = exports.MAINLINE_SOURCE_LEVELS.indexOf(source); if (index < 0) throw new Error("主线来源关卡不存在:" + source); return index + 1; } function mainlineUnlockLevel(sourceLevel) { return mapMainlineUnlockLevel(sourceLevel, exports.MAINLINE_SOURCE_LEVELS, exports.MAINLINE_TEMPLATE_SOURCES); } function mapMainlineUnlockLevel(sourceLevel, levels, templates) { // 调序可能把高阶敌人提前;解锁必须不晚于最早达到来源门槛的模板关卡。 // 新增来源 ID 很大,但难度来自模板,不能因此提前解锁全部内容。 const index = levels.findIndex((level) => (templates[level] ?? level) >= sourceLevel); return index < 0 ? levels.length : index + 1; } function remapMainlineRecords(records, sources = exports.MAINLINE_SOURCE_LEVELS) { const result = {}; sources.forEach((sourceLevel, index) => { result[String(index + 1)] = records[String(sourceLevel)]; }); return result; } function remapMainlineIndex(index) { const firstAppearances = {}; for (const [group, entries] of Object.entries(index.firstAppearances || {})) { const mappedEntries = {}; for (const [id, appearance] of Object.entries(entries)) { mappedEntries[id] = { ...appearance, displayLevel: mainlineUnlockLevel(appearance.displayLevel), }; } firstAppearances[group] = mappedEntries; } return { ...index, levelCount: exports.MAINLINE_LEVEL_COUNT, firstAppearances }; } function remapContentUnlocks(entries) { return entries.map((entry) => entry.unlockLevel == null ? { ...entry } : { ...entry, unlockLevel: mainlineUnlockLevel(entry.unlockLevel), }); } }, "assets/Logic/Scripts/GhostKingLevelAdapter.ts":function(module,exports,load){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.adaptGhostKingLevel = void 0; const GhostKingConfig_1 = load("assets/Framework/Scripts/GhostKingConfig.ts"); /** * 把已适配的主线关卡改造成群雄逐鹿关卡: * 血量和单波血量按调参缩放,时间限制取自鬼王难度表,并记录原始显示关卡号。 * * @param level 已适配的关卡数据(内部深拷贝,不修改入参) * @param ghostKingLevel 鬼王关卡序号 * @param tuning 鬼王调参,默认 GHOST_KING_TUNING */ var adaptGhostKingLevel = function (level, ghostKingLevel, tuning) { if (undefined === tuning) tuning = GhostKingConfig_1.GHOST_KING_TUNING; var difficultyRank = Number(level.difficulty?.rank); var timeLimit = GhostKingConfig_1.GHOST_KING_RULES.timeLimits[difficultyRank]; if (!(timeLimit > 0 && tuning.bossHpMultiplier > 0)) throw new Error("INVALID_GHOST_KING_TUNING"); var adapted = JSON.parse(JSON.stringify(level)); adapted.sourceDisplayLevel = level.displayLevel; adapted.displayLevel = ghostKingLevel; adapted.battleMode = "ghost-king"; adapted.title = "群雄逐鹿 · 第" + ghostKingLevel + "关"; adapted.combatBalance.bossHp = level.combatBalance.bossHp * tuning.bossHpMultiplier; adapted.combatBalance.targetLeaderTime = timeLimit; adapted.combatBalance.minionHpStageOffsets = [0, 1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6]; adapted.combatBalance.minionHpUnit = 2 * level.combatBalance.minionHpUnit; return adapted; }; exports.adaptGhostKingLevel = adaptGhostKingLevel; }, "assets/Framework/Scripts/GhostKingConfig.ts":function(module,exports,load){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GHOST_KING_RULES = exports.GHOST_KING_TUNING = exports.GHOST_KING_ORDER_WINDOW = exports.GHOST_KING_AD_ENERGY = exports.GHOST_KING_UNLOCK_ADS = exports.GHOST_KING_UNLOCK_LEVEL = exports.ghostKingSourceLevel = exports.buildGhostKingOrder = exports.buildGhostKingIntroductions = exports.GHOST_KING_LEVEL_COUNT = void 0; const GhostKingLevels_1 = load("assets/Framework/Scripts/GhostKingLevels.ts"); const MainlineLevelOrder_1 = load("assets/Framework/Scripts/MainlineLevelOrder.ts"); var GhostKingLevels_2 = load("assets/Framework/Scripts/GhostKingLevels.ts"); Object.defineProperty(exports, "GHOST_KING_LEVEL_COUNT", { enumerable: true, get: function () { return GhostKingLevels_2.GHOST_KING_LEVEL_COUNT; } }); var buildGhostKingIntroductions = function (e, t) { return e !== 1 || t ? [] : [{ id: "ghost-king-introduction", kind: "mode", displayName: "群雄争霸", portraitSource: "", abilityText: "限时清盘,别让敌军追上你", descriptionText: "击杀小兵会向前补位,不会拉退敌将\n主角行走消耗体力,耗尽后休息至回满\n任意军械离场能恢复主角50%体力", detailText: "", sortOrder: 0 }]; }; exports.buildGhostKingIntroductions = buildGhostKingIntroductions; var buildGhostKingOrder = function (e) { for (var t = e.filter(function (e) { return e.difficulty >= 3 && e.difficulty <= 5; }).slice().sort(function (e, t) { return e.sourceLevel - t.sourceLevel; }), i = [], n = 0; n < t.length; n += r) for (var o = t.slice(n, n + r), a = function () { var e = 3 + i.length % 3, t = o.findIndex(function (t) { return t.difficulty === e; }); i.push(o.splice(t < 0 ? 0 : t, 1)[0].sourceLevel); }; o.length > 0;) a(); return i; }; exports.buildGhostKingOrder = buildGhostKingOrder; var ghostKingSourceLevel = function (e) { if (!Number.isInteger(e) || e < 1 || e > GhostKingLevels_1.GHOST_KING_SOURCE_LEVELS.length) throw new RangeError("逐鹿关卡编号超出范围:" + e); return (0, MainlineLevelOrder_1.contentDisplayLevel)(GhostKingLevels_1.GHOST_KING_SOURCE_LEVELS[e - 1]); }; exports.ghostKingSourceLevel = ghostKingSourceLevel; ({ "buildGhostKingIntroductions": buildGhostKingIntroductions, "buildGhostKingOrder": buildGhostKingOrder, "ghostKingSourceLevel": ghostKingSourceLevel }); var GHOST_KING_UNLOCK_LEVEL = 20; exports.GHOST_KING_UNLOCK_LEVEL = GHOST_KING_UNLOCK_LEVEL; var GHOST_KING_UNLOCK_ADS = 3; exports.GHOST_KING_UNLOCK_ADS = GHOST_KING_UNLOCK_ADS; var GHOST_KING_AD_ENERGY = 2; exports.GHOST_KING_AD_ENERGY = GHOST_KING_AD_ENERGY; var GHOST_KING_ORDER_WINDOW = 12; exports.GHOST_KING_ORDER_WINDOW = GHOST_KING_ORDER_WINDOW; var r = GHOST_KING_ORDER_WINDOW; var GHOST_KING_TUNING = { bossHpMultiplier: 3 }; exports.GHOST_KING_TUNING = GHOST_KING_TUNING; var GHOST_KING_RULES = { minimumGap: 280, maximumGap: 560, catchUpMultiplier: 3, timeLimits: { 3: 150, 4: 180, 5: 210 }, baseScores: { 3: 1e3, 4: 1500, 5: 2e3 }, walkSeconds: 10, restSeconds: 5, exitRecovery: 50, reviveSeconds: 60, timeScore: { atLimit: 600, earlyPerSecond: 30, overtimePerSecond: 10 } }; exports.GHOST_KING_RULES = GHOST_KING_RULES; }, "assets/Framework/Scripts/GhostKingLevels.ts":function(module,exports,load){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GHOST_KING_PREVIOUS_LEVELS = exports.GHOST_KING_SOURCE_LEVELS = exports.GHOST_KING_LEVEL_COUNT = void 0; exports.configureGhostKingSources = configureGhostKingSources; const MainlineLevelOrder_1 = load("assets/Framework/Scripts/MainlineLevelOrder.ts"); const LEGACY_GHOST_KING_SOURCE_LEVELS = [4, 5, 12, 8, 13, 15, 9, 14, 20, 11, 19, 17, 22, 29, 24, 25, 28, 32, 30, 33, 36, 34, 35, 38, 39, 40, 41, 48, 42, 45, 52, 56, 49, 57, 55, 58, 59, 63, 60, 61, 66, 65, 64, 71, 67, 69, 72, 70, 74, 76, 77, 78, 80, 83, 79, 81, 86, 84, 85, 89, 90, 92, 93, 94, 98, 95, 97, 105, 102, 100, 103, 104, 113, 110, 107, 115, 111, 117, 120, 122, 124, 121, 127, 123, 132, 131, 130, 134, 133, 136, 135, 139, 143, 141, 147, 144, 148, 152, 150, 154, 153, 155, 156, 157, 161, 158, 159, 160, 163, 162, 165, 164, 168, 167, 166, 174, 172, 169, 171, 173, 177, 178, 175, 182, 180, 179, 183, 187, 185, 189, 190, 193, 203, 195, 194, 210, 197, 199, 213, 200, 207, 202, 206, 209, 215, 224, 217, 218, 225, 222, 220, 229, 226, 223, 227, 228, 232, 230, 237, 235, 231, 240, 236, 233, 247, 243, 239, 246, 263, 249, 251, 264, 253, 257, 255, 259, 261, 260, 262, 266, 269, 271, 267, 274, 272, 268, 281, 273, 277, 275, 279, 283, 284, 286, 287, 285, 295, 291, 289, 296, 297, 292, 294, 298, 299, 302, 307, 300, 303, 309, 304, 306, 310, 314, 312, 313, 316, 318, 320, 322, 323, 326, 331, 324, 327, 325, 329, 330, 332, 333, 337, 335, 338, 342, 336, 348, 345, 339, 340, 343, 349, 350, 354, 351, 356, 362, 352, 359, 355, 357, 360, 358, 364, 366, 365, 367, 369, 371, 368, 370, 375, 376, 374, 377, 381, 384, 378, 383, 388, 387, 385, 390, 395, 393, 391, 394, 397, 406, 404, 398, 410, 407, 400, 402, 411, 403, 408, 409, 416, 417, 413, 421, 418, 415, 424, 420, 422, 426, 427, 425, 428, 430, 431, 429, 435, 434, 438, 439, 437, 440, 442, 441, 446, 443, 450, 447, 445, 452, 453, 448, 449, 455, 454, 457, 460, 458, 462, 463, 467, 464, 465, 466, 471, 468, 469, 472, 475, 476, 474, 481, 484, 477, 482, 479, 485, 483, 486, 487, 488, 490, 500, 489, 492, 503, 491, 495, 493, 494, 499, 496, 508, 504, 506, 513, 509, 507, 518, 511, 514, 512, 516, 515, 519, 520, 528, 521, 522, 532, 526, 524, 534, 529, 531, 530, 537, 538, 535, 539, 541, 536, 540, 545, 547, 542, 544, 546, 553, 551, 549, 557, 554, 552, 558, 556, 555, 559, 560, 561, 569, 565, 562, 574, 566, 563, 575, 567, 570, 576, 568, 573, 577, 579, 578, 581, 583, 585, 582, 584, 590, 591, 587, 589, 596, 594, 592, 598, 601, 593, 595, 604, 599, 602, 603, 605, 609, 608, 611, 618, 610, 614, 620, 613, 617, 621, 615, 622, 630, 623, 624, 636, 628, 626, 627, 632, 631, 633, 634, 635, 643, 640, 639, 644, 646, 641, 645, 648, 642, 649, 652, 650, 654, 657, 656, 658, 660, 663, 659, 662, 664, 667, 665, 666, 673, 671, 668, 675, 672, 676, 678, 677, 681, 682, 679, 684, 688, 685, 689, 692, 687, 690, 694, 696, 698, 699, 701, 702, 703, 709, 705, 704, 716, 707, 710, 708, 711, 712, 713, 714, 720, 717, 722, 724, 723, 725, 726, 730, 727, 729, 728, 731, 732, 736, 737, 733, 744, 739, 735, 738, 740, 741, 742, 743, 745, 746, 754, 750, 747, 755, 751, 749, 752, 753, 757, 756, 759, 766, 758, 762, 768, 763, 769, 770, 767, 773, 771, 772, 787, 775, 777, 788, 780, 778, 790, 783, 782, 784, 786, 785, 791, 793, 794, 799, 796, 798, 800, 801, 802, 803, 805, 806, 809, 807, 808, 810, 814, 817, 811, 821, 819, 813, 820, 822, 823, 825, 826, 828, 829, 833, 831, 830, 832, 834, 835, 837, 840, 839, 838, 841, 846, 842, 843, 850, 845, 847, 848, 849, 861, 852, 853, 862, 854, 860, 869, 856, 863, 858, 866, 870, 871, 872, 873, 877, 880, 875, 881, 882, 878, 886, 885, 884, 901, 889, 888, 890, 893, 891, 892, 895, 894, 897, 898, 900, 904, 903, 902, 907, 905, 909, 908, 912, 910, 911, 915, 914, 919, 931, 917, 921, 922, 924, 927, 926, 930, 929, 932, 933, 934, 939, 938, 935, 947, 941, 937, 940, 944, 943, 946, 948, 951, 953, 949, 954, 956, 950, 960, 959, 952, 961, 963, 958, 965, 971, 964, 968, 972, 966, 974, 967, 969, 977, 973, 975, 980, 981, 979, 982, 985, 983, 986, 988, 989, 992, 991, 994, 997, 998, 995, 1004, 999, 1e3, 1006, 1003, 1002, 1009, 1010, 1012, 1013, 1016, 1018, 1014, 1019, 1021, 1023, 1026, 1024, 1025, 1027, 1028, 1029, 1031, 1030, 1032, 1036, 1037, 1033, 1041, 1040, 1034, 1043, 1045, 1053, 1046, 1048, 1054, 1047, 1050, 1055, 1049, 1052, 1058, 1056, 1057, 1064, 1061, 1060, 1065, 1066, 1062, 1067, 1070]; const GHOST_KING_RETAINED_LEVELS = Object.freeze(LEGACY_GHOST_KING_SOURCE_LEVELS.map((source, index) => ({ source, level: index + 1 })) .filter(entry => !MainlineLevelOrder_1.PREVIOUS_REMOVED_MAINLINE_LEVELS.has(entry.source))); let GHOST_KING_SOURCE_LEVELS = Object.freeze([...LEGACY_GHOST_KING_SOURCE_LEVELS]); exports.GHOST_KING_SOURCE_LEVELS = GHOST_KING_SOURCE_LEVELS; exports.GHOST_KING_LEVEL_COUNT = GHOST_KING_SOURCE_LEVELS.length; function configureGhostKingSources(sources) { exports.GHOST_KING_SOURCE_LEVELS = GHOST_KING_SOURCE_LEVELS = Object.freeze([...sources]); exports.GHOST_KING_LEVEL_COUNT = sources.length; } const GHOST_KING_PREVIOUS_LEVELS = Object.freeze(GHOST_KING_RETAINED_LEVELS.map(entry => entry.level)); exports.GHOST_KING_PREVIOUS_LEVELS = GHOST_KING_PREVIOUS_LEVELS; }}, cache = {}; function load(id) { if (cache[id]) return cache[id].exports; const module = {exports:{}}; cache[id]=module; factories[id](module,module.exports,load); return module.exports; } if (!Array.prototype.contains) Object.defineProperty(Array.prototype,'contains',{value:Array.prototype.includes,configurable:true}); const copy = value => JSON.parse(JSON.stringify(value)); const catalogFactory = load("assets/Logic/Scripts/YnykContentConfig.ts").createYnykContentCatalog; let catalog, difficulty, order, templateOrder; const adapter = load("assets/Logic/Scripts/LevelAdapter.ts"), optimizer = load("assets/Logic/Scripts/BoardLayoutOptimizer.ts"); const byId = new Map(data.definitions.map(item=>[item.id,item])); const basePosition = new Map(data.sourceOrder.map((id,index)=>[id,index])); const sceneFor = number => data.sceneRoutes[data.routeByLevel[basePosition.get(templateOrder[number-1])]]; const sceneForId = id => data.routesByScene[id]; const settingsFor = number => settingsOptions.records[templateOrder[number-1]]; function configure(nextOrder, templates, archivedLevels = {}) { order = [...nextOrder,...Object.keys(archivedLevels).map(Number).sort((a,b)=>a-b)]; templateOrder = order.map(id=>templates[id]); const records = source => Object.fromEntries(templateOrder.map((id,index)=>[index+1,source[basePosition.get(id)+1]])); difficulty = {...data.difficulty,levelCount:order.length,levels:records(data.difficulty.levels)}; const sources = Object.fromEntries(order.map(id=>[id,data.sourceTemplates[templates[id]] ?? templates[id]])); const unlocks = entries => entries.map(entry=>({...entry,...(entry.unlockLevel ? {unlockLevel:load("assets/Framework/Scripts/MainlineLevelOrder.ts").mapMainlineUnlockLevel(entry.unlockLevel,nextOrder,sources)} : {})})); catalog = catalogFactory({...data.config,artifacts:unlocks(data.config.artifacts),mechanisms:unlocks(data.config.mechanisms)},{...data.monsters,monsters:unlocks(data.monsters.monsters)},data.scenes,{...data.encounters,levels:records(data.encounters.levels)}); settingsOptions.monsters = catalog.monsters; } configure(data.order,Object.fromEntries(data.sourceOrder.map(id=>[id,id])),data.archivedLevels); function validate(level, sourceOnly = false, encounterContext) { const issues = []; const add = (message, collection, entryIndex) => issues.push({ message, collection, entryIndex }); if (!level || !Number.isInteger(level.displayLevel) || level.displayLevel < 1 || level.displayLevel > order.length) { return { issues: [{ message: '关卡编号无效' }], board: null }; } if (!Number.isInteger(level.width) || !Number.isInteger(level.height) || level.width < 1 || level.height < 1 || level.width > 64 || level.height > 64) { return { issues: [{ message: '棋盘行列数必须是 1 到 64 的整数' }], board: null }; } const occupied = new Map(); for (const collection of ['characters', 'aoes']) { if (!Array.isArray(level[collection]) || level[collection].length > 2048) { add('对象列表无效或超过 2048 个对象', collection); continue; } level[collection].forEach((entry, entryIndex) => { if (!Array.isArray(entry) || entry.length < 4 || !entry.slice(0, 4).every(Number.isSafeInteger)) { add('对象类型、坐标和朝向必须是整数', collection, entryIndex); return; } const definition = byId.get(entry[0]); if (!definition || definition.collection !== collection) { add('对象类型不存在或分类不符', collection, entryIndex); return; } const footprint = definition.footprintsByOrientation[String(entry[3])]; if (!footprint) { add('朝向必须是 1、2、3、4', collection, entryIndex); return; } if (entry.length > 4 && (entry[4] === null || typeof entry[4] !== 'object' || Array.isArray(entry[4]))) add('扩展参数必须是 JSON 对象', collection, entryIndex); else for (const problem of extraFields.validate(entry[4])) add(problem, collection, entryIndex); for (const [dx, dy] of footprint.cells) { const col = entry[1] + dx, row = entry[2] + dy; if (col < 0 || row < 0 || col >= level.width || row >= level.height) add(definition.name + '超出源棋盘范围', collection, entryIndex); // 封印锁允许覆盖军械;军械彼此重叠才是游戏适配层定义的硬错误。 if (collection === 'characters') { const key = col + ',' + row; if (occupied.has(key)) add('军械占格重叠:' + key, collection, entryIndex); occupied.set(key, entryIndex); } } }); } try { const effectiveSettings = levelSettings.resolve(level.levelSettings, settingsFor(level.displayLevel), settingsOptions); if (level.levelSettings) for (const id of [effectiveSettings.encounter.bossId, ...effectiveSettings.encounter.monsterIds]) { const enemy = catalog.getMonster(id); const unlockLevel = encounterContext?.unlocks[id] ?? enemy.unlockLevel; if (unlockLevel > (encounterContext?.displayLevel ?? level.displayLevel)) throw new Error(enemy.name + '尚未在当前关卡解锁(第 ' + unlockLevel + ' 关)'); } if (issues.length || sourceOnly) return { issues, board: null, effectiveSettings }; const scene = sceneForId(effectiveSettings.encounter.sceneId); const activeCatalog = Object.create(catalog); activeCatalog.getEncounter = () => effectiveSettings.encounter; const activeDifficulty = { ...difficulty, levels: { ...difficulty.levels, [level.displayLevel]: effectiveSettings.difficulty } }; const adapted = adapter.adaptLevel(copy(level), activeCatalog, { routeData: scene.routeData, difficultyConfig: activeDifficulty, boardRotationOffsetDeg: scene.rotation, }); const board = optimizer.optimizeLevel(adapted, scene.routeData); return { issues, board, scene: scene.name, boundary: scene.routeData.walkable_area.inner_boundary, effectiveSettings }; } catch (error) { add('游戏布局适配失败:' + error.message); return { issues, board: null }; } } window.offlineEditor = { data, validate, copy, configure, adaptGhost: load("assets/Logic/Scripts/GhostKingLevelAdapter.ts").adaptGhostKingLevel }; })(); (() => { 'use strict'; const { data, validate, copy, configure } = window.offlineEditor; const model = window.MainlineWorkspace; const key = 'offline-level-editor:' + data.rulesVersion + ':' + data.dataVersion; const layout = level => JSON.stringify([level.width, level.height, level.characters, level.aoes, level.levelSettings]); let workspace = model.create(data), revisions = {}, storedText, storageError = ''; const activate = value => configure(value.order, value.templates, value.archivedLevels); function ghostLevel(number, value = workspace) { const source = data.ghostSources[number - 1], base = model.sourceLevel(value, source); if (!base) throw new Error('逐鹿关卡编号或来源无效'); return { ...copy(base), ...copy(value.ghostLayouts[number] || base.ghostKingLayout || {}), displayLevel: number }; } function validateGhost(level, sourceOnly = false, value = workspace) { const source = data.ghostSources[level.displayLevel - 1], position = model.sourceOrder(value).indexOf(source); if (position < 0) throw new Error('逐鹿关卡编号超出范围'); const result = validate({ ...model.sourceLevel(value, source), width: level.width, height: level.height, characters: level.characters, aoes: level.aoes, displayLevel: position + 1 }, sourceOnly); if (result.board) result.board = window.offlineEditor.adaptGhost(result.board, level.displayLevel); return result; } function checkGhostLayouts(value) { for (const [id, level] of Object.entries(value.archivedLevels || {})) checked({ ...level, displayLevel: model.sourceOrder(value).indexOf(Number(id)) + 1 }, true); for (const [id, layout] of Object.entries(value.ghostLayouts)) { const result = validateGhost({ ...layout, displayLevel: Number(id) }, false, value); if (result.issues.length) throw new Error('逐鹿第 ' + id + ' 关校验失败:' + result.issues[0].message); } } function checked(level, sourceOnly = false) { const result = validate(level, sourceOnly); if (result.issues.length) throw new Error('第 ' + level.displayLevel + ' 关校验失败:' + result.issues[0].message); return level; } function storageMessage(error) { if (error?.name === 'QuotaExceededError') return '浏览器工作区空间不足,请先导出数据包备份'; if (['SecurityError', 'InvalidStateError', 'NotAllowedError'].includes(error?.name)) return '浏览器禁止本地存储,请先导出数据包备份'; return error?.message || '浏览器工作区读写失败,请先导出数据包备份'; } const database = new Promise((resolve, reject) => { if (!window.indexedDB) { reject(new Error('当前浏览器不支持工作区存储,请先导出数据包备份')); return; } const request = window.indexedDB.open('offline-level-editor', 1); request.onupgradeneeded = () => request.result.createObjectStore('workspaces'); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); request.onblocked = () => reject(new Error('工作区数据库被其他窗口占用,请关闭其他编辑器窗口后重试')); }); async function accessWorkspace(text) { const db = await database; return new Promise((resolve, reject) => { const tx = db.transaction('workspaces', text === undefined ? 'readonly' : 'readwrite'); const store = tx.objectStore('workspaces'), request = store.get(key); let failure; tx.oncomplete = () => resolve(request.result); tx.onabort = () => reject(failure || tx.error || new Error('工作区读写已取消')); request.onsuccess = () => { if (text === undefined) return; // 检查与写入必须处于同一个事务,避免多个窗口互相覆盖。 if (request.result !== storedText) { failure = new Error('工作区已被其他窗口修改,请先导出当前数据包,再刷新页面'); tx.abort(); return; } store.put(text, key); }; }); } async function persist(next) { try { const text = JSON.stringify(next); await accessWorkspace(text); storedText = text; } catch (error) { throw new Error(storageMessage(error)); } } const restored = (async () => { try { storedText = await accessWorkspace(); } catch (error) { storageError = storageMessage(error); } try { // 新存档优先;首次保存前兼容旧存档,不删除旧数据。 const text = storedText ?? localStorage.getItem(key); if (!text) return; const stored = JSON.parse(text); if (!stored.formatVersion) { for (const [number, level] of Object.entries(stored)) workspace.levels[Number(number) - 1] = level; } else workspace = model.normalize(stored, data); activate(workspace); workspace.levels.forEach((level, index) => { const baseIndex = data.order.indexOf(workspace.order[index]); if (baseIndex < 0 || JSON.stringify(level) !== JSON.stringify({...data.levels[baseIndex], displayLevel:index+1})) checked(level); }); checkGhostLayouts(workspace); } catch (error) { workspace = model.create(data); storageError = '未恢复本机工作区:' + storageMessage(error); } finally { activate(workspace); } })(); window.offlineEditor.api = async (url, body) => { await restored; if (url === '/api/bootstrap') return { project: '离线工作区-' + data.dataVersion, levelCount: workspace.order.length, ghostCount: data.ghostSources.length, definitions: data.definitions, settingsCatalog: data.settingsCatalog }; if (url === '/api/validate') return validate(body.level); if (url === '/api/ghost-validate') return validateGhost(body.level); const ghostMatch = /^\/api\/ghost-levels\/(\d+)$/.exec(url); if (ghostMatch) { const number = Number(ghostMatch[1]), id = 'ghost-' + number; let level = ghostLevel(number); if (body) { if (body.revision !== String(revisions.mainline || 0)) throw new Error('逐鹿或主线工作区已变化,请重新打开关卡'); if (body.level?.displayLevel !== number) throw new Error('逐鹿关卡编号不匹配'); const result = validateGhost(body.level); if (result.issues.length) throw new Error('逐鹿校验失败:' + result.issues[0].message); const next = copy(workspace); next.ghostLayouts[number] = Object.fromEntries(['width', 'height', 'characters', 'aoes'].map(field => [field, copy(body.level[field])])); await persist(next); workspace = next; revisions.mainline = (revisions.mainline || 0) + 1; level = ghostLevel(number); } return { level, sourceLevel: id, revision: String(revisions.mainline || 0), ...validateGhost(level), backup: '本机逐鹿工作区;交付请导出项目文件包' }; } if (url === '/api/project-export') { if (body.revision !== String(revisions.mainline || 0)) throw new Error('主线工作区已更新,请重新导出'); const next = model.normalize(body.package, data); try { activate(next); for (let index = 0; index < next.levels.length; index++) { const baseIndex = data.order.indexOf(next.order[index]); checked(next.levels[index], baseIndex >= 0 && layout(next.levels[index]) === layout(data.levels[baseIndex])); if (index % 25 === 0) await new Promise(resolve => setTimeout(resolve, 0)); } checkGhostLayouts(next); if (body.revision !== String(revisions.mainline || 0)) throw new Error('工作区已变化,请重新导出'); const { projectFiles, definitions, ...baseline } = data; return { data: copy(baseline), files: copy(projectFiles), package: next }; } finally { activate(workspace); } } if (url === '/api/mainline') { if (body) { if (body.revision !== String(revisions.mainline || 0)) throw new Error('主线工作区已更新,请重新打开编排窗口'); const next = model.normalize(body.package, data); const previous = workspace; try { activate(next); for (let index = 0; index < next.levels.length; index++) { const id = next.order[index], originalIndex = workspace.order.indexOf(id); const unchanged = originalIndex >= 0 && layout(next.levels[index]) === layout(workspace.levels[originalIndex]); checked(next.levels[index], unchanged); if (index % 25 === 0) await new Promise(resolve => setTimeout(resolve, 0)); } if (workspace !== previous) throw new Error('主线工作区已更新,请重新打开编排窗口'); checkGhostLayouts(next); await persist(next); workspace = next; for (const id of workspace.order) revisions[id] = (revisions[id] || 0) + 1; revisions.mainline = (revisions.mainline || 0) + 1; } finally { activate(workspace); } } return { package: copy(workspace), revision: String(revisions.mainline || 0) }; } const match = /^\/api\/levels\/(\d+)$/.exec(url); if (!match) throw new Error('不支持的离线操作'); const number = Number(match[1]), id = workspace.order[number - 1]; if (!id) throw new Error('关卡编号超出范围'); if (body) { if (body.revision !== String(revisions[id] || 0)) throw new Error('工作区已更新,请重新打开关卡'); const next = copy(workspace); next.levels[number - 1] = body.level; const normalized = model.normalize(next, data); checked(normalized.levels[number - 1]); await persist(normalized); workspace = normalized; revisions[id] = (revisions[id] || 0) + 1; revisions.mainline = (revisions.mainline || 0) + 1; } const level = copy(workspace.levels[number - 1]); return { level, revision: String(revisions[id] || 0), sourceLevel: id, templateSource: data.sourceTemplates[workspace.templates[id]] ?? workspace.templates[id], ...validate(level), backup: '本机浏览器工作区;交付请导出完整数据包' }; }; document.addEventListener('DOMContentLoaded', () => { document.getElementById('save').title = '保存到本机浏览器工作区'; document.getElementById('save').lastChild.textContent = '存本机'; restored.then(() => { if (storageError) setTimeout(() => message(storageError, true), 1000); }); }); })();