Tạo Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
class Controller { constructor() { } static delayControl(normalControl,delayControl,beforeDelay,timeDelay){ let beforeControl = 0; let timeTouch = 0; let id = null; let loops; let loopTimer = () => { beforeControl = beforeControl + 5; timeTouch = timeTouch + 5; loops = setTimeout(()=>loopTimer(),5); }; loopTimer(); let checkTouchDevice = () => { return 'ontouchstart' in document; }; if(checkTouchDevice()){ document.addEventListener("touchstart", (event) => { id = event.target.id; if(id in normalControl) normalControl[id](); }); document.addEventListener("touchend", () => { id = null; }); } else { document.addEventListener("mousedown", (event) => { id = event.target.id; if(id in normalControl) normalControl[id](); }); document.addEventListener("mouseup", () => { id = null; }); document.addEventListener('keydown',(event)=>{ id = event.code; if(id in normalControl) normalControl[id](); },true); document.addEventListener('keyup',()=>{ id = null; },true); } let listenDelayControl = ()=>{ if(id in delayControl){ if(beforeControl > beforeDelay){ delayControl[id](); timeTouch = 0; } else if(timeTouch > timeDelay){ delayControl[id](); } beforeControl = 0; } setTimeout(()=>listenDelayControl(),5); }; listenDelayControl(); } } |
Sử dụng
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Controller.delayControl( { ArrowDown: () => this.brick.moveDown(), ArrowUp: () => this.brick.rotate(), Space: () => this.pauseGame(), Enter: () => this.nextGame(), "myCanvas": () => this.pauseGame(), "moveDown": ()=> this.brick.moveDown(), "Rotate": ()=> this.brick.rotate() }, { ArrowLeft: () => this.brick.moveLeft(), ArrowRight: () => this.brick.moveRight(), "moveLeft": ()=> this.brick.moveLeft(), "moveRight": ()=> this.brick.moveRight() },40,200); |