Add basic autoplay features to frontend

Rudimentary play for white against engine is now possible.
This commit is contained in:
2021-12-27 20:16:38 +01:00
parent c92a9e42d7
commit 5916a054ad
2 changed files with 37 additions and 1 deletions

View File

@@ -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)

View File

@@ -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);