I’m making a snake game in React and it works fine but I have defined a switch case, where you can control the snake with the arrow keys. But there’s a problem, when the snake is going to one direction I don’t want it to be able to go to the opposite direction. For example if it is moving to the left, it should’t be able to move to the right when the arrow key is pressed. Now I’m wondering how can I define an If statement in my switch case for it? My code so far looks like this :
//handle user input
const handleKeyPress = (e) => {
e = e || window.event;
setStarted(true);
switch (e.keyCode) {
case 38:
setDirection('UP');
break;
case 40:
setDirection('DOWN');
break;
case 37:
setDirection('LEFT');
break;
case 39:
setDirection('RIGHT');
break;
default:
break;
}
};
//moving the snake
const moveSnake = () => {
//take temporary positions
let tempSnakePosition;
let dir;
//get fresh cordinates
setSnakeCordinates((prev) => {
tempSnakePosition = [...prev];
return prev;
});
setDirection((prev) => {
dir = prev;
return prev;
});
//find head
let tempHead = tempSnakePosition[tempSnakePosition.length - 1];
//change head
let l = tempHead.left;
let t = tempHead.top;
switch (dir) {
case 'RIGHT':
if ('LEFT' && 'UP')
l = tempHead.left + size
break;
case 'LEFT':
if ('RIGHT')
l = tempHead.left - size;
break;
case 'DOWN':
t = tempHead.top + size;
break;
case 'UP':
t = tempHead.top - size;
break;
default:
break;
}