Source

Sokoban Solver / modules / Shlomif-Sokoban-Solver / lib / Shlomif / Sokoban / Solver / Board.pm

Full commit
  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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package Shlomif::Sokoban::Solver::Board;

use strict;
use warnings;

=head1 NAME

Shlomif::Sokoban::Solver::Board - a board for the sokosolver.

=head1 SYNOPSIS

For internal use by the Sokoban solver. See the test files.

=cut

use List::Util qw(max);

use Object::Tiny qw/
    height
    width
    _collect
    _data
    _dests
    _init_state
    _queue
/;

my $dest_place_bits = 0x1;
my $wall_bits = 0x2;

my $box_bits = 0x1;
my $reachable_bits = 0x2;

=head1 METHODS

=head2 load($board)

Loads a board in standard Sokoban notation.

=cut

sub _calc_offset
{
    my ($self, $x, $y) = @_;

    return $y*$self->width()+$x;
}

sub load
{
    my ($pkg, $contents) = @_;

    # Remove trailing whitespace.
    $contents =~ s{(\s*\n)+\z}{}ms; 

    # Remove trailing whitespace from lines.
    $contents =~ s{\s+$}{}gms;

    my @lines = (map { [ split(//, $_) ] } split(/\n/, $contents));

    my $data = "";

    my $init_state = "";
    my $init_pos;

    my $self = 
        $pkg->new(
            height => scalar(@lines),
            width => max(map { scalar(@$_) } @lines),
            _data => \$data,
            _dests => [],
            _init_state => \$init_state,
            _collect => +{},
            _queue => [],
        );



    foreach my $y (0 .. $#lines)
    {
        my $l = $lines[$y];

        foreach my $x (0 .. $#$l)
        {
            my $offset = $self->_calc_offset($x, $y);

            # Initialise the init_state block to the default.
            vec($init_state, $offset, 2) = 0;
            if ($l->[$x] eq "#")
            {
                vec(${$self->_data()}, $offset, 2) = $wall_bits;
            }
            elsif ($l->[$x] eq ".")
            {
                vec(${$self->_data()}, $offset, 2) = $dest_place_bits;
                push @{$self->_dests()}, [$x, $y];
            }
            else
            {
                vec(${$self->_data()}, $offset, 2) = 0;
                if ($l->[$x] eq '$')
                {
                    vec($init_state, $offset, 2) = $box_bits;
                }
                elsif ($l->[$x] eq '@')
                {
                    $init_pos = [$x, $y];
                }
            }
        }
    }

    if (!defined($init_pos))
    {
        die "The initial position of the player was not defined.";
    }

    $self->_mark_reachable(\$init_state, @$init_pos);

    return $self;
}

=head2 $board->is_wall($x,$y)

Returns if the block at the position $x,$y is a wall.

=cut

sub is_wall
{
    my ($self, $x, $y) = @_;

    return (vec(${$self->_data()}, $self->_calc_offset($x,$y), 2) == $wall_bits);
}

=head2 $board->is_dest($x,$y)

Returns if the block at the position $x,$y is a destination block.

=cut

sub is_dest
{
    my ($self, $x, $y) = @_;

    return (vec(${$self->_data()}, $self->_calc_offset($x,$y), 2)
            == $dest_place_bits
        );
}

=head2 $board->is_box($s_ref, $x, $y)

Is ($x,$y) in the state referenced by $s_ref a box?

=cut

sub is_box
{
    my ($self, $s_ref, $x, $y) = @_;
    return (vec($$s_ref, $self->_calc_offset($x,$y), 2) == $box_bits);
}

=head2 $board->is_reachable($s_ref, $x, $y)

Is ($x,$y) in the state referenced by $s_ref reachable by the player?

=cut

sub is_reachable
{
    my ($self, $s_ref, $x, $y) = @_;
    return (vec($$s_ref, $self->_calc_offset($x,$y), 2) == $reachable_bits);
}

sub _mark_reachable
{
    my ($self, $s_ref, $start_x, $start_y) = @_;

    # Breadth-first search to find all the reachable positions in the board.
    my @to_check =([$start_x, $start_y]);

    while (my $pos = shift(@to_check))
    {
        # Mark as reachable.
        vec($$s_ref, $self->_calc_offset(@$pos), 2) = $reachable_bits;

        foreach my $offset ([-1,0],[1,0],[0,-1],[0,1])
        {
            my @new_pos = ($pos->[0]+$offset->[0], $pos->[1]+$offset->[1]);
            if (   ($new_pos[0] >= 0)
                && ($new_pos[1] >= 0)
                && ($new_pos[0] < $self->width())
                && ($new_pos[1] < $self->height())
                && (! $self->is_wall(@new_pos))
                && (! $self->is_box($s_ref, @new_pos))
                && (! $self->is_reachable($s_ref, @new_pos))
               )
            {
                push @to_check, \@new_pos;
            }
        }
    }

    return;
}

sub _rotate
{
    my ($self, $s_ref) = @_;

    my $ret = "";

    my $width = $self->width()-1;
    my $height = $self->height()-1;

    for my $x (0 .. $width)
    {
        for my $y (0 .. $height)
        {
            vec($ret, $self->_calc_offset($y, $width-$x), 2) =
                vec($$s_ref, $self->_calc_offset($x,$y), 2);
        }
    }

    return \$ret;
}

# Get the minimal rotation permutation
sub _get_min_rot_perm
{
    my ($self, $s_ref) = @_;

    # Find the minimal board by its rotation permutations.
    my $min_rot_times = 0;
    my $min_rot_board = $s_ref;
    foreach my $r (1 .. 3)
    {
        my $new = $self->_rotate($s_ref);
        if ($$new lt $$min_rot_board)
        {
            $min_rot_times = $r;
            $min_rot_board = $new;
        }
        $s_ref = $new;
    }

    return ($min_rot_times, $min_rot_board);
}

sub _derive
{
    my ($self, $state_ref, $box_xy, $push_to_xy) = @_;

    my $new_state = "";

    for my $y (0 .. $self->height()-1)
    {
        for my $x (0 .. $self->width()-1)
        {
            my $offset = $self->_calc_offset($x, $y);
            if ($self->is_box($state_ref, $x, $y))
            {
                vec($new_state, $offset, 2) = $box_bits;
            }
            else
            {
                vec($new_state, $offset, 2) = 0;
            }
        }
    }

    # Move the new box.
    vec($new_state, $self->_calc_offset(@$box_xy), 2) = 0;
    vec($new_state, $self->_calc_offset(@$push_to_xy), 2) = $box_bits;

    # Mark the reachable bits.
    $self->_mark_reachable(\$new_state, @$box_xy);

    return \$new_state;
}

sub _output
{
    my ($self, $s_ref) = @_;

    for my $y (0 .. ($self->height()-1))
    {
        for my $x (0 .. ($self->width()-1))
        {
            print   $self->is_wall($x, $y) ? "#"
                  : $self->is_box($s_ref, $x, $y)  ? '$'
                  : $self->is_dest($x, $y) ? "."
                  : " "
                  ;
        }
        print "\n";
    }
    print "\n";
}

sub _is_final
{
    my ($self, $s_ref) = @_;

    foreach my $d (@{$self->_dests()})
    {
        if (! $self->is_box($s_ref, @$d))
        {
            return 0;
        }
    }
    return 1;
}

sub _try_to_move_box
{
    my ($self, $state_ref, $x, $y) = @_;

    for my $offset ([-1,0],[1,0],[0,-1],[0,1])
    {
        my @push_to = ($x+$offset->[0], $y+$offset->[1]);
        my @push_from = ($x-$offset->[0], $y-$offset->[1]);
        
        if (   (! $self->is_wall(@push_to))
            && (! $self->is_box($state_ref, @push_to))
            && $self->is_reachable($state_ref, @push_from)
           )
        {
            # We can push.
            my $new_state_ref =
                $self->_derive($state_ref, [$x, $y], \@push_to)
                ;

            # Print it - this is temporary for debugging.
            # (Now commented out.)
            # $self->_output($new_state_ref);

            # Else - register it and proceed.
            
            my ($rot_idx, $rot_state) =
                $self->_get_min_rot_perm($new_state_ref);
            if (exists($self->_collect()->{$$rot_state}))
            {
                # Do nothing
            }
            else
            {
                $self->_collect()->{$$rot_state} =
                {
                    r => (($rot_idx+$self->_collect()->{$$state_ref}->{r})%4),
                    p => $state_ref
                };
                if ($self->_is_final($rot_state))
                {
                    return $rot_state;
                }
                push @{$self->_queue()}, $rot_state;
            }
            
        }
    }

    return;
}

sub _trace_solution
{
    my ($self, $final_state) = @_;

    my @solution;

    {
        my $state = $final_state;

        while (defined($state))
        {
            push @solution, $state;
            $state = $self->_collect->{$$state}->{p};
        }
    }

    foreach my $state (reverse(@solution))
    {
        my $r = $self->_collect->{$$state}->{r};

        # Normalize the state from its rotated position.
        my $rot_state = $state;
        while ($r%4 != 0)
        {
            $rot_state = $self->_rotate($rot_state);
            $r++;
        }

        $self->_output($rot_state);
    }
}

=head2 $board->solve()

Actually solve the board.

=cut

sub solve
{
    my $self = shift;

    my $s_ref = $self->_init_state();

    my ($rot_idx, $rot_state) = $self->_get_min_rot_perm($s_ref);

    $self->_collect()->{$$rot_state} = { r => $rot_idx, p => undef() };

    push @{$self->_queue()}, $rot_state;

    my $w = $self->width()-1;
    my $h = $self->height()-1;

    while (my $state_ref = pop(@{$self->_queue()}))
    {
        for my $y (0 .. $h)
        {
            for my $x (0 .. $w)
            {
                if ($self->is_box($state_ref, $x, $y))
                {
                    my $final = $self->_try_to_move_box($state_ref, $x, $y);

                    if (defined($final))
                    {
                        $self->_trace_solution($final);

                        return $final;
                    }
                }
            }
        }
    }
}

=head2 width()

Returns the width of the board.

=head2 height()

Returns the height of the board.

=cut

1;