idle / js /engine.js
Lashtw's picture
fix(assets): clean up cutout background & internal holes for era2 b3 and b10 (20261129_v1)
e58357c
Raw History Blame Contribute Delete
77.2 kB
import { BUILDINGS, COST_GROWTH, LEVEL_MILESTONES, MILESTONE_MULT, STAR_COSTS, STAR_MULT, STAR_BASE_MAX, STAR_EXTRA_MULT, STAR_EXTRA_COST_GROWTH, EVOLVE_MULT, OFFLINE_CAP_HOURS, OFFLINE_CAP_HOURS_UPGRADED, CLICK_BASE, CLICK_PROD_RATIO, TIERS, PASS_SCORE, REVIEW_MAX_QUESTIONS, SCHEDULE, GLOBAL_MULTS, CLASS_STAGES, CLASS_STAGE_BONUS, QUIZ_COIN_SECONDS, QUIZ_COIN_MIN, QUIZ_COIN_DAILY_FULL, QUIZ_COIN_REPEAT_RATIO, OPEN_OFFSET_DAYS, DEFAULT_OPEN_HOUR, SYSTEMS, WEEKLY_SCHEDULE, SLOTH_PENALTY_MULT, EVENTS_CONFIG, WORLD_BOSS_ROSTER, WORLD_BOSS_END_DATE, MERCHANT, ERA2_TALLY_COST, ERA2_BASE_PROD, ERA2_SEQUENCE, ERA2_CONDITIONS, ERA2_TOWN_NAMES, } from './config.js?v=20261129_v1'; import { todayStr, addDays } from './util.js?v=20261129_v1'; import { normalizeWorldBossState, getScheduledOpenTs, formatCountdown, formatOpenAt } from './world-boss-schedule.js?v=20261129_v1'; import { resolveWeeklySpotlight, resolveCaravanModeState } from './event-schedule.js?v=20261129_v1'; export { normalizeWorldBossState, formatCountdown, formatOpenAt }; export { todayStr, REVIEW_MAX_QUESTIONS, WORLD_BOSS_ROSTER, ERA2_TALLY_COST, ERA2_BASE_PROD, ERA2_SEQUENCE, ERA2_CONDITIONS, ERA2_TOWN_NAMES }; export function newGame() { const buildings = {}; BUILDINGS.forEach((b) => { buildings[b.id] = { lv: 0, star: 0, era2: false }; }); return { coins: 15, totalEarned: 0, blueprints: 0, donated: 0, // 個人貢獻的「捐獻值」 donatedCoins: 0, // 個人累積捐出的金幣(計算 √ 遞減用) clicks: 0, weeklyDonated: {}, // 各週捐出的糧草總量 { w1: 100000, ... } tianjiDate: null, // 最後遊玩天機閣日期 tianjiPlayed: 0, // 今日遊玩次數 (0 或 1) items: { peek: 0, eliminate: 0 }, // 錦囊卷軸背包 (偷看卷 peek, 刪去卷 eliminate) mistakes: {}, // 個人錯題本資料庫 { [questionKey]: { id, bank, n, q, o, a, wrongCount, lastWrongAt, lastMyAns, source, mastered } } merchant: { gold: 0, // 西域金幣 exp: 0, // 商隊 EXP (好感度) coupons: 0, // 8折特許券數量 day: todayStr(), // 當前日期 dayCount: 0, // 今日已答題次數 (上限 5) dayCoins: 0, // 今日已得西域金幣 (上限 16) dayRewWordIds: [], // 今日已領獎單字 ID todayMult: null, todayDiscount: null, todayDiscountLabel: null, marketUnlocked: false, weekendRewarded: false, stats: {}, // 單字答題統計 { [wordN]: { c, w, lastAt } } buys: {}, // 商品購買紀錄 { [itemId]: { week, count, total } } }, merchantBuffs: {}, titles: [], curTitle: null, hasDragonFrame: false, extraBossOrders: 0, extraBossOrdersDate: null, boss: { date: null, used: 0, rewardClaimed: false, claimed: {} }, lottery: { cycles: {} }, bazaar: { cycles: {} }, buildings, peakBuildings: {}, peakProd: 0, seenClassStages: [], workClicksDate: null, workClicksToday: 0, era2Unlocked: false, seenEra2Intro: false, stats: { perfectCount: 0 }, lastTick: Date.now(), }; } // ============================================================= // 統一資源發放 API(單一真相來源,嚴禁各活動模組自創欄位名) // ============================================================= export function grantGrain(game, amount) { if (!game) return 0; const val = Math.max(0, Math.round(Number(amount) || 0)); game.coins = (Number(game.coins) || 0) + val; game.totalEarned = (Number(game.totalEarned) || 0) + val; return val; } export function grantTally(game, amount) { if (!game) return 0; const val = Math.max(0, Number(amount) || 0); game.blueprints = Math.round(((Number(game.blueprints) || 0) + val) * 10) / 10; return game.blueprints; } export function grantScroll(game, type = 'auto', count = 1) { if (!game) return { type: 'peek', total: 0 }; game.items = game.items || { peek: 0, eliminate: 0 }; const n = Math.max(1, Math.round(Number(count) || 1)); let target = type; if (target !== 'peek' && target !== 'eliminate') { const p = Number(game.items.peek) || 0; const e = Number(game.items.eliminate) || 0; target = p < e ? 'peek' : (p > e ? 'eliminate' : (Math.random() < 0.5 ? 'peek' : 'eliminate')); } game.items[target] = Math.max(0, (Number(game.items[target]) || 0) + n); return { type: target, added: n, total: game.items[target] }; } // 產生題目唯一鍵值 export function getQuestionKey(q) { if (!q) return 'unknown'; if (q.id) return String(q.id); if (q.bank && typeof q.n !== 'undefined' && q.n !== null) return `${q.bank}_${q.n}`; let hash = 0; const str = String(q.q || ''); for (let i = 0; i < str.length; i++) { hash = ((hash << 5) - hash) + str.charCodeAt(i); hash |= 0; } return `q_${Math.abs(hash)}`; } // 記錄答錯題目(錯題本前置收集) export function recordMistake(game, q, myLabel, source = 'quiz') { if (!game || !q) return; if (!game.mistakes || typeof game.mistakes !== 'object') { game.mistakes = {}; } const key = getQuestionKey(q); const existing = game.mistakes[key] || { id: key, bank: q.bank || 'default', n: typeof q.n !== 'undefined' ? q.n : null, q: q.q || '', o: Array.isArray(q.o) ? [...q.o] : [], a: q.a || '', wrongCount: 0, reviewCount: 0, reviewCorrectCount: 0, mastered: false, createdAt: Date.now(), }; existing.wrongCount = (existing.wrongCount || 0) + 1; existing.lastWrongAt = Date.now(); existing.lastMyAns = myLabel || ''; existing.source = source; existing.mastered = false; // 再次答錯則標記為未精熟 existing.reviewCorrectCount = 0; // 重置錯題三鎖累計複習答對次數,防止重整被 normalizeGame 翻回精熟 // 確保題目題幹、選項與正解完整保留,以便未來錯題本介面隨時能無依賴讀取 if (q.q) existing.q = q.q; if (Array.isArray(q.o) && q.o.length) existing.o = [...q.o]; if (q.a) existing.a = q.a; if (q.bank) existing.bank = q.bank; if (typeof q.n !== 'undefined') existing.n = q.n; game.mistakes[key] = existing; return existing; } // 記錄答對題目(若該題在錯題本中,累加連續答對次數與精熟標記) export function recordCorrect(game, q) { if (!game || !game.mistakes || !q) return; const key = getQuestionKey(q); if (game.mistakes[key]) { const item = game.mistakes[key]; item.reviewCorrectCount = (item.reviewCorrectCount || 0) + 1; item.lastCorrectAt = Date.now(); // 規則:至少累計複習答對 3 次才標記為精熟並移出活躍錯題庫 if (item.reviewCorrectCount >= 3) { item.mastered = true; } } } // 舊存檔補欄位(防止新增建築後壞掉) export function normalizeGame(g) { const base = newGame(); if (!g || typeof g !== 'object') return base; const out = { ...base, ...g }; out.buildings = { ...base.buildings, ...(g.buildings || {}) }; // 歷史高水位守護(Ratchet Mechanism):城池等級與星級只增不減,杜絕舊存檔或多設備反向覆寫 out.peakBuildings = { ...(g.peakBuildings || {}) }; for (const id of Object.keys(out.buildings)) { const b = out.buildings[id] || {}; let curLv = Number(b.lv) || 0; let curStar = Number(b.star) || 0; const isEra2 = !!b?.era2; const peak = out.peakBuildings[id] || { maxLv: 0, maxStar: 0 }; // 🌟 第二紀元星級獨立高水位防護: // 若城池為第二紀元,但峰值尚未標記為 era2(如舊資料或未同步標記),補齊 era2 標記並以當前真實星級為起點(勿誤殺二紀元已升滿的 5 星) if (isEra2 && !peak.era2) { peak.era2 = true; peak.maxStar = curStar; } if (curStar < (peak.maxStar || 0)) { console.warn(`[Ratchet Guard] 偵測到城池 ${id} 星級異常下降 (${curStar} < 歷史峰值 ${peak.maxStar}),已自動阻擋並拉齊峰值!`); curStar = peak.maxStar; } if (curLv < (peak.maxLv || 0)) { console.warn(`[Ratchet Guard] 偵測到城池 ${id} 等級異常下降 (${curLv} < 歷史峰值 ${peak.maxLv}),已自動阻擋並拉齊峰值!`); curLv = peak.maxLv; } peak.maxLv = Math.max(peak.maxLv || 0, curLv); peak.maxStar = Math.max(peak.maxStar || 0, curStar); if (isEra2) peak.era2 = true; out.peakBuildings[id] = peak; out.buildings[id] = { lv: curLv, star: curStar, era2: isEra2 }; } out.peakProd = Math.max(Number(g.peakProd) || 0, 0); ['coins', 'totalEarned', 'blueprints', 'donated', 'donatedCoins', 'clicks'].forEach((k) => { out[k] = Number(out[k]) || 0; }); // 幽靈欄位自動防呆遷移(防止誤寫入 tally 或 scrolls 造成學生資源遺失) if (Number(g.tally) > 0) { console.warn(`[Schema Guard] 偵測到非標準欄位 game.tally (${g.tally}),已自動遷移併入 game.blueprints!`); out.blueprints = Math.round((out.blueprints + Number(g.tally)) * 10) / 10; delete out.tally; } out.weeklyDonated = { ...(g.weeklyDonated || {}) }; for (const k of Object.keys(out.weeklyDonated)) { out.weeklyDonated[k] = clampWeeklyDonated(k, out.weeklyDonated[k]); } out.tianjiDate = g.tianjiDate || null; out.tianjiPlayed = Number(g.tianjiPlayed) || 0; out.items = { peek: Math.max(0, Number(g.items?.peek) || 0), eliminate: Math.max(0, Number(g.items?.eliminate) || 0), }; if (Number(g.scrolls) > 0) { console.warn(`[Schema Guard] 偵測到非標準欄位 game.scrolls (${g.scrolls}),已自動遷移併入 game.items.peek!`); out.items.peek += Math.round(Number(g.scrolls)); delete out.scrolls; } out.mistakes = (g.mistakes && typeof g.mistakes === 'object') ? g.mistakes : {}; // 確保所有錯題皆依「至少答對 3 次才算精熟」的新標準校正(原本答對 2 次被標記 mastered 者自動恢復為待精熟) for (const m of Object.values(out.mistakes)) { if (m && typeof m === 'object') { m.mastered = (Number(m.reviewCorrectCount) || 0) >= 3; } } const today = todayStr(); const m = (g.merchant && typeof g.merchant === 'object') ? g.merchant : {}; const isSameDay = m.day === today; out.merchant = { ...base.merchant, ...m, gold: Math.max(0, Number(m.gold) || 0), exp: Math.max(0, Number(m.exp) || 0), coupons: Math.max(0, Number(m.coupons) || 0), day: today, dayCount: isSameDay ? Math.max(0, Number(m.dayCount) || 0) : 0, dayCoins: isSameDay ? Math.max(0, Number(m.dayCoins) || 0) : 0, dayRewWordIds: (isSameDay && Array.isArray(m.dayRewWordIds)) ? [...m.dayRewWordIds] : [], todayMult: (isSameDay && m.todayMult !== null && m.todayMult !== undefined && Number.isFinite(Number(m.todayMult))) ? Number(m.todayMult) : null, todayDiscount: (isSameDay && m.todayDiscount !== null && m.todayDiscount !== undefined && Number.isFinite(Number(m.todayDiscount))) ? Number(m.todayDiscount) : null, todayDiscountLabel: (isSameDay && m.todayDiscountLabel) ? String(m.todayDiscountLabel) : null, marketUnlocked: isSameDay ? !!m.marketUnlocked : false, weekendRewarded: isSameDay ? !!m.weekendRewarded : false, stats: (m.stats && typeof m.stats === 'object') ? m.stats : {}, buys: (m.buys && typeof m.buys === 'object') ? m.buys : {}, }; out.merchantBuffs = (g.merchantBuffs && typeof g.merchantBuffs === 'object') ? { ...g.merchantBuffs } : {}; // ⚔️ 西域商隊討伐神兵(烏茲神鋼/突騎破陣弓/大漠破甲重弩)自動對帳與校準,確保購買紀錄 100% 轉化為世界 Boss 暴擊增益 const buys = out.merchant.buys || {}; const uzCount = Math.min(3, Math.max(0, Number(buys.uzSteel) || 0)); if (uzCount > 0) { out.merchantBuffs.bossCritRate = Math.max(Number(out.merchantBuffs.bossCritRate) || 0, Math.round(uzCount * 0.05 * 100) / 100); } if ((Number(buys.bow) || 0) > 0) { out.merchantBuffs.bossCritDmg = Math.max(Number(out.merchantBuffs.bossCritDmg) || 0, 0.5); } if ((Number(buys.crossbow) || 0) > 0) { out.merchantBuffs.bossCritFlat = Math.max(Number(out.merchantBuffs.bossCritFlat) || 0, 1); } out.titles = Array.isArray(g.titles) ? [...g.titles] : []; out.curTitle = g.curTitle || (out.titles.length > 0 ? out.titles[out.titles.length - 1] : null); out.hasDragonFrame = !!g.hasDragonFrame; out.era2Unlocked = !!g.era2Unlocked; out.seenEra2Intro = !!g.seenEra2Intro; out.stats = { ...(g.stats || {}) }; out.extraBossOrdersDate = g.extraBossOrdersDate || g.boss?.date || null; out.extraBossOrders = (out.extraBossOrdersDate === today) ? Math.max(0, Number(g.extraBossOrders) || 0) : 0; // 錯題樂透正規化+自動裁剪 7 日以前題鍵明細(保留近 3 期完整明細) const rawLotCycles = (g.lottery && typeof g.lottery.cycles === 'object' && g.lottery.cycles) ? g.lottery.cycles : {}; const todayMidMs = Date.parse(`${today}T12:00:00+08:00`); const cycleEntries = Object.entries(rawLotCycles); cycleEntries.sort((a, b) => (Number(b[1]?.lastRoundAt) || 0) - (Number(a[1]?.lastRoundAt) || 0)); const prunedCycles = {}; cycleEntries.forEach(([cid, cData], idx) => { if (!cData || typeof cData !== 'object') return; const reg = Math.max(0, Math.floor(Number(cData.regularBalls) || 0)); const gold = Math.max(0, Math.floor(Number(cData.goldenBalls) || 0)); const weight = Math.max(reg + gold * 2, Math.floor(Number(cData.weight) || 0)); const dailyUsed = {}; if (cData.dailyUsed && typeof cData.dailyUsed === 'object') { for (const [dKey, cnt] of Object.entries(cData.dailyUsed)) { const dMs = Date.parse(`${dKey}T12:00:00+08:00`); if (idx < 3 || !Number.isFinite(dMs) || !Number.isFinite(todayMidMs) || (todayMidMs - dMs) <= 14 * 86400 * 1000) { dailyUsed[dKey] = Math.max(0, Math.floor(Number(cnt) || 0)); } } } const seenQuestionKeysByDay = {}; if (idx < 3 && cData.seenQuestionKeysByDay && typeof cData.seenQuestionKeysByDay === 'object') { for (const [dKey, arr] of Object.entries(cData.seenQuestionKeysByDay)) { const dMs = Date.parse(`${dKey}T12:00:00+08:00`); if (Number.isFinite(dMs) && Number.isFinite(todayMidMs) && (todayMidMs - dMs) <= 7 * 86400 * 1000 && Array.isArray(arr)) { seenQuestionKeysByDay[dKey] = Array.from(new Set(arr.map(String))); } } } prunedCycles[cid] = { regularBalls: reg, goldenBalls: gold, weight, dailyUsed, seenQuestionKeysByDay, claimed: Boolean(cData.claimed), lastRoundAt: Number(cData.lastRoundAt) || 0, }; }); out.lottery = { cycles: prunedCycles }; // 西域萬國大市集存檔正規化 const rawBazaarCycles = (g.bazaar && typeof g.bazaar === 'object' && g.bazaar.cycles && typeof g.bazaar.cycles === 'object') ? g.bazaar.cycles : {}; const normBazaarCycles = {}; for (const [cid, raw] of Object.entries(rawBazaarCycles)) { if (!raw || typeof raw !== 'object') continue; const normBoolIntMap = (src) => { const res = {}; if (!src || typeof src !== 'object') return res; for (const [k, v] of Object.entries(src)) { const nVal = Math.floor(Number(k)); if (v && Number.isInteger(nVal) && nVal > 0) { res[String(nVal)] = true; } } return res; }; normBazaarCycles[cid] = { litWords: normBoolIntMap(raw.litWords), claimedLines: normBoolIntMap(raw.claimedLines), firstBloodWon: normBoolIntMap(raw.firstBloodWon), dailyLitDate: (typeof raw.dailyLitDate === 'string' && raw.dailyLitDate) ? raw.dailyLitDate : '', dailyLitCount: Math.max(0, Math.floor(Number(raw.dailyLitCount) || 0)), clearedMistakes: Math.max(0, Math.floor(Number(raw.clearedMistakes) || 0)), encounters: Math.max(0, Math.floor(Number(raw.encounters) || 0)), lastNpc: (typeof raw.lastNpc === 'string' && raw.lastNpc) ? raw.lastNpc : null, lastNpcStreak: Math.max(0, Math.floor(Number(raw.lastNpcStreak) || 0)), updatedAt: Math.max(0, Number(raw.updatedAt) || 0), }; } out.bazaar = { cycles: normBazaarCycles }; out.lastTick = Number(out.lastTick) || Date.now(); return out; } /** * 取得學生在西域商隊購買之世界 Boss 討伐神兵加成明細 * 同時檢查 game.merchantBuffs 與 game.merchant.buys,確保舊存檔或即時購買皆 100% 生效 */ export function getBossWeaponBuffs(game) { const g = game || {}; const buffs = g.merchantBuffs || {}; const buys = g.merchant?.buys || {}; const uzCountFromBuys = Math.min(3, Math.max(0, Number(buys.uzSteel) || 0)); const critRateBonus = Math.min(0.5, Math.max(Number(buffs.bossCritRate) || 0, Math.round(uzCountFromBuys * 0.05 * 100) / 100)); const uzCount = Math.max(uzCountFromBuys, Math.round(critRateBonus / 0.05)); const hasBow = (Number(buys.bow) || 0) > 0 || (Number(buffs.bossCritDmg) || 0) > 0; const critDmgBonus = hasBow ? Math.max(Number(buffs.bossCritDmg) || 0, 0.5) : 0; const hasCrossbow = (Number(buys.crossbow) || 0) > 0 || (Number(buffs.bossCritFlat) || 0) > 0; const critFlatBonus = hasCrossbow ? Math.max(Number(buffs.bossCritFlat) || 0, 1) : 0; const critDamage = Math.round((2 + critFlatBonus) * (1 + critDmgBonus)); const tags = []; if (critRateBonus > 0) tags.push(`⚔️烏茲神鋼+${Math.round(critRateBonus * 100)}%暴擊`); if (hasCrossbow) tags.push(`🎯重弩+${critFlatBonus}暴傷`); if (hasBow) tags.push(`🏹破陣弓+${Math.round(critDmgBonus * 100)}%暴傷`); return { uzCount, hasBow, hasCrossbow, critRateBonus, critDmgBonus, critFlatBonus, critDamage, hasAnyWeapon: tags.length > 0, summaryText: tags.join('・') }; } // 取得天機閣今日狀態 (0/1 或 1/1) export function getTianjiStatus(game, today = todayStr()) { const isToday = game?.tianjiDate === today; const played = isToday ? (Number(game?.tianjiPlayed) || 0) : 0; return { played, canPlay: played < 1, left: Math.max(0, 1 - played), today, }; } const RANGE_BY_ID = Object.fromEntries(SCHEDULE.map((r) => [r.id, r])); export function rangeById(id) { return RANGE_BY_ID[id]; } const WEEK_TARGET_MAP = Object.fromEntries(WEEKLY_SCHEDULE.map((w) => [w.id, w.target])); export function clampWeeklyDonated(weekId, val) { const num = Math.max(0, Number(val) || 0); const cap = WEEK_TARGET_MAP[weekId]; return (typeof cap === 'number' && cap > 0) ? Math.min(num, cap) : num; } export function isPassed(progress, id) { return !!(progress && progress[id] && progress[id].best >= PASS_SCORE); } // 計算每週捐獻狀態與怠惰判定(徹底根治怠惰誤判) export function getWeekStatus(game, now = Date.now(), classInfo = null, studentUid = null) { const today = todayStr(new Date(now)); let currentIdx = WEEKLY_SCHEDULE.findIndex((w) => today >= w.start && today <= w.end); if (currentIdx === -1) { if (today < WEEKLY_SCHEDULE[0].start) currentIdx = 0; // 尚未開始,算在第 1 週 else currentIdx = WEEKLY_SCHEDULE.length - 1; // 超過最後一週 } const currentWeek = WEEKLY_SCHEDULE[currentIdx]; const prevWeek = currentIdx > 0 ? WEEKLY_SCHEDULE[currentIdx - 1] : null; const wd = game?.weeklyDonated || {}; const aidRecord = (studentUid && classInfo?.peerAid?.[studentUid]) ? classInfo.peerAid[studentUid] : null; const aidWeeks = (aidRecord && aidRecord.weeks && typeof aidRecord.weeks === 'object') ? aidRecord.weeks : {}; const prevGoal = prevWeek ? prevWeek.target : 0; let prevDonated = prevWeek ? clampWeeklyDonated(prevWeek.id, Math.max(Number(wd[prevWeek.id]) || 0, Number(aidWeeks[prevWeek.id]) || 0)) : 0; // 1. 同袍代捐救助檢測:若班級協調池中記錄有該生的代捐紀錄,自動融合其捐獻額 if (aidRecord) { if (prevWeek && prevDonated < prevGoal) { prevDonated = prevGoal; } } let shortfall = prevWeek ? Math.max(0, prevGoal - prevDonated) : 0; const currentGoal = currentWeek.target; const rawCurrentDonated = Math.max(Number(wd[currentWeek.id]) || 0, Number(aidWeeks[currentWeek.id]) || 0); const currentDonated = clampWeeklyDonated(currentWeek.id, rawCurrentDonated); // 2. 人性化與全軍豁免機制(徹底根治懈怠誤傷): // (a) 若當週軍餉已經圓滿達標(currentDonated >= currentGoal),立即豁免上週怠惰懲罰! // (b) 若當週捐獻金額足以涵蓋上週欠額(currentDonated >= shortfall),自動沖抵欠額,解除怠惰! // (c) 若班級共拓已完成第 1 階段以上(全軍齊心破局),或該生本週已有任何主動捐獻(currentDonated > 0),全體豁免歷史怠惰! // (d) 若班級 peerAid 中已記錄救助,直接視為已全額達標! const hasClassStageRelief = classInfo && (classInfo.donated >= 1000000 || classStage(classInfo.donated || 0).stage >= 1); const isPeerAided = !!(classInfo?.peerAid && studentUid && classInfo.peerAid[studentUid]); if (currentDonated >= currentGoal || currentDonated >= shortfall || hasClassStageRelief || isPeerAided || currentDonated > 0) { shortfall = 0; } const currentDone = currentDonated >= currentGoal; const isSloth = shortfall > 0; return { currentIdx, currentWeek, prevWeek, shortfall, isSloth, currentDonated, currentGoal, currentDone, }; } // 由測驗進度與遊戲狀態推導出的所有「解鎖狀態」 export function derive(progress = {}, classInfo = null, game = null, now = Date.now(), studentUid = null) { const unitsPassed = SCHEDULE.filter((r) => r.tier === 1 && isPassed(progress, r.id)).length; const evolved = new Set(SCHEDULE.filter((r) => r.evolve && isPassed(progress, r.id)).map((r) => r.evolve)); const systems = new Set(SCHEDULE.filter((r) => r.system && isPassed(progress, r.id)).map((r) => r.system)); let globalMult = 1; const sources = []; for (const [key, mult] of Object.entries(GLOBAL_MULTS)) { if (isPassed(progress, key)) { globalMult *= mult; sources.push({ key, mult }); } } const stage = classStage(classInfo?.donated || 0).stage; const classBonus = 1 + stage * CLASS_STAGE_BONUS * (systems.has('v4') ? 2 : 1); globalMult *= classBonus; // 西域商隊秘寶:全軍破境神丹(全名都秒產永久加成) const globalProdAdd = Math.max(0, Number(game?.merchantBuffs?.globalProdAdd) || 0); if (globalProdAdd > 0) { const pillMult = 1 + globalProdAdd; globalMult *= pillMult; sources.push({ key: 'merchant_pill', mult: pillMult, name: '全軍破境神丹 (西域秘寶)' }); } // 西域商隊秘寶:汗血寶馬令(出征輜重與駐防升級成本永久折扣) const costDiscount = Math.min(0.9, Math.max(0, Number(game?.merchantBuffs?.costDiscount) || 0)); // 怠惰狀況懲罰判定 (x0.7) const weekStatus = getWeekStatus(game, now, classInfo, studentUid); if (weekStatus.isSloth) { globalMult *= SLOTH_PENALTY_MULT; sources.push({ key: 'sloth', mult: SLOTH_PENALTY_MULT, name: '怠惰狀況 (上週軍餉未達標)' }); } const offlineCapSec = (systems.has('v1') ? OFFLINE_CAP_HOURS_UPGRADED : OFFLINE_CAP_HOURS) * 3600; return { unitsPassed, evolved, systems, globalMult, classBonus, sources, weekStatus, offlineCapSec, costDiscount, donateMult: systems.has('v4') ? 2 : 1, lucky: systems.has('v3'), }; } export function isUnlocked(bDef, d) { return d.unitsPassed >= bDef.unlockUnits; } // 檢查是否滿足前置城鎮條件 export function isPrereqMet(bDef, game) { if (!bDef.requires || bDef.requires.length === 0) return true; const capturedCount = Object.values(game?.buildings || {}).filter(b => (b?.lv || 0) > 0).length; if (bDef.minCaptured && capturedCount < bDef.minCaptured) return false; // 若為王畿 (b10),必須滿足所有指定前置名都 if (bDef.id === 'b10') { return bDef.requires.every(id => (game?.buildings[id]?.lv || 0) > 0); } // 其餘城鎮只要任一前置名都已攻克,即具備戰略行軍補給線 return bDef.requires.some(id => (game?.buildings[id]?.lv || 0) > 0); } // 獲取城鎮出征戰備詳情(供 UI 與提示使用) export function getConquerRequirements(bDef, game, dState) { const unitPassed = dState.unitsPassed >= bDef.unlockUnits; const prereqMet = isPrereqMet(bDef, game); const tallyHave = game.blueprints || 0; const tallyNeed = bDef.tallyCost || 1; const tallyMet = tallyHave >= tallyNeed; const grainHave = game.coins || 0; const costDiscount = Math.min(0.9, Math.max(0, Number(dState?.costDiscount ?? game?.merchantBuffs?.costDiscount) || 0)); const grainNeed = Math.round((bDef.grainCost || 0) * (1 - costDiscount)); const grainMet = grainHave >= grainNeed; // 找出具體缺少的前置城鎮名稱 let missingPrereqs = []; if (bDef.requires && bDef.requires.length > 0) { const requiredDefs = bDef.requires.map(rid => BUILDINGS.find(x => x.id === rid)).filter(Boolean); if (bDef.id === 'b10') { missingPrereqs = requiredDefs.filter(r => (game?.buildings[r.id]?.lv || 0) === 0).map(r => r.name); if (bDef.minCaptured && Object.values(game?.buildings || {}).filter(b => (b?.lv || 0) > 0).length < bDef.minCaptured) { missingPrereqs.push(`收復任意 ${bDef.minCaptured} 座城鎮`); } } else if (!prereqMet) { missingPrereqs = [requiredDefs.map(r => r.name).join(' 或 ')]; } } const ready = unitPassed && prereqMet && tallyMet && grainMet; return { unitPassed, prereqMet, missingPrereqs, tallyHave, tallyNeed, tallyMet, grainHave, grainNeed, grainMet, ready, }; } // 是否可執行出征 export function canConquer(bDef, game, dState) { const isCaptured = (game?.buildings[bDef.id]?.lv || 0) > 0; if (isCaptured) return false; return getConquerRequirements(bDef, game, dState).ready; } // 執行出征攻克城鎮 export function conquerTown(bDef, game, dState) { const reqs = getConquerRequirements(bDef, game, dState); if ((game?.buildings[bDef.id]?.lv || 0) > 0 || !reqs.ready) return false; game.blueprints -= reqs.tallyNeed; game.coins -= reqs.grainNeed; if (!game.buildings[bDef.id]) { game.buildings[bDef.id] = { lv: 0, star: 0 }; } game.buildings[bDef.id].lv = 1; // 攻佔拔旗,實體化升為 Lv.1,開始生產糧草! return true; } export function milestoneCount(lv) { return LEVEL_MILESTONES.filter((m) => lv >= m).length; } export function nextMilestone(lv) { return LEVEL_MILESTONES.find((m) => lv < m) || null; } export function buildingProd(bDef, bState, d) { if (!bState || bState.lv <= 0) return 0; // 第二紀元時代基底重鑄(Base Jump):基礎產能 baseProd 躍升至現代天朝標準(拯救老夥伴) const base = (bState?.era2 && (bDef.era2BaseProd || ERA2_BASE_PROD?.[bDef.id])) ? (bDef.era2BaseProd || ERA2_BASE_PROD[bDef.id]) : bDef.baseProd; let p = base * bState.lv; p *= Math.pow(MILESTONE_MULT, milestoneCount(bState.lv)); p *= starMult(bState.star || 0); if (d.evolved.has(bDef.id)) p *= EVOLVE_MULT; return p * d.globalMult; } export function totalProd(game, d) { return BUILDINGS.reduce((s, b) => s + buildingProd(b, game.buildings[b.id], d), 0); } // 產量自我監控與健康診斷(檢驗當前秒產是否異常低於歷史峰值) export function checkYieldHealth(game, d) { if (!game || !game.buildings) { return { healthy: true, currentProd: 0, baseProd: 0, peakProd: 0, isSloth: false, dropRatio: 0 }; } const currentProd = totalProd(game, d || { evolved: new Set(), globalMult: 1 }); const isSloth = !!d?.weekStatus?.isSloth; // 排除怠惰懲罰後的基準產能 const baseProd = isSloth ? (currentProd / SLOTH_PENALTY_MULT) : currentProd; const peakProd = Math.max(Number(game.peakProd) || 0, 0); if (peakProd > 0) { const threshold = peakProd * 0.98; // 2% 浮點容差 if (baseProd < threshold) { const dropRatio = Math.round((1 - baseProd / peakProd) * 100); return { healthy: false, currentProd, baseProd, peakProd, isSloth, dropRatio, reason: `檢測到秒產異常回退!基準秒產 (${baseProd.toFixed(1)}) 顯著低於歷史峰值 (${peakProd.toFixed(1)}),跌幅約 ${dropRatio}%!` }; } } return { healthy: true, currentProd, baseProd, peakProd: Math.max(peakProd, baseProd), isSloth, dropRatio: 0 }; } // 產量自我修復:以 peakBuildings 歷史高水位強制補正星級與等級 export function healYield(game) { if (!game || typeof game !== 'object') return { healed: false, repaired: [] }; const repaired = []; game.buildings = game.buildings || {}; game.peakBuildings = game.peakBuildings || {}; for (const id of Object.keys(game.buildings)) { const b = game.buildings[id] || {}; const peak = game.peakBuildings[id] || { maxLv: 0, maxStar: 0 }; let curLv = Number(b.lv) || 0; let curStar = Number(b.star) || 0; const isEra2 = !!b.era2; let changed = false; // 若城池為第二紀元且 peak 尚未適配 era2,僅補齊標記並以當前真實星級為基準 if (isEra2 && !peak.era2) { peak.era2 = true; peak.maxStar = curStar; changed = true; } if (curStar < (peak.maxStar || 0)) { repaired.push({ id, field: 'star', from: curStar, to: peak.maxStar }); curStar = peak.maxStar; changed = true; } if (curLv < (peak.maxLv || 0)) { repaired.push({ id, field: 'lv', from: curLv, to: peak.maxLv }); curLv = peak.maxLv; changed = true; } if (changed) { game.buildings[id] = { lv: curLv, star: curStar, era2: isEra2 }; } peak.maxLv = Math.max(peak.maxLv || 0, curLv); peak.maxStar = Math.max(peak.maxStar || 0, curStar); if (isEra2) peak.era2 = true; game.peakBuildings[id] = peak; } return { healed: repaired.length > 0, repaired }; } function resolveCostMult(discountOrObj) { let disc = 0; if (typeof discountOrObj === 'number') { disc = discountOrObj; } else if (discountOrObj && typeof discountOrObj === 'object') { disc = Number(discountOrObj.costDiscount ?? discountOrObj.merchantBuffs?.costDiscount) || 0; } return Math.max(0.1, 1 - Math.min(0.9, Math.max(0, disc))); } export function levelCost(bDef, lv, discount = 0) { return bDef.baseCost * resolveCostMult(discount) * Math.pow(COST_GROWTH, lv); } // 從 lv 連買 n 級的總價(等比級數) export function bulkCost(bDef, lv, n, discount = 0) { const r = COST_GROWTH; return bDef.baseCost * resolveCostMult(discount) * Math.pow(r, lv) * (Math.pow(r, n) - 1) / (r - 1); } export function maxAffordable(bDef, lv, coins, discount = 0) { const r = COST_GROWTH; const first = bDef.baseCost * resolveCostMult(discount) * Math.pow(r, lv); if (coins < first) return 0; return Math.floor(Math.log(coins * (r - 1) / first + 1) / Math.log(r)); } // 星級:前 5 星用固定表,第 6 星起無上限、成本等比遞增 export function starCost(star) { if (star < STAR_BASE_MAX) return STAR_COSTS[star]; const last = STAR_COSTS[STAR_BASE_MAX - 1]; return Math.ceil(last * Math.pow(STAR_EXTRA_COST_GROWTH, star - STAR_BASE_MAX + 1)); } export function starMult(star) { const base = Math.min(star, STAR_BASE_MAX); const extra = Math.max(0, star - STAR_BASE_MAX); return Math.pow(STAR_MULT, base) * Math.pow(STAR_EXTRA_MULT, extra); } // 下一顆星的倍率(給 UI 提示用) export function nextStarMult(star) { return star < STAR_BASE_MAX ? STAR_MULT : STAR_EXTRA_MULT; } export function clickValue(game, d) { return Math.max(CLICK_BASE, totalProd(game, d) * CLICK_PROD_RATIO) * (d.lucky ? 1.5 : 1); } // 依照實際經過時間推進(線上 tick 與離線結算共用) export function advance(game, d, now = Date.now(), { offline = false } = {}) { const lastTick = Number(game.lastTick) || now; let sec = Math.max(0, (now - lastTick) / 1000); let capped = false; if (offline && Number.isFinite(d.offlineCapSec) && sec > d.offlineCapSec) { sec = d.offlineCapSec; capped = true; } let offlineMult = 1; if (offline && (Number(game?.merchantBuffs?.offlineMult) || 1) > 1) { const expire = Number(game?.merchantBuffs?.offlineExpire) || 0; if (now < expire || lastTick < expire) { offlineMult = Number(game.merchantBuffs.offlineMult) || 1; } } const gain = totalProd(game, d) * sec * offlineMult; game.coins += gain; game.totalEarned += gain; game.lastTick = now; return { sec, gain, capped, offlineMult }; } // ---------- 班級 ---------- // 依使用者需求:直接以捐獻之糧草數量 1:1 累積呈現(乘上同袍共鳴加成倍率) export function donationValue(prevCoins, addCoins, mult = 1) { return addCoins * (mult || 1); } export function classStage(donated) { let stage = 0; for (const s of CLASS_STAGES) { if (donated >= s.need) stage++; else break; } const next = CLASS_STAGES[stage] || null; const prevNeed = stage > 0 ? CLASS_STAGES[stage - 1].need : 0; const pct = next ? Math.min(1, (donated - prevNeed) / (next.need - prevNeed)) : 1; return { stage, next, pct, name: stage > 0 ? CLASS_STAGES[stage - 1].name : '空地' }; } // ---------- 測驗開放 ---------- export function openDate(range) { if (!range?.date) return ''; const [y, m, d] = String(range.date).split('-').map(Number); const dow = new Date(y, (m || 1) - 1, d || 1).getDay(); // 0=日, 1=一, 2=二 // 週一測驗改為上週四 (-4 天)、週二測驗改為上週五 (-4 天),其餘為表定前 2 天 const offset = (dow === 1 || dow === 2) ? -4 : (Number.isFinite(OPEN_OFFSET_DAYS) ? OPEN_OFFSET_DAYS : -2); return addDays(range.date, offset); } export function isRangeOpen(range, classInfo, now = new Date()) { if (classInfo?.openAll) return true; if (Array.isArray(classInfo?.openRanges) && classInfo.openRanges.includes(range.id)) return true; const openDayStr = openDate(range); const openHour = Number.isFinite(range.openHour) ? range.openHour : (DEFAULT_OPEN_HOUR ?? 7); const targetTs = new Date(`${openDayStr}T${String(openHour).padStart(2, '0')}:00:00+08:00`).getTime(); let curTs = Date.now(); if (typeof now === 'number') curTs = now; else if (now instanceof Date) curTs = now.getTime(); else if (typeof now === 'string') { if (/^\d{4}-\d{2}-\d{2}$/.test(now)) { if (now > openDayStr) return true; if (now < openDayStr) return false; curTs = Date.now(); } else { curTs = Date.parse(now) || Date.now(); } } return curTs >= targetTs; } // ============================================================= // 特殊與跨領域活動開放判定(依後台設定排程或老師手動模式) // ============================================================= export { EVENTS_CONFIG }; // ============================================================= // 西域商隊 ⇄ 駱駝商人 隔週交替排程 // - 以 MERCHANT.caravanStartDate(2026-11-02 週一)為第 0 週錨點 // - 偶數週(0,2,4…):西域商隊開市(駱駝商人收起) // - 奇數週(1,3,5…):駱駝商人出沒,預習「下一週西域商隊」的單字單元(西域商隊收起) // - 會考衝刺總複習期(schedule.reviewAll)起:西域商隊常駐 // ============================================================= const ROT_DAY_MS = 86400000; function dateStrToUtcDays(s) { const [y, m, d] = String(s).split('-').map(Number); return Math.floor(Date.UTC(y, (m || 1) - 1, d || 1) / ROT_DAY_MS); } /** 回傳今日所屬的商隊交替週資訊 */ export function getCaravanRotation(today = todayStr()) { const anchor = MERCHANT?.caravanStartDate || '2026-11-02'; const camelAnchor = MERCHANT?.startDate || '2026-10-27'; const t = typeof today === 'string' ? today : todayStr(today); const reviewItem = (MERCHANT?.schedule || []).find(it => it.reviewAll); if (t < anchor) { return { beforeStart: true, isCaravanWeek: false, weekIndex: -1, nextCaravanDate: anchor, nextCamelDate: t >= camelAnchor ? t : camelAnchor, }; } if (reviewItem && t >= reviewItem.date) { return { beforeStart: false, isCaravanWeek: true, weekIndex: -1, reviewAll: true, nextCaravanDate: t, nextCamelDate: null, }; } const weekIndex = Math.floor((dateStrToUtcDays(t) - dateStrToUtcDays(anchor)) / 7); const isCaravanWeek = weekIndex % 2 === 0; const nextMonday = addDays(anchor, (weekIndex + 1) * 7); const nextCaravanDate = isCaravanWeek ? t : nextMonday; let nextCamelDate = null; if (!isCaravanWeek) { nextCamelDate = t; } else if (!reviewItem || nextMonday < reviewItem.date) { nextCamelDate = nextMonday; } return { beforeStart: false, isCaravanWeek, weekIndex, nextCaravanDate, nextCamelDate }; } export function isEventOpen(eventId, classInfo, now = new Date()) { const cfg = EVENTS_CONFIG.find(e => e.id === eventId); if (!cfg) return false; const eventSettings = classInfo?.eventSettings?.[eventId] || {}; const mode = eventSettings.mode || 'auto'; // 'auto' | 'open' | 'bazaar' | 'caravan' | 'closed' if (mode === 'closed') return false; if (mode === 'open') return true; if (eventId === 'caravan' && (mode === 'bazaar' || mode === 'caravan')) return true; // mode === 'auto' -> 依排程日期判定 const scheduleDate = eventSettings.scheduleDate || cfg.defaultDate; const today = typeof now === 'string' ? now : todayStr(now); if (today < scheduleDate) return false; // 西域商隊(含萬國大市集四期)與駱駝商人:隔週自動交替 if (eventId === 'caravan') { const cm = resolveCaravanModeState(classInfo, now); if (cm.activeType === 'bazaar') return true; return cm.isOpen; } if (eventId === 'camel') { const rot = getCaravanRotation(today); if (rot.beforeStart) return true; return !rot.isCaravanWeek; } return true; } /** 計算指定排程日期起算的下一個輪替實際開放日(避免商隊/駱駝設定在輪休週時誤顯示休市日) */ function resolveScheduledOpenDate(eventId, scheduleDate) { if (eventId === 'caravan') { const rot = getCaravanRotation(scheduleDate); return rot.nextCaravanDate || scheduleDate; } if (eventId === 'camel') { const rot = getCaravanRotation(scheduleDate); return rot.nextCamelDate; } return scheduleDate; } export function getEventStatusInfo(eventId, classInfo, now = new Date()) { const cfg = EVENTS_CONFIG.find(e => e.id === eventId); if (!cfg) return null; const eventSettings = classInfo?.eventSettings?.[eventId] || {}; const mode = eventSettings.mode || 'auto'; const scheduleDate = eventSettings.scheduleDate || cfg.defaultDate; const today = typeof now === 'string' ? now : todayStr(now); const isOpen = isEventOpen(eventId, classInfo, eventId === 'caravan' ? now : today); const isAlternating = eventId === 'caravan' || eventId === 'camel'; let label = ''; let badgeClass = ''; let nextOpenDate = null; let closedReason = ''; if (mode === 'open' || (eventId === 'caravan' && (mode === 'bazaar' || mode === 'caravan'))) { nextOpenDate = today; if (mode === 'bazaar') { label = '🎪 已手動切換【西域萬國大市集】'; } else if (mode === 'caravan') { label = '🐪 已手動切換【傳統西域商隊】'; } else { label = '⭐ 已手動開放'; } badgeClass = 'badge-gold'; } else if (mode === 'closed') { nextOpenDate = null; closedReason = '目前由老師暫時關閉開放'; label = '🔒 手動關閉'; badgeClass = 'badge-dim'; } else if (today < scheduleDate) { nextOpenDate = resolveScheduledOpenDate(eventId, scheduleDate); closedReason = nextOpenDate ? `預計 ${nextOpenDate} 開放` : '會考衝刺期由西域商隊常駐'; label = nextOpenDate ? `🔒 等待排程 (${nextOpenDate} 開放)` : '🎓 會考衝刺休市 (商隊常駐)'; badgeClass = 'badge-mute'; } else if (isAlternating) { const cm = eventId === 'caravan' ? resolveCaravanModeState(classInfo, now) : null; if (cm && cm.activeType === 'bazaar') { nextOpenDate = today; label = cm.isCountdown ? '⏳ 萬國大市集預告中 (07:00 開市)' : '🎪 萬國大市集開放中'; badgeClass = cm.isCountdown ? 'badge-gold' : 'badge-mint'; } else { const rot = getCaravanRotation(today); if (isOpen) { nextOpenDate = today; label = rot.reviewAll ? '🟢 會考衝刺常駐開放' : '🟢 自動輪替 (本週開放中)'; badgeClass = 'badge-mint'; } else { nextOpenDate = eventId === 'caravan' ? rot.nextCaravanDate : rot.nextCamelDate; closedReason = nextOpenDate ? `預計 ${nextOpenDate} 開放` : '會考衝刺期由西域商隊常駐'; label = nextOpenDate ? `🔄 輪替休市中 (${nextOpenDate} 開放)` : '🎓 會考衝刺休市 (商隊常駐)'; badgeClass = 'badge-mute'; } } } else { nextOpenDate = today; label = '🟢 排程已到 (已開放)'; badgeClass = 'badge-mint'; } return { ...cfg, mode, scheduleDate, nextOpenDate, closedReason, isOpen, label, badgeClass }; } // ============================================================= // 每日精熟複習目標(防作業感機制:每次最多 4 個複習,包含最新開放進度) // ============================================================= export const MAX_DAILY_REVIEW_COUNT = 4; /** * 取得當前「今日每日複習焦點」考卷列表(至多 4 個,包含最新開放單元) * @param {object} classInfo 班級開課資訊 * @param {Date|string|number} now 當前時間或日期 * @returns {Array} 今日被列入每日複習目標的 range 物件陣列(至多 4 個) */ export function getDailyReviewRanges(classInfo, now = new Date()) { const openRanges = SCHEDULE.filter(r => isRangeOpen(r, classInfo, now)); if (openRanges.length <= MAX_DAILY_REVIEW_COUNT) { return openRanges; } // 取最後 MAX_DAILY_REVIEW_COUNT 個(必然涵蓋當前最新開放進度) return openRanges.slice(-MAX_DAILY_REVIEW_COUNT); } /** * 檢查特定考卷是否屬於今日每日複習焦點 * @param {string} rangeId 考卷 ID (如 'u1', 'u2'...) * @param {object} classInfo 班級開課資訊 * @param {Date|string|number} now 當前時間或日期 * @returns {boolean} */ export function isDailyReviewRange(rangeId, classInfo, now = new Date()) { const reviewRanges = getDailyReviewRanges(classInfo, now); return reviewRanges.some(r => r.id === rangeId); } export const PERFECT_SCORE = 100; /** * 檢查特定單元是否已解鎖「10 題精熟複習模式」 * 教師最新教學規範:單元測驗必須取得 100 分滿分後,才能解鎖 10 題複習減負模式; * 若僅 85~99 分通過,後續複習仍維持完整題數(如 25 題)直到考出 100 分滿分。 * @param {object} progress 學生測驗進度物件 * @param {string} rangeId 測驗單元 ID * @returns {boolean} */ export function isReviewModeUnlocked(progress, rangeId) { return !!(progress && progress[rangeId] && progress[rangeId].best >= PERFECT_SCORE); } /** * 計算指定測驗單元本次應抽出的題數 * - 若為該單元排定之「測驗日期當天」(today === range.date),維持完整題數(如 25 題) * - 若非測驗日期當天,且已達到 100 分滿分(isReviewModeUnlocked),統一隨機抽 REVIEW_MAX_QUESTIONS (10) 題精熟複習 * - 若尚未達到 100 分滿分(含未通過、或 85~99 分通過),一律維持完整題數(如 25 題)直到取得 100 分 */ export function getQuizQuestionCount(range, progress, today = todayStr()) { const tier = TIERS[range?.tier]; const fullCount = tier ? tier.maxQuestions : 25; if (!range) return fullCount; if (today === range.date) return fullCount; if (isReviewModeUnlocked(progress, range.id)) { return Math.min(fullCount, REVIEW_MAX_QUESTIONS); } return fullCount; } /** * 取得班級當前世界 Boss 設定(支援 Phase 1 饕餮 與 Phase 2 窮奇) */ export function getActiveWorldBossConfig(classInfo, now = Date.now()) { const wb = normalizeWorldBossState(classInfo?.worldBoss, now); const bossId = wb?.bossId || 'taotie'; return WORLD_BOSS_ROSTER[bossId] || WORLD_BOSS_ROSTER.taotie; } /** * 將 calcWorldBossStatus 的 today 參數換算為判定用時間戳: * - today 為今天(或未指定)→ 使用真實當下時間(倒數精準到秒) * - today 為指定的過去/未來日期(測試或模擬)→ 取該日東八區正午 */ function resolveBossNowTs(today, nowTs) { if (Number.isFinite(nowTs)) return nowTs; if (!today || today === todayStr()) return Date.now(); const t = new Date(`${today}T12:00:00+08:00`).getTime(); return Number.isFinite(t) ? t : Date.now(); } /** * 世界 Boss 獎勵是否已領取(依 Boss 期別分開記錄) * - 新制:game.boss.claimed = { taotie: true, qiongqi: true } * - 舊制:game.boss.rewardClaimed = true(僅第一期饕餮時代存在)→ 視為饕餮已領,不影響後續期別 */ export function hasClaimedBossReward(game, bossId = 'taotie') { const b = game?.boss || {}; if (b.claimed && typeof b.claimed === 'object' && b.claimed[bossId]) return true; return bossId === 'taotie' && b.rewardClaimed === true; } /** 標記指定期別世界 Boss 獎勵已領取 */ export function markBossRewardClaimed(game, bossId = 'taotie') { if (!game || typeof game !== 'object') return; game.boss = game.boss || {}; const claimed = (game.boss.claimed && typeof game.boss.claimed === 'object') ? { ...game.boss.claimed } : {}; // 舊制旗標先轉存為饕餮已領,避免遺失第一期紀錄 if (game.boss.rewardClaimed === true && !claimed.taotie) claimed.taotie = true; claimed[bossId] = true; game.boss.claimed = claimed; game.boss.rewardClaimed = true; } /** * 依學生當前遊戲進度(已通關單元數 / 章節數)動態計算世界 Boss 討伐全服獎勵 * 解決中後期城池與升星動輒需要 8~28 枚兵符、原本僅發 1 枚兵符不足的問題 */ export function calcWorldBossRewards(progress, game, classInfo, isKiller = false) { const safeGame = (game && typeof game === 'object' && game.buildings) ? game : newGame(); const d = derive(progress || {}, classInfo || {}, safeGame); const units = d.unitsPassed || 0; const chapters = d.chaptersPassed || 0; const curProd = Math.max(100, totalProd(safeGame, d)); // 當前班級進度已達第 8 單元,全服統一發放固定 6 枚兵符,MVP/最後一擊額外加碼 +3 枚(共 9 枚) const baseBp = 6; const killerBonusBp = 3; const grainHours = 6; const scrollsEach = 2; const tierLabel = '中後階爭霸期'; const totalBp = baseBp + (isKiller ? killerBonusBp : 0); const coins = Math.max(2000, Math.round(curProd * 3600 * grainHours)); return { unitsPassed: units, chaptersPassed: chapters, tierLabel, baseBp, killerBonusBp, totalBp, grainHours, coins, peekCount: scrollsEach, eliminateCount: scrollsEach, }; } /** * 取得世界 Boss 今日出題主題(一天出技藝班錯題,一天出英文錯題,每日嚴格輪流出) * 支援 classInfo.worldBoss.questionMode: 'auto' (預設每日輪流) | 'vocational' (鎖定技藝班) | 'english' (鎖定英文) */ export function getBossDailyQuestionTheme(classInfo, today = todayStr()) { const mode = classInfo?.worldBoss?.questionMode || 'auto'; if (mode === 'vocational') { return { type: 'vocational', name: '技藝班專業錯題', badge: '🛠️ 技藝專精日', desc: '今日主題:攻克技藝班專業科目弱點題!克服專業疏漏方能破印!', nextDayType: 'english', nextDayName: '西域英文單字錯題', }; } if (mode === 'english') { return { type: 'english', name: '西域英文單字錯題', badge: '🐫 西域夷語日', desc: '今日主題:攻克西域商隊夷語單字弱點題!掌握絲路詞彙制霸戰場!', nextDayType: 'vocational', nextDayName: '技藝班專業錯題', }; } // 自動每日輪流:以標準東八區日期間隔計算,保證相鄰兩天絕不重複 const dt = new Date(`${today}T00:00:00+08:00`); const epochDays = Math.floor(dt.getTime() / 86400000); const isVocational = (epochDays % 2 !== 0); // 奇數日技藝班專業,偶數日西域英文單字 return isVocational ? { type: 'vocational', name: '技藝班專業錯題', badge: '🛠️ 技藝專精日', desc: '今日戰場主題:【技藝班專業錯題】攻克學科弱點(明日輪替為西域英文錯題)', nextDayType: 'english', nextDayName: '西域英文單字錯題', } : { type: 'english', name: '西域英文單字錯題', badge: '🐫 西域夷語日', desc: '今日戰場主題:【西域英文單字錯題】攻克夷語詞彙(明日輪替為技藝班專業錯題)', nextDayType: 'vocational', nextDayName: '技藝班專業錯題', }; } /** * 純函數:計算世界 Boss 的當前綜合狀態 * 包含:解鎖狀態、血量百分比、剩餘討伐令、預告模式、終結者資訊等 * 適用於:game.js, boss-test.html, admin.js, verify-integrity.mjs */ export function calcWorldBossStatus(classInfo, progress, game, today = todayStr(), nowTsArg = null, uid = null) { const nowTs = resolveBossNowTs(today, nowTsArg); const wb = normalizeWorldBossState(classInfo?.worldBoss, nowTs) || {}; const bossCfg = WORLD_BOSS_ROSTER[wb.bossId] || WORLD_BOSS_ROSTER.taotie; const reqUnit = bossCfg.unlockUnit || 'u3'; const isPreviewMode = wb.phaseMode === 'preview'; // ⏳ 封印倒數模式:大地圖現身並倒數,時間一到自動破印開打(不受 eventSettings.boss 歷史 closed 狀態影響) const isScheduledMode = wb.phaseMode === 'scheduled'; const openAtRaw = isScheduledMode ? Number(wb.openAt) : NaN; const openAt = isScheduledMode ? (Number.isFinite(openAtRaw) ? openAtRaw : getScheduledOpenTs(bossCfg.id)) : null; const isCountdown = isScheduledMode && Number.isFinite(openAt) && nowTs < openAt; const countdownMs = isCountdown ? Math.max(0, openAt - nowTs) : 0; const isClosedMode = wb.phaseMode === 'closed' || wb.phaseMode === 'taotie_closed' || wb.hidden === true; // 若為第一期饕餮,若手動關閉或非開放模式且日期已過截止日,則視為已圓滿收起(地圖不呈現圖標) const isTaotieConcluded = (bossCfg.id === 'taotie') && (isClosedMode || (wb.phaseMode !== 'open' && today > (WORLD_BOSS_END_DATE || '2026-11-01'))); // 2026-11-16 起:舊版未設定 weeklySpotlight 且無 cycleId 之窮奇,僅在教師尚未確認結清且仍有未領獎學生時保留「僅限領獎」入口 const spotlightInfo = classInfo?.weeklySpotlight ? resolveWeeklySpotlight(classInfo, nowTs) : null; const isYinYangPre = !!bossCfg.isYinYang || bossCfg.id === 'qiongqi'; const preDefeated = !!wb.defeated || (isYinYangPre ? (typeof wb.yangHp === 'number' && typeof wb.yinHp === 'number' && wb.yangHp <= 0 && wb.yinHp <= 0) : (typeof wb.curHp === 'number' && wb.curHp <= 0)); let isLegacyExpired = false; let claimOnlyAfterEnd = false; if (!wb.cycleId) { if (spotlightInfo && spotlightInfo.eventId !== 'boss') { const myClaimed = hasClaimedBossReward(game, bossCfg.id); const alreadySettledOrCleared = Boolean(classInfo?.legacyBossClearedAt || classInfo?.bossSettlements?.[bossCfg.id]); if (alreadySettledOrCleared || myClaimed || !preDefeated) { isLegacyExpired = true; } else { claimOnlyAfterEnd = true; } } else if (!spotlightInfo && String(today) >= '2026-11-16') { const myClaimed = hasClaimedBossReward(game, bossCfg.id); const alreadySettledOrCleared = Boolean(classInfo?.legacyBossClearedAt || classInfo?.bossSettlements?.[bossCfg.id] || isClosedMode); if (alreadySettledOrCleared || myClaimed || !preDefeated) { isLegacyExpired = true; } else { claimOnlyAfterEnd = true; } } } const isExpired = isClosedMode || isTaotieConcluded || isLegacyExpired || (bossCfg.id === 'taotie' ? !!(WORLD_BOSS_END_DATE && today > WORLD_BOSS_END_DATE) : false); const isDirectOpen = wb.phaseMode === 'open'; const isUnlockedDate = (isScheduledMode ? !isCountdown : (isDirectOpen || isEventOpen('boss', classInfo, today))) && !isPreviewMode && !isClosedMode && !isExpired; const isReqPassed = (progress?.[reqUnit]?.best || 0) >= PASS_SCORE; const unlocked = isUnlockedDate && !isExpired && isReqPassed; // 討伐令計算(每日 3 次 + 額外購買/贈送討伐令,嚴格限定當日 extraBossOrdersDate === today) const extraOrders = (game?.extraBossOrdersDate === today) ? Math.max(0, Number(game?.extraBossOrders) || 0) : 0; const maxOrders = 3 + extraOrders; const gameUsed = (game?.boss?.date === today) ? Math.max(0, Number(game?.boss?.used) || 0) : 0; const effUid = uid || (typeof window !== 'undefined' && window.student?.uid ? window.student.uid : null); let wbDailyUsed = 0; if (effUid && wb?.damages?.[effUid]) { const dRec = wb.damages[effUid]; if (dRec.dailyUsed && typeof dRec.dailyUsed[today] === 'number') { wbDailyUsed = Math.max(0, Number(dRec.dailyUsed[today]) || 0); } else if (dRec.lastDate === today && typeof dRec.todayCount === 'number') { wbDailyUsed = Math.max(0, Number(dRec.todayCount) || 0); } } let hwmUsed = 0; if (effUid && typeof localStorage !== 'undefined') { try { const raw = localStorage.getItem('idle_boss_hwm_' + effUid); if (raw) { const parsed = JSON.parse(raw); if (parsed && parsed.date === today) { hwmUsed = Math.max(0, Number(parsed.used) || 0); } } } catch (e) { } } // 🛡️ 權威戰報降噪校準:若班級伺服器戰報已載入(damages 存在,即使今日尚無出征紀錄亦視為 0 次), // 且本地 hwmUsed 或 gameUsed 異常大於 maxOrders,以伺服器權威次數為準校準修正,並洗滌本地髒高水位快取! let used = Math.max(gameUsed, wbDailyUsed, hwmUsed); const hasAuthDamagesMap = Boolean(effUid && wb && typeof wb.damages === 'object'); const hasAuthDailyEntry = Boolean(effUid && wb?.damages?.[effUid]?.dailyUsed?.[today] !== undefined); if (used > maxOrders && (hasAuthDailyEntry || hasAuthDamagesMap)) { const authDailyUsed = hasAuthDailyEntry ? Math.max(0, Number(wb.damages[effUid].dailyUsed[today]) || 0) : wbDailyUsed; if (authDailyUsed <= maxOrders) { used = authDailyUsed; if (typeof localStorage !== 'undefined') { try { localStorage.setItem('idle_boss_hwm_' + effUid, JSON.stringify({ date: today, used: authDailyUsed })); } catch (e) { } } } } else if (hwmUsed > maxOrders && Math.max(gameUsed, wbDailyUsed) <= maxOrders) { used = Math.max(gameUsed, wbDailyUsed); if (effUid && typeof localStorage !== 'undefined') { try { localStorage.setItem('idle_boss_hwm_' + effUid, JSON.stringify({ date: today, used })); } catch (e) { } } } const ordersLeft = Math.max(0, maxOrders - used); const defaultHp = bossCfg.defaultMaxHp || 500; const isYinYang = !!bossCfg.isYinYang || bossCfg.id === 'qiongqi'; const yangMaxHp = isYinYang ? (Number(wb.yangMaxHp) || bossCfg.yangMaxHp || 1200) : 0; const yinMaxHp = isYinYang ? (Number(wb.yinMaxHp) || bossCfg.yinMaxHp || 800) : 0; let yangHp = 0; let yinHp = 0; let maxHp = wb.maxHp || defaultHp; let curHp = typeof wb.curHp === 'number' ? Math.max(0, wb.curHp) : defaultHp; if (isYinYang) { maxHp = yangMaxHp + yinMaxHp; const hasSplitHp = typeof wb.yangHp === 'number' || typeof wb.yinHp === 'number'; if (hasSplitHp) { yangHp = typeof wb.yangHp === 'number' ? Math.max(0, wb.yangHp) : yangMaxHp; yinHp = typeof wb.yinHp === 'number' ? Math.max(0, wb.yinHp) : yinMaxHp; curHp = yangHp + yinHp; } else if (typeof wb.curHp === 'number' && wb.curHp === 0) { yangHp = 0; yinHp = 0; curHp = 0; } else { yangHp = yangMaxHp; yinHp = yinMaxHp; curHp = maxHp; } } const yangPct = yangMaxHp > 0 ? Math.max(0, Math.min(100, Math.round((yangHp / yangMaxHp) * 100))) : 0; const yangPctFloat = yangMaxHp > 0 ? Math.max(0, Math.min(100, (yangHp / yangMaxHp) * 100)) : 0; const yinPct = yinMaxHp > 0 ? Math.max(0, Math.min(100, Math.round((yinHp / yinMaxHp) * 100))) : 0; const yinPctFloat = yinMaxHp > 0 ? Math.max(0, Math.min(100, (yinHp / yinMaxHp) * 100)) : 0; const yangSealed = isYinYang && yangHp <= 0; const yinSealed = isYinYang && yinHp <= 0; const pct = Math.max(0, Math.min(100, Math.round((curHp / maxHp) * 100))); const pctFloat = Math.max(0, Math.min(100, (curHp / maxHp) * 100)); const defeated = !!wb.defeated || (isYinYang ? (yangHp <= 0 && yinHp <= 0) : curHp <= 0); return { bossCfg, bossId: bossCfg.id, isYinYang, yangHp, yangMaxHp, yangPct, yangPctFloat, yangSealed, yinHp, yinMaxHp, yinPct, yinPctFloat, yinSealed, reqUnit, reqUnitName: bossCfg.unlockUnitName || reqUnit, isReqPassed, isU3Passed: isReqPassed, unlocked, isPreviewMode, isScheduledMode, isCountdown, countdownMs, openAt: Number.isFinite(openAt) ? openAt : null, isClosedMode, isTaotieConcluded, isUnlockedDate, isExpired, claimOnlyAfterEnd, ordersLeft, maxOrders, usedOrders: used, used, canFight: Boolean(unlocked && !defeated && ordersLeft > 0), defeated, curHp, maxHp, pct, pctFloat, killer: wb.killer || null, damages: wb.damages || {}, chargeThresholds: wb.chargeThresholds || null, questionMode: wb.questionMode || 'auto' }; } /** * 輔助函數:計算數列的百分位數 (Percentile) */ function calcPercentile(sortedArr, p) { if (!Array.isArray(sortedArr) || sortedArr.length === 0) return 0; const idx = Math.min(sortedArr.length - 1, Math.max(0, Math.floor((sortedArr.length - 1) * p))); return Number(sortedArr[idx]) || 0; } /** * 根據全班該科目的錯題數陣列,動態推算 4 階【⚡集氣試煉】加題門檻 [t1, t2, t3, t4] * - 采用全班 P25 / P50 / P75 / P90 分位數結合最小值保底,確保每一期無論錯題多寡, * 全班都有約 75% 學生可觸發 +1 題、50% 觸發 +2 題、25% 觸發 +3 題、前 10~15% 觸發 +4 題! */ export function buildAdaptiveChargeThresholds(counts = [], mode = 'dual') { const valid = (Array.isArray(counts) ? counts : []) .map(n => Math.max(0, Number(n) || 0)) .filter(n => n > 0) .sort((a, b) => a - b); // 預設保底門檻(當班級尚無錯題數據時使用) const defaults = { yang: [5, 12, 20, 28], yin: [2, 5, 9, 14], dual: [6, 14, 24, 35], legacy: [5, 12, 20, 28] }; const fb = defaults[mode] || defaults.dual; if (valid.length < 3) return fb; const minFloor = mode === 'yin' ? [2, 4, 7, 11] : (mode === 'yang' ? [4, 9, 15, 22] : [5, 11, 18, 26]); const t1 = Math.max(minFloor[0], Math.round(calcPercentile(valid, 0.20))); const t2 = Math.max(t1 + 2, minFloor[1], Math.round(calcPercentile(valid, 0.48))); const t3 = Math.max(t2 + 3, minFloor[2], Math.round(calcPercentile(valid, 0.72))); const t4 = Math.max(t3 + 4, minFloor[3], Math.round(calcPercentile(valid, 0.88))); return [t1, t2, t3, t4]; } /** * 給定學生在該模式下的未精熟錯題數與門檻陣列 [t1, t2, t3, t4],回傳應插入的集氣試煉題數 (0~4) */ export function calcStudentChargeQuestions(mistakeCount, mode = 'dual', customThresholds = null) { const cnt = Math.max(0, Number(mistakeCount) || 0); const defaults = { yang: [5, 12, 20, 28], yin: [2, 5, 9, 14], dual: [6, 14, 24, 35], legacy: [5, 12, 20, 28] }; const th = (customThresholds && Array.isArray(customThresholds[mode]) && customThresholds[mode].length === 4) ? customThresholds[mode] : (defaults[mode] || defaults.dual); if (cnt >= th[3]) return 4; if (cnt >= th[2]) return 3; if (cnt >= th[1]) return 2; if (cnt >= th[0]) return 1; return 0; } /** * 🧠 世界 Boss 智慧動態配平演算法 (Auto-Scaling Balance Engine) * 根據全班學生清單的當前錯題庫狀況、預計討伐天數與每日出勤率,自動推算: * 1. 全班陽軀(技藝)、陰軀(英文)、雙修(合計)的未精熟錯題總量與分布 * 2. 自動分位數【⚡集氣試煉】四階門檻 (chargeThresholds) * 3. 考慮全班平均集氣加題後的單日期望總傷害與目標總血量 (maxHp / yangMaxHp / yinMaxHp) * (綜合「討伐天數火力模型 70%」+「清題精熟需求模型 30%」,並將陽陰血量比自動鎖定在合理的 25%~75% 區間) */ export function calcDynamicWorldBossBalance(students = [], options = {}) { const targetDays = Math.max(1, Math.min(14, Number(options.targetDays) || 4.5)); const attendanceRate = Math.max(0.2, Math.min(1.0, Number(options.attendanceRate) || 0.80)); const dailyOrders = Math.max(1, Number(options.dailyOrders) || 3); const attacksPerOrder = Math.max(5, Number(options.attacksPerOrder) || 10); const baseCritRate = 0.15; const chargedCritRate = 0.42; const chargePassRate = 0.78; // 預估集氣題答對率 const list = Array.isArray(students) ? students.filter(s => s && s.role !== 'teacher' && Number(s.seat) !== 20) : []; const activeStudents = list.length > 0 ? list : (Array.isArray(students) ? students : []); const studentCount = Math.max(1, activeStudents.length); const vocCounts = []; const engCounts = []; const dualCounts = []; let totalVocMistakes = 0; let totalEngMistakes = 0; let totalVocReviewsNeeded = 0; // 距離 3 次精熟還差幾次答對 let totalEngReviewsNeeded = 0; for (const s of activeStudents) { const bankId = s?.bankId || 'wiring'; const mists = Object.values(s?.game?.mistakes || {}).filter(m => m && m.q && Array.isArray(m.o)); let sVoc = 0; let sEng = 0; for (const m of mists) { const rev = Math.max(0, Number(m.reviewCorrectCount) || 0); if (rev < 3) { const needed = 3 - rev; if (m.bank === 'english') { sEng++; totalEngReviewsNeeded += needed; } else if (!m.bank || m.bank === bankId || m.bank === 'default') { sVoc++; totalVocReviewsNeeded += needed; } } } vocCounts.push(sVoc); engCounts.push(sEng); dualCounts.push(sVoc + sEng); totalVocMistakes += sVoc; totalEngMistakes += sEng; } // 1. 動態生成三模式的四階集氣門檻 const chargeThresholds = { yang: buildAdaptiveChargeThresholds(vocCounts, 'yang'), yin: buildAdaptiveChargeThresholds(engCounts, 'yin'), dual: buildAdaptiveChargeThresholds(dualCounts, 'dual') }; // 2. 計算全班平均每令可獲得的集氣題數與期望單令傷害 let sumChargePerOrder = 0; for (let i = 0; i < activeStudents.length; i++) { const cYang = calcStudentChargeQuestions(vocCounts[i], 'yang', chargeThresholds); const cYin = calcStudentChargeQuestions(engCounts[i], 'yin', chargeThresholds); const cDual = calcStudentChargeQuestions(dualCounts[i], 'dual', chargeThresholds); sumChargePerOrder += (cYang * 0.4 + cYin * 0.25 + cDual * 0.35); } const avgChargeQuestions = activeStudents.length > 0 ? (sumChargePerOrder / activeStudents.length) : 1.5; const effectiveBuffedAttacks = Math.min(attacksPerOrder, avgChargeQuestions * chargePassRate); const unbuffedAttacks = Math.max(0, attacksPerOrder - effectiveBuffedAttacks); // 普通擊 = 1 + 15% = 1.15 HP;集氣強化擊 = 1 + 42% = 1.42 HP const avgDmgPerOrder = Math.round((unbuffedAttacks * (1 + baseCritRate) + effectiveBuffedAttacks * (1 + chargedCritRate)) * 100) / 100; const expectedDailyOrdersTotal = Math.round(studentCount * attendanceRate * dailyOrders * 10) / 10; const expectedDailyDamage = Math.round(expectedDailyOrdersTotal * avgDmgPerOrder); // 3. 計算建議總血量: // 模型 A(日程火力模型 75% 權重):全班每日期望總傷害 × 預計討伐天數 // 模型 B(錯題精熟模型 25% 權重):全班待精熟總答對次數 × 平均每題傷害 (約 1.22 HP) const cadenceHp = expectedDailyDamage * targetDays; const totalReviewsNeeded = totalVocReviewsNeeded + totalEngReviewsNeeded; const masteryHp = Math.max(600, totalReviewsNeeded * 1.22); const rawTotalHp = (cadenceHp * 0.75) + (masteryHp * 0.25); const recommendedTotalHp = Math.max(600, Math.round(rawTotalHp / 100) * 100); // 4. 計算陽軀(技藝)與陰軀(英文)的黃金血量配比 // 依據全班兩科待複習題量占比,並平滑收斂至 [30% ~ 70%] 區間,避免單邊過少瞬間秒殺 const totalMistakes = Math.max(1, totalVocMistakes + totalEngMistakes); const rawYangRatio = totalVocMistakes / totalMistakes; // 將原始比例與 60:40 基準做加權平滑,並限制在 0.35 ~ 0.75 之間 const smoothedYangRatio = Math.min(0.75, Math.max(0.35, rawYangRatio * 0.65 + 0.60 * 0.35)); const yangMaxHp = Math.max(200, Math.round((recommendedTotalHp * smoothedYangRatio) / 50) * 50); const yinMaxHp = Math.max(200, recommendedTotalHp - yangMaxHp); const finalTotalHp = yangMaxHp + yinMaxHp; return { studentCount, attendanceRate, targetDays, dailyOrders, attacksPerOrder, totalVocMistakes, totalEngMistakes, totalMistakes: totalVocMistakes + totalEngMistakes, totalVocReviewsNeeded, totalEngReviewsNeeded, avgVocMistakes: Math.round((totalVocMistakes / studentCount) * 10) / 10, avgEngMistakes: Math.round((totalEngMistakes / studentCount) * 10) / 10, avgChargeQuestions: Math.round(avgChargeQuestions * 100) / 100, avgDmgPerOrder: Math.round(avgDmgPerOrder * 10) / 10, expectedDailyOrdersTotal, expectedDailyDamage, maxHp: finalTotalHp, yangMaxHp, yinMaxHp, yangRatioPct: Math.round((yangMaxHp / finalTotalHp) * 100), yinRatioPct: Math.round((yinMaxHp / finalTotalHp) * 100), chargeThresholds }; } // ---------- 測驗獎勵 ---------- // 規則:門檻獎勵只補「差額」(不能靠重複考同一份刷資源) // 已通過後每天第一次複習 ≥85 分 → reviewBonus // (防作業感:每日僅限精選的至多 4 個單元發放 reviewBonus,其餘往期單元為自由演練) export function getQuizRangeRewardsMap(range, game) { const tier = TIERS[range?.tier]; if (!tier) return { 85: 0, 95: 0, 100: 0 }; const isCapitalBuilt = !!(game?.buildings?.b10 && (game.buildings.b10.lv > 0 || game.buildings.b10.conquered)); const isPostUnit8 = Number(range?.s) >= 9 || (typeof range?.id === 'string' && /^u(\d+)$/.test(range.id) && parseInt(range.id.slice(1), 10) >= 9); return (range?.tier === 1 && isCapitalBuilt && isPostUnit8) ? { 85: 3, 95: 5, 100: 8 } : tier.reward; } export function computeQuizReward(range, score, prevEntry, game, d, today = todayStr(), classInfo = null) { const tier = TIERS[range.tier]; const prev = prevEntry || { best: 0, attempts: 0, claimed: 0, lastReviewDay: null }; let target = 0; // 若霸業王城已建造完成(b10.lv >= 1),且為第 9 單元及之後的新關卡,單元測驗滿分獎勵晉升為 8 兵符(85分: 3, 95分: 5, 100分: 8) // 舊單元(第 1~8 單元)無論王城是否建造,滿分獎勵上限一律鎖定為 5 兵符,杜絕回刷舊題洗兵符漏洞 const rewardsMap = getQuizRangeRewardsMap(range, game); for (const [th, amt] of Object.entries(rewardsMap)) { if (score >= Number(th)) target = Math.max(target, amt); } const tierBlueprints = Math.max(0, target - (prev.claimed || 0)); const wasPassed = prev.best >= PASS_SCORE; let reviewBonus = 0; // 檢查是否符合每日複習兵符資格: // 1. 先前已通過 // 2. 本次得分 ≥ 85 // 3. 今天尚未在此卷領取過複習兵符 // 4. 若傳入 classInfo,必須在今日 4 個精選複習目標內;若無傳入則保持相容 const eligibleForReview = !classInfo || isDailyReviewRange(range.id, classInfo, today); if (wasPassed && score >= PASS_SCORE && prev.lastReviewDay !== today && eligibleForReview) { reviewBonus = tier.reviewBonus; } const prod = totalProd(game, d); // 同一份考卷每天前 N 次全額金幣,之後打折 const coinCount = prev.coinDay === today ? (prev.coinCount || 0) + 1 : 1; const coinRatio = coinCount <= QUIZ_COIN_DAILY_FULL ? 1 : QUIZ_COIN_REPEAT_RATIO; const coins = Math.max(QUIZ_COIN_MIN, prod * QUIZ_COIN_SECONDS) * (score / 100) * coinRatio; const firstPass = !wasPassed && score >= PASS_SCORE; const entry = { best: Math.max(prev.best || 0, score), attempts: (prev.attempts || 0) + 1, claimed: Math.max(prev.claimed || 0, target), lastReviewDay: reviewBonus ? today : (prev.lastReviewDay || null), lastScore: score, lastAt: Date.now(), passedAt: firstPass ? Date.now() : (prev.passedAt || null), coinDay: today, coinCount, }; return { blueprints: tierBlueprints + reviewBonus, tierBlueprints, reviewBonus, coins, coinReduced: coinRatio < 1, firstPass, entry }; } // 首次通過時的「質變」說明(給結果畫面用) export function unlockText(range, progressAfter) { const out = []; if (range.tier === 1) { const d = derive(progressAfter); const newly = BUILDINGS.filter((b) => b.unlockUnits === d.unitsPassed && b.unlockUnits > 0); newly.forEach((b) => out.push(`🚩 開放城鎮出征情報:${b.icon} ${b.name}(${b.specialty})`)); } if (range.evolve) { const b = BUILDINGS.find((x) => x.id === range.evolve); out.push(`🧬 ${b.icon} ${b.name} 進化!產量 x${EVOLVE_MULT}`); } if (range.system) { const s = SYSTEMS[range.system]; out.push(`${s.icon} 解鎖新系統:${s.name}(${s.desc})`); } if (GLOBAL_MULTS[range.id]) out.push(`✨ 全域產量 x${GLOBAL_MULTS[range.id]}`); return out; } // 檢查目前是否處於暫停建設時段(平日 17:00~隔日 07:00、週末全天、或教師自訂休整) export function checkConstructionStatus(classInfo, now = Date.now()) { const date = new Date(now); const day = date.getDay(); // 0 是週日, 1-5 是週一到週五, 6 是週六 const hour = date.getHours(); const minute = date.getMinutes(); const timeNum = hour + minute / 60; // 17:00 即 17.0 const cp = classInfo?.constructionPause || {}; // 1. 教師手動強制暫停(一鍵全軍休整) if (cp.enabled) { return { allowed: false, reason: cp.reason || '全班臨時休整', type: 'manual' }; } // 2. 教師自訂臨時排程區間(例如段考週、假期) if (cp.rangeStart && cp.rangeEnd) { const startTs = new Date(cp.rangeStart).getTime(); const endTs = new Date(cp.rangeEnd).getTime(); if (!isNaN(startTs) && !isNaN(endTs) && now >= startTs && now <= endTs) { return { allowed: false, reason: cp.reason || `指定排程休整 (${cp.rangeStart.replace('T', ' ')} ~ ${cp.rangeEnd.replace('T', ' ')})`, type: 'scheduled_range' }; } } // 檢查該班級是否啟用「常態課後防沉迷管制」(平日夜間與週末休整) // 預設為 true(未設定或 undefined 視為開啟);若教師後台設為 false(如教師體驗班),則解除常態休整 const routineEnabled = cp.routineEnabled !== false; if (routineEnabled) { // 3. 例行常規:週六、週日全天禁止建設 if (day === 0 || day === 6) { return { allowed: false, reason: '週末全天', type: 'weekend' }; } // 4. 例行常規:週一至週五 17:00 ~ 隔天 07:00 禁止建設(即只有 07:00 <= timeNum < 17:00 允許建設) if (timeNum >= 17 || timeNum < 7) { return { allowed: false, reason: '平日課後時段 (17:00 ~ 07:00)', type: 'weekday_night' }; } } return { allowed: true, reason: '' }; } // ---------- 第二紀元天地質變與城鎮飛升邏輯 ---------- /** * 取得第二紀元飛升誓約總體進度狀態 * 包含四大前置條件(王城建置、全城1星、20次滿分、瓷都5星) */ export function getEra2Status(game, progress = {}) { const g = game || {}; const b = g.buildings || {}; // 條件 1: 建造霸業王城 (1/1) const b10Built = !!(b.b10 && (b.b10.lv > 0 || b.b10.conquered)); // 條件 2: 所有建築達到 1 星 (x/10) - 若已進入第二紀元(era2),該城視為已超越 1 星前置 const all1StarCount = BUILDINGS.filter(bd => (b[bd.id]?.star || 0) >= 1 || !!b[bd.id]?.era2).length; const all1StarMet = all1StarCount >= BUILDINGS.length; // 條件 3: 拿到 20 次滿分 (x/20) // 自動防呆統計:至少等於目前已考取 100 分之單元數 const perfectUnits = Object.values(progress).filter(p => p && p.best >= 100).length; const currentPerfectCount = Math.max(Number(g.stats?.perfectCount) || 0, perfectUnits); const perfectMet = currentPerfectCount >= ERA2_CONDITIONS.perfectCount; // 條件 4: 景陽瓷都達到 5 星 (x/5) - 若 b1 已飛升(era2),該城視為已超越 5 星前置 const b1Star = Number(b.b1?.star) || 0; const b1StarMet = b1Star >= ERA2_CONDITIONS.b1Star || !!b.b1?.era2; const allMet = b10Built && all1StarMet && perfectMet && b1StarMet; const unlocked = !!(g.era2Unlocked || allMet); return { b10Built, all1StarCount, all1StarTotal: BUILDINGS.length, all1StarMet, perfectCount: currentPerfectCount, perfectGoal: ERA2_CONDITIONS.perfectCount, perfectMet, b1Star: b.b1?.era2 ? ERA2_CONDITIONS.b1Star : b1Star, b1StarGoal: ERA2_CONDITIONS.b1Star, b1StarMet, allMet, unlocked, completedCount: (b10Built ? 1 : 0) + (all1StarMet ? 1 : 0) + (perfectMet ? 1 : 0) + (b1StarMet ? 1 : 0), totalGoals: 4 }; } /** * 檢查特定城鎮升級第二紀元的條件(嚴格依序解鎖,前一座升級後方可升級下一座) */ export function getEra2UpgradeInfo(bId, game, progress = {}) { const g = game || {}; const bState = g.buildings?.[bId] || { lv: 0, star: 0 }; const isEra2 = !!bState.era2; const is5Star = (bState.star || 0) >= 5; const era2Status = getEra2Status(g, progress); const isUnlocked = era2Status.unlocked; const seqIndex = ERA2_SEQUENCE.indexOf(bId); let prevTownName = null; let prevEra2Met = true; if (seqIndex > 0) { const prevBId = ERA2_SEQUENCE[seqIndex - 1]; prevEra2Met = !!g.buildings?.[prevBId]?.era2; const prevBDef = BUILDINGS.find(x => x.id === prevBId); prevTownName = prevBDef ? prevBDef.name : prevBId; } const hasTallies = (g.blueprints || 0) >= ERA2_TALLY_COST; const canUpgrade = isUnlocked && !isEra2 && is5Star && prevEra2Met && hasTallies; let lockReason = ''; if (isEra2) { lockReason = '已完成第二紀元質變'; } else if (!isUnlocked) { lockReason = '需先達成第二紀元四大飛升誓約'; } else if (!is5Star) { lockReason = `需先達到 ★5 滿星(目前 ★${bState.star || 0})`; } else if (!prevEra2Met) { lockReason = `需先將前置名都【${prevTownName}】升級至第二紀元`; } else if (!hasTallies) { lockReason = `兵符不足(需 ${ERA2_TALLY_COST} 兵符,持有 ${g.blueprints || 0})`; } return { isEra2, is5Star, isUnlocked, prevEra2Met, prevTownName, hasTallies, canUpgrade, lockReason, cost: ERA2_TALLY_COST, era2Name: ERA2_TOWN_NAMES[bId] || bId, seqIndex, isFirst: seqIndex === 0 }; } /** * 執行城鎮第二紀元昇華升級 */ export function evolveTownToEra2(bId, game, progress = {}) { const info = getEra2UpgradeInfo(bId, game, progress); if (!info.canUpgrade) return { ok: false, reason: info.lockReason }; game.buildings[bId].era2 = true; game.buildings[bId].star = 0; // 🌟 飛升後星級重鑄歸零,回歸無星初始狀態,重新開啟升星長征! game.peakBuildings = game.peakBuildings || {}; game.peakBuildings[bId] = game.peakBuildings[bId] || { maxLv: game.buildings[bId].lv || 0, maxStar: 0 }; game.peakBuildings[bId].maxStar = 0; // 🌟 同步重置歷史高水位,開啟第二紀元專屬升星軌道 game.peakBuildings[bId].era2 = true; game.blueprints = Math.max(0, (game.blueprints || 0) - ERA2_TALLY_COST); return { ok: true, townName: info.era2Name }; }
import {
BUILDINGS, COST_GROWTH, LEVEL_MILESTONES, MILESTONE_MULT, STAR_COSTS, STAR_MULT,
STAR_BASE_MAX, STAR_EXTRA_MULT, STAR_EXTRA_COST_GROWTH,
EVOLVE_MULT, OFFLINE_CAP_HOURS, OFFLINE_CAP_HOURS_UPGRADED, CLICK_BASE, CLICK_PROD_RATIO,
TIERS, PASS_SCORE, REVIEW_MAX_QUESTIONS, SCHEDULE, GLOBAL_MULTS, CLASS_STAGES, CLASS_STAGE_BONUS,
QUIZ_COIN_SECONDS, QUIZ_COIN_MIN, QUIZ_COIN_DAILY_FULL, QUIZ_COIN_REPEAT_RATIO,
OPEN_OFFSET_DAYS, DEFAULT_OPEN_HOUR, SYSTEMS, WEEKLY_SCHEDULE, SLOTH_PENALTY_MULT,
EVENTS_CONFIG, WORLD_BOSS_ROSTER, WORLD_BOSS_END_DATE, MERCHANT,
ERA2_TALLY_COST, ERA2_BASE_PROD, ERA2_SEQUENCE, ERA2_CONDITIONS, ERA2_TOWN_NAMES,
} from './config.js?v=20261129_v1';
import { todayStr, addDays } from './util.js?v=20261129_v1';
import { normalizeWorldBossState, getScheduledOpenTs, formatCountdown, formatOpenAt } from './world-boss-schedule.js?v=20261129_v1';
import { resolveWeeklySpotlight, resolveCaravanModeState } from './event-schedule.js?v=20261129_v1';
export { normalizeWorldBossState, formatCountdown, formatOpenAt };
export { todayStr, REVIEW_MAX_QUESTIONS, WORLD_BOSS_ROSTER, ERA2_TALLY_COST, ERA2_BASE_PROD, ERA2_SEQUENCE, ERA2_CONDITIONS, ERA2_TOWN_NAMES };
export function newGame() {
const buildings = {};
BUILDINGS.forEach((b) => { buildings[b.id] = { lv: 0, star: 0, era2: false }; });
return {
coins: 15,
totalEarned: 0,
blueprints: 0,
donated: 0, // 個人貢獻的「捐獻值」
donatedCoins: 0, // 個人累積捐出的金幣(計算 √ 遞減用)
clicks: 0,
weeklyDonated: {}, // 各週捐出的糧草總量 { w1: 100000, ... }
tianjiDate: null, // 最後遊玩天機閣日期
tianjiPlayed: 0, // 今日遊玩次數 (0 或 1)
items: { peek: 0, eliminate: 0 }, // 錦囊卷軸背包 (偷看卷 peek, 刪去卷 eliminate)
mistakes: {}, // 個人錯題本資料庫 { [questionKey]: { id, bank, n, q, o, a, wrongCount, lastWrongAt, lastMyAns, source, mastered } }
merchant: {
gold: 0, // 西域金幣
exp: 0, // 商隊 EXP (好感度)
coupons: 0, // 8折特許券數量
day: todayStr(), // 當前日期
dayCount: 0, // 今日已答題次數 (上限 5)
dayCoins: 0, // 今日已得西域金幣 (上限 16)
dayRewWordIds: [], // 今日已領獎單字 ID
todayMult: null,
todayDiscount: null,
todayDiscountLabel: null,
marketUnlocked: false,
weekendRewarded: false,
stats: {}, // 單字答題統計 { [wordN]: { c, w, lastAt } }
buys: {}, // 商品購買紀錄 { [itemId]: { week, count, total } }
},
merchantBuffs: {},
titles: [],
curTitle: null,
hasDragonFrame: false,
extraBossOrders: 0,
extraBossOrdersDate: null,
boss: { date: null, used: 0, rewardClaimed: false, claimed: {} },
lottery: { cycles: {} },
bazaar: { cycles: {} },
buildings,
peakBuildings: {},
peakProd: 0,
seenClassStages: [],
workClicksDate: null,
workClicksToday: 0,
era2Unlocked: false,
seenEra2Intro: false,
stats: { perfectCount: 0 },
lastTick: Date.now(),
};
}
// =============================================================
// 統一資源發放 API(單一真相來源,嚴禁各活動模組自創欄位名)
// =============================================================
export function grantGrain(game, amount) {
if (!game) return 0;
const val = Math.max(0, Math.round(Number(amount) || 0));
game.coins = (Number(game.coins) || 0) + val;
game.totalEarned = (Number(game.totalEarned) || 0) + val;
return val;
}
export function grantTally(game, amount) {
if (!game) return 0;
const val = Math.max(0, Number(amount) || 0);
game.blueprints = Math.round(((Number(game.blueprints) || 0) + val) * 10) / 10;
return game.blueprints;
}
export function grantScroll(game, type = 'auto', count = 1) {
if (!game) return { type: 'peek', total: 0 };
game.items = game.items || { peek: 0, eliminate: 0 };
const n = Math.max(1, Math.round(Number(count) || 1));
let target = type;
if (target !== 'peek' && target !== 'eliminate') {
const p = Number(game.items.peek) || 0;
const e = Number(game.items.eliminate) || 0;
target = p < e ? 'peek' : (p > e ? 'eliminate' : (Math.random() < 0.5 ? 'peek' : 'eliminate'));
}
game.items[target] = Math.max(0, (Number(game.items[target]) || 0) + n);
return { type: target, added: n, total: game.items[target] };
}