Merrills/Terminal.pm untested

filter: Statementstmt 0.0% 0 / 880 Branchbran 0.0% 0 / 450 Conditioncond 0.0% 0 / 238 MC/DCmcdc 0.0% 0 / 136 Subroutinesub 0.0% 0 / 87 Podpod 0.0% 0 / 71 totaltotal 0.0% 0 / 1862 CC 226 SCAR 55.9
CC
226
Cov
0%
_run
1260.0
pick
552.0
show_choice
380.0
CRAP 267.1
1 package Game::Merrills::Terminal;
2  
3 use strict;
4 use warnings;
5  
6 use Object::Proto::Sugar -types;
7 use Game::Merrills;
8 use Game::Merrills::Bot;
9 use Game::Merrills::Notation;
10 use Game::Merrills::Points;
11 use Getopt::Long ();
12 use Game::Terminal::Kit::History;
13 use Game::Terminal::Kit::Keys;
14 use Game::Terminal::Kit::Line;
15 use Game::Terminal::Kit::Log;
16 use Game::Terminal::Kit::Run;
17 use Game::Terminal::Kit::Screen;
18 use Game::Terminal::Kit::Steer;
19  
20 our $VERSION = '0.03';
21  
22 use constant {
23 PITCH => 4,
24 WIDTH => 27,
25 ROWS => 13,
26 RECENT => 2,
27 };
28  
29 our (%COMMAND, %GLYPH, %INK, %GROUND, %BRACKET, %KEY);
30  
31 BEGIN {
32 %COMMAND = (
33 help => 'this list',
34 '?' => 'this list',
35 moves => 'the legal moves, numbered: play one by its number',
36 pick => 'choose a move with the arrow keys instead of typing it',
37 type => 'go back to typing moves out',
38 hint => 'what the bot would play here',
39 board => 'draw the board again',
40 position => 'the position as one line of text',
41 undo => 'take back your last move, and the reply to it',
42 redo => 'play again what undo took back',
43 'save FILE' => 'write the game out',
44 'load FILE' => 'read a game back in',
45 'level N' => 'set the strength of the bot, 1 to 5',
46 ascii => 'letters and dashes instead of drawn men and lines',
47 colour => 'turn the colours on or off',
48 draw => 'offer a draw',
49 accept => 'accept a draw that was offered',
50 decline => 'turn a draw down',
51 resign => 'give the game up',
52 quit => 'stop playing',
53 );
54  
55 %GLYPH = (
56 ascii => {
57 across => '-', down => '|', empty => '.', taken => 'x',
58 white => 'W', black => 'B',
59 },
60 wide => {
61 across => "\x{2500}", down => "\x{2502}", empty => "\x{00B7}", taken => "\x{00D7}",
62 white => "\x{25CB}", black => "\x{25CF}",
63 },
64 painted => {
65 across => "\x{2500}", down => "\x{2502}", empty => "\x{00B7}", taken => "\x{00D7}",
66 white => "\x{25CF}", black => "\x{25CF}",
67 },
68 );
69  
70 %INK = (
71 line => '38;5;179',
72 empty => '1;38;5;222',
73 white => '1;38;5;231',
74 black => '1;38;5;16',
75 bracket => '1;38;5;230',
76 taken => '1;38;5;217',
77 label => '38;5;109',
78 title => '1;38;5;222',
79 you => '1;38;5;120',
80 them => '1;38;5;215',
81 said => '38;5;250',
82 turn => '1;38;5;231',
83 mill => '1;38;5;220',
84 warn => '1;38;5;209',
85 good => '1;38;5;120',
86 hint => '38;5;117',
87 dim => '38;5;244',
88 step => '1;38;5;159',
89 cursor => '1;38;5;16;48;5;220',
90 key => '1;38;5;222',
91 );
92  
93 %GROUND = (
94 board => '48;5;94',
95 mill => '48;5;130',
96 last => '48;5;25',
97 left => '48;5;24',
98 taken => '48;5;124',
99 candidate => '48;5;28',
100 takeable => '48;5;127',
101 option => '48;5;58',
102 chosen => '48;5;31',
103 );
104  
105 %BRACKET = (
106 last => [ '(', ')' ],
107 left => [ '(', ')' ],
108 taken => [ '(', ')' ],
109 candidate => [ '[', ']' ],
110 takeable => [ '{', '}' ],
111 chosen => [ '<', '>' ],
112 );
113  
114 %KEY = (
115 u => 'undo',
116 r => 'redo',
117 t => 'type',
118 q => 'quit',
119 );
120 }
121  
122 my %OTHER = (white => 'black', black => 'white');
123  
124 has game => (
125 is => 'rw',
126 isa => Object
127 );
128  
129 has bot => (
130 is => 'rw'
131 );
132  
133 has human => (
134 is => 'rw',
135 isa => Str,
136 default => 'white'
137 );
138  
139 has [qw/in out/] => (
140 is => 'rw'
141 );
142  
143 has [qw/interactive colour/] => (
144 is => 'rw'
145 );
146  
147 has ascii => (
148 is => 'rw',
149 isa => Bool,
150 default => 0
151 );
152  
153 has redraw => (
154 is => 'rw',
155 isa => Bool,
156 default => 1
157 );
158  
159 has highlight => (
160 is => 'rw',
161 isa => HashRef,
162 default => sub { {} }
163 );
164  
165 has picking => (
166 is => 'rw',
167 isa => Bool
168 );
169  
170 has [qw/keyboard screen log/] => (
171 is => 'rw'
172 );
173  
174 has frame => (
175 is => 'rw',
176 isa => ArrayRef
177 );
178  
179 has keysource => (
180 is => 'rw',
181 isa => CodeRef
182 );
183  
184 has pending => (
185 is => 'rw',
186 isa => ArrayRef,
187 default => sub { [] }
188 );
189  
190 has preview => (
191 is => 'rw'
192 );
193  
194 has frames => (
195 is => 'rw',
196 isa => Int,
197 default => 0
198 );
199  
200 has history => (
201 is => 'rw'
202 );
203  
204 sub BUILD {
205 my ($self) = @_;
206 $self->game(Game::Merrills->new) unless $self->game;
207 die "human must be white, black, both or none, got '" . $self->human . "'"
208 unless $self->human =~ m/^(?:white|black|both|none)$/;
209 $self->in(\*STDIN) unless $self->in;
210 $self->out(\*STDOUT) unless $self->out;
211 $self->interactive(-t $self->in ? 1 : 0) unless defined $self->interactive;
212 $self->colour($self->interactive && !Game::Terminal::Kit::Screen::no_colour() ? 1 : 0)
213 unless defined $self->colour;
214 $self->keyboard(Game::Terminal::Kit::Keys->new(
215 in => $self->in,
216 pending => $self->pending,
217 ($self->keysource ? (keysource => $self->keysource) : ()),
218 )) unless $self->keyboard;
219 $self->screen(Game::Terminal::Kit::Screen->new(
220 out => $self->out,
221 interactive => $self->interactive,
222 colour => $self->colour,
223 ascii => $self->ascii,
224 )) unless $self->screen;
225 $self->log(Game::Terminal::Kit::Log->new(keep => RECENT)) unless $self->log;
226 $self->history(Game::Terminal::Kit::History->new(
227 save => sub { $_[0]->to_text },
228 load => sub { Game::Merrills->from_text($_[0]) },
229 )) unless $self->history;
230 $self->history->start($self->game);
231 $self->picking($self->interactive ? 1 : 0) unless defined $self->picking;
232 $self->picking(0) unless $self->keys_available;
233 $self->layer;
234 $self->screen->flush_on;
235 return $self;
236 }
237  
238 sub layer {
239 my ($self) = @_;
240 my $screen = $self->screen;
241 $screen->ascii($self->ascii ? 1 : 0);
242 $screen->colour($self->colour ? 1 : 0);
243 binmode $self->out, ':raw';
244 $screen->utf8;
245 return $self;
246 }
247  
248 sub start {
249 my ($self) = @_;
250 $self->say($self->paint("Nine Men's Morris.", 'title')
251 . $self->paint(' Type help for the commands.', 'dim'));
252 $self->picking(0) if $self->picking && !$self->enter_raw;
253 $self->history->start($self->game);
254 Game::Terminal::Kit::Run::guard(sub { $self->turns }, $self->keyboard, $self->screen);
255 return $self->game->result;
256 }
257  
258 sub turns {
259 my ($self) = @_;
260 while (1) {
261 my $picking = $self->picking && $self->raw && $self->human ne 'none';
262 $self->render if $self->redraw && !$picking;
263 if (my $result = $self->game->result) {
264 $self->render if $picking;
265 last;
266 }
267 if ($self->bot_plays($self->game->turn)) {
268 $self->bot_move;
269 next;
270 }
271 $self->person_turn;
272 my $line = $picking ? $self->pick : $self->read_line;
273 unless (defined $line) {
274 $self->say('Bye.');
275 last;
276 }
277 $self->log->shown;
278 my $stop = $self->command($line);
279 $self->log->shown unless $self->picking && $self->raw;
280 last if $stop;
281 }
282 return $self;
283 }
284  
285 sub person_turn {
286 my ($self) = @_;
287 $self->history->turn($self->game);
288 return $self;
289 }
290  
291 sub raw {
292 my ($self) = @_;
293 return $self->keyboard->raw;
294 }
295  
296 sub recent {
297 my ($self) = @_;
298 return [ map { @{$_} } @{ $self->log->recent } ];
299 }
300  
301 sub heard {
302 my ($self) = @_;
303 return $self->log->notes;
304 }
305  
306 sub keys_available {
307 my ($self) = @_;
308 return $self->keyboard->keys_available;
309 }
310  
311 sub enter_raw {
312 my ($self) = @_;
313 return $self->keyboard->enter_raw ? $self : undef;
314 }
315  
316 sub leave_raw {
317 my ($self) = @_;
318 $self->keyboard->leave_raw;
319 return $self;
320 }
321  
322 sub read_key {
323 my ($self, $wait) = @_;
324 return $self->keyboard->read_key($wait);
325 }
326  
327 sub components {
328 my ($self, $move) = @_;
329 return [ grep { defined } $move->from, $move->to, $move->remove ];
330 }
331  
332 sub matching {
333 my ($self, $prefix) = @_;
334 my @match;
335 MOVE: for my $move (@{ $self->game->legal_moves }) {
336 my $parts = $self->components($move);
337 next if @{$parts} < @{$prefix};
338 for my $i (0 .. $#{$prefix}) {
339 next MOVE unless $parts->[$i] == $prefix->[$i];
340 }
341 push @match, $move;
342 }
343 return \@match;
344 }
345  
346 sub options_for {
347 my ($self, $prefix) = @_;
348 my %next;
349 for my $move (@{ $self->matching($prefix) }) {
350 my $parts = $self->components($move);
351 $next{ $parts->[ scalar @{$prefix} ] } = 1 if @{$parts} > @{$prefix};
352 }
353 return [ sort { $a <=> $b } keys %next ];
354 }
355  
356 sub complete {
357 my ($self, $prefix) = @_;
358 for my $move (@{ $self->matching($prefix) }) {
359 return $move if @{ $self->components($move) } == @{$prefix};
360 }
361 return undef;
362 }
363  
364 sub nearest {
365 my ($self, $from, $direction, $candidates) = @_;
366 my @points = ($from, grep { $_ != $from } @{$candidates});
367 my $next = Game::Terminal::Kit::Steer::nearest(
368 [ map { [ Game::Merrills::Points::col_of($_), Game::Merrills::Points::row_of($_) ] } @points ],
369 0, Game::Terminal::Kit::Steer::way($direction),
370 );
371 return defined $next ? $points[$next] : $from;
372 }
373  
374 sub step_of {
375 my ($self, $prefix) = @_;
376 my $placing = $self->game->phase eq 'placing';
377 my @steps = $placing ? qw/to remove/ : qw/from to remove/;
378 return $steps[ scalar @{$prefix} ];
379 }
380  
381 sub pick {
382 my ($self) = @_;
383 return undef unless $self->raw;
384 return undef unless @{ $self->game->legal_moves };
385  
386 my (@prefix, $at, $hinted);
387 my $notice = [ @{ $self->log->notes } ];
388 $self->log->shown;
389 while (1) {
390 my $options = $self->options_for(\@prefix);
391 if ($hinted && !(defined $at && grep { $_ == $at } @{$options})) {
392 my $parts = $self->components($hinted);
393 my $follows = !grep { $parts->[$_] != $prefix[$_] } 0 .. $#prefix;
394 $at = $parts->[ scalar @prefix ] if $follows && @{$parts} > @prefix;
395 }
396 $at = $options->[0] unless defined $at && grep { $_ == $at } @{$options};
397  
398 $self->show_choice(\@prefix, $options, $at, $notice);
399 $notice = [];
400 my $key = $self->read_key;
401 if (!defined $key || $key eq 'eof' || $key eq 'interrupt') {
402 $self->done_picking;
403 return undef;
404 }
405  
406 if ($key =~ m/^(?:up|down|left|right)$/) {
407 $at = $self->nearest($at, $key, $options);
408 next;
409 }
410 if ($key eq 'tab' || $key eq 'j' || $key eq 'back_tab' || $key eq 'k') {
411 my ($index) = grep { $options->[$_] == $at } 0 .. $#{$options};
412 $at = $options->[ Game::Terminal::Kit::Steer::ring(
413 scalar @{$options}, $index, $key eq 'tab' || $key eq 'j' ? 1 : -1) ];
414 next;
415 }
416 if ($key eq 'home' || $key eq 'page_up') {
417 $at = $options->[0];
418 next;
419 }
420 if ($key eq 'end' || $key eq 'page_down') {
421 $at = $options->[-1];
422 next;
423 }
424 if ($key =~ m/^[a-gA-G]$/) {
425 my $rank = $self->read_key;
426 my $point = defined $rank ? Game::Merrills::Points::point($key . $rank) : undef;
427 if (defined $point && grep { $_ == $point } @{$options}) {
428 $at = $point;
429 }
430 else {
431 $notice = [ $self->paint(
432 defined $point ? ucfirst(Game::Merrills::Points::name($point)) . ' cannot be chosen here.'
433 : 'A point is a letter and a number, like d2.', 'warn') ];
434 }
435 next;
436 }
437 if ($key eq 'enter' || $key eq ' ') {
438 push @prefix, $at;
439 undef $at;
440 my $move = $self->complete(\@prefix) or next;
441 $self->done_picking;
442 $self->played($self->game->move($move));
443 return '';
444 }
445 if ($key eq 'backspace' || $key eq 'escape') {
446 if (@prefix) {
447 $at = pop @prefix;
448 }
449 else {
450 $notice = [ $self->paint('There is nothing to go back over.', 'warn') ];
451 }
452 next;
453 }
454 if ($key eq 'h') {
455 my $hint = $self->hint;
456 $notice = [ $self->paint($hint->{line}, 'hint') ];
457 $hinted = $hint->{move};
458 @prefix = ();
459 undef $at;
460 next;
461 }
462 if ($key eq '?') {
463 $notice = $self->key_lines;
464 next;
465 }
466 if ($key eq ':') {
467 $self->done_picking;
468 return $self->read_line(': ');
469 }
470 if ($KEY{$key}) {
471 $self->done_picking;
472 return $KEY{$key};
473 }
474 $notice = [ $self->paint('That key does nothing here. Press ? for the ones that do.', 'warn') ];
475 }
476 }
477  
478 sub done_picking {
479 my ($self) = @_;
480 $self->highlight({});
481 $self->preview(undef);
482 return $self;
483 }
484  
485 sub show_choice {
486 my ($self, $prefix, $options, $at, $notice) = @_;
487 my $game = $self->game;
488 my $step = $self->step_of($prefix);
489 my $side = $game->turn;
490 my %mark = map { $_ => 'option' } @{$options};
491 my @said;
492  
493 my $board = $game->board;
494 my ($from, $to) = $step eq 'from' ? ($at, undef)
495 : $step eq 'to' ? ($game->phase eq 'placing' ? undef : $prefix->[0], $at)
496 : ($game->phase eq 'placing' ? (undef, $prefix->[0]) : @{$prefix}[ 0, 1 ]);
497  
498 if (defined $to) {
499 $board->set($from, undef) if defined $from;
500 $board->set($to, $side);
501 $mark{$from} = 'left' if defined $from;
502 $mark{$to} = 'chosen';
503 }
504 if ($step eq 'to') {
505 my @takes = grep { defined $_->remove } @{ $self->matching([ @{$prefix}, $at ]) };
506 $mark{ $_->remove } = 'takeable' for @takes;
507 $mark{$at} = 'candidate';
508 push @said, $takes[0]->closes > 1 ? 'closes two mills' : 'closes a mill' if @takes;
509 push @said, 'a flight'
510 if defined $from && !Game::Merrills::Points::is_adjacent($from, $at);
511 }
512 elsif ($step eq 'remove') {
513 $mark{$_} = 'takeable' for @{$options};
514 $mark{$at} = 'candidate';
515 push @said, 'takes this man';
516 }
517 else {
518 $mark{$at} = 'candidate';
519 }
520  
521 $self->preview($board);
522 $self->highlight(\%mark);
523 $self->frames($self->frames + 1);
524  
525 my $name = Game::Merrills::Points::name($at);
526 my ($index) = grep { $options->[$_] == $at } 0 .. $#{$options};
527 my $ask = $step eq 'from' ? 'Choose a man to move.'
528 : $step eq 'to' && !defined $from ? 'Choose a point to place a man on.'
529 : $step eq 'to' ? sprintf('Move %s to where?', Game::Merrills::Points::name($from))
530 : defined $from ? sprintf('Move %s to %s and take which man?',
531 Game::Merrills::Points::name($from), Game::Merrills::Points::name($to))
532 : sprintf('Place on %s and take which man?', Game::Merrills::Points::name($to));
533 my $cursor = sprintf '> %s%s', $name, @said ? ', ' . join(', ', @said) : '';
534  
535 my @lines = (@{ $self->board_lines }, '', @{ $self->status_lines }, '',
536 $self->paint($ask, 'step'),
537 ' ' . $self->paint($cursor, 'cursor')
538 . $self->paint(sprintf(' %d of %d', $index + 1, scalar @{$options}), 'dim'));
539 push @lines, '', @{$notice} if $notice && @{$notice};
540 push @lines, '', $self->legend;
541 $self->frame(\@lines);
542 $self->screen->show(\@lines);
543 $self->redraw(0);
544 return $self;
545 }
546  
547 sub legend {
548 my ($self) = @_;
549 my @keys = (
550 [ 'arrows', 'move' ], [ 'tab', 'next' ], [ 'enter', 'choose' ],
551 [ 'backspace', 'back' ], [ 'h', 'hint' ], [ 'u', 'undo' ], [ 'r', 'redo' ], [ 't', 'type' ],
552 [ 'q', 'quit' ], [ '?', 'help' ],
553 );
554 return join $self->paint(' | ', 'dim'),
555 map { $self->paint($_->[0], 'key') . ' ' . $self->paint($_->[1], 'dim') } @keys;
556 }
557  
558 sub key_lines {
559 my ($self) = @_;
560 return [
561 'The arrow keys move to the nearest point that can be chosen that way.',
562 'Tab and shift-tab, or j and k, go round every one of them in turn.',
563 'A letter and a number, like d2, jump straight to that point.',
564 'Enter or space chooses. A move is chosen a step at a time: the man,',
565 'where it goes, and the man it takes if it closes a mill.',
566 'Backspace or escape goes back a step. h shows what the bot would play.',
567 'u takes a move back and r plays it again.',
568 't goes back to typing, q quits, : types a command.',
569 ];
570 }
571  
572 sub set_picking {
573 my ($self, $word) = @_;
574 if ($word eq 'type') {
575 $self->leave_raw;
576 $self->picking(0);
577 $self->redraw(1);
578 $self->say('Type your moves. The command pick brings the keys back.');
579 return 0;
580 }
581 return $self->say('This terminal cannot be read a key at a time.') && 0
582 unless $self->enter_raw;
583 $self->picking(1);
584 return 0;
585 }
586  
587 sub replay {
588 my ($self, $record) = @_;
589 my $moves = Game::Merrills::Notation::parse_record($record);
590 my $position = Game::Merrills::Notation::record_position($record);
591 my $game = Game::Merrills->new(
592 flying => $self->game->flying,
593 defined $position ? (position => $position) : ()
594 );
595 $self->game($game);
596 $self->history->start($game);
597 $self->log->recent([]);
598 $self->render;
599  
600 my $number = 0;
601 for my $move (@{$moves}) {
602 $number++;
603 if ($self->interactive) {
604 my $line = $self->read_line($self->paint('enter for the next move, q to stop: ', 'dim'));
605 last if !defined $line || $line =~ m/^\s*q/i;
606 }
607 my $played = $game->move($move);
608 die "illegal record: move $number, '"
609 . Game::Merrills::Notation::format_move($move) . "': " . $played->message . "\n"
610 if ref $played eq 'Game::Merrills::Error';
611 $self->played($played);
612 $self->render;
613 }
614 return $game->result;
615 }
616  
617 sub bot_for {
618 my ($self, $side) = @_;
619 my $bot = $self->bot;
620 return ref $bot eq 'HASH' ? $bot->{$side} : $bot;
621 }
622  
623 sub bot_plays {
624 my ($self, $side) = @_;
625 return 0 if $self->human eq 'both' || !$self->bot_for($side);
626 return 1 if $self->human eq 'none';
627 return $side eq $self->human ? 0 : 1;
628 }
629  
630 sub bot_move {
631 my ($self) = @_;
632 my $side = $self->game->turn;
633 my $out = $self->out;
634 print {$out} $self->paint(ucfirst($side) . ' is thinking', 'dim') if $self->interactive;
635 my $move = $self->bot_for($side)->choose($self->game);
636 print {$out} "\r\e[K" if $self->interactive;
637 return undef unless $move;
638 $self->played($self->game->move($move));
639 return $move;
640 }
641  
642 sub played {
643 my ($self, $move) = @_;
644 $self->log->record($self->narrate($move));
645 $self->redraw(1);
646 return $move;
647 }
648  
649 sub name_of {
650 my ($self, $side) = @_;
651 return $side eq $self->human ? 'You' : ucfirst $side;
652 }
653  
654 sub narrate {
655 my ($self, $move) = @_;
656 my $who = $self->name_of($move->side);
657 my $to = Game::Merrills::Points::name($move->to);
658 my $text = $move->is_placement
659 ? sprintf('%s placed a man on %s', $who, $to)
660 : sprintf('%s %s %s to %s', $who, $move->flew ? 'flew' : 'moved',
661 Game::Merrills::Points::name($move->from), $to);
662 if ($move->is_capture) {
663 my $victim = $OTHER{ $move->side };
664 $text .= sprintf ', closed %s and took %s man on %s',
665 $move->closes > 1 ? 'two mills' : 'a mill',
666 $victim eq $self->human ? 'your' : "the $victim",
667 Game::Merrills::Points::name($move->remove);
668 }
669 return $text . '.';
670 }
671  
672 sub read_line {
673 my ($self, $prompt) = @_;
674 $prompt = $self->paint($self->game->turn . '>', $self->ink_of($self->game->turn)) . ' '
675 unless defined $prompt;
676 if ($self->raw) {
677 my $typed = Game::Terminal::Kit::Line->new(
678 prompt => $prompt,
679 head => $self->frame || [],
680 );
681 my ($event, $text) = $typed->run($self->keyboard, $self->screen);
682 return $event eq 'chosen' ? $text : $event eq 'back' ? '' : undef;
683 }
684 my $out = $self->out;
685 print {$out} $prompt;
686 my $line = readline $self->in;
687 unless (defined $line) {
688 print {$out} "\n" unless $self->interactive;
689 return undef;
690 }
691 chomp $line;
692 print {$out} "$line\n" unless $self->interactive;
693 return $line;
694 }
695  
696 sub say {
697 my ($self, $line) = @_;
698 $self->screen->say($line);
699 $self->log->note($line);
700 return $self;
701 }
702  
703 sub clear {
704 my ($self) = @_;
705 $self->screen->clear;
706 return $self;
707 }
708  
709 sub paint {
710 my ($self, $text, @keys) = @_;
711 my @codes = grep { defined } map { $INK{$_} || $GROUND{$_} } @keys;
712 return $self->screen->paint($text, join ';', @codes);
713 }
714  
715 sub ink_of {
716 my ($self, $side) = @_;
717 return 'turn' if $self->human eq 'both' || $self->human eq 'none';
718 return $side eq $self->human ? 'you' : 'them';
719 }
720  
721 sub render {
722 my ($self) = @_;
723 $self->clear;
724 $self->say($_) for @{ $self->board_lines }, '', @{ $self->status_lines };
725 $self->redraw(0);
726 return $self;
727 }
728  
729 sub glyphs {
730 my ($self) = @_;
731 return $GLYPH{ $self->ascii ? 'ascii' : $self->colour ? 'painted' : 'wide' };
732 }
733  
734 sub marks {
735 my ($self) = @_;
736 my %mark;
737 if (my $last = $self->game->history->[-1]) {
738 $mark{ $last->from } = 'left' if defined $last->from;
739 $mark{ $last->remove } = 'taken' if defined $last->remove;
740 $mark{ $last->to } = 'last';
741 }
742 my $extra = $self->highlight;
743 $mark{$_} = $extra->{$_} for keys %{$extra};
744 return \%mark;
745 }
746  
747 sub canvas {
748 my ($self) = @_;
749 my @canvas = map { [ map { [ ' ', 'gap' ] } 1 .. WIDTH ] } 1 .. ROWS;
750 for my $mill (Game::Merrills::Points::mills()) {
751 for my $step (0, 1) {
752 my ($one, $two) = @{$mill}[ $step, $step + 1 ];
753 my ($row, $col) = (2 * Game::Merrills::Points::row_of($one),
754 1 + PITCH * Game::Merrills::Points::col_of($one));
755 my ($end_row, $end_col) = (2 * Game::Merrills::Points::row_of($two),
756 1 + PITCH * Game::Merrills::Points::col_of($two));
757 if ($row == $end_row) {
758 $canvas[$row][$_] = [ 'across', 'line' ] for $col + 1 .. $end_col - 1;
759 }
760 else {
761 $canvas[$_][$col] = [ 'down', 'line' ] for $row + 1 .. $end_row - 1;
762 }
763 }
764 }
765  
766 my $board = $self->preview || $self->game->board;
767 my $marks = $self->marks;
768 for my $point (Game::Merrills::Points::all_points()) {
769 my ($row, $col) = (2 * Game::Merrills::Points::row_of($point),
770 1 + PITCH * Game::Merrills::Points::col_of($point));
771 my $side = $board->side_at($point);
772 my $mark = $marks->{$point};
773 my $ground = $mark ? $mark : $side && $board->in_mill($point) ? 'mill' : undef;
774 $canvas[$row][$col] = [
775 $side ? $side : $mark && $mark eq 'taken' ? 'taken' : 'empty',
776 $side ? $side : $mark && $mark eq 'taken' ? 'taken' : 'empty',
777 $ground,
778 ];
779 next unless $mark && $BRACKET{$mark};
780 $canvas[$row][ $col - 1 ] = [ $BRACKET{$mark}[0], 'bracket', $mark ];
781 $canvas[$row][ $col + 1 ] = [ $BRACKET{$mark}[1], 'bracket', $mark ];
782 }
783 return \@canvas;
784 }
785  
786 sub board_lines {
787 my ($self) = @_;
788 my $glyph = $self->glyphs;
789 my $canvas = $self->canvas;
790 my @aside = @{ $self->aside };
791 my @lines;
792 for my $row (0 .. ROWS - 1) {
793 my $drawn = WIDTH;
794 my $label = $row % 2 ? ' ' : 7 - ($row / 2);
795 my $line = ($row % 2 ? ' ' : $self->paint($label, 'label')) . ' ';
796 if ($self->colour) {
797 my $code = '';
798 for my $cell (@{ $canvas->[$row] }) {
799 my ($what, $kind, $ground) = @{$cell};
800 my $want = join ';', $INK{$kind} || $INK{line}, $GROUND{ $ground || 'board' };
801 $line .= "\e[${want}m" unless $want eq $code;
802 $code = $want;
803 $line .= defined $glyph->{$what} ? $glyph->{$what} : $what;
804 }
805 $line .= "\e[0m";
806 }
807 else {
808 my $text = join '', map { defined $glyph->{ $_->[0] } ? $glyph->{ $_->[0] } : $_->[0] }
809 @{ $canvas->[$row] };
810 $text =~ s/ +$//;
811 $drawn = length $text;
812 $line .= $text;
813 }
814 my $note = $aside[$row];
815 if (defined $note && length $note) {
816 $line .= ' ' x (2 + WIDTH - $drawn);
817 $line .= $note;
818 }
819 $line =~ s/ +$//;
820 push @lines, $line;
821 }
822 push @lines, ' ' . join ' ', map { $self->paint($_, 'label') } 'a' .. 'g';
823 return \@lines;
824 }
825  
826 sub aside {
827 my ($self) = @_;
828 my $game = $self->game;
829 my $glyph = $self->glyphs;
830 my @aside;
831 my $row = 2;
832 for my $side (qw/white black/) {
833 my $man = $self->paint($glyph->{$side}, $side, 'board');
834 my $name = $self->paint(sprintf('%-5s', ucfirst $side), $self->ink_of($side));
835 $name .= $self->paint(' (you)', 'dim') if $side eq $self->human;
836 $aside[$row] = $name;
837 $aside[ $row + 1 ] = sprintf 'in hand %d on the board %d lost %d',
838 $game->in_hand($side), $game->on_board($side),
839 Game::Merrills::Board::MEN - $game->men($side);
840 my $hand = $game->in_hand($side);
841 $aside[ $row + 2 ] = $hand
842 ? join ' ', ($self->colour ? $man : $glyph->{$side}) x $hand
843 : '';
844 $row += 4;
845 }
846 return \@aside;
847 }
848  
849 sub mills_of {
850 my ($self, $side) = @_;
851 my $board = $self->game->board;
852 my @mills;
853 for my $mill (Game::Merrills::Points::mills()) {
854 next if grep { ($board->side_at($_) || '') ne $side } @{$mill};
855 push @mills, join '-', map { Game::Merrills::Points::name($_) } @{$mill};
856 }
857 return \@mills;
858 }
859  
860 sub status_lines {
861 my ($self) = @_;
862 my $game = $self->game;
863 my @lines = map { $self->paint($_, 'said') } @{ $self->recent };
864  
865 for my $side (qw/white black/) {
866 my $mills = $self->mills_of($side);
867 next unless @{$mills};
868 push @lines, $self->paint(
869 sprintf('%s %s: %s', ucfirst $side, @{$mills} == 1 ? 'mill' : 'mills',
870 join ', ', @{$mills}),
871 'mill'
872 );
873 }
874  
875 if (my $result = $game->result) {
876 push @lines, $self->paint($result->stringify,
877 $result->is_draw ? 'mill'
878 : $result->winner eq $self->human ? 'good'
879 : $self->human =~ m/^(?:white|black)$/ ? 'warn' : 'good');
880 return \@lines;
881 }
882  
883 my $turn = $game->turn;
884 my $who = ucfirst($turn) . ($turn eq $self->human ? ' (you)' : '');
885 my $phase = $game->phase;
886 push @lines, $self->paint(
887 $phase eq 'placing' ? sprintf('%s to place, %d in hand.', $who, $game->in_hand($turn))
888 : $phase eq 'flying' ? sprintf('%s to move, and flying.', $who)
889 : sprintf('%s to move.', $who),
890 $self->ink_of($turn)
891 );
892  
893 my $limit = $Game::Merrills::NO_MILL_LIMIT;
894 push @lines, $self->paint(
895 sprintf('No mill for %d moves: it is a draw at %d.', $game->no_mill, $limit), 'warn'
896 ) if $limit && $game->no_mill * 2 >= $limit;
897  
898 push @lines, $self->paint(
899 sprintf('%s has offered a draw: accept or decline.', ucfirst $game->draw_offered_by), 'hint'
900 ) if $game->draw_offered_by;
901  
902 return \@lines;
903 }
904  
905 sub command {
906 my ($self, $line) = @_;
907 $line =~ s/^\s+|\s+$//g;
908 return 0 unless length $line;
909  
910 my ($word, $argument) = split ' ', $line, 2;
911 $word = lc $word;
912  
913 return $self->show_help if $word eq 'help' || $word eq '?';
914 return $self->redraw(1) && 0 if $word eq 'board';
915 return $self->show_moves if $word eq 'moves';
916 return $self->set_picking($word) if $word eq 'pick' || $word eq 'type';
917 return $self->show_hint if $word eq 'hint';
918 return $self->say($self->game->to_position) && 0 if $word eq 'position';
919 return $self->take_back if $word eq 'undo';
920 return $self->play_again if $word eq 'redo';
921 return $self->save($argument) if $word eq 'save';
922 return $self->load($argument) if $word eq 'load';
923 return $self->set_level($argument) if $word eq 'level';
924 return $self->toggle($word) if $word eq 'ascii' || $word eq 'colour' || $word eq 'color';
925 return $self->offer_draw if $word eq 'draw';
926 return $self->answer_draw($word) if $word eq 'accept' || $word eq 'decline';
927 return $self->resign if $word eq 'resign';
928 return $self->quit if $word eq 'quit';
929  
930 return $self->play_number($word) if $word =~ m/^[0-9]+$/;
931 return $self->play($line);
932 }
933  
934 sub play {
935 my ($self, $notation) = @_;
936 my $move = $self->game->move($notation);
937 unless (ref $move eq 'Game::Merrills::Error') {
938 $self->played($move);
939 return 0;
940 }
941  
942 $self->say($self->paint(ucfirst($move->message) . '.', 'warn'));
943 $self->say('Type moves for the list, or help for the commands.')
944 if $move->not_a_move;
945 my @legal = @{ $move->legal };
946 $self->say('You could play: ' . join(', ', map { $_->notation } @legal[ 0 .. ($#legal > 11 ? 11 : $#legal) ])
947 . (@legal > 12 ? sprintf(', and %d more', @legal - 12) : '') . '.')
948 if @legal && !$move->not_a_move && !$move->game_over;
949 return 0;
950 }
951  
952 sub play_number {
953 my ($self, $number) = @_;
954 my $legal = $self->game->legal_moves;
955 return $self->say("There is no move $number. Type moves for the list.") && 0
956 unless $number >= 1 && $number <= @{$legal};
957 $self->played($self->game->move($legal->[ $number - 1 ]));
958 return 0;
959 }
960  
961 sub show_moves {
962 my ($self) = @_;
963 my $legal = $self->game->legal_moves;
964 return $self->say('There is nothing to play.') && 0 unless @{$legal};
965 my @cells = map { sprintf '%2d. %-9s', $_ + 1, $legal->[$_]->notation } 0 .. $#{$legal};
966 while (my @row = splice @cells, 0, 5) {
967 my $text = join ' ', @row;
968 $text =~ s/ +$//;
969 $self->say($text);
970 }
971 $self->say('Play one by its number, or type it out.');
972 return 0;
973 }
974  
975 sub hint {
976 my ($self) = @_;
977 my $bot = $self->bot_for($OTHER{ $self->game->turn })
978 || $self->bot_for($self->game->turn)
979 || Game::Merrills::Bot->new;
980 my $move = $bot->choose($self->game);
981 return { line => 'There is nothing to play.' } unless $move;
982 my $score = $bot->last_search->{score};
983 return {
984 move => $move,
985 line => sprintf('Try %s%s.', $move->notation,
986 defined $score ? sprintf(' (it scores that %+.2f)', $score / 100) : '')
987 };
988 }
989  
990 sub show_hint {
991 my ($self) = @_;
992 $self->say($self->paint($self->hint->{line}, 'hint'));
993 return 0;
994 }
995  
996 sub take_back {
997 my ($self) = @_;
998 my $game = $self->history->undo;
999 return $self->say('There is nothing to take back.') && 0 unless $game;
1000 $self->swap($game);
1001 $self->later('Taken back.');
1002 return 0;
1003 }
1004  
1005 sub play_again {
1006 my ($self) = @_;
1007 my $game = $self->history->redo;
1008 return $self->say('There is nothing to play again.') && 0 unless $game;
1009 $self->swap($game);
1010 $self->later('Played again.');
1011 return 0;
1012 }
1013  
1014 sub swap {
1015 my ($self, $game) = @_;
1016 $self->game($game);
1017 $self->done_picking;
1018 $self->log->recent([]);
1019 my $bot = $self->bot;
1020 $_->last_search(undef) for grep { $_ } ref $bot eq 'HASH' ? values %{$bot} : ($bot);
1021 $self->redraw(1);
1022 return $self;
1023 }
1024  
1025 sub later {
1026 my ($self, $line) = @_;
1027 if ($self->picking && $self->raw) {
1028 $self->redraw(1);
1029 }
1030 else {
1031 $self->render;
1032 }
1033 $self->say($line);
1034 return $self;
1035 }
1036  
1037 sub save {
1038 my ($self, $file) = @_;
1039 return $self->say('Save needs a file name.') && 0 unless $file;
1040 open my $handle, '>', $file
1041 or return $self->say("Cannot write $file: $!") && 0;
1042 print {$handle} $self->game->to_text;
1043 close $handle;
1044 $self->say("Saved to $file.");
1045 return 0;
1046 }
1047  
1048 sub load {
1049 my ($self, $file) = @_;
1050 return $self->say('Load needs a file name.') && 0 unless $file;
1051 open my $handle, '<', $file
1052 or return $self->say("Cannot read $file: $!") && 0;
1053 my $text = do { local $/; <$handle> };
1054 close $handle;
1055 my $game = eval { Game::Merrills->from_text($text, flying => $self->game->flying) };
1056 unless ($game) {
1057 my $why = $@;
1058 $why =~ s/\s+$//;
1059 return $self->say("That is not a game I can read: $why") && 0;
1060 }
1061 $self->swap($game);
1062 $self->history->start($game);
1063 $self->later("Loaded $file, " . scalar(@{ $game->history }) . ' moves in.');
1064 return 0;
1065 }
1066  
1067 sub set_level {
1068 my ($self, $level) = @_;
1069 return $self->say('Level takes a number from 1 to 5.') && 0
1070 unless defined $level && $level =~ m/^[1-5]$/;
1071 my $bot = $self->bot;
1072 if (ref $bot eq 'HASH') {
1073 $bot->{$_} = Game::Merrills::Bot->new(level => $level, seed => $bot->{$_}->seed)
1074 for grep { $bot->{$_} } keys %{$bot};
1075 }
1076 else {
1077 $self->bot(Game::Merrills::Bot->new(level => $level, seed => $bot ? $bot->seed : 0));
1078 }
1079 $self->say("The bot is at level $level.");
1080 return 0;
1081 }
1082  
1083 sub toggle {
1084 my ($self, $what) = @_;
1085 $what = 'colour' if $what eq 'color';
1086 $self->$what($self->$what ? 0 : 1);
1087 $self->layer;
1088 $self->redraw(1);
1089 return 0;
1090 }
1091  
1092 sub offer_draw {
1093 my ($self) = @_;
1094 my $game = $self->game;
1095 my $side = $self->human =~ m/^(?:white|black)$/ ? $self->human : $game->turn;
1096 my $offered = $game->offer_draw($side);
1097 return $self->say(ucfirst($offered->message) . '.') && 0
1098 if ref $offered eq 'Game::Merrills::Error';
1099 my $bot = $self->bot_plays($OTHER{$side}) ? $self->bot_for($OTHER{$side}) : undef;
1100 unless ($bot) {
1101 $self->say(ucfirst($side) . ' offers a draw. ' . ucfirst($OTHER{$side})
1102 . ' may accept or decline.');
1103 return 0;
1104 }
1105  
1106 my $score = $bot->last_search ? $bot->last_search->{score} : undef;
1107 if (defined $score && $score <= 30) {
1108 $game->accept_draw($OTHER{$side});
1109 $self->say('The bot takes the draw.');
1110 $self->redraw(1);
1111 }
1112 else {
1113 $game->decline_draw($OTHER{$side});
1114 $self->say('The bot plays on.');
1115 }
1116 return 0;
1117 }
1118  
1119 sub answer_draw {
1120 my ($self, $word) = @_;
1121 my $game = $self->game;
1122 my $offered = $game->draw_offered_by;
1123 my $side = $offered ? $OTHER{$offered} : $game->turn;
1124 my $answer = $word eq 'accept' ? $game->accept_draw($side) : $game->decline_draw($side);
1125 return $self->say(ucfirst($answer->message) . '.') && 0
1126 if ref $answer eq 'Game::Merrills::Error';
1127 return $self->redraw(1) && 0 if $word eq 'accept';
1128 $self->say(ucfirst($side) . ' plays on.');
1129 return 0;
1130 }
1131  
1132 sub resign {
1133 my ($self) = @_;
1134 my $game = $self->game;
1135 my $resigned = $game->resign($self->human =~ m/^(?:white|black)$/ ? $self->human : $game->turn);
1136 return $self->say(ucfirst($resigned->message) . '.') && 0
1137 if ref $resigned eq 'Game::Merrills::Error';
1138 $self->redraw(1);
1139 return 0;
1140 }
1141  
1142 sub quit {
1143 my ($self) = @_;
1144 return 1 unless $self->game->status eq 'active' && @{ $self->game->history };
1145 my $answer = $self->read_line('Really quit, with the game unfinished? (y/n) ');
1146 return 1 if !defined $answer || $answer =~ m/^\s*y/i;
1147 return 0;
1148 }
1149  
1150 sub help_lines {
1151 my ($self) = @_;
1152 return [
1153 'A move is its points: d2 to place a man, d2-d3 to move one.',
1154 'One that closes a mill says which man it takes: d2-d3xa1.',
1155 map { sprintf ' %-10s %s', $_, $COMMAND{$_} }
1156 sort { length $a <=> length $b || $a cmp $b } keys %COMMAND
1157 ];
1158 }
1159  
1160 sub show_help {
1161 my ($self) = @_;
1162 $self->say($_) for @{ $self->help_lines };
1163 return 0;
1164 }
1165  
1166 sub _usage {
1167 my @levels = Game::Merrills::Bot->levels;
1168 my $levels = "$levels[0] to $levels[-1]";
1169 my $limit = Game::Merrills::NO_MILL_PLIES;
1170  
1171 return <<"USAGE";
1172 merrills - play Nine Men's Morris
1173  
1174 Usage: merrills [options]
1175  
1176 -l, --level N the bot's strength, $levels (default 3)
1177 -s, --side SIDE the side you play: white, black or random (default white)
1178 --hotseat two people at one keyboard, and no bot
1179 --bot-vs-bot watch two bots; give --level twice for white and black
1180 --position STR begin from a position, as the position command prints it
1181 --load FILE carry on a game that the save command wrote
1182 --replay FILE show such a game a move at a time
1183 --seed N makes a game repeatable: the same seed, the same game
1184 --no-flying a side down to three men still moves along the lines
1185 -a, --ascii letters and dashes, for a terminal without the glyphs
1186 --colour paint the board even off a terminal; --no-colour never
1187 --no-pick type the moves out instead of choosing them with the keys
1188 -v, --version print the version
1189 -h, --help this
1190  
1191 White moves first. Place your nine men in turn, then move them along the
1192 lines. Three in a row is a mill and takes a man: one in a mill is safe while
1193 any stands outside one. Down to three men, you fly. Two men, or no move, and
1194 you have lost. A position three times, or $limit moves without a mill, is a
1195 draw.
1196  
1197 On a terminal a move is chosen with the arrow keys, a step at a time: the
1198 man, where it goes, the man it takes. The board is drawn as the move would
1199 leave it, so a mill is seen before it is closed. Needs Term::ReadKey; without
1200 it, or off a terminal, moves are typed: d2 to place, d2-d3 to move, d2-d3xa1
1201 to take. Type help in the game for the commands.
1202  
1203 The board marks what the last move did with shapes, so they survive
1204 --no-colour and a file: (W) the man that moved, (.) where it came from, (x)
1205 where a man was taken.
1206  
1207 Levels $levels[-2] and $levels[-1] look a good deal further and take noticeably longer a move.
1208 A level's effort is counted in positions and never in seconds, so a busy
1209 machine plays the same game as an idle one.
1210  
1211 Exit status is 0 if you won or drew, 1 if you lost, 2 for a bad option.
1212 USAGE
1213 }
1214  
1215 sub _reason {
1216 my ($why) = @_;
1217 $why = 'could not start' unless defined $why && length $why;
1218 $why =~ s/ at \S+ line \d+\.?\s*\z//;
1219 $why =~ s/\s+\z//;
1220 return $why;
1221 }
1222  
1223 sub _bad {
1224 my ($why) = @_;
1225 print STDERR "merrills: $why\n\n", _usage();
1226 return 2;
1227 }
1228  
1229 sub options {
1230 return [
1231 { name => 'level', type => 'int', min => 1, max => 5, help => "the bot's strength" },
1232 { name => 'side', type => 'enum', choices => [qw(white black random)], help => 'your side' },
1233 { name => 'hotseat', type => 'flag', help => 'two people at one keyboard, no bot' },
1234 { name => 'bot-vs-bot', type => 'flag', help => 'watch two bots' },
1235 { name => 'flying', type => 'bool', help => 'a side down to three men may fly' },
1236 { name => 'seed', type => 'str', help => 'the same seed, the same game' },
1237 ];
1238 }
1239  
1240 sub run {
1241 my ($class, @argv) = @_;
1242 my $saved = Getopt::Long::Configure(qw(no_ignore_case));
1243 my $status = $class->_run(\@argv);
1244 Getopt::Long::Configure($saved);
1245 return $status;
1246 }
1247  
1248 sub _run {
1249 my ($class, $argv) = @_;
1250 my %opt = (
1251 level => [],
1252 side => 'white',
1253 flying => 1,
1254 ascii => 0,
1255 );
1256  
1257 Getopt::Long::GetOptionsFromArray($argv, \%opt,
1258 'level|l=s@',
1259 'side|s=s',
1260 'hotseat',
1261 'bot-vs-bot',
1262 'position=s',
1263 'load=s',
1264 'replay=s',
1265 'seed=s',
1266 'flying!',
1267 'ascii|a',
1268 'colour|color!',
1269 'pick!',
1270 'version|v',
1271 'help|h',
1272 ) or do { print STDERR _usage(); return 2 };
1273  
1274 if ($opt{help}) { print _usage(); return 0 }
1275  
1276 if ($opt{version}) {
1277 print "merrills $Game::Merrills::VERSION\n";
1278 return 0;
1279 }
1280  
1281 return _bad("there is nothing to do with '$argv->[0]': options begin with --") if @{$argv};
1282  
1283 my @levels = Game::Merrills::Bot->levels;
1284 my %is_level = map { $_ => 1 } @levels;
1285 my @level = @{ $opt{level} };
1286 for my $level (@level) {
1287 return _bad("--level takes a number from $levels[0] to $levels[-1], not '$level'")
1288 unless $is_level{$level};
1289 }
1290 return _bad('--level can be given twice at most, once a side') if @level > 2;
1291 return _bad('--level twice is for --bot-vs-bot, where each side has a bot')
1292 if @level == 2 && !$opt{'bot-vs-bot'};
1293 return _bad('--hotseat is two people and --bot-vs-bot is none: choose one')
1294 if $opt{hotseat} && $opt{'bot-vs-bot'};
1295 return _bad('--hotseat has no bot for --level to set') if $opt{hotseat} && @level;
1296 return _bad("--side is white, black or random, not '$opt{side}'")
1297 unless $opt{side} =~ m/^(?:white|black|random)$/;
1298 return _bad("--seed takes a whole number, not '$opt{seed}'")
1299 if defined $opt{seed} && $opt{seed} !~ m/^[0-9]+$/;
1300  
1301 my @sources = grep { defined $opt{$_} } qw/position load replay/;
1302 return _bad('--' . join(' and --', @sources) . ' each say where the game begins: give one')
1303 if @sources > 1;
1304  
1305 my $seed = defined $opt{seed} ? $opt{seed} : (time ^ $$) % 1_000_000;
1306 my $side = $opt{side} eq 'random' ? ($seed % 2 ? 'black' : 'white') : $opt{side};
1307 @level = (3) unless @level;
1308 @level = (@level, @level) if @level == 1;
1309  
1310 my ($game, $record);
1311 if (defined $opt{position}) {
1312 $game = eval { Game::Merrills->new(position => $opt{position}, flying => $opt{flying}) }
1313 or return _bad('--position: ' . _reason($@));
1314 }
1315 elsif (defined(my $file = defined $opt{load} ? $opt{load} : $opt{replay})) {
1316 open my $handle, '<', $file or return _bad("cannot read $file: $!");
1317 $record = do { local $/; <$handle> };
1318 close $handle;
1319 $game = eval { Game::Merrills->from_text($record, flying => $opt{flying}) }
1320 or return _bad("$file is not a game that plays: " . _reason($@));
1321 }
1322 else {
1323 $game = Game::Merrills->new(flying => $opt{flying});
1324 }
1325  
1326 my ($human, $bot, $who);
1327 if (defined $opt{replay}) {
1328 $human = 'both';
1329 }
1330 elsif ($opt{hotseat}) {
1331 $human = 'both';
1332 $who = 'White and Black: two people at one keyboard.';
1333 }
1334 elsif ($opt{'bot-vs-bot'}) {
1335 $human = 'none';
1336 $bot = {
1337 white => Game::Merrills::Bot->new(level => $level[0], seed => $seed),
1338 black => Game::Merrills::Bot->new(level => $level[1], seed => $seed + 1),
1339 };
1340 $who = "White: the bot at level $level[0]. Black: the bot at level $level[1].";
1341 }
1342 else {
1343 $human = $side;
1344 $bot = Game::Merrills::Bot->new(level => $level[0], seed => $seed);
1345 $who = sprintf '%s: you. %s: the bot at level %d.',
1346 ucfirst $side, $side eq 'white' ? 'Black' : 'White', $level[0];
1347 }
1348 $who .= ' No flying.' if defined $who && !$opt{flying};
1349  
1350 my $terminal = $class->new(
1351 game => $game,
1352 human => $human,
1353 ascii => $opt{ascii} ? 1 : 0,
1354 (defined $bot ? (bot => $bot) : ()),
1355 (exists $opt{colour} ? (colour => $opt{colour} ? 1 : 0) : ()),
1356 (exists $opt{pick} ? (picking => $opt{pick} ? 1 : 0) : ()),
1357 );
1358  
1359 my $result = Game::Terminal::Kit::Run::guard(sub {
1360 return $terminal->replay($record) if defined $opt{replay};
1361 $terminal->say($who);
1362 return $terminal->start;
1363 }, $terminal->keyboard, $terminal->screen);
1364  
1365 return 0 unless $result;
1366 return 0 if $result->is_draw || $human eq 'both' || $human eq 'none' || defined $opt{replay};
1367 return $result->winner eq $human ? 0 : 1;
1368 }
1369  
1370 1;
1371  
1372 __END__