Keyboard.ts
1 export class Keyboard { 2 private readonly keys: { [key: string]: boolean } 3 private readonly lasts: Array<string> 4 5 public constructor() { 6 this.keys = {} 7 this.lasts = [] 8 9 this.listen() 10 } 11 12 public listen(): void { 13 document.addEventListener('keyup', this) 14 document.addEventListener('keydown', this) 15 } 16 17 public unlisten(): void { 18 document.removeEventListener('keyup', this) 19 document.removeEventListener('keydown', this) 20 } 21 22 public handleEvent(e: KeyboardEvent): void { 23 switch (e.type) { 24 case 'keyup': 25 this.onkeyup(e) 26 break 27 case 'keydown': 28 this.onkeydown(e) 29 break 30 } 31 } 32 33 /** 34 * Tant que la touche est levée (non enfoncée) 35 */ 36 public up(k: string): boolean { 37 return !this.keys[k] 38 } 39 40 /** 41 * Tant que la touche est enfoncée 42 */ 43 public down(k: string): boolean { 44 return this.keys[k] 45 } 46 47 /** 48 * Lorsque la touche a été enfoncée 49 */ 50 public press(k: string): boolean { 51 const v = this.keys[k] 52 this.keys[k] = false 53 54 return v 55 } 56 57 /** 58 * Lorsque la touche a été relâchée 59 */ 60 public release(k: string): boolean { 61 const last = this.lasts[this.lasts.indexOf(k)] 62 63 if (typeof last !== 'undefined') { 64 this.lasts.splice(this.lasts.indexOf(k), 1) 65 } 66 67 return last === k 68 } 69 70 private onkeyup(e: KeyboardEvent): void { 71 this.lasts.push(e.code) 72 this.keys[e.code] = false 73 } 74 75 private onkeydown(e: KeyboardEvent): void { 76 this.keys[e.code] = true 77 } 78 }