summaryrefslogtreecommitdiff
path: root/lib/GridFiller/Chooser/Random.pm
blob: f949c4d3b4375f1bd48eac19a911fc23d54e1ae0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package GridFiller::Chooser::Random; 
use Moose;
use namespace::autoclean;
use GridFiller::Constants ':all';
use Carp;
 
extends 'GridFiller::Chooser';
 
sub find_place_for {
    my ($self,$word) = @_;
 
    my $dir = int(rand(2)) ? $HORIZONTAL : $VERTICAL;
 
    my $length = $self->length->($word);
 
    my @ret;
 
    if ($dir == $HORIZONTAL) {
        @ret = $self->_find_place_horiz($length);
        @ret = $self->_find_place_vert($lengthunless @ret;
    }
    else {
        @ret = $self->_find_place_vert($length);
        @ret = $self->_find_place_horiz($lengthunless @ret;
    }
 
    return @ret;
}
 
sub _find_place_horiz {
    my ($self,$length) = @_;
 
    my $rows = scalar @{$self->grid};
    my $col;
 
    for my $row (0..$rows-1) {
        $col = $self->_find_in_row($row,$length);
        return (0,$col,$row,$HORIZONTALif defined $col;
    }
    return;
}
 
sub _find_place_vert {
    my ($self,$length) = @_;
 
    my $cols = scalar @{$self->grid->[0]};
    my $row;
 
    for my $col (0..$cols-1) {
        $row = $self->_find_in_col($col,$length);
        return (0,$col,$row,$VERTICALif defined $row;
    }
    return;
}
 
{
my %symbols=(
    $NOTHING => ' ',
    $BLACK => 'X',
    $WHITE => 'O',
);
 
sub _do_find {
    my ($self,$str,$length) = @_;
 
    my ($skip) = ($str =~ m{^ (.*?) (?: X{$length} | O{$length} ) }x);
 
    $self->log->debug(defined $skip ? " skip <$skip>" : " nope");
 
    return length($skipif defined $skip;
    return;
}
 
sub _find_in_row {
    my ($self,$row,$length) = @_;
 
    my $str = join '',map { $symbols{$_} } @{$self->grid->[$row]};
 
    $self->log->debug("row $row = $str");
 
    return $self->_do_find($str,$length);
}
 
sub _find_in_col {
    my ($self,$col,$length) = @_;
 
    my $str = join '',map { $symbols{$_->[$col]} } @{$self->grid};
 
    $self->log->debug("col $col = $str");
 
    return $self->_do_find($str,$length);
}
}
 
1;