Refactor move handling in frontend

Make the move handlers better encapsulated and abstract away the click.

Issue #3
This commit is contained in:
2021-12-13 20:05:07 +01:00
parent 941a5c072a
commit f9212a8291

View File

@@ -16,8 +16,8 @@ class Backend {
getConfig() {
return this.config;
}
makeMove(move) {
this.config.makeMove(move);
makeMove(source, target) {
this.config.makeMove(source, target);
}
getAvailableMoves(position) {
position;
@@ -40,34 +40,32 @@ class Chess {
this.configVis.configuration = config;
this.configVis.draw(this.canvas);
}
showAvailableMoves(canMoveTo) {
canMoveTo;
initializeMove(source) {
if (source === null) return;
let validMoves = this.backend.getAvailableMoves(source);
if (validMoves === null) return;
this.moveSource = source;
}
finalizeMove(target) {
if (target !== null) {
this.backend.makeMove(this.moveSource, target);
}
this.syncBackend();
this.moveSource = null;
}
click(ev) {
if (this.moveSource === null) {
this._firstClick(ev);
let rc = this.canvas.screenCoordsToRowCol(ev.clientX, ev.clientY);
let position;
if (rc === null) {
position = null;
} else {
this._secondClick(ev);
position = visuals.rowColToBoardIndex(...rc);
}
if (this.moveSource === null) {
this.initializeMove(position);
} else {
this.finalizeMove(position);
}
_firstClick(ev) {
let rcA = this.canvas.screenCoordsToRowCol(ev.clientX, ev.clientY);
if (rcA === null) return;
let positionA = visuals.rowColToBoardIndex(...rcA);
this.showAvailableMoves(this.backend.getAvailableMoves(positionA));
this.moveSource = positionA;
}
_secondClick(ev) {
let rcB = this.canvas.screenCoordsToRowCol(ev.clientX, ev.clientY);
if (rcB !== null) {
let move = {
from: this.moveSource,
to: visuals.rowColToBoardIndex(...rcB),
};
this.backend.makeMove(move);
this.syncBackend();
}
this.moveSource = null;
}
}
@@ -87,12 +85,12 @@ class Configuration {
dropAt(position) {
this.board.delete(position);
}
makeMove(move) {
const piece = this.getAt(move.from);
makeMove(source, target) {
const piece = this.getAt(source);
if (piece === null) return;
else {
this.setAt(move.to, piece);
this.dropAt(move.from);
this.setAt(target, piece);
this.dropAt(source);
}
}
}