/** * 游戏时长 计时 * @param {function} endCallback 倒计时结束的回调函数 * @param {number} duration 游戏时长 * @param {number} count 游戏倒计时时长 * * @property {number} duration 游戏时长 * @property {number} count 游戏倒计时时长 * @property {number} startTime 游戏开始是ms * @property {boolean} started 游戏是否开始 * @property {object} lib 资源库 * @property {object} bg 时间倒计时背景 * @property {object} text 倒计时文本 * @property {number} timerId 定时器id * @property {function} endCallback 结束回调函数 */ function Time(endCallback, duration, count) { this.duration = duration; this.count = count; this.startTime = Date.now(); this.started = false; // 是否开始游戏 this.lib = library; this.bg = null; this.text = null; this.timerId = null; this.endCallback = endCallback; } /** * 静态方法 封装new init 返回实例 * @param {function} endCallback 倒计时结束的回调函数 * @param {number} duration 游戏时长 * @param {number} count 游戏倒计时时长 * @returns */ Time.of = function (endCallback, duration = config.duration || 60, count = config.count || 5) { const instance = new Time(endCallback, duration, count); instance.init(); return instance; }; // 初始化 Time.prototype.init = function () { this.renderBg(); this.renderText(this.duration); }; // 开始游戏 开始倒计时 Time.prototype.start = function (startTime = Date.now()) { this.started = true; state = 1; this.startTime = startTime; this.update(); }; // 开始游戏 开始倒计时 Time.prototype.end = function () { this.started = false; this.timerId && clearTimeout(this.timerId); this.timerId = null; // 执行结束后的回调 this.endCallback(); }; // 渲染背景 Time.prototype.renderBg = function () { const initX = this.lib.properties.width - 100; const initY = 80; const instance = new this.lib.timeBg(); instance.x = initX; instance.y = initY; this.bg = instance; stage.addChild(instance); }; // 渲染文本 Time.prototype.renderText = function (time) { const text = new createjs.Text(time, 'bold 40px Arial', '#823d16'); text.x = this.lib.properties.width - 100; text.y = 100; text.textAlign = 'center'; text.textBaseline = 'alphabetic'; this.text = text; stage.addChild(text); }; // 更新文本 Time.prototype.update = function () { if (this.timerId || !this.started) return; // const endTime = this.startTime + this.count * 1000 + this.duration * 1000; const endTime = this.startTime + this.duration * 1000; // console.log('endTime: ', endTime); this.timerId = setInterval(() => { let leftTime = Math.round((endTime - Date.now()) / 1000); console.log('leftTime: ', leftTime); this.text && stage.removeChild(this.text); if (leftTime <= 0) { leftTime = 0; this.end(); } this.renderText(leftTime); }, 1000); };