Commit e538c88a authored by Master Q's avatar Master Q

游戏优化

parent 1fddbb17
...@@ -114,15 +114,15 @@ class Layers extends FYGE.Container { ...@@ -114,15 +114,15 @@ class Layers extends FYGE.Container {
/** /**
* 舞台中心点位置x * 舞台中心点位置x
*/ */
// get stageCenterX(): number { get stageCenterX(): number {
// return this.stage.viewRect.x + this.stage.viewRect.width >> 1; return this.stage.viewRect.x + this.stage.viewRect.width >> 1;
// } }
/** /**
* 舞台中心点位置y,layer位置做过偏移的就不对了,所以还是自行算吧 * 舞台中心点位置y,layer位置做过偏移的就不对了,所以还是自行算吧
*/ */
// get stageCenterY(): number { get stageCenterY(): number {
// return this.stage.viewRect.y + this.stage.viewRect.height >> 1; return this.stage.viewRect.y + this.stage.viewRect.height >> 1;
// } }
} }
export const layers = new Layers(); export const layers = new Layers();
......
{ {
"groups": [ "groups": [
{
"keys": "countdown-back.png",
"name": "CountDownComp"
},
{ {
"keys": "back_index.png,gg_back.png,one_more-btn.png", "keys": "back_index.png,gg_back.png,one_more-btn.png",
"name": "GameOverPanel" "name": "GameOverPanel"
}, },
{ {
"keys": "p1-b.png,p1.png", "keys": "balance_guidance.png,guidance-t1.png,p1-b.png,p1.png",
"name": "GameScene" "name": "GameScene"
}, },
{ {
......
...@@ -178,7 +178,7 @@ export class Main { ...@@ -178,7 +178,7 @@ export class Main {
// const scene = Tools.globalData.newUser ? StoryScene : IndexScene; // const scene = Tools.globalData.newUser ? StoryScene : IndexScene;
// vtodo 是否是新手 // vtodo 是否是新手
changeScene(NewGuyScene); changeScene(GameScene);
// MusicBtn.changeMusicStatus(true); // TODO 进游戏打开音乐先 // MusicBtn.changeMusicStatus(true); // TODO 进游戏打开音乐先
......
export const ResJson = { export const ResJson = {
"groups": [ "groups": [
{
"keys": "countdown-back.png",
"name": "CountDownComp"
},
{ {
"keys": "back_index.png,gg_back.png,one_more-btn.png", "keys": "back_index.png,gg_back.png,one_more-btn.png",
"name": "GameOverPanel" "name": "GameOverPanel"
}, },
{ {
"keys": "p1-b.png,p1.png", "keys": "balance_guidance.png,guidance-t1.png,p1-b.png,p1.png",
"name": "GameScene" "name": "GameScene"
}, },
{ {
......
...@@ -3,6 +3,17 @@ import { RES } from "../../module/RES"; ...@@ -3,6 +3,17 @@ import { RES } from "../../module/RES";
import UI from "../UI"; import UI from "../UI";
type ProgressType = {
width?: number,
height?: number,
showProgressText?: boolean,
valueDesc?: string,
valueColor?: string,
type?: string,
typeColor?: number,
[x: string]: any
}
/** /**
* 纯色进度条 * 纯色进度条
*/ */
...@@ -10,29 +21,50 @@ export class ProgressBar extends FYGE.Container { ...@@ -10,29 +21,50 @@ export class ProgressBar extends FYGE.Container {
private upImage: FYGE.Graphics; private upImage: FYGE.Graphics;
private progressTxt: FYGE.TextField; private progressTxt: FYGE.TextField;
private maxLength: number; private maxLength: number;
private pHeight: number
private barColor: number private barColor: number
private progressCfg: ProgressType
constructor(barColor?: number) { constructor(barColor?: number, opt?:ProgressType) {
super() super()
this.maxLength = 377//最大长度
opt = this.progressCfg = Object.assign({}, {
width: 377,
height: 19,
showProgressText: true,
valueDesc: '',
valueColor: '#f8c862',
type: 'stroke',
typeColor: 0xffffff
}, opt)
this.maxLength = opt.width//最大长度
this.pHeight = opt.height
this._value = 0; this._value = 0;
this.addChild(new FYGE.Shape()) if (this.progressCfg.type == 'stroke') {
.beginStroke( 0xffffff,2) this.addChild(new FYGE.Shape())
.drawRoundedRect(0, 0, this.maxLength, 19, 10) .beginStroke(opt.typeColor, 2)
.endStroke(); .drawRoundedRect(0, 0, this.maxLength, this.pHeight, this.pHeight / 2)
.endStroke();
} else {
this.addChild(new FYGE.Shape())
.beginFill(opt.typeColor)
.drawRoundedRect(-1, -1, this.maxLength + 2, this.pHeight + 2, this.pHeight / 2 + 1)
.endFill();
}
this.barColor = barColor || 0xf8c862 this.barColor = barColor || 0xf8c862
this.upImage = this.addChild(new FYGE.Graphics()) this.upImage = this.addChild(new FYGE.Graphics())
.beginFill(barColor) .beginFill(barColor)
.drawRoundedRect(0, 0, this.value * this.maxLength, 19, 10) .drawRoundedRect(0, 0, this.value * this.maxLength, this.pHeight, 10)
.endFill(); .endFill();
this.progressTxt = UI.Txt( opt.showProgressText && (this.progressTxt = UI.Txt(
this, "0%", 22, "#f8c862", FYGE.TEXT_ALIGN.CENTER, this, `${this.progressCfg.valueDesc} 0%`, 22, this.progressCfg.valueColor, FYGE.TEXT_ALIGN.CENTER,
80, (this.maxLength - 80) / 2, 36 this.maxLength, 0, 36
); ));
} }
/** /**
...@@ -48,11 +80,11 @@ export class ProgressBar extends FYGE.Container { ...@@ -48,11 +80,11 @@ export class ProgressBar extends FYGE.Container {
if (v < 0) v = 0; if (v < 0) v = 0;
if (v > 1) v = 1; if (v > 1) v = 1;
this._value = v; this._value = v;
this.progressTxt.text = ((v * 100) >> 0) + "%"; this.progressTxt && (this.progressTxt.text = this.progressCfg.valueDesc + ((v * 100) >> 0) + "%");
var length = this._value * this.maxLength var length = this._value * this.maxLength
this.upImage.clear() this.upImage.clear()
.beginFill(this.barColor) .beginFill(this.barColor)
.drawRoundedRect(0, 0, length, 19, 10) .drawRoundedRect(0, 0, length, this.pHeight, 10)
.endFill(); .endFill();
} }
} }
import { layers } from "../../module/views/layers"
import { Module } from "../../module/views/Module"
import { countDown } from "../common/countDown"
import UI from "../UI"
import { dateLeftFormat, padStart } from "../utils/utils"
type TimeObj = {
t: number
}
export default class CountDownComp extends Module {
timeoutFn: Array<Function>
tobj: TimeObj // 倒计时
constructor(t: number) {
super(t)
}
get groupNames(): string[] {
return ['CountDownComp']
}
cdt: FYGE.TextField
initUi() {
UI.Sp(this, 'countdown-back.png')
this.cdt = UI.Txt(this, '00:00:00', 30, '#ffffff', FYGE.TEXT_ALIGN.LEFT, 200, 63, 17)
this.initTime(this.data)
}
/**
* 添加 Timeout function
* @param fnc
*/
addTimeoutFunc(fnc: Function) {
(this.timeoutFn || (this.timeoutFn = [])).push(fnc)
}
removeTimeoutFunc(fnc: Function) {
var i = this.timeoutFn.indexOf(fnc)
if (i == -1) return null;
this.timeoutFn.splice(i, 1)
}
/**
* 初始化时间
* @param t
*/
initTime(t:number) {
this.tobj = {t}
this.formatTime(t)
}
formatTime(n:number) {
var _t = dateLeftFormat('mm:ss', (n / 1000) >> 0)
_t += `:${padStart((n%1000/10 >> 0), 2, '0')}`;
this.cdt.text = _t
return _t
}
countDown(time: TimeObj, onChange: Function) {
var tobj = this.tobj = time
FYGE.Tween.get(this.tobj, {
onChange: () => {
onChange(tobj.t)
}
})
.to({t: 0}, time.t)
.call(() => {
this.timeoutFn && this.timeoutFn.forEach(f => f())
})
return tobj
}
stop() {
FYGE.Tween.removeTweens(this.tobj)
}
restart(t?:number) {
t && this.initTime(t)
this.start()
}
start() {
this.countDown(this.tobj, (n:number) => {
this.formatTime(n)
})
}
}
\ No newline at end of file
...@@ -3,6 +3,22 @@ type SubType = { ...@@ -3,6 +3,22 @@ type SubType = {
that?: any that?: any
} }
type SystemInfo = {
platform: string,
[x: string]: any
}
function getSystemInfo():Promise<SystemInfo> {
return new Promise((resolve, reject) => {
// @ts-ignore
my.getSystemInfo({
success: function(res) {
resolve(res)
}
})
})
}
class DeviceMotion { class DeviceMotion {
subs: Array<SubType> = [] // 订阅 方法 subs: Array<SubType> = [] // 订阅 方法
...@@ -10,12 +26,21 @@ class DeviceMotion { ...@@ -10,12 +26,21 @@ class DeviceMotion {
this.initEvents() this.initEvents()
} }
initEvents() { platform: string
async initEvents() {
if (my) { if (my) {
// @ts-ignore const { platform } = await getSystemInfo()
this.platform = platform.toLowerCase()
//@ts-ignore
my.onDeviceMotionChange((res) => { my.onDeviceMotionChange((res) => {
res.beta = -res.beta // 通过 platform 进行判断当前是 弧度制还是 角度值
if (this.platform != 'android') {
res.alpha = res.alpha / 180 * Math.PI
res.beta = res.beta / 180 * Math.PI
res.gamma = res.gamma / 180 * Math.PI
} else {
res.beta = -res.beta
}
this.orientationHandler(res) this.orientationHandler(res)
}) })
} else { } else {
...@@ -33,6 +58,15 @@ class DeviceMotion { ...@@ -33,6 +58,15 @@ class DeviceMotion {
} }
removeEvents() {
if (my) {
//@ts-ignore
my.offDeviceMotionChange();
} else {
// window.removeEventListener('deviceorientation')
}
}
orientationHandler = (event) => { orientationHandler = (event) => {
const res = event const res = event
......
...@@ -7,6 +7,7 @@ import deviceMotionSubs from './DeviceMotion'; ...@@ -7,6 +7,7 @@ import deviceMotionSubs from './DeviceMotion';
import { GDispatcher } from '../../Main'; import { GDispatcher } from '../../Main';
import { MotionInitFunc, MotionInitScene } from './MotionInit'; import { MotionInitFunc, MotionInitScene } from './MotionInit';
import { setCenterPos } from '../NewGuyScene/NewGuyScene'; import { setCenterPos } from '../NewGuyScene/NewGuyScene';
import CountDownComp from '../../components/CountDownComp';
const Container = FYGE.Container const Container = FYGE.Container
const TEXT_ALIGN = FYGE.TEXT_ALIGN const TEXT_ALIGN = FYGE.TEXT_ALIGN
...@@ -54,9 +55,9 @@ function pos2Len(p1: pos, p2:pos):number { ...@@ -54,9 +55,9 @@ function pos2Len(p1: pos, p2:pos):number {
export class GameScene extends MotionInitScene { export class GameScene extends MotionInitScene {
ralpha: number ralpha: number = 0
rbeta: number rbeta: number = 0
rgamma: number rgamma: number = 0
constructor(...args){ constructor(...args){
super(...args) super(...args)
...@@ -70,36 +71,60 @@ export class GameScene extends MotionInitScene { ...@@ -70,36 +71,60 @@ export class GameScene extends MotionInitScene {
betaText: FYGE.TextField betaText: FYGE.TextField
gammaText: FYGE.TextField gammaText: FYGE.TextField
centerp: FYGE.Sprite centerp: FYGE.Sprite
gyroscope: FYGE.TextField
cdp: CountDownComp
async initUi() { async initUi() {
UI.Txt(this, '陀螺仪游戏调试', 50, '#000000', TEXT_ALIGN.CENTER, layers.stageWidth, layers.stageOffsetX, layers.stageOffsetY + 10, true) UI.Txt(this, '陀螺仪游戏调试', 50, '#000000', TEXT_ALIGN.CENTER, layers.stageWidth, layers.stageOffsetX, layers.stageOffsetY + 10, true)
this.alphaText = UI.Txt(this, 'alpha: 0', 40, '#000000', TEXT_ALIGN.CENTER, layers.stageWidth, layers.stageOffsetX, layers.stageOffsetY + 100) this.alphaText = UI.Txt(this, 'alpha: 0', 40, '#000000', TEXT_ALIGN.CENTER, layers.stageWidth, layers.stageOffsetX, layers.stageOffsetY + 100)
this.betaText = UI.Txt(this, 'beta: 0', 40, '#000000', TEXT_ALIGN.CENTER, layers.stageWidth, layers.stageOffsetX, layers.stageOffsetY + 150) this.betaText = UI.Txt(this, 'beta: 0', 40, '#000000', TEXT_ALIGN.CENTER, layers.stageWidth, layers.stageOffsetX, layers.stageOffsetY + 150)
this.gammaText = UI.Txt(this, 'gamma: 0', 40, '#000000', TEXT_ALIGN.CENTER, layers.stageWidth, layers.stageOffsetX, layers.stageOffsetY + 200) this.gammaText = UI.Txt(this, 'gamma: 0', 40, '#000000', TEXT_ALIGN.CENTER, layers.stageWidth, layers.stageOffsetX, layers.stageOffsetY + 200)
// var curr = this.addChild(new FYGE.Graphics()) this.gyroscope = UI.Txt(this, '', 40, '#000000', TEXT_ALIGN.CENTER, layers.stageWidth, 0, layers.stageOffsetY + 300)
// curr.lineStyle(5,0x00ff00,1);
// curr.drawRoundedRect(100, 100, 200, 100, 50)
// vtodo 模拟中心点 // vtodo 模拟中心点
var centerp = this.centerp = setCenterPos(UI.Sp(this, 'p1-b.png')) var centerp = this.centerp = setCenterPos(UI.Sp(this, 'p1-b.png'))
this.setChildIndex(centerp, -1) var cdp = this.cdp = this.addChild(new CountDownComp(12000))
this.cdp.addTimeoutFunc(() => {
console.log('时间结束')
})
cdp.position.set(layers.stageOffsetX + layers.stageWidth - 230, layers.stageOffsetY + 40)
super.initUi()
} }
initGame() { initGame() {
this.addChild(new GameEle('p1-b.png', this.centerp, () => { this.cdp.start()
console.log(233)
this.addChild(new GameEle('p1.png', this.centerp, () => {
this.cdp.initTime(15000)
this.motionInitFunc.showGuidance()
})) }))
} }
shoot() {
this.cdp.stop()
}
unshoot() {
this.cdp.start()
}
initEvents() { initEvents() {
console.log('%c 初始化事件 ========', 'color: green') console.log('%c 初始化事件 ========', 'color: green')
// vtodo 先用window 陀螺仪进行处理 // vtodo 先用window 陀螺仪进行处理
deviceMotionSubs.notify(this.orientationHandler, this) deviceMotionSubs.notify(this.orientationHandler, this)
//@ts-ignore
// my && my.onGyroscopeChange((res) => {
// this.gyroscope.text = `x:${res.x.toFixed(2)}, y: ${res.y.toFixed(2)}, z: ${res.z.toFixed(2)}`
// this.alphaText.text = `alpha: ${(this.ralpha += res.z).toFixed(2)}`
// this.betaText.text = `beta: ${(this.rbeta += res.x).toFixed(2)}`
// this.gammaText.text = `gamma: ${(this.rgamma += res.y).toFixed(2)}`
// })
} }
removeEvents() { removeEvents() {
...@@ -107,9 +132,9 @@ export class GameScene extends MotionInitScene { ...@@ -107,9 +132,9 @@ export class GameScene extends MotionInitScene {
} }
orientationHandler(event) { orientationHandler(event) {
var alpha = this.ralpha = event.alpha var alpha = event.alpha
var beta = this.rbeta = event.beta var beta = event.beta
var gamma = this.rgamma = event.gamma var gamma = event.gamma
this.alphaText.text = `alpha: ${event.alpha.toFixed(2)}` this.alphaText.text = `alpha: ${event.alpha.toFixed(2)}`
this.betaText.text = `beta: ${event.beta.toFixed(2)}` this.betaText.text = `beta: ${event.beta.toFixed(2)}`
...@@ -172,6 +197,7 @@ export class GameEle extends Container { ...@@ -172,6 +197,7 @@ export class GameEle extends Container {
} }
destroy() { destroy() {
deviceMotionSubs.removeEvents()
this.removeEvents() this.removeEvents()
super.destroy() super.destroy()
} }
...@@ -214,6 +240,7 @@ export class GameEle extends Container { ...@@ -214,6 +240,7 @@ export class GameEle extends Container {
ay = this.accy + (this.vy >=0 ? -1 : 1) * this.resisteAcc ay = this.accy + (this.vy >=0 ? -1 : 1) * this.resisteAcc
} }
this.vx += ax this.vx += ax
this.vy += ay this.vy += ay
...@@ -229,19 +256,21 @@ export class GameEle extends Container { ...@@ -229,19 +256,21 @@ export class GameEle extends Container {
// } // }
// vtodo 游戏大小 先设置100 // vtodo 游戏大小 先设置100
if (this.x > layers.stageWidth + layers.stageOffsetX - 100) { var sw = this.sprite.width / 2
this.x = layers.stageWidth + layers.stageOffsetX - 100 if (this.x > layers.stageWidth + layers.stageOffsetX - sw) {
this.x = layers.stageWidth + layers.stageOffsetX - sw
this.vx = 0 this.vx = 0
} else if (this.x < layers.stageOffsetX) { } else if (this.x < layers.stageOffsetX + sw) {
this.x = layers.stageOffsetX this.x = layers.stageOffsetX + sw
this.vx = 0 this.vx = 0
} }
if (this.y > layers.stageHeight + layers.stageOffsetY - 100) { var sh = this.sprite.height / 2
this.y = layers.stageHeight + layers.stageOffsetY - 100 if (this.y > layers.stageHeight + layers.stageOffsetY - sh) {
this.y = layers.stageHeight + layers.stageOffsetY - sh
this.vy = 0 this.vy = 0
} else if (this.y < layers.stageOffsetY) { } else if (this.y < layers.stageOffsetY + sh) {
this.y = layers.stageOffsetY this.y = layers.stageOffsetY + sh
this.vy = 0 this.vy = 0
} }
......
...@@ -51,12 +51,18 @@ export class MotionInitFunc extends Container { ...@@ -51,12 +51,18 @@ export class MotionInitFunc extends Container {
init() { init() {
this.maskCont = UI.Ctn(this, layers.stageOffsetX, layers.stageOffsetY) this.maskCont = UI.Ctn(this, layers.stageOffsetX, layers.stageOffsetY)
UI.Rect(this.maskCont , layers.stageWidth, layers.stageHeight, 0x1b1a1a, 0).alpha=0.8 UI.Rect(this.maskCont , layers.stageWidth, layers.stageHeight, 0x1b1a1a, 0).alpha=0.8
// console.log(this.mask)
UI.Txt(this.maskCont, '端平手机', 30, '#ffffff', TEXT_ALIGN.CENTER, layers.stageWidth, 0, 1000, true)
var p = this.progress = this.maskCont.addChild(new ProgressBar(0xcccccc)) UI.Sp(this.maskCont, 'balance_guidance.png', 310, layers.stageHeight / 2 - 266)
p.y = 920
p.x = 177 UI.Txt(this.maskCont, '端平手机开始游戏', 36, '#ffffff', TEXT_ALIGN.CENTER, layers.stageWidth, 0, layers.stageHeight / 2 + 326, true)
var p = this.progress = this.maskCont.addChild(new ProgressBar(0xcccccc, {
width: 150,
height: 10,
showProgressText: false
}))
p.y = layers.stageHeight / 2 - 316
p.x = 297
this.showGuidance() this.showGuidance()
} }
...@@ -99,13 +105,13 @@ export class MotionInitScene extends Scene { ...@@ -99,13 +105,13 @@ export class MotionInitScene extends Scene {
constructor(...args) { constructor(...args) {
super(...args) super(...args)
this.initMotion()
this._initEvents() this._initEvents()
} }
initMotion() { initUi() {
var cb = this.initGame.bind(this) var cb = this.initGame.bind(this)
this.motionInitFunc = this.addChild(new MotionInitFunc(cb)) this.motionInitFunc = this.addChild(new MotionInitFunc(cb))
super.initUi()
} }
_initEvents() { _initEvents() {
...@@ -120,14 +126,28 @@ export class MotionInitScene extends Scene { ...@@ -120,14 +126,28 @@ export class MotionInitScene extends Scene {
destroy() { destroy() {
this._removeEvents() this._removeEvents()
// this.motionInitFunc.hideGuidance()
super.destroy() super.destroy()
} }
protected shoot() {
}
protected unshoot() {
}
focusProgress: ProgressBar focusProgress: ProgressBar
addTimeCountDown = debounce((e) => { addTimeCountDown = debounce((e) => {
console.log('addTimeCountDown') this.shoot()
this.focusProgress = this.addChild(new ProgressBar(0xcccccc)) this.focusProgress = this.addChild(new ProgressBar(0xff200d, {
this.focusProgress.position.set(177, 900) valueDesc: '保存进度',
valueColor: '#000000',
type: 'fill',
typeColor: 0x111111
}))
this.focusProgress.position.set(177, layers.stageCenterY + 400)
FYGE.Tween.get(this.focusProgress) FYGE.Tween.get(this.focusProgress)
.to({value: 1}, 3000) .to({value: 1}, 3000)
.call(() => { .call(() => {
...@@ -135,19 +155,21 @@ export class MotionInitScene extends Scene { ...@@ -135,19 +155,21 @@ export class MotionInitScene extends Scene {
typeof e.data == 'function' && e.data() typeof e.data == 'function' && e.data()
this.removeTimeCountDown() this.removeTimeCountDown()
}) })
}, 600) }, 400)
removeTimeCountDown() { removeTimeCountDown() {
this.focusProgress && FYGE.Tween.removeTweens(this.focusProgress) if (this.focusProgress) {
this.unshoot()
FYGE.Tween.removeTweens(this.focusProgress)
this.removeChild(this.focusProgress)
}
// @ts-ignore // @ts-ignore
clearTimeout(this.addTimeCountDown.timer.curr) clearTimeout(this.addTimeCountDown.timer.curr)
this.removeChild(this.focusProgress)
} }
/** /**
* 完成端平操作后 function * 完成端平操作后 function
*/ */
protected initGame() { protected initGame() {
console.log(123123)
} }
} }
...@@ -26,17 +26,33 @@ export class NewGuyScene extends MotionInitScene { ...@@ -26,17 +26,33 @@ export class NewGuyScene extends MotionInitScene {
centerp: FYGE.Sprite centerp: FYGE.Sprite
initUi() { initUi() {
var centerp = this.centerp = setCenterPos(UI.Sp(this, 'p1-b.png')) var centerp = this.centerp = setCenterPos(UI.Sp(this, 'p1-b.png'))
this.setChildIndex(centerp, -1) this.setChildIndex(centerp, -1)
super.initUi()
} }
g1: FYGE.Sprite
initGame() { initGame() {
console.log('initGame') this.g1 = UI.Sp(this, 'guidance-t1.png', layers.stageCenterX, layers.stageCenterY + 400)
this.g1.anchorTexture.set(0.5, 0.5)
var e = this.addChild(new GameEle('p1-b.png', this.centerp, () => { var e = this.addChild(new GameEle('p1-b.png', this.centerp, () => {
changeScene(GameScene) changeScene(GameScene)
})) }))
} }
shoot() {
this.g1.visible = false
this.desc && (this.desc.visible = false)
}
desc: FYGE.TextField
unshoot() {
this.g1 && (this.g1.visible = false)
this.desc || (this.desc = UI.Txt(this, '啊哦,没有保持住,再试一次吧', 30, '#111111', FYGE.TEXT_ALIGN.CENTER, layers.stageWidth, 0, layers.stageCenterY + 400))
}
} }
\ No newline at end of file
/**
* 函数防抖,如下拉菜单
* @param {Function} fn
* @param {Number} delay
* @returns
*/
export function debounce(fn: Function, delay:number=2000) {
let timer = null;
return function(...args) {
let context = this;
if(timer) clearTimeout(timer)
timer = setTimeout(()=>{
fn.apply(context, args)
}, delay)
}
}
/**
* 函数节流, 用作防连点
* @param {Function} fn
* @param {Number} delay
* @returns
*/
export function throttle(fn:Function, delay: number=2000) {
let flag = true,
timer = null;
return function (...args) {
let context = this;
if(!flag) return;
flag = false;
clearTimeout(timer);
fn.apply(context, args);
timer = setTimeout(() => {
flag = true
}, delay)
}
}
/**
* 时间格式化
* @param {*} fmt
* @param {*} date
* @returns
*/
export function dateFormat(fmt, date) {
let ret;
date = new Date(date)
const opt = {
"Y+": date.getFullYear().toString(), // 年
"M+": (date.getMonth() + 1).toString(), // 月
"d+": date.getDate().toString(), // 日
"h+": date.getHours().toString(), // 时
"m+": date.getMinutes().toString(), // 分
"s+": date.getSeconds().toString() // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
};
for (let k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
};
};
return fmt;
}
/**
* 返回时间格式 r 秒单位
* @param {*} fmt
* @param {*} r
* @returns
*/
export function dateLeftFormat(fmt: string, r:number):string {
if (r < 0) return '-1'
let ret
let opt = {
"h+": Math.floor(r / 3600).toString(), //小时
"m+": Math.floor(r % 3600 / 60).toString(), //分
"s+": Math.floor(r % 60).toString(), //秒
}
for (let k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
};
};
return fmt;
}
/**
* 字符串填充 向前
* @param ns 当前需要被填充的数据
* @param len 被填充至len
* @param s 填充的数据
*/
export function padStart(ns: number | string, len: number, s: string | number) {
var _ns = typeof ns == 'number' ? ns + '' : ns
var _s = typeof s == 'number' ? s + '' : s
var _len = _ns.length
return _len >= len ? _ns : (_s.repeat(len) + ns).slice(-len)
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment