Merrills/Bot.pm untested

filter: Statementstmt 0.0% 0 / 311 Branchbran 0.0% 0 / 138 Conditioncond 0.0% 0 / 86 MC/DCmcdc 0.0% 0 / 53 Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 628 CC 70 SCAR 50.6
CC
70
Cov
0%
_search
506.0
_evaluate
110.0
choose
90.0
CRAP 157.9
1 package Game::Merrills::Bot;
2  
3 use strict;
4 use warnings;
5  
6 use Object::Proto::Sugar -types;
7 use Game::Merrills ();
8 use Game::Merrills::Points;
9 use Game::Merrills::Notation;
10 use Game::Merrills::Rules;
11 use Game::Merrills::Move;
12  
13 our $VERSION = '0.03';
14  
15 use constant {
16 WIN => 10_000,
17 INFINITY => 1_000_000,
18 MAX_EXTENSION => 2,
19 MAX_PV => 20,
20 EXACT => 0,
21 LOWER => 1,
22 UPPER => -1,
23 };
24  
25 use constant {
26 RM_FROM => Game::Merrills::Move::RM_FROM,
27 RM_TO => Game::Merrills::Move::RM_TO,
28 RM_REMOVE => Game::Merrills::Move::RM_REMOVE,
29 RM_CLOSES => Game::Merrills::Move::RM_CLOSES,
30 HAND_WHITE => Game::Merrills::Rules::HAND_WHITE,
31 HAND_BLACK => Game::Merrills::Rules::HAND_BLACK,
32 };
33  
34 our (%LEVEL, $MAN, $OPEN_TWO, $REACH, $MOBILITY, $JUNCTION);
35  
36 BEGIN {
37 %LEVEL = (
38 1 => { depth => 1, nodes => 300, jitter => 1 },
39 2 => { depth => 3, nodes => 3_000, jitter => 1 },
40 3 => { depth => 5, nodes => 20_000, jitter => 0 },
41 4 => { depth => 7, nodes => 100_000, jitter => 0 },
42 5 => { depth => 9, nodes => 400_000, jitter => 0 },
43 );
44  
45 $MAN = 100;
46 $OPEN_TWO = 8;
47 $REACH = 10;
48 $MOBILITY = 2;
49 $JUNCTION = 3;
50 }
51  
52 my %OTHER = (white => 'black', black => 'white');
53 my %VALUE = (white => 1, black => -1);
54  
55 my $ADJACENT = \@Game::Merrills::Points::ADJACENT;
56 my $MILLS = \@Game::Merrills::Points::MILLS;
57 my $MILLS_OF = \@Game::Merrills::Points::MILLS_OF;
58  
59 has level => (
60 is => 'ro',
61 isa => Int,
62 default => 3
63 );
64  
65 has seed => (
66 is => 'ro',
67 isa => Int,
68 default => 0
69 );
70  
71 has transposition => (
72 is => 'rw',
73 isa => Bool,
74 default => 1
75 );
76  
77 has last_search => (
78 is => 'rw'
79 );
80  
81 sub BUILD {
82 my ($self) = @_;
83 die 'level must be 1 .. 5, got ' . (defined $self->level ? "'" . $self->level . "'" : 'undef')
84 unless defined $self->level && $LEVEL{ $self->level };
85 return $self;
86 }
87  
88 sub levels {
89 return sort { $a <=> $b } keys %LEVEL;
90 }
91  
92 sub setting_for {
93 my ($class, $level) = @_;
94 my $setting = defined $level ? $LEVEL{$level} : undef;
95 die 'level must be 1 .. 5, got ' . (defined $level ? "'$level'" : 'undef') unless $setting;
96 return { %{$setting} };
97 }
98  
99 sub choose {
100 my ($self, $game) = @_;
101 return undef if $game->result;
102  
103 my $legal = $game->legal_moves;
104 return undef unless @{$legal};
105  
106 if (@{$legal} == 1) {
107 $self->last_search({
108 depth => 0,
109 nodes => 0,
110 score => undef,
111 forced => 1,
112 move => $legal->[0]->notation,
113 pv => [ $legal->[0]->notation ]
114 });
115 return $legal->[0];
116 }
117  
118 my $spec = $LEVEL{ $self->level };
119 my $position = Game::Merrills::Rules::position($game->board);
120 my $turn = $game->turn;
121 my $state = {
122 nodes => 0,
123 budget => $spec->{nodes},
124 jitter => $spec->{jitter},
125 table => {},
126 history => {},
127 killers => [],
128 flying => $game->flying ? 1 : 0,
129 limit => $Game::Merrills::NO_MILL_LIMIT || 0,
130 aborted => 0
131 };
132 my $seen = { %{ $game->repetition } };
133  
134 my ($best, $score, $reached);
135 for my $depth (1 .. $spec->{depth}) {
136 last if $state->{nodes} >= $state->{budget};
137 $state->{aborted} = 0;
138 my ($iteration_score, $move) = $self->_root(
139 $state, $position, $turn, $depth, $game->no_mill, $seen, $game->ply
140 );
141 last if $state->{aborted} || !$move;
142 ($best, $score, $reached) = ($move, $iteration_score, $depth);
143 }
144  
145 my $chosen = $legal->[0];
146 if ($best) {
147 my $name = _name($best);
148 for my $move (@{$legal}) {
149 next unless _name($move->to_raw) eq $name;
150 $chosen = $move;
151 last;
152 }
153 }
154  
155 $self->last_search({
156 depth => $reached || 0,
157 nodes => $state->{nodes},
158 score => $score,
159 forced => 0,
160 move => $chosen->notation,
161 pv => $self->_pv($state, $position, $turn, $best)
162 });
163 return $chosen;
164 }
165  
166 sub _name {
167 my ($raw) = @_;
168 return join '.', map { defined $_ ? $_ : '-' } @{$raw}[ RM_FROM, RM_TO, RM_REMOVE ];
169 }
170  
171 sub _notation {
172 my ($raw) = @_;
173 return Game::Merrills::Notation::format_move({
174 from => $raw->[RM_FROM],
175 to => $raw->[RM_TO],
176 remove => $raw->[RM_REMOVE],
177 });
178 }
179  
180 sub _root {
181 my ($self, $state, $position, $turn, $depth, $no_mill, $seen, $ply) = @_;
182 my $moves = Game::Merrills::Rules::generate($position, $turn, $state->{flying});
183 return (undef, undef) unless @{$moves};
184  
185 my $alpha = -INFINITY();
186 my ($best, $best_score);
187 for my $raw (@{ $self->_ordered($state, $moves, 0, undef) }) {
188 my $bound = $state->{jitter} ? -INFINITY() : $alpha;
189 my $score = $self->_child(
190 $state, $position, $turn, $raw,
191 $depth - 1, -INFINITY(), -$bound, 1, 0, $no_mill, $seen
192 );
193 return (undef, undef) if $state->{aborted};
194  
195 $score += _jitter($self->seed, $ply, $raw) if $state->{jitter};
196  
197 if (!defined $best_score || $score > $best_score) {
198 ($best, $best_score) = ($raw, $score);
199 $alpha = $score if $score > $alpha && !$state->{jitter};
200 }
201 }
202 return ($best_score, $best);
203 }
204  
205 sub _child {
206 my ($self, $state, $position, $turn, $raw, $depth, $alpha, $beta, $ply,
207 $extension, $no_mill, $seen) = @_;
208  
209 my $next = $OTHER{$turn};
210 my ($child_seen, $child_quiet) = !defined $raw->[RM_FROM] || defined $raw->[RM_REMOVE]
211 ? ({}, 0)
212 : ($seen, $no_mill + 1);
213  
214 Game::Merrills::Rules::apply($position, $turn, $raw);
215 my $key;
216 if (!$position->[HAND_WHITE] && !$position->[HAND_BLACK]) {
217 $key = join '', @{$position}[ 0 .. 23 ], $next;
218 $child_seen->{$key}++;
219 }
220  
221 my $score = -$self->_search(
222 $state, $position, $next, $depth, $alpha, $beta, $ply, $extension,
223 $child_quiet, $child_seen, $key
224 );
225  
226 if (defined $key) {
227 delete $child_seen->{$key} unless --$child_seen->{$key};
228 }
229 Game::Merrills::Rules::unapply($position, $turn, $raw);
230 return $score;
231 }
232  
233 sub _search {
234 my ($self, $state, $position, $turn, $depth, $alpha, $beta, $ply,
235 $extension, $no_mill, $seen, $key) = @_;
236  
237 $state->{nodes}++;
238 if ($state->{nodes} >= $state->{budget}) {
239 $state->{aborted} = 1;
240 return 0;
241 }
242  
243 my $value = $VALUE{$turn};
244 my $men = $position->[ $value > 0 ? HAND_WHITE : HAND_BLACK ];
245 $men += grep { $_ == $value } @{$position}[ 0 .. 23 ];
246 return -WIN() + $ply if $men < 3;
247  
248 return 0 if defined $key && ($seen->{$key} || 0) >= 3;
249 return 0 if $state->{limit} && $no_mill >= $state->{limit};
250  
251 return $self->_quiesce(
252 $state, $position, $turn, $alpha, $beta, $ply, $extension, $no_mill, $seen
253 ) if $depth <= 0;
254  
255 my $slot = pack('c26', @{$position}) . $turn;
256 my $entry = $self->transposition ? $state->{table}{$slot} : undef;
257 my $table_move;
258 if ($entry) {
259 $table_move = $entry->[3];
260 if ($entry->[0] >= $depth && abs($entry->[1]) < WIN - 100) {
261 return $entry->[1] if $entry->[2] == EXACT;
262 return $entry->[1] if $entry->[2] == LOWER && $entry->[1] >= $beta;
263 return $entry->[1] if $entry->[2] == UPPER && $entry->[1] <= $alpha;
264 }
265 }
266  
267 my $moves = Game::Merrills::Rules::generate($position, $turn, $state->{flying});
268 return -WIN() + $ply unless @{$moves};
269  
270 my $original = $alpha;
271 my ($best_score, $best_move) = (-INFINITY(), undef);
272 for my $raw (@{ $self->_ordered($state, $moves, $ply, $table_move) }) {
273 my $score = $self->_child(
274 $state, $position, $turn, $raw,
275 $depth - 1, -$beta, -$alpha, $ply + 1, $extension, $no_mill, $seen
276 );
277 return 0 if $state->{aborted};
278  
279 if ($score > $best_score) {
280 ($best_score, $best_move) = ($score, $raw);
281 $alpha = $score if $score > $alpha;
282 }
283 next if $alpha < $beta;
284  
285 my $name = _name($raw);
286 $state->{history}{$name} += $depth * $depth;
287 my $killers = $state->{killers}[$ply] ||= [];
288 unshift @{$killers}, $name
289 unless @{$killers} && $killers->[0] eq $name;
290 pop @{$killers} while @{$killers} > 2;
291 last;
292 }
293  
294 if ($self->transposition) {
295 my $flag = $best_score <= $original ? UPPER
296 : $best_score >= $beta ? LOWER
297 : EXACT;
298 $state->{table}{$slot} = [
299 $depth, $best_score, $flag,
300 $best_move && [ @{$best_move} ]
301 ];
302 }
303 return $best_score;
304 }
305  
306 sub _quiesce {
307 my ($self, $state, $position, $turn, $alpha, $beta, $ply, $extension,
308 $no_mill, $seen) = @_;
309  
310 return -WIN() + $ply
311 unless Game::Merrills::Rules::has_move($position, $turn, $state->{flying});
312  
313 my $stand = _evaluate($position, $turn, $state->{flying});
314 return $stand if $extension >= MAX_EXTENSION || $stand >= $beta;
315  
316 my @captures = grep { defined $_->[RM_REMOVE] }
317 @{ Game::Merrills::Rules::generate($position, $turn, $state->{flying}) };
318 return $stand unless @captures;
319  
320 my $best = $stand;
321 $alpha = $stand if $stand > $alpha;
322 for my $raw (@captures) {
323 my $score = $self->_child(
324 $state, $position, $turn, $raw,
325 0, -$beta, -$alpha, $ply + 1, $extension + 1, $no_mill, $seen
326 );
327 return 0 if $state->{aborted};
328 $best = $score if $score > $best;
329 $alpha = $score if $score > $alpha;
330 last if $alpha >= $beta;
331 }
332 return $best;
333 }
334  
335 sub _ordered {
336 my ($self, $state, $moves, $ply, $table_move) = @_;
337 my $wanted = $table_move ? _name($table_move) : '';
338 my $killers = $state->{killers}[$ply] || [];
339 my $history = $state->{history};
340  
341 my @scored;
342 for my $i (0 .. $#{$moves}) {
343 my $raw = $moves->[$i];
344 my $name = _name($raw);
345 my $score = 0;
346 $score += 1_000_000 if $name eq $wanted;
347 $score += 1_000 + (10 * $raw->[RM_CLOSES]) if defined $raw->[RM_REMOVE];
348 $score += 400 if @{$killers} && $killers->[0] eq $name;
349 $score += 300 if @{$killers} > 1 && $killers->[1] eq $name;
350 $score += $history->{$name} || 0;
351 push @scored, [ $score, $i, $raw ];
352 }
353 return [
354 map { $_->[2] } sort { $b->[0] <=> $a->[0] || $a->[1] <=> $b->[1] } @scored
355 ];
356 }
357  
358 sub _pv {
359 my ($self, $state, $position, $turn, $first) = @_;
360 my @pv;
361 my @undo;
362  
363 my $raw = $first;
364 while (@pv < MAX_PV) {
365 unless ($raw) {
366 my $entry = $state->{table}{ pack('c26', @{$position}) . $turn } or last;
367 $raw = $entry->[3] or last;
368 }
369 my $name = _name($raw);
370 last unless grep { _name($_) eq $name }
371 @{ Game::Merrills::Rules::generate($position, $turn, $state->{flying}) };
372 push @pv, _notation($raw);
373 Game::Merrills::Rules::apply($position, $turn, $raw);
374 push @undo, [ $turn, $raw ];
375 $turn = $OTHER{$turn};
376 undef $raw;
377 }
378 Game::Merrills::Rules::unapply($position, @{ pop @undo }) while @undo;
379 return \@pv;
380 }
381  
382 sub _jitter {
383 my ($seed, $ply, $raw) = @_;
384 my $string = $seed . ':' . $ply . ':' . _name($raw);
385 my $hash = 0;
386 $hash = (($hash * 33) + ord) % 65_521 for split //, $string;
387 return $hash % 25;
388 }
389  
390 sub _evaluate {
391 my ($position, $turn, $flying) = @_;
392 my %hand = (1 => $position->[HAND_WHITE], -1 => $position->[HAND_BLACK]);
393 my %score = (1 => 0, -1 => 0);
394 my %count = (1 => 0, -1 => 0);
395 for my $point (0 .. 23) {
396 $count{ $position->[$point] }++ if $position->[$point];
397 }
398 my $placing = $hand{1} || $hand{-1};
399  
400 my @open;
401 for my $mill (@{$MILLS}) {
402 my ($one, $two, $three) = @{$position}[ @{$mill} ];
403 my $sum = $one + $two + $three;
404 next unless ($sum == 2 || $sum == -2) && !($one && $two && $three);
405 my ($empty) = grep { !$position->[$_] } @{$mill};
406 push @open, [ $sum > 0 ? 1 : -1, $empty, $mill ];
407 }
408  
409 for my $two (@open) {
410 my ($side, $empty, $mill) = @{$two};
411 $score{$side} += $OPEN_TWO;
412 if ($hand{$side}) {
413 $score{$side} += $REACH;
414 next;
415 }
416 if ($flying && $count{$side} == 3) {
417 $score{$side} += $REACH;
418 next;
419 }
420 my $reach = 0;
421 for my $near (@{ $ADJACENT->[$empty] }) {
422 next unless $position->[$near] == $side;
423 next if grep { $_ == $near } @{$mill};
424 $reach = 1;
425 }
426 $score{$side} += $REACH if $reach;
427 }
428  
429 for my $point (0 .. 23) {
430 my $side = $position->[$point] or next;
431 if ($placing) {
432 $score{$side} += $JUNCTION * (@{ $ADJACENT->[$point] } - 2);
433 next;
434 }
435 my $free = grep { !$position->[$_] } @{ $ADJACENT->[$point] };
436 $score{$side} += $MOBILITY * $free;
437 }
438  
439 $score{$_} += $MAN * ($count{$_} + $hand{$_}) for 1, -1;
440  
441 my $value = $VALUE{$turn};
442 return $score{$value} - $score{ -$value };
443 }
444  
445 1;
446  
447 __END__