javascripttetris

JavaScript Tetris key controls


I am having a problem when I press my keys controls, mainly the arrows on the keyboard. If the viewpoint is small enough it also moves the screen up and down because of the vertical side bar and the tetris piece at the same time. And I want the pieces to only move when I press the arrows. I am a novice at JS and I am not sure where to start to solve the problem, suggestions to where to start to look at?

Here is my Js script

document.addEventListener("keydown", CONTROL);

function CONTROL(event) {
    if (event.keyCode == 37) {
        p.moveLeft();
        dropStart = Date.now();
    }
    else if (event.keyCode == 38) {
        p.rotate();
    }
    else if (event.keyCode == 39) {
        p.moveRight();
        dropStart = Date.now();
    }
    else if (event.keyCode == 40) {
        p.moveDown(0);
    }
}

Solution

  • const p = { // JUST FOR THIS DEMO. You use Piece.prototype
        moveLeft()  { console.log("LEFT"); },
        rotate()    { console.log("ROTATE"); },
        moveRight() { console.log("RIGHT"); },
        moveDown()  { console.log("DOWN"); },
    };
    
    const keyActions = {
      ArrowLeft: p.moveLeft,
      ArrowRight: p.moveRight,
      ArrowUp: p.rotate,
      ArrowDown: p.moveDown,
    };
    
    const handleArrowKeys = (ev) => {
      const kc = ev.keyCode;
      const notArrowKey = kc < 37 || kc > 40;
      if (ev.repeat || notArrowKey) return; // Do nothing.
      ev.preventDefault(); // Prevent browser scroll on arrows
      return keyActions[ev.key]();
    };
    
    document.addEventListener("keydown", handleArrowKeys);
    Click here to focus and use arrow keys.