From f9212a8291b01bca69a46e2894a7b45893d74014 Mon Sep 17 00:00:00 2001 From: Pavel Lutskov Date: Mon, 13 Dec 2021 20:05:07 +0100 Subject: [PATCH] Refactor move handling in frontend Make the move handlers better encapsulated and abstract away the click. Issue #3 --- frontend/main.js | 56 +++++++++++++++++++++++------------------------- 1 file changed, 27 insertions(+), 29 deletions(-) diff --git a/frontend/main.js b/frontend/main.js index 142148f..65a9b07 100644 --- a/frontend/main.js +++ b/frontend/main.js @@ -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); } - } - _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(); + if (this.moveSource === null) { + this.initializeMove(position); + } else { + this.finalizeMove(position); } - 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); } } }