Implement basic frontend-engine interaction
Use a Flask-based Python server as an adapter to the engine's stdin-stdout inferface.
This commit is contained in:
46
adapter/adapter.py
Normal file
46
adapter/adapter.py
Normal file
@@ -0,0 +1,46 @@
|
||||
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, file, rank = piece_str
|
||||
return {
|
||||
"who": dict(PIECE_TYPE)[piece_type],
|
||||
"color": dict(COLOR)[color],
|
||||
"position": f"{file}{rank}",
|
||||
}
|
||||
|
||||
|
||||
@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 = [
|
||||
make_piece(position_str[i : i + 4])
|
||||
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)
|
||||
Reference in New Issue
Block a user