Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript input Direction confusion in snake game javascript?

shivajikobardan

Legendary Coder
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?
 
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?
 
Back
Top Bottom