Gin/Terminal.pm untested

filter: Statementstmt 0.0% 0 / 589 Branchbran 0.0% 0 / 306 Conditioncond 0.0% 0 / 115 MC/DCmcdc 0.0% 0 / 67 Subroutinesub 0.0% 0 / 81 Podpod 0.0% 0 / 64 totaltotal 0.0% 0 / 1222 CC 154 SCAR 46.2
CC
154
Cov
0%
human_move
462.0
run
306.0
pick_discard
156.0
CRAP 101.9
1 package Game::Gin::Terminal;
2  
3 use strict;
4 use warnings;
5  
6 use Object::Proto::Sugar -types;
7  
8 use Digest::SHA ();
9  
10 use Game::Gin ();
11 use Game::Gin::Bot ();
12 use Game::Gin::Card qw(name_of long_name_of id_of deadwood_of rank_of suit_of);
13 use Game::Gin::Deadwood qw(best deadwood KNOCK_AT);
14 use Game::Gin::Search ();
15 use Game::Terminal::Kit::Choose;
16 use Game::Terminal::Kit::Keys;
17 use Game::Terminal::Kit::Log;
18 use Game::Terminal::Kit::Picker;
19 use Game::Terminal::Kit::Run;
20 use Game::Terminal::Kit::Screen;
21 use Getopt::Long ();
22  
23 our $VERSION = '0.04';
24  
25 our @RANK_TEXT = ('', 'A', 2 .. 9, '10', 'J', 'Q', 'K');
26  
27 our %SUIT = (
28 S => { wide => "\x{2660}", ascii => 'S', colour => '90' },
29 H => { wide => "\x{2665}", ascii => 'H', colour => '31' },
30 D => { wide => "\x{2666}", ascii => 'D', colour => '31' },
31 C => { wide => "\x{2663}", ascii => 'C', colour => '90' },
32 );
33  
34 use constant {
35 CARD_WIDTH => 11,
36 FAN_WIDTH => 4,
37 };
38  
39 our %MARK_INK = (
40 drew => '1;32',
41 took => '1;36',
42 cursor => '1;7',
43 );
44  
45 our %FRAME = (
46 plain => {
47 wide => [ "\x{250C}", "\x{2510}", "\x{2514}", "\x{2518}",
48 "\x{2500}", "\x{2502}" ],
49 ascii => [ '+', '+', '+', '+', '-', '|' ],
50 },
51 fresh => {
52 wide => [ "\x{2554}", "\x{2557}", "\x{255A}", "\x{255D}",
53 "\x{2550}", "\x{2551}" ],
54 ascii => [ '#', '#', '#', '#', '=', '#' ],
55 },
56 cursor => {
57 wide => [ "\x{250F}", "\x{2513}", "\x{2517}", "\x{251B}",
58 "\x{2501}", "\x{2503}" ],
59 ascii => [ '>', '>', '>', '>', '=', '!' ],
60 },
61 );
62  
63 our %MARK_FRAME = (
64 drew => 'fresh',
65 took => 'fresh',
66 cursor => 'cursor',
67 );
68  
69 has game => (is => 'rw', isa => Any);
70 has out => (is => 'ro', isa => Any);
71 has in => (is => 'ro', isa => Any);
72 has mode => (is => 'ro', isa => Str);
73 has level => (is => 'ro', isa => Int);
74 has seat => (is => 'ro', isa => Str);
75 has ascii => (is => 'ro', isa => Any);
76 has colour => (is => 'ro', isa => Any);
77 has quit => (is => 'rw', isa => Any);
78 has keyboard => (is => 'rw', isa => Any);
79 has screen => (is => 'rw', isa => Any);
80 has log => (is => 'rw', isa => Any);
81 has marks => (is => 'rw', isa => HashRef, default => {});
82 has _keysource => (is => 'rw', isa => Any, init_arg => 'keysource');
83 has _pending => (is => 'rw', isa => ArrayRef, default => [], init_arg => 'pending');
84 has _picking => (is => 'rw', isa => Any, init_arg => 'picking');
85 has _staring => (is => 'rw', isa => Any, init_arg => 'interactive');
86  
87 sub _out { return $_[0]->out || \*STDOUT }
88 sub _in { return $_[0]->in || \*STDIN }
89 sub _mode { return $_[0]->mode || 'bot' }
90 sub _level { return $_[0]->level || 2 }
91 sub _seat { return $_[0]->seat || 'p1' }
92 sub _ascii { return $_[0]->ascii ? 1 : 0 }
93  
94 sub BUILD {
95 my ($self) = @_;
96  
97 my $colour = defined $self->colour ? ($self->colour ? 1 : 0)
98 : ((eval { -t $self->_out }
99 && !Game::Terminal::Kit::Screen::no_colour()) ? 1 : 0);
100  
101 $self->keyboard($self->_new_keyboard) unless $self->keyboard;
102 $self->screen(Game::Terminal::Kit::Screen->new(
103 out => $self->_out,
104 colour => $colour,
105 ascii => $self->_ascii,
106 (defined $self->_staring ? (interactive => $self->_staring ? 1 : 0) : ()),
107 )) unless $self->screen;
108 $self->log(Game::Terminal::Kit::Log->new(keep => 2)) unless $self->log;
109  
110 $self->screen->utf8->flush_on;
111 return $self;
112 }
113  
114 sub _new_keyboard {
115 my ($self) = @_;
116 return Game::Terminal::Kit::Keys->new(
117 in => $self->_in,
118 pending => $self->_pending,
119 ($self->_keysource ? (keysource => $self->_keysource) : ()),
120 );
121 }
122  
123 sub paint {
124 my ($self, $text, $code) = @_;
125 return $self->screen->paint($text, $code);
126 }
127  
128 sub say_to { my ($self, @what) = @_; $self->screen->say(join '', @what); return }
129  
130 sub interactive { return $_[0]->screen->interactive ? 1 : 0 }
131  
132 sub picking {
133 my ($self, @set) = @_;
134 $self->_picking($set[0] ? 1 : 0) if @set;
135 return $self->_picking ? 1 : 0 if defined $self->_picking;
136 return $self->keys_available;
137 }
138  
139 sub keysource {
140 my ($self, @set) = @_;
141 return $self->keyboard->keysource unless @set;
142  
143 $self->_keysource($set[0]);
144 if ($set[0]) {
145 $self->keyboard->keysource($set[0]);
146 return $set[0];
147 }
148  
149 $self->keyboard->leave_raw;
150 $self->keyboard($self->_new_keyboard);
151 return $set[0];
152 }
153  
154 sub pending { return $_[0]->keyboard->pending }
155  
156 sub raw { return $_[0]->keyboard->raw ? 1 : 0 }
157  
158 sub keys_available { return $_[0]->keyboard->keys_available }
159  
160 sub enter_raw { return $_[0]->keyboard->enter_raw ? $_[0] : undef }
161  
162 sub leave_raw { $_[0]->keyboard->leave_raw; return $_[0] }
163  
164 sub read_key { return $_[0]->keyboard->read_key }
165  
166 sub clear {
167 my ($self) = @_;
168 $self->screen->clear(scrollback => 1);
169 return $self;
170 }
171  
172 sub handover {
173 my ($self, $seat) = @_;
174 return 1 unless $self->_mode eq 'hotseat';
175  
176 my $question = "pass the keyboard to $seat, then press return";
177  
178 $self->clear;
179 $self->say_to('') for 1 .. ($self->interactive ? 0 : 30);
180  
181 unless ($self->picking && $self->enter_raw) {
182 $self->say_to($question);
183 return defined $self->ask('') ? 1 : 0;
184 }
185  
186 my $ready = Game::Terminal::Kit::Choose->new(
187 question => $question,
188 choices => [ [ 1, "$seat has it" ] ],
189 legend => [ '', 'enter when they do, q to stop' ],
190 screen => $self->screen,
191 );
192 $ready->picker->numbered(0);
193  
194 while (1) {
195 my ($event) = $ready->run($self->keyboard, $self->screen);
196 return 1 if $event eq 'chosen';
197 return 0 if $event eq 'quit';
198 }
199 }
200  
201 sub ask {
202 my ($self, $prompt) = @_;
203 return $self->keyboard->read_line($prompt, $self->_out);
204 }
205  
206 sub pretty {
207 my ($self, $id) = @_;
208 return '-' unless defined $id;
209 my $suit = $SUIT{ suit_of($id) };
210 return $self->paint(
211 $RANK_TEXT[ rank_of($id) ] . $suit->{ $self->_ascii ? 'ascii' : 'wide' },
212 $suit->{colour}
213 );
214 }
215  
216 sub _card_rows {
217 my ($self, $id, $mark) = @_;
218 my $rank = $RANK_TEXT[ rank_of($id) ];
219 my $suit = $SUIT{ suit_of($id) };
220 my $pip = $suit->{ $self->_ascii ? 'ascii' : 'wide' };
221 my $set = $FRAME{ ($mark && $MARK_FRAME{$mark}) || 'plain' };
222 my ($tl, $tr, $bl, $br, $h, $v)
223 = @{ $set->{ $self->_ascii ? 'ascii' : 'wide' } };
224  
225 return ([
226 $tl . ($h x 9) . $tr,
227 $v . sprintf('%-9s', $rank) . $v,
228 $v . sprintf('%-9s', $pip) . $v,
229 $v . (' ' x 9) . $v,
230 $v . ' ' . $pip . ' ' . $v,
231 $v . (' ' x 9) . $v,
232 $v . sprintf('%9s', $pip) . $v,
233 $v . sprintf('%9s', $rank) . $v,
234 $bl . ($h x 9) . $br,
235 ], $suit->{colour});
236 }
237  
238 sub card_art {
239 my ($self, $id, $mark) = @_;
240 my ($rows, $colour) = $self->_card_rows($id, $mark);
241 my $ink = $mark && $MARK_INK{$mark} ? $MARK_INK{$mark} : $colour;
242 return [ map { $self->paint($_, $ink) } @$rows ];
243 }
244  
245 sub card_space {
246 my ($self) = @_;
247 my ($h, $v) = $self->_ascii ? ('-', ':') : ("\x{2504}", "\x{250A}");
248 return [ map { $self->paint($_, '90') } (
249 ' ' . ($h x 9) . ' ',
250 (map { $v . (' ' x 9) . $v } 1 .. 7),
251 ' ' . ($h x 9) . ' ',
252 ) ];
253 }
254  
255 sub card_back {
256 my ($self) = @_;
257 my ($tl, $tr, $bl, $br, $h, $v, $fill) = $self->_ascii
258 ? ('+', '+', '+', '+', '-', '|', '#')
259 : ("\x{250C}", "\x{2510}", "\x{2514}", "\x{2518}", "\x{2500}", "\x{2502}", "\x{2591}");
260 return [
261 $tl . ($h x 9) . $tr,
262 (map { $v . ($fill x 9) . $v } 1 .. 7),
263 $bl . ($h x 9) . $br,
264 ];
265 }
266  
267 sub fan {
268 my ($self, $ids, $marks) = @_;
269 return [ ('') x 9 ] unless $ids && @$ids;
270 $marks ||= {};
271 my @out = ('') x 9;
272 for my $i (0 .. $#$ids) {
273 my $mark = $marks->{ $ids->[$i] };
274 my ($rows, $colour) = $self->_card_rows($ids->[$i], $mark);
275 my $ink = $mark && $MARK_INK{$mark} ? $MARK_INK{$mark} : $colour;
276 my $last = $i == $#$ids;
277 for my $row (0 .. 8) {
278 my $part = $last ? $rows->[$row] : substr $rows->[$row], 0, FAN_WIDTH;
279 $out[$row] .= $self->paint($part, $ink);
280 }
281 }
282 return \@out;
283 }
284  
285 sub fan_width {
286 my ($self, $n) = @_;
287 return 0 unless $n;
288 return (($n - 1) * FAN_WIDTH) + CARD_WIDTH;
289 }
290  
291 sub _beside {
292 my ($self, $gap, @blocks) = @_;
293 my $height = 0;
294 for my $block (@blocks) {
295 $height = scalar @{ $block->{lines} } if @{ $block->{lines} } > $height;
296 }
297 my @rows = ('') x $height;
298 for my $i (0 .. $#blocks) {
299 my $block = $blocks[$i];
300 for my $row (0 .. $height - 1) {
301 $rows[$row] .= ' ' x $gap if $i;
302 my $line = $block->{lines}[$row];
303 $rows[$row] .= defined $line ? $line : ' ' x $block->{width};
304 }
305 }
306 s/\s+\z// for @rows;
307 return @rows;
308 }
309  
310 sub render {
311 my ($self, $seat, $without, $marks) = @_;
312 my $deal = $self->game->deal;
313 my $hand = $deal->hand_of($seat);
314  
315 my @cards = @{ $hand->cards };
316 @cards = grep { $_ != $without } @cards if defined $without;
317 my $melding = best(\@cards);
318  
319 my @lines;
320 push @lines, sprintf('deal %d, dealt by %s', $deal->number, $deal->dealer);
321 push @lines, sprintf('score p1 %d p2 %d (to %d)',
322 $self->game->scores->{p1}, $self->game->scores->{p2},
323 $self->game->target);
324 push @lines, '';
325 push @lines, $self->table_lines($deal, $seat);
326 push @lines, '';
327 push @lines, $self->hand_lines($melding, $marks);
328 push @lines, $self->knock_line($melding);
329 return \@lines;
330 }
331  
332 sub knock_line {
333 my ($self, $melding) = @_;
334 return $melding->{deadwood} <= KNOCK_AT
335 ? sprintf('you may knock (%d)', $melding->{deadwood})
336 : sprintf('%d to go before you may knock', $melding->{deadwood} - KNOCK_AT);
337 }
338  
339 sub preview {
340 my ($self, $seat, $card) = @_;
341 my @rest = grep { $_ != $card } @{ $self->game->deal->hand_of($seat)->cards };
342 return best(\@rest);
343 }
344  
345 sub fan_items {
346 my ($self, $seat) = @_;
347  
348 my (%playable, %knock);
349 for my $move (@{ $self->game->deal->legal($seat) }) {
350 next unless $move->{kind} eq 'discard';
351 $playable{ $move->{card} } = 1;
352 $knock{ $move->{card} } = 1 if $move->{knock};
353 }
354  
355 my $groups = $self->hand_groups(best($self->game->deal->hand_of($seat)->cards));
356  
357 my @out;
358 for my $group (@$groups) {
359 for my $card (@{ $group->{cards} }) {
360 push @out, {
361 label => $self->pretty($card),
362 skip => $playable{$card} ? 0 : 1,
363 value => {
364 card => $card,
365 knock => $knock{$card} ? 1 : 0,
366 loose => $group->{loose},
367 },
368 };
369 }
370 }
371  
372 return \@out;
373 }
374  
375 sub choice_cards {
376 my ($self, $seat) = @_;
377 return [ map { $_->{value} } grep { !$_->{skip} } @{ $self->fan_items($seat) } ];
378 }
379  
380 sub first_loose {
381 my ($self, $choices) = @_;
382 my ($at) = grep { $choices->[$_]{loose} } 0 .. $#$choices;
383 return defined $at ? $at : 0;
384 }
385  
386 sub discard_picker {
387 my ($self, $seat, $big) = @_;
388 return Game::Terminal::Kit::Picker->new(
389 items => $self->fan_items($seat),
390 prefer => sub { $_[0]{value}{loose} },
391 across => 1,
392 numbered => 0,
393 window => 0,
394 screen => $self->screen,
395 game_keys => {
396 q => 'stop',
397 k => 'knock',
398 v => 'remeld',
399 '?' => 'help',
400 ($big ? (g => 'big_gin') : ()),
401 },
402 );
403 }
404  
405 sub legend {
406 my ($self, $choice) = @_;
407 my @key = ('left and right to choose', 'enter to discard');
408 push @key, 'k to discard and knock' if $choice && $choice->{knock};
409 push @key, '? for the rest', 'q to stop';
410 return join ', ', @key;
411 }
412  
413 sub pick_discard {
414 my ($self, $seat) = @_;
415  
416 my $legal = $self->game->deal->legal($seat);
417 my ($big) = grep { $_->{kind} eq 'big_gin' } @$legal;
418  
419 my $picker = $self->discard_picker($seat, $big);
420 return undef unless defined $picker->current;
421  
422 my $remelded = 0;
423  
424 while (1) {
425 my $choice = $picker->current;
426 $self->show_choice($seat, $choice, $big, $remelded);
427  
428 my ($event, $value) = $picker->step($self->read_key);
429 next if $event eq 'moved';
430 return undef if $event eq 'quit';
431 return { kind => 'discard', card => $value->{card} } if $event eq 'chosen';
432  
433 $value = '' unless $event eq 'key';
434  
435 if ($value eq 'stop') { $self->quit(1); return undef }
436  
437 if ($value eq 'knock') {
438 return { kind => 'discard', card => $choice->{card}, knock => 1 }
439 if $choice->{knock};
440 $self->log->note('you cannot knock on that one');
441 next;
442 }
443  
444 if ($value eq 'big_gin') { return $big }
445  
446 if ($value eq 'remeld') { $remelded = !$remelded; next }
447 if ($value eq 'help') { $self->log->note($self->help_lines); next }
448  
449 $self->log->note('that key does nothing here. ? for the ones that do');
450 }
451 }
452  
453 sub _frame {
454 my ($self, @body) = @_;
455 my $log = $self->log;
456  
457 my @lines = ('');
458 push @lines, (map { @$_ } @{ $log->recent }), '' if @{ $log->recent };
459 push @lines, @body;
460 push @lines, '', map { ' ' . $_ } @{ $log->notes } if @{ $log->notes };
461  
462 $log->shown;
463 return @lines;
464 }
465  
466 sub show_choice {
467 my ($self, $seat, $choice, $big, $remelded) = @_;
468  
469 my $card = $choice->{card};
470 my @body;
471  
472 if ($remelded) {
473 push @body, @{ $self->render($seat, $card) }, '',
474 ' that is the hand WITHOUT ' . $self->pretty($card)
475 . '. v puts it back.';
476 }
477 else {
478 my %mark = (%{ $self->marks }, $card => 'cursor');
479 push @body, @{ $self->render($seat, undef, \%mark) }, '',
480 ' ' . $self->without_line($seat, $choice);
481 }
482  
483 push @body, ' big gin is there for the taking: press g' if $big;
484  
485 $self->clear;
486 $self->screen->say($self->_frame(@body), '', ' ' . $self->legend($choice));
487 return;
488 }
489  
490 sub without_line {
491 my ($self, $seat, $choice) = @_;
492 my $melding = $self->preview($seat, $choice->{card});
493 my $line = 'throw ' . $self->pretty($choice->{card})
494 . ' and your count is ' . $melding->{deadwood};
495 $line .= ', which lets you knock' if $choice->{knock};
496 return $line;
497 }
498  
499 sub help_lines {
500 return (
501 'left and right walk your hand. the card under the cursor is the one',
502 'you would throw, and the line under the fan says what it leaves you.',
503 'enter discards it. k discards it and knocks, when that is allowed.',
504 'v shows the hand remelded without it. g declares big gin when it is',
505 'offered. q stops. ? is this.',
506 );
507 }
508  
509 sub table_lines {
510 my ($self, $deal, $seat) = @_;
511 my $upcard = $deal->upcard;
512 my @label = (
513 sprintf('stock %d', $deal->stock_left),
514 defined $upcard ? 'upcard ' . $self->pretty($upcard) : 'no upcard',
515 );
516  
517 my @blocks = ({
518 width => CARD_WIDTH,
519 lines => $deal->stock_left ? $self->card_back : $self->card_space,
520 }, {
521 width => CARD_WIDTH,
522 lines => defined $upcard
523 ? $self->card_art($upcard, $self->marks->{$upcard})
524 : $self->card_space,
525 });
526  
527 my $head = sprintf('%-*s', CARD_WIDTH + 5, $label[0]) . $label[1];
528 return ($head, $self->_beside(5, @blocks));
529 }
530  
531 sub hand_groups {
532 my ($self, $melding) = @_;
533 my @group;
534 for my $meld (@{ $melding->{melds} }) {
535 my @cards = sort { $a <=> $b } @$meld;
536 my $same = 1;
537 $same &&= rank_of($_) == rank_of($cards[0]) for @cards;
538 push @group, {
539 cards => \@cards,
540 label => $same ? 'set' : 'run',
541 loose => 0,
542 };
543 }
544 push @group, {
545 cards => [ sort { $a <=> $b } @{ $melding->{unmatched} } ],
546 label => 'loose ' . $melding->{deadwood},
547 loose => 1,
548 } if @{ $melding->{unmatched} };
549 return \@group;
550 }
551  
552 sub hand_lines {
553 my ($self, $melding, $marks) = @_;
554 my @group = @{ $self->hand_groups($melding) };
555  
556 my @ids = map { @{ $_->{cards} } } @group;
557 return ('you are holding nothing') unless @ids;
558  
559 my @lines = @{ $self->fan(\@ids, $marks || $self->marks) };
560 push @lines, $self->_brackets(\@group, scalar @ids);
561 return @lines;
562 }
563  
564 sub _brackets {
565 my ($self, $groups, $total) = @_;
566 my ($h, $bl, $br) = $self->_ascii
567 ? ('-', '+', '+') : ("\x{2500}", "\x{2514}", "\x{2518}");
568 my $line = '';
569 my $seen = 0;
570 for my $group (@$groups) {
571 my $n = scalar @{ $group->{cards} };
572 $seen += $n;
573 my $width = $seen == $total ? $self->fan_width($n) : $n * FAN_WIDTH;
574 my $label = $group->{label};
575 $label = '' if length($label) + 4 > $width;
576 my $rule = $width - 2 - length $label;
577 my $left = int($rule / 2);
578 $line .= $self->paint(
579 $bl . ($h x $left) . $label . ($h x ($rule - $left)) . $br, '90'
580 );
581 }
582 return $line;
583 }
584  
585 sub show { my ($self, $seat) = @_; $self->say_to($_) for @{ $self->render($seat) }; return }
586  
587 sub card_named {
588 my ($self, $text) = @_;
589 return undef unless defined $text;
590 $text =~ s/\s+//g;
591 for my $suit (keys %SUIT) {
592 my $pip = $SUIT{$suit}{wide};
593 $text =~ s/\Q$pip\E/$suit/g;
594 }
595 $text =~ s/\A10/T/;
596 return id_of($text);
597 }
598  
599 sub bot_move { my ($self, $seat) = @_;
600 return Game::Gin::Bot->new(level => $self->_level)->choose($self->game, $seat) }
601  
602 sub is_human {
603 my ($self, $seat) = @_;
604 my $mode = $self->_mode;
605 return 0 if $mode eq 'watch';
606 return 1 if $mode eq 'hotseat';
607 return $seat eq $self->_seat ? 1 : 0;
608 }
609  
610 sub human_move {
611 my ($self, $seat) = @_;
612 my $deal = $self->game->deal;
613 my $legal = $deal->legal($seat);
614 my $phase = $deal->phase;
615  
616 if ($phase eq 'forced_draw') { return { kind => 'draw' } }
617  
618 return $self->pick_move($seat, $phase, $legal) if $self->picking;
619  
620 if ($phase eq 'upcard') {
621 my $a = $self->ask('take the ' . $self->pretty($deal->upcard) . '? (y/n) ');
622 return undef unless defined $a;
623 return undef if $self->_stopping($a);
624 return { kind => $a =~ /^y/i ? 'take' : 'pass' };
625 }
626 if ($phase eq 'draw') {
627 my $a = $self->ask('(d)raw or (t)ake ' . $self->pretty($deal->upcard) . '? ');
628 return undef unless defined $a;
629 return undef if $self->_stopping($a);
630 return { kind => $a =~ /^t/i ? 'take' : 'draw' };
631 }
632  
633 my ($big) = grep { $_->{kind} eq 'big_gin' } @$legal;
634 if ($big) {
635 my $a = $self->ask('big gin! declare it? (y/n) ');
636 return $big if defined $a && $a =~ /^y/i;
637 }
638  
639 while (1) {
640 my $a = $self->ask('discard which card? (e.g. KH, or KH! to knock) ');
641 return undef unless defined $a;
642 return undef if $self->_stopping($a);
643  
644 if ($a =~ /\A\s*(?:\?|h|help)\s*\z/i) {
645 $self->say_to($_) for $self->typed_help;
646 next;
647 }
648  
649 my $knock = $a =~ s/!\s*$//;
650 my $card = $self->card_named($a);
651 unless (defined $card) { $self->say_to('not a card'); next }
652 my ($move) = grep { $_->{kind} eq 'discard' && $_->{card} == $card
653 && (($_->{knock} ? 1 : 0) == ($knock ? 1 : 0)) } @$legal;
654 return $move if $move;
655 $self->say_to($knock ? 'you cannot knock on that' : 'you are not holding that');
656 }
657 }
658  
659 sub _stopping {
660 my ($self, $answer) = @_;
661 return 0 unless defined $answer && $answer =~ /\A\s*(?:q|quit|exit)\s*\z/i;
662 $self->quit(1);
663 return 1;
664 }
665  
666 sub typed_help {
667 return (
668 'name a card to discard it: KH, or 10H, or K with the pip itself.',
669 'add a ! to knock with it: KH!',
670 'quit stops. ? is this.',
671 );
672 }
673  
674 sub pick_move {
675 my ($self, $seat, $phase, $legal) = @_;
676  
677 unless ($self->enter_raw) {
678 $self->picking(0);
679 return $self->human_move($seat);
680 }
681  
682 return $self->pick_draw($seat, $phase) if $phase eq 'upcard' || $phase eq 'draw';
683 return $self->pick_discard($seat);
684 }
685  
686 sub pick_draw {
687 my ($self, $seat, $phase) = @_;
688  
689 my $deal = $self->game->deal;
690 my $upcard = $deal->upcard;
691  
692 while (1) {
693 my @body = (@{ $self->render($seat) }, '',
694 ' u takes the ' . $self->pretty($upcard)
695 . ', d draws from the stock'
696 . ($phase eq 'upcard' ? ', n passes it up' : ''));
697  
698 $self->clear;
699 $self->screen->say($self->_frame(@body), '', ' ? for the rest, q to stop');
700  
701 my $key = $self->read_key;
702 return undef if !defined $key || $key eq 'eof' || $key eq 'interrupt';
703 if ($key eq 'q') { $self->quit(1); return undef }
704  
705 return { kind => 'take' } if $key eq 'u' || $key eq 't';
706  
707 if ($key eq 'd') {
708 return { kind => 'draw' } if $phase eq 'draw';
709 $self->log->note('on the first turn it is take it or pass it up: u or n');
710 next;
711 }
712  
713 if ($key eq 'n' || $key eq 'p') {
714 return { kind => 'pass' } if $phase eq 'upcard';
715 $self->log->note('you cannot pass now: u to take it, d to draw');
716 next;
717 }
718  
719 if ($key eq '?') {
720 $self->log->note($phase eq 'upcard'
721 ? 'u takes the upcard, n passes it up. that is the whole choice.'
722 : 'u takes the upcard, d draws the card nobody has seen.');
723 next;
724 }
725  
726 $self->log->note('that key does nothing here. ? for the ones that do');
727 }
728 }
729  
730 sub play {
731 my ($self, %o) = @_;
732 my $seed = $o{seed} || Digest::SHA::sha256(join ':', 'gin', $$, time, rand);
733 $self->game(Game::Gin->build(seed => $seed, dealer => $o{dealer} || 'p1'));
734  
735 $self->say_to(sprintf('deal %d, dealt by %s',
736 $self->game->number, $self->game->dealer))
737 if $self->_mode eq 'watch';
738  
739 my $limit = $o{limit} || 20_000;
740 my $moves = 0;
741 my $last_seat;
742 while (!$self->game->over && !$self->quit && $moves++ < $limit) {
743 my $seat = $self->game->turn or last;
744 my $number = $self->game->number;
745  
746 my $move;
747 if ($self->is_human($seat)) {
748 if (!defined $last_seat || $last_seat ne $seat) {
749 last unless $self->handover($seat);
750 $last_seat = $seat;
751 }
752 $self->show($seat) unless $self->picking;
753 $move = $self->human_move($seat);
754 last unless $move;
755 }
756 else {
757 $move = $self->bot_move($seat);
758 last unless $move;
759 }
760  
761 my %held = $self->is_human($seat)
762 ? (map { $_ => 1 } @{ $self->game->deal->hand_of($seat)->cards })
763 : ();
764  
765 my @out = $self->game->apply($seat, $move);
766 if (ref $out[0] eq 'Game::Gin::Error') { $self->say_to($out[0]->message); next }
767 $self->remember($seat, \%held, \@out);
768 $self->log->record(grep { defined } map { $self->told($_) } @out);
769 $self->announce($_) for @out;
770 $self->say_to('') if $self->game->number != $number;
771 }
772  
773 $self->leave_raw;
774  
775 $self->announce_result;
776 return $self->game;
777 }
778  
779 sub remember {
780 my ($self, $seat, $held, $out) = @_;
781  
782 my $discard = grep { $_->{kind} eq 'discard' } @$out;
783 my $deal = $self->game->deal;
784  
785 if ($discard) {
786 my $upcard = $deal->upcard;
787 $self->marks(defined $upcard && !$self->is_human($seat)
788 ? { $upcard => 'took' } : {});
789 return $self;
790 }
791  
792 return $self->marks({}) unless $self->is_human($seat);
793  
794 my $hand = $deal->hand_of($seat) or return $self->marks({});
795 my $took = grep { $_->{kind} eq 'take' } @$out;
796  
797 my %mark;
798 for my $card (@{ $hand->cards }) {
799 next if $held->{$card};
800 $mark{$card} = $took ? 'took' : 'drew';
801 }
802  
803 $self->marks(\%mark);
804 return $self;
805 }
806  
807 sub told {
808 my ($self, $out) = @_;
809 my $k = $out->{kind};
810 return "$out->{seat} takes " . $self->pretty($out->{card}) if $k eq 'take';
811 return "$out->{seat} draws" if $k eq 'draw';
812 return "$out->{seat} passes" if $k eq 'pass';
813 return "$out->{seat} discards " . $self->pretty($out->{card})
814 . ($out->{knock} ? ' and knocks' : '') if $k eq 'discard';
815 return "$out->{seat} declares big gin" if $k eq 'big_gin';
816 return 'the stock ran out: the hand is cancelled' if $k eq 'cancelled';
817 if ($k eq 'hand_end') {
818 return sprintf('%s wins the hand by %s, %d points',
819 $out->{winner}, $out->{how} // '?', $out->{points})
820 if $out->{winner};
821 return 'the hand is over';
822 }
823 return sprintf('deal %d, dealt by %s', $out->{number}, $out->{dealer})
824 if $k eq 'deal';
825 return undef;
826 }
827  
828 sub announce {
829 my ($self, $out) = @_;
830 my $line = $self->told($out);
831 $self->say_to($line) if defined $line;
832 return;
833 }
834  
835 sub announce_result {
836 my ($self) = @_;
837 my $r = $self->game->result or return $self->say_to('unfinished');
838 $self->say_to(sprintf('%s wins: %d to %d%s',
839 $r->{winner} // 'nobody',
840 $r->{totals}{ $r->{winner} // 'p1' },
841 $r->{totals}{ $r->{loser} // 'p2' },
842 $r->{shutout} ? ', a shutout' : ''));
843 return;
844 }
845  
846 sub _usage {
847 return <<'USAGE';
848 gin - gin rummy at a prompt
849  
850 gin play the bot as p1
851 gin --seat p2 play the bot as p2
852 gin --mode hotseat two people at one keyboard
853 gin --mode watch two bots, and you read
854 gin --level 1 a weaker opponent (1 or 2)
855 gin --seed tuesday deal the same game every time
856 gin --ascii letters instead of the suit pips
857 gin --nocolour no colour (NO_COLOR does the same)
858 gin --nopick type the moves out instead of pointing at them
859  
860 Your hand is fanned like a hand of cards, with a bracket under each meld
861 saying whether it is a set or a run and what the rest of it is costing you.
862  
863 On a terminal you point at the card you mean: the left and right keys walk
864 your own hand, and the fan above shows what the hand WOULD be without the
865 card under the cursor, remelded, with the deadwood that leaves you. Enter
866 discards it, k discards and knocks when that is allowed, u takes the upcard,
867 d draws, ? lists the keys and q stops. Needs Term::ReadKey; without it, or
868 off a terminal, every move is typed.
869  
870 Typed instead: answer y or n for the upcard, d or t to draw or take, and name
871 a card to discard it (KH). Add a ! to knock with it (KH!). What the card
872 itself says is taken too, so the suit pip and 10H work as well as KH and TH.
873 Type quit to stop, or help for the rest.
874  
875 The card you just drew or took is marked in your hand, and so is the upcard
876 when your opponent took it rather than drawing.
877  
878 Exit status is 0 if your seat won, or if nobody was playing a seat, 1 if you
879 lost or stopped early, and 2 for a bad option.
880 USAGE
881 }
882  
883 sub options {
884 return [
885 { name => 'mode', type => 'enum', choices => [qw(bot hotseat watch)], help => 'you against the bot, two people, or two bots' },
886 { name => 'level', type => 'int', min => 1, max => 2, help => "the bot's strength" },
887 { name => 'seat', type => 'enum', choices => [qw(p1 p2)], help => 'your seat' },
888 { name => 'seed', type => 'str', help => 'deal the same game every time' },
889 ];
890 }
891  
892 sub run {
893 my ($class, @argv) = @_;
894 my %o = (mode => 'bot', level => 2, seat => 'p1');
895  
896 my $ok = eval {
897 local $SIG{__WARN__} = sub { print STDERR "gin: $_[0]" };
898 Getopt::Long::GetOptionsFromArray(\@argv,
899 'mode=s' => \$o{mode},
900 'level=i' => \$o{level},
901 'seat=s' => \$o{seat},
902 'seed=s' => \$o{seed},
903 'ascii' => \$o{ascii},
904 'colour!' => \$o{colour},
905 'color!' => \$o{colour},
906 'pick!' => \$o{pick},
907 'help' => \$o{help},
908 );
909 };
910 if (!$ok) { print STDERR _usage(); return 2 }
911 if ($o{help}) { print _usage(); return 0 }
912 if (@argv) { print STDERR "gin: not an option: $argv[0]\n", _usage(); return 2 }
913  
914 my $levels = Game::Gin::Search::LEVELS;
915 my $refused
916 = $o{mode} !~ /\A(?:bot|hotseat|watch)\z/ ? 'mode must be bot, hotseat or watch'
917 : $o{seat} !~ /\A p[12] \z/x ? 'seat must be p1 or p2'
918 : !($o{level} =~ /\A\d+\z/ && $o{level} >= 1 && $o{level} <= $levels)
919 ? "level must be 1 to $levels"
920 : undef;
921 if (defined $refused) { print STDERR "gin: $refused\n", _usage(); return 2 }
922  
923 my $seed = defined $o{seed} ? Digest::SHA::sha256($o{seed}) : undef;
924  
925 my $ui = $class->new(
926 mode => $o{mode},
927 level => $o{level},
928 seat => $o{seat},
929 ($o{ascii} ? (ascii => 1) : ()),
930 (defined $o{colour} ? (colour => $o{colour}) : ()),
931 (defined $o{pick} ? (picking => $o{pick} ? 1 : 0) : ()),
932 );
933  
934 my $game = Game::Terminal::Kit::Run::guard(
935 sub { $ui->play(defined $seed ? (seed => $seed) : ()) },
936 $ui->keyboard, $ui->screen,
937 );
938  
939 my $result = $game && $game->result;
940 return 1 unless $result;
941 return 0 if $o{mode} eq 'watch' || $o{mode} eq 'hotseat';
942 return 0 if ($result->{winner} // '') eq $o{seat};
943 return 1;
944 }
945  
946  
947 1;
948  
949 __END__