Add basic moving capabilities
This commit is contained in:
@@ -46,6 +46,13 @@ function computeScreenCoords(position, canvas) {
|
|||||||
return [topPx, leftPx]
|
return [topPx, leftPx]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class Move {
|
||||||
|
constructor(kind, from, to) {
|
||||||
|
this.kind = kind;
|
||||||
|
this.from = from;
|
||||||
|
this.to = to;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
class Piece {
|
class Piece {
|
||||||
constructor(who, color, position) {
|
constructor(who, color, position) {
|
||||||
@@ -75,6 +82,12 @@ class Piece {
|
|||||||
this._im.style.left = `${leftPx}px`;
|
this._im.style.left = `${leftPx}px`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
undraw() {
|
||||||
|
if (this._im !== null) {
|
||||||
|
this._im.remove();
|
||||||
|
this._im = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Configuration {
|
class Configuration {
|
||||||
@@ -86,6 +99,28 @@ class Configuration {
|
|||||||
piece.draw(canvas);
|
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() {
|
function setupBoard() {
|
||||||
@@ -125,11 +160,19 @@ function boardIndexToRowCol(boardIndex) {
|
|||||||
return [row, col];
|
return [row, col];
|
||||||
}
|
}
|
||||||
|
|
||||||
function demo() {
|
async function demo() {
|
||||||
let canvas = createCanvas();
|
let canvas = createCanvas();
|
||||||
drawChessBoard(canvas);
|
drawChessBoard(canvas);
|
||||||
let config = setupBoard();
|
let config = setupBoard();
|
||||||
config.draw(canvas);
|
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();
|
demo();
|
||||||
|
|||||||
Reference in New Issue
Block a user