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..