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); } function post_json(url, json) { var request = new XMLHttpRequest(); request.open("post", url, false); request.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); request.send(JSON.stringify(json)); if (request.status != 200) return null; return JSON.parse(request.responseText); } class Backend { getConfig() { return new Map( Object.entries(get_json("http://localhost:3000/get_state/")) ); } makeMove(source, target) { return post_json("http://localhost:3000/make_move/", [source, target]); } getAvailableMoves(position) { return post_json("http://localhost:3000/get_moves/", position); } } 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); } updateState() { 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.activeSquares.setMoveSquares(this.canvas, validMoves); this.moveSource = source; } finalizeMove(target) { if (target !== null) { this.backend.makeMove(this.moveSource, target); } this.activeSquares.unselectSquare(this.canvas); this.activeSquares.unsetMoveSquares(this.canvas); this.updateState(); 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); } } } new Chess();