input Direction confusion in snake game javascript

Here’s the full code:

This is the code that I’m interested in:

window.addEventListener("keydown", e => {
  inputDir = { x: 0, y: 1 };;
  switch (e.key) {
    case "ArrowUp":
      inputDir.x = 0;
      inputDir.y = -1;
    case "ArrowDown":
      inputDir.x = 0;
      inputDir.y = 1;
    case "ArrowLeft":
      inputDir.x = -1;
      inputDir.y = 0;
    case "ArrowRight":
      inputDir.x = 1;
      inputDir.y = 0;


What is inputDir variable? (I didn’t write this code, I’m learning it from a tutorial, you know tutorials don’t cover stuffs well).
What I’m not understanding is why are we setting inputDir at 0th row, 1st column? What does that mean? Can you provide some explanations with figures(if possible) about this issue?

I must tell why my confusion came here:
Earlier in the code, we’ve done this:

//head of snake
let snakeArr = [
    x: 13,
    y: 15

Here x,y means the grid row 13, grid column 15. That is why I’m confused. We’re using same variable names in 2 places with different meanings. In this question, we’re using x,y for direction(up,down etc).
How are we able to do this?

inputDir and snakeArr are two different things. The snakeArr stores the current position of our snake (and all of its segments). The inputDir variable seems to be an object that specifies what direction the snake is always moving in. They look similar but are unrelated.

Were you able to get the game to work? It didn’t actually work when I tried to run it. My hunch is that the main function has the requestAnimationFrame call at the front as opposed to towards the end.

I haven’t watched this video, but I have heard others say it was a good one as they tried to learn how to code the snake game :slight_smile:

moving the snake part isn’t done yet,that’s why it doesn’t work atm.

My confusion is cleared.



are 2 different object names. It doesn’t matter if we use same key name for both of them.

1 Like

Correct! :slight_smile: