Home > Back-end >  IF statement in Switch React JS
IF statement in Switch React JS

Time:12-15

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. as in prevent changing direction along same axis, ie left if currently moving right, down if currently moving up

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;
}

CodePudding user response:

const [prevDir, setPrevDir] = useState('');  

const handleKeyPress = (e) => {
    switch (e.keyCode) {
        case 38:
            if(prevDir !== 'DOWN') {
                setDirection('UP'); 
            }
            break;
        case 40:
            if(prevDir !== 'UP') {
                setDirection('DOWN');
                break;
            }
        case 37:
            if(prevDir !== 'RIGHT') {
                setDirection('LEFT');
            }
            break;
        case 39:
            if(prevDir !== 'LEFT') {
                setDirection('RIGHT');
                break;
            }
        default:
            break;
      }
}

setDirection((prev) => {
    dir = prev;
    setPrevDir(prev);
    return prev;
 });

CodePudding user response:

Try using you dir variable like this:

//handle user input
const handleKeyPress = (e) => {
e = e || window.event;
setStarted(true);
switch (e.keyCode) {
  case 38:
    if(dir !== 'DOWN')
      setDirection('UP');
    break;
  case 40:
    if(dir !== 'UP')
      setDirection('DOWN');
    break;
  case 37:
    if(dir !== 'RIGHT')
      setDirection('LEFT');
    break;
  case 39:
    if(dir !== 'LEFT')
      setDirection('RIGHT');
    break;
  default:
    break;
  }
};
  • Related