Input Direction confusion in snake game javascript

Joined
Dec 11, 2022
Messages
11
Reaction score
1
Here's the full code:


This is the code that I'm interested in:


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


  }
})
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?
 
Joined
Dec 11, 2022
Messages
11
Reaction score
1
I must tell why my confusion came here:
Earlier in the code, we’ve done this:
Code:
//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?
 

Attachments

  • 1673353499744.gif
    1673353499744.gif
    43 bytes · Views: 4
Joined
Dec 11, 2022
Messages
11
Reaction score
1
My confusion is cleared.

arrSnake=[{x:0,y:1}]

inputDir={x:0,y:1}

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top