Currently, I am working on a snake game project as part of my JavaScript course. I have encountered an issue where the game registers a collision when two keys are pressed simultaneously, even though there is no visual collision.
https://i.sstatic.net/j426n.png
This is the code for managing keyboard key inputs:
document.onkeydown = function handleKeyDown(e){
const key = e.keyCode;
let newDirection;
switch(key){
case 37:
newDirection = "left";
break;
case 38:
newDirection = "up";
break;
case 39:
newDirection = "right";
break;
case 40:
newDirection = "down";
break;
case 32:
restart();
return;
default:
return;
}
snakee.setDirection(newDirection);
}
I am looking for ways to avoid this issue. Someone suggested using the preventDefault() event - should I implement it?
EDIT1
Below is the checkCollision method from the constructor function for the snake object:
this.checkCollision = function(){
// Code snippet for collision detection
};
EDIT2:
After considering your feedback, I made some changes to the implementation. Instead of using a switch statement, I switched to an if/else approach.
// Revised keyboard input handling logic
// Code snippet
However, I still face the issue of simultaneous key presses triggering unexpected behavior. When all properties in the map object are false, pressing two keys at once leads to conflicts. I am unsure how to address this problem.