Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
IF statement in Switch React JS

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;
}
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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;
 });
over 4 years ago · Santiago Trujillo Denunciar

0

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;
  }
};
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda