Gin/Search.pm untested

filter: Statementstmt 0.0% 0 / 78 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 32 MC/DCmcdc 0.0% 0 / 17 Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 173 CC 17 SCAR 33.9
CC
17
Cov
0%
potential
56.0
knock_now
42.0
worth_taking
20.0
CRAP 29.7
1 package Game::Gin::Search;
2  
3 use strict;
4 use warnings;
5  
6 use Exporter 'import';
7  
8 use Game::Gin::Card qw(rank_of suit_of deadwood_of CARDS);
9 use Game::Gin::Deadwood qw(deadwood KNOCK_AT);
10  
11 our $VERSION = '0.04';
12 our @EXPORT_OK = qw(worth_taking best_discard knock_now potential LEVELS);
13  
14 use constant LEVELS => 2;
15  
16 sub potential {
17 my (%o) = @_;
18 my @hand = @{ $o{hand} || [] };
19 my $card = $o{card};
20 return 0 unless defined $card;
21  
22 my ($rank, $suit) = (rank_of($card), suit_of($card));
23 my $score = 0;
24 for my $other (@hand) {
25 next if $other == $card;
26 $score += 2 if rank_of($other) == $rank;
27 next unless suit_of($other) eq $suit;
28 my $gap = abs(rank_of($other) - $rank);
29 $score += 2 if $gap == 1;
30 $score += 1 if $gap == 2;
31 }
32 return $score;
33 }
34  
35 sub worth_taking {
36 my (%o) = @_;
37 my @hand = @{ $o{hand} || [] };
38 my $upcard = $o{upcard};
39 my $level = $o{level} || 1;
40 return 0 unless defined $upcard && @hand;
41  
42 my $now = deadwood(\@hand);
43 my @with = (@hand, $upcard);
44 my $best = best_discard(hand => \@with, level => $level, just_taken => $upcard);
45 return 0 unless defined $best;
46 my $after = deadwood([ grep { $_ != $best } @with ]);
47  
48 return $after < $now ? 1 : 0;
49 }
50  
51 sub best_discard {
52 my (%o) = @_;
53 my @hand = @{ $o{hand} || [] };
54 my $level = $o{level} || 1;
55 my $just = $o{just_taken};
56  
57 my @options = grep { !defined $just || $_ != $just } @hand;
58 return undef unless @options;
59  
60 my @ranked;
61 for my $card (@options) {
62 my $left = deadwood([ grep { $_ != $card } @hand ]);
63 push @ranked, {
64 card => $card,
65 left => $left,
66 pot => $level >= 2 ? potential(hand => \@hand, card => $card) : 0,
67 };
68 }
69  
70 @ranked = sort {
71 $a->{left} <=> $b->{left}
72 || $a->{pot} <=> $b->{pot}
73 || deadwood_of($b->{card}) <=> deadwood_of($a->{card})
74 || $a->{card} <=> $b->{card}
75 } @ranked;
76  
77 return $ranked[0]{card};
78 }
79  
80 sub knock_now {
81 my (%o) = @_;
82 my $deadwood = $o{deadwood};
83 my $level = $o{level} || 1;
84 my $stock_left = $o{stock_left} // 31;
85 return 0 unless defined $deadwood && $deadwood <= KNOCK_AT;
86  
87 return 1 if $deadwood == 0;
88 return 1 if $level <= 1;
89 return 1 if $stock_left <= 8;
90 return $deadwood <= 7 ? 1 : 0;
91 }
92  
93 1;
94  
95 __END__