113 lines
2.5 KiB
JavaScript
113 lines
2.5 KiB
JavaScript
import * as visuals from "./visuals.js";
|
|
|
|
function get_json(url) {
|
|
var request = new XMLHttpRequest();
|
|
request.open("get", url, false);
|
|
request.send(null);
|
|
return JSON.parse(request.responseText);
|
|
}
|
|
|
|
class Backend {
|
|
constructor() {
|
|
this.config = new Configuration(
|
|
new Map(Object.entries(get_json("http://localhost:3000/get_state/")))
|
|
);
|
|
}
|
|
getConfig() {
|
|
return this.config;
|
|
}
|
|
makeMove(move) {
|
|
this.config.makeMove(move);
|
|
}
|
|
getAvailableMoves(position) {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
class Chess {
|
|
constructor() {
|
|
this.backend = new Backend();
|
|
this.canvas = new visuals.Canvas();
|
|
this.configVis = new visuals.ConfigVis(this.backend.getConfig());
|
|
this.configVis.draw(this.canvas);
|
|
this.moveSource = null;
|
|
this.canMoveTo = [];
|
|
document.onclick = (ev) => this.click(ev);
|
|
}
|
|
syncBackend() {
|
|
let config = this.backend.getConfig();
|
|
this.configVis.configuration = config;
|
|
this.configVis.draw(this.canvas);
|
|
}
|
|
showAvailableMoves(canMoveTo) {}
|
|
click(ev) {
|
|
if (this.moveSource === null) {
|
|
this._firstClick(ev);
|
|
} else {
|
|
this._secondClick(ev);
|
|
}
|
|
}
|
|
_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;
|
|
}
|
|
}
|
|
|
|
class Move {
|
|
constructor(kind, from, to) {
|
|
this.kind = kind;
|
|
this.from = from;
|
|
this.to = to;
|
|
}
|
|
}
|
|
|
|
class Piece {
|
|
constructor(piece_type, color) {
|
|
this.piece_type = piece_type;
|
|
this.color = color;
|
|
}
|
|
}
|
|
|
|
class Configuration {
|
|
constructor(board) {
|
|
this.board = new Map(board);
|
|
}
|
|
getAt(position) {
|
|
if (!this.board.has(position)) {
|
|
return null;
|
|
}
|
|
return this.board.get(position);
|
|
}
|
|
setAt(position, piece) {
|
|
this.board.set(position, piece);
|
|
}
|
|
dropAt(position) {
|
|
this.board.delete(position);
|
|
}
|
|
makeMove(move) {
|
|
const piece = this.getAt(move.from);
|
|
if (piece === null) return;
|
|
else {
|
|
this.setAt(move.to, piece);
|
|
this.dropAt(move.from);
|
|
}
|
|
}
|
|
}
|
|
|
|
new Chess();
|