| 1 | package Game::Merrills::Result; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Object::Proto::Sugar -types; | ||
| 7 | |||
| 8 | our $VERSION = '0.03'; | ||
| 9 | |||
| 10 | our (@REASONS, %REASON); | ||
| 11 | |||
| 12 | BEGIN { | ||
| 13 | @REASONS = qw/few blocked repetition no_mill agreement resign timeout/; | ||
| 14 | %REASON = map { $_ => 1 } @REASONS; | ||
| 15 | } | ||
| 16 | |||
| 17 | has winner => ( | ||
| 18 | is => 'ro' | ||
| 19 | ); | ||
| 20 | |||
| 21 | has reason => ( | ||
| 22 | is => 'ro', | ||
| 23 | isa => Str | ||
| 24 | ); | ||
| 25 | |||
| 26 | sub BUILD { | ||
| 27 | my ($self) = @_; | ||
| 28 | my $reason = $self->reason; | ||
| 29 | die 'reason must be one of ' . join(', ', @REASONS) . ', got ' | ||
| 30 | . (defined $reason ? "'$reason'" : 'undef') | ||
| 31 | unless defined $reason && $REASON{$reason}; | ||
| 32 | my $winner = $self->winner; | ||
| 33 | die "winner must be white, black or undef for a draw, got '$winner'" | ||
| 34 | if defined $winner && $winner ne 'white' && $winner ne 'black'; | ||
| 35 | my $drawn = $reason eq 'repetition' || $reason eq 'no_mill' || $reason eq 'agreement'; | ||
| 36 | die "a game that ends by $reason is a draw and has no winner" | ||
| 37 | if $drawn && defined $winner; | ||
| 38 | die "a game that ends by $reason has a winner" | ||
| 39 | if !$drawn && !defined $winner; | ||
| 40 | return $self; | ||
| 41 | } | ||
| 42 | |||
| 43 | sub reasons { | ||
| 44 | return @REASONS; | ||
| 45 | } | ||
| 46 | |||
| 47 | sub is_draw { | ||
| 48 | return defined $_[0]->winner ? 0 : 1; | ||
| 49 | } | ||
| 50 | |||
| 51 | sub loser { | ||
| 52 | my ($self) = @_; | ||
| 53 | return undef if $self->is_draw; | ||
| 54 | return $self->winner eq 'white' ? 'black' : 'white'; | ||
| 55 | } | ||
| 56 | |||
| 57 | sub stringify { | ||
| 58 | my ($self) = @_; | ||
| 59 | my $reason = $self->reason; | ||
| 60 | return 'Draw: agreed' if $reason eq 'agreement'; | ||
| 61 | return 'Draw: the same position three times' if $reason eq 'repetition'; | ||
| 62 | return 'Draw: too long without a mill' if $reason eq 'no_mill'; | ||
| 63 | my $loser = ucfirst $self->loser; | ||
| 64 | my $winner = ucfirst $self->winner; | ||
| 65 | return "$winner wins: $loser has fewer than three men" if $reason eq 'few'; | ||
| 66 | return "$winner wins: $loser has no move" if $reason eq 'blocked'; | ||
| 67 | return "$winner wins: $loser resigned" if $reason eq 'resign'; | ||
| 68 | return "$winner wins: $loser ran out of time"; | ||
| 69 | } | ||
| 70 | |||
| 71 | 1; | ||
| 72 | |||
| 73 | __END__ |