Makes it easier to start the app eliminating the danger of forgetting to build.
73 lines
1.6 KiB
Python
73 lines
1.6 KiB
Python
import os
|
|
import subprocess
|
|
|
|
import flask
|
|
from flask_cors import CORS
|
|
|
|
|
|
PIECE_TYPE = [("P", "pawn")]
|
|
COLOR = [
|
|
("W", "white"),
|
|
("B", "black"),
|
|
]
|
|
|
|
HERE = os.path.abspath(os.path.dirname(__file__))
|
|
app = flask.Flask(__name__)
|
|
CORS(app)
|
|
engine = subprocess.Popen(
|
|
["cargo", "run"],
|
|
stdin=subprocess.PIPE,
|
|
stdout=subprocess.PIPE,
|
|
cwd=os.path.join(HERE, "../rs"),
|
|
)
|
|
|
|
|
|
def make_piece(piece_str):
|
|
piece_type, color = piece_str
|
|
return {
|
|
"piece_type": dict(PIECE_TYPE)[piece_type],
|
|
"color": dict(COLOR)[color],
|
|
}
|
|
|
|
|
|
def ask_engine(command):
|
|
engine.stdin.write(f"{command}\n".encode("ascii"))
|
|
engine.stdin.flush()
|
|
reply = engine.stdout.readline().decode("ascii").strip()
|
|
status, result = reply.split(",")
|
|
if status != "ok":
|
|
flask.abort(400)
|
|
return result
|
|
|
|
|
|
def parse_state(state_str):
|
|
return {
|
|
state_str[i + 2 : i + 4]: make_piece(state_str[i : i + 2])
|
|
for i in range(0, len(state_str), 4)
|
|
}
|
|
|
|
|
|
@app.route("/get_state/")
|
|
def get_state():
|
|
state_str = ask_engine("get_state")
|
|
return flask.jsonify(parse_state(state_str))
|
|
|
|
|
|
@app.route("/get_moves/", methods=["POST"])
|
|
def get_moves():
|
|
position_str = flask.request.json
|
|
moves_str = ask_engine(f"get_moves,{position_str}")
|
|
moves = [moves_str[i : i + 2] for i in range(0, len(moves_str), 2)]
|
|
return flask.jsonify(moves)
|
|
|
|
|
|
@app.route("/make_move/", methods=["POST"])
|
|
def make_move():
|
|
source, target = flask.request.json
|
|
state_str = ask_engine(f"make_move,{source},{target}")
|
|
return flask.jsonify(parse_state(state_str))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
app.run(debug=True, host="127.0.0.1", port=3000)
|