blib/lib/Game/Brandubh/Terminal.pm

filter: Statementstmt 91.3% 21 / 23 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 93.5% 29 / 31 CC 1 SCAR 0.4
CC
1
Cov
91%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/Game/Brandubh/Rules.pm ↑ Summary Brandubh.xs »
1 package Game::Brandubh::Terminal;
2  
3 37 ▶use 5.014;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 37 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 37 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 37 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 37 ▶use Digest::SHA ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 37 ▶use Getopt::Long ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 37 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 0 ▶use Object::Proto::Sugar;
Subroutine BEGIN: called CC=1 SCAR=2.6
12 use Game::Terminal::Kit::Choose;
13 use Game::Terminal::Kit::History;
14 use Game::Terminal::Kit::Keys;
15 use Game::Terminal::Kit::Line;
16 use Game::Terminal::Kit::Log;
17 use Game::Terminal::Kit::Run;
18 use Game::Terminal::Kit::Screen;
19 use Game::Terminal::Kit::Steer;
20  
21 use Game::Brandubh;
22 use Game::Brandubh::Bot;
23 use Game::Brandubh::Notation qw(square_name square_parse);
24  
25 our $VERSION = '0.03';
26  
27 our (@COMMANDS, %DIRECTION, %KEY, %GROUND, %INK, %GLYPH, %ENDING);
28  
29 BEGIN {
30 @COMMANDS = (
31 [ 'd1d3' => 'play a move: the square a piece leaves, then where it goes' ],
32 [ 'moves' => 'every legal move, and what each would capture' ],
33 [ 'hint' => 'what the program would play here' ],
34 [ 'undo' => 'take back your last move, and the reply to it' ],
35 [ 'redo' => 'play again what undo took back' ],
36 [ 'board' => 'draw the board again' ],
37 [ 'pick' => 'choose moves on the board with the arrow keys' ],
38 [ 'type' => 'go back to typing moves' ],
39 [ 'level N' => 'how hard the program plays, 1 to 3' ],
40 [ 'side WHO' => 'attackers, defenders, both or none: which side is yours' ],
41 [ 'new' => 'start another game' ],
42 [ 'save FILE' => 'write the game to a file' ],
43 [ 'load FILE' => 'read a game back from a file' ],
44 [ 'draw' => 'offer a draw' ],
45 [ 'resign' => 'give the game up' ],
46 [ 'rules' => 'the rules of the game' ],
47 [ 'colour' => 'turn colour on or off' ],
48 [ 'help' => 'this list' ],
49 [ 'quit' => 'stop playing' ],
50 );
51  
52 %DIRECTION = (
53 up => [ 0, 1 ], down => [ 0, -1 ], left => [ -1, 0 ], right => [ 1, 0 ],
54 );
55  
56 %KEY = (
57 u => 'undo',
58 r => 'redo',
59 R => 'rules',
60 n => 'new',
61 q => 'quit',
62 c => 'colour',
63 );
64  
65 %GROUND = (
66 light => '48;5;180',
67 dark => '48;5;137',
68 throne => '48;5;94',
69 corner => '48;5;58',
70 cursor => '48;5;33',
71 from => '48;5;240',
72 to => '48;5;34',
73 reach => '48;5;108',
74 taken => '48;5;160',
75 trail => '48;5;222',
76 );
77  
78 %INK = (
79 attacker => '1;38;5;16',
80 defender => '1;38;5;231',
81 king => '1;38;5;165',
82 mark => '38;5;236',
83 reach => '1;38;5;22',
84 taken => '1;38;5;231',
85 title => '1;38;5;220',
86 good => '1;38;5;34',
87 bad => '1;38;5;160',
88 quiet => '38;5;245',
89 key => '1;38;5;33',
90 warn => '1;38;5;208',
91 );
92  
93 %GLYPH = (
94 wide => { attacker => "\x{25B2}", defender => "\x{25CF}", king => "\x{265A}",
95 throne => "\x{2726}", corner => "\x{25C8}", reach => "\x{2022}", taken => "\x{2715}", from => "\x{25E6}" },
96 ascii => { attacker => 'A', defender => 'D', king => 'K',
97 throne => '#', corner => 'X', reach => '.', taken => 'x', from => '_' },
98 );
99  
100 %ENDING = (
101 corner => 'The king has reached a corner. The defenders win.',
102 edge => 'The king has reached the edge. The defenders win.',
103 capture => 'The king is captured. The attackers win.',
104 no_pieces => 'The attackers have no piece left. The defenders win.',
105 repetition => 'The same position has come round once too often. The game is drawn.',
106 no_move => 'The side to move cannot move. The game is drawn.',
107 ply_cap => 'The game has run its full length with no end. It is drawn.',
108 agreed => 'A draw, by agreement.',
109 );
110 }
111  
112 has game => (is => 'rw');
113  
114 has [qw/in out/] => (is => 'rw');
115  
116 has [qw/interactive colour unicode picking/] => (is => 'rw');
117  
118 has human => (is => 'rw', default => 'attackers');
119  
120 has level => (is => 'rw', default => 2);
121  
122 has seed => (is => 'rw');
123  
124 has variant => (is => 'rw');
125  
126 has keysource => (is => 'rw');
127  
128 has pending => (is => 'rw', default => []);
129  
130 has [qw/_keyboard _screen _log _frame/] => (is => 'rw');
131  
132 has focus => (is => 'rw');
133  
134 has chosen => (is => 'rw');
135  
136 has redraw => (is => 'rw', default => 1);
137  
138 has pause => (is => 'rw');
139  
140 has menu => (is => 'rw');
141  
142 has history => (is => 'rw');
143  
144 sub BUILD {
145 my ($self) = @_;
146 $self->in(\*STDIN) unless $self->in;
147 $self->out(\*STDOUT) unless $self->out;
148 $self->interactive(-t $self->in ? 1 : 0) unless defined $self->interactive;
149 $self->colour($self->interactive && !Game::Terminal::Kit::Screen::no_colour() ? 1 : 0) unless defined $self->colour;
150 $self->unicode($self->colour ? 1 : 0) unless defined $self->unicode;
151 $self->_keyboard(Game::Terminal::Kit::Keys->new(
152 in => $self->in,
153 pending => $self->pending,
154 ($self->keysource ? (keysource => $self->keysource) : ()),
155 ));
156 $self->_screen(Game::Terminal::Kit::Screen->new(
157 out => $self->out,
158 interactive => $self->interactive,
159 colour => $self->colour,
160 ascii => $self->unicode ? 0 : 1,
161 ));
162 $self->_log(Game::Terminal::Kit::Log->new(keep => 8));
163 $self->picking($self->interactive ? 1 : 0) unless defined $self->picking;
164 $self->picking(0) unless $self->keys_available;
165 $self->pause($self->interactive && !$self->keysource ? 1 : 0) unless defined $self->pause;
166 $self->menu(0) unless defined $self->menu;
167  
168 Carp::croak("Game::Brandubh::Terminal: side is attackers, defenders, both or none, not '" . $self->human . "'")
169 unless $self->human =~ /\A(?:attackers|defenders|both|none)\z/;
170 Carp::croak('Game::Brandubh::Terminal: level is 1, 2 or 3')
171 unless $self->level =~ /\A[123]\z/;
172  
173 $self->seed(Digest::SHA::sha256(join '|', 'brandubh', $$, time, rand)) unless defined $self->seed;
174 $self->game($self->fresh_game) unless $self->game;
175  
176 my $terminal = $self;
177 Scalar::Util::weaken($terminal);
178 $self->history(Game::Terminal::Kit::History->new(
179 save => sub { $_[0]->as_text },
180 load => sub { scalar Game::Brandubh->from_text($_[0], seed => $terminal->seed) },
181 )) unless $self->history;
182 $self->history->start($self->game);
183  
184 $self->_screen->utf8->flush_on;
185 return;
186 }
187  
188 sub fresh_game {
189 my ($self) = @_;
190 return Game::Brandubh->new(
191 seed => $self->seed,
192 (defined $self->variant ? (variant => $self->variant) : ()),
193 );
194 }
195  
196 sub budget { (Game::Brandubh::Bot->levels)[ $_[0]->level - 1 ] }
197  
198 sub start {
199 my ($self) = @_;
200 $self->picking(0) if $self->picking && !$self->enter_raw;
201 $self->history->start($self->game);
202  
203 $self->remark($self->paint('Brandubh.', 'title') . ' Type help for the commands.') unless $self->raw;
204 Game::Terminal::Kit::Run::guard(
205 sub { $self->turns if !$self->menu || !$self->raw || $self->ask_how_to_play },
206 $self->_keyboard, $self->_screen,
207 );
208 return 0;
209 }
210  
211 sub turns {
212 my ($self) = @_;
213 while (1) {
214 my $picking = $self->picking && $self->raw;
215 my $game = $self->game;
216  
217 if ($game->status eq 'finished') {
218 $self->person_turn unless $self->human eq 'none';
219 my $line = $picking ? $self->pick_ended : $self->read_ended;
220 last unless defined $line;
221 last if $self->command($line);
222 next;
223 }
224 if ($self->bot_plays($game->side_to_move)) {
225 $self->bot_move;
226 next;
227 }
228  
229 $self->person_turn;
230 $self->render if $self->redraw && !$picking;
231 my $line = $picking ? $self->pick : $self->read_line;
232 unless (defined $line) {
233 $self->say('Bye.');
234 last;
235 }
236 last if $self->command($line);
237 }
238 return $self;
239 }
240  
241 sub person_turn {
242 my ($self) = @_;
243 $self->history->turn($self->game);
244 return $self;
245 }
246  
247 sub read_ended {
248 my ($self) = @_;
249 $self->render if $self->redraw;
250 return $self->read_line('new, undo or quit> ');
251 }
252  
253 sub pick_ended {
254 my ($self) = @_;
255 $self->focus(undef);
256 $self->chosen(undef);
257 while (1) {
258 $self->show('ended');
259 my $key = $self->read_key;
260 return undef if !defined $key || $key eq 'eof' || $key eq 'interrupt';
261 return 'new' if $key eq 'n' || $key eq 'enter';
262 return 'undo' if $key eq 'u';
263 return 'redo' if $key eq 'r';
264 return 'quit' if $key eq 'q' || $key eq 'escape';
265 return 'rules' if $key eq 'R';
266 return $self->read_line(': ') if $key eq ':';
267 }
268 }
269  
270 sub bot_plays {
271 my ($self, $side) = @_;
272 return 0 if $self->human eq 'both';
273 return 1 if $self->human eq 'none';
274 return $side eq $self->human ? 0 : 1;
275 }
276  
277 sub bot_move {
278 my ($self) = @_;
279 my $game = $self->game;
280 my $side = $game->side_to_move;
281 if ($self->raw) {
282 $self->show('thinking');
283 }
284 my $thought = Game::Brandubh::Bot->think($game, seed => $self->seed, level => $self->budget);
285 return undef unless $thought;
286 $game->play_or_die($thought->{move});
287  
288 my $shown = $game->shown->[-1];
289 my $line = sprintf 'The %s played %s', $side, $self->paint($shown, 'key');
290 my ($taken) = $shown =~ /x([a-g1-7,]+)/;
291 $line .= ', taking ' . join(' and ', split /,/, $taken) if defined $taken;
292 $line .= $thought->{slipped} ? ' (without much thought).' : '.';
293 $self->remark($line) if $self->human eq 'none';
294 $self->_log->forget->record($line) unless $self->human eq 'none';
295 $self->redraw(1);
296 if ($self->human eq 'none') {
297 $self->render;
298 select undef, undef, undef, 0.4 if $self->pause;
299 }
300 return $thought->{move};
301 }
302  
303 sub raw {
304 my ($self) = @_;
305 return $self->_keyboard->raw;
306 }
307  
308 sub notice {
309 my ($self) = @_;
310 return [ $self->_log->lines ];
311 }
312  
313 sub keys_available {
314 my ($self) = @_;
315 return $self->_keyboard->keys_available;
316 }
317  
318 sub enter_raw {
319 my ($self) = @_;
320 return $self if $self->raw;
321 return undef unless $self->_keyboard->enter_raw;
322 $self->_screen->hide_cursor unless $self->keysource;
323 return $self;
324 }
325  
326 sub leave_raw {
327 my ($self) = @_;
328 $self->_keyboard->leave_raw;
329 $self->_screen->restore;
330 return $self;
331 }
332  
333 sub read_key {
334 my ($self) = @_;
335 return $self->_keyboard->read_key;
336 }
337  
338 sub coordinates {
339 my ($name) = @_;
340 my ($file, $rank) = square_parse($name);
341 return ($file, $rank);
342 }
343  
344 sub steer {
345 my ($self, $from, $key, $among) = @_;
346 my $way = $DIRECTION{$key} or return $from;
347 my @names = ($from, grep { $_ ne $from } @{$among});
348 my @points = map { [ coordinates($_) ] } @names;
349 my $to = Game::Terminal::Kit::Steer::nearest(\@points, 0, @{$way}, cone => 1);
350 return defined $to ? $names[$to] : $from;
351 }
352  
353 sub movable {
354 my ($self) = @_;
355 my %seen;
356 return [ grep { !$seen{$_}++ } map { $_->{from} } @{ $self->game->legal } ];
357 }
358  
359 sub reach {
360 my ($self, $from) = @_;
361 return [ grep { $_->{from} eq $from } @{ $self->game->legal } ];
362 }
363  
364 sub pick {
365 my ($self) = @_;
366 return undef unless $self->raw;
367 my $movable = $self->movable;
368 return undef unless @{$movable};
369  
370 $self->chosen(undef);
371 $self->focus($movable->[0]) unless defined $self->focus && grep { $_ eq $self->focus } @{$movable};
372  
373 while (1) {
374 my $chosen = $self->chosen;
375 my $entries = defined $chosen ? $self->reach($chosen) : [];
376 my $among = defined $chosen ? [ map { $_->{to} } @{$entries} ] : $movable;
377  
378 $self->show(defined $chosen ? 'where' : 'which');
379 my $key = $self->read_key;
380 return undef if !defined $key || $key eq 'eof' || $key eq 'interrupt';
381  
382 if ($key =~ /\A(?:up|down|left|right)\z/) {
383 $self->focus($self->steer($self->focus, $key, $among));
384 next;
385 }
386 if ($key eq 'tab' || $key eq 'back_tab') {
387 my ($at) = grep { $among->[$_] eq $self->focus } 0 .. $#{$among};
388 $at = 0 unless defined $at;
389 $self->focus($among->[ Game::Terminal::Kit::Steer::ring(scalar @{$among}, $at, $key eq 'tab' ? 1 : -1) ]);
390 next;
391 }
392 if ($key eq 'home') { $self->focus($among->[0]); next }
393 if ($key eq 'end') { $self->focus($among->[-1]); next }
394  
395 if ($key eq 'enter' || $key eq ' ') {
396 if (!defined $chosen) {
397 $self->chosen($self->focus);
398 $self->focus($self->reach($self->focus)->[0]{to});
399 next;
400 }
401 my ($entry) = grep { $_->{to} eq $self->focus } @{$entries};
402 next unless $entry;
403 $self->game->play_or_die($entry->{move});
404 $self->_log->forget;
405 $self->chosen(undef);
406 $self->focus(undef);
407 $self->redraw(1);
408 return '';
409 }
410 if ($key eq 'escape' || $key eq 'backspace') {
411 if (defined $chosen) {
412 $self->focus($chosen);
413 $self->chosen(undef);
414 }
415 next;
416 }
417 if ($key eq 'h') {
418 my $move = $self->hint_move;
419 if (defined $move) {
420 my ($from, $to) = (substr($move, 0, 2), substr($move, 2, 2));
421 $self->chosen($from);
422 $self->focus($to);
423 $self->_log->record('The program would play ' . $self->paint("$from-$to", 'key') . '. Enter to play it.');
424 }
425 next;
426 }
427 if ($key eq '?') {
428 $self->show('help');
429 $self->read_key;
430 next;
431 }
432 if ($key eq ':') {
433 $self->chosen(undef);
434 return $self->read_line(': ');
435 }
436 if ($key =~ /\A[123]\z/) {
437 $self->set_level($key);
438 next;
439 }
440 if ($KEY{$key}) {
441 $self->chosen(undef);
442 return $KEY{$key};
443 }
444 next if $key eq 'unknown';
445 $self->_log->record('That key does nothing here. Press ? for the ones that do.')
446 unless grep { /does nothing here/ } @{ $self->notice };
447 }
448 }
449  
450 sub marks {
451 my ($self, $mode) = @_;
452 my $game = $self->game;
453 my %mark;
454  
455 my $shown = $game->shown;
456 if (@{$shown}) {
457 my ($from, $to) = $shown->[-1] =~ /([a-g][1-7])-([a-g][1-7])/;
458 $mark{$from} = $mark{$to} = 'trail' if defined $from;
459 }
460 return (\%mark, $game->pieces) unless $mode eq 'which' || $mode eq 'where';
461  
462 my $pieces = $game->pieces;
463 my $chosen = $self->chosen;
464 if (!defined $chosen) {
465 $mark{ $self->focus } = 'cursor' if defined $self->focus;
466 if (defined $self->focus) {
467 $mark{ $_->{to} } ||= 'reach' for @{ $self->reach($self->focus) };
468 $mark{ $self->focus } = 'cursor';
469 }
470 return (\%mark, $pieces);
471 }
472  
473 my $entries = $self->reach($chosen);
474 $mark{ $_->{to} } = 'reach' for @{$entries};
475 my ($entry) = grep { $_->{to} eq $self->focus } @{$entries};
476 if ($entry) {
477 my %after = %{$pieces};
478 $after{ $entry->{to} } = delete $after{$chosen};
479 $mark{$chosen} = 'from';
480 $mark{ $entry->{to} } = 'to';
481 $mark{$_} = 'taken' for @{ $entry->{captures} };
482 return (\%mark, \%after);
483 }
484 $mark{$chosen} = 'from';
485 return (\%mark, $pieces);
486 }
487  
488 sub paint {
489 my ($self, $text, $ink) = @_;
490 my $screen = $self->_screen;
491 $screen->colour($self->colour ? 1 : 0);
492 return $screen->paint($text, $INK{$ink} || $ink);
493 }
494  
495 sub glyph {
496 my ($self, $what) = @_;
497 return $GLYPH{ $self->unicode ? 'wide' : 'ascii' }{$what};
498 }
499  
500 sub special {
501 my ($name) = @_;
502 return 'throne' if $name eq 'd4';
503 return 'corner' if $name =~ /\A[ag][17]\z/;
504 return '';
505 }
506  
507 sub board_lines {
508 my ($self, $mode) = @_;
509 my ($mark, $pieces) = $self->marks($mode || 'plain');
510 return $self->colour ? $self->painted_board($mark, $pieces) : $self->plain_board($mark, $pieces);
511 }
512  
513 sub painted_board {
514 my ($self, $mark, $pieces) = @_;
515 my @lines;
516 for my $rank (reverse 0 .. 6) {
517 my ($top, $bottom) = ('', '');
518 for my $file (0 .. 6) {
519 my $name = square_name($file, $rank);
520 my $what = $mark->{$name} || '';
521 my $piece = $pieces->{$name};
522 my $place = special($name);
523  
524 my $ground = $what && $what ne 'reach' ? $GROUND{$what}
525 : $what eq 'reach' ? $GROUND{reach}
526 : $place ? $GROUND{$place}
527 : (($file + $rank) % 2 ? $GROUND{light} : $GROUND{dark});
528  
529 my ($glyph, $ink);
530 if ($what eq 'taken') { ($glyph, $ink) = ($self->glyph('taken'), $INK{taken}) }
531 elsif (defined $piece) { ($glyph, $ink) = ($self->glyph($piece), $INK{$piece}) }
532 elsif ($what eq 'from') { ($glyph, $ink) = ($self->glyph('from'), $INK{mark}) }
533 elsif ($what eq 'reach'){ ($glyph, $ink) = ($self->glyph('reach'), $INK{reach}) }
534 elsif ($place) { ($glyph, $ink) = ($self->glyph($place), $INK{mark}) }
535 else { ($glyph, $ink) = (' ', $INK{mark}) }
536  
537 $top .= "\e[${ground};${ink}m $glyph \e[0m";
538 $bottom .= "\e[${ground}m \e[0m";
539 }
540 push @lines, sprintf(' %d ', $rank + 1) . $top, ' ' . $bottom;
541 }
542 push @lines, ' ' . join('', map { " $_ " } 'a' .. 'g');
543 return \@lines;
544 }
545  
546 sub plain_board {
547 my ($self, $mark, $pieces) = @_;
548 my $rule = ' +' . ('---+' x 7);
549 my @lines = (' ' . join(' ', 'a' .. 'g'), $rule);
550 for my $rank (reverse 0 .. 6) {
551 my $row = sprintf ' %d |', $rank + 1;
552 for my $file (0 .. 6) {
553 my $name = square_name($file, $rank);
554 my $what = $mark->{$name} || '';
555 my $piece = $pieces->{$name};
556 my $place = special($name);
557 my $glyph = $what eq 'taken' ? $self->glyph('taken')
558 : defined $piece ? $self->glyph($piece)
559 : $what eq 'from' ? $self->glyph('from')
560 : $what eq 'reach' ? $self->glyph('reach')
561 : $place ? $self->glyph($place)
562 : ' ';
563 $row .= $what eq 'cursor' ? "[$glyph]|"
564 : $what eq 'to' ? "($glyph)|"
565 : $what eq 'trail' ? "'$glyph'|"
566 : " $glyph |";
567 }
568 push @lines, $row, $rule;
569 }
570 return \@lines;
571 }
572  
573 sub who {
574 my ($self, $side) = @_;
575 return 'you' if $self->human eq $side;
576 return 'either of you' if $self->human eq 'both';
577 return 'the program, level ' . $self->level;
578 }
579  
580 sub status_lines {
581 my ($self) = @_;
582 my $game = $self->game;
583 my $pieces = $game->pieces;
584 my %count;
585 $count{$_}++ for values %{$pieces};
586  
587 my @lines;
588 if ($game->status eq 'finished') {
589 push @lines, @{ $self->result_lines };
590 }
591 else {
592 my $side = $game->side_to_move;
593 push @lines, sprintf '%s to move: %s.',
594 $self->paint('The ' . $side, $side eq 'attackers' ? 'warn' : 'good'), $self->who($side);
595 }
596 push @lines, sprintf '%s %s %s %s %s %s',
597 'Attackers', $self->tray('attacker', $count{attacker} || 0, 8),
598 'Defenders', $self->tray('defender', $count{defender} || 0, 4),
599 'King', $self->tray('king', $count{king} || 0, 1);
600  
601 push @lines, $self->paint($self->table_line, 'quiet');
602  
603 my $shown = $game->shown;
604 my $from = @{$shown} > 6 ? @{$shown} - 6 : 0;
605 push @lines, $self->paint('Move ' . ($game->ply + 1) . '.', 'quiet')
606 . (@{$shown} ? ' ' . $self->paint(join(' ', map { ($_ + 1) . '. ' . $shown->[$_] } $from .. $#{$shown}), 'quiet') : '');
607  
608 my $repeats = $game->repeats;
609 my $limit = $game->variant->repeat;
610 push @lines, $self->paint(sprintf('This position has now stood %d time%s. At %d the game is drawn.',
611 $repeats, ($repeats == 1 ? '' : 's'), $limit), 'warn')
612 if $game->status eq 'active' && $repeats > 1;
613 push @lines, $self->paint('The ' . $game->side_of($game->draw_offered_by) . ' have offered a draw.', 'warn')
614 if defined $game->draw_offered_by;
615 return \@lines;
616 }
617  
618 sub table_line {
619 my ($self) = @_;
620 my $human = $self->human;
621 return 'Two players at one keyboard.' if $human eq 'both';
622 return 'The program plays both sides, at level ' . $self->level . '.' if $human eq 'none';
623 return sprintf 'You have the %s; the program has the %s, at level %d.',
624 $human, ($human eq 'attackers' ? 'defenders' : 'attackers'), $self->level;
625 }
626  
627 sub result_lines {
628 my ($self) = @_;
629 my $result = $self->game->result or return [];
630 my $how = $result->how;
631 my $line = $how eq 'resign'
632 ? sprintf('The %s resign. The %s win.', $result->loser, $result->winner)
633 : $ENDING{$how};
634 my $ink = !defined $result->winner ? 'warn'
635 : $self->human eq $result->winner ? 'good'
636 : $self->human eq $result->loser ? 'bad'
637 : 'title';
638 my @lines = ($self->paint($line, $ink));
639 push @lines, $self->paint('You win.', 'good') if defined $result->winner && $self->human eq $result->winner;
640 push @lines, $self->paint('The program wins.', 'bad') if defined $result->winner && $self->human eq $result->loser;
641 return \@lines;
642 }
643  
644 sub legend {
645 my ($self, $mode) = @_;
646 my $k = sub { $self->paint($_[0], 'key') };
647 return $k->('arrows') . ' choose a piece ' . $k->('enter') . ' pick it up ' . $k->('h') . ' hint '
648 . $k->('u') . ' undo ' . $k->('r') . ' redo ' . $k->('?') . ' help ' . $k->('q') . ' quit'
649 if $mode eq 'which';
650 return $k->('arrows') . ' choose where ' . $k->('enter') . ' play it ' . $k->('esc') . ' put it back '
651 . $k->('?') . ' help'
652 if $mode eq 'where';
653 return $k->('n') . ' new game ' . $k->('u') . ' undo ' . $k->('r') . ' redo ' . $k->('R') . ' rules ' . $k->('q') . ' quit'
654 if $mode eq 'ended';
655 return 'The program is thinking...' if $mode eq 'thinking';
656 return 'Press any key to go back to the board.';
657 }
658  
659 sub preview_lines {
660 my ($self) = @_;
661 my $chosen = $self->chosen;
662 return [] unless defined $chosen;
663 my ($entry) = grep { $_->{to} eq $self->focus } @{ $self->reach($chosen) };
664 return [] unless $entry;
665 my $line = sprintf 'The %s from %s to %s', $entry->{piece}, $chosen, $entry->{to};
666 $line .= ', taking ' . join(' and ', @{ $entry->{captures} }) if @{ $entry->{captures} };
667 $line .= '.';
668 $line .= ' ' . $self->paint('This wins the game.', 'good') if $entry->{wins};
669 return [$line];
670 }
671  
672 sub banner {
673 my ($self) = @_;
674 return [' BRANDUBH'] unless $self->colour;
675 my $bar = join '', map { "\e[48;5;${_}m \e[0m" } 94, 130, 136, 172, 178, 220, 178, 172, 136, 130, 94;
676 return [ ' ' . $self->paint('B R A N D U B H', 'title') . ' ' . $bar ];
677 }
678  
679 sub tray {
680 my ($self, $piece, $left, $of) = @_;
681 my $glyph = $self->glyph($piece);
682 my $gone = $self->unicode ? "\x{00B7}" : '.';
683 return ($glyph x $left) . ($gone x ($of - $left)) . " $left" unless $self->colour;
684 my $ground = '48;5;' . ($piece eq 'attacker' ? '180' : '94');
685 return "\e[${ground};$INK{$piece}m " . join(' ', ($glyph) x $left) . ($left ? ' ' : '') . "\e[0m"
686 . $self->paint(join('', (" $gone") x ($of - $left)), 'quiet');
687 }
688  
689 sub choose {
690 my ($self, $question, $options, $at) = @_;
691 my $k = sub { $self->paint($_[0], 'key') };
692 my $ask = Game::Terminal::Kit::Choose->new(
693 question => $question,
694 choices => $options,
695 at => defined $at ? $at : 0,
696 legend => [ '', $k->('up') . ' and ' . $k->('down') . ' to choose, ' . $k->('enter') . ' to take it, ' . $k->('q') . ' to leave' ],
697 screen => $self->_screen,
698 );
699 $ask->picker->head([ @{ $self->banner }, '', $question, '' ]);
700 $ask->picker->numbered(0);
701 my ($event, $value) = $ask->run($self->_keyboard, $self->_screen);
702 return defined $event && $event eq 'chosen' ? $value : undef;
703 }
704  
705 sub ask_how_to_play {
706 my ($self) = @_;
707 my $side = $self->choose('Which side will you take?', [
708 [ 'attackers', 'The attackers', 'eight pieces round the board; they move first and must capture the king' ],
709 [ 'defenders', 'The defenders', 'the king and his four; he must reach a corner. The gentler side to learn on' ],
710 [ 'both', 'Both', 'two people at this keyboard' ],
711 [ 'none', 'Neither', 'watch the program play itself' ],
712 ], $self->human eq 'defenders' ? 1 : $self->human eq 'both' ? 2 : $self->human eq 'none' ? 3 : 0);
713 return 0 unless defined $side;
714 $self->human($side);
715 return 1 if $side eq 'both';
716  
717 my $level = $self->choose('How hard should the program play?', [
718 [ 1, 'Level 1', 'looks a move or two ahead, and now and then does not look at all' ],
719 [ 2, 'Level 2', 'looks three moves ahead' ],
720 [ 3, 'Level 3', 'looks four or five moves ahead: its best' ],
721 ], $self->level - 1);
722 return 0 unless defined $level;
723 $self->level($level);
724 return 1;
725 }
726  
727 sub screen {
728 my ($self, $mode) = @_;
729 my @lines = (@{ $self->banner }, '');
730 if ($mode eq 'help') {
731 push @lines, @{ $self->help_lines }, '', $self->legend('help');
732 return \@lines;
733 }
734 if ($mode eq 'rules') {
735 push @lines, @{ $self->rules_lines }, '', $self->legend('rules');
736 return \@lines;
737 }
738 push @lines, @{ $self->notice }, ('') x (@{ $self->notice } ? 1 : 0);
739 push @lines, @{ $self->board_lines($mode) }, '';
740 push @lines, @{ $self->status_lines };
741 push @lines, @{ $self->preview_lines } if $mode eq 'where';
742 push @lines, '', $self->legend($mode);
743 return \@lines;
744 }
745  
746 sub show {
747 my ($self, $mode) = @_;
748 my $lines = $self->screen($mode);
749 $self->_frame($lines);
750 $self->_screen->show($lines);
751 $self->redraw(0);
752 return $self;
753 }
754  
755 sub render {
756 my ($self) = @_;
757 $self->_screen->clear;
758 $self->say($_) for @{ $self->notice };
759 $self->say($_) for @{ $self->board_lines('plain') }, '', @{ $self->status_lines };
760 $self->redraw(0);
761 return $self;
762 }
763  
764 sub say {
765 my ($self, $line) = @_;
766 $self->_screen->say($line);
767 return $self;
768 }
769  
770 sub remark {
771 my ($self, $line) = @_;
772 if ($self->raw) {
773 $self->_log->record($line);
774 return $self;
775 }
776 return $self->say($line);
777 }
778  
779 sub read_line {
780 my ($self, $prompt) = @_;
781 my $out = $self->out;
782 my $game = $self->game;
783 my $ask = defined $prompt ? $prompt : ($game->side_to_move || 'game over') . '> ';
784 if ($self->raw) {
785 my $typed = Game::Terminal::Kit::Line->new(prompt => $ask, head => $self->_frame || []);
786 my ($event, $text) = $typed->run($self->_keyboard, $self->_screen);
787 return $event eq 'chosen' ? $text : $event eq 'back' ? '' : undef;
788 }
789 print {$out} $ask;
790 my $line = readline $self->in;
791 return undef unless defined $line;
792 chomp $line;
793 return $line;
794 }
795  
796 sub command {
797 my ($self, $line) = @_;
798 $line =~ s/\A\s+//;
799 $line =~ s/\s+\z//;
800 return 0 unless length $line;
801 my ($word, $rest) = split /\s+/, $line, 2;
802 $word = lc $word;
803 $rest = '' unless defined $rest;
804  
805 return 1 if $word eq 'quit' || $word eq 'exit' || $word eq 'q';
806 if ($word eq 'help' || $word eq '?') { $self->page('help'); return 0 }
807 if ($word eq 'rules') { $self->page('rules'); return 0 }
808 if ($word eq 'board') { $self->redraw(1); return 0 }
809 if ($word eq 'moves') { $self->show_moves; return 0 }
810 if ($word eq 'hint') { $self->show_hint; return 0 }
811 if ($word eq 'undo') { $self->take_back; return 0 }
812 if ($word eq 'redo') { $self->play_again; return 0 }
813 if ($word eq 'new') { $self->new_game; return 0 }
814 if ($word eq 'save') { $self->save($rest); return 0 }
815 if ($word eq 'load') { $self->load($rest); return 0 }
816 if ($word eq 'level') { $self->set_level($rest); return 0 }
817 if ($word eq 'side') { $self->set_side($rest); return 0 }
818 if ($word eq 'draw') { $self->offer_draw; return 0 }
819 if ($word eq 'resign') { $self->resign; return 0 }
820 if ($word eq 'colour' || $word eq 'color') {
821 $self->colour($self->colour ? 0 : 1);
822 $self->redraw(1);
823 return 0;
824 }
825 if ($word eq 'pick') {
826 if ($self->keys_available && $self->enter_raw) { $self->picking(1) }
827 else { $self->remark('The arrow keys need Term::ReadKey and a terminal. Still typing.') }
828 $self->redraw(1);
829 return 0;
830 }
831 if ($word eq 'type') {
832 $self->picking(0);
833 $self->leave_raw;
834 $self->redraw(1);
835 return 0;
836 }
837  
838 my $move = $line;
839 $move =~ s/\A([a-gA-G][1-7])\s+([a-gA-G][1-7])\z/$1$2/;
840 $self->play_text($move);
841 return 0;
842 }
843  
844 sub play_text {
845 my ($self, $move) = @_;
846 my $game = $self->game;
847 if ($game->status eq 'finished') {
848 $self->remark('The game is over. new starts another.');
849 return $self;
850 }
851 my $refused = $game->play($move);
852 if ($refused) {
853 my $code = $refused->code;
854 $self->remark($code eq 'bad_move'
855 ? "I do not know '$move'. A move is two squares, like d1d3. help lists the commands."
856 : ucfirst($refused->message) . '.');
857 return $self;
858 }
859 $self->_log->forget;
860 $self->redraw(1);
861 return $self;
862 }
863  
864 sub page {
865 my ($self, $which) = @_;
866 if ($self->raw) {
867 $self->show($which);
868 $self->read_key;
869 $self->redraw(1);
870 return $self;
871 }
872 $self->say($_) for @{ $which eq 'help' ? $self->help_lines : $self->rules_lines };
873 return $self;
874 }
875  
876 sub show_moves {
877 my ($self) = @_;
878 my $legal = $self->game->legal;
879 unless (@{$legal}) {
880 $self->remark('There are no moves: the game is over.');
881 return $self;
882 }
883 my %by;
884 push @{ $by{ $_->{from} } }, $_ for @{$legal};
885 for my $from (sort keys %by) {
886 my @to = map {
887 $_->{to} . (@{ $_->{captures} } ? 'x' . join(',', @{ $_->{captures} }) : '') . ($_->{wins} ? '!' : '')
888 } sort { $a->{to} cmp $b->{to} } @{ $by{$from} };
889 $self->say(sprintf ' %-8s %s %s', $by{$from}[0]{piece}, $from, join(' ', @to));
890 }
891 $self->say(sprintf '%d moves. x marks a capture, ! a move that wins.', scalar @{$legal});
892 return $self;
893 }
894  
895 sub hint_move {
896 my ($self) = @_;
897 return Game::Brandubh::Bot->hint($self->game, seed => $self->seed);
898 }
899  
900 sub show_hint {
901 my ($self) = @_;
902 my $move = $self->hint_move;
903 $self->remark(defined $move
904 ? 'The program would play ' . substr($move, 0, 2) . '-' . substr($move, 2, 2) . '.'
905 : 'The game is over: there is nothing to play.');
906 return $self;
907 }
908  
909 sub take_back {
910 my ($self) = @_;
911 my $game = $self->history->undo;
912 unless ($game) {
913 $self->remark('There is nothing to take back.');
914 return 0;
915 }
916 $self->swap($game);
917 $self->remark('Taken back.');
918 return 1;
919 }
920  
921 sub play_again {
922 my ($self) = @_;
923 my $game = $self->history->redo;
924 unless ($game) {
925 $self->remark('There is nothing to play again.');
926 return 0;
927 }
928 $self->swap($game);
929 $self->remark('Played again.');
930 return 1;
931 }
932  
933 sub swap {
934 my ($self, $game) = @_;
935 $self->game($game);
936 $self->_log->forget;
937 $self->focus(undef);
938 $self->chosen(undef);
939 $self->redraw(1);
940 return $self;
941 }
942  
943 sub new_game {
944 my ($self) = @_;
945 $self->seed(Digest::SHA::sha256($self->seed . 'again'));
946 $self->game($self->fresh_game);
947 $self->history->start($self->game);
948 $self->_log->forget->record('A new game.');
949 $self->focus(undef);
950 $self->chosen(undef);
951 $self->redraw(1);
952 return $self;
953 }
954  
955 sub save {
956 my ($self, $file) = @_;
957 unless (length $file) {
958 $self->remark('save needs a file name.');
959 return 0;
960 }
961 my $handle;
962 unless (open $handle, '>', $file) {
963 $self->remark("Cannot write $file: $!.");
964 return 0;
965 }
966 print {$handle} $self->game->as_text;
967 close $handle;
968 $self->remark("Saved to $file.");
969 return 1;
970 }
971  
972 sub load {
973 my ($self, $file) = @_;
974 unless (length $file) {
975 $self->remark('load needs a file name.');
976 return 0;
977 }
978 my $handle;
979 unless (open $handle, '<', $file) {
980 $self->remark("Cannot read $file: $!.");
981 return 0;
982 }
983 my $text = do { local $/; <$handle> };
984 close $handle;
985 my ($game, $refused, $at) = Game::Brandubh->from_text($text, seed => $self->seed);
986 if (!$game || $refused) {
987 $self->remark($game
988 ? sprintf('%s is not a game I can play: move %d is refused (%s).', $file, $at + 1, $refused->message)
989 : "$file is not a saved game.");
990 return 0;
991 }
992 $self->game($game);
993 $self->history->start($game);
994 my $loaded = sprintf 'Loaded %s: %d moves.', $file, $game->ply;
995 $self->_log->forget->record($loaded);
996 $self->say($loaded) unless $self->raw;
997 $self->focus(undef);
998 $self->chosen(undef);
999 $self->redraw(1);
1000 return 1;
1001 }
1002  
1003 sub set_level {
1004 my ($self, $level) = @_;
1005 unless (defined $level && $level =~ /\A[123]\z/) {
1006 $self->remark('A level is 1, 2 or 3.');
1007 return 0;
1008 }
1009 $self->level($level);
1010 $self->remark("The program now plays at level $level.");
1011 return 1;
1012 }
1013  
1014 sub set_side {
1015 my ($self, $side) = @_;
1016 $side = lc(defined $side ? $side : '');
1017 unless ($side =~ /\A(?:attackers|defenders|both|none)\z/) {
1018 $self->remark('A side is attackers, defenders, both or none.');
1019 return 0;
1020 }
1021 $self->human($side);
1022 $self->remark($side eq 'both' ? 'Both sides are yours.'
1023 : $side eq 'none' ? 'The program plays both sides.'
1024 : "You have the $side.");
1025 $self->redraw(1);
1026 return 1;
1027 }
1028  
1029 sub seat_of_human {
1030 my ($self) = @_;
1031 my $game = $self->game;
1032 return $game->turn if $self->human eq 'both' || $self->human eq 'none';
1033 return $game->seat_of($self->human);
1034 }
1035  
1036 sub offer_draw {
1037 my ($self) = @_;
1038 my $game = $self->game;
1039 if ($game->status eq 'finished') {
1040 $self->remark('The game is over.');
1041 return 0;
1042 }
1043 my $seat = $self->seat_of_human;
1044 my $other = $seat eq 'p1' ? 'p2' : 'p1';
1045 if ($self->human eq 'both') {
1046 $game->offer_draw($seat);
1047 $game->accept_draw($other);
1048 $self->redraw(1);
1049 return 1;
1050 }
1051 my $score = $game->search(budget => $self->budget, salt => 'draw');
1052 my $for_program = $score ? ($game->turn eq $seat ? -$score->{score} : $score->{score}) : 0;
1053 if ($for_program > 150) {
1054 $self->remark('The program declines the draw.');
1055 return 0;
1056 }
1057 $game->offer_draw($seat);
1058 $game->accept_draw($other);
1059 $self->redraw(1);
1060 return 1;
1061 }
1062  
1063 sub resign {
1064 my ($self) = @_;
1065 my $game = $self->game;
1066 if ($game->status eq 'finished') {
1067 $self->remark('The game is over.');
1068 return 0;
1069 }
1070 $game->resign($self->seat_of_human);
1071 $self->redraw(1);
1072 return 1;
1073 }
1074  
1075 sub help_lines {
1076 my ($self) = @_;
1077 my @lines = ('Typed commands:', '');
1078 push @lines, sprintf(' %-10s %s', $_->[0], $_->[1]) for @COMMANDS;
1079 push @lines, '', 'On the board, with the arrow keys:', '',
1080 ' arrows move to a piece, then to where it should go',
1081 ' tab the next one, in order',
1082 ' enter pick the piece up, then put it down',
1083 ' esc put the piece back',
1084 ' h show the move the program would play',
1085 ' 1 2 3 how hard the program plays',
1086 ' u r undo, redo',
1087 ' R n c q rules, new game, colour, quit',
1088 ' : type a command';
1089 return \@lines;
1090 }
1091  
1092 sub rules_lines {
1093 my ($self) = @_;
1094 my $repeat = $self->game->variant->repeat;
1095 my $nth = $repeat == 2 ? 'second' : $repeat == 3 ? 'third' : $repeat == 4 ? 'fourth' : "${repeat}th";
1096 return [
1097 'Brandubh is played on seven squares by seven. The middle square is the',
1098 'throne and the four corners are the king\'s way out.',
1099 '',
1100 'The attackers have eight pieces and move first. The defenders have four,',
1101 'and the king, who starts on the throne.',
1102 '',
1103 'Every piece moves like a rook: any distance along a row or a column, not',
1104 'onto another piece and not over one. No piece may stop on the throne, not',
1105 'even the king once he has left it, though a piece may slide across it',
1106 'while it is empty. Only the king may stop on a corner.',
1107 '',
1108 'A piece is captured when the enemy moves so that it stands between two',
1109 'enemy pieces, one on each side, along a row or a column. An empty corner,',
1110 'and the throne while it is empty, each count as an enemy to both sides.',
1111 'Only the piece that moved captures: a piece may move between two enemies',
1112 'and stand there unharmed. One move can capture up to three. Nothing is',
1113 'captured against the edge of the board.',
1114 '',
1115 'The king is captured by attackers: four round him on the throne, three',
1116 'when he stands beside it, and two, like any piece, anywhere else.',
1117 '',
1118 'The king wins by reaching a corner. The attackers win by capturing him,',
1119 'and lose if they have no piece left.',
1120 '',
1121 "The game is drawn when a position comes round for the $nth time, when",
1122 'the side to move cannot move, and when it has gone on too long to end.',
1123 ];
1124 }
1125  
1126 sub _usage {
1127 return <<'USAGE';
1128 brandubh - the Irish tafl game, in a terminal
1129  
1130 brandubh [options]
1131  
1132 --side WHO attackers (the default), defenders, both, or none
1133 --level N how hard the program plays: 1, 2 (the default) or 3
1134 --variant TEXT the rule set, for example 'custom repeat=2'
1135 --seed HEX sixty-four hexadecimal characters; the same seed plays the same game
1136 --load FILE carry on with a saved game
1137 --no-colour letters and lines instead of a painted board
1138 --no-pick type moves instead of choosing them with the arrow keys
1139 --no-unicode letters for the pieces, with colour kept
1140 --version the version, and stop
1141 --help this, and stop
1142  
1143 In a terminal, moves are chosen on the board with the arrow keys; press ? for
1144 the keys. Anywhere else, type a move as two squares, like d1d3, or help.
1145 USAGE
1146 }
1147  
1148 sub options {
1149 return [
1150 { name => 'side', type => 'enum', choices => [qw(attackers defenders both none)], help => 'your side; both is hotseat, none is watching' },
1151 { name => 'level', type => 'int', min => 1, max => 3, help => 'how hard the program plays' },
1152 { name => 'seed', type => 'str', help => 'sixty-four hexadecimal characters; the same seed plays the same game' },
1153 ];
1154 }
1155  
1156 sub run {
1157 my ($class, @argv) = @_;
1158  
1159 my %given;
1160 my $parsed = Getopt::Long::GetOptionsFromArray(
1161 \@argv, \%given,
1162 'level=i', 'side=s', 'seed=s', 'variant=s', 'load=s',
1163 'colour|color!', 'pick!', 'unicode!', 'version', 'help',
1164 );
1165  
1166 if (!$parsed || @argv) {
1167 print STDERR "brandubh: I do not know '@argv'.\n" if $parsed && @argv;
1168 print STDERR _usage();
1169 return 2;
1170 }
1171 if ($given{help}) {
1172 print _usage();
1173 return 0;
1174 }
1175 if ($given{version}) {
1176 print "brandubh $Game::Brandubh::VERSION\n";
1177 return 0;
1178 }
1179  
1180 my %with;
1181 $with{level} = $given{level} if defined $given{level};
1182 $with{human} = $given{side} if defined $given{side};
1183 $with{variant} = $given{variant} if defined $given{variant};
1184 $with{colour} = $given{colour} if defined $given{colour};
1185 $with{picking} = $given{pick} if defined $given{pick};
1186 $with{unicode} = $given{unicode} if defined $given{unicode};
1187 $with{menu} = 1 unless defined $given{side} || defined $given{level} || defined $given{load};
1188  
1189 if (defined $given{seed}) {
1190 if ($given{seed} !~ /\A[0-9a-fA-F]{64}\z/) {
1191 print STDERR "brandubh: a seed is sixty-four hexadecimal characters.\n";
1192 return 2;
1193 }
1194 $with{seed} = pack 'H*', $given{seed};
1195 }
1196  
1197 my $terminal = eval { $class->new(%with) };
1198 if (!$terminal) {
1199 (my $why = $@) =~ s/ at \S+ line \d+\.?\s*\z//;
1200 $why =~ s/\AGame::Brandubh(?:::\w+)*: //;
1201 print STDERR "brandubh: $why.\n";
1202 return 2;
1203 }
1204  
1205 if (defined $given{load}) {
1206 return 2 unless $terminal->load($given{load});
1207 }
1208  
1209 return $terminal->start;
1210 }
1211  
1212 1;
1213  
1214 __END__
« blib/lib/Game/Brandubh/Rules.pm ↑ Summary Brandubh.xs »