From 0540b262ddf667e628cd588b1733ec3dd851b2d8 Mon Sep 17 00:00:00 2001 From: Pavel Lutskov Date: Tue, 1 Jun 2021 21:47:06 +0200 Subject: [PATCH] Add basic moving capabilities --- frontend/main.js | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/frontend/main.js b/frontend/main.js index b2980a0..2259ee2 100644 --- a/frontend/main.js +++ b/frontend/main.js @@ -46,6 +46,13 @@ function computeScreenCoords(position, canvas) { return [topPx, leftPx] } +class Move { + constructor(kind, from, to) { + this.kind = kind; + this.from = from; + this.to = to; + } +} class Piece { constructor(who, color, position) { @@ -75,6 +82,12 @@ class Piece { this._im.style.left = `${leftPx}px`; } } + undraw() { + if (this._im !== null) { + this._im.remove(); + this._im = null; + } + } } class Configuration { @@ -86,6 +99,28 @@ class Configuration { piece.draw(canvas); } } + getAt(position) { + for (let piece of this.pieces) { + if (piece.position === position) return piece; + } + return null; + } + dropAt(position) { + for (let idx = 0; idx < this.pieces.length; idx++) { + if (this.pieces[idx].position === position) { + this.pieces[idx].undraw(); + this.pieces.splice(idx, 1); + return; + } + } + } + makeMove(move, canvas) { + let piece = this.getAt(move.from); + if (piece === null) return; + this.dropAt(move.to); + piece.position = move.to; + piece.draw(canvas); + } } function setupBoard() { @@ -125,11 +160,19 @@ function boardIndexToRowCol(boardIndex) { return [row, col]; } -function demo() { +async function demo() { let canvas = createCanvas(); drawChessBoard(canvas); let config = setupBoard(); config.draw(canvas); + await new Promise(r => setTimeout(r, 6000)); + config.makeMove({'kind': 'xxx', 'from': 'e2', 'to': 'e4'}, canvas); + await new Promise(r => setTimeout(r, 2000)); + config.makeMove({'kind': 'xxx', 'from': 'e7', 'to': 'e5'}, canvas); + await new Promise(r => setTimeout(r, 2000)); + config.makeMove({'kind': 'xxx', 'from': 'd2', 'to': 'd4'}, canvas); + await new Promise(r => setTimeout(r, 2000)); + config.makeMove({'kind': 'xxx', 'from': 'e5', 'to': 'd4'}, canvas); } demo();