Download js/bazaar.js from Lashtw/idle: direct link, hf CLI and curl.
- Browser
- Download file 47.7 kB
-
https://huggingface.co/spaces/Lashtw/idle/resolve/main/js/bazaar.js
- Command line
-
hf download hf://spaces/Lashtw/idle/js/bazaar.js
-
curl -L -o bazaar.js https://huggingface.co/spaces/Lashtw/idle/resolve/main/js/bazaar.js
47.7 kB
// ============================================================================
// js/bazaar.js
// 西域萬國大市集(Western Grand Bazaar)核心邏輯模組(純資料與規則計算,無 DOM 操作)
// - 10 卷 5×5 個人確定性亂數賓果(240 單字 + 10 格中央賜福 = 250 格 / 120 條連線)
// - 每日早上 07:00(UTC+8)累積點亮額度(50 -> 100 -> 150 -> 200 -> 240)
// - 錯題三鎖鏈與全域 game.mistakes 雙向同步
// - 4 大市集角色隨機遭遇戰與結算引擎
// ============================================================================
import { BAZAAR_CONFIG, MERCHANT, getTitleDef } from './config.js?v=20261129_v1';
import { todayStr, shuffle } from './util.js?v=20261129_v1';
import {
grantGrain,
grantTally,
grantScroll,
recordMistake,
recordCorrect,
derive,
totalProd,
} from './engine.js?v=20261129_v1';
import { resolveCaravanModeState } from './event-schedule.js?v=20261129_v1';
import {
loadEnglishWords,
speakWord,
maskExampleSentence,
getMerchantStatus,
calcBargainDiscount,
} from './merchant.js?v=20261129_v1';
export { loadEnglishWords, speakWord };
const DAY_MS = 86400 * 1000;
const TAIPEI_OFFSET_MS = 8 * 3600 * 1000;
const NPC_IDS = ['captain', 'weaver', 'lutist', 'scholar'];
const OPTION_LABELS = ['A', 'B', 'C', 'D'];
const DEFAULT_ZH_FALLBACK = ['美好', '時間', '工作', '發現', '保持', '出發', '朋友', '學校', '力量', '平靜'];
const DEFAULT_WORD_FALLBACK = ['time', 'work', 'good', 'make', 'find', 'keep', 'life', 'hope'];
const BAZAAR_LINES = [
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[0, 5, 10, 15, 20],
[1, 6, 11, 16, 21],
[2, 7, 12, 17, 22],
[3, 8, 13, 18, 23],
[4, 9, 14, 19, 24],
[0, 6, 12, 18, 24],
[4, 8, 12, 16, 20],
];
const BARGAIN_MULT_MAP = { 5: 1.0, 4: 2.0, 3: 3.0, 2: 4.0, 1: 4.5, 0: 5.0 };
const BARGAIN_DISCOUNT_MAP = { 5: 0.2, 4: 0.4, 3: 0.6, 2: 0.8, 1: 0.9, 0: 1.0 };
const BARGAIN_LABEL_MAP = { 5: '2折', 4: '4折', 3: '6折', 2: '8折', 1: '9折', 0: '原價' };
const IRREGULAR_EN_FORMS = {
find: ['found'],
fall: ['fell', 'fallen'],
choose: ['chose', 'chosen'],
spend: ['spent'],
catch: ['caught'],
hide: ['hid', 'hidden'],
throw: ['threw', 'thrown'],
win: ['won'],
bite: ['bit', 'bitten'],
draw: ['drew', 'drawn'],
blow: ['blew', 'blown'],
leaf: ['leaves'],
tooth: ['teeth'],
foot: ['feet'],
mouse: ['mice'],
child: ['children'],
man: ['men'],
woman: ['women'],
go: ['went', 'gone'],
come: ['came'],
make: ['made'],
take: ['took', 'taken'],
give: ['gave', 'given'],
get: ['got', 'gotten'],
say: ['said'],
see: ['saw', 'seen'],
know: ['knew', 'known'],
think: ['thought'],
bring: ['brought'],
buy: ['bought'],
teach: ['taught'],
eat: ['ate', 'eaten'],
drink: ['drank', 'drunk'],
write: ['wrote', 'written'],
read: ['read'],
run: ['ran'],
sit: ['sat'],
stand: ['stood'],
begin: ['began', 'begun'],
break: ['broke', 'broken'],
build: ['built'],
feel: ['felt'],
fly: ['flew', 'flown'],
forget: ['forgot', 'forgotten'],
grow: ['grew', 'grown'],
hear: ['heard'],
hold: ['held'],
keep: ['kept'],
leave: ['left'],
lose: ['lost'],
meet: ['met'],
pay: ['paid'],
put: ['put'],
ride: ['rode', 'ridden'],
ring: ['rang', 'rung'],
rise: ['rose', 'risen'],
send: ['sent'],
sing: ['sang', 'sung'],
sleep: ['slept'],
speak: ['spoke', 'spoken'],
swim: ['swam', 'swum'],
tell: ['told'],
understand: ['understood'],
wear: ['wore', 'worn'],
win: ['won'],
// 常見衍生詞防洩漏
king: ['kingdom', 'kingdoms'],
hunt: ['hunter', 'hunters'],
magic: ['magician', 'magicians', 'magical'],
male: ['female', 'females'],
angle: ['triangle', 'triangles'],
};
/**
* FNV-1a 32-bit 無號雜湊函數
* @param {string} str
* @returns {number}
*/
export function hash32(str) {
const s = String(str ?? '');
let h = 0x811c9dc5;
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return h >>> 0;
}
/**
* Mulberry32 確定性虛擬亂數產生器,回傳 [0, 1) 浮點數
* @param {number} seed
* @returns {() => number}
*/
export function mulberry32(seed) {
let a = seed >>> 0;
return function rng() {
let t = (a += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function deterministicShuffle(arr, randFn = Math.random) {
if (randFn === Math.random) return shuffle(arr);
const out = arr.slice();
for (let i = out.length - 1; i > 0; i--) {
const raw = Number(randFn());
const r = Number.isFinite(raw) ? Math.min(0.999999999999, Math.max(0, raw)) : 0;
const j = Math.floor(r * (i + 1));
[out[i], out[j]] = [out[j], out[i]];
}
return out;
}
function escapeRegExp(str) {
return String(str).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function toNowMs(now = new Date()) {
if (now instanceof Date) return now.getTime();
if (typeof now === 'string') {
if (/^\d{4}-\d{2}-\d{2}$/.test(now)) return Date.parse(`${now}T12:00:00+08:00`);
const parsed = Date.parse(now);
return Number.isFinite(parsed) ? parsed : Date.now();
}
const num = Number(now);
return Number.isFinite(num) ? num : Date.now();
}
function resolveCycleConfig(cycleId) {
const cycles = BAZAAR_CONFIG?.cycles || {};
return cycles[cycleId] || cycles.bazaar_1;
}
function pickDistractorWords(targetWord, allPoolWords, count = 3, randFn = Math.random) {
const pool = Array.isArray(allPoolWords) ? allPoolWords : [];
const targetZh = String(targetWord?.zh || '').trim();
const targetEn = String(targetWord?.word || '').trim().toLowerCase();
const samePos = [];
const otherPos = [];
for (const w of pool) {
if (!w || w.n === targetWord?.n) continue;
const wEn = String(w.word || '').trim().toLowerCase();
const wZh = String(w.zh || '').trim();
if (!wEn || !wZh || wEn === targetEn || wZh === targetZh) continue;
if (w.pos === targetWord?.pos) samePos.push(w);
else otherPos.push(w);
}
const picked = [];
const usedEn = new Set([targetEn]);
const usedZh = new Set([targetZh]);
for (const bucket of [deterministicShuffle(samePos, randFn), deterministicShuffle(otherPos, randFn)]) {
for (const w of bucket) {
if (picked.length >= count) break;
const wEn = String(w.word).trim().toLowerCase();
const wZh = String(w.zh).trim();
if (usedEn.has(wEn) || usedZh.has(wZh)) continue;
usedEn.add(wEn);
usedZh.add(wZh);
picked.push(w);
}
}
return picked;
}
/**
* 確保 game.bazaar.cycles[cycleId] 欄位存在且結構正規
*/
export function ensureBazaarCycleState(game, cycleId) {
const target = game && typeof game === 'object' ? game : {};
if (!target.bazaar || typeof target.bazaar !== 'object') {
target.bazaar = { cycles: {} };
}
if (!target.bazaar.cycles || typeof target.bazaar.cycles !== 'object') {
target.bazaar.cycles = {};
}
const cid = String(cycleId || 'bazaar_1');
const cur = target.bazaar.cycles[cid];
if (!cur || typeof cur !== 'object') {
target.bazaar.cycles[cid] = {
litWords: {},
claimedLines: {},
firstBloodWon: {},
dailyLitDate: '',
dailyLitCount: 0,
clearedMistakes: 0,
encounters: 0,
lastNpc: null,
lastNpcStreak: 0,
updatedAt: 0,
};
} else {
if (!cur.litWords || typeof cur.litWords !== 'object') cur.litWords = {};
if (!cur.claimedLines || typeof cur.claimedLines !== 'object') cur.claimedLines = {};
if (!cur.firstBloodWon || typeof cur.firstBloodWon !== 'object') cur.firstBloodWon = {};
if (typeof cur.dailyLitDate !== 'string') cur.dailyLitDate = '';
cur.dailyLitCount = Math.max(0, Math.floor(Number(cur.dailyLitCount) || 0));
cur.clearedMistakes = Math.max(0, Math.floor(Number(cur.clearedMistakes) || 0));
cur.encounters = Math.max(0, Math.floor(Number(cur.encounters) || 0));
if (typeof cur.lastNpc !== 'string' || !cur.lastNpc) cur.lastNpc = null;
cur.lastNpcStreak = Math.max(0, Math.floor(Number(cur.lastNpcStreak) || 0));
cur.updatedAt = Math.max(0, Number(cur.updatedAt) || 0);
}
return target.bazaar.cycles[cid];
}
/**
* 取得以台北時間每日早上 07:00 為換日線之日期鍵(YYYY-MM-DD)與下次 07:00 重置時間戳
*/
export function getBazaarDailyKey(now = new Date()) {
const nowMs = toNowMs(now);
// 台北時間 +8h,若於每日 07:00 換日(即 UTC+1h 剛好跨 00:00)
const shifted = new Date(nowMs + 3600 * 1000);
return shifted.toISOString().slice(0, 10);
}
export function getNextBazaarDailyResetMs(now = new Date()) {
const dailyKey = getBazaarDailyKey(now);
const openAtTodayMs = Date.parse(`${dailyKey}T07:00:00+08:00`);
return openAtTodayMs + DAY_MS;
}
/**
* 依學生 UID 與期別產生確定性 10 卷 5×5 賓果盤面(正中央 cellIndex=12 為 Free 格)
*/
export function buildBazaarBoards(uid, cycleId) {
const cycle = resolveCycleConfig(cycleId);
const words = [];
for (let n = cycle.startN; n <= cycle.endN; n++) {
words.push(n);
}
const rng = mulberry32(hash32(`${String(uid || 'guest')}:${cycle.id}`));
const shuffledWords = deterministicShuffle(words, rng);
const scrollCount = BAZAAR_CONFIG.scrollCount || 10;
const cellsPerBoard = (BAZAAR_CONFIG.boardSize || 5) * (BAZAAR_CONFIG.boardSize || 5);
const freeIdx = BAZAAR_CONFIG.freeCellIndex ?? 12;
const boards = [];
for (let scrollIndex = 0; scrollIndex < scrollCount; scrollIndex++) {
const board = [];
let wordSlot = 0;
for (let cellIndex = 0; cellIndex < cellsPerBoard; cellIndex++) {
if (cellIndex === freeIdx) {
board.push({ scrollIndex, cellIndex, isFree: true, n: null });
} else {
board.push({
scrollIndex,
cellIndex,
isFree: false,
n: shuffledWords[scrollIndex * 24 + wordSlot],
});
wordSlot++;
}
}
boards.push(board);
}
return boards;
}
/**
* 計算每日早上 07:00 重置之每日 50 格點亮上限資訊(包含強制開啟模式皆預設嚴守每日 50 格)
*/
export function getBazaarQuotaInfo(classInfo = {}, now = new Date()) {
const modeState = resolveCaravanModeState(classInfo, now);
const nowMs = toNowMs(now);
const dailyCap = BAZAAR_CONFIG.dailyLitCap || BAZAAR_CONFIG.dailyQuotaStep || 50;
if (modeState.activeType !== 'bazaar') {
return {
modeState,
dayIdx: -1,
dailyKey: getBazaarDailyKey(nowMs),
dailyQuotaCap: 0,
maxLitQuota: 0,
nextUnlockAtMs: null,
};
}
if (!modeState.isForcedOpen && (!modeState.isOpen || (Number.isFinite(modeState.openAtMs) && nowMs < modeState.openAtMs))) {
return {
modeState,
dayIdx: -1,
dailyKey: getBazaarDailyKey(nowMs),
dailyQuotaCap: 0,
maxLitQuota: 0,
nextUnlockAtMs: modeState.openAtMs ?? null,
};
}
const dailyKey = getBazaarDailyKey(nowMs);
const nextUnlockAtMs = getNextBazaarDailyResetMs(nowMs);
const dayIdx = Number.isFinite(modeState.openAtMs) && nowMs >= modeState.openAtMs
? Math.max(0, Math.floor((nowMs - modeState.openAtMs) / DAY_MS))
: 0;
return {
modeState,
dayIdx,
dailyKey,
dailyQuotaCap: dailyCap,
maxLitQuota: dailyCap,
nextUnlockAtMs,
};
}
/**
* 查詢單字在全域錯題本中的三鎖淨化進度
*/
export function getWordMistakeChainState(game, n) {
const m = game?.mistakes?.[`english_${n}`];
if (m && !m.mastered && (Number(m.reviewCorrectCount) || 0) < 3) {
return {
isLockedMistake: true,
progress: Math.max(0, Math.min(2, Math.floor(Number(m.reviewCorrectCount) || 0))),
needed: 3,
};
}
return { isLockedMistake: false, progress: 0, needed: 1 };
}
/**
* 計算學生在當期大市集的盤面點亮數、當日已點亮水位、120 條連線數、聽牌卷數與鎖鏈錯題清單
*/
export function computeBazaarSummary(game, uid, cycleId, now = new Date()) {
const cycle = resolveCycleConfig(cycleId);
const resolvedCycleId = cycle.id;
const cycleState = ensureBazaarCycleState(game, resolvedCycleId);
const boards = buildBazaarBoards(uid, resolvedCycleId);
let litCount = 0;
const scrollLines = [];
const tenpaiLines = [];
const nearBingoScrolls = [];
for (let s = 0; s < boards.length; s++) {
const board = boards[s];
const isCellLit = (cell) => Boolean(cell.isFree || cycleState.litWords[String(cell.n)]);
for (const cell of board) {
if (!cell.isFree && cycleState.litWords[String(cell.n)]) {
litCount++;
}
}
let linesOnBoard = 0;
let tenpaiCount = 0;
for (const line of BAZAAR_LINES) {
let litInLine = 0;
for (const idx of line) {
if (isCellLit(board[idx])) litInLine++;
}
if (litInLine === 5) linesOnBoard++;
else if (litInLine === 4) tenpaiCount++;
}
scrollLines.push(linesOnBoard);
tenpaiLines.push(tenpaiCount);
if (tenpaiCount > 0) nearBingoScrolls.push(s);
}
const totalLines = scrollLines.reduce((acc, v) => acc + v, 0);
const totalCellsLit = litCount + boards.length;
const dailyKey = getBazaarDailyKey(now);
const dailyQuotaCap = BAZAAR_CONFIG.dailyLitCap || BAZAAR_CONFIG.dailyQuotaStep || 50;
const dailyLitCount = cycleState.dailyLitDate === dailyKey
? Math.max(0, Math.floor(Number(cycleState.dailyLitCount) || 0))
: 0;
const remTotal = Math.max(0, (BAZAAR_CONFIG.totalWordsPerCycle || 240) - litCount);
const remDailyQuota = Math.min(Math.max(0, dailyQuotaCap - dailyLitCount), remTotal);
const activeChainWords = [];
const tappableChainWords = [];
for (let n = cycle.startN; n <= cycle.endN; n++) {
if (cycleState.litWords[String(n)]) continue;
const chain = getWordMistakeChainState(game, n);
if (chain.isLockedMistake) {
activeChainWords.push(n);
if (chain.progress < 2) tappableChainWords.push(n);
}
}
return {
cycleId: resolvedCycleId,
boards,
litCount,
totalCellsLit,
totalLines,
dailyKey,
dailyLitCount,
dailyQuotaCap,
remDailyQuota,
scrollLines,
tenpaiLines,
nearBingoScrolls,
activeChainWords,
tappableChainWords,
};
}
/**
* 抽出下一場遭遇戰 NPC,避免連續出現同一角色超過 2 次
*/
export function pickNextBazaarNpc(cycleState, randFn = Math.random) {
const prevNpc = cycleState?.lastNpc || null;
const prevStreak = Number(cycleState?.lastNpcStreak) || 0;
const candidates = (prevNpc && prevStreak >= 2)
? NPC_IDS.filter(id => id !== prevNpc)
: NPC_IDS;
const raw = Number(randFn());
const r = Number.isFinite(raw) ? Math.min(0.999999999999, Math.max(0, raw)) : 0;
const chosen = candidates[Math.floor(r * candidates.length)];
if (cycleState && typeof cycleState === 'object') {
cycleState.lastNpcStreak = chosen === prevNpc ? prevStreak + 1 : 1;
cycleState.lastNpc = chosen;
}
return chosen;
}
/**
* 組裝合法的 4 選 1 標準英語測驗物件,確保與世界 Boss / 錯題樂透 100% 相容
*/
export function buildSafeStandardQuestion(wordObj, allPoolWords, randFn = Math.random) {
const distractors = pickDistractorWords(wordObj, allPoolWords, 3, randFn);
const wrongZh = distractors.map(d => String(d.zh).trim());
for (const fallback of DEFAULT_ZH_FALLBACK) {
if (wrongZh.length >= 3) break;
if (fallback !== wordObj.zh && !wrongZh.includes(fallback)) {
wrongZh.push(fallback);
}
}
while (wrongZh.length < 3) {
wrongZh.push(`其他釋義${wrongZh.length + 1}`);
}
const rawChoices = [
{ text: wordObj.zh, correct: true },
{ text: wrongZh[0], correct: false },
{ text: wrongZh[1], correct: false },
{ text: wrongZh[2], correct: false },
];
const shuffled = deterministicShuffle(rawChoices, randFn);
const o = shuffled.map(c => c.text);
const ansIdx = Math.max(0, shuffled.findIndex(c => c.correct));
const posPart = wordObj.pos ? `(${wordObj.pos})` : '';
return {
id: `english_${wordObj.n}`,
bank: 'english',
n: wordObj.n,
q: `請問英文單字【${wordObj.word}】${posPart} 的意思是?`,
o,
a: OPTION_LABELS[ansIdx],
};
}
/**
* 將英文例句中的目標單字安全挖空(支援常見詞尾變化;若無法安全遮罩則回傳 ok: false)
*/
export function maskEnglishCloze(ex, word) {
if (!ex || !word) return { ok: false, maskedEx: null };
const w = String(word).trim();
if (!w) return { ok: false, maskedEx: null };
const esc = escapeRegExp(w);
const patterns = [`${esc}(?:s|es|ed|d|ing)?`];
if (/e$/i.test(w) && w.length > 2) {
patterns.push(`${escapeRegExp(w.slice(0, -1))}(?:e|es|ed|ing)`);
}
if (/y$/i.test(w) && w.length > 2) {
patterns.push(`${escapeRegExp(w.slice(0, -1))}(?:y|ys|ies|ied|ying|yed)`);
}
if (/fe$/i.test(w) && w.length > 2) {
patterns.push(`${escapeRegExp(w.slice(0, -2))}ves`);
} else if (/f$/i.test(w) && w.length > 2) {
patterns.push(`${escapeRegExp(w.slice(0, -1))}ves`);
}
if (/[bcdfghjklmnpqrstvwxz]$/i.test(w) && w.length >= 3) {
const last = escapeRegExp(w.slice(-1));
patterns.push(`${esc}${last}(?:ed|ing)`);
}
const irreg = IRREGULAR_EN_FORMS[w.toLowerCase()];
if (Array.isArray(irreg)) {
for (const form of irreg) {
if (form) patterns.push(escapeRegExp(form));
}
}
const rx = new RegExp(`\\b(?:${patterns.join('|')})\\b`, 'gi');
const masked = String(ex).replace(rx, '______');
const leakTokens = [esc, ...(Array.isArray(irreg) ? irreg.map(escapeRegExp) : [])];
const leakRx = new RegExp(`\\b(?:${leakTokens.join('|')})\\b`, 'i');
if (masked.includes('______') && !leakRx.test(masked)) {
return { ok: true, maskedEx: masked };
}
return { ok: false, maskedEx: null };
}
function buildEnglishOptionsForWord(wordObj, cycleWords, randFn) {
const distractors = pickDistractorWords(wordObj, cycleWords, 3, randFn);
const wrongWords = distractors.map(d => d.word);
for (const fb of DEFAULT_WORD_FALLBACK) {
if (wrongWords.length >= 3) break;
if (fb.toLowerCase() !== String(wordObj.word).toLowerCase() && !wrongWords.includes(fb)) {
wrongWords.push(fb);
}
}
const rawChoices = [
{ word: wordObj.word, zh: wordObj.zh, correct: true },
...wrongWords.slice(0, 3).map((w, i) => ({
word: w,
zh: distractors[i]?.zh || DEFAULT_ZH_FALLBACK[i],
correct: false,
})),
];
return deterministicShuffle(rawChoices, randFn);
}
function buildScrambleTiles(word, randFn) {
const chars = String(word || '').split('');
const distinct = new Set(chars.map(c => c.toLowerCase()));
if (distinct.size <= 1) return chars;
let tiles = chars;
for (let attempt = 0; attempt < 16; attempt++) {
tiles = deterministicShuffle(chars, randFn);
if (tiles.join('') !== word) return tiles;
}
const diffIdx = tiles.findIndex(c => c !== tiles[0]);
if (diffIdx > 0) {
[tiles[0], tiles[diffIdx]] = [tiles[diffIdx], tiles[0]];
}
return tiles;
}
function buildBazaarItemFromEntry(entry, npcId, cycleWords, randFn) {
const { wordObj, isFiller, canLightToday, chainBefore } = entry;
const safeQ = buildSafeStandardQuestion(wordObj, cycleWords, randFn);
let questionMode = 'mc_zh';
let promptText = wordObj.word;
let promptSub = wordObj.pos ? `(${wordObj.pos})` : '';
let maskedEx = null;
let options = [...safeQ.o];
let answerIndex = Math.max(0, OPTION_LABELS.indexOf(safeQ.a));
let scrambleTiles = null;
let audioOptions = null;
let muteOptions = null;
let muteAnswerIndex = null;
let mutePromptText = null;
let mutePromptSub = null;
if (npcId === 'captain') {
questionMode = 'mc_zh';
maskedEx = maskExampleSentence(wordObj.exZh, wordObj.zh, wordObj.word, options);
} else if (npcId === 'weaver') {
questionMode = 'pair_5x5';
} else if (npcId === 'lutist') {
questionMode = 'audio_mc';
const choices = buildEnglishOptionsForWord(wordObj, cycleWords, randFn);
audioOptions = choices.map(c => ({ word: c.word, zh: c.zh, label: `${c.word} — ${c.zh}` }));
muteOptions = choices.map(c => c.word);
options = audioOptions.map(o => o.label);
answerIndex = Math.max(0, choices.findIndex(c => c.correct));
muteAnswerIndex = answerIndex;
promptText = `🔊 請聽發音辨識單字${wordObj.pos ? ` (${wordObj.pos})` : ''}`;
promptSub = wordObj.pos || '';
mutePromptText = wordObj.zh;
mutePromptSub = wordObj.exZh || '';
} else if (npcId === 'scholar') {
const choices = buildEnglishOptionsForWord(wordObj, cycleWords, randFn);
options = choices.map(c => c.word);
answerIndex = Math.max(0, choices.findIndex(c => c.correct));
if (!isFiller && chainBefore === 2 && canLightToday) {
questionMode = 'scramble_en';
scrambleTiles = buildScrambleTiles(wordObj.word, randFn);
const cloze = maskEnglishCloze(wordObj.ex, wordObj.word);
maskedEx = cloze.ok ? cloze.maskedEx : null;
promptText = `請重組字母拼出對應單字:${wordObj.zh}`;
promptSub = wordObj.pos ? `(${wordObj.pos})` : '';
} else {
questionMode = 'cloze_en';
const cloze = maskEnglishCloze(wordObj.ex, wordObj.word);
if (cloze.ok) {
maskedEx = cloze.maskedEx;
promptText = cloze.maskedEx;
promptSub = wordObj.exZh ? `${wordObj.zh}|${wordObj.exZh}` : wordObj.zh;
} else {
maskedEx = null;
const hintPrefix = wordObj.word.length > 1 ? `${wordObj.word[0]}... ` : '';
promptText = `請依中文線索選出正確單字:${wordObj.zh}(提示:${hintPrefix}共 ${wordObj.word.length} 字母)`;
promptSub = wordObj.exZh || '';
}
}
}
return {
n: wordObj.n,
wordObj,
isFiller,
canLightToday,
chainBefore,
questionMode,
promptText,
promptSub,
maskedEx,
options,
answerIndex,
scrambleTiles,
audioOptions,
muteOptions,
muteAnswerIndex,
mutePromptText,
mutePromptSub,
safeQ,
answered: false,
isCorrect: null,
outcome: null,
};
}
function getCycleWordsFromAll(allWords, cycleId) {
const cycleConfig = resolveCycleConfig(cycleId);
return (Array.isArray(allWords) ? allWords : []).filter(
w => w && Number(w.n) >= cycleConfig.startN && Number(w.n) <= cycleConfig.endN
);
}
function pickNextBazaarEntries(game, cycleWords, session, count, now = null, randFn = Math.random) {
const cycleState = ensureBazaarCycleState(game, session.cycleId);
const explicitDailyKey = (now !== null && now !== undefined) ? getBazaarDailyKey(now) : null;
if (explicitDailyKey && (!session.dailyKey || explicitDailyKey > session.dailyKey)) {
session.dailyKey = explicitDailyKey;
}
const activeDailyKey = explicitDailyKey || session.dailyKey || getBazaarDailyKey(new Date());
const dailyCap = session.dailyQuotaCap || BAZAAR_CONFIG.dailyLitCap || BAZAAR_CONFIG.dailyQuotaStep || 50;
const totalCap = BAZAAR_CONFIG.totalWordsPerCycle || 240;
const liveDailyCount = cycleState.dailyLitDate === activeDailyKey
? Math.max(0, Math.floor(Number(cycleState.dailyLitCount) || 0))
: 0;
let liveLitCount = 0;
for (const w of cycleWords) {
if (cycleState.litWords[String(w.n)]) liveLitCount++;
}
const remTotal = Math.max(0, totalCap - liveLitCount);
const remQuota = Math.min(Math.max(0, dailyCap - liveDailyCount), remTotal);
if (!Array.isArray(session.recentUsedN)) {
session.recentUsedN = [];
}
const batchUsedN = new Set();
const recentSet = new Set(session.recentUsedN);
const selected = [];
const canPick = (w, allowWrap = false) => {
if (!w) return false;
const n = Number(w.n);
if (batchUsedN.has(n)) return false;
if (!allowWrap && recentSet.has(n)) return false;
return true;
};
const pushPick = (w, canLightToday, isFiller) => {
batchUsedN.add(Number(w.n));
recentSet.add(Number(w.n));
session.recentUsedN.push(Number(w.n));
selected.push({
wordObj: w,
canLightToday,
isFiller,
chainBefore: getWordMistakeChainState(game, w.n).progress,
});
};
const fillFromBuckets = (allowWrap) => {
const unlitWords = cycleWords.filter(w => !cycleState.litWords[String(w.n)] && canPick(w, allowWrap));
const litWordsPool = cycleWords.filter(w => Boolean(cycleState.litWords[String(w.n)]) && canPick(w, allowWrap));
const tappablePool = unlitWords.filter(w => {
const st = getWordMistakeChainState(game, w.n);
return st.isLockedMistake && st.progress < 2;
});
if (remQuota > 0 && liveLitCount < totalCap) {
const canLightSlots = Math.min(count, remQuota);
const lockedUnlit = deterministicShuffle(
unlitWords.filter(w => getWordMistakeChainState(game, w.n).isLockedMistake),
randFn
);
const normalUnlit = deterministicShuffle(
unlitWords.filter(w => !getWordMistakeChainState(game, w.n).isLockedMistake),
randFn
);
let li = 0;
let ni = 0;
while (selected.length < canLightSlots && (li < lockedUnlit.length || ni < normalUnlit.length)) {
const shouldTryLocked = li < lockedUnlit.length && (ni >= normalUnlit.length || randFn() < 0.4);
if (shouldTryLocked) {
const cand = lockedUnlit[li++];
if (canPick(cand, allowWrap)) pushPick(cand, true, false);
} else {
const cand = normalUnlit[ni++];
if (canPick(cand, allowWrap)) pushPick(cand, true, false);
}
}
while (selected.length < canLightSlots && li < lockedUnlit.length) {
const cand = lockedUnlit[li++];
if (canPick(cand, allowWrap)) pushPick(cand, true, false);
}
}
if (selected.length < count) {
for (const w of deterministicShuffle(tappablePool, randFn)) {
if (selected.length >= count) break;
if (canPick(w, allowWrap)) pushPick(w, false, false);
}
}
if (selected.length < count) {
for (const w of deterministicShuffle(litWordsPool, randFn)) {
if (selected.length >= count) break;
if (canPick(w, allowWrap)) pushPick(w, false, true);
}
}
if (selected.length < count) {
for (const w of deterministicShuffle(cycleWords, randFn)) {
if (selected.length >= count) break;
if (canPick(w, allowWrap)) pushPick(w, false, true);
}
}
};
fillFromBuckets(false);
if (selected.length < count && cycleWords.length > batchUsedN.size) {
// 當可用字池於同場已輪過一遍,重置 recentUsedN(保留本盤與最後一題防連出重複)再補齊
const lastN = session.recentUsedN.length ? session.recentUsedN[session.recentUsedN.length - 1] : null;
recentSet.clear();
session.recentUsedN = [];
if (lastN !== null && cycleWords.length > batchUsedN.size + 1) {
recentSet.add(lastN);
session.recentUsedN.push(lastN);
}
fillFromBuckets(true);
}
let liveMode = 'practice';
if (remQuota > 0 && liveLitCount < totalCap) {
liveMode = 'normal';
} else if (remQuota === 0 && cycleWords.some(w => {
if (cycleState.litWords[String(w.n)]) return false;
const st = getWordMistakeChainState(game, w.n);
return st.isLockedMistake && st.progress < 2;
})) {
liveMode = 'chain_drill';
}
return { selected, liveMode, remDailyQuota: remQuota };
}
function buildWeaverPairBoardFromItems(itemsWithIndex, randFn) {
return {
leftCards: itemsWithIndex.map(({ item, itemIndex }) => ({
itemIndex,
n: item.n,
word: item.wordObj.word,
pos: item.wordObj.pos || '',
ipa: item.wordObj.ipa || '',
})),
rightCards: deterministicShuffle(
itemsWithIndex.map(({ item, itemIndex }) => ({
itemIndex,
n: item.n,
zh: item.wordObj.zh,
})),
randFn
),
};
}
/**
* 產生一場西域大市集 NPC 遭遇戰(timedMode 為 true 時動態抽題無限續題;否則固定 5 題相容標準介面)
*/
export function generateBazaarEncounter(game, allWords, uid, classInfo = {}, now = new Date(), opts = {}) {
const randFn = typeof opts.randFn === 'function' ? opts.randFn : Math.random;
const timedMode = Boolean(opts.timedMode);
const quota = getBazaarQuotaInfo(classInfo, now);
const cycleConfig = quota.modeState.cycleConfig;
const cycleId = quota.modeState.cycleId;
if (!cycleId || !cycleConfig || (!quota.modeState.isOpen && !quota.modeState.isForcedOpen)) {
throw new Error('西域萬國大市集尚未開市或目前未啟用');
}
const cycleState = ensureBazaarCycleState(game, cycleId);
const cycleWords = getCycleWordsFromAll(allWords, cycleId);
if (cycleWords.length === 0) {
throw new Error(`找不到 ${cycleId} 對應範圍的單字題庫`);
}
const summary = computeBazaarSummary(game, uid, cycleId, now);
const npcId = opts.forceNpcId || pickNextBazaarNpc(cycleState, randFn);
const initialCount = (!timedMode || npcId === 'weaver')
? (BAZAAR_CONFIG.encounterBatchSize || 5)
: 1;
const session = {
cycleId,
npcId,
mode: 'normal',
timedMode,
dailyKey: quota.dailyKey,
dailyQuotaCap: quota.dailyQuotaCap,
quotaMax: quota.maxLitQuota,
litBefore: summary.litCount,
dailyLitBefore: summary.dailyLitCount,
linesBefore: summary.totalLines,
classInfo,
progress: opts.progress || {},
recentUsedN: [],
items: [],
pairBoard: null,
settled: false,
settlement: null,
};
if (timedMode) {
const picked = pickNextBazaarEntries(game, cycleWords, session, initialCount, now, randFn);
session.mode = picked.liveMode;
session.items = picked.selected.map(entry => buildBazaarItemFromEntry(entry, npcId, cycleWords, randFn));
if (npcId === 'weaver') {
session.pairBoard = buildWeaverPairBoardFromItems(
session.items.map((item, itemIndex) => ({ item, itemIndex })),
randFn
);
}
return session;
}
const remQuota = summary.remDailyQuota;
let mode = 'practice';
if (remQuota > 0 && summary.litCount < BAZAAR_CONFIG.totalWordsPerCycle) {
mode = 'normal';
} else if (remQuota === 0 && summary.tappableChainWords.length > 0) {
mode = 'chain_drill';
}
session.mode = mode;
const batchSize = BAZAAR_CONFIG.encounterBatchSize || 5;
const wordByN = new Map(cycleWords.map(w => [Number(w.n), w]));
const selectedEntries = [];
const usedN = new Set();
const pushEntry = (wordObj, canLightToday, isFiller) => {
if (!wordObj || usedN.has(wordObj.n) || selectedEntries.length >= batchSize) return false;
usedN.add(wordObj.n);
selectedEntries.push({
wordObj,
canLightToday,
isFiller,
chainBefore: getWordMistakeChainState(game, wordObj.n).progress,
});
return true;
};
const litPool = cycleWords.filter(w => Boolean(cycleState.litWords[String(w.n)]));
const tappablePool = summary.tappableChainWords.map(n => wordByN.get(n)).filter(Boolean);
if (mode === 'normal') {
const canLightCap = Math.min(batchSize, remQuota);
const unlitWords = cycleWords.filter(w => !cycleState.litWords[String(w.n)]);
const lockedUnlit = [];
const normalUnlit = [];
for (const w of unlitWords) {
if (getWordMistakeChainState(game, w.n).isLockedMistake) lockedUnlit.push(w);
else normalUnlit.push(w);
}
const shuffledLocked = deterministicShuffle(lockedUnlit, randFn);
const shuffledNormal = deterministicShuffle(normalUnlit, randFn);
let lockedPicked = 0;
for (const w of shuffledLocked) {
if (lockedPicked >= 2 || selectedEntries.length >= canLightCap) break;
if (pushEntry(w, true, false)) lockedPicked++;
}
for (const w of shuffledNormal) {
if (selectedEntries.length >= canLightCap) break;
pushEntry(w, true, false);
}
for (const w of shuffledLocked) {
if (selectedEntries.length >= canLightCap) break;
pushEntry(w, true, false);
}
for (const w of deterministicShuffle(tappablePool, randFn)) {
if (selectedEntries.length >= batchSize) break;
pushEntry(w, false, false);
}
for (const w of deterministicShuffle(litPool, randFn)) {
if (selectedEntries.length >= batchSize) break;
pushEntry(w, false, true);
}
} else if (mode === 'chain_drill') {
for (const w of deterministicShuffle(tappablePool, randFn)) {
if (selectedEntries.length >= batchSize) break;
pushEntry(w, false, false);
}
for (const w of deterministicShuffle(litPool, randFn)) {
if (selectedEntries.length >= batchSize) break;
pushEntry(w, false, true);
}
for (const w of deterministicShuffle(cycleWords, randFn)) {
if (selectedEntries.length >= batchSize) break;
pushEntry(w, false, true);
}
} else {
for (const w of deterministicShuffle(litPool, randFn)) {
if (selectedEntries.length >= batchSize) break;
pushEntry(w, false, true);
}
for (const w of deterministicShuffle(cycleWords, randFn)) {
if (selectedEntries.length >= batchSize) break;
pushEntry(w, false, true);
}
}
const items = selectedEntries.map(entry => buildBazaarItemFromEntry(entry, npcId, cycleWords, randFn));
session.items = items;
session.pairBoard = npcId === 'weaver'
? buildWeaverPairBoardFromItems(items.map((item, itemIndex) => ({ item, itemIndex })), randFn)
: null;
session.recentUsedN = items.map(it => Number(it.n));
return session;
}
/**
* 限時模式動態抽取下一題(即時依據目前今日 50 格剩餘額度自動分流:正常點亮 / 敲鎖特訓 / 自由複習)
*/
export function drawNextBazaarItem(game, allWords, session, now = null, randFn = Math.random) {
if (!session || !session.cycleId) return null;
const cycleWords = getCycleWordsFromAll(allWords, session.cycleId);
if (!cycleWords.length) return null;
const picked = pickNextBazaarEntries(game, cycleWords, session, 1, now, randFn);
if (!picked.selected.length) return null;
session.mode = picked.liveMode;
const item = buildBazaarItemFromEntry(picked.selected[0], session.npcId, cycleWords, randFn);
session.items.push(item);
return {
item,
itemIndex: session.items.length - 1,
mode: picked.liveMode,
remDailyQuota: picked.remDailyQuota,
};
}
/**
* 限時模式為波斯織毯娘子抽取下一盤 5×5 配對卡片(自動對應全域 itemIndex)
*/
export function drawNextWeaverBoard(game, allWords, session, now = null, randFn = Math.random) {
if (!session || !session.cycleId) return null;
const cycleWords = getCycleWordsFromAll(allWords, session.cycleId);
if (!cycleWords.length) return null;
const batchSize = BAZAAR_CONFIG.encounterBatchSize || 5;
const picked = pickNextBazaarEntries(game, cycleWords, session, batchSize, now, randFn);
if (!picked.selected.length) return null;
session.mode = picked.liveMode;
const boardItems = [];
for (const entry of picked.selected) {
const item = buildBazaarItemFromEntry(entry, session.npcId || 'weaver', cycleWords, randFn);
session.items.push(item);
boardItems.push({ item, itemIndex: session.items.length - 1 });
}
const pairBoard = buildWeaverPairBoardFromItems(boardItems, randFn);
session.pairBoard = pairBoard;
return {
pairBoard,
mode: picked.liveMode,
remDailyQuota: picked.remDailyQuota,
};
}
/**
* 依本場實際答錯單字建置「戰後錯題列表與分批配對複習」資料(不改動全域 mistakes/litWords)
*/
export function buildWrongReviewDeck(session, allWords = [], randFn = Math.random) {
if (!session || !Array.isArray(session.items)) {
return { wrongWords: [], pages: [] };
}
const wrongByN = new Map();
for (const it of session.items) {
if (!it || !it.answered || it.isCorrect) continue;
const n = Number(it.n);
if (wrongByN.has(n)) continue;
wrongByN.set(n, {
n,
word: String(it.wordObj?.word || ''),
pos: String(it.wordObj?.pos || ''),
zh: String(it.wordObj?.zh || ''),
ex: String(it.wordObj?.ex || ''),
exZh: String(it.wordObj?.exZh || ''),
isWrongWord: true,
});
}
const wrongWords = Array.from(wrongByN.values());
if (wrongWords.length === 0) {
return { wrongWords: [], pages: [] };
}
// 建立備用干擾字池:先拿本場答對的單字,再用同周期單字補足
const distractorPool = [];
const seenDistractorN = new Set(wrongWords.map(w => w.n));
for (const it of session.items) {
if (!it || !it.answered || !it.isCorrect) continue;
const n = Number(it.n);
if (seenDistractorN.has(n)) continue;
seenDistractorN.add(n);
distractorPool.push({
n,
word: String(it.wordObj?.word || ''),
pos: String(it.wordObj?.pos || ''),
zh: String(it.wordObj?.zh || ''),
isWrongWord: false,
});
}
const cycleWords = getCycleWordsFromAll(allWords, session.cycleId);
for (const w of deterministicShuffle(cycleWords, randFn)) {
const n = Number(w.n);
if (seenDistractorN.has(n)) continue;
seenDistractorN.add(n);
distractorPool.push({
n,
word: String(w.word || ''),
pos: String(w.pos || ''),
zh: String(w.zh || ''),
isWrongWord: false,
});
}
const PAGE_SIZE = 5;
const pages = [];
for (let i = 0; i < wrongWords.length; i += PAGE_SIZE) {
const chunk = wrongWords.slice(i, i + PAGE_SIZE);
const pageCards = chunk.map(w => ({ ...w }));
const targetMinCards = Math.min(4, wrongWords.length + distractorPool.length);
const pageNSet = new Set(pageCards.map(c => c.n));
for (const d of distractorPool) {
if (pageCards.length >= targetMinCards) break;
if (pageNSet.has(d.n)) continue;
pageNSet.add(d.n);
pageCards.push({ ...d });
}
const leftCards = deterministicShuffle(pageCards, randFn).map(c => ({
pairKey: String(c.n),
n: c.n,
word: c.word,
pos: c.pos,
isWrongWord: Boolean(c.isWrongWord),
}));
let rightShuffled = deterministicShuffle(pageCards, randFn);
if (pageCards.length >= 2) {
const leftSig = leftCards.map(c => String(c.n)).join(',');
for (let attempt = 0; attempt < 6; attempt++) {
if (rightShuffled.map(c => String(c.n)).join(',') !== leftSig) break;
rightShuffled = deterministicShuffle(pageCards, randFn);
}
if (rightShuffled.map(c => String(c.n)).join(',') === leftSig) {
rightShuffled = [...rightShuffled.slice(1), rightShuffled[0]];
}
}
const rightCards = rightShuffled.map(c => ({
pairKey: String(c.n),
n: c.n,
zh: c.zh,
isWrongWord: Boolean(c.isWrongWord),
}));
pages.push({
pageIndex: pages.length,
wrongCount: chunk.length,
leftCards,
rightCards,
});
}
return { wrongWords, pages };
}
/**
* 記錄單題作答結果,即時推進錯題三鎖鏈或點亮賓果格(每題具備冪等保護)
*/
export function recordBazaarItemOutcome(game, session, itemIndex, isCorrect, chosenLabel = '', now = null) {
if (!session || !Array.isArray(session.items) || !session.items[itemIndex]) {
return null;
}
const item = session.items[itemIndex];
if (item.answered) return item.outcome;
item.answered = true;
item.isCorrect = Boolean(isCorrect);
const cycleState = ensureBazaarCycleState(game, session.cycleId);
const n = item.n;
const nKey = String(n);
const curDailyKey = (now !== null && now !== undefined)
? getBazaarDailyKey(now)
: (session.dailyKey || getBazaarDailyKey(new Date()));
if (curDailyKey && (!session.dailyKey || curDailyKey > session.dailyKey)) {
session.dailyKey = curDailyKey;
}
const activeDailyKey = curDailyKey || session.dailyKey;
const dailyCap = session.dailyQuotaCap || BAZAAR_CONFIG.dailyLitCap || BAZAAR_CONFIG.dailyQuotaStep || 50;
const totalCap = BAZAAR_CONFIG.totalWordsPerCycle || 240;
if (cycleState.dailyLitDate !== activeDailyKey) {
cycleState.dailyLitDate = activeDailyKey;
cycleState.dailyLitCount = 0;
}
if (item.isFiller) {
if (item.isCorrect) {
recordCorrect(game, item.safeQ);
} else if (!cycleState.litWords[nKey]) {
recordMistake(game, item.safeQ, chosenLabel || '誤選', 'bazaar');
}
item.outcome = {
chainBefore: 0,
chainAfter: 0,
newlyLit: false,
isFiller: true,
grainBonus: 0,
};
return item.outcome;
}
const before = getWordMistakeChainState(game, n);
const currentLitCount = Object.keys(cycleState.litWords).filter(k => cycleState.litWords[k]).length;
const canConsumeDailySlot = () => (
item.canLightToday
&& !cycleState.litWords[nKey]
&& currentLitCount < totalCap
&& cycleState.dailyLitCount < dailyCap
);
if (item.isCorrect) {
if (before.isLockedMistake) {
recordCorrect(game, item.safeQ);
const m = game?.mistakes?.[`english_${n}`];
const rev = Number(m?.reviewCorrectCount) || 0;
if (rev >= 3) {
cycleState.clearedMistakes += 1;
let newlyLit = false;
if (canConsumeDailySlot()) {
cycleState.litWords[nKey] = true;
cycleState.dailyLitCount += 1;
newlyLit = true;
}
item.outcome = {
chainBefore: before.progress,
chainAfter: 3,
newlyLit,
chainShattered: true,
grainBonus: 0,
};
return item.outcome;
}
item.outcome = {
chainBefore: before.progress,
chainAfter: rev,
newlyLit: false,
chainCracked: true,
grainBonus: 0,
};
return item.outcome;
}
recordCorrect(game, item.safeQ);
let newlyLit = false;
if (canConsumeDailySlot()) {
cycleState.litWords[nKey] = true;
cycleState.dailyLitCount += 1;
newlyLit = true;
}
item.outcome = {
chainBefore: 0,
chainAfter: 1,
newlyLit,
grainBonus: 0,
};
return item.outcome;
}
recordMistake(game, item.safeQ, chosenLabel || '誤選', 'bazaar');
item.outcome = {
chainBefore: before.progress,
chainAfter: 0,
newlyLit: false,
chainReset: true,
grainBonus: 0,
};
return item.outcome;
}
/**
* 巡檢並自動補發任何已達個人連線門檻卻尚未領取的寶箱(防止戰中中斷退出漏領)
*/
export function claimPendingPersonalMilestones(game, uid, cycleId, classInfo = null, now = new Date(), progress = {}) {
const nowMs = toNowMs(now);
const nowDate = new Date(nowMs);
const cycleConfig = resolveCycleConfig(cycleId);
const cycleState = ensureBazaarCycleState(game, cycleId);
const summary = computeBazaarSummary(game, uid, cycleId, nowDate);
const dState = derive(progress || {}, classInfo || null, game, nowMs);
const cps = Math.max(1, totalProd(game, dState) || 1);
getMerchantStatus(game, nowDate);
const m = game.merchant;
const newPersonalMilestones = [];
for (const pm of BAZAAR_CONFIG.personalMilestones || []) {
const lineKey = String(pm.lines);
if (summary.totalLines >= pm.lines && !cycleState.claimedLines[lineKey]) {
cycleState.claimedLines[lineKey] = true;
const granted = { lines: pm.lines, label: pm.label, desc: pm.desc };
if (pm.grainSec) {
granted.grain = grantGrain(game, Math.max(100, Math.round(cps * pm.grainSec)));
}
if (pm.merchantGold) {
m.gold = (Number(m.gold) || 0) + pm.merchantGold;
granted.merchantGold = pm.merchantGold;
}
if (pm.scrollType) {
granted.scroll = grantScroll(game, pm.scrollType, pm.scrollCount || 1);
}
if (pm.coupons) {
m.coupons = (Number(m.coupons) || 0) + pm.coupons;
granted.coupons = pm.coupons;
}
if (pm.tallies) {
grantTally(game, pm.tallies);
granted.tallies = pm.tallies;
}
if (pm.isGrandPrize && cycleConfig?.grandTitle) {
game.titles = Array.isArray(game.titles) ? game.titles : [];
if (!game.titles.includes(cycleConfig.grandTitle)) {
game.titles.push(cycleConfig.grandTitle);
}
game.curTitle = cycleConfig.grandTitle;
granted.title = cycleConfig.grandTitle;
granted.titleDef = getTitleDef(cycleConfig.grandTitle);
}
newPersonalMilestones.push(granted);
}
}
return { newPersonalMilestones, summary };
}
/**
* 結算整場遭遇戰:檢查個人連線里程碑、發放 120 線大獎稱號、黑市金幣/折扣與週末券(具備冪等保護)
*/
export function settleBazaarEncounter(game, uid, session, classInfo = null, now = new Date()) {
if (!session) return null;
if (session.settled) return session.settlement;
const nowMs = toNowMs(now);
const nowDate = new Date(nowMs);
const cycleState = ensureBazaarCycleState(game, session.cycleId);
cycleState.encounters += 1;
cycleState.updatedAt = Date.now();
const resolvedClassInfo = classInfo || session.classInfo || null;
const { newPersonalMilestones, summary: afterSummary } = claimPendingPersonalMilestones(
game,
uid,
session.cycleId,
resolvedClassInfo,
nowDate,
session.progress || {}
);
const m = game.merchant;
m.marketUnlocked = true;
const answeredItems = (session.items || []).filter(it => Boolean(it && it.answered));
let correctCount = 0;
for (const it of answeredItems) {
if (it.isCorrect) correctCount++;
}
let roundMult;
let roundDiscount;
let roundDiscountLabel;
if (session.timedMode || answeredItems.length > 5) {
const bargain = calcBargainDiscount(correctCount);
roundMult = bargain.todayMult;
roundDiscount = bargain.discount;
roundDiscountLabel = bargain.discountLabel;
} else {
const clampedCorrect = Math.max(0, Math.min(5, correctCount));
roundMult = BARGAIN_MULT_MAP[clampedCorrect];
roundDiscount = BARGAIN_DISCOUNT_MAP[clampedCorrect];
roundDiscountLabel = BARGAIN_LABEL_MAP[clampedCorrect];
}
if (m.todayMult === null || m.todayMult === undefined || roundMult <= m.todayMult) {
m.todayMult = roundMult;
m.todayDiscount = roundDiscount;
m.todayDiscountLabel = roundDiscountLabel;
}
m.dayRewWordIds = Array.isArray(m.dayRewWordIds) ? m.dayRewWordIds : [];
const dailyCoinCap = MERCHANT.dailyCoinCap || 16;
let merchantCoinsEarned = 0;
let merchantExpEarned = 0;
for (const it of answeredItems) {
if (!it.isCorrect) continue;
if (!m.dayRewWordIds.includes(it.n) && (Number(m.dayCoins) || 0) < dailyCoinCap) {
m.dayRewWordIds.push(it.n);
m.dayCoins = (Number(m.dayCoins) || 0) + 1;
m.gold = (Number(m.gold) || 0) + 1;
m.exp = (Number(m.exp) || 0) + 1;
merchantCoinsEarned++;
merchantExpEarned++;
}
}
const tpDay = new Date(nowMs + TAIPEI_OFFSET_MS).getUTCDay();
let weekendCouponGranted = false;
if ((tpDay === 0 || tpDay === 6) && !m.weekendRewarded) {
m.weekendRewarded = true;
m.coupons = (Number(m.coupons) || 0) + 1;
weekendCouponGranted = true;
}
session.settled = true;
session.settlement = {
cycleId: session.cycleId,
npcId: session.npcId,
answeredCount: answeredItems.length,
correctCount,
litBefore: session.litBefore,
litAfter: afterSummary.litCount,
linesBefore: session.linesBefore,
linesAfter: afterSummary.totalLines,
newPersonalMilestones,
merchantCoinsEarned,
merchantExpEarned,
discountLabel: m.todayDiscountLabel,
roundDiscountLabel,
todayMult: m.todayMult,
weekendCouponGranted,
summary: afterSummary,
};
return session.settlement;
}
// ============================================================================
// js/bazaar.js
// 西域萬國大市集(Western Grand Bazaar)核心邏輯模組(純資料與規則計算,無 DOM 操作)
// - 10 卷 5×5 個人確定性亂數賓果(240 單字 + 10 格中央賜福 = 250 格 / 120 條連線)
// - 每日早上 07:00(UTC+8)累積點亮額度(50 -> 100 -> 150 -> 200 -> 240)
// - 錯題三鎖鏈與全域 game.mistakes 雙向同步
// - 4 大市集角色隨機遭遇戰與結算引擎
// ============================================================================
import { BAZAAR_CONFIG, MERCHANT, getTitleDef } from './config.js?v=20261129_v1';
import { todayStr, shuffle } from './util.js?v=20261129_v1';
import {
grantGrain,
grantTally,
grantScroll,
recordMistake,
recordCorrect,
derive,
totalProd,
} from './engine.js?v=20261129_v1';
import { resolveCaravanModeState } from './event-schedule.js?v=20261129_v1';
import {
loadEnglishWords,
speakWord,
maskExampleSentence,
getMerchantStatus,
calcBargainDiscount,
} from './merchant.js?v=20261129_v1';
export { loadEnglishWords, speakWord };
const DAY_MS = 86400 * 1000;
const TAIPEI_OFFSET_MS = 8 * 3600 * 1000;
const NPC_IDS = ['captain', 'weaver', 'lutist', 'scholar'];
const OPTION_LABELS = ['A', 'B', 'C', 'D'];
const DEFAULT_ZH_FALLBACK = ['美好', '時間', '工作', '發現', '保持', '出發', '朋友', '學校', '力量', '平靜'];
const DEFAULT_WORD_FALLBACK = ['time', 'work', 'good', 'make', 'find', 'keep', 'life', 'hope'];
const BAZAAR_LINES = [
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[0, 5, 10, 15, 20],
[1, 6, 11, 16, 21],
[2, 7, 12, 17, 22],
[3, 8, 13, 18, 23],
[4, 9, 14, 19, 24],
[0, 6, 12, 18, 24],
[4, 8, 12, 16, 20],
];
const BARGAIN_MULT_MAP = { 5: 1.0, 4: 2.0, 3: 3.0, 2: 4.0, 1: 4.5, 0: 5.0 };
const BARGAIN_DISCOUNT_MAP = { 5: 0.2, 4: 0.4, 3: 0.6, 2: 0.8, 1: 0.9, 0: 1.0 };
const BARGAIN_LABEL_MAP = { 5: '2折', 4: '4折', 3: '6折', 2: '8折', 1: '9折', 0: '原價' };
const IRREGULAR_EN_FORMS = {
find: ['found'],
fall: ['fell', 'fallen'],
choose: ['chose', 'chosen'],
spend: ['spent'],
catch: ['caught'],
hide: ['hid', 'hidden'],
throw: ['threw', 'thrown'],
win: ['won'],
bite: ['bit', 'bitten'],
draw: ['drew', 'drawn'],
blow: ['blew', 'blown'],
leaf: ['leaves'],
tooth: ['teeth'],
foot: ['feet'],
mouse: ['mice'],
child: ['children'],
man: ['men'],
woman: ['women'],
go: ['went', 'gone'],
come: ['came'],
make: ['made'],
take: ['took', 'taken'],
give: ['gave', 'given'],
get: ['got', 'gotten'],
say: ['said'],
see: ['saw', 'seen'],
know: ['knew', 'known'],
think: ['thought'],
bring: ['brought'],
buy: ['bought'],
teach: ['taught'],
eat: ['ate', 'eaten'],
drink: ['drank', 'drunk'],
write: ['wrote', 'written'],
read: ['read'],
run: ['ran'],
sit: ['sat'],
stand: ['stood'],
begin: ['began', 'begun'],
break: ['broke', 'broken'],
build: ['built'],
feel: ['felt'],
fly: ['flew', 'flown'],