diff --git a/adapter/adapter.py b/adapter/adapter.py index 5dc01ec..5e8c7a2 100644 --- a/adapter/adapter.py +++ b/adapter/adapter.py @@ -22,6 +22,10 @@ engine = subprocess.Popen( ) +def reverse(zipped): + return ((b, a) for a, b in zipped) + + def make_piece(piece_str): piece_type, color = piece_str return { @@ -68,5 +72,12 @@ def make_move(): return flask.jsonify(parse_state(state_str)) +@app.route("/choose_move/", methods=["POST"]) +def choose_move(): + color = dict(reverse(COLOR))[flask.request.json] + move = ask_engine(f"choose_move,{color}") + return flask.jsonify(move) + + if __name__ == "__main__": app.run(debug=True, host="127.0.0.1", port=3000) diff --git a/frontend/main.js b/frontend/main.js index 82fe807..3ea8eef 100644 --- a/frontend/main.js +++ b/frontend/main.js @@ -25,6 +25,9 @@ class Backend { makeMove(source, target) { return post_json("http://localhost:3000/make_move/", [source, target]); } + chooseMove(color) { + return post_json("http://localhost:3000/choose_move/", color); + } getAvailableMoves(position) { return post_json("http://localhost:3000/get_moves/", position); } @@ -34,6 +37,16 @@ class Chess { constructor() { this.backend = new Backend(); this.canvas = new visuals.Canvas(); + this.button = document.createElement("button"); + this.autoplay = false; + this.button.innerHTML = "Autoplay Off"; + this.button.onclick = () => { + this.autoplay = !this.autoplay; + this.button.innerHTML = ["Autoplay Off", "Autoplay On"][ + Number(this.autoplay) + ]; + }; + document.body.appendChild(this.button); this.configVis = new visuals.ConfigVis(this.backend.getConfig()); this.configVis.draw(this.canvas); this.activeSquares = new visuals.ActiveSquares(); @@ -46,6 +59,12 @@ class Chess { this.configVis.configuration = config; this.configVis.draw(this.canvas); } + chooseMove() { + let move = this.backend.chooseMove("black"); + if (move === null) return; + this.backend.makeMove(...move); + this.updateState(); + } initializeMove(source) { if (source === null) return; let validMoves = this.backend.getAvailableMoves(source); @@ -55,13 +74,19 @@ class Chess { this.moveSource = source; } finalizeMove(target) { + let success; if (target !== null) { - this.backend.makeMove(this.moveSource, target); + success = this.backend.makeMove(this.moveSource, target) !== null; + } else { + success = false; } this.activeSquares.unselectSquare(this.canvas); this.activeSquares.unsetMoveSquares(this.canvas); this.updateState(); this.moveSource = null; + if (this.autoplay && success) { + this.chooseMove(); + } } click(ev) { let rc = this.canvas.screenCoordsToRowCol(ev.clientX, ev.clientY);