summaryrefslogtreecommitdiff
path: root/lib/GridFiller.pm
blob: 44f0a504a898280c4007754ce495c9f058c5adb4 (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
package GridFiller; 
use Moose;
use namespace::autoclean;
use GridFiller::Types qw(GridT WordListT);
use GridFiller::Status;
use GridFiller::Result;
use Carp;
 
with 'MooseX::Log::Log4perl';
 
has words => (
    isa => WordListT,
    required => 1,
    is => 'ro',
);
 
has grid => (
    isa => GridT,
    required => 1,
    is => 'ro',
);
 
sub fill {
    my ($self) = @_;
 
    my $status = GridFiller::Status->new({grid => $self->grid, words => $self->words});
    my $result = GridFiller::Result->new({source_grid => $self->grid});
 
    while ($status->unfilled() && $status->has_next_word()) {
        my $word = $status->get_next_word();
 
        $self->log->debug("Placing $word");
 
        my ($x,$y,$dir) = $status->find_place_for($word);
 
        if (! defined $x) {
            $self->log->debug("No place for $word");
            $result->mark_leftover($word);
            next;
        };
 
        $result->place_word_at($word,$x,$y,$dir);
        $status->place_word_at($word,$x,$y,$dir);
 
        if ($self->log->is_debug) {
            $self->log->debug($status->to_string);
            $self->log->debug($result->to_string);
        }
    }
 
    return $result;
}
 
1;