| 1 | package Game::Gin::Meld; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Exporter 'import'; | ||
| 7 | |||
| 8 | use Game::Gin::Card qw(rank_of suit_of); | ||
| 9 | |||
| 10 | our $VERSION = '0.04'; | ||
| 11 | our @EXPORT_OK = qw(melds_in is_meld is_set is_run MIN_MELD); | ||
| 12 | |||
| 13 | use constant MIN_MELD => 3; | ||
| 14 | |||
| 15 | sub is_set { | ||
| 16 | my ($cards) = @_; | ||
| 17 | return 0 unless @$cards >= MIN_MELD && @$cards <= 4; | ||
| 18 | my $rank = rank_of($cards->[0]); | ||
| 19 | my %suit; | ||
| 20 | for my $c (@$cards) { | ||
| 21 | return 0 unless rank_of($c) == $rank; | ||
| 22 | return 0 if $suit{ suit_of($c) }++; | ||
| 23 | } | ||
| 24 | return 1; | ||
| 25 | } | ||
| 26 | |||
| 27 | sub is_run { | ||
| 28 | my ($cards) = @_; | ||
| 29 | return 0 unless @$cards >= MIN_MELD; | ||
| 30 | my $suit = suit_of($cards->[0]); | ||
| 31 | my @rank; | ||
| 32 | for my $c (@$cards) { | ||
| 33 | return 0 unless suit_of($c) eq $suit; | ||
| 34 | push @rank, rank_of($c); | ||
| 35 | } | ||
| 36 | @rank = sort { $a <=> $b } @rank; | ||
| 37 | for my $i (1 .. $#rank) { | ||
| 38 | return 0 unless $rank[$i] == $rank[ $i - 1 ] + 1; | ||
| 39 | } | ||
| 40 | return 1; | ||
| 41 | } | ||
| 42 | |||
| 43 | sub is_meld { my ($cards) = @_; return is_set($cards) || is_run($cards) ? 1 : 0 } | ||
| 44 | |||
| 45 | sub melds_in { | ||
| 46 | my ($cards) = @_; | ||
| 47 | my @out; | ||
| 48 | |||
| 49 | my %by_rank; | ||
| 50 | push @{ $by_rank{ rank_of($_) } }, $_ for @$cards; | ||
| 51 | for my $rank (sort { $a <=> $b } keys %by_rank) { | ||
| 52 | my @same = sort { $a <=> $b } @{ $by_rank{$rank} }; | ||
| 53 | next unless @same >= MIN_MELD; | ||
| 54 | push @out, [@same]; | ||
| 55 | if (@same == 4) { | ||
| 56 | for my $skip (0 .. 3) { | ||
| 57 | push @out, [ map { $same[$_] } grep { $_ != $skip } 0 .. 3 ]; | ||
| 58 | } | ||
| 59 | } | ||
| 60 | } | ||
| 61 | |||
| 62 | my %by_suit; | ||
| 63 | push @{ $by_suit{ suit_of($_) } }, $_ for @$cards; | ||
| 64 | for my $suit (sort keys %by_suit) { | ||
| 65 | my @same = sort { rank_of($a) <=> rank_of($b) } @{ $by_suit{$suit} }; | ||
| 66 | next unless @same >= MIN_MELD; | ||
| 67 | |||
| 68 | my $start = 0; | ||
| 69 | for my $i (1 .. @same) { | ||
| 70 | my $breaks = $i == @same | ||
| 71 | || rank_of($same[$i]) != rank_of($same[ $i - 1 ]) + 1; | ||
| 72 | next unless $breaks; | ||
| 73 | my @stretch = @same[ $start .. $i - 1 ]; | ||
| 74 | for my $len (MIN_MELD .. scalar @stretch) { | ||
| 75 | for my $at (0 .. @stretch - $len) { | ||
| 76 | push @out, [ @stretch[ $at .. $at + $len - 1 ] ]; | ||
| 77 | } | ||
| 78 | } | ||
| 79 | $start = $i; | ||
| 80 | } | ||
| 81 | } | ||
| 82 | |||
| 83 | return @out; | ||
| 84 | } | ||
| 85 | |||
| 86 | 1; | ||
| 87 | |||
| 88 | __END__ |