Dominoes.pm

filter: Statementstmt 85.7% 12 / 14 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 89.4% 17 / 19 CC 1 SCAR 0.6
CC
1
Cov
86%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Dominoes/Notation.pm ↑ Summary Dominoes/Set.pm »
1 package Game::Dominoes;
2  
3 14 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 14 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 14 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 14 ▶use Digest::SHA ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 0 ▶use Object::Proto::Sugar -types;
Subroutine BEGIN: called CC=1 SCAR=2.6
9  
10 use Game::Dominoes::Tile;
11 use Game::Dominoes::Set;
12 use Game::Dominoes::Hand;
13 use Game::Dominoes::Boneyard;
14 use Game::Dominoes::Play;
15 use Game::Dominoes::Layout;
16 use Game::Dominoes::Rules;
17 use Game::Dominoes::Scoring;
18 use Game::Dominoes::Notation;
19 use Game::Dominoes::Error;
20 use Game::Dominoes::Result;
21  
22 our $VERSION = '0.04';
23  
24 our %HAND_SIZE = (2 => 9, 3 => 7, 4 => 5);
25  
26 our %TARGET = (2 => 250, 3 => 200, 4 => 200);
27  
28 our @VARIANTS = qw/all_fives draw block/;
29  
30 has seed => (is => 'ro', isa => Str);
31 has players => (is => 'ro', isa => Int, default => 2);
32 has variant => (is => 'ro', isa => Str, default => 'all_fives');
33 has target => (is => 'rw', isa => Int);
34 has scale => (is => 'ro', isa => Int, default => 1);
35 has reserve => (is => 'ro', isa => Int, default => 0);
36  
37 has status => (is => 'rw', isa => Str, default => 'active');
38 has hand_number => (is => 'rw', isa => Int, default => 0);
39 has turn => (is => 'rw', isa => Int);
40 has hands => (is => 'rw', isa => HashRef, default => {});
41 has scores => (is => 'rw', isa => HashRef, default => {});
42 has boneyard => (is => 'rw', isa => Object);
43 has layout => (is => 'rw', isa => Object);
44 has result => (is => 'rw', isa => Object);
45 has history => (is => 'rw', isa => ArrayRef, default => []);
46  
47 has leader => (is => 'rw', isa => Int);
48 has forced_tile => (is => 'rw', isa => Object);
49  
50 has passes => (is => 'rw', isa => Int, default => 0);
51  
52 has deductions => (is => 'rw', isa => HashRef, default => {});
53  
54 sub BUILD {
55 my ($self) = @_;
56  
57 die 'Game::Dominoes: seed must be 32 bytes'
58 unless defined $self->seed && length $self->seed == 32;
59 die 'Game::Dominoes: players must be 2, 3 or 4'
60 unless $HAND_SIZE{ $self->players };
61 die 'Game::Dominoes: unknown variant ' . $self->variant
62 unless grep { $_ eq $self->variant } @VARIANTS;
63 die 'Game::Dominoes: scale must be a positive integer'
64 unless $self->scale >= 1;
65  
66 $self->target($TARGET{ $self->players } / $self->scale)
67 unless defined $self->target;
68 die 'Game::Dominoes: target must be a positive integer'
69 unless $self->target > 0;
70  
71 $self->scores({ map { $_ => 0 } $self->seats })
72 unless keys %{ $self->scores };
73 $self->leader($self->_by_lot(1)) unless defined $self->leader;
74  
75 if (keys %{ $self->hands }) {
76 $self->layout(Game::Dominoes::Layout->new) unless $self->layout;
77 $self->boneyard(Game::Dominoes::Boneyard->new(reserve => $self->reserve))
78 unless $self->boneyard;
79 $self->hand_number(1) unless $self->hand_number;
80 $self->turn($self->leader) unless defined $self->turn;
81 }
82 else {
83 $self->_deal;
84 }
85 return $self;
86 }
87  
88 sub seats { return 1 .. $_[0]->players }
89  
90 sub hand_size { return $HAND_SIZE{ $_[0]->players } }
91  
92 sub _by_lot {
93 my ($self, $n) = @_;
94 my $word = unpack 'N', Digest::SHA::sha256($self->seed . "lot:$n");
95 my $limit = int(4294967296 / $self->players) * $self->players;
96 my $i = 0;
97 while ($word >= $limit) {
98 $word = unpack 'N', Digest::SHA::sha256($self->seed . "lot:$n:" . ++$i);
99 }
100 return ($word % $self->players) + 1;
101 }
102  
103 sub _note {
104 my ($self, $kind, %rest) = @_;
105 push @{ $self->history }, { kind => $kind, hand => $self->hand_number, %rest };
106 return;
107 }
108  
109 sub _deal {
110 my ($self) = @_;
111  
112 $self->hand_number($self->hand_number + 1);
113 my $order = Game::Dominoes::Set::order_for($self->seed, $self->hand_number);
114 my $size = $self->hand_size;
115  
116 my %hands;
117 my $at = 0;
118 for my $seat ($self->seats) {
119 my @ids = @{$order}[ $at .. $at + $size - 1 ];
120 $at += $size;
121 $hands{$seat} = Game::Dominoes::Hand->new(
122 tiles => [ map { Game::Dominoes::Set::tile_of($_) } @ids ]
123 );
124 }
125  
126 $self->hands(\%hands);
127 $self->boneyard(Game::Dominoes::Boneyard->new(
128 reserve => $self->reserve,
129 tiles => [ map { Game::Dominoes::Set::tile_of($_) } @{$order}[ $at .. $#$order ] ],
130 ));
131 $self->layout(Game::Dominoes::Layout->new);
132 $self->turn($self->leader);
133 $self->passes(0);
134 $self->forced_tile(undef);
135 $self->deductions({});
136  
137 $self->_note('deal', seat => $self->leader);
138 return;
139 }
140  
141 sub hand { return $_[0]->hands->{ $_[1] } }
142  
143 sub hand_count {
144 my ($self, $seat) = @_;
145 my $hand = $self->hands->{$seat} or return 0;
146 return $hand->count;
147 }
148  
149 sub boneyard_count { return $_[0]->boneyard->count }
150  
151 sub open_ends { return $_[0]->layout->open_ends }
152  
153 sub count { return Game::Dominoes::Scoring::count($_[0]->layout) }
154  
155 sub legal {
156 my ($self, $seat) = @_;
157 return [] unless $self->status eq 'active';
158 return [] unless defined $seat && defined $self->turn && $seat == $self->turn;
159  
160 my $hand = $self->hands->{$seat} or return [];
161 my $moves = Game::Dominoes::Rules::candidates($self->layout, $hand);
162  
163 if (my $forced = $self->forced_tile) {
164 $moves = [ grep { $_->{tile}->id == $forced->id } @$moves ];
165 }
166  
167 return [ map { {
168 kind => 'play',
169 tile => $_->{tile},
170 arm => $_->{arm},
171 points => Game::Dominoes::Rules::score_of(
172 $self->layout, $_->{tile}, $_->{arm}, $self->scale
173 ),
174 } } @$moves ];
175 }
176  
177 sub view {
178 my ($self, $seat) = @_;
179 $seat = 'spectator' unless defined $seat;
180 my $own = ($seat ne 'spectator' && $self->hands->{$seat}) ? $self->hands->{$seat} : undef;
181  
182 return {
183 seat => $seat,
184 players => $self->players,
185 variant => $self->variant,
186 target => $self->target,
187 scale => $self->scale,
188 status => $self->status,
189 turn => $self->turn,
190 hand_number => $self->hand_number,
191 scores => { %{ $self->scores } },
192 layout => $self->layout,
193 ends => [ $self->open_ends ],
194 count => $self->count,
195 counts => { map { $_ => $self->hand_count($_) } $self->seats },
196 boneyard => $self->boneyard_count,
197 deductions => { map { $_ => { %{ $self->deductions->{$_} || {} } } } $self->seats },
198 forced => $self->forced_tile,
199 hand => $own ? [ @{ $own->tiles } ] : undef,
200 count_own => $own ? $own->count : 0,
201 };
202 }
203  
204 sub _error { return Game::Dominoes::Error->throw($_[1], @_[2 .. $#_]) }
205  
206 sub _move_of {
207 my ($self, $move) = @_;
208 return undef unless defined $move;
209  
210 if (!ref $move) {
211 my $parsed = eval { Game::Dominoes::Notation::parse_move($move) };
212 return undef unless $parsed && ($parsed->{kind} // '') eq 'play';
213 return { tile => $parsed->{tile}, arm => $parsed->{arm} };
214 }
215 if (ref $move eq 'HASH') {
216 my $tile = $move->{tile};
217 return undef unless defined $tile;
218 $tile = eval { Game::Dominoes::Notation::parse_tile($tile) } unless ref $tile;
219 return undef unless ref $tile;
220 return { tile => $tile, arm => $move->{arm} };
221 }
222 return { tile => $move->tile, arm => $move->arm };
223 }
224  
225 sub play {
226 my ($self, $seat, $move) = @_;
227  
228 return $self->_error('game_over') unless $self->status eq 'active';
229 return $self->_error('not_your_turn')
230 unless defined $seat && defined $self->turn && $seat == $self->turn;
231  
232 my $want = $self->_move_of($move);
233 return $self->_error('bad_move') unless $want && ref $want->{tile};
234  
235 my $hand = $self->hands->{$seat};
236 return $self->_error('tile_not_held') unless $hand->holds($want->{tile});
237  
238 if (my $forced = $self->forced_tile) {
239 return $self->_error('tile_not_held')
240 unless $want->{tile}->id == $forced->id;
241 }
242  
243 my $layout = $self->layout;
244 my $arm = $want->{arm};
245 $arm = ($layout->arms_open)[0] unless defined $arm;
246 return $self->_error('no_such_arm')
247 unless grep { $_ eq $arm } @Game::Dominoes::Layout::ARMS;
248 return $self->_error('arm_closed')
249 unless grep { $_ eq $arm } $layout->arms_open;
250 return $self->_error('end_mismatch')
251 unless $layout->can_place($want->{tile}, $arm);
252  
253 $hand->remove($want->{tile});
254 my $play = $layout->place($want->{tile}, $arm);
255 $self->forced_tile(undef);
256 $self->passes(0);
257  
258 my $points = Game::Dominoes::Scoring::score_for($self->count, $self->scale);
259 $play->points($points);
260 $self->_award($seat, $points) if $points;
261 $self->_note('play', seat => $seat, play => $play, points => $points);
262  
263 return $play if $self->_check_target;
264  
265 if ($hand->is_empty) {
266 $self->_end_hand('out', $seat);
267 return $play;
268 }
269  
270 $self->_advance;
271 return $play;
272 }
273  
274 sub _award {
275 my ($self, $seat, $points) = @_;
276 $self->scores->{$seat} += $points;
277 return;
278 }
279  
280 sub _check_target {
281 my ($self) = @_;
282 my ($high) = sort { $b <=> $a } values %{ $self->scores };
283 return 0 unless $high >= $self->target;
284 $self->_finish('target');
285 return 1;
286 }
287  
288 sub _advance {
289 my ($self) = @_;
290  
291 for (1 .. $self->players * 2) {
292 $self->turn($self->turn % $self->players + 1);
293 $self->forced_tile(undef);
294  
295 my $hand = $self->hands->{ $self->turn };
296 return if Game::Dominoes::Rules::can_play($self->layout, $hand);
297  
298 my $drawn = 0;
299 while ($self->boneyard->can_draw) {
300 my $tile = $self->boneyard->draw;
301 $hand->add($tile);
302 $drawn++;
303 next unless Game::Dominoes::Rules::can_play($self->layout, $hand);
304 $self->forced_tile($tile);
305 last;
306 }
307 $self->_note('draw', seat => $self->turn, count => $drawn) if $drawn;
308 return if $self->forced_tile;
309  
310 my @shut = $self->layout->open_ends;
311 $self->deductions->{ $self->turn }{$_} = 1 for @shut;
312  
313 $self->_note('pass', seat => $self->turn, cannot => [ sort { $a <=> $b } @shut ]);
314 $self->passes($self->passes + 1);
315 if ($self->passes >= $self->players) {
316 $self->_end_hand('blocked');
317 return;
318 }
319 }
320 return;
321 }
322  
323 sub _end_hand {
324 my ($self, $reason, $out) = @_;
325  
326 my %pips = map { $_ => $self->hands->{$_}->pips } $self->seats;
327  
328 if ($reason eq 'out') {
329 my $total = 0;
330 $total += $pips{$_} for grep { $_ != $out } $self->seats;
331 my $points = Game::Dominoes::Scoring::bonus($total, $self->scale);
332 $self->_award($out, $points);
333 $self->_note('hand_end', reason => 'out', seat => $out,
334 points => $points, pips => \%pips);
335 $self->leader($out);
336 }
337 else {
338 my ($low) = sort { $a <=> $b } values %pips;
339 my @light = sort { $a <=> $b } grep { $pips{$_} == $low } $self->seats;
340  
341 if (@light == 1) {
342 my $total = 0;
343 $total += $pips{$_} for grep { $_ != $light[0] } $self->seats;
344 my $points = Game::Dominoes::Scoring::bonus($total, $self->scale);
345 $self->_award($light[0], $points);
346 $self->_note('hand_end', reason => 'blocked', seat => $light[0],
347 points => $points, pips => \%pips);
348 }
349 elsif (@light == 2 && $self->players == 3) {
350 my ($third) = grep { $pips{$_} != $low } $self->seats;
351 my $points = Game::Dominoes::Scoring::bonus($pips{$third}, $self->scale);
352 my $each = int($points / 2);
353 $self->_award($light[0], $points - $each);
354 $self->_award($light[1], $each);
355 $self->_note('hand_end', reason => 'blocked_split',
356 seats => \@light, points => $points, pips => \%pips);
357 }
358 else {
359 $self->_note('hand_end', reason => 'blocked_tied',
360 seats => \@light, points => 0, pips => \%pips);
361 }
362 $self->leader($self->_by_lot($self->hand_number + 1));
363 }
364  
365 return if $self->_check_target;
366 $self->_deal;
367 return;
368 }
369  
370 sub _finish {
371 my ($self, $reason, $seat) = @_;
372 $self->status('finished');
373 $self->turn(undef);
374 $self->result(Game::Dominoes::Result->new(
375 places => $self->places,
376 scores => { %{ $self->scores } },
377 reason => $reason,
378 ));
379 $self->_note('game_end', reason => $reason, (defined $seat ? (seat => $seat) : ()));
380 return;
381 }
382  
383 sub places {
384 my ($self) = @_;
385 my $scores = $self->scores;
386 my @order = sort { $scores->{$b} <=> $scores->{$a} } $self->seats;
387  
388 my (%place, $last, $rank);
389 my $seen = 0;
390 for my $seat (@order) {
391 $seen++;
392 if (!defined $last || $scores->{$seat} != $last) {
393 $rank = $seen;
394 $last = $scores->{$seat};
395 }
396 $place{$seat} = $rank;
397 }
398 return \%place;
399 }
400  
401 sub resign {
402 my ($self, $seat) = @_;
403 return $self->_error('game_over') unless $self->status eq 'active';
404 return $self->_error('not_your_turn')
405 unless defined $seat && $self->hands->{$seat};
406  
407 my $scores = $self->scores;
408 my ($high) = sort { $b <=> $a } map { $scores->{$_} } grep { $_ != $seat } $self->seats;
409 $scores->{$seat} = -1 if $scores->{$seat} >= $high;
410 $self->_finish('resign', $seat);
411 return $self->result;
412 }
413  
414 our @HEADER = qw/seed players variant target scale reserve resigned/;
415  
416 sub to_text {
417 my ($self, %opt) = @_;
418 my (@moves, $resigned);
419 for my $event (@{ $self->history }) {
420 push @moves, $event->{play} if $event->{kind} eq 'play';
421 push @moves, { kind => 'draw', count => $event->{count} }
422 if $event->{kind} eq 'draw';
423 push @moves, { kind => 'pass' } if $event->{kind} eq 'pass';
424 push @moves, { kind => 'hand_end' } if $event->{kind} eq 'hand_end';
425 $resigned = $event->{seat}
426 if $event->{kind} eq 'game_end' && $event->{reason} eq 'resign';
427 }
428 my $log = Game::Dominoes::Notation::to_text(\@moves);
429 return $log unless $opt{with_seed};
430  
431 my @lines = (
432 'seed ' . unpack('H*', $self->seed),
433 map({ "$_ " . $self->$_ } qw/players variant target scale reserve/),
434 (defined $resigned ? "resigned $resigned" : ()),
435 "moves $log",
436 );
437 return join "\n", @lines;
438 }
439  
440 sub from_text {
441 my ($class, $text, %args) = @_;
442  
443 die 'Game::Dominoes: from_text wants the text of a game'
444 unless defined $text && !ref $text;
445  
446 my %known = map { $_ => 1 } @HEADER, 'moves';
447 my @lines = grep { /\S/ } split /\r?\n/, $text;
448 my (%field, $log);
449  
450 if (grep { /\A\s*(\w+)/ && $known{$1} } @lines) {
451 for my $line (@lines) {
452 $line =~ s/\A\s+//;
453 $line =~ s/\s+\z//;
454 my ($key, $value) = $line =~ /\A(\w+)(?:\s+(.*))?\z/;
455 die "Game::Dominoes: from_text does not know the line '$line'"
456 unless defined $key && $known{$key};
457 die "Game::Dominoes: from_text found two $key lines"
458 if exists $field{$key};
459 $field{$key} = defined $value ? $value : '';
460 }
461 die 'Game::Dominoes: from_text found no moves line'
462 unless exists $field{moves};
463 $log = delete $field{moves};
464  
465 if (exists $field{seed}) {
466 die 'Game::Dominoes: the seed must be 64 hexadecimal digits'
467 unless $field{seed} =~ /\A[0-9a-fA-F]{64}\z/;
468 $field{seed} = pack 'H*', $field{seed};
469 }
470 for my $key (qw/players target scale reserve resigned/) {
471 next unless exists $field{$key};
472 die "Game::Dominoes: $key must be a whole number, not '$field{$key}'"
473 unless $field{$key} =~ /\A-?\d+\z/;
474 }
475 }
476 else {
477 $log = $text;
478 }
479  
480 %field = (%args, %field);
481 my $resigned = delete $field{resigned};
482 die 'Game::Dominoes: from_text needs the seed, in the text or as an argument'
483 unless defined $field{seed};
484  
485 my $moves = eval { Game::Dominoes::Notation::from_text($log) };
486 unless ($moves) {
487 (my $why = $@) =~ s/ at \S+ line \d+\.?\n\z//;
488 die "Game::Dominoes: from_text could not read the moves: $why";
489 }
490  
491 my $game = $class->new(%field);
492 my $n = 0;
493 for my $move (@$moves) {
494 $n++;
495 next unless $move->{kind} eq 'play';
496 my $token = Game::Dominoes::Notation::move_text($move);
497 die "Game::Dominoes: move $n, $token, comes after the game is over"
498 unless $game->status eq 'active';
499 my $out = $game->play($game->turn, { tile => $move->{tile}, arm => $move->{arm} });
500 die "Game::Dominoes: move $n, $token, was refused: " . $out->message
501 if ref $out eq 'Game::Dominoes::Error';
502 }
503  
504 die 'Game::Dominoes: the draws, passes and ends of hands in the text are not the ones its plays make'
505 unless $game->to_text eq Game::Dominoes::Notation::to_text($moves);
506  
507 if (defined $resigned) {
508 die "Game::Dominoes: seat $resigned cannot resign here"
509 unless $game->status eq 'active' && $game->hands->{$resigned};
510 $game->resign($resigned);
511 }
512  
513 return $game;
514 }
515  
516 1;
517  
518 __END__
« Dominoes/Notation.pm ↑ Summary Dominoes/Set.pm »