Soe Say
Soe Say

Reputation: 27

Screen arrow keys for mobile device do not work well

I am working with the JavaScript game project. It is a snake game. I am facing with a bug. Function for keyboard arrow keys are work well. But screen arrow keys for mobile device are not work well. I made the game to start when user touch any keys from keyboard. There is a problem in mobile devices, I am trying to start a game when user touch screen arrow keys. But I can't do it well. Screen arrow key can direct the snake, but can't start the game.

Here my JavaScript code:

// Handling User Input
const handleInput = () => {
    document.addEventListener('keydown', e => {
        switch(e.keyCode) {
          case key.arrowUp:    movingDirection = movingDirection === 'down' ? 'down' : 'up'; break;
            case key.arrowDown:  movingDirection = movingDirection === 'up' ? 'up' : 'down'; break;
            case key.arrowLeft:  movingDirection = movingDirection === 'right' ? 'right' : 'left'; break;
            case key.arrowRight: movingDirection = movingDirection === 'left' ? 'left' : 'right'; break;
        }
       
        function left(){
           movingDirection = movingDirection === 'right' ? 'right' : 'left';
       };
       function up(){
            movingDirection = movingDirection === 'down' ? 'down' : 'up';
        };
       function down(){
           movingDirection = movingDirection === 'up' ? 'up' : 'down';
        };
        function right(){
            movingDirection = movingDirection === 'left' ? 'left' : 'right';
        };
        
        document.getElementById("left").onclick = function() {left()};
       document.getElementById("up").onclick = function() {up()};
        document.getElementById("down").onclick = function() {down()};
       document.getElementById("right").onclick = function() {right()};

        if (moveInterval === undefined) {
            moveInterval = setInterval(() => {
                move(movingDirection || 'left');
            }, 1000 / speed);
       }
    });
}


// Define key variables.
const speed = 6;
const worldSize = 10;
const startPoint = [5,5];
const snake = [startPoint];
const key = {
   arrowUp: 38,
   arrowDown: 40,
   arrowLeft: 37,
   arrowRight: 39,
};

let movingDirection;
let moveInterval;


// Start Game
const startGame = () => {
   handleInput();
   checkItemAt(...startPoint);
   placeAppleAt(...getRandomPosition());
}


startGame();

This is a Git-hub link(all my code is here): https://github.com/Boixzz/MyCheckSnake

This is preview of my game: https://heroic-donut-2ce9d6.netlify.app

I want to start the game by touching the screen arrow keys. I am not familiar with mobile device. Please help! Thank you.

Upvotes: 0

Views: 209

Answers (0)

Related Questions