blib/lib/Games/GUI/Battleship/AI/Naive.pm untested

filter: Statementstmt 0.0% 0 / 76 Branchbran 0.0% 0 / 4 Conditioncond 0.0% 0 / 11 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 8 Podpod n/a totaltotal 0.0% 0 / 99 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package Games::GUI::Battleship::AI::Naive;
2  
3 use v5.38;
4 use experimental 'signatures';
5 use feature 'try';
6 no warnings 'experimental::try';
7 use parent 'Games::GUI::Battleship::AI';
8  
9 use Logic::Relational ();
10 use Logic::Relational::Syntax;
11 use Logic::Relational::Goal::Call;
12  
13 our $CURRENT_SHOTS = {};
14  
15 logic NaiveAITemplate {
16 fact shot_hit( 0, 0 );
17 fact shot_miss( 0, 0 );
18 fact sunk_cell( 0, 0 );
19  
20 rule cell_unshot( $x, $y ) {
21 guard(
22 [ $x, $y ],
23 sub ( $vx, $vy ) {
24 return 0 if $vx < 1 || $vx > 10 || $vy < 1 || $vy > 10;
25 return $Games::GUI::Battleship::AI::Naive::CURRENT_SHOTS->{
26 "$vx,$vy"} ? 0 : 1;
27 }
28 );
29 }
30  
31 rule cell_valid( $x, $y ) {
32 between( 1, 10, $y );
33 between( 1, 10, $x );
34 cell_unshot( $x, $y );
35 }
36  
37 rule adjacent( $x1, $y1, $x2, $y2 ) {
38 is_goal( $x2, [$x1], sub ($v) { $v + 1 } );
39 unify( $y1, $y2 );
40 }
41 rule adjacent( $x1, $y1, $x2, $y2 ) {
42 is_goal( $x2, [$x1], sub ($v) { $v - 1 } );
43 unify( $y1, $y2 );
44 }
45 rule adjacent( $x1, $y1, $x2, $y2 ) {
46 is_goal( $y2, [$y1], sub ($v) { $v + 1 } );
47 unify( $x1, $x2 );
48 }
49 rule adjacent( $x1, $y1, $x2, $y2 ) {
50 is_goal( $y2, [$y1], sub ($v) { $v - 1 } );
51 unify( $x1, $x2 );
52 }
53  
54 # Priority 1: Basic Adjacent Probe (No Line Extension)
55 rule select_target( $x, $y, $mode ) {
56 fresh my ( $hx, $hy );
57 shot_hit( $hx, $hy );
58 adjacent( $hx, $hy, $x, $y );
59 cell_valid( $x, $y );
60 unify( $mode, 'Basic Adjacent Probe' );
61 }
62  
63 # Priority 2: Linear Sequential Scan
64 rule select_target( $x, $y, $mode ) {
65 between( 1, 10, $y );
66 between( 1, 10, $x );
67 cell_unshot( $x, $y );
68 unify( $mode, 'Linear Sequential Scan' );
69 }
70 }
71  
72 sub new ( $class, %args ) {
73 $args{name} = 'NaiveAI';
74 $args{difficulty} = 'easy';
75 return $class->SUPER::new(%args);
76 }
77  
78 sub init_program ($self) {
79 $self->{program} = $self->clone_program($NaiveAITemplate::PROGRAM);
80 return $self->{program};
81 }
82  
83 sub select_target ($self) {
84 local $CURRENT_SHOTS = $self->{shots_history};
85  
86 my $tx = Logic::Relational::variable('x');
87 my $ty = Logic::Relational::variable('y');
88 my $tm = Logic::Relational::variable('mode');
89  
90 my $q = $self->{program}->query(
91 Logic::Relational::Goal::Call->new(
92 'select_target', [ $tx, $ty, $tm ]
93 )
94 );
95  
96 my $sol = $q->next // return;
97 return ( $sol->value($tx), $sol->value($ty), $sol->value($tm) );
98 }
99  
100 1;
101