-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvaluator.py
140 lines (111 loc) · 5.07 KB
/
valuator.py
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
""" Valuator to evaluate board states. """
import chess
class Valuator:
MAX_VAL = 100000
MIN_VAL = -100000
piece_values = {chess.PAWN: 10,
chess.KNIGHT: 30,
chess.BISHOP: 30,
chess.ROOK: 50,
chess.QUEEN: 90,
chess.KING: 900}
# Postional values. Use [-square_num] for black and subtract value.
position_values = {
chess.PAWN: [
0, 0, 0, 0, 0, 0, 0, 0,
5, 5, 5, 5, 5, 5, 5, 5,
1, 1, 2, 3, 3, 2, 1, 1,
0.5, 0.5, 1, 2.5, 2.5, 1, 0.5, 0.5,
0, 0, 0, 2, 2, 0, 0, 0,
0.5, -0.5, -1, 0, 0, -1, -0.5, 0.5,
0.5, 1, 1, -2, -2, 1, 1, 0.5,
0, 0, 0, 0, 0, 0, 0, 0
],
chess.KNIGHT: [
-5.0, -4.0, -3.0, -3.0, -3.0, -3.0, -4.0, -5.0,
-4.0, -2.0, 0.0, 0.0, 0.0, 0.0, -2.0, -4.0,
-3.0, 0.0, 1.0, 1.5, 1.5, 1.0, 0.0, -3.0,
-3.0, 0.5, 1.5, 2.0, 2.0, 1.5, 0.5, -3.0,
-3.0, 0.0, 1.5, 2.0, 2.0, 1.5, 0.0, -3.0,
-3.0, 0.5, 1.0, 1.5, 1.5, 1.0, 0.5, -3.0,
-4.0, -2.0, 0.0, 0.5, 0.5, 0.0, -2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-2.0, -1.0, -1.0, -0.5, -0.5, -1.0, -1.0, -2.0
],
chess.KING: [
-3.0, -4.0, -4.0, -5.0, -5.0, -4.0, -4.0, -3.0,
-3.0, -4.0, -4.0, -5.0, -5.0, -4.0, -4.0, -3.0,
-3.0, -4.0, -4.0, -5.0, -5.0, -4.0, -4.0, -3.0,
-3.0, -4.0, -4.0, -5.0, -5.0, -4.0, -4.0, -3.0,
-2.0, -3.0, -3.0, -4.0, -4.0, -3.0, -3.0, -2.0,
-1.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -1.0,
2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 2.0,
2.0, 3.0, 1.0, 0.0, 0.0, 1.0, 3.0, 2.0
]
}
cache_misses = 0
def __init__(self):
self.memoization = {} # Dict for optimisation,
# key,val = FEN + info, valution.
# Make object call with state parameter
def __call__(self, s):
key = s.key() # To FEN and other info
if key not in self.memoization:
self.cache_misses += 1
self.memoization[key] = self.value(s)
return self.memoization[key]
def value(self, s):
""" Value the given state argument. """
b = s.board
# Game over values
if b.is_game_over():
if b.result() == "1-0": # White wins
return self.MAX_VAL
elif b.result() == "0-1": # Black wins
return self.MIN_VAL
else:
return 0
# Net piece values & positional values.
# White is maximising (positive)
# Black is minimising (negative)
val = 0.0
pm = s.board.piece_map()
for square, piece in pm.items():
# Get piece value
piece_val = self.piece_values[piece.piece_type]
if piece.color == chess.WHITE:
val += piece_val
val += self.position_values[piece.piece_type][square]
else:
val -= piece_val
val -= self.position_values[piece.piece_type][-square]
return val