-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendgame.py
More file actions
77 lines (65 loc) · 1.97 KB
/
endgame.py
File metadata and controls
77 lines (65 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import json
import random
import urllib
import urllib2
from board import Board
from pieces import get_piece_by_title
from utils import name_to_cell, color_sign, get_fen_from_board
def get_syzygy_best_move(board):
'''
WDL - 6 pieces
DTM - 5 pieces
'''
if len(board.pieces) > 6:
return None
fen = get_fen_from_board(board)
try:
response = urllib2.urlopen(
"https://syzygy-tables.info/api/v2?fen={}".format(urllib.quote(fen))).read()
parsed = json.loads(response)
except Exception:
return None
parsed_moves = [{
'key': key,
'wdl': value['wdl'],
'dtm': value['dtm']
} for key, value in parsed['moves'].items()]
if not parsed_moves:
# Is it a draw?
return None
random.shuffle(parsed_moves)
if len(board.pieces) == 6:
parsed_moves.sort(key=lambda x: x['wdl'])
else:
parsed_moves.sort(key=lambda x: (x['wdl'], -x['dtm']))
parsed_move = parsed_moves[0]
# TODO: promotions
sign = color_sign(board.move_color)
if parsed_move['wdl'] == 0:
evaluation = 0
else:
if parsed_move['dtm'] is None:
evaluation = Board.MAX_EVALUATION / 2
else:
evaluation = Board.MAX_EVALUATION / 2 - abs(parsed_move['dtm']) - 1
if parsed_move['wdl'] > 0:
evaluation *= -1
evaluation *= sign
position = name_to_cell(parsed_move['key'][:2])
new_position = name_to_cell(parsed_move['key'][2:4])
piece = board.pieces[position][0]
new_piece = piece
if len(parsed_move['key']) == 5:
new_piece = get_piece_by_title(parsed_move['key'][4])
captured_piece, _ = board.pieces.get(new_position, (None, None))
move = {
'position': position,
'new_position': new_position,
'piece': piece,
'new_piece': new_piece,
'captured_piece': captured_piece
}
return {
'evaluation': evaluation,
'moves': [move]
}