top | item 34321897

(no title)

throwaway0asd | 3 years ago

This code sets an event listener on the window object for the keydown event. That means when the window has focus (or any child thereof) and a keyboard key is pressed that handler will intercept the event.

On keyboard events there is a key property which names the keyboard key pressed to result in the event execution. This handler is only looking for the 4 arrow keys and modifying an object assigned to variable inputDir. What’s interesting is that inputDir is reassigned to a baseline on each key press irrespective of the keyboard key.

Objects in JavaScript are what other languages call a hash map, a key/value pair. Key names are always string data types and there is no type or value restriction on object values. This particular object has two keys assigned: x and y. Values are reassigned respectively to an arrow key press.

discuss

order

shivajikobardan|3 years ago

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?

red_Seashell_32|3 years ago

Further on this - inputDir is just vector, which says where to movement is happening.

As initial is x=0, y=1, it means it will increase position Y by 1 - in other words it initially goes downwards.