Files
CINC/systems/GameTimeManager.js
T
2026-02-04 18:46:11 +08:00

124 lines
4.1 KiB
JavaScript

/**
* GameTimeManager 游戏时间管理类
*
* 负责管理游戏中的时间系统,包括:
* 1. 游戏时间的更新和计算
* 2. 游戏时间与现实时间的转换
* 3. 游戏日期的获取
* 4. 昼夜状态的管理
*/
export default class GameTimeManager {
/**
* 构造函数
* 初始化时间管理系统
*/
constructor() {
this.gameTime = 0 // 游戏中的时间戳(单位:秒)
// 固定为60秒/分钟,60分钟/小时,24小时/天,30天/月,12月/年
this.minuteSec = 60
this.hourSec = 60 * this.minuteSec
this.daySec = 24 * this.hourSec
this.monthSec = 30 * this.daySec
this.yearSec = 12 * this.monthSec
this.lastRealTime = 0 // 上一次更新的现实时间戳(毫秒)
this.gameTimeUpdateInterval = 1000/60 // 游戏中的每秒时间更新间隔(毫秒)
this.isDay = true // 昼夜状态
}
/**
* 初始化时间系统
* @param {number} initialGameTime - 初始游戏时间戳
*/
init(initialGameTime) {
this.lastRealTime = Date.now() // 初始更新时间戳为当前现实时间
this.isDay = true // 设置初始为白天
this.gameTime = initialGameTime // 设置游戏初始时间
}
/**
* 更新游戏时间
* 每帧调用,刷新游戏时间
*/
updateGameTime() {
// 获取当前现实时间戳
const currentRealTime = Date.now()
// 计算与上次更新的时间差(毫秒)
const deltaRealTime = currentRealTime - this.lastRealTime
if (deltaRealTime <= this.gameTimeUpdateInterval) { // 小于更新间隔,不更新时间
return
} else {
let addSec = deltaRealTime / this.gameTimeUpdateInterval // 计算增加的秒数
this.gameTime += addSec // 更新游戏时间
this.lastRealTime = currentRealTime // 刷新更新时间戳
}
}
/**
* 获取游戏中的日期
* 根据游戏时间戳计算游戏年月日时分秒,格式为YYYY-MM-DD HH:mm:ss
*/
getGameDate() {
// 计算当前时间的年、月、日、时、分、秒
const year = Math.floor(this.gameTime / this.yearSec)
const month = Math.floor((this.gameTime % this.yearSec) / this.monthSec)+1
const day = Math.floor((this.gameTime % this.monthSec) / this.daySec)+1
const hour = Math.floor((this.gameTime % this.daySec) / this.hourSec)
const minute = Math.floor((this.gameTime % this.hourSec) / this.minuteSec)
const second = Math.floor(this.gameTime % this.minuteSec)
// 格式化日期字符串
const dateString = `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day} ${hour < 10 ? '0' : ''}${hour}:${minute < 10 ? '0' : ''}${minute}:${second < 10 ? '0' : ''}${second}`
const formatDate = {
year, month, day, hour, minute, second ,
dateString,
}
return formatDate
}
/**
* 转换游戏时间字符串为游戏时间戳
* 接收时间字符串,格式为YYYY-MM-DD HH:mm:ss,返回游戏时间戳(单位:秒)
*/
toGameTime(gameTimeString) {
// 解析时间字符串为秒数
const [year, month, day, hour, minute, second] = gameTimeString.split(/[- :]/).map(Number)
// 计算游戏时间戳
return year * this.yearSec + (month - 1) * this.monthSec + (day - 1) * this.daySec + hour * this.hourSec + minute * this.minuteSec + second
}
/**
* 更新昼夜状态
* 每帧调用,根据游戏时间切换白天黑夜状态
*/
updateDayNight() {
const hour = this.getGameDate().hour
if (hour >= 6 && hour < 18) {
this.isDay = true
} else {
this.isDay = false
}
return this.isDay
}
/**
* 获取当前昼夜状态
*/
getDayNightState() {
return this.isDay
}
/**
* 获取当前游戏时间
*/
getGameTime() {
return this.gameTime
}
/**
* 设置游戏时间
*/
setGameTime(gameTime) {
this.gameTime = gameTime
}
}