Add basic moving capabilities

This commit is contained in:
2021-06-01 21:47:06 +02:00
parent a3ae7c9f71
commit 0540b262dd

View File

@@ -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();