Files
chess/adapter/adapter.py

46 lines
990 B
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(
[os.path.join(HERE, "../rs/target/debug/schach")],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
def make_piece(piece_str):
piece_type, color = piece_str
return {
"piece_type": dict(PIECE_TYPE)[piece_type],
"color": dict(COLOR)[color],
}
@app.route("/get_state/")
def get_state():
engine.stdin.write(b"get_state\n")
engine.stdin.flush()
position_str = engine.stdout.readline().decode("ascii").strip()
position = {
position_str[i + 2 : i + 4]: make_piece(position_str[i : i + 2])
for i in range(0, len(position_str), 4)
}
return flask.jsonify(position)
if __name__ == "__main__":
app.run(debug=True, host="127.0.0.1", port=3000)