Search code examples
javascripttetris

Tetris on Java Script key control problem


I am having a problem when I move my key 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

    • Arrow keys moving the browser window is a default browser behavior.
      Use event.preventDefault()
    • To listen only to arrow keys use if (k >= 37 && k <= 40) {, or the opposite: if (k < 37 || k > 40) return;

    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"); },
    };
    
    document.addEventListener("keydown", CONTROL);
    
    function CONTROL(event) {
      const k = event.keyCode;
      
      if (k < 37 || k > 40) return; // Do nothing if was not an arrow key. Else Do:
      
      event.preventDefault();       // Prevent browser scroll on arrows
      if(k == 37 || k == 39) dropStart = Date.now(); // Only for left or right
    
      return {
        37: p.moveLeft,
        38: p.rotate,
        39: p.moveRight,
        40: p.moveDown
      }[k]();
    }
    html, body {min-height: 100%;}