blib/lib/Game/Mahjong/Terminal.pm untested

filter: Statementstmt 0.0% 0 / 652 Branchbran 0.0% 0 / 326 Conditioncond 0.0% 0 / 144 MC/DCmcdc 0.0% 0 / 87 Subroutinesub 0.0% 0 / 66 Podpod 0.0% 0 / 49 totaltotal 0.0% 0 / 1324 CC 164 SCAR 44.4
CC
164
Cov
0%
tile_art
182.0
pick_discard
182.0
run
182.0
CRAP 84.8
1 package Game::Mahjong::Terminal;
2  
3 use 5.010;
4 use strict;
5 use warnings;
6  
7 use Object::Proto::Sugar -types;
8  
9 use Game::Mahjong;
10 use Game::Mahjong::Tiles;
11 use Game::Mahjong::Notation;
12 use Game::Mahjong::Rules;
13 use Game::Mahjong::Bot;
14 use Game::Mahjong::Fans;
15 use Game::Mahjong::Result;
16 use Getopt::Long ();
17 use Game::Terminal::Kit::Keys;
18 use Game::Terminal::Kit::Log;
19 use Game::Terminal::Kit::Picker;
20 use Game::Terminal::Kit::Run;
21 use Game::Terminal::Kit::Screen;
22  
23 our $VERSION = '0.04';
24  
25 has seed => (is => 'ro', isa => Str, required => 1);
26  
27 has level => (is => 'ro', isa => Int, default => 2);
28  
29 has seat => (is => 'ro', isa => Int, default => 0);
30  
31 has in => (is => 'ro', required => 1);
32  
33 has out => (is => 'ro', required => 1);
34  
35 has colour => (is => 'ro', default => 0);
36  
37 has glyphs => (is => 'ro', default => 0);
38  
39 has ascii => (is => 'ro', default => 0);
40  
41 has clear => (is => 'ro', default => 0);
42  
43 has auto => (is => 'ro', default => 0);
44  
45 has names => (is => 'ro', isa => ArrayRef, default => sub { [ 'You', 'Ada', 'Bram', 'Cho' ] });
46  
47 has rules => (is => 'rw');
48  
49 has bots => (is => 'rw', isa => ArrayRef, default => []);
50  
51 has hinter => (is => 'rw');
52  
53 has quit => (is => 'rw', default => 0);
54  
55 has finished => (is => 'rw', default => 0);
56  
57 has winner => (is => 'rw');
58  
59 has cursor => (is => 'rw');
60  
61 has [qw/keyboard screen log/] => (is => 'rw');
62  
63 has keysource => (is => 'rw');
64  
65 has pending => (is => 'rw', isa => ArrayRef, default => sub { [] });
66  
67 has _picking => (is => 'rw', init_arg => 'picking');
68  
69 our %SGR = (bold => 1, dim => 2, red => 31, green => 32, yellow => 33, blue => 34, magenta => 35, cyan => 36);
70  
71 our %WALK = map { $_ => 1 } qw(left right up down tab back_tab home end page_up page_down);
72  
73 our %WIND = (0 => 'East', 1 => 'South', 2 => 'West', 3 => 'North');
74 our $DOT = '|';
75  
76 sub _clear {
77 my ($self) = @_;
78 $self->screen->clear;
79 return;
80 }
81  
82 my %GLYPH;
83 BEGIN {
84 my @m = map { chr(0x1F007 + $_) } 0 .. 8;
85 my @p = map { chr(0x1F019 + $_) } 0 .. 8;
86 my @s = map { chr(0x1F010 + $_) } 0 .. 8;
87 my @w = (chr 0x1F000, chr 0x1F001, chr 0x1F002, chr 0x1F003);
88 my @d = (chr 0x1F004, chr 0x1F005, chr 0x1F006);
89 my @f = map { chr(0x1F022 + $_) } 0 .. 3;
90 my @t = map { chr(0x1F026 + $_) } 0 .. 3;
91 my $i = 1;
92 $GLYPH{ $i++ } = $_ for @m, @p, @s, @w, @d, @f, @t;
93 }
94  
95 sub BUILD {
96 my ($self) = @_;
97 die 'Game::Mahjong::Terminal: the seat is 0 to 3' unless $self->seat >= 0 && $self->seat <= 3;
98 die 'Game::Mahjong::Terminal: the level is 1 to 3' unless $self->level >= 1 && $self->level <= 3;
99 $self->rules(Game::Mahjong::Rules->new(seed => $self->seed));
100 $self->bots([ map { Game::Mahjong::Bot->new(level => $self->level, seed => $self->seed) } 0 .. 3 ]);
101 $self->hinter(Game::Mahjong::Bot->new(level => 3, seed => $self->seed . ':hint'));
102 $self->keyboard(Game::Terminal::Kit::Keys->new(
103 in => $self->in,
104 pending => $self->pending,
105 ($self->keysource ? (keysource => $self->keysource) : ()),
106 )) unless $self->keyboard;
107 $self->screen(Game::Terminal::Kit::Screen->new(
108 out => $self->out,
109 interactive => ($self->colour && $self->clear ? 1 : 0),
110 colour => ($self->colour ? 1 : 0),
111 ascii => ($self->ascii ? 1 : 0),
112 )) unless $self->screen;
113 $self->log(Game::Terminal::Kit::Log->new) unless $self->log;
114 return;
115 }
116  
117 sub _c {
118 my ($self, $code, $text) = @_;
119 return $self->screen->paint($text, $SGR{$code});
120 }
121  
122 our %HONOUR_FACE = (
123 we => 'E', ws => 'S', ww => 'W', wn => 'N',
124 dr => 'R', dg => 'G', dw => 'B',
125 );
126  
127 our %INK = (m => 196, p => 25, s => 29, f => 170, t => 178);
128 our %HONOUR_INK = (we => 240, ws => 240, ww => 240, wn => 240,
129 dr => 196, dg => 29, dw => 245);
130 our $FACE_BG = 230;
131 our $EDGE_FG = 180;
132 our $SIDE_FG = 137;
133 our $BACK_BG = 66;
134  
135 our $FRESH_FG = 28;
136  
137 our %FRAME = (
138 plain => {
139 wide => [ "\x{250c}", "\x{2510}", "\x{2514}", "\x{2518}",
140 "\x{2502}", "\x{2500}" ],
141 ascii => [ '+', '+', '+', '+', '|', '-' ],
142 },
143 fresh => {
144 wide => [ "\x{2554}", "\x{2557}", "\x{255a}", "\x{255d}",
145 "\x{2551}", "\x{2550}" ],
146 ascii => [ '#', '#', '#', '#', '#', '=' ],
147 },
148 cursor => {
149 wide => [ "\x{250f}", "\x{2513}", "\x{2517}", "\x{251b}",
150 "\x{2503}", "\x{2501}" ],
151 ascii => [ '+', '+', '+', '+', '!', '=' ],
152 },
153 );
154  
155 sub face {
156 my ($self, $kind) = @_;
157 return ' ' unless defined $kind;
158 return $GLYPH{$kind} if $self->glyphs;
159 my $code = Game::Mahjong::Tiles::code_of($kind);
160 return $HONOUR_FACE{$code} . ' ' if $HONOUR_FACE{$code};
161 my $text = Game::Mahjong::Notation::print($kind);
162 $text = substr($text, 0, 2) if length $text > 2;
163 return length $text == 1 ? "$text " : $text;
164 }
165  
166 sub _ink {
167 my ($self, $kind) = @_;
168 my $code = Game::Mahjong::Tiles::code_of($kind);
169 return $HONOUR_INK{$code} if $HONOUR_INK{$code};
170 return $INK{ substr($code, 0, 1) } // 240;
171 }
172  
173 sub tile_art {
174 my ($self, $kind, %o) = @_;
175 my $ascii = $self->ascii;
176 my $style = $o{cursor} ? 'cursor' : $o{mark} ? 'fresh' : 'plain';
177 my ($tl, $tr, $bl, $br, $v, $h)
178 = @{ $FRAME{$style}{ $ascii ? 'ascii' : 'wide' } };
179  
180 my $face = $o{back} ? ($ascii ? '##' : "\x{2592}\x{2592}") : $self->face($kind);
181  
182 my $bg = $o{back} ? $BACK_BG : $FACE_BG;
183 my $ink = $o{back} ? 250 : $self->colour ? $self->_ink($kind) : 0;
184  
185 my $edge = $o{mark} ? $FRESH_FG : $EDGE_FG;
186 my $side = $o{mark} ? $FRESH_FG : $SIDE_FG;
187  
188 my @on = $o{cursor} ? (1, 7) : $o{mark} ? (1) : ();
189 my $screen = $self->screen;
190  
191 return (
192 $screen->paint($tl . $h x 2 . $tr, join ';', @on, "38;5;$edge", "48;5;$bg"),
193 $screen->paint($v . $face . $v, join ';', @on, "38;5;$ink", "48;5;$bg"),
194 $screen->paint($bl . $h x 2 . $br, join ';', @on, "38;5;$side", "48;5;$bg"),
195 );
196 }
197  
198 sub tile_row {
199 my ($self, $kinds, %o) = @_;
200 my @line = ('', '', '');
201 my $backs = $o{backs} || {};
202 my $gaps = $o{gaps} || {};
203 for my $i (0 .. $#$kinds) {
204 my $pad = $gaps->{$i} ? ' ' : ($i ? ' ' : '');
205 my @art = $self->tile_art($kinds->[$i],
206 back => $backs->{$i},
207 mark => (defined $o{mark} && $o{mark} == $i),
208 cursor => (defined $o{cursor} && $o{cursor} == $i));
209 $line[$_] .= $pad . $art[$_] for 0 .. 2;
210 }
211 return @line;
212 }
213  
214 sub tile_chip {
215 my ($self, $kind, %o) = @_;
216 my $face = $self->face($kind);
217 my $chip = $o{last} ? "<$face>" : "[$face]";
218 return $chip unless $self->colour;
219 my $ink = $self->_ink($kind);
220 my $bg = $o{last} ? 223 : $FACE_BG;
221 return $self->screen->paint($chip, "38;5;$ink;48;5;$bg");
222 }
223  
224 sub tile_chips {
225 my ($self, @kinds) = @_;
226 return join '', map { $self->tile_chip($_) } @kinds;
227 }
228  
229 sub tile {
230 my ($self, $kind) = @_;
231 return $self->glyphs ? $GLYPH{$kind} : Game::Mahjong::Notation::print($kind);
232 }
233  
234 sub tiles {
235 my ($self, @kinds) = @_;
236 return '' unless @kinds;
237 return $self->glyphs ? join('', map { $GLYPH{$_} } @kinds) : Game::Mahjong::Notation::print(@kinds);
238 }
239  
240 sub name_of {
241 my ($self, $seat) = @_;
242 return $self->names->[$seat];
243 }
244  
245 sub _does {
246 my ($self, $seat, $third, $second) = @_;
247 return $self->name_of($seat) . ' ' . ($seat == $self->seat ? $second : $third);
248 }
249  
250 sub say {
251 my ($self, @text) = @_;
252 $self->screen->say(join '', @text);
253 return;
254 }
255  
256 sub _on_turn {
257 my ($self, $seat) = @_;
258 my $turn = $self->rules->turn;
259 return defined $turn && $self->rules->phase eq 'discard' && $turn == $seat ? 1 : 0;
260 }
261  
262 sub _wind_of {
263 my ($self, $seat) = @_;
264 return $WIND{ $self->rules->seat_wind($seat) };
265 }
266  
267 sub show_table {
268 my ($self) = @_;
269 my $g = $self->rules;
270 my $me = $self->seat;
271 my $w = $g->window;
272  
273 $self->_clear;
274 $self->say('');
275 $self->say($self->_c('bold', sprintf 'Hand %d of %d %s %s round %s you are %s %s wall %d',
276 $g->hand_no, Game::Mahjong::Result::HANDS, $DOT, $WIND{ $g->prevailing }, $DOT,
277 $self->_wind_of($me), $DOT, $g->wall->remaining));
278 $self->say('Totals ' . join(' ', map {
279 sprintf '%s %s', $self->name_of($_),
280 $self->_c($g->totals->[$_] < 0 ? 'red' : 'green', sprintf '%+d', $g->totals->[$_])
281 } 0 .. 3));
282 $self->say('');
283  
284 for my $i (1 .. 3) {
285 my $seat = ($me + $i) % 4;
286 my $hand = $g->hand_of($seat);
287 my $mark = $self->_on_turn($seat) ? $self->_c('yellow', '>') : ' ';
288 my $dealer = $seat == $g->dealer ? ' (deals)' : '';
289 $self->say(sprintf '%s %-5s %-6s %2d tiles%s%s',
290 $mark, $self->name_of($seat), $self->_wind_of($seat), $hand->size, $dealer,
291 (@{ $hand->flowers } ? ' flowers ' . $self->tile_chips(@{ $hand->flowers }) : ''));
292 $self->say(' sets ' . $self->_melds_line($hand)) if @{ $hand->melds };
293 $self->say(' pool ' . $self->_pool($seat));
294 }
295  
296 if ($w && $g->is_active) {
297 $self->say('');
298 my @art = $self->tile_row([ $w->{tile} ]);
299 my $from = $self->name_of($w->{from});
300 my $verb = $g->phase eq 'rob' ? 'adds to a pung' : 'discards';
301 $self->say(' ' . $art[0]);
302 $self->say(' ' . $art[1] . ' ' . $self->_c('yellow', "$from $verb this"));
303 $self->say(' ' . $art[2]);
304 }
305  
306 my $mine = $g->hand_of($me);
307 $self->say('');
308 $self->say($self->_c('bold', sprintf '%s %-5s %-6s%s%s',
309 ($self->_on_turn($me) ? $self->_c('yellow', '>') : ' '),
310 $self->name_of($me), $self->_wind_of($me),
311 ($me == $g->dealer ? ' (you deal)' : ''),
312 (@{ $mine->flowers } ? ' flowers ' . $self->tile_chips(@{ $mine->flowers }) : '')));
313 $self->say(' pool ' . $self->_pool($me));
314 if (@{ $mine->melds }) {
315 $self->say('');
316 $self->say(' Your sets:');
317 $self->say(' ' . $_) for $self->_melds_art($mine);
318 }
319 $self->say('');
320 $self->say(' Your hand:');
321 $self->say(' ' . $_) for $self->_rack_art;
322 return;
323 }
324  
325 sub _melds_art {
326 my ($self, $hand) = @_;
327 my (@kinds, %backs, %gaps);
328 my $n = 0;
329 for my $meld (@{ $hand->melds }) {
330 $gaps{$n} = 1 if $n;
331 for my $t (@{ $meld->tiles }) { push @kinds, $t; $n++ }
332 }
333 return ('-') unless @kinds;
334 my @line = $self->tile_row(\@kinds, backs => \%backs, gaps => \%gaps);
335 my $label = '';
336 my $at = 0;
337 for my $meld (@{ $hand->melds }) {
338 my $width = 5 * scalar(@{ $meld->tiles }) - 1;
339 $label .= ' ' if $at;
340 $label .= sprintf '%-*s', $width, $meld->kind . ($meld->concealed ? ' (concealed)' : '');
341 $at++;
342 }
343 return (@line, $label);
344 }
345  
346 sub _melds_line {
347 my ($self, $hand) = @_;
348 my @out;
349 for my $meld (@{ $hand->melds }) {
350 push @out, $meld->concealed && $hand != $self->rules->hand_of($self->seat)
351 ? $self->screen->paint('[##][##][##][##]', "48;5;$BACK_BG;38;5;250")
352 : $self->tile_chips(@{ $meld->tiles });
353 }
354 return join ' ', @out;
355 }
356  
357 sub rack_order {
358 my ($self) = @_;
359 my $g = $self->rules;
360 my @kinds = $g->hand_of($self->seat)->tiles;
361  
362 my $drawn = $self->_on_turn($self->seat) ? $g->drawn : undef;
363 return (\@kinds, undef) unless defined $drawn;
364  
365 my ($at) = grep { $kinds[$_] == $drawn } 0 .. $#kinds;
366 return (\@kinds, undef) unless defined $at;
367  
368 splice @kinds, $at, 1;
369 push @kinds, $drawn;
370 return (\@kinds, $#kinds);
371 }
372  
373 sub _rack_art {
374 my ($self) = @_;
375 my ($kinds, $last) = $self->rack_order;
376 my @kinds = @$kinds;
377 my %gaps;
378 $gaps{$last} = 1 if defined $last;
379 my @line = $self->tile_row(\@kinds, gaps => \%gaps,
380 mark => $last, cursor => $self->cursor);
381 my $numbers = '';
382 for my $i (0 .. $#kinds) {
383 $numbers .= $gaps{$i} ? ' ' : ($i ? ' ' : '');
384 $numbers .= sprintf ' %-3s', $i + 1;
385 }
386 $numbers = substr($numbers, 0, length($numbers) - 1) if length $numbers;
387 push @line, $numbers;
388 push @line, $self->_c('dim', sprintf ' %s the tile you just drew',
389 $self->_caret_under($last, \%gaps))
390 if defined $last;
391 return @line;
392 }
393  
394 sub _caret_under {
395 my ($self, $i, $gaps) = @_;
396 my $col = 0;
397 for my $n (0 .. $i) { $col += ($gaps->{$n} ? 3 : ($n ? 1 : 0)) + 4 }
398 return (' ' x ($col - 3)) . '^';
399 }
400  
401 sub _pool {
402 my ($self, $seat) = @_;
403 my @p = @{ $self->rules->pool_of($seat) };
404 return $self->_c('dim', 'nothing thrown yet') unless @p;
405 my $w = $self->rules->window;
406 my $lit = ($w && $w->{from} == $seat) ? $#p : -1;
407 my @rows;
408 my $i = 0;
409 my @chips = map { $self->tile_chip($_, last => ($i++ == $lit)) } @p;
410 while (@chips) { push @rows, join '', splice @chips, 0, 12 }
411 return join "\n ", @rows;
412 }
413  
414 sub show_hand_end {
415 my ($self, $e) = @_;
416 $self->say('');
417 if (!defined $e->{winner}) {
418 $self->say($self->_c('bold', 'The wall is exhausted: nobody wins this hand.'));
419 }
420 else {
421 my $who = $self->name_of($e->{winner});
422 my $how = $e->{by} eq 'self' ? 'self-drawn' : $e->{by} eq 'rob' ? 'robbing the kong of ' . $self->name_of($e->{from}) : 'off ' . $self->name_of($e->{from}) . "'s discard";
423 if (defined $e->{tile}) {
424 my @art = $self->tile_row([ $e->{tile} ]);
425 $self->say(' ' . $art[0]);
426 $self->say(' ' . $art[1] . ' ' . $self->_c('bold', sprintf '%s, %s.', $who, $how));
427 $self->say(' ' . $art[2]);
428 }
429 else {
430 $self->say($self->_c('bold', sprintf '%s with the dealt tiles, a heavenly hand.', $who));
431 }
432 for my $f (@{ $e->{fans} }) {
433 my $fan = Game::Mahjong::Fans::by_key($f->{key});
434 $self->say(sprintf ' %-32s %3d%s', $fan->name, $f->{points} * $f->{times}, $f->{times} > 1 ? " ($f->{times} x $f->{points})" : '');
435 }
436 $self->say(sprintf ' %-32s %3d', $self->_c('bold', 'Total'), $e->{points});
437 $self->say('Settlement: ' . join(', ', map { sprintf '%s %s', $self->name_of($_), $self->_c($e->{deltas}[$_] < 0 ? 'red' : 'green', ($e->{deltas}[$_] >= 0 ? '+' : '') . $e->{deltas}[$_]) } 0 .. 3));
438 }
439 for my $seat (0 .. 3) {
440 my @k = @{ $e->{concealed_kongs}[$seat] || [] };
441 $self->say(sprintf '%s a concealed kong of %s.', $self->_does($seat, 'shows', 'show'), $self->tiles(($_) x 4)) for @k;
442 }
443 $self->say('Totals now: ' . join(' ', map { sprintf '%s %d', $self->name_of($_), $e->{totals}[$_] } 0 .. 3));
444 return;
445 }
446  
447 sub show_game_end {
448 my ($self, $e) = @_;
449 $self->finished(1);
450 $self->winner($e->{winner});
451 $self->say('');
452 $self->say($self->_c('bold', 'The game is over after sixteen hands.'));
453 my @order = sort { $e->{places}[$a] <=> $e->{places}[$b] } 0 .. 3;
454 $self->say(sprintf ' %d. %-5s %5d', $e->{places}[$_], $self->name_of($_), $e->{totals}[$_]) for @order;
455 $self->say(defined $e->{winner} ? $self->_does($e->{winner}, 'wins', 'win') . ' the game.' : 'A shared first place: the game is drawn.');
456 return;
457 }
458  
459 sub narrate {
460 my ($self, @events) = @_;
461 for my $e (@events) {
462 my $k = $e->{kind};
463 my $actor = $e->{actor};
464 if ($k eq 'deal') { $self->say($self->_c('dim', sprintf 'Hand %d. %s.', $e->{hand}, $self->_does($e->{dealer}, 'deals', 'deal'))) }
465 elsif ($k eq 'flower') { $self->say(sprintf '%s a flower, %s, and %s again.', $self->_does($e->{seat}, 'exposes', 'expose'), $self->tile($e->{tile}), $e->{seat} == $self->seat ? 'draw' : 'draws') }
466 elsif ($k eq 'drew' && $e->{seat} == $self->seat && $self->_on_turn($self->seat) && defined $self->rules->drawn) {
467 $self->say(sprintf 'You draw %s from the %s.', $self->tile($self->rules->drawn), $e->{from} eq 'back' ? 'back of the wall' : 'wall');
468 }
469 elsif ($k eq 'discard' && $actor ne $self->seat) { $self->say(sprintf '%s discards %s.', $self->name_of($actor), $self->tile($e->{tile})) }
470 elsif ($k eq 'claimed') {
471 next if $e->{meld} eq 'win';
472 $self->say(sprintf '%s %s from %s for a %s.', $self->_does($e->{seat}, 'claims', 'claim'), $self->tile($e->{tile}), $self->name_of($e->{from}), $e->{meld});
473 }
474 elsif ($k eq 'kong' && $actor ne $self->seat) { $self->say(sprintf '%s declares a %s kong of %s.', $self->name_of($actor), $e->{how}, $self->tile($e->{tile})) }
475 elsif ($k eq 'hand_end') { $self->show_hand_end($e) }
476 elsif ($k eq 'game_end') { $self->show_game_end($e) }
477 }
478 return;
479 }
480  
481 sub help {
482 my ($self) = @_;
483 $self->say('Commands:');
484 $self->say(' <n> discard the tile numbered n in your hand');
485 $self->say(' d <tile> discard a tile by name, e.g. d 5m, d E, d B (white dragon)');
486 $self->say(' kong <tile> declare a kong (four in hand, or the fourth for your exposed pung)');
487 $self->say(' win declare your hand complete');
488 $self->say(' pass | pung | kong | chow <n> answer a discard (chow <n> picks the shape offered)');
489 $self->say(' hint what the strongest bot would do');
490 $self->say(' table show the table again');
491 $self->say(' fans list the eighty-one scoring elements and their points');
492 $self->say(' help this list');
493 $self->say(' quit leave the game');
494 return;
495 }
496  
497 sub show_fans {
498 my ($self) = @_;
499 for my $fan (Game::Mahjong::Fans::all()) {
500 $self->say(sprintf '%2d %-36s %2d', $fan->n, $fan->name, $fan->points);
501 }
502 return;
503 }
504  
505 sub _describe_legal {
506 my ($self, @legal) = @_;
507 my $g = $self->rules;
508 if ($g->phase ne 'discard') {
509 my $w = $g->window;
510 my @lines;
511 my $n = 0;
512 for my $m (@legal) {
513 my $text = $m->{kind} eq 'chow' ? sprintf('chow %d (%s)', ++$n, $self->tiles(@{ $m->{tiles} })) : $m->{kind};
514 push @lines, $text;
515 }
516 $self->say(sprintf '%s %s %s. You may: %s', $self->name_of($w->{from}), ($g->phase eq 'rob' ? 'adds to a pung' : 'discards'), $self->tile($w->{tile}), join(', ', @lines));
517 return;
518 }
519 my @extra = grep { $_->{kind} ne 'discard' } @legal;
520 $self->say('You may also: ' . join(', ', map { $_->{kind} eq 'kong' ? 'kong ' . $self->tile($_->{tile}) : $_->{kind} } @extra)) if @extra;
521 return;
522 }
523  
524 sub picking {
525 my ($self, @set) = @_;
526 $self->_picking($set[0] ? 1 : 0) if @set;
527 return 0 if $self->auto;
528 return $self->_picking ? 1 : 0 if defined $self->_picking;
529 return $self->keys_available;
530 }
531  
532 sub raw {
533 my ($self) = @_;
534 return $self->keyboard->raw;
535 }
536  
537 sub keys_available {
538 my ($self) = @_;
539 return $self->keyboard->keys_available;
540 }
541  
542 sub enter_raw {
543 my ($self) = @_;
544 return $self->keyboard->enter_raw ? $self : undef;
545 }
546  
547 sub leave_raw {
548 my ($self) = @_;
549 $self->keyboard->leave_raw;
550 return $self;
551 }
552  
553 sub read_key {
554 my ($self) = @_;
555 return $self->keyboard->read_key;
556 }
557  
558 sub throw_line {
559 my ($self, $kind) = @_;
560  
561 my $hand = $self->rules->hand_of($self->seat);
562 my $left = Game::Mahjong::Shanten::after_discard($hand, $kind);
563  
564 my $line = sprintf 'throw %s and you are %s',
565 $self->tile($kind),
566 $left < 0 ? 'out' : $left == 0 ? 'waiting' : "$left away";
567  
568 my $rest = $hand->clone;
569 $rest->remove($kind);
570 my @help = Game::Mahjong::Shanten::ukeire($rest);
571 $line .= sprintf ', %d %s help', scalar @help,
572 @help == 1 ? 'kind would' : 'kinds would' if @help;
573  
574 $line .= ', a step backwards'
575 if $left > Game::Mahjong::Shanten::shanten($hand);
576  
577 return $line;
578 }
579  
580 sub picker {
581 my ($self, @legal) = @_;
582  
583 my ($kinds) = $self->rack_order;
584 my %throwable = map { $_->{tile} => 1 }
585 grep { $_->{kind} eq 'discard' } @legal;
586 my @open = grep { $throwable{ $kinds->[$_] } } 0 .. $#$kinds;
587 return undef unless @open;
588  
589 return Game::Terminal::Kit::Picker->new(
590 items => [ map {
591 { label => $self->tile($_), value => $_, skip => ($throwable{$_} ? 0 : 1) }
592 } @$kinds ],
593 at => $open[-1],
594 across => 1,
595 numbered => 0,
596 window => 0,
597 game_keys => { h => 'hint', t => 'type', '?' => 'help', map { $_ => $_ } 1 .. 9 },
598 screen => $self->screen,
599 );
600 }
601  
602 sub pick_discard {
603 my ($self, @legal) = @_;
604  
605 my $picker = $self->picker(@legal) or return undef;
606 my $log = $self->log;
607  
608 while (1) {
609 $self->show_pick($picker, \@legal);
610  
611 my $key = $self->read_key;
612 my ($event, $value) = $picker->step($key);
613 if ($event eq 'quit') {
614 $self->quit(1);
615 return undef;
616 }
617 next if $event eq 'moved';
618  
619 if ($event eq 'chosen') {
620 my ($m) = grep { $_->{kind} eq 'discard' && $_->{tile} == $value } @legal;
621 return $m;
622 }
623  
624 unless ($event eq 'key') {
625 $log->note('that key does nothing here. ? for the ones that do')
626 unless $event eq 'none' && $WALK{$key};
627 next;
628 }
629  
630 if ($value eq 'hint') {
631 my $m = $self->hinter->hint($self->rules, $self->seat);
632 if ($m && $m->{kind} eq 'discard') {
633 my ($found) = grep {
634 !$picker->skipped($_) && $picker->value_of($_) == $m->{tile}
635 } 0 .. $#{ $picker->items };
636 $picker->jump($found) if defined $found;
637 }
638 $log->note('Hint: ' . $self->_move_text($m)) if $m;
639 next;
640 }
641  
642 if ($value eq 'type') { $self->picking(0); return $self->read_move(@legal) }
643  
644 if ($value eq 'help') { $log->note($self->pick_help); next }
645  
646 if ($value > @{ $picker->items } || $picker->skipped($value - 1)) {
647 $log->note('no tile is numbered ' . $value . ' here');
648 next;
649 }
650 $picker->jump($value - 1);
651 }
652 }
653  
654 sub pick_help {
655 return (
656 'left and right walk your rack. the tile under the cursor is the one',
657 'you would throw, and the line under it says what that leaves you.',
658 'enter throws it, a number jumps to that tile, h is the hint,',
659 't goes back to typing, q stops.',
660 );
661 }
662  
663 sub show_pick {
664 my ($self, $picker, $legal) = @_;
665  
666 $self->cursor($picker->at);
667 $self->show_table;
668 $self->cursor(undef);
669  
670 $self->say(' ' . $self->throw_line($picker->current));
671 $self->_describe_legal(@$legal);
672 $self->say(' ' . $self->_c('dim', $_)) for $self->log->lines;
673 $self->log->shown;
674 $self->say(' ' . $self->_c('dim', 'arrows to choose, enter to throw, ? for the keys'));
675 return;
676 }
677  
678 sub read_move {
679 my ($self, @legal) = @_;
680 my $g = $self->rules;
681 my $hand = $g->hand_of($self->seat);
682  
683 if ($g->phase eq 'discard' && $self->picking) {
684 if ($self->enter_raw) {
685 my $move = $self->pick_discard(@legal);
686 $self->leave_raw;
687 return $move;
688 }
689 $self->picking(0);
690 }
691  
692 while (1) {
693 my $line = $self->keyboard->read_line('> ', $self->out);
694 unless (defined $line) { $self->quit(1); return undef }
695 next unless length $line;
696 my ($cmd, @args) = split ' ', lc $line;
697 if ($cmd eq 'quit' || $cmd eq 'q') { $self->quit(1); return undef }
698 if ($cmd eq 'help' || $cmd eq '?') { $self->help; next }
699 if ($cmd eq 'table' || $cmd eq 't') { $self->show_table; $self->_describe_legal(@legal); next }
700 if ($cmd eq 'fans') { $self->show_fans; next }
701 if ($cmd eq 'hint' || $cmd eq 'h') {
702 my $m = $self->hinter->hint($g, $self->seat);
703 $self->say('Hint: ' . $self->_move_text($m)) if $m;
704 next;
705 }
706 my $move = $self->_parse($cmd, \@args, \@legal, $hand);
707 unless ($move) { $self->say('Not a move here. Type help for the commands.'); next }
708 return $move;
709 }
710 }
711  
712 sub _move_text {
713 my ($self, $m) = @_;
714 return 'discard ' . $self->tile($m->{tile}) if $m->{kind} eq 'discard';
715 return 'kong ' . $self->tile($m->{tile}) if $m->{kind} eq 'kong' && $m->{tile};
716 return 'chow with ' . $self->tiles(@{ $m->{tiles} }) if $m->{kind} eq 'chow';
717 return $m->{kind};
718 }
719  
720 sub _parse_tile {
721 my ($self, $text) = @_;
722 return undef unless defined $text;
723 my $t = $text;
724 $t =~ s/\A([1-9])([mps])\z/$1$2/;
725 $t = uc $t if $t =~ /\A[eswnrgb]\z/;
726 my @ids = eval { Game::Mahjong::Notation::parse($t) };
727 return @ids == 1 ? $ids[0] : undef;
728 }
729  
730 sub _parse {
731 my ($self, $cmd, $args, $legal, $hand) = @_;
732 my $g = $self->rules;
733 if ($g->phase eq 'discard') {
734 if ($cmd =~ /\A\d+\z/) {
735 my ($kinds) = $self->rack_order;
736 my $t = $cmd >= 1 ? $kinds->[ $cmd - 1 ] : undef;
737 return undef unless $t;
738 my ($m) = grep { $_->{kind} eq 'discard' && $_->{tile} == $t } @$legal;
739 return $m;
740 }
741 if ($cmd eq 'd' || $cmd eq 'discard') {
742 my $t = $self->_parse_tile($args->[0]) or return undef;
743 my ($m) = grep { $_->{kind} eq 'discard' && $_->{tile} == $t } @$legal;
744 return $m;
745 }
746 if ($cmd eq 'kong') {
747 my @k = grep { $_->{kind} eq 'kong' } @$legal;
748 return $k[0] if @k == 1 && !@$args;
749 my $t = $self->_parse_tile($args->[0]) or return undef;
750 my ($m) = grep { $_->{tile} == $t } @k;
751 return $m;
752 }
753 if ($cmd eq 'win') { my ($m) = grep { $_->{kind} eq 'win' } @$legal; return $m }
754 return undef;
755 }
756 if ($cmd eq 'chow') {
757 my @c = grep { $_->{kind} eq 'chow' } @$legal;
758 return $c[0] if @c == 1 && !@$args;
759 my $n = $args->[0];
760 return undef unless defined $n && $n =~ /\A\d+\z/ && $c[ $n - 1 ];
761 return $c[ $n - 1 ];
762 }
763 my ($m) = grep { $_->{kind} eq $cmd } @$legal;
764 return $m;
765 }
766  
767 sub start {
768 my ($self) = @_;
769 my $g = $self->rules;
770 $self->say($self->_c('bold', 'Mahjong, the competition rules: sixteen hands, eight points to win.'));
771 $self->say('Seed ' . $self->seed . ', bots at level ' . $self->level . '. Type help for the commands.') unless $self->auto;
772 $self->narrate($g->take_outcomes);
773 my $shown = -1;
774  
775 while ($g->is_active && !$self->quit) {
776 my @waiting = $g->waiting_on;
777 last unless @waiting;
778 my ($seat) = grep { $_ == $self->seat } @waiting;
779 if (defined $seat && !$self->auto) {
780 my @legal = $g->legal($seat);
781 if ($shown != $g->moves) { $self->show_table; $shown = $g->moves }
782 $self->_describe_legal(@legal);
783 my $move = $self->read_move(@legal);
784 last unless $move;
785 my $r = $g->apply($seat, $move);
786 if (ref $r && $r->can('error')) { $self->say('Refused: ' . $r->message); next }
787 my @out = $g->take_outcomes;
788 $self->narrate(@out);
789 next;
790 }
791 my $bot_seat = $waiting[0];
792 if ($self->auto && $bot_seat == $self->seat && $g->phase eq 'discard' && $shown != $g->moves) {
793 $self->show_table;
794 $shown = $g->moves;
795 }
796 my $move = $self->bots->[$bot_seat]->choose($g, $bot_seat) or last;
797 my $r = $g->apply($bot_seat, $move);
798 die 'Game::Mahjong::Terminal: the bot was refused: ' . $r->code if ref $r && $r->can('error');
799 $self->narrate($g->take_outcomes);
800 }
801 if ($self->quit) { $self->say('Goodbye.') }
802 return $g;
803 }
804  
805 sub _usage {
806 return <<'USAGE';
807 mahjong: a game against three bots under the Chinese Official rules
808  
809 --seed STRING the game (the same seed deals the same tiles); a fresh one by default
810 --level 1..3 the bots' strength, 2 by default
811 --seat 0..3 your seat, 0 by default (seat 0 deals the first hand)
812 --glyphs put the Unicode Mahjong Tiles block on the tile faces
813 --ascii draw the tile frames with + - | for a terminal without box drawing
814 --no-clear do not clear the screen before each table
815 --no-colour plain text (colour is on when standard output is a terminal
816 and NO_COLOR is unset or empty)
817 --no-pick type the moves out instead of pointing at them
818 --auto four bots, no prompt: watch a game
819 --help this
820  
821 On a terminal the left and right keys walk your own rack and the tile under
822 the cursor is the one you would throw. The line under it says what that
823 leaves you: how far from a winning hand, and how many tiles would help.
824 Enter throws it, the number keys still work, ? lists the keys and q stops.
825 Needs Term::ReadKey; without it, or off a terminal, every move is typed.
826  
827 At a typed prompt: a number discards that tile, "help" lists the rest.
828  
829 Exit status is 0 if you won or the game was drawn, 1 if you lost or stopped
830 early, 2 for an option the game will not take.
831 USAGE
832 }
833  
834 sub options {
835 return [
836 { name => 'level', type => 'int', min => 1, max => 3, help => "the bots' strength" },
837 { name => 'seat', type => 'int', min => 0, max => 3, help => 'your seat; seat 0 deals the first hand' },
838 { name => 'glyphs', type => 'flag', help => 'the Unicode Mahjong Tiles block on the tile faces' },
839 { name => 'auto', type => 'flag', help => 'four bots, no prompt: watch a game' },
840 { name => 'seed', type => 'str', help => 'the same seed deals the same tiles' },
841 ];
842 }
843  
844 sub run {
845 my ($class, @argv) = @_;
846 my $tty = -t STDOUT ? 1 : 0;
847 my %o = (level => 2, seat => 0, colour => ($tty && !Game::Terminal::Kit::Screen::no_colour() ? 1 : 0), glyphs => 0, auto => 0,
848 ascii => 0, clear => $tty);
849  
850 my $ok = eval {
851 local $SIG{__WARN__} = sub { print STDERR "mahjong: $_[0]" };
852 Getopt::Long::GetOptionsFromArray(\@argv,
853 'seed=s' => \$o{seed},
854 'level=i' => \$o{level},
855 'seat=i' => \$o{seat},
856 'glyphs!' => \$o{glyphs},
857 'colour!' => \$o{colour},
858 'color!' => \$o{colour},
859 'auto' => \$o{auto},
860 'ascii!' => \$o{ascii},
861 'clear!' => \$o{clear},
862 'pick!' => \$o{pick},
863 'help|h' => \$o{help},
864 );
865 };
866 if (!$ok) { print STDERR _usage(); return 2 }
867 if ($o{help}) { print _usage(); return 0 }
868 if (@argv) { print STDERR "mahjong: not an option: $argv[0]\n", _usage(); return 2 }
869  
870 $o{seed} //= sprintf('%s-%d', scalar(localtime), $$);
871  
872 my $t = eval {
873 $class->new(
874 seed => $o{seed}, level => $o{level}, seat => $o{seat},
875 in => \*STDIN, out => \*STDOUT, colour => $o{colour}, glyphs => $o{glyphs}, auto => $o{auto},
876 ascii => $o{ascii}, clear => $o{clear},
877 (defined $o{pick} ? (picking => $o{pick} ? 1 : 0) : ()),
878 );
879 };
880  
881 unless ($t) {
882 my $why = $@ || 'could not start';
883 $why =~ s/ at \S+ line \d+\.?\s*\z//;
884 $why =~ s/\A[\w:]+: //;
885 chomp $why;
886 print STDERR "mahjong: $why\n";
887 return 2;
888 }
889  
890 $t->screen->utf8->flush_on;
891  
892 Game::Terminal::Kit::Run::guard(sub { $t->start }, $t->keyboard, $t->screen);
893  
894 return 1 unless $t->finished;
895 return 0 if $o{auto};
896 return 0 unless defined $t->winner;
897 return 0 if $t->winner == $o{seat};
898 return 1;
899 }
900  
901 1;
902  
903 __END__