-6
class Piece {

    constructor() {
        this.x = 0;
        this.y = 0;
    }

    move(p) {
        this.x = p.x;
        this.y = p.y;
    }
}

let piece = new Piece();

const KEY = {
    LEFT: 'ArrowLeft'
}

const moves = {
    [KEY.LEFT]: (p) => ({...p, x: p.x - 1})
}

document.addEventListener('keydown', event => {
    if (moves[event.key]) {  
        event.preventDefault();
    
        let p = moves[event.key](piece);
    
        piece.move(p);
        }
    }
});

I cannot understand how to move a piece. piece is an instance of class Piece, to the best of my knowledge.

When variable p is declared, moves[event.keyCode](piece) is included, I don't know how this grammar works.

Especially this part.[KEY.LEFT]: (p) => ({...p, x: p.x - 1})

I'm wondering why there should be a : between [KEY.LEFT] and (p), and if there's no parentheses over the arrow function, the interpreter gets a grammar error. this. '('{...p, x: p.x - 1}')'

and ...p, x: p.x - 1 And what this means. I'm sorry it's such a basic grammar, but I don't know where I can ask questions.

I think I've tried something too difficult that doesn't fit my level..

  • That looks like basic JavaScript code. If you don't understand it, you should start with an introduction book or tutorial. – jabaa Jul 15 '23 at 12:41
  • Are you just asking what [an arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) is? It's not clear what specifically you're asking. – David Jul 15 '23 at 12:41
  • 1
    `moves` is an object with a property named `ArrowLeft` (which is the value of `KEY.LEFT`) and that property is a function. So in the last line you just call a function providing a parameter `piece` which is not clear what it is from your question. As it's tetris `piece` probably describes the position of a square within the tetris grid, but that's guessing. Please provide more details to what actually is the question. – Mushroomator Jul 15 '23 at 12:41

1 Answers1

0

moves[KEY.LEFT] is a reference to a function. This function accepts p as an argument. You are passing piece to this function.

Within the function it applies the Spread operator to define a new object which is effectively a clone of the piece which was passed in, with the x property ameneded.

Here's an example of your original code using more readable syntax, which may make its logic clearer:

const moves = {
  'ArrowLeft': function(piece) {
    return {
      ...piece,
      x: piece.x - 1
    }
  }
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339