1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Stratadox\PuzzleSolver\Puzzle\SlidingCrates; |
4
|
|
|
|
5
|
|
|
use function abs; |
6
|
|
|
use function current; |
7
|
|
|
use function end; |
8
|
|
|
|
9
|
|
|
final class Rectangle |
10
|
|
|
{ |
11
|
|
|
/** @var int */ |
12
|
|
|
private $x; |
13
|
|
|
/** @var int */ |
14
|
|
|
private $y; |
15
|
|
|
/** @var int */ |
16
|
|
|
private $w; |
17
|
|
|
/** @var int */ |
18
|
|
|
private $h; |
19
|
|
|
|
20
|
|
|
private function __construct(int $x, int $y, int $w, int $h) |
21
|
|
|
{ |
22
|
|
|
$this->x = $x; |
23
|
|
|
$this->y = $y; |
24
|
|
|
$this->w = $w; |
25
|
|
|
$this->h = $h; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public static function fromCoordinates(array ...$coordinates): self |
29
|
|
|
{ |
30
|
|
|
[$x1, $y1] = current($coordinates); |
31
|
|
|
[$x2, $y2] = end($coordinates); |
32
|
|
|
$h = abs($y2 - $y1) + 1; |
33
|
|
|
$w = abs($x2 - $x1) + 1; |
34
|
|
|
return new self($x1, $y1, $w, $h); |
|
|
|
|
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function isHorizontal(): bool |
38
|
|
|
{ |
39
|
|
|
return $this->w >= $this->h; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function isVertical(): bool |
43
|
|
|
{ |
44
|
|
|
return $this->h >= $this->w; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function after(Push $push): self |
48
|
|
|
{ |
49
|
|
|
$new = clone $this; |
50
|
|
|
$new->x = $push->newX($this->x); |
51
|
|
|
$new->y = $push->newY($this->y); |
52
|
|
|
return $new; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function collidesWith(Rectangle $other): bool |
56
|
|
|
{ |
57
|
|
|
return $this->x < $other->x + $other->w |
58
|
|
|
&& $this->x + $this->w > $other->x |
59
|
|
|
&& $this->y < $other->y + $other->h |
60
|
|
|
&& $this->y + $this->h > $other->y; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function isOutOfBounds(int $width, int $height): bool |
64
|
|
|
{ |
65
|
|
|
return $this->x < 0 |
66
|
|
|
|| $this->x + $this->w > $width |
67
|
|
|
|| $this->y < 0 |
68
|
|
|
|| $this->y + $this->h > $height; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
public function coordinates(): array |
72
|
|
|
{ |
73
|
|
|
$coordinates = []; |
74
|
|
|
for ($x = 0; $x < $this->w; ++$x) { |
75
|
|
|
for ($y = 0; $y < $this->h; ++$y) { |
76
|
|
|
$coordinates[] = [$this->x + $x, $this->y + $y]; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
return $coordinates; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
public function __toString(): string |
83
|
|
|
{ |
84
|
|
|
return "($this->x, $this->y, $this->w, $this->h)"; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|