UNPKG

tiny-essentials

Version:

Collection of small, essential scripts designed to be used across various projects. These simple utilities are crafted for speed, ease of use, and versatility.

673 lines 26.7 kB
export default TinyDayNightCycle; /** * Represents a mapping of weather type names to their selected values. * Each key is the name of a weather type, and the value is either: * - a string containing the selected weather configuration name, or * - `null` if no selection has been made. */ export type SelectedWeather = Record<string, string | null>; /** * Callback used to dynamically calculate weather probabilities. */ export type WeatherCallback = (configs: { hour: number; minute: number; currentMinutes: number; isDay: boolean; season: string; weather: SelectedWeather; }) => number; /** * Represents the complete set of weather configurations. */ export type WeatherCfgs = { /** * - Default weather configuration applied when no specific condition matches. */ default: WeatherCfg; /** * - Weather configuration used during daytime hours. */ day: WeatherCfg; /** * - Weather configuration used during nighttime hours. */ night: WeatherCfg; /** * - Specific weather configurations mapped by hour (e.g., `"06": WeatherCfg`). */ hours: Record<string, WeatherCfg>; /** * - Specific weather configurations mapped by season name. */ seasons: Record<string, WeatherCfg>; }; /** * A weather configuration object mapping weather types to probability weights * or dynamic WeatherCallback functions. */ export type WeatherCfg = Record<string, number | WeatherCallback>; /** * Weather data with resolved numeric probability values. */ export type WeatherData = Record<string, number>; /** * Represents the data for a moon's current phase. */ export type MoonData = { /** * - The name of the moon. */ name: string; /** * - The current phase index (zero-based) within the moon's cycle. */ phaseIndex: number; /** * - The descriptive name of the current phase. */ phaseName: string; /** * - The total number of phases/days in the moon's full cycle. */ cycleLength: number; }; /** * Represents the raw data structure for a moon's cycle. */ export type MoonRaw = { /** * - The name of the moon. */ name: string; /** * - Total number of phases in the moon's cycle. */ cycleLength: number; /** * - The current phase index (0-based). */ currentPhase: number; /** * - Optional list of names for each phase in the cycle. */ phaseNames?: string[] | undefined; }; /** * Represents a mapping of weather type names to their selected values. * Each key is the name of a weather type, and the value is either: * - a string containing the selected weather configuration name, or * - `null` if no selection has been made. * * @typedef {Record<string, string|null>} SelectedWeather */ /** * Callback used to dynamically calculate weather probabilities. * * @callback WeatherCallback * @param {Object} configs - Contextual information about the current time and weather state. * @param {number} configs.hour - Current in-game hour (0–23). * @param {number} configs.minute - Current in-game minute (0–59). * @param {number} configs.currentMinutes - Minutes since midnight (0–1439). * @param {boolean} configs.isDay - Whether it's currently daytime. * @param {string} configs.season - Current season. * @param {SelectedWeather} configs.weather - Current active weather types or nulls if none. * @returns {number} Probability weight for the weather type. */ /** * Represents the complete set of weather configurations. * * @typedef {Object} WeatherCfgs * @property {WeatherCfg} default - Default weather configuration applied when no specific condition matches. * @property {WeatherCfg} day - Weather configuration used during daytime hours. * @property {WeatherCfg} night - Weather configuration used during nighttime hours. * @property {Record<string, WeatherCfg>} hours - Specific weather configurations mapped by hour (e.g., `"06": WeatherCfg`). * @property {Record<string, WeatherCfg>} seasons - Specific weather configurations mapped by season name. */ /** * A weather configuration object mapping weather types to probability weights * or dynamic WeatherCallback functions. * * @typedef {Record<string, number | WeatherCallback>} WeatherCfg */ /** * Weather data with resolved numeric probability values. * * @typedef {Record<string, number>} WeatherData */ /** * Represents the data for a moon's current phase. * * @typedef {Object} MoonData * @property {string} name - The name of the moon. * @property {number} phaseIndex - The current phase index (zero-based) within the moon's cycle. * @property {string} phaseName - The descriptive name of the current phase. * @property {number} cycleLength - The total number of phases/days in the moon's full cycle. */ /** * Represents the raw data structure for a moon's cycle. * * @typedef {Object} MoonRaw * @property {string} name - The name of the moon. * @property {number} cycleLength - Total number of phases in the moon's cycle. * @property {number} currentPhase - The current phase index (0-based). * @property {string[]} [phaseNames] - Optional list of names for each phase in the cycle. */ /** * TinyDayNightCycle is a lightweight and flexible JavaScript library designed to simulate day and * night cycles along with seasonal changes, moons, weather patterns, and in-game time tracking. * It allows you to manage and customize time progression, including hours, * minutes, and seconds, as well as date transitions with support for variable month lengths and years. * * This system also supports dynamic weather changes, moon phases, * and seasonal adjustments, making it ideal for game development, simulations, * or any interactive experience that requires realistic or custom time and environmental cycles. * * With easy-to-use methods and configurable settings, TinyDayNightCycle provides * you with precise control over the flow of time and weather in your application. * * This class provides: * - Customizable day/night cycle with variable sunrise/sunset. * - Calendar system with adjustable month lengths. * - Dynamic weather with multiple configurable probability layers. * - Multi-moon phase tracking. * * Time and date calculations are independent from the real world and can run at any speed. */ declare class TinyDayNightCycle { /** * @param {number} dayStart - Hour of the day start (0-23) * @param {number} nightStart - Hour of the night start (0-23) */ constructor(dayStart?: number, nightStart?: number); /** * Sets the number of in-game seconds representing a full day. * Keeps the proportion based on the current `hourSize` and `minuteSize` if `autoSizeAdjuste` is enabled. * @param {number} value - Positive finite number representing seconds in a full day. * @throws {Error} If `value` is not a positive finite number. */ set daySize(value: number); /** * Gets the number of in-game seconds representing a full day. * @returns {number} */ get daySize(): number; /** * Sets whether automatic size adjustment is enabled. * @param {boolean} value - `true` to keep the proportional relation between day, hour, and minute sizes; `false` to disable auto-adjustment. * @throws {TypeError} If `value` is not a boolean. */ set autoSizeAdjuste(value: boolean); /** * Gets whether automatic size adjustment is enabled. * @returns {boolean} */ get autoSizeAdjuste(): boolean; /** * Sets the number of in-game seconds representing a full hour. * Keeps the proportion based on the current `daySize` and `minuteSize` if `autoSizeAdjuste` is enabled. * @param {number} value - Positive finite number representing seconds in a full hour. * @throws {Error} If `value` is not a positive finite number. */ set hourSize(value: number); /** * Gets the number of in-game seconds representing a full hour. * @returns {number} */ get hourSize(): number; /** * Sets the number of in-game seconds representing a full minute. * Keeps the proportion based on the current `daySize` and `hourSize` if `autoSizeAdjuste` is enabled. * @param {number} value - Positive finite number representing seconds in a full minute. * @throws {Error} If `value` is not a positive finite number. */ set minuteSize(value: number); /** * Gets the number of in-game seconds representing a full minute. * @returns {number} */ get minuteSize(): number; /** * Indicates whether this instance has been destroyed. * @type {boolean} */ get isDestroyed(): boolean; /** * Sets the current time in seconds since midnight. * Also updates the currentMinutes property accordingly. * @param {number} value - Current seconds since midnight (0 to 86399). * @throws {TypeError} If the value is not a number. * @throws {RangeError} If the value is outside the valid range. */ set currentSeconds(value: number); /** * Gets the current time in seconds since midnight. * @returns {number} Current seconds (0 to 86399). */ get currentSeconds(): number; /** * Sets the current time in minutes since midnight. * Also updates the currentSeconds property accordingly (seconds set to zero). * @param {number} value - Current minutes since midnight (0 to 1439). * @throws {TypeError} If the value is not a number. * @throws {RangeError} If the value is outside the valid range. */ set currentMinutes(value: number); /** * Gets the current time in minutes since midnight. * @returns {number} Current minutes (0 to 1439). */ get currentMinutes(): number; /** * Sets the current time in hours since midnight. * Accepts decimal numbers to specify partial hours. * Also updates currentMinutes and currentSeconds accordingly. * @param {number} value - Current hours since midnight (0 to less than 24). * @throws {TypeError} If the value is not a finite number. * @throws {RangeError} If the value is outside the valid range. */ set currentHours(value: number); /** * Gets the current time in hours since midnight. * May be a decimal value (e.g., 14.5 = 14:30). * @returns {number} Current hours (0 to less than 24). */ get currentHours(): number; /** * Returns all moons with their current phase details. * @returns {MoonData[]} Array of moons including their name, current phase index, phase name, and cycle length. */ get moons(): MoonData[]; /** * Returns a list of all season names currently configured. * @returns {string[]} Array of season names. */ get seasons(): string[]; /** * Sets the hour at which day starts. * @param {number} value Hour (0-23). * @throws {TypeError} If value is not a number. */ set dayStart(value: number); /** @returns {number} Hour at which day starts (0-23). */ get dayStart(): number; /** * Sets the hour at which night starts. * @param {number} value Hour (0-23). * @throws {TypeError} If value is not a number. */ set nightStart(value: number); /** @returns {number} Hour at which night starts (0-23). */ get nightStart(): number; /** * Sets the current weather type. * @param {SelectedWeather} value Weather type strings or nulls for no weather. * @throws {TypeError} If value is not a string or null. */ set weather(value: SelectedWeather); /** @returns {SelectedWeather} Currently active weather types or nulls if none. */ get weather(): SelectedWeather; /** * Sets the current season. * Must be one of the configured seasons. * @param {string} value Season name. * @throws {TypeError} If value is not a string or not a configured season. */ set currentSeason(value: string); /** @returns {string} Currently active season name. */ get currentSeason(): string; /** * Sets the current day of the month. * @param {number} value Day number. * @throws {TypeError} If value is not a number. */ set currentDay(value: number); /** @returns {number} Current day of the month. */ get currentDay(): number; /** * Sets the current month. * @param {number} value Month number. * @throws {TypeError} If value is not a number. */ set currentMonth(value: number); /** @returns {number} Current month number. */ get currentMonth(): number; /** * Sets the current year. * @param {number} value Year count. * @throws {TypeError} If value is not a number. */ set currentYear(value: number); /** @returns {number} Current year count. */ get currentYear(): number; /** * Sets a custom configuration for the number of days in each month. * This allows for non-standard calendar systems. * @param {number[]} value - An object where keys are month numbers and values are the number of days. */ set monthDays(value: number[]); /** * Returns a shallow copy of the mapping of month numbers to days. * Can be customized for non-standard calendar systems. * @returns {number[]} Object mapping month number to days. */ get monthDays(): number[]; /** * Sets the weather duration range in minutes. * @param {{min: number, max: number}} value Object with min and max durations. * @throws {TypeError} If value or its min/max are invalid. */ set weatherDuration(value: { min: number; max: number; }); /** * Returns the configured range of weather durations in minutes. * @returns {{min: number, max: number}} Object with min and max weather duration. */ get weatherDuration(): { min: number; max: number; }; /** * Sets the remaining time for current weather in minutes. * @param {number} value Minutes remaining. * @throws {TypeError} If value is not a number. */ set weatherTimeLeft(value: number); /** @returns {number} Minutes left until current weather expires. */ get weatherTimeLeft(): number; /** * Sets the entire weather configuration object. * Accepts default, day, night, hours, and seasons settings. * @param {WeatherCfgs} config - The new weather configuration. * @throws {TypeError} If the provided value is not a valid object or contains invalid data types. */ set weatherConfig(config: WeatherCfgs); /** * Returns the entire weather configuration object. * Includes default, day, night, hours, and seasons settings. * @returns {WeatherCfgs} Deep copy of the weather configuration. */ get weatherConfig(): WeatherCfgs; /** --------------------- SEASON SYSTEM --------------------- */ /** * Adds or updates a season with the provided numeric values. * * @param {string} name - The name of the season to add or update. * @param {number[]} values - An array of month values associated with the season. * @throws {TypeError} If `name` is not a string or `values` is not an array of numbers. */ addSeason(name: string, values: number[]): void; /** * Removes a season from the collection. * * @param {string} name - The name of the season to remove. * @throws {TypeError} If `name` is not a string. */ removeSeason(name: string): void; /** * Checks whether a season exists in the collection. * * @param {string} name - The name of the season to check. * @returns {boolean} `true` if the season exists, otherwise `false`. * @throws {TypeError} If `name` is not a string. */ hasSeason(name: string): boolean; /** * Retrieves the mouth values associated with a season. * * @param {string} name - The name of the season to retrieve. * @returns {number[]} A copy of the month values for the specified season. * @throws {TypeError} If `name` is not a string. * @throws {Error} If the season does not exist. */ getSeason(name: string): number[]; /** --------------------- TIME SYSTEM --------------------- */ /** * Sets the internal time directly. * @param {Object} settings * @param {number} [settings.hour=0] - 0 to 23 * @param {number} [settings.minute=0] - 0 to 59 * @param {number} [settings.second=0] - 0 to 59 */ setTime({ hour, minute, second }: { hour?: number | undefined; minute?: number | undefined; second?: number | undefined; }): void; /** * Adds time to the current clock. * @param {Object} settings * @param {number} [settings.hours=0] * @param {number} [settings.minutes=0] * @param {number} [settings.seconds=0] */ addTime({ hours, minutes, seconds }: { hours?: number | undefined; minutes?: number | undefined; seconds?: number | undefined; }): void; /** * Returns the current time as both an object and a formatted string, * using the in-game time scale. * * @param {Object} [settings={}] - Optional configuration for time calculation. * @param {number} [settings.hourSize=this.#hourSize] - Number of in-game seconds representing an hour. * @param {number} [settings.minuteSize=this.#minuteSize] - Number of in-game seconds representing a minute. * @param {boolean} [settings.withSeconds=false] - Whether to include seconds in the formatted string. * @returns {{ * hour: number, * minute: number, * second: number, * formatted: string * }} An object containing the hour, minute, second, and the formatted time string. */ getTime({ withSeconds, hourSize, minuteSize }?: { hourSize?: number | undefined; minuteSize?: number | undefined; withSeconds?: boolean | undefined; }): { hour: number; minute: number; second: number; formatted: string; }; /** * Determines whether the current time is considered day. * Day is defined as the period between `dayStart` and `nightStart`. * @returns {boolean} True if current time is day, false otherwise. */ isDay(): boolean; /** * Calculates the number of minutes until the next day period starts. * @returns {number} Minutes until day start. */ minutesUntilDay(): number; /** * Calculates the number of seconds until the next day period starts. * @returns {number} Seconds until day start. */ secondsUntilDay(): number; /** * Calculates the number of hours until the next day period starts. * @returns {number} Hours until day start. */ hoursUntilDay(): number; /** * Calculates the number of minutes until the next night period starts. * @returns {number} Minutes until night start. */ minutesUntilNight(): number; /** * Calculates the number of seconds until the next night period starts. * @returns {number} Seconds until night start. */ secondsUntilNight(): number; /** * Calculates the number of hours until the next night period starts. * @returns {number} Hours until night start. */ hoursUntilNight(): number; /** * Helper method to calculate time until a specified hour. * Works in seconds internally for higher precision. * Wraps around if target hour is earlier than current time. * Supports returning time in minutes, seconds, or hours. * * @param {number} targetHour - The target hour (0–23). * @param {'minutes'|'seconds'|'hours'} unit - The unit to return. * @returns {number} Time until target hour, in the specified unit. */ timeUntil(targetHour: number, unit: "minutes" | "seconds" | "hours"): number; /** * Instantly sets the current time to the start of the specified phase. * @param {"day"|"night"} phase - The phase to set the time to. */ setTo(phase: "day" | "night"): void; /** --------------------- DAY/MONTH/YEAR SYSTEM --------------------- */ /** * Advances the current date by one day. * Automatically wraps months and years based on the configured month days. * Also updates the season and advances moon phases by 1. * @param {number} [amount=1] - Number of days to move forward. */ nextDay(amount?: number): void; /** * Moves the current date backward by one day. * Automatically wraps months and years based on the configured month days. * Also updates the season and rewinds moon phases by 1. * @param {number} [amount=1] - Number of days to move backward. */ prevDay(amount?: number): void; /** * Updates the current season based on the month. */ updateSeason(): void; /** --------------------- WEATHER SYSTEM --------------------- */ /** * Sets the weather configuration. * @param {WeatherCfgs} config * An object defining default probabilities, time-based probabilities, day/night differences, and seasonal probabilities. */ setWeatherConfig(config: WeatherCfgs): void; /** * Sets the minimum and maximum duration for any weather type. * @param {number} minMinutes - Minimum duration in minutes. * @param {number} maxMinutes - Maximum duration in minutes. */ setWeatherDuration(minMinutes: number, maxMinutes: number): void; /** * Updates the remaining time for the current weather. * Automatically selects a new weather type if time runs out. * @param {number} minutesPassed - Number of in-game minutes passed since last update. */ updateWeatherTimer(minutesPassed: number): void; /** * Forces the weather to a specific type, optionally for a given duration. * @param {Object} settings - Configuration object. * @param {string} [settings.where='main'] - The target weather zone or location key. * @param {string|null} settings.type - The weather type (e.g., "sunny", "rain", "storm"). * @param {number|null} [settings.duration=null] - Duration in minutes. If null, a random duration is used. */ forceWeather({ where, type, duration }: { where?: string | undefined; type: string | null; duration?: number | null | undefined; }): void; /** * Chooses a new weather type based on configured probabilities. * Probabilities can come from: * - Default settings * - Hour-based ranges * - Day/night differences * - Seasonal settings * - Custom overrides passed as parameter * If a value is a function, it will be executed with contextual data and must return a number. * @param {Object} [settings={}] - Configuration object. * @param {string} [settings.where='main'] - The target weather zone or location key. * @param {WeatherCfg} [settings.customWeather] - Optional weather probability overrides. * @returns {string|null} - The selected weather type, or null if none selected. */ chooseNewWeather({ customWeather, where }?: { where?: string | undefined; customWeather?: WeatherCfg | undefined; }): string | null; /** * Returns a random integer between min and max, inclusive. * @param {number} min - Minimum value. * @param {number} max - Maximum value. * @returns {number} - A random integer between min and max. */ _randomInRange(min: number, max: number): number; /** --------------------- MOON SYSTEM --------------------- */ /** * Add a new moon to the system. * @param {string} name - Name of the moon. * @param {number} cycleLength - Number of days in cycle. * @param {string[]} phaseNames - Optional list of phase names. * @param {number} [startingPhase=0] - Initial phase. * @returns {number} - The moon index. */ addMoon(name: string, cycleLength: number, phaseNames: string[], startingPhase?: number): number; /** * Remove a moon by name. * @param {string} name */ removeMoon(name: string): void; /** * Advance all moons in a number of days. * @param {number} days */ advanceMoons(days?: number): void; /** * Retrocede all moons in a number of days. * @param {number} days */ rewindMoons(days?: number): void; /** * Advances the phase of a single moon by a number of days. * @param {number} moonIndex - The index of the moon to advance. * @param {number} days - Number of days to advance. Defaults to 1. * @throws {RangeError} If the moonIndex is invalid. */ advanceMoon(moonIndex: number, days?: number): void; /** * Rewinds the phase of a single moon by a number of days. * @param {number} moonIndex - The index of the moon to rewind. * @param {number} days - Number of days to rewind. Defaults to 1. * @throws {RangeError} If the moonIndex is invalid. */ rewindMoon(moonIndex: number, days?: number): void; /** * Checks if a moon exists at the specified index. * * @param {number} index - The index of the moon to check. * @returns {boolean} `true` if a moon exists at the given index, otherwise `false`. */ moonExists(index: number): boolean; /** * Retrieves the moon with its current phase details. * * @param {number|MoonRaw} index - The moon index in the internal collection or a `MoonRaw` object. * @returns {MoonData} The moon including its name, current phase index, phase name, and cycle length. * @throws {TypeError} If `index` is neither a number nor a valid `MoonRaw` object. * @throws {RangeError} If `index` is a number but no moon exists at that position. * @throws {Error} If `index` is a `MoonRaw` object but required properties are missing or invalid. */ getMoon(index: number | MoonRaw): MoonData; /** * Checks if the instance has been destroyed and throws an error if so. * @private * @throws {Error} If the instance has already been destroyed. */ private _checkDestroyed; /** * Destroys all stored data and marks the instance as unusable. * Clears all internal maps, arrays, and resets primitive values to defaults. * Once destroyed, any further method calls should throw an error or be ignored. */ destroy(): void; #private; } //# sourceMappingURL=TinyDayNightCycle.d.mts.map