-
Notifications
You must be signed in to change notification settings - Fork 0
/
static_book_player.coffee
51 lines (44 loc) · 1.11 KB
/
static_book_player.coffee
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
{ encode_normalized } = require './encode'
book = require './openings.json'
{ SCORE_MULT } = require './pattern'
defaults =
random: 1
verbose: true
module.exports = (options={}) ->
opts = {defaults..., options...}
(board, me, moves) ->
nodes = []
sum = 0
max = -Infinity
best = null
for move in moves or board.list_moves(me)
flips = board.move me, move
code = encode_normalized(board)
data = book[code]
board.undo me, move, flips
if data
value = data.value * me
node = {move, value, n:data.n}
nodes.push node
if value > max
max = value
best = node
return null unless nodes.length
if opts.random
avg = 0
for node in nodes
avg += node.n
avg /= nodes.length
sum_p = 0
for node in nodes
node.p = (node.n / avg) ** (1 / opts.random)
sum_p += node.p
r = Math.random() * sum_p
sum_p = 0
for node in nodes
sum_p += node.p
if sum_p > r
best = node
break
console.log 'book', best.n if opts.verbose
best