Dominoes/Terminal.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Dominoes/Result.pm ↑ Summary Dominoes/Tile.pm »
1 package Game::Dominoes::Terminal;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 0 ▶use Object::Proto::Sugar -types;
Subroutine BEGIN: called CC=1 SCAR=2.6
7  
8 use Game::Dominoes;
9 use Game::Dominoes::Bot;
10 use Game::Dominoes::Notation;
11 use Game::Dominoes::Rules;
12 use Game::Dominoes::Scoring;
13 use Game::Terminal::Kit::History;
14 use Game::Terminal::Kit::Keys;
15 use Game::Terminal::Kit::Log;
16 use Game::Terminal::Kit::Picker;
17 use Game::Terminal::Kit::Run;
18 use Game::Terminal::Kit::Screen;
19 use Getopt::Long ();
20  
21 our $VERSION = '0.04';
22  
23 our @PIPS = (
24 [],
25 [[1, 1]],
26 [[0, 0], [2, 2]],
27 [[0, 0], [1, 1], [2, 2]],
28 [[0, 0], [0, 2], [2, 0], [2, 2]],
29 [[0, 0], [0, 2], [1, 1], [2, 0], [2, 2]],
30 [[0, 0], [0, 2], [1, 0], [1, 2], [2, 0], [2, 2]],
31 );
32  
33 our %CHARS = (
34 wide => {
35 pip => "\x{25CF}",
36 h => "\x{2500}", v => "\x{2502}",
37 tl => "\x{250C}", tr => "\x{2510}", bl => "\x{2514}", br => "\x{2518}",
38 t => "\x{252C}", b => "\x{2534}", l => "\x{251C}", r => "\x{2524}",
39 },
40 ascii => {
41 pip => '*',
42 h => '-', v => '|',
43 tl => '+', tr => '+', bl => '+', br => '+',
44 t => '+', b => '+', l => '+', r => '+',
45 },
46 );
47  
48 our %MARKED = (
49 recent => {
50 wide => {
51 h => "\x{2550}", v => "\x{2551}",
52 tl => "\x{2554}", tr => "\x{2557}", bl => "\x{255A}", br => "\x{255D}",
53 t => "\x{2566}", b => "\x{2569}", l => "\x{2560}", r => "\x{2563}",
54 },
55 ascii => {
56 h => '=', v => '#',
57 tl => '#', tr => '#', bl => '#', br => '#',
58 t => '#', b => '#', l => '#', r => '#',
59 },
60 },
61 preview => {
62 wide => {
63 h => "\x{2501}", v => "\x{2503}",
64 tl => "\x{250F}", tr => "\x{2513}", bl => "\x{2517}", br => "\x{251B}",
65 t => "\x{2533}", b => "\x{253B}", l => "\x{2523}", r => "\x{252B}",
66 },
67 ascii => {
68 h => '=', v => '!',
69 tl => '+', tr => '+', bl => '+', br => '+',
70 t => '+', b => '+', l => '+', r => '+',
71 },
72 },
73 );
74  
75 our %MARK_INK = (
76 new => '1;32',
77 recent => '32',
78 preview => '1;36',
79 );
80  
81 our %MARK_FRAME = (
82 new => 'recent',
83 recent => 'recent',
84 preview => 'preview',
85 );
86  
87 our %PICK_KEY = (
88 'v' => 'live',
89 '?' => 'help',
90 't' => 'type',
91 ':' => 'command',
92 );
93  
94 our $WINDOW = 8;
95  
96 has game => (is => 'rw', isa => Object);
97  
98 has bots => (is => 'rw', isa => HashRef, default => {});
99  
100 has in => (is => 'rw');
101 has out => (is => 'rw');
102  
103 has colour => (is => 'rw', isa => Bool);
104 has ascii => (is => 'rw', isa => Bool, default => 0);
105  
106 has compact => (is => 'rw', isa => Bool, default => 0);
107  
108 has width => (is => 'rw', isa => Int, default => 0);
109  
110 has handover => (is => 'rw', isa => Bool);
111  
112 has quit => (is => 'rw', isa => Bool, default => 0);
113  
114 has recent => (is => 'rw', isa => ArrayRef, default => []);
115  
116 has keysource => (is => 'rw');
117  
118 has pending => (is => 'rw', isa => ArrayRef, default => []);
119  
120 has keyboard => (is => 'rw');
121 has screen => (is => 'rw');
122 has log => (is => 'rw');
123  
124 has history => (is => 'rw');
125  
126 has _picking => (is => 'rw', init_arg => 'picking', private => 1);
127 has _seen => (is => 'rw', isa => Int, default => 0, private => 1);
128 has _told => (is => 'rw', isa => HashRef, default => {}, private => 1);
129  
130 sub BUILD {
131 my ($self) = @_;
132 $self->in(\*STDIN) unless $self->in;
133 $self->out(\*STDOUT) unless $self->out;
134 $self->game(Game::Dominoes->new(seed => "\0" x 32)) unless $self->game;
135  
136 my $tty = eval { -t $self->out } ? 1 : 0;
137 unless (defined $self->colour) {
138 $self->colour(($tty && !Game::Terminal::Kit::Screen::no_colour()) ? 1 : 0);
139 }
140 unless (defined $self->handover) {
141 $self->handover($self->_humans > 1 ? 1 : 0);
142 }
143 $self->keyboard(Game::Terminal::Kit::Keys->new(
144 in => $self->in,
145 pending => $self->pending,
146 ($self->keysource ? (keysource => $self->keysource) : ()),
147 )) unless $self->keyboard;
148 $self->screen(Game::Terminal::Kit::Screen->new(
149 out => $self->out,
150 interactive => $tty,
151 colour => $self->colour ? 1 : 0,
152 ascii => $self->ascii ? 1 : 0,
153 )) unless $self->screen;
154 $self->log(Game::Terminal::Kit::Log->new(keep => $self->game->players))
155 unless $self->log;
156 $self->history(Game::Terminal::Kit::History->new(
157 save => sub { $_[0]->to_text(with_seed => 1) },
158 load => sub { Game::Dominoes->from_text($_[0]) },
159 )) unless $self->history;
160 $self->history->start($self->game);
161 $self->_seen(scalar @{ $self->game->history });
162 $self->screen->utf8->flush_on;
163 return $self;
164 }
165  
166 sub _in_step {
167 my ($self) = @_;
168 my $screen = $self->screen;
169 $screen->colour($self->colour ? 1 : 0);
170 $screen->ascii($self->ascii ? 1 : 0);
171 return $screen;
172 }
173  
174 sub _humans {
175 my ($self) = @_;
176 return scalar grep { !$self->bots->{$_} } $self->game->seats;
177 }
178  
179 sub remember {
180 my ($self, $seat, $play) = @_;
181 return $self unless ref $play && $play->can('tile') && $play->tile;
182  
183 my $recent = $self->recent;
184 push @$recent, { seat => $seat, play => $play };
185  
186 shift @$recent while @$recent > $self->game->players;
187  
188 $self->log->keep($self->game->players);
189 $self->log->record("seat $seat played " . $play->tile->stringify
190 . ' on ' . $play->arm
191 . ($play->points ? ' for ' . $play->points : '')
192 . ($play->spinner ? ', the spinner' : ''));
193  
194 return $self;
195 }
196  
197 sub table_marks {
198 my ($self) = @_;
199 my $recent = $self->recent;
200 my %mark;
201 for my $i (0 .. $#$recent) {
202 $mark{ $recent->[$i]{play}->tile->id }
203 = $i == $#$recent ? 'new' : 'recent';
204 }
205 return \%mark;
206 }
207  
208 sub recent_lines {
209 my ($self) = @_;
210 return map { @$_ } @{ $self->log->recent };
211 }
212  
213 sub _say {
214 my ($self, @text) = @_;
215 $self->screen->say(join '', @text);
216 return;
217 }
218  
219 sub _ask {
220 my ($self, $prompt) = @_;
221 return $self->keyboard->read_line($prompt, $self->out);
222 }
223  
224 sub table {
225 my ($self, $view, $marks) = @_;
226 my $layout = $view->{layout};
227 $marks ||= $self->table_marks;
228 return (' (nothing on the table yet)') unless $layout->count;
229 return $self->_compact_table($layout, $marks) if $self->compact;
230  
231 my $spinner = $layout->spinner_index;
232 my $line = $layout->line;
233 my @cell = map {
234 $self->_tile_art($line->[$_]{left}, $line->[$_]{right},
235 $line->[$_]{tile}->is_double,
236 defined $spinner && $_ == $spinner,
237 $marks->{ $line->[$_]{tile}->id })
238 } 0 .. $#$line;
239 my @band = $self->_wrap(\@cell);
240 my ($first, $last) = ($band[0], $band[-1]);
241  
242 my $at = sub {
243 my ($run) = @_;
244 return 2 unless defined $spinner && $run && $spinner >= $run->{from}
245 && $spinner <= $run->{to};
246 return $run->{x}[ $spinner - $run->{from} ];
247 };
248  
249 my @rows;
250 if (@{ $layout->u }) {
251 my @arm = map {
252 $self->_tile_art($_->{inner}, $_->{outer}, $_->{tile}->is_double, 0,
253 $marks->{ $_->{tile}->id })
254 } @{ $layout->u };
255 my $indent = $at->($first);
256 push @rows, map { $self->_band($_, $indent) } $self->_wrap(\@arm, $indent);
257 push @rows, $self->_stem($indent);
258 }
259  
260 push @rows, map { $self->_band($_, 2) } @band;
261  
262 if (@{ $layout->d }) {
263 my @arm = map {
264 $self->_tile_art($_->{inner}, $_->{outer}, $_->{tile}->is_double, 0,
265 $marks->{ $_->{tile}->id })
266 } @{ $layout->d };
267 my $indent = $at->($last);
268 push @rows, $self->_stem($indent);
269 push @rows, map { $self->_band($_, $indent) } $self->_wrap(\@arm, $indent);
270 }
271 return @rows;
272 }
273  
274 sub _compact_table {
275 my ($self, $layout, $marks) = @_;
276 $marks ||= {};
277 my @rows;
278 push @rows, ' ' . join(' ', map { $self->_tile($_->{tile}, $marks) } @{ $layout->u })
279 if @{ $layout->u };
280 push @rows, ' ' . join(' ', map { $self->_tile($_->{tile}, $marks) } @{ $layout->line });
281 push @rows, ' ' . join(' ', map { $self->_tile($_->{tile}, $marks) } @{ $layout->d })
282 if @{ $layout->d };
283 return @rows;
284 }
285  
286 sub _tile {
287 my ($self, $tile, $marks) = @_;
288  
289 my $mark = $marks ? $marks->{ $tile->id } : undef;
290 my $text = ($mark ? '{' : '[') . $tile->high . '|' . $tile->low
291 . ($mark ? '}' : ']');
292  
293 return $self->_paint($text, $MARK_INK{$mark}) if $mark;
294 return $tile->is_double ? $self->_paint($text, '1;33') : $text;
295 }
296  
297 sub _tile_art {
298 my ($self, $one, $two, $across, $bright, $mark) = @_;
299 my $kind = $self->ascii ? 'ascii' : 'wide';
300 my $c = $mark && $MARK_FRAME{$mark}
301 ? $MARKED{ $MARK_FRAME{$mark} }{$kind}
302 : $CHARS{$kind};
303 my @face = ($self->_face($one, $across), $self->_face($two, $across));
304  
305 my @lines;
306 if ($across) {
307 push @lines, $c->{tl} . ($c->{h} x 3) . $c->{tr};
308 push @lines, map { $c->{v} . $_ . $c->{v} } @{ $face[0] };
309 push @lines, $c->{l} . ($c->{h} x 3) . $c->{r};
310 push @lines, map { $c->{v} . $_ . $c->{v} } @{ $face[1] };
311 push @lines, $c->{bl} . ($c->{h} x 3) . $c->{br};
312 }
313 else {
314 push @lines, $c->{tl} . ($c->{h} x 3) . $c->{t} . ($c->{h} x 3) . $c->{tr};
315 push @lines, map {
316 $c->{v} . $face[0][$_] . $c->{v} . $face[1][$_] . $c->{v}
317 } 0 .. 2;
318 push @lines, $c->{bl} . ($c->{h} x 3) . $c->{b} . ($c->{h} x 3) . $c->{br};
319 }
320  
321 my $ink = $mark ? $MARK_INK{$mark} : ($bright ? '1;33' : undef);
322 @lines = map { $self->_paint($_, $ink) } @lines if defined $ink;
323  
324 return { width => $across ? 5 : 9, lines => \@lines };
325 }
326  
327 sub _face {
328 my ($self, $pips, $turned) = @_;
329 my $pip = $CHARS{ $self->ascii ? 'ascii' : 'wide' }{pip};
330 my @grid = map { [ (' ') x 3 ] } 0 .. 2;
331 for my $spot (@{ $PIPS[$pips] || [] }) {
332 my ($row, $col) = @$spot;
333 ($row, $col) = ($col, 2 - $row) if $turned;
334 $grid[$row][$col] = $pip;
335 }
336 return [ map { join '', @$_ } @grid ];
337 }
338  
339 sub _paint {
340 my ($self, $text, $code) = @_;
341 return $self->_in_step->paint($text, $code);
342 }
343  
344 sub _wrap {
345 my ($self, $cells, $indent) = @_;
346 $indent = 2 unless defined $indent;
347 my $room = ($self->width || ($self->screen->size)[0]) - $indent;
348 $room = 20 if $room < 20;
349  
350 my @run;
351 my ($cells_in, $x, @at) = ([], $indent);
352 my $from = 0;
353 for my $i (0 .. $#$cells) {
354 my $cell = $cells->[$i];
355 if (@$cells_in && $x + $cell->{width} - $indent > $room) {
356 push @run, { cells => $cells_in, x => [@at], from => $from, to => $i - 1 };
357 ($cells_in, $x, @at) = ([], $indent);
358 $from = $i;
359 }
360 push @$cells_in, $cell;
361 push @at, $x;
362 $x += $cell->{width};
363 }
364 push @run, { cells => $cells_in, x => [@at], from => $from, to => $#$cells }
365 if @$cells_in;
366 return @run;
367 }
368  
369 sub _band {
370 my ($self, $run, $indent) = @_;
371 my @cells = @{ $run->{cells} };
372 my $height = 0;
373 for my $cell (@cells) {
374 $height = scalar @{ $cell->{lines} } if @{ $cell->{lines} } > $height;
375 }
376  
377 my @rows = map { ' ' x $indent } 1 .. $height;
378 for my $cell (@cells) {
379 my $top = int(($height - scalar @{ $cell->{lines} }) / 2);
380 for my $row (0 .. $height - 1) {
381 my $line = $cell->{lines}[ $row - $top ];
382 $rows[$row] .= ($row >= $top && defined $line)
383 ? $line : ' ' x $cell->{width};
384 }
385 }
386  
387 s/\s+\z// for @rows;
388  
389 return @rows;
390 }
391  
392 sub _stem {
393 my ($self, $indent) = @_;
394 my $c = $CHARS{ $self->ascii ? 'ascii' : 'wide' };
395 return (' ' x ($indent + 2)) . $c->{v};
396 }
397  
398 sub _ends_line {
399 my ($self, $view) = @_;
400 my $count = $view->{count};
401 my $short = (5 - $count % 5) % 5;
402 my $text = 'ends ' . join(' ', @{ $view->{ends} }) . ' count ' . $count;
403 $text .= $short ? " ($short more would score)" : ' (scores)';
404 return $text;
405 }
406  
407 sub _scores_line {
408 my ($self, $view) = @_;
409 return 'scores ' . join(' ', map {
410 "seat $_: $view->{scores}{$_}"
411 } sort { $a <=> $b } keys %{ $view->{scores} });
412 }
413  
414 sub _hands_line {
415 my ($self, $view) = @_;
416 return 'tiles ' . join(' ', map {
417 "seat $_: $view->{counts}{$_}"
418 } sort { $a <=> $b } keys %{ $view->{counts} })
419 . ' boneyard: ' . $view->{boneyard};
420 }
421  
422 sub hand_lines {
423 my ($self, $view) = @_;
424 my @tiles = @{ $view->{hand} || [] };
425 return ('your tiles: (none)') unless @tiles;
426 return ('your tiles: ' . join ' ', map { $self->_tile($_) } @tiles)
427 if $self->compact;
428  
429 my @cell = map {
430 my $art = $self->_tile_art($_->high, $_->low, 0, 0);
431 push @{ $art->{lines} }, sprintf '%-9s', ' ' . $_->stringify . ' ';
432 $art;
433 } @tiles;
434 return ('your tiles:', map { $self->_band($_, 2) } $self->_wrap(\@cell));
435 }
436  
437 sub show {
438 my ($self, $view) = @_;
439 $self->_say('');
440 $self->_say("hand $view->{hand_number} " . $self->_scores_line($view));
441 $self->_say($self->_hands_line($view));
442 $self->_say('');
443 $self->_say($_) for $self->table($view);
444 $self->_say('');
445 $self->_say($self->_ends_line($view)) if $view->{layout}->count;
446 $self->_say($_) for $self->hand_lines($view);
447 return;
448 }
449  
450 sub picking {
451 my ($self, @set) = @_;
452 $self->_picking($set[0] ? 1 : 0) if @set;
453 return $self->_picking ? 1 : 0 if defined $self->_picking;
454 return $self->keys_available;
455 }
456  
457 sub raw {
458 my ($self) = @_;
459 return $self->keyboard->raw;
460 }
461  
462 sub keys_available {
463 my ($self) = @_;
464 return $self->keyboard->keys_available;
465 }
466  
467 sub enter_raw {
468 my ($self) = @_;
469 return $self->keyboard->enter_raw ? $self : undef;
470 }
471  
472 sub leave_raw {
473 my ($self) = @_;
474 $self->keyboard->leave_raw;
475 return $self;
476 }
477  
478 sub read_key {
479 my ($self) = @_;
480 return $self->keyboard->read_key;
481 }
482  
483 sub preview {
484 my ($self, $view, $move) = @_;
485  
486 my $trial = $view->{layout}->clone;
487 my $play = $trial->place($move->{tile}, $move->{arm});
488  
489 return ({
490 %$view,
491 layout => $trial,
492 count => Game::Dominoes::Scoring::count($trial),
493 ends => [ $trial->open_ends ],
494 }, $play);
495 }
496  
497 sub picker {
498 my ($self, $moves, $at) = @_;
499  
500 my @items = map {
501 my $label = sprintf '%-8s %s', $_->{tile}->stringify . '@' . $_->{arm},
502 $_->{points} ? "scores $_->{points}" : '';
503 $label =~ s/\s+\z//;
504 +{ label => $label, value => $_ };
505 } @$moves;
506  
507 return Game::Terminal::Kit::Picker->new(
508 items => \@items,
509 window => $WINDOW,
510 game_keys => { %PICK_KEY, %{ $self->history->game_keys } },
511 log => $self->log,
512 screen => $self->_in_step,
513 (defined $at ? (at => $at) : ()),
514 );
515 }
516  
517 sub choice_lines {
518 my ($self, $moves, $at) = @_;
519 return $self->_rows($self->picker($moves, $at));
520 }
521  
522 sub _rows {
523 my ($self, $picker) = @_;
524 return map { /\A\s+\d+ further / ? " $_" : " $_" } $picker->rows;
525 }
526  
527 sub legend {
528 return (
529 'arrows to choose, enter to play, a number to jump to it',
530 'v for the table as it stands, ? for the commands, t to type, q to quit',
531 'u to take back your last move, r to play it again',
532 );
533 }
534  
535 sub pick {
536 my ($self, $view) = @_;
537  
538 my $seat = $view->{seat};
539 my $moves = $self->game->legal($seat);
540  
541 return $self->_typed_turn($view) unless @$moves;
542  
543 unless ($self->enter_raw) {
544 $self->picking(0);
545 return $self->_typed_turn($view);
546 }
547  
548 my $picker = $self->picker($moves);
549 my $log = $self->log;
550 my $live = 0;
551  
552 $self->screen->clear(scrollback => 1);
553  
554 while (1) {
555 $self->_show_choice($view, $picker, $live);
556  
557 my ($event, $value) = $picker->step($self->read_key);
558  
559 if ($event eq 'quit') {
560 $self->leave_raw;
561 $self->quit(1);
562 return 0;
563 }
564  
565 if ($event eq 'chosen') {
566 $self->leave_raw;
567 return $self->_play($seat, $value);
568 }
569  
570 if ($event eq 'back' || ($event eq 'none' && @{ $log->notes })) {
571 $log->shown->note('that key does nothing here. ? for the ones that do');
572 next;
573 }
574  
575 next unless $event eq 'key';
576  
577 if ($value eq 'live') { $live = !$live; next }
578 if ($value eq 'help') { $log->note($self->help); next }
579 if ($value eq 'undo' || $value eq 'redo') {
580 my $moved = $value eq 'undo' ? $self->take_back : $self->play_again;
581 next unless $moved;
582 $self->leave_raw;
583 return 1;
584 }
585  
586 $self->leave_raw;
587 $self->picking(0) if $value eq 'type';
588 return $self->_typed_turn($view);
589 }
590 }
591  
592 sub _show_choice {
593 my ($self, $view, $picker, $live) = @_;
594  
595 my $log = $self->log;
596 my $move = $picker->current;
597  
598 my @lines = ('', "hand $view->{hand_number} " . $self->_scores_line($view),
599 $self->_hands_line($view));
600  
601 if (my @said = $self->recent_lines) {
602 push @lines, '', map { " $_" } @said;
603 }
604  
605 my ($shown, $title);
606 if ($live) {
607 $shown = $view;
608 $title = ' the table as it stands:';
609 }
610 else {
611 my ($peek) = $self->preview($view, $move);
612 $shown = $peek;
613 $title = ' if you play ' . $move->{tile}->stringify
614 . ' on ' . $move->{arm} . ':';
615 }
616  
617 push @lines, '', $title, $self->table($shown, $live ? undef : {
618 %{ $self->table_marks },
619 $move->{tile}->id => 'preview',
620 });
621 push @lines, '';
622 push @lines, $self->_ends_line($shown) if $shown->{layout}->count;
623  
624 push @lines, '', $self->hand_lines($view), '', $self->_rows($picker);
625  
626 if (my @notice = @{ $log->notes }) {
627 push @lines, '', map { " $_" } @notice;
628 }
629  
630 push @lines, '', map { " $_" } $self->legend;
631  
632 $self->screen->show(\@lines);
633 $log->shown;
634  
635 return;
636 }
637  
638 sub _typed_turn {
639 my ($self, $view) = @_;
640 $self->show($view);
641 $self->_say($_) for $self->_legal_lines($view);
642 my $line = $self->_ask("seat $view->{seat}> ");
643 return $self->command($line, $view);
644 }
645  
646 sub _legal_lines {
647 my ($self, $view) = @_;
648 my $moves = $self->game->legal($view->{seat});
649 return (' (nothing to play)') unless @$moves;
650 my $i = 0;
651 return map {
652 my $line = sprintf(' %2d. %-8s %s', ++$i,
653 $_->{tile}->stringify . '@' . $_->{arm},
654 $_->{points} ? "scores $_->{points}" : '');
655 $line =~ s/\s+\z//;
656 $line;
657 } @$moves;
658 }
659  
660 sub command {
661 my ($self, $line, $view) = @_;
662 my $game = $self->game;
663 my $seat = $view->{seat};
664  
665 return 0 unless defined $line;
666 $line =~ s/\A\s+//;
667 $line =~ s/\s+\z//;
668 return 1 unless length $line;
669  
670 my ($word, @rest) = split /\s+/, $line;
671 $word = lc $word;
672  
673 if ($word eq 'quit' || $word eq 'q') { $self->quit(1); return 0 }
674 if ($word eq 'help' || $word eq '?') { $self->_say($_) for $self->help; return 1 }
675 if ($word eq 'table' || $word eq 'board') { $self->_say($_) for $self->table($view); return 1 }
676 if ($word eq 'hand' || $word eq 'tiles') {
677 $self->_say($_) for $self->hand_lines($view);
678 return 1;
679 }
680 if ($word eq 'ends' || $word eq 'count') { $self->_say($self->_ends_line($view)); return 1 }
681 if ($word eq 'scores') { $self->_say($self->_scores_line($view)); return 1 }
682 if ($word eq 'legal' || $word eq 'moves') { $self->_say($_) for $self->_legal_lines($view); return 1 }
683 if ($word eq 'ascii') { $self->ascii(!$self->ascii); $self->_in_step->utf8; return 1 }
684 if ($word eq 'type') { $self->picking(0); return 1 }
685  
686 if ($word eq 'pick') {
687 if ($self->keys_available) {
688 $self->picking(1);
689 return $self->pick($view);
690 }
691 $self->_say('the keys are not available here, so this game is typed.'
692 . ' Term::ReadKey and a terminal are what it takes');
693 return 1;
694 }
695  
696 if ($word eq 'compact') { $self->compact(!$self->compact); return 1 }
697 if ($word eq 'colour' || $word eq 'color') { $self->colour(!$self->colour); return 1 }
698 if ($word eq 'history' || $word eq 'log') { $self->_say($game->to_text); return 1 }
699 if ($word eq 'undo') { $self->take_back; return 1 }
700 if ($word eq 'redo') { $self->play_again; return 1 }
701  
702 if ($word eq 'hint') {
703 my $bot = Game::Dominoes::Bot->new(level => 4, seed => 1);
704 my $move = $bot->choose($game, $seat);
705 $self->_say($move
706 ? 'try ' . $move->{tile}->stringify . '@' . $move->{arm}
707 : 'nothing to suggest');
708 return 1;
709 }
710  
711 if ($word eq 'play' || $word eq 'p') { return $self->_play($seat, join(' ', @rest)) }
712  
713 return $self->_play($seat, $line) if $line =~ /\A[0-6]-[0-6]/;
714  
715 if ($word =~ /\A\d+\z/) {
716 my $moves = $game->legal($seat);
717 my $pick = $moves->[ $word - 1 ];
718 unless ($pick) { $self->_say('no such move'); return 1 }
719 return $self->_play($seat, $pick);
720 }
721  
722 $self->_say("I do not know '$word'. Try help.");
723 return 1;
724 }
725  
726 sub _play {
727 my ($self, $seat, $move) = @_;
728  
729 if (!ref $move && $move =~ /\A([0-6]-[0-6])\s+([LRUDlrud])\z/) {
730 $move = "$1\@" . uc $2;
731 }
732  
733 if (!ref $move && $move =~ /\A([0-6]-[0-6])\z/) {
734 my $want = Game::Dominoes::Notation::parse_tile($1);
735 my @fit = grep { $_->{tile}->id == $want->id } @{ $self->game->legal($seat) };
736  
737 if (@fit > 1) {
738 $self->_say('which arm? ' . join(' ',
739 map { $_->{tile}->stringify . '@' . $_->{arm} } @fit));
740 return 1;
741 }
742 $move = @fit ? { tile => $want, arm => $fit[0]{arm} } : { tile => $want };
743 }
744  
745 my $out = $self->game->play($seat, $move);
746 if (ref $out eq 'Game::Dominoes::Error') {
747 $self->_say('no: ' . $out->message);
748 return 1;
749 }
750 $self->remember($seat, $out);
751 $self->_say('played ' . $out->tile->stringify . ' on ' . $out->arm
752 . ($out->points ? ' for ' . $out->points : ''));
753 return 1;
754 }
755  
756 sub help {
757 return (
758 ' play <tile> [arm] or just 6-4, or the number from `legal`',
759 ' legal table hand ends scores history hint',
760 ' undo redo take back your last move and the replies to it, or play it again',
761 ' pick type ascii colour compact quit',
762 ' arms are L and R along the line, U and D off the spinner',
763 ' a double is laid crosswise, which is how the table is drawn',
764 ' a tile in a heavy frame is one played since you last looked',
765 );
766 }
767  
768 sub _handover {
769 my ($self, $seat) = @_;
770 return 1 unless $self->handover;
771 $self->_say('');
772 $self->_say(('') x 30);
773 my $line = $self->_ask("Pass to seat $seat, then press return: ");
774 return defined $line ? 1 : 0;
775 }
776  
777 sub person_turn {
778 my ($self) = @_;
779 my $game = $self->game;
780 my $events = $game->history;
781 my ($drew, $dealt);
782 for my $event (@{$events}[ $self->_seen .. $#$events ]) {
783 $drew = 1 if $event->{kind} eq 'draw' && !$self->bots->{ $event->{seat} };
784 $dealt = 1 if $event->{kind} eq 'hand_end';
785 }
786 $self->_seen(scalar @$events);
787 $self->history->turn($game);
788 return $self unless $drew || $dealt;
789  
790 $self->history->clear;
791 $self->_once($drew ? 'draw' : 'deal', $drew
792 ? 'Drawing from the boneyard: nothing before it can be taken back.'
793 : 'A new hand: nothing before it can be taken back.');
794 return $self;
795 }
796  
797 sub take_back {
798 my ($self) = @_;
799 my $game = $self->history->undo;
800 unless ($game) {
801 $self->_remark('There is nothing to take back.');
802 return 0;
803 }
804 $self->swap($game);
805 $self->_remark('Taken back.');
806 return 1;
807 }
808  
809 sub play_again {
810 my ($self) = @_;
811 my $game = $self->history->redo;
812 unless ($game) {
813 $self->_remark('There is nothing to play again.');
814 return 0;
815 }
816 $self->swap($game);
817 $self->_remark('Played again.');
818 return 1;
819 }
820  
821 sub swap {
822 my ($self, $game) = @_;
823 $self->game($game);
824 $self->_seen(scalar @{ $game->history });
825 $self->log->forget;
826 $self->recent([]);
827 my @plays = grep { $_->{kind} eq 'play' } @{ $game->history };
828 splice @plays, 0, @plays - $game->players if @plays > $game->players;
829 $self->remember($_->{seat}, $_->{play}) for @plays;
830 return $self;
831 }
832  
833 sub _remark {
834 my ($self, $text) = @_;
835 return $self->log->note($text) if $self->picking;
836 $self->_say($text);
837 return $self;
838 }
839  
840 sub _once {
841 my ($self, $what, $text) = @_;
842 return $self if $self->_told->{$what}++;
843 return $self->_remark($text);
844 }
845  
846 sub start {
847 my ($self) = @_;
848 my $game = $self->game;
849 $self->history->start($game);
850 $self->_seen(scalar @{ $game->history });
851  
852 $self->_say('Dominoes: All Fives, ' . $game->players . ' seats, to ' . $game->target);
853 $self->_say('Type help for the commands.');
854  
855 my $last_seat;
856 while ($self->game->status eq 'active' && !$self->quit) {
857 $game = $self->game;
858 my $seat = $game->turn;
859 last unless defined $seat;
860  
861 if (my $bot = $self->bots->{$seat}) {
862 my $move = $bot->choose($game, $seat) or last;
863 my $out = $game->play($seat, $move);
864 last if ref $out eq 'Game::Dominoes::Error';
865 $self->remember($seat, $out);
866 $self->_say("seat $seat played " . $out->tile->stringify
867 . ' on ' . $out->arm . ($out->points ? ' for ' . $out->points : ''));
868 next;
869 }
870  
871 if (!defined $last_seat || $last_seat != $seat) {
872 last unless $self->_handover($seat);
873 $last_seat = $seat;
874 }
875  
876 $self->person_turn;
877 my $view = $game->view($seat);
878  
879 if ($self->picking) {
880 last unless $self->pick($view);
881 next;
882 }
883  
884 last unless $self->_typed_turn($view);
885 }
886  
887 $game = $self->game;
888 if (my $result = $game->result) {
889 $self->_say('');
890 $self->_say($result->stringify);
891 return $result;
892 }
893  
894 $self->_say('');
895 $self->_say('stopped');
896 return $game->result;
897 }
898  
899 sub _usage {
900 return <<'USAGE';
901 dominoes - draw dominoes with All Fives scoring
902  
903 dominoes [options]
904  
905 --players=N 2, 3 or 4 (default 2)
906 --seat=N which seat the human takes (default 1)
907 --hotseat every seat is a person, with a hand-over between turns
908 --bot-vs-bot nobody is a person
909 --level=N bot level 1 to 5, repeatable, one per bot seat
910 --target=N default 250 at two seats, 200 at three or four
911 --scale=N divide every score, for the cribbage board variation
912 (use --scale=5 --target=61 together, never one alone)
913 --variant=S all_fives, draw or block
914 --reserve=N tiles at the back of the boneyard nobody may draw
915 --seed=S reproduce a game exactly
916 --ascii plain ASCII only
917 --compact tiles as [6|4] on one line instead of drawn
918 --width=N what the drawn table may use before it wraps (default: the
919 terminal's width)
920 --colour force colour on or off (--nocolour)
921 --nopick type the moves out instead of choosing them with the keys
922 --version print the version
923 --help this
924  
925 Arms are L and R along the main line, U and D off the spinner.
926  
927 On a terminal the legal moves are listed under the table and chosen with
928 the arrow keys: the table above the list is the one the move under the
929 cursor would make, with its new count and what it would score, so a
930 placement is seen before it is played. Enter plays it, v shows the table as
931 it stands, t goes back to typing and ? prints the commands. Needs
932 Term::ReadKey; without it, or off a terminal, the moves are typed out.
933  
934 u takes back your last move and every reply to it, and r plays them again;
935 typed, they are undo and redo. Nothing before a tile you drew from the
936 boneyard, or before a new hand, can be taken back.
937  
938 The tile each seat just played is marked on the table, because at four
939 seats three of them land between your turns.
940  
941 Exit status is 0 if your seat won or nobody was playing a seat, 1 if you
942 lost or stopped early, 2 for a bad option.
943 USAGE
944 }
945  
946 sub _bad {
947 my ($why) = @_;
948 $why =~ s/ at \S+ line \d+\.?\s*\z//;
949 $why =~ s/\A[\w:]+: //;
950 chomp $why;
951 print {\*STDERR} "dominoes: $why\n";
952 return 2;
953 }
954  
955 sub options {
956 return [
957 { name => 'players', type => 'int', min => 2, max => 4, help => 'seats at the table' },
958 { name => 'seat', type => 'int', min => 1, max => 4, help => 'which seat you take' },
959 { name => 'level', type => 'int', min => 1, max => 5, help => "the bots' level" },
960 { name => 'variant', type => 'enum', choices => [qw(all_fives draw block)], help => 'the rules' },
961 { name => 'target', type => 'int', min => 50, max => 500, help => 'the score that wins' },
962 { name => 'hotseat', type => 'flag', help => 'every seat is a person' },
963 { name => 'bot-vs-bot', type => 'flag', help => 'nobody is a person' },
964 { name => 'seed', type => 'str', help => 'reproduce a game exactly' },
965 ];
966 }
967  
968 sub run {
969 my ($class, @argv) = @_;
970 my $saved = Getopt::Long::Configure(qw(bundling no_ignore_case));
971 my $status = $class->_run(\@argv);
972 Getopt::Long::Configure($saved);
973 return $status;
974 }
975  
976 sub _run {
977 my ($class, $argv) = @_;
978 my %opt = (players => 2, seat => 1, level => [], variant => 'all_fives');
979  
980 Getopt::Long::GetOptionsFromArray($argv,
981 'players=i' => \$opt{players},
982 'seat=i' => \$opt{seat},
983 'hotseat' => \$opt{hotseat},
984 'bot-vs-bot' => \$opt{botonly},
985 'level=i@' => $opt{level},
986 'target=i' => \$opt{target},
987 'scale=i' => \$opt{scale},
988 'variant=s' => \$opt{variant},
989 'seed=s' => \$opt{seed},
990 'reserve=i' => \$opt{reserve},
991 'ascii' => \$opt{ascii},
992 'compact' => \$opt{compact},
993 'width=i' => \$opt{width},
994 'colour!' => \$opt{colour},
995 'color!' => \$opt{colour},
996 'pick!' => \$opt{pick},
997 'version' => \$opt{version},
998 'help|h|?' => \$opt{help},
999 ) or do { print {\*STDERR} _usage(); return 2 };
1000  
1001 if ($opt{help}) { print _usage(); return 0 }
1002  
1003 if ($opt{version}) {
1004 print "dominoes (Game::Dominoes) $Game::Dominoes::VERSION\n";
1005 return 0;
1006 }
1007  
1008 if (@{$argv}) {
1009 print {\*STDERR} "dominoes: there is nothing to do with '$argv->[0]': options begin with --\n", _usage();
1010 return 2;
1011 }
1012  
1013 return _bad('--players must be 2, 3 or 4') unless $opt{players} =~ /\A[234]\z/;
1014 return _bad("--seat must be a seat from 1 to $opt{players}")
1015 unless $opt{seat} =~ /\A\d+\z/
1016 && $opt{seat} >= 1 && $opt{seat} <= $opt{players};
1017  
1018 my $seed = defined $opt{seed}
1019 ? substr(($opt{seed} x 32), 0, 32)
1020 : pack('N8', map { int rand 2**32 } 1 .. 8);
1021  
1022 my $game = eval {
1023 Game::Dominoes->new(
1024 seed => $seed,
1025 players => $opt{players},
1026 variant => $opt{variant},
1027 (defined $opt{target} ? (target => $opt{target}) : ()),
1028 (defined $opt{scale} ? (scale => $opt{scale}) : ()),
1029 (defined $opt{reserve} ? (reserve => $opt{reserve}) : ()),
1030 );
1031 };
1032  
1033 return _bad($@ || 'could not deal') unless $game;
1034  
1035 my @bot_seats =
1036 $opt{hotseat} ? ()
1037 : $opt{botonly} ? ($game->seats)
1038 : (grep { $_ != $opt{seat} } $game->seats);
1039  
1040 my @levels = @{ $opt{level} };
1041 my %bots;
1042 my $i = 0;
1043 for my $seat (@bot_seats) {
1044 my $level = $levels[$i] // $levels[-1] // 3;
1045 $bots{$seat} = Game::Dominoes::Bot->new(level => $level, seed => $seat * 7919);
1046 $i++;
1047 }
1048  
1049 my $terminal = eval {
1050 $class->new(
1051 game => $game,
1052 bots => \%bots,
1053 (defined $opt{colour} ? (colour => $opt{colour}) : ()),
1054 ($opt{ascii} ? (ascii => 1) : ()),
1055 ($opt{compact} ? (compact => 1) : ()),
1056 (defined $opt{width} ? (width => $opt{width}) : ()),
1057 (defined $opt{pick} ? (picking => $opt{pick} ? 1 : 0) : ()),
1058 );
1059 };
1060  
1061 return _bad($@ || 'could not start') unless $terminal;
1062  
1063 my $result = Game::Terminal::Kit::Run::guard(
1064 sub { $terminal->start }, $terminal->keyboard, $terminal->screen,
1065 );
1066  
1067 return 1 unless $result;
1068 return 0 if $opt{hotseat} || $opt{botonly};
1069 return 0 if grep { $_ == $opt{seat} } @{ $result->winners };
1070 return 1;
1071 }
1072  
1073 1;
1074  
1075 __END__
« Dominoes/Result.pm ↑ Summary Dominoes/Tile.pm »