Am trying to convert game controls from keyboard keys to buttons on the page

Viewed 34

i have a tetris game that is controlled when arrow key on the keyboard is pressed, but i want to actually place these responsibility on 4 HTML buttons instead. here is the code working so far:

```document.body.onkeydown = function( e ) {
    var keys = {
        37: 'left',
        39: 'right',
        40: 'down',
        38: 'rotate',
        32: 'drop'
    };
    if ( typeof keys[ e.keyCode ] != 'undefined' ) {
        keyPress( keys[ e.keyCode ] );
        render();
    }
};```

**And here is the the keyPress function that handles the movement and direction of the object based on which key code is pressed. the render() function is the function that draws the game objects: **

     switch ( key ) {
         case "left":
             if ( valid( -1 ) ) {
                 --currentX;
                 xPush.play();
             }
             break;
         case 'right':
             if ( valid( 1 ) ) {
                 ++currentX;
                 xPush.play();
             }
             break;
         case 'down':
             if ( valid( 0, 1 ) ) {
                 ++currentY;
                 xPush.play();
             }
             break;
         case 'rotate':
             var rotated = rotate( current );
             if ( valid( 0, 0, rotated ) ) {
                 current = rotated;
             }
             break;
         case 'drop':
             while( valid(0, 1) ) {
                 ++currentY;
             }
             tick();
             break;
     }
 }

please i want to add 4 HTML buttons to do the control instead of keyboard keys/ keys code. Thank you all

2 Answers

Basically you need just to replace the onkeydown function of yours.

var buttons = document.querySelectorAll(".action");
buttons.forEach(function(button) {
  button.addEventListener('mousedown', function(e) {
    keypress(button.getAttribute("data-action"));
    // render();
  })
})

function keypress(key) {
  console.log ("key " + key + " was pressed");
}
<button class="action" data-action="left">left</button>
<button class="action" data-action="right">right</button>
<button class="action" data-action="down">down</button>
<button class="action" data-action="rotate">rotate</button>
<button class="action" data-action="drop">drop</button>

var buttons = document.querySelectorAll(".action");
buttons.forEach(function(button) {
  button.addEventListener('mousedown', function(e) {
    keypress(button.getAttribute("data-action"));
    // render();
  })
})

function keypress(key) {
  console.log ("key " + key + " was pressed");
}
Related