Advertisement
Czogista

GraczPoruszaSięKlawiaturą

Aug 15th, 2020 (edited)
1,953
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const Keys = new (class {
  2.   constructor() {
  3.     this.pressedKeys = [];
  4.     this.keysToRemove = [];
  5.     this.forbidden = [37, 38, 39, 40, 65, 68, 83, 87];
  6.   }
  7.   add(key) {
  8.     if (!this.pressedKeys.includes(key)) {
  9.       console.log(`Pressed ${String.fromCharCode(key)}`);
  10.       this.pressedKeys.push(key);
  11.     }
  12.   }
  13.   preRemove(key) {
  14.     if (!this.keysToRemove.includes(key)) {
  15.       this.keysToRemove.push(key);
  16.     }
  17.   }
  18.   remove(key) {
  19.     if (this.pressedKeys.includes(key)) {
  20.       console.log(`Released ${String.fromCharCode(key)}`);
  21.       this.pressedKeys.splice(this.pressedKeys.indexOf(key), 1);
  22.     }
  23.   }
  24.   playerMovesUsingKeyboard() {
  25.     for (const key of this.forbidden) {
  26.       if (this.pressedKeys.includes(key)) {
  27.         return true;
  28.       }
  29.     }
  30.     return false;
  31.   }
  32. })();
  33. //Usuwanie w wybranym momencie
  34. while (Keys.keysToRemove.length) {
  35.   Keys.remove(Keys.keysToRemove[0]);
  36.   Keys.keysToRemove.shift();
  37. }
  38. //Listenery
  39. document.addEventListener("keydown", (event) => {
  40.   if (["INPUT", "TEXTAREA"].includes(event.target.tagName)) {
  41.     return;
  42.   }
  43.   Keys.add(event.which);
  44. });
  45.  
  46. document.addEventListener("keyup", (event) => {
  47.   if (["INPUT", "TEXTAREA"].includes(event.target.tagName)) {
  48.     return;
  49.   }
  50.   Keys.preRemove(event.which);
  51. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement