Skip to content

Commit e47fc80

Browse files
committed
Add a move search api using Flask
1 parent a922013 commit e47fc80

5 files changed

Lines changed: 79 additions & 0 deletions

File tree

app/__init__.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# -*- coding: utf-8 -*-
2+
from flask import Flask
3+
4+
# Initialize the app
5+
app = Flask(__name__, instance_relative_config=True)
6+
7+
# Load the views
8+
from app import views
9+
10+
# Load the config file
11+
app.config.from_object('config')

app/views.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# -*- coding: utf-8 -*-
2+
from flask import jsonify
3+
from flask import request
4+
from flask import abort
5+
6+
from app import app
7+
from zerosum import solvers
8+
from zerosum import base
9+
from zerosum.examples import tictactoe
10+
11+
12+
solvers_map = {
13+
'minimax': solvers.Minimax,
14+
'negamax': solvers.Negamax,
15+
'alphabeta': solvers.AlphaBeta,
16+
}
17+
18+
19+
evaluators_map = {
20+
'smart': tictactoe.SmartEvaluator,
21+
'simple': tictactoe.SimpleEvaluator,
22+
}
23+
24+
25+
@app.route('/')
26+
def index():
27+
api_description = {
28+
'/api/search/': {
29+
'evaluators': list(evaluators_map),
30+
'solvers': list(solvers_map),
31+
'maxDepth': list(range(10)),
32+
}
33+
}
34+
return jsonify(api_description)
35+
36+
37+
@app.route('/api/search', methods=['POST'])
38+
def search():
39+
data = request.json
40+
if not data or 'board' not in data or 'players' not in data:
41+
abort(400)
42+
43+
board = tictactoe.Board(squares=data['board'], players=data['players'])
44+
45+
Evaluator = evaluators_map[data.get('evaluator', 'smart')]
46+
Solver = solvers_map[data.get('solver', 'minimax')]
47+
max_depth = data.get('maxDepth', 5)
48+
49+
solver = Solver(evaluator=Evaluator(), max_depth=max_depth)
50+
scored_move = solver.search(board)
51+
result = dict(zip(['score', 'move'], scored_move))
52+
53+
response = {
54+
'result': result,
55+
'solver': Solver.__name__,
56+
'evaluator': Evaluator.__name__,
57+
'maxDepth': max_depth,
58+
}
59+
return jsonify(response)

config.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# -*- coding: utf-8 -*-
2+
# Enable Flask's debugging features. Should be False in production
3+
DEBUG = True

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
Faker==0.7.17
22
Click>=6.0
3+
Flask==0.12.2

run.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# -*- coding: utf-8 -*-
2+
from app import app
3+
4+
if __name__ == '__main__':
5+
app.run()

0 commit comments

Comments
 (0)