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

filter: Statementstmt 0.0% 0 / 65 Branchbran 0.0% 0 / 24 Conditioncond 0.0% 0 / 23 MC/DCmcdc 0.0% 0 / 14 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 141 CC 13 SCAR 39.1
CC
13
Cov
0%
settle
110.0
places
6.0
winner
6.0
CRAP 50.0
1 package Game::Mahjong::Result;
2  
3 use 5.010;
4 use strict;
5 use warnings;
6  
7 our $VERSION = '0.04';
8  
9 use constant BASE => 8;
10 use constant SEATS => 4;
11 use constant HANDS => 16;
12 use constant ROUNDS => 4;
13  
14 sub settle {
15 my (%o) = @_;
16 my @deltas = (0) x SEATS;
17 my $by = $o{by} // '';
18 return \@deltas if $by eq 'exhausted';
19  
20 my $winner = $o{winner};
21 die 'Game::Mahjong::Result: the winner is a seat 0 to 3'
22 unless defined $winner && $winner =~ /\A[0-3]\z/;
23 my $points = $o{points};
24 die 'Game::Mahjong::Result: points are a whole number'
25 unless defined $points && $points =~ /\A\d+\z/;
26  
27 if ($by eq 'self') {
28 for my $seat (0 .. SEATS - 1) {
29 next if $seat == $winner;
30 $deltas[$seat] -= BASE + $points;
31 $deltas[$winner] += BASE + $points;
32 }
33 return \@deltas;
34 }
35 if ($by eq 'discard' || $by eq 'rob') {
36 my $from = $o{from};
37 die 'Game::Mahjong::Result: a win by discard names the discarder'
38 unless defined $from && $from =~ /\A[0-3]\z/ && $from != $winner;
39 for my $seat (0 .. SEATS - 1) {
40 next if $seat == $winner;
41 my $gives = $seat == $from ? BASE + $points : BASE;
42 $deltas[$seat] -= $gives;
43 $deltas[$winner] += $gives;
44 }
45 return \@deltas;
46 }
47 die "Game::Mahjong::Result: no such way to win '$by'";
48 }
49  
50 sub places {
51 my ($totals) = @_;
52 my @seats = sort { $totals->[$b] <=> $totals->[$a] || $a <=> $b } 0 .. $#$totals;
53 my (@places, $place, $last);
54 for my $i (0 .. $#seats) {
55 my $seat = $seats[$i];
56 if (!defined $last || $totals->[$seat] != $last) {
57 $place = $i + 1;
58 $last = $totals->[$seat];
59 }
60 $places[$seat] = $place;
61 }
62 return \@places;
63 }
64  
65 sub winner {
66 my ($totals) = @_;
67 my $places = places($totals);
68 my @first = grep { $places->[$_] == 1 } 0 .. $#$places;
69 return @first == 1 ? $first[0] : undef;
70 }
71  
72 sub finished {
73 my ($hands_played) = @_;
74 return $hands_played >= HANDS ? 1 : 0;
75 }
76  
77 1;
78  
79 __END__