Durak/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
« Durak.pm ↑ Summary
1 package Game::Durak::Terminal;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶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::Durak ();
9 use Game::Durak::Bot ();
10 use Game::Durak::Card qw(name_of long_name_of suit_of rank_of face_of);
11 use Game::Durak::Table ();
12 use Getopt::Long ();
13 use Game::Terminal::Kit::Keys ();
14 use Game::Terminal::Kit::Log ();
15 use Game::Terminal::Kit::Picker ();
16 use Game::Terminal::Kit::Run ();
17 use Game::Terminal::Kit::Screen ();
18  
19 our $VERSION = '0.04';
20  
21 my %SUIT = (
22 S => { wide => "\x{2660}", ascii => 'S', colour => '37' },
23 H => { wide => "\x{2665}", ascii => 'H', colour => '31' },
24 D => { wide => "\x{2666}", ascii => 'D', colour => '31' },
25 C => { wide => "\x{2663}", ascii => 'C', colour => '37' },
26 );
27  
28 my %SAID = (
29 attack => 'attack with',
30 beat => 'beat it with',
31 take => 'take the bout',
32 done => 'are done',
33 swap => 'exchange the trump six',
34 resign => 'give up',
35 );
36  
37 my %STEER = map { $_ => 1 }
38 qw(left right up down tab back_tab home end page_up page_down);
39  
40 has game => (is => 'rw', isa => Any);
41 has out => (is => 'ro', isa => Any);
42 has in => (is => 'ro', isa => Any);
43 has seed => (is => 'ro', isa => Str);
44 has level => (is => 'ro', isa => Int);
45 has seat => (is => 'ro', isa => Int);
46 has ascii => (is => 'ro', isa => Any);
47 has colour => (is => 'ro', isa => Any);
48 has paint => (is => 'ro', isa => Any);
49 has width => (is => 'ro', isa => Int);
50 has height => (is => 'ro', isa => Int);
51 has keyboard => (is => 'rw', isa => Any);
52 has screen => (is => 'rw', isa => Any);
53 has log => (is => 'rw', isa => Any);
54  
55 has keysource => (is => 'rw', isa => Any);
56  
57 has pending => (is => 'rw', isa => ArrayRef, default => sub { [] });
58  
59 has _picking => (is => 'rw', isa => Any, init_arg => 'picking');
60  
61 has _table => (is => 'rw', isa => Any);
62  
63 sub _out { return $_[0]->out || \*STDOUT }
64 sub _in { return $_[0]->in || \*STDIN }
65 sub _level { return defined $_[0]->level ? $_[0]->level : 3 }
66 sub _seat { return defined $_[0]->seat ? $_[0]->seat : 1 }
67 sub _ascii { return $_[0]->ascii ? 1 : 0 }
68 sub _them { return 3 - $_[0]->_seat }
69  
70 sub BUILD {
71 my ($self) = @_;
72 my $out = $self->_out;
73 my $colour = defined $self->colour ? ($self->colour ? 1 : 0)
74 : ((eval { -t $out } && !Game::Terminal::Kit::Screen::no_colour()) ? 1 : 0);
75 my $paint = defined $self->paint ? ($self->paint ? 1 : 0) : $colour;
76 $self->keyboard(Game::Terminal::Kit::Keys->new(
77 in => $self->_in,
78 pending => $self->pending,
79 ($self->keysource ? (keysource => $self->keysource) : ()),
80 )) unless $self->keyboard;
81 $self->screen(Game::Terminal::Kit::Screen->new(
82 out => $out,
83 interactive => $paint,
84 colour => $colour,
85 ascii => $self->_ascii,
86 )) unless $self->screen;
87 $self->log(Game::Terminal::Kit::Log->new) unless $self->log;
88 $self->screen->utf8->flush_on;
89 return $self;
90 }
91  
92 sub _colour { return $_[0]->screen->colour ? 1 : 0 }
93 sub _paint { return $_[0]->screen->interactive ? 1 : 0 }
94  
95 sub table_of {
96 my ($self) = @_;
97 my $table = $self->_table;
98 return $table if $table;
99 $table = Game::Durak::Table->new(
100 width => $self->width || 80,
101 height => $self->height || 24,
102 ascii => $self->ascii,
103 );
104 $self->_table($table);
105 return $table;
106 }
107  
108 sub frame {
109 my ($self, $view, %o) = @_;
110 my $table = $self->table_of;
111 my $grid = $table->screen($view, %o);
112 return $self->_colour ? $table->paint($grid) : $table->lines($grid);
113 }
114  
115 sub headline {
116 my ($self, $room) = @_;
117 my @said = @{ $self->log->notes };
118 return '' unless @said;
119 my $latest = $said[-1];
120 my $line = '';
121 while (@said) {
122 my $next = pop @said;
123 my $grown = length $line ? "$next, $line" : $next;
124 last if length $grown > $room;
125 $line = $grown;
126 }
127 $line = substr($latest, 0, $room) unless length $line;
128 return $line;
129 }
130  
131 sub show {
132 my ($self, $view, %o) = @_;
133 my $handle = $self->_out;
134 my $screen = $self->screen;
135 my $table = $self->table_of;
136 my $footer = defined $o{footer} ? $o{footer} : '';
137 my $lines = $self->frame($view,
138 header => (defined $o{header} ? $o{header} : $self->headline($table->width - 2)),
139 footer => $footer,
140 (defined $o{cursor} ? (cursor => $o{cursor}) : ()),
141 );
142 $screen->at(1, 1);
143 print {$handle} join("\n", @$lines);
144 $screen->at($table->height, length($footer) + 3);
145 $self->log->shown;
146 return;
147 }
148  
149 sub told {
150 my ($self, @lines) = @_;
151 return unless @lines;
152 if ($self->_paint) {
153 $self->log->note(@lines);
154 return;
155 }
156 $self->say(" $_") for @lines;
157 return;
158 }
159  
160 sub say {
161 my ($self, @what) = @_;
162 $self->screen->say(join '', @what);
163 return;
164 }
165  
166 sub card {
167 my ($self, $id) = @_;
168 return '--' unless defined $id;
169 my $suit = suit_of($id);
170 my $face = face_of($id)
171 . ($self->_ascii ? $SUIT{$suit}{ascii} : $SUIT{$suit}{wide});
172 return $face unless $self->_colour;
173 return "\e[$SUIT{$suit}{colour}m$face\e[0m";
174 }
175  
176 sub hand_line {
177 my ($self, $hand, $cursor) = @_;
178 my $n = 0;
179  
180 return join ' ', map { ++$n . ') ' . $self->card($_) } @$hand
181 unless defined $cursor;
182  
183 return join ' ', map {
184 $n++;
185 ($cursor == $n ? '>' : ' ') . $n . ') ' . $self->card($_);
186 } @$hand;
187 }
188  
189 sub bout_line {
190 my ($self, $bout) = @_;
191 return 'nothing on the table' unless $bout && @{ $bout->{pairs} };
192 return join ' ', map {
193 $self->card($_->{attack}) . ' / ' . $self->card($_->{beat})
194 } @{ $bout->{pairs} };
195 }
196  
197 sub table {
198 my ($self, $view, %o) = @_;
199  
200 my @lines;
201 push @lines, '';
202 push @lines, sprintf 'trump %s%s talon %d heap %d they hold %d',
203 $self->card_suit($view->{trump}),
204 (defined $view->{trump_card}
205 ? ' (' . $self->card($view->{trump_card}) . ' face up)' : ''),
206 $view->{talon}, $view->{discard},
207 $view->{counts}{ 3 - $view->{seat} };
208 push @lines, '';
209 push @lines, ' ' . $self->bout_line($view->{bout});
210 push @lines, '';
211 push @lines, ' ' . $self->hand_line($view->{hand}, $o{cursor});
212 return join "\n", @lines;
213 }
214  
215 sub card_suit {
216 my ($self, $suit) = @_;
217 my $face = $self->_ascii ? $SUIT{$suit}{ascii} : $SUIT{$suit}{wide};
218 return $self->_colour ? "\e[$SUIT{$suit}{colour}m$face\e[0m" : $face;
219 }
220  
221 sub playable {
222 my ($self, $view) = @_;
223 my %card = map { $_->{card} => 1 }
224 grep { defined $_->{card} } @{ $view->{legal} };
225 my @at;
226 my $n = 0;
227 for my $held (@{ $view->{hand} }) {
228 $n++;
229 push @at, $n if $card{$held};
230 }
231 return \@at;
232 }
233  
234 sub prompt_for {
235 my ($self, $view) = @_;
236 my %kinds = map { $_->{kind} => 1 } @{ $view->{legal} };
237 my @what;
238  
239 my $playable = $self->playable($view);
240 push @what, '[' . join(' ', @$playable) . '] a card' if @$playable;
241  
242 push @what, 't take' if $kinds{take};
243 push @what, 'd done' if $kinds{done};
244 push @what, 'x exchange' if $kinds{swap};
245 push @what, 'r resign';
246 push @what, 'q quit';
247 return join ' ', @what;
248 }
249  
250 sub keys_available {
251 my ($self) = @_;
252 return $self->keyboard->keys_available;
253 }
254  
255 sub picking {
256 my ($self, @set) = @_;
257 $self->_picking($set[0] ? 1 : 0) if @set;
258 return $self->_picking ? 1 : 0 if defined $self->_picking;
259 return $self->keys_available;
260 }
261  
262 sub raw {
263 my ($self) = @_;
264 return $self->keyboard->raw;
265 }
266  
267 sub enter_raw {
268 my ($self) = @_;
269 return $self->keyboard->enter_raw ? $self : undef;
270 }
271  
272 sub leave_raw {
273 my ($self) = @_;
274 $self->keyboard->leave_raw;
275 return $self;
276 }
277  
278 sub read_key {
279 my ($self) = @_;
280 return $self->keyboard->read_key;
281 }
282  
283 sub card_line {
284 my ($self, $view, $card) = @_;
285  
286 my ($move) = grep { defined $_->{card} && $_->{card} == $card }
287 @{ $view->{legal} };
288 return $self->card($card) . ': not one you can play' unless $move;
289  
290 my $trump = suit_of($card) eq $view->{trump} ? ', a trump' : '';
291 my $bout = $view->{bout};
292  
293 if ($move->{kind} eq 'defend') {
294 my $beats = defined $bout && defined $bout->{unbeaten}
295 ? ' the ' . $self->card($bout->{unbeaten}) : ' the attack';
296 return $self->card($card) . ": beats$beats$trump";
297 }
298  
299 my $room = defined $bout ? ($bout->{cap} - $bout->{size}) : 0;
300 my $with = $room > 1 ? sprintf ', %d more could follow', $room - 1
301 : $room == 1 ? ', the last this bout can hold' : '';
302  
303 return $self->card($card) . ": they must beat it$trump$with";
304 }
305  
306 sub pick_keys {
307 return 'arrows to choose, enter to play, ? for the keys';
308 }
309  
310 sub pick_help {
311 return (
312 'arrows walk the cards you may play, enter plays the one under the cursor',
313 'the line above says what it would do',
314 't take, d done, x exchange, r resign, q quit',
315 );
316 }
317  
318 sub picker {
319 my ($self, $view) = @_;
320  
321 my %move = map { $_->{card} => $_ }
322 reverse grep { defined $_->{card} } @{ $view->{legal} };
323  
324 my @items;
325 for my $slot (@{ $self->playable($view) }) {
326 my $card = $view->{hand}[ $slot - 1 ];
327 push @items, {
328 label => $self->card($card),
329 value => $move{$card},
330 card => $card,
331 slot => $slot,
332 };
333 }
334  
335 return Game::Terminal::Kit::Picker->new(
336 items => \@items,
337 numbered => 0,
338 window => 0,
339 game_keys => {
340 t => 'take', d => 'done', x => 'swap', r => 'resign', '?' => 'help',
341 (map { ($_ => $_) } 1 .. 9),
342 },
343 );
344 }
345  
346 sub pick_move {
347 my ($self, $view) = @_;
348  
349 my $picker = $self->picker($view);
350 my $items = $picker->items;
351  
352 my %by;
353 push @{ $by{ $_->{kind} } }, $_ for @{ $view->{legal} };
354  
355 my @notice;
356  
357 while (1) {
358 my $item = @$items ? $items->[ $picker->at ] : undef;
359  
360 $self->told(@notice) if @notice;
361 @notice = ();
362 $self->told($self->card_line($view, $item->{card})) if $item;
363  
364 $self->position($view,
365 cursor => ($item ? $item->{slot} : undef),
366 footer => $self->pick_keys);
367  
368 my $key = $self->read_key;
369 my ($event, $value) = $picker->step($key);
370  
371 return { kind => 'quit' } if $event eq 'quit';
372 return $value if $event eq 'chosen';
373 next if $event eq 'moved';
374  
375 if ($event eq 'key') {
376 return $by{$value}[0]
377 if $value =~ /\A(?:take|done|swap)\z/ && $by{$value};
378 return { kind => 'resign' } if $value eq 'resign';
379 if ($value eq 'help') { @notice = $self->pick_help; next }
380 if ($value =~ /\A[1-9]\z/) {
381 my ($found) = grep { $items->[$_]{slot} == $value } 0 .. $#$items;
382 if (defined $found) { $picker->jump($found); next }
383 @notice = ("you cannot play card $value");
384 next;
385 }
386 }
387  
388 @notice = ('that key does nothing here')
389 unless @$items && $STEER{$key};
390 }
391 }
392  
393 sub move_for {
394 my ($self, $view, $said) = @_;
395  
396 return undef unless defined $said;
397 $said =~ s/\A\s+|\s+\z//g;
398 return { kind => 'quit' } if lc $said eq 'q' || lc $said eq 'quit';
399  
400 my %by;
401 push @{ $by{ $_->{kind} } }, $_ for @{ $view->{legal} };
402  
403 return $by{take}[0] if lc $said eq 't' && $by{take};
404 return $by{done}[0] if lc $said eq 'd' && $by{done};
405 return $by{swap}[0] if lc $said eq 'x' && $by{swap};
406 return { kind => 'resign' } if lc $said eq 'r';
407  
408 return undef unless $said =~ /\A[0-9]+\z/ && $said >= 1;
409 my $card = $view->{hand}[ $said - 1 ];
410 return undef unless defined $card;
411  
412 my ($move) = grep {
413 defined $_->{card} && $_->{card} == $card
414 } @{ $view->{legal} };
415  
416 return $move;
417 }
418  
419 sub cards {
420 my ($self, $n) = @_;
421 return $n == 1 ? '1 card' : "$n cards";
422 }
423  
424 sub narration {
425 my ($self, $view, @events) = @_;
426 my $me = $view->{seat};
427 my @said;
428  
429 for my $event (@events) {
430 my $kind = $event->{kind};
431  
432 if ($SAID{$kind}) {
433 my $who = !defined $event->{seat} ? 'somebody'
434 : $event->{seat} == $me ? 'you' : 'they';
435 my $what = defined $event->{card}
436 ? ' ' . long_name_of($event->{card}) : '';
437 push @said, "$who $SAID{$kind}$what";
438 next;
439 }
440  
441 if ($kind eq 'bout_end') {
442 if ($event->{taken}) {
443 my $took = 3 - $event->{next_attacker};
444 push @said, sprintf '%s pick up %s',
445 $took == $me ? 'you' : 'they', $self->cards($event->{cards});
446 }
447 else {
448 push @said, sprintf 'the bout is beaten off, %s',
449 $self->cards($event->{cards});
450 }
451 next;
452 }
453  
454 if ($kind eq 'refill') {
455 next unless $event->{drawn}{1} || $event->{drawn}{2};
456 push @said, sprintf 'you draw %d, they draw %d, %d left',
457 $event->{drawn}{$me}, $event->{drawn}{ 3 - $me },
458 $event->{talon};
459 next;
460 }
461  
462 if ($kind eq 'out') {
463 push @said, $event->{seat} == $me ? 'you are out' : 'they are out';
464 next;
465 }
466  
467 if ($kind eq 'game_end') {
468 push @said, !defined $event->{fool} ? 'a draw, and no fool'
469 : $event->{fool} == $me ? 'you are the durak'
470 : 'they are the durak';
471 }
472 }
473  
474 return @said;
475 }
476  
477 sub narrate {
478 my ($self, $view, @events) = @_;
479 my @said = $self->narration($view, @events);
480 return unless @said;
481 $self->say('') if grep { $_ =~ /durak|a draw/ } @said;
482 $self->say(" $_") for @said;
483 return;
484 }
485  
486 sub start {
487 my ($self) = @_;
488 my $game = Game::Durak->build(seed => $self->seed);
489 die $game->message . "\n" if ref $game eq 'Game::Durak::Error';
490 $self->game($game);
491 return $game;
492 }
493  
494 sub play {
495 my ($self) = @_;
496  
497 my $game = $self->game || $self->start;
498 my $me = $self->_seat;
499 my $bot = Game::Durak::Bot->new(
500 level => Game::Durak::Bot->level_for($self->_level),
501 seed => ($self->seed || '') . ':bot',
502 );
503  
504 $self->open_screen($game);
505  
506 while (!$game->over) {
507 my $seat = $game->turn;
508 my $view = $game->view($seat);
509  
510 if ($seat != $me) {
511 my $move = $bot->choose($view);
512 last unless $move;
513 my @events = $game->apply($seat, $move);
514 last if ref $events[0] eq 'Game::Durak::Error';
515 $self->told($self->narration($game->view($me), @events));
516 next;
517 }
518  
519 my $move;
520 if ($self->picking && $self->enter_raw) {
521 $move = $self->pick_move($view);
522 last unless $move;
523 }
524 else {
525 $self->picking(0);
526 $self->position($view);
527  
528 my $said = $self->keyboard->read_line;
529 last unless defined $said;
530  
531 $move = $self->move_for($view, $said);
532 unless ($move) {
533 $self->told('that is not one of the answers');
534 next;
535 }
536 }
537  
538 last if $move->{kind} eq 'quit';
539  
540 my @events = $game->apply($seat, $move);
541 if (ref $events[0] eq 'Game::Durak::Error') {
542 $self->told($events[0]->message);
543 next;
544 }
545  
546 $self->told($self->narration($game->view($me), @events));
547 }
548  
549 $self->leave_raw;
550 $self->close_screen($game);
551  
552 return $game->result;
553 }
554  
555 sub open_screen {
556 my ($self, $game) = @_;
557  
558 if ($self->_paint) {
559 $self->screen->clear;
560 $self->told(sprintf 'durak: the loser is the fool, and seat %d opens',
561 $game->turn);
562 return;
563 }
564  
565 $self->say('durak: the loser is the fool');
566 $self->say('trump is ' . $self->card_suit($game->trump)
567 . ', and seat ' . $game->turn . ' opens');
568 return;
569 }
570  
571 sub position {
572 my ($self, $view, %o) = @_;
573  
574 my $footer = defined $o{footer} ? $o{footer} : $self->prompt_for($view);
575  
576 return $self->show($view, footer => $footer,
577 (defined $o{cursor} ? (cursor => $o{cursor}) : ()))
578 if $self->_paint;
579  
580 $self->say($self->table($view, %o));
581 $self->say(' ' . $footer);
582 return;
583 }
584  
585 sub close_screen {
586 my ($self, $game) = @_;
587 return unless $self->_paint;
588  
589 my $view = $game->view($self->_seat);
590 my $result = $game->result;
591 my $fool = $result ? $result->{fool} : undef;
592 my $over = !$result ? 'you left the table'
593 : !defined $fool ? 'a draw, and no fool'
594 : $fool == $self->_seat ? 'you are the durak'
595 : 'they are the durak';
596  
597 $self->show($view, header => $over, footer => 'the deal is over');
598 $self->screen->say("\e[0m");
599 return;
600 }
601  
602  
603 sub _usage {
604 return <<'USAGE';
605 usage: durak [--level 1-5] [--seat 1|2] [--seed STRING] [--ascii] [--no-colour]
606 [--no-paint] [--width N] [--height N]
607  
608 A deal of Podkidnoy Durak against the bot. You are the seat given by --seat
609 and the bot plays the other one. The seed decides the deal, and the same seed
610 deals the same cards every time.
611  
612 The table is drawn on one painted screen at a terminal and printed as plain
613 lines when the output is a pipe or a file. --paint and --no-paint say so
614 either way, and --width and --height fit the screen to a window that is not
615 eighty by twenty-four.
616  
617 At a terminal the arrow keys walk the cards you may play and the line above
618 the table says what the one under the cursor would do: whether they must beat
619 it, which attack it beats, whether it is a trump, and how much room the bout
620 has left. Enter plays it. The moves that are not cards keep their own keys.
621 Needs Term::ReadKey; --no-pick, or no terminal, numbers them at a prompt
622 instead.
623  
624 At the prompt, a number plays that card. t takes, d is done, x exchanges the
625 trump, r resigns and q (or quit) stops.
626  
627 Exit status is 0 if you won or the deal was stopped, 1 if you were the fool,
628 2 for an option the game will not take.
629 USAGE
630 }
631  
632 sub options {
633 return [
634 { name => 'level', type => 'int', min => 1, max => 5, help => 'how hard the bot plays' },
635 { name => 'seat', type => 'enum', choices => [qw(1 2)], help => 'your seat; the bot takes the other' },
636 { name => 'seed', type => 'str', help => 'the deal; the same seed deals the same cards' },
637 ];
638 }
639  
640 sub run {
641 my ($class, @argv) = @_;
642 my %opt = (level => 3, seat => 1);
643  
644 my $ok = eval {
645 local $SIG{__WARN__} = sub { print STDERR "durak: $_[0]" };
646 Getopt::Long::GetOptionsFromArray(\@argv, \%opt,
647 'level=i', 'seat=i', 'seed=s', 'ascii', 'colour!',
648 'paint!', 'pick!', 'width=i', 'height=i', 'help');
649 };
650 if (!$ok) { print STDERR _usage(); return 2 }
651 if ($opt{help}) { print _usage(); return 0 }
652 if (@argv) { print STDERR "durak: not an option: $argv[0]\n", _usage(); return 2 }
653  
654 my $levels = Game::Durak::Bot->ladder;
655 unless ($opt{seat} =~ /\A[12]\z/) {
656 print STDERR "durak: --seat must be 1 or 2, not '$opt{seat}'\n";
657 return 2;
658 }
659 unless ($opt{level} =~ /\A[0-9]+\z/ && $opt{level} >= 1 && $opt{level} <= $levels) {
660 print STDERR "durak: --level must be 1 to $levels, not '$opt{level}'\n";
661 return 2;
662 }
663  
664 my $said = defined $opt{seed} ? $opt{seed}
665 : join q{}, map { chr 97 + int rand 26 } 1 .. 32;
666 my $seed = sprintf q{%-32.32s}, $said;
667  
668 my $terminal = $class->new(
669 seed => $seed,
670 level => $opt{level},
671 seat => $opt{seat},
672 ascii => $opt{ascii},
673 colour => $opt{colour},
674 paint => $opt{paint},
675 width => $opt{width},
676 height => $opt{height},
677 (defined $opt{pick} ? (picking => $opt{pick} ? 1 : 0) : ()),
678 );
679  
680 my $result = Game::Terminal::Kit::Run::guard(
681 sub { $terminal->play }, $terminal->keyboard, $terminal->screen,
682 );
683 return 0 unless $result;
684  
685 $terminal->say('');
686 $terminal->say("the seed was $said");
687  
688 return 1 if ref $result eq 'HASH'
689 && defined $result->{fool} && $result->{fool} == $opt{seat};
690 return 0;
691 }
692  
693 1;
694  
695 __END__
« Durak.pm ↑ Summary