| 1 | package Game::Dominoes::Result; | ||
| 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 | our $VERSION = '0.04'; | ||
| 9 | |||
| 10 | our @REASONS; | ||
| 11 | |||
| 12 | BEGIN { @REASONS = qw/target blocked resign timeout/ } | ||
| 13 | |||
| 14 | has places => ( | ||
| 15 | is => 'ro', | ||
| 16 | isa => HashRef, | ||
| 17 | default => {} | ||
| 18 | ); | ||
| 19 | |||
| 20 | has scores => ( | ||
| 21 | is => 'ro', | ||
| 22 | isa => HashRef, | ||
| 23 | default => {} | ||
| 24 | ); | ||
| 25 | |||
| 26 | has reason => ( | ||
| 27 | is => 'ro', | ||
| 28 | isa => Str | ||
| 29 | ); | ||
| 30 | |||
| 31 | sub BUILD { | ||
| 32 | my ($self) = @_; | ||
| 33 | if (defined $self->reason) { | ||
| 34 | die 'Game::Dominoes::Result: unknown reason ' . $self->reason | ||
| 35 | unless grep { $_ eq $self->reason } @REASONS; | ||
| 36 | } | ||
| 37 | return $self; | ||
| 38 | } | ||
| 39 | |||
| 40 | sub reasons { | ||
| 41 | return [@REASONS]; | ||
| 42 | } | ||
| 43 | |||
| 44 | sub winners { | ||
| 45 | my ($self) = @_; | ||
| 46 | my $places = $self->places; | ||
| 47 | return [ sort { $a <=> $b } grep { $places->{$_} == 1 } keys %$places ]; | ||
| 48 | } | ||
| 49 | |||
| 50 | sub winner { | ||
| 51 | my ($self) = @_; | ||
| 52 | my $winners = $self->winners; | ||
| 53 | return @$winners == 1 ? $winners->[0] : undef; | ||
| 54 | } | ||
| 55 | |||
| 56 | sub is_draw { | ||
| 57 | return @{ $_[0]->winners } > 1 ? 1 : 0; | ||
| 58 | } | ||
| 59 | |||
| 60 | sub seats { | ||
| 61 | my ($self) = @_; | ||
| 62 | return [ sort { $a <=> $b } keys %{ $self->places } ]; | ||
| 63 | } | ||
| 64 | |||
| 65 | sub ranking { | ||
| 66 | my ($self) = @_; | ||
| 67 | my $places = $self->places; | ||
| 68 | my %by; | ||
| 69 | push @{ $by{ $places->{$_} } }, $_ for keys %$places; | ||
| 70 | return [ map { [ sort { $a <=> $b } @{ $by{$_} } ] } sort { $a <=> $b } keys %by ]; | ||
| 71 | } | ||
| 72 | |||
| 73 | sub stringify { | ||
| 74 | my ($self) = @_; | ||
| 75 | my $scores = $self->scores; | ||
| 76 | my $order = join ', ', map { | ||
| 77 | join(' and ', map { "seat $_" } @$_) . ' (' . ($scores->{ $_->[0] } // 0) . ')' | ||
| 78 | } @{ $self->ranking }; | ||
| 79 | my $head = $self->is_draw ? 'Drawn' : 'Seat ' . $self->winner . ' wins'; | ||
| 80 | return $head . ' by ' . ($self->reason // 'unknown') . ': ' . $order; | ||
| 81 | } | ||
| 82 | |||
| 83 | 1; | ||
| 84 | |||
| 85 | __END__ | ||