/** * 随机种子相关工具函数 * 统一管理随机种子的生成和处理 * 种子范围:0 到 2^23-1 (0 到 8388607) */ // 最大种子值:2^23 = 8388608 export const MAX_RANDOM_SEED = Math.pow(2, 23) /** * 生成随机种子 * 生成范围在 0 到 2^23-1 之间的随机种子 * @returns {number} 随机种子值 (0 <= seed < 2^23) */ export const generateRandomSeed = () => { return Math.floor(Math.random() * MAX_RANDOM_SEED) } /** * 验证随机种子是否有效 * @param {*} seed - 待验证的种子值 * @returns {boolean} 是否为有效种子 */ export const isValidSeed = (seed) => { // 种子必须是非负整数,允许0 if (seed === null || seed === undefined) { return false } const num = Number(seed) return !isNaN(num) && num >= 0 && num < MAX_RANDOM_SEED && Number.isInteger(num) } /** * 格式化随机种子显示 * @param {number} seed - 种子值 * @returns {string} 格式化后的字符串 */ export const formatSeed = (seed) => { if (!isValidSeed(seed)) { return '' } return seed.toString() } /** * 解析输入的随机种子 * @param {string|number} input - 用户输入的值 * @returns {number|null} 解析后的种子值,无效时返回null */ export const parseSeedInput = (input) => { if (input === null || input === undefined || input === '') return null const num = parseInt(input) if (isNaN(num) || num < 0) { return null } // 限制最大值为 2^23 - 1 return Math.min(num, MAX_RANDOM_SEED - 1) } /** * 获取随机种子的优先级 * 优先级:自定义 > 拆分 > 项目 > 默认 * @param {Object} options - 配置选项 * @param {number} options.customSeed - 自定义种子 * @param {number} options.splitSeed - 拆分种子 * @param {number} options.projectSeed - 项目种子 * @param {boolean} options.useCustom - 是否使用自定义种子 * @returns {Object} { seed: number, source: string } */ export const getRandomSeedWithPriority = (options = {}) => { const { customSeed, splitSeed, projectSeed, useCustom = false } = options // 如果指定使用自定义种子且有效 if (useCustom && isValidSeed(customSeed)) { return { seed: customSeed, source: 'custom' } } // 检查拆分种子 if (isValidSeed(splitSeed)) { return { seed: splitSeed, source: 'split' } } // 检查项目种子 if (isValidSeed(projectSeed)) { return { seed: projectSeed, source: 'project' } } // 生成新种子 return { seed: generateRandomSeed(), source: 'generated' } } export default { MAX_RANDOM_SEED, generateRandomSeed, isValidSeed, formatSeed, parseSeedInput, getRandomSeedWithPriority }