102 lines
2.4 KiB
JavaScript
102 lines
2.4 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(source, target) {
|
|
this.config.makeMove(source, target);
|
|
}
|
|
getAvailableMoves(position) {
|
|
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.activeSquares = new visuals.ActiveSquares();
|
|
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);
|
|
}
|
|
initializeMove(source) {
|
|
if (source === null) return;
|
|
let validMoves = this.backend.getAvailableMoves(source);
|
|
if (validMoves === null) return;
|
|
this.activeSquares.selectSquare(this.canvas, source);
|
|
this.moveSource = source;
|
|
}
|
|
finalizeMove(target) {
|
|
if (target !== null) {
|
|
this.backend.makeMove(this.moveSource, target);
|
|
}
|
|
this.activeSquares.unselectSquare(this.canvas);
|
|
this.syncBackend();
|
|
this.moveSource = null;
|
|
}
|
|
click(ev) {
|
|
let rc = this.canvas.screenCoordsToRowCol(ev.clientX, ev.clientY);
|
|
let position;
|
|
if (rc === null) {
|
|
position = null;
|
|
} else {
|
|
position = visuals.rowColToBoardIndex(...rc);
|
|
}
|
|
if (this.moveSource === null) {
|
|
this.initializeMove(position);
|
|
} else {
|
|
this.finalizeMove(position);
|
|
}
|
|
}
|
|
}
|
|
|
|
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(source, target) {
|
|
const piece = this.getAt(source);
|
|
if (piece === null) return;
|
|
else {
|
|
this.setAt(target, piece);
|
|
this.dropAt(source);
|
|
}
|
|
}
|
|
}
|
|
|
|
new Chess();
|