blib/lib/Game/RoyalUr/Terminal.pm

filter: Statementstmt 90.0% 18 / 20 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.5% 25 / 27 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/Game/RoyalUr/Variant.pm ↑ Summary RoyalUr.xs »
1 package Game::RoyalUr::Terminal;
2  
3 47 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 47 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 47 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 47 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 47 ▶use Digest::SHA ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 47 ▶use Getopt::Long ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 0 ▶use Object::Proto::Sugar;
Subroutine BEGIN: called CC=1 SCAR=2.6
11  
12 use Game::Terminal::Kit::History;
13 use Game::Terminal::Kit::Keys;
14 use Game::Terminal::Kit::Run;
15 use Game::Terminal::Kit::Screen;
16 use Game::Terminal::Kit::Steer;
17  
18 use Game::RoyalUr;
19 use Game::RoyalUr::Bot;
20 use Game::RoyalUr::Variant;
21 use Game::RoyalUr::Notation ();
22  
23 our $VERSION = '0.03';
24  
25 my (%STYLE, %GLYPH, %OTHER, @FILES);
26 BEGIN {
27 %STYLE = (
28 title => '1;38;5;220',
29 grid => '38;5;241',
30 label => '38;5;245',
31 light => '1;38;5;229',
32 dark => '1;38;5;39',
33 rosette => '1;38;5;205',
34 cursor => '1;38;5;16;48;5;220',
35 landing => '1;38;5;16;48;5;114',
36 capture => '1;38;5;231;48;5;160',
37 marked => '1;38;5;220',
38 unmarked => '38;5;240',
39 key => '1;38;5;214',
40 good => '1;38;5;114',
41 bad => '1;38;5;203',
42 quiet => '38;5;245',
43 step => '38;5;109',
44 );
45  
46 %GLYPH = (
47 wide => {
48 light => "\x{25CF}", dark => "\x{25CB}", rosette => "\x{2726}",
49 marked => "\x{25B2}", unmarked => "\x{25B3}",
50 h => "\x{2500}", v => "\x{2502}",
51 tl => "\x{256D}", tr => "\x{256E}", bl => "\x{2570}", br => "\x{256F}",
52 td => "\x{252C}", tu => "\x{2534}", lt => "\x{251C}", rt => "\x{2524}", x => "\x{253C}",
53 },
54 ascii => {
55 light => 'O', dark => '@', rosette => '*',
56 marked => '^', unmarked => '.',
57 h => '-', v => '|',
58 tl => '+', tr => '+', bl => '+', br => '+',
59 td => '+', tu => '+', lt => '+', rt => '+', x => '+',
60 },
61 );
62  
63 %OTHER = (light => 'dark', dark => 'light');
64 @FILES = ('a' .. 'h');
65 }
66  
67 has game => (is => 'rw');
68  
69 has [qw/in out/] => (is => 'rw');
70  
71 has [qw/interactive colour unicode picking/] => (is => 'rw');
72  
73 has mode => (is => 'rw', default => 'bot');
74  
75 has side => (is => 'rw', default => 'light');
76  
77 has level => (is => 'rw');
78  
79 has rules => (is => 'rw', default => 'finkel');
80  
81 has first => (is => 'rw', default => 'roll');
82  
83 has seed => (is => 'rw');
84  
85 has pace => (is => 'rw');
86  
87 has route => (is => 'rw', default => 0);
88  
89 has record => (is => 'rw');
90  
91 has keysource => (is => 'rw');
92  
93 has history => (is => 'rw');
94  
95 has sleeper => (is => 'rw');
96  
97 has [qw/_keyboard _screen/] => (is => 'rw');
98  
99 has _events => (is => 'rw', private => 1);
100  
101 has _told => (is => 'rw', private => 1);
102  
103 has _cursor => (is => 'rw', private => 1);
104  
105 has _note => (is => 'rw', private => 1);
106  
107 sub BUILD {
108 my ($self) = @_;
109 $self->in(\*STDIN) unless $self->in;
110 $self->out(\*STDOUT) unless $self->out;
111 $self->interactive(-t $self->in ? 1 : 0) unless defined $self->interactive;
112 $self->colour($self->interactive && !Game::Terminal::Kit::Screen::no_colour() ? 1 : 0) unless defined $self->colour;
113 $self->unicode($self->interactive ? 1 : 0) unless defined $self->unicode;
114 $self->_keyboard(Game::Terminal::Kit::Keys->new(
115 in => $self->in,
116 ($self->keysource ? (keysource => $self->keysource) : ()),
117 ));
118 $self->_screen(Game::Terminal::Kit::Screen->new(
119 out => $self->out,
120 interactive => $self->interactive,
121 colour => $self->colour,
122 ascii => $self->unicode ? 0 : 1,
123 ));
124 $self->picking($self->interactive ? 1 : 0) unless defined $self->picking;
125 $self->picking(0) unless $self->_keyboard->keys_available;
126 $self->pace($self->interactive && !$self->keysource ? 1 : 0) unless defined $self->pace;
127  
128 Carp::croak("Game::RoyalUr::Terminal: mode is bot, hotseat or watch, not '" . $self->mode . "'")
129 unless $self->mode =~ /\A(?:bot|hotseat|watch)\z/;
130 Carp::croak("Game::RoyalUr::Terminal: side is light or dark, not '" . $self->side . "'")
131 unless $self->side =~ /\A(?:light|dark)\z/;
132 Carp::croak("Game::RoyalUr::Terminal: first is light, dark or roll, not '" . $self->first . "'")
133 unless $self->first =~ /\A(?:light|dark|roll)\z/;
134 Carp::croak('Game::RoyalUr::Terminal: pace is a number of seconds, 0 or more')
135 unless $self->pace =~ /\A\d+(?:\.\d+)?\z/;
136  
137 my $variant = Game::RoyalUr::Variant->of($self->rules);
138 my @levels = Game::RoyalUr::Bot->levels($variant);
139 $self->level($levels[-1]) unless defined $self->level;
140 Carp::croak('Game::RoyalUr::Terminal: level is a whole number from 1 to ' . $levels[-1])
141 unless $self->level =~ /\A\d+\z/ && $self->level >= 1 && $self->level <= $levels[-1];
142  
143 $self->seed(Digest::SHA::sha256(join '|', 'royalur', $$, time, rand)) unless defined $self->seed;
144 $self->_events([]);
145 $self->_told(0);
146 $self->_cursor(0);
147 if ($self->game) {
148 $self->_told(scalar @{ $self->game->log });
149 }
150 else {
151 $self->game($self->_fresh_game);
152 $self->_announce_opening;
153 }
154 $self->history(Game::Terminal::Kit::History->new(
155 save => sub { $_[0]->to_text },
156 load => sub { Game::RoyalUr->from_text($_[0]) },
157 )) unless $self->history;
158 $self->history->start($self->game);
159  
160 $self->_screen->utf8->flush_on;
161 return;
162 }
163  
164 sub _fresh_game {
165 my ($self) = @_;
166 return Game::RoyalUr->new(
167 seed => $self->seed,
168 rules => $self->rules,
169 ($self->first eq 'roll' ? () : (first => $self->first)),
170 );
171 }
172  
173 sub _announce_opening {
174 my ($self) = @_;
175 my $game = $self->game;
176 my @throws = @{ $game->opening };
177 return unless @throws;
178 while (@throws) {
179 my ($light, $dark) = splice @throws, 0, 2;
180 my ($l, $d) = (scalar(grep { $_ } @$light), scalar(grep { $_ } @$dark));
181 $self->_event(undef, sprintf 'To see who starts, light threw %s %d and dark %s %d%s',
182 $self->_dice($light), $l, $self->_dice($dark), $d, $l == $d ? ': a tie, again.' : '.');
183 }
184 $self->_event($game->first, ucfirst($game->first) . ' moves first.');
185 return;
186 }
187  
188 sub _paint {
189 my ($self, $text, $style) = @_;
190 return $text unless defined $style;
191 return $self->_screen->paint($text, $STYLE{$style});
192 }
193  
194 sub _raw { $_[0]->_keyboard->raw }
195  
196 sub _glyph { $GLYPH{ $_[0]->unicode ? 'wide' : 'ascii' }{ $_[1] } }
197  
198 sub _dice {
199 my ($self, $faces) = @_;
200 return join ' ', map { $self->_paint($self->_glyph($_ ? 'marked' : 'unmarked'), $_ ? 'marked' : 'unmarked') } @$faces;
201 }
202  
203 sub _event {
204 my ($self, $side, $text) = @_;
205 push @{ $self->_events }, { side => $side, text => $text };
206 return;
207 }
208  
209 sub events { [ map { $_->{text} } @{ $_[0]->_events } ] }
210  
211 sub _person {
212 my ($self, $side) = @_;
213 return 0 if $self->mode eq 'watch';
214 return 1 if $self->mode eq 'hotseat';
215 return $side eq $self->side ? 1 : 0;
216 }
217  
218 sub _who {
219 my ($self, $side) = @_;
220 return ucfirst $side if $self->mode ne 'bot';
221 return $side eq $self->side ? 'You' : ucfirst $side;
222 }
223  
224 my $said = sub {
225 my ($entry) = @_;
226 return Game::RoyalUr::Notation::format_forfeit($entry->{roll}) unless defined $entry->{move};
227 my ($from, $to) = split /-/, $entry->{move};
228 return Game::RoyalUr::Notation::format_display({ from => $from, to => $to, %$entry });
229 };
230  
231 sub _tell {
232 my ($self, $pause) = @_;
233 my $game = $self->game;
234 my $log = $game->log;
235 my $told = $self->_told;
236 while ($told < @$log) {
237 my $entry = $log->[ $told++ ];
238 my $who = $self->_who($entry->{side});
239 my $text;
240 if (!defined $entry->{move}) {
241 $text = $entry->{roll} == 0
242 ? "$who rolled nothing and lost the turn."
243 : "$who rolled $entry->{roll} and could not move: the turn is lost.";
244 }
245 else {
246 $text = "$who played " . $said->($entry);
247 $text .= ', capturing' if $entry->{captures};
248 $text .= $entry->{home} ? ', home.'
249 : $entry->{rosette} ? ', onto a rosette: another roll.' : '.';
250 }
251 $self->_event($entry->{side}, $text);
252 $self->_told($told);
253 my $slow = !defined $entry->{move} || !$self->_person($entry->{side});
254 if ($pause && $slow && $self->_raw) {
255 $self->show('wait');
256 $self->_wait;
257 }
258 }
259 $self->_told($told);
260 return;
261 }
262  
263 sub _wait {
264 my ($self) = @_;
265 my $pace = $self->pace;
266 return unless $pace > 0;
267 return $self->sleeper->($pace) if $self->sleeper;
268 select undef, undef, undef, $pace;
269 return;
270 }
271  
272 my $coordinates = sub {
273 my ($place, $side) = @_;
274 return (4.5, $side eq 'light' ? 0 : 2) if $place eq 'hand';
275 return (ord(substr $place, 0, 1) - ord('a'), substr($place, 1, 1) - 1);
276 };
277  
278 sub candidates {
279 my ($self) = @_;
280 return $self->game->legal;
281 }
282  
283 sub steer {
284 my ($self, $key) = @_;
285 my @moves = $self->candidates;
286 return $self->_cursor unless @moves;
287 my $at = $self->_cursor;
288 $at = $#moves if $at > $#moves;
289  
290 if ($key eq 'tab') { $at = Game::Terminal::Kit::Steer::ring(scalar @moves, $at, 1) }
291 if ($key eq 'back_tab' || $key eq 'backtab') { $at = Game::Terminal::Kit::Steer::ring(scalar @moves, $at, -1) }
292 if ($key =~ /\A[1-7]\z/ && $key <= @moves) { $at = $key - 1 }
293  
294 if (my ($dx, $dy) = Game::Terminal::Kit::Steer::way($key)) {
295 my $side = $self->game->side;
296 my @points = map { [ $coordinates->($_->from, $side) ] } @moves;
297 if ($dy) { $_->[1] = -$_->[1] for @points }
298 $at = Game::Terminal::Kit::Steer::axis(\@points, $at, $dx, $dy);
299 }
300 $self->_cursor($at);
301 return $at;
302 }
303  
304 my $cells_after = sub {
305 my ($game, $move) = @_;
306 my (%cell, %hand, %home, %mark);
307 for my $file (@FILES) {
308 for my $row (1 .. 3) {
309 my $name = "$file$row";
310 next unless Game::RoyalUr::Notation::square_ok($name);
311 $cell{$name} = $game->at($name);
312 }
313 }
314 for my $side (qw(light dark)) {
315 $hand{$side} = $game->hand($side);
316 $home{$side} = $game->home($side);
317 }
318 return (\%cell, \%hand, \%home, \%mark) unless $move;
319  
320 my $side = $move->side;
321 if ($move->from eq 'hand') { $hand{$side}--; $mark{"hand $side"} = 'cursor' }
322 else { $cell{ $move->from } = undef; $mark{ $move->from } = 'cursor' }
323 if ($move->captures) {
324 $hand{ $OTHER{$side} }++;
325 $mark{"hand $OTHER{$side}"} = 'capture';
326 }
327 if ($move->home) { $home{$side}++; $mark{"home $side"} = 'landing' }
328 else { $cell{ $move->to } = $side; $mark{ $move->to } = 'landing' }
329 return (\%cell, \%hand, \%home, \%mark);
330 };
331  
332 my %BRACKET;
333 BEGIN { %BRACKET = (cursor => [ '[', ']' ], landing => [ '(', ')' ], capture => [ '<', '>' ], last => [ '_', '_' ]) }
334  
335 sub _framed {
336 my ($self, $what, $mark) = @_;
337 my ($open, $close) = $mark ? @{ $BRACKET{$mark} } : (' ', ' ');
338 my $inside = defined $what ? $self->_glyph($what) : ' ';
339 return $self->_paint($open . $inside . $close, $mark) if $mark && $mark ne 'last';
340 return $open . (defined $what ? $self->_paint($inside, $what) : $inside) . $close;
341 }
342  
343 sub _row {
344 my ($self, $row, $cell, $mark) = @_;
345 my $v = $self->_paint($self->_glyph('v'), 'grid');
346 my @parts;
347 for my $file (@FILES) {
348 my $name = "$file$row";
349 if (!Game::RoyalUr::Notation::square_ok($name)) { push @parts, undef; next }
350 my $rosette = $name =~ /\A(?:a1|g1|a3|g3|d2)\z/ ? $self->_paint($self->_glyph('rosette'), 'rosette') : ' ';
351 push @parts, $rosette . $self->_framed($cell->{$name}, $mark->{$name}) . ' ';
352 }
353 my $line = $self->_paint($row, 'label') . ' ' . $v;
354 if (defined $parts[4]) { $line .= join($v, @parts) . $v }
355 else { $line .= join($v, @parts[0 .. 3]) . $v . (' ' x 11) . $v . join($v, @parts[6, 7]) . $v }
356 return ' ' . $line;
357 }
358  
359 sub _border {
360 my ($self, $kind) = @_;
361 my $g = sub { $self->_glyph($_[0]) };
362 my $bar = $g->('h') x 5;
363 my $block = sub { my ($left, $mid, $right, $n) = @_; $g->($left) . join($g->($mid), ($bar) x $n) . $g->($right) };
364 my $line = $kind eq 'top' ? $block->('tl', 'td', 'tr', 4) . (' ' x 11) . $block->('tl', 'td', 'tr', 2)
365 : $kind eq 'bottom' ? $block->('bl', 'tu', 'br', 4) . (' ' x 11) . $block->('bl', 'tu', 'br', 2)
366 : $g->('lt') . join($g->('x'), ($bar) x 4) . $g->('x') . $bar . $g->($kind eq 'upper' ? 'td' : 'tu') . $bar
367 . $g->('x') . join($g->('x'), ($bar) x 2) . $g->('rt');
368 return ' ' . $self->_paint($line, 'grid');
369 }
370  
371 sub _tray {
372 my ($self, $side, $hand, $home, $mark) = @_;
373 my $pieces = sub {
374 my ($count, $which) = @_;
375 my @shown = map { $self->_paint($self->_glyph($side), $side) } 1 .. $count;
376 my $m = $mark->{"$which $side"};
377 if ($m && $m eq 'cursor') { push @shown, $self->_framed(undef, 'cursor') }
378 elsif ($m && @shown) { $shown[-1] = $self->_framed($side, $m) }
379 return @shown ? join(' ', @shown) : $self->_paint('none', 'quiet');
380 };
381 return sprintf ' %s hand %s home %s',
382 $self->_paint(sprintf('%-5s', $side), $side), $pieces->($hand->{$side}, 'hand'), $pieces->($home->{$side}, 'home');
383 }
384  
385 sub board_lines {
386 my ($self, $move) = @_;
387 my $game = $self->game;
388 my ($cell, $hand, $home, $mark) = $cells_after->($game, $move);
389 if (!$move) {
390 my %latest;
391 for my $entry (@{ $game->log }) {
392 $latest{ $entry->{side} } = $entry if defined $entry->{move};
393 }
394 for my $entry (values %latest) {
395 my (undef, $to) = split /-/, $entry->{move};
396 $mark->{$to} = 'last' if $to ne 'home' && defined $cell->{$to} && $cell->{$to} eq $entry->{side};
397 }
398 }
399 my @lines = (
400 $self->_tray('dark', $hand, $home, $mark),
401 ' ' . $self->_paint(join(' ', @FILES), 'label'),
402 $self->_border('top'),
403 $self->_row(3, $cell, $mark),
404 $self->_border('upper'),
405 $self->_row(2, $cell, $mark),
406 $self->_border('lower'),
407 $self->_row(1, $cell, $mark),
408 $self->_border('bottom'),
409 $self->_tray('light', $hand, $home, $mark),
410 );
411 push @lines, '', @{ $self->_route_lines } if $self->route;
412 return \@lines;
413 }
414  
415 sub _route_lines {
416 my ($self) = @_;
417 my $game = $self->game;
418 my $side = $game->side || $game->first;
419 my $variant = $game->variant;
420 my $route = $variant->route eq 'long' ? Game::RoyalUr::Engine::ROUTE_LONG() : Game::RoyalUr::Engine::ROUTE_SHORT();
421 my $index = $side eq 'light' ? Game::RoyalUr::Engine::SIDE_LIGHT() : Game::RoyalUr::Engine::SIDE_DARK();
422 my @lines = (' ' . $self->_paint('The ' . $variant->route . " route, as $side travels it:", 'quiet'));
423 for my $row (reverse 0 .. 2) {
424 my $line = ' ' . $self->_paint($row + 1, 'label') . ' ';
425 for my $file (0 .. 7) {
426 my $cell = Game::RoyalUr::Engine->cell_of($file, $row);
427 my $step = $cell < 0 ? 0 : Game::RoyalUr::Engine->route_step($route, $index, $cell);
428 $line .= $cell < 0 ? ' ' : $step ? $self->_paint(sprintf(' %2d ', $step), 'step') : $self->_paint(' . ', 'quiet');
429 }
430 push @lines, $line;
431 }
432 return \@lines;
433 }
434  
435 sub _roll_line {
436 my ($self) = @_;
437 my $game = $self->game;
438 return () if $game->is_over || !defined $game->roll;
439 my $throw = $game->throw;
440 my $roll = $game->roll;
441 my $marked = grep { $_ } @$throw;
442 my $text = sprintf ' %s rolled %s %s', $self->_who($game->side), $self->_paint($roll, 'key'), $self->_dice($throw);
443 $text .= $self->_paint(' (nothing marked is worth four)', 'quiet') if !$marked && $roll;
444 return $text;
445 }
446  
447 sub _result_line {
448 my ($self) = @_;
449 my $result = $self->game->result or return ();
450 my $home = $result->home;
451 return ' ' . $self->_paint('The game ran its full length with no end. It is drawn.', 'bad') if $result->is_draw;
452 my $winner = $result->winner;
453 return ' ' . $self->_paint(sprintf('%s won: %s resigned.', ucfirst $winner, $result->loser), 'good')
454 if $result->how eq 'resign';
455 return ' ' . $self->_paint(sprintf('%s won, all %d home to %d, in %d plies.',
456 ucfirst $winner, $home->{$winner}, $home->{ $result->loser }, $result->plies), 'good');
457 }
458  
459 sub _event_lines {
460 my ($self) = @_;
461 my @recent = @{ $self->_events };
462 @recent = @recent[ -4 .. -1 ] if @recent > 4;
463 return map { ' ' . $self->_paint($_->{text}, $_->{side} || 'quiet') } @recent;
464 }
465  
466 sub _readout {
467 my ($self, $move) = @_;
468 my $text = Game::RoyalUr::Notation::format_display($move);
469 my @does;
470 push @does, 'enters the board' if $move->from eq 'hand';
471 push @does, 'captures' if $move->captures;
472 push @does, 'lands on a rosette: roll again' if $move->rosette;
473 push @does, 'comes home' if $move->home;
474 return ' ' . $self->_paint($text, 'key') . (@does ? ' ' . join(', ', @does) : '');
475 }
476  
477 sub _legend {
478 my ($self, $mode) = @_;
479 my $k = sub { $self->_paint($_[0], 'key') };
480 return ' ' . join(' ', $k->('n') . ' new game', $k->('u') . ' take back',
481 ($self->history->can_redo ? $k->('r') . ' play again' : ()), $k->('q') . ' leave') if $mode eq 'ended';
482 return ' ' . $self->_paint('...', 'quiet') if $mode eq 'wait';
483 return ' ' . join(' ', $k->('arrows') . ' choose a piece', $k->('enter') . ' move it',
484 $k->('u') . ' take back', $k->('r') . ' play again', $k->('R') . ' route', $k->('?') . ' help', $k->('q') . ' leave');
485 }
486  
487 sub screen {
488 my ($self, $mode) = @_;
489 $mode = 'plain' unless defined $mode;
490 my $game = $self->game;
491 my $variant = $game->variant;
492 my @lines = (
493 ' ' . $self->_paint('The Royal Game of Ur', 'title') . ' '
494 . $self->_paint(join(', ', (defined $variant->name ? $variant->name : $variant->describe),
495 ($self->mode eq 'bot' ? 'you are ' . $self->side . ', against level ' . $self->level
496 : $self->mode eq 'hotseat' ? 'two players' : 'level ' . $self->level . ' against itself')), 'quiet'),
497 '',
498 );
499 if ($mode eq 'help') {
500 push @lines, map { " $_" } @{ $self->help_lines };
501 return \@lines;
502 }
503 my @moves = $mode eq 'pick' ? $self->candidates : ();
504 my $at = $self->_cursor;
505 $at = $#moves if $at > $#moves;
506 my $move = @moves ? $moves[$at] : undef;
507  
508 push @lines, @{ $self->board_lines($move) }, '';
509 push @lines, $self->_roll_line, $self->_result_line;
510 push @lines, $self->_readout($move) if $move;
511 push @lines, '';
512 push @lines, $self->_event_lines;
513 push @lines, ' ' . $self->_paint($self->_note, 'bad') if defined $self->_note;
514 push @lines, '', $self->_legend($mode) if $mode eq 'pick' || $mode eq 'ended' || $mode eq 'wait';
515 return \@lines;
516 }
517  
518 sub show {
519 my ($self, $mode) = @_;
520 $self->_screen->show($self->screen($mode));
521 return $self;
522 }
523  
524 sub help_lines {
525 return [
526 'A move is a piece. The roll says how far it goes, so choosing the piece is',
527 'the whole move.',
528 '',
529 ' arrows, tab walk the pieces that can move',
530 ' 1 to 7 go straight to one of them',
531 ' enter, space move it',
532 ' u take back your last turn and every reply to it',
533 ' r play a turn taken back again',
534 ' R show or hide the route',
535 ' n a new game',
536 ' q leave (asked twice)',
537 '',
538 'The board shows what the move would leave: [ ] where the piece was, ( ) where',
539 'it lands, and < > round a piece it sends back to its owner\'s hand.',
540 '',
541 'Typing instead: a number from the list, or a move such as hand-b1 or a2-d2;',
542 'and undo, redo, new, route, moves, record FILE, level N, help, quit.',
543 ];
544 }
545  
546 sub _enter_raw {
547 my ($self) = @_;
548 return 1 if $self->_raw;
549 return 0 unless $self->_keyboard->enter_raw;
550 $self->_screen->hide_cursor->clear unless $self->keysource;
551 return 1;
552 }
553  
554 sub pick {
555 my ($self) = @_;
556 my $leaving = 0;
557 $self->_cursor(0) if $self->_cursor > $self->candidates - 1;
558 while (1) {
559 $self->show('pick');
560 my $key = $self->_keyboard->read_key;
561 return undef if !defined $key || $key eq 'eof' || $key eq 'interrupt';
562 $self->_note(undef);
563 if ($key eq 'q' || $key eq 'escape') {
564 return 'quit' if $leaving;
565 $leaving = 1;
566 $self->_note('Press q again to leave the game, or any other key to stay.');
567 next;
568 }
569 $leaving = 0;
570 if ($key eq 'enter' || $key eq ' ') {
571 my @moves = $self->candidates;
572 return Game::RoyalUr::Notation::format_move($moves[ $self->_cursor ]);
573 }
574 return 'undo' if $key eq 'u';
575 return 'redo' if $key eq 'r';
576 return 'new' if $key eq 'n';
577 return 'route' if $key eq 'R';
578 if ($key eq '?') {
579 $self->show('help');
580 $self->_keyboard->read_key;
581 next;
582 }
583 $self->steer($key);
584 }
585 }
586  
587 sub _ended_key {
588 my ($self) = @_;
589 while (1) {
590 $self->show('ended');
591 my $key = $self->_keyboard->read_key;
592 return undef if !defined $key || $key eq 'eof' || $key eq 'interrupt';
593 return 'new' if $key eq 'n' || $key eq 'enter';
594 return 'undo' if $key eq 'u';
595 return 'redo' if $key eq 'r';
596 return 'quit' if $key eq 'q' || $key eq 'escape';
597 }
598 }
599  
600 sub _say {
601 my ($self, @lines) = @_;
602 $self->_screen->say(@lines) if @lines;
603 return;
604 }
605  
606 sub _read_line {
607 my ($self) = @_;
608 my $game = $self->game;
609 my $out = $self->out;
610 $self->_say(@{ $self->screen('plain') });
611 if (!$game->is_over) {
612 my @moves = $self->candidates;
613 $self->_say(map { sprintf ' %s %s', $self->_paint($_ + 1, 'key'), substr($self->_readout($moves[$_]), 4) } 0 .. $#moves);
614 }
615 my $line = $self->_keyboard->read_line(
616 $game->is_over ? 'new, undo or quit> ' : $game->side . ' (' . $game->roll . ')> ', $out);
617 print {$out} "\n" unless $self->interactive;
618 return $line;
619 }
620  
621 sub command {
622 my ($self, $line) = @_;
623 my $game = $self->game;
624 $self->_note(undef);
625 return 0 unless defined $line && length $line;
626 my ($word, $rest) = split ' ', $line, 2;
627 $word = lc $word;
628  
629 return 1 if $word eq 'quit' || $word eq 'q' || $word eq 'exit';
630 if ($word eq 'help' || $word eq '?') {
631 $self->_say(map { " $_" } @{ $self->help_lines });
632 return 0;
633 }
634 if ($word eq 'new' || $word eq 'n') {
635 $self->seed(Digest::SHA::sha256($self->seed . 'next'));
636 $self->game($self->_fresh_game);
637 $self->_events([]);
638 $self->_told(0);
639 $self->_cursor(0);
640 $self->history->start($self->game);
641 $self->_announce_opening;
642 return 0;
643 }
644 if ($word eq 'undo' || $word eq 'u') {
645 $self->take_back;
646 return 0;
647 }
648 if ($word eq 'redo' || $word eq 'r') {
649 $self->play_again;
650 return 0;
651 }
652 if ($word eq 'route') {
653 $self->route($self->route ? 0 : 1);
654 return 0;
655 }
656 if ($word eq 'moves') {
657 $self->_say(map { ' ' . $said->($_) } @{ $game->log });
658 return 0;
659 }
660 if ($word eq 'record') {
661 if (!defined $rest || !length $rest) { $self->_note('record wants the name of a file.') }
662 elsif ($self->save($rest)) { $self->_event(undef, "The game is written to $rest.") }
663 else { $self->_note("I could not write '$rest'.") }
664 return 0;
665 }
666 if ($word eq 'level') {
667 my @levels = Game::RoyalUr::Bot->levels($game->variant);
668 if (defined $rest && $rest =~ /\A\d+\z/ && $rest >= 1 && $rest <= $levels[-1]) {
669 $self->level($rest);
670 $self->_event(undef, "The program now plays at level $rest.");
671 }
672 else { $self->_note('A level is a number from 1 to ' . $levels[-1] . '.') }
673 return 0;
674 }
675 if ($game->is_over) {
676 $self->_note('The game is over. Type new, undo or quit.');
677 return 0;
678 }
679  
680 my $move = $line;
681 if ($line =~ /\A[1-7]\z/) {
682 my @moves = $self->candidates;
683 if ($line > @moves) {
684 $self->_note("There are only " . scalar(@moves) . " moves to choose from.");
685 return 0;
686 }
687 $move = $moves[ $line - 1 ];
688 }
689 if ($game->play($move)) {
690 $self->_cursor(0);
691 $self->_tell(1);
692 }
693 else {
694 my $error = $game->error;
695 $self->_note($error->code eq 'bad_move'
696 ? "I do not know '$line'. A move is two places, like hand-b1 or a2-d2, or its number in the list."
697 : ucfirst($error->message) . '.');
698 }
699 return 0;
700 }
701  
702 sub take_back {
703 my ($self) = @_;
704 $self->_keep;
705 my $game = $self->history->undo;
706 unless ($game) {
707 $self->_note('There is nothing to take back.');
708 return 0;
709 }
710 $self->swap($game);
711 $self->_event(undef, 'Taken back.');
712 return 1;
713 }
714  
715 sub play_again {
716 my ($self) = @_;
717 $self->_keep;
718 my $game = $self->history->redo;
719 unless ($game) {
720 $self->_note('There is nothing to play again.');
721 return 0;
722 }
723 $self->swap($game);
724 $self->_event(undef, 'Played again.');
725 return 1;
726 }
727  
728 sub _keep {
729 my ($self) = @_;
730 $self->history->record($self->game) if $self->mode ne 'watch';
731 return;
732 }
733  
734 sub swap {
735 my ($self, $game) = @_;
736 $self->game($game);
737 $self->_told(scalar @{ $game->log });
738 $self->_cursor(0);
739 $self->_note(undef);
740 return $self;
741 }
742  
743 sub person_turn {
744 my ($self) = @_;
745 $self->history->turn($self->game);
746 return $self;
747 }
748  
749 sub save {
750 my ($self, $file) = @_;
751 open my $fh, '>', $file or return 0;
752 print {$fh} $self->game->to_record;
753 return close $fh ? 1 : 0;
754 }
755  
756 sub _bot_move {
757 my ($self) = @_;
758 my $game = $self->game;
759 $self->show('wait') if $self->_raw;
760 my $bot = Game::RoyalUr::Bot->new(level => $self->level);
761 my $move = $bot->choose($game) or return;
762 $game->play_or_die($move);
763 $self->_tell(1);
764 return;
765 }
766  
767 sub _turns {
768 my ($self) = @_;
769 $self->_tell(1);
770 while (1) {
771 my $game = $self->game;
772 my $picking = $self->picking && $self->_raw;
773 if ($game->is_over) {
774 last if $self->mode eq 'watch' && !$self->interactive;
775 my $line = $picking ? $self->_ended_key : $self->_read_line;
776 last unless defined $line;
777 last if $self->command($line);
778 $self->_tell(1);
779 next;
780 }
781 if (!$self->_person($game->side)) {
782 $self->_bot_move;
783 next;
784 }
785 $self->person_turn;
786 my $line = $picking ? $self->pick : $self->_read_line;
787 last unless defined $line;
788 last if $self->command($line);
789 }
790 return;
791 }
792  
793 sub start {
794 my ($self) = @_;
795 $self->picking(0) if $self->picking && !$self->_enter_raw;
796  
797 Game::Terminal::Kit::Run::guard(sub { $self->_turns }, $self->_keyboard, $self->_screen);
798  
799 $self->_say(@{ $self->screen('plain') }) if $self->mode eq 'watch' || $self->game->is_over;
800 $self->save($self->record) if defined $self->record;
801 return 0;
802 }
803  
804 sub _usage {
805 return <<'USAGE';
806 royalur - the Royal Game of Ur, in a terminal
807  
808 royalur [options]
809  
810 --mode HOW bot (the default): you against the program
811 hotseat: two people at one keyboard
812 watch: the program against itself
813 --rules NAME finkel (the default) or masters
814 --level N how well the program plays, 1 upward; the top by default
815 --side WHICH light (the default) or dark: your side against the program
816 --first WHO light, dark, or roll (the default): throw the dice for it
817 --seed HEX hexadecimal; the same seed throws the same dice
818 --pace SECONDS how long a lost turn and the program's move stay up
819 --route show the order the squares are visited in
820 --record FILE write the game to FILE when you leave
821 --replay FILE carry on from a game written by --record
822 --ascii plain letters and lines, for a terminal with no Unicode
823 --unicode line and shape characters, where they are not the default
824 --no-colour no colour; nothing is lost without it
825 --no-pick type moves instead of choosing them with the arrow keys
826 --version the version, and stop
827 --help this, and stop
828  
829 In a terminal, the pieces that can move are walked with the arrow keys and the
830 board shows what each move would leave; press ? for the keys. Anywhere else,
831 type a number from the list, a move such as hand-b1 or a2-d2, or help.
832 USAGE
833 }
834  
835 sub options {
836 return [
837 { name => 'mode', type => 'enum', choices => [qw(bot hotseat watch)], help => 'you against the program, two people, or the program against itself' },
838 { name => 'rules', type => 'enum', choices => [qw(finkel masters)], help => 'the route and the rules' },
839 { name => 'level', type => 'int', min => 1, max => 4, help => 'how well the program plays; the top by default' },
840 { name => 'side', type => 'enum', choices => [qw(light dark)], help => 'your side against the program' },
841 { name => 'first', type => 'enum', choices => [qw(light dark roll)], help => 'who moves first, or throw the dice for it' },
842 { name => 'seed', type => 'str', help => 'hexadecimal; the same seed throws the same dice' },
843 ];
844 }
845  
846 sub run {
847 my ($class, @argv) = @_;
848  
849 my %given;
850 my $parsed = Getopt::Long::GetOptionsFromArray(
851 \@argv, \%given,
852 'mode=s', 'rules=s', 'level=i', 'side=s', 'first=s', 'seed=s', 'pace=s',
853 'record=s', 'replay=s', 'ascii', 'unicode!', 'route', 'colour|color!', 'pick!', 'version', 'help',
854 );
855  
856 if (!$parsed || @argv) {
857 print STDERR "royalur: I do not know '@argv'.\n" if $parsed && @argv;
858 print STDERR _usage();
859 return 2;
860 }
861 if ($given{help}) {
862 print _usage();
863 return 0;
864 }
865 if ($given{version}) {
866 print "royalur $Game::RoyalUr::VERSION\n";
867 return 0;
868 }
869  
870 my %with;
871 $with{$_} = $given{$_} for grep { defined $given{$_} } qw(mode rules level side first pace record route);
872 $with{colour} = $given{colour} if defined $given{colour};
873 $with{picking} = $given{pick} if defined $given{pick};
874 $with{unicode} = $given{unicode} if defined $given{unicode};
875 $with{unicode} = 0 if $given{ascii};
876  
877 if (defined $given{seed}) {
878 if ($given{seed} !~ /\A(?:[0-9a-fA-F]{2})+\z/) {
879 print STDERR "royalur: a seed is hexadecimal, two characters a byte.\n";
880 return 2;
881 }
882 $with{seed} = pack 'H*', $given{seed};
883 }
884  
885 if (defined $given{replay}) {
886 open my $fh, '<', $given{replay} or do {
887 print STDERR "royalur: I could not read '$given{replay}'.\n";
888 return 2;
889 };
890 my $text = do { local $/; <$fh> };
891 close $fh;
892 my ($game, $error) = Game::RoyalUr->replay($text);
893 if (!$game) {
894 my $detail = $error->detail;
895 print STDERR "royalur: '$given{replay}' is not a game I can replay: ", $error->message,
896 (defined $detail->{line} ? " (line $detail->{line})" : defined $detail->{ply} ? ' (turn ' . ($detail->{ply} + 1) . ')' : ''), ".\n";
897 return 2;
898 }
899 $with{game} = $game;
900 $with{rules} = $game->variant;
901 $with{seed} = $game->seed if defined $game->seed;
902 }
903  
904 my $terminal = eval { $class->new(%with) };
905 if (!$terminal) {
906 (my $why = $@) =~ s/ at \S+ line \d+\.?\s*\z//;
907 $why =~ s/\AGame::RoyalUr(?:::\w+)*: //;
908 print STDERR "royalur: $why.\n";
909 return 2;
910 }
911  
912 return $terminal->start;
913 }
914  
915 1;
916  
917 __END__
« blib/lib/Game/RoyalUr/Variant.pm ↑ Summary RoyalUr.xs »