Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
Trying to control movement in a game with arrow keys and and buttons with JS

This is a snake game but I'm trying to let users control the snake with arrow keys and clickable buttons. The arrow keys work fine but i can't get all the buttons to work, one button will work and then nothing else 😢

I've tried to put them in all in their own switch statement and then I tried an if-else but still Nada.

Any help or even just some info on what way I should go about it would be much appreciated.

let inputDirection = {
  x: 0,
  y: 0
}
let lastInputDirection = {
  x: 0,
  y: 0
}

let btnUp = document.querySelector(".btn-up")
let btnLeft = document.querySelector(".btn-left")
let btnRight = document.querySelector(".btn-right")
let btnDown = document.querySelector(".btn-down")


window.addEventListener('keydown', e => {

  switch (e.key) {

    case 'ArrowUp':
      // case btnUp:  
      console.log('hi');
      if (lastInputDirection.y !== 0) break
      inputDirection = {
        x: 0,
        y: -1
      }
      break

    case 'ArrowDown':
      if (lastInputDirection.y !== 0) break
      inputDirection = {
        x: 0,
        y: 1
      }
      break

    case 'ArrowLeft':
      if (lastInputDirection.x !== 0) break
      inputDirection = {
        x: -1,
        y: 0
      }
      break

    case 'ArrowRight':
      if (lastInputDirection.x !== 0) break
      inputDirection = {
        x: 1,
        y: 0
      }
      break

  }
})

function getInputDirection() {
  lastInputDirection = inputDirection
  return inputDirection
}
<button type="button" class="btn-up">Up</button><br>
<button type="button" class="btn-left">left</button><button type="button" class="btn-right">Right</button><br>
<button type="button" class="btn-down">Down</button><br>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can reuse the statements in your switch as event listeners for the buttons

let inputDirection = {
  x: 0,
  y: 0
}
let lastInputDirection = {
  x: 0,
  y: 0
}



const ArrowUp = () => {
  console.log('hi');
  if (lastInputDirection.y !== 0) return
  inputDirection = {
    x: 0,
    y: -1
  }
};
const ArrowDown = () => {
  if (lastInputDirection.y !== 0) return
  inputDirection = {
    x: 0,
    y: 1
  }
};

const ArrowLeft = () => {
  if (lastInputDirection.x !== 0) return
  inputDirection = {
    x: -1,
    y: 0
  }
};

const ArrowRight = () => {
  if (lastInputDirection.x !== 0) return
  inputDirection = {
    x: 1,
    y: 0
  }
};

let btnUp = document.querySelector(".btn-up")
let btnLeft = document.querySelector(".btn-left")
let btnRight = document.querySelector(".btn-right")
let btnDown = document.querySelector(".btn-down")
btnUp.addEventListener("click",ArrowUp)
btnLeft.addEventListener("click",ArrowLeft)
btnRight.addEventListener("click",ArrowRight)
btnDown.addEventListener("click",ArrowDown)




window.addEventListener('keydown', e => { console.log(e.key)
  switch (e.key) { 
    case 'ArrowUp':
      ArrowUp();
      break
    case 'ArrowDown':
      ArrowDown();
      break
    case 'ArrowLeft':
      ArrowLeft();
      break
    case 'ArrowRight':
      ArrowRight();
      break
  }
})

function getInputDirection() {
  lastInputDirection = inputDirection
  return inputDirection
}
<button type="button" class="btn-up">Up</button><br>
<button type="button" class="btn-left">left</button><button type="button" class="btn-right">Right</button><br>
<button type="button" class="btn-down">Down</button><br>

about 4 years ago · Juan Pablo Isaza Relatório

0

Set event listeners to your buttons.

function Up() {
  console.log('hi');
  // Do something
}
<button onclick="Up(event)">Up</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

Everything is working now.

Thanks for the help.

const btnUpOne = document.getElementById('btn-up-one')     
const btnLeftOne = document.getElementById('btn-left-one')     
const btnRightOne = document.getElementById('btn-right-one')     
const btnDownOne = document.getElementById('btn-down-one')

btnUpOne.addEventListener('click', goingUp)    
btnRightOne.addEventListener('click', goingRight)    
btnLeftOne.addEventListener('click', goingLeft)    
btnDownOne.addEventListener('click', goingDown)

//BUTTON MOVEMENTS
//UP
function goingUp(e){
    
  if(lastInputDirection.y !== 0)
  return;

  inputDirection = { x: 0, y: -1 }
  console.log('up');
}

//DOWN
function goingDown(e){

  if(lastInputDirection.y !== 0)
  return;

  inputDirection = { x: 0, y: 1 }
  console.log('down');
  
}

//RIGHT
function goingRight(e){

  if(lastInputDirection.x !== 0)
  return;

  inputDirection = { x: 1, y: 0 }
  console.log('right');   
}

//left
function goingLeft(e){

  if(lastInputDirection.x !== 0)
  return;

  inputDirection = { x: -1, y: 0 }
  console.log('left');
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda