From 095fd1560764f45c244586da256a5e37b0505720 Mon Sep 17 00:00:00 2001 From: Dennis Eichhorn Date: Tue, 20 Aug 2019 16:28:38 +0200 Subject: [PATCH] Update Grid.php --- Algorithm/PathFinding/Grid.php | 74 ++++++++++++++++++++++++++++++++-- 1 file changed, 71 insertions(+), 3 deletions(-) diff --git a/Algorithm/PathFinding/Grid.php b/Algorithm/PathFinding/Grid.php index 7b9110e9e..09e69a8d1 100644 --- a/Algorithm/PathFinding/Grid.php +++ b/Algorithm/PathFinding/Grid.php @@ -24,16 +24,84 @@ namespace phpOMS\Algorithm\PathFinding; */ class Grid { - private array $nodes = []; + private array $nodes = [[]]; private ?Node $nullNode = null; + public function __construct(Node $nullNode) + { + $this->nullNode = $nullNode; + } + public function getNullNode() : Node { return $this->nullNode; } - public function setNullNode(Node $nullNode) : void + public function getNode(int $x, int $y) : Node { - $this->nullNode = $nullNode; + if (!isset($this->nodes[$x]) || $this->nodes[$x][$y]) { + return $this->nullNode; + } + + return $this->nodes[$x][$y]; + } + + public function getNeighbors(Node $node, int $movement) : array + { + $x = $node->getX(); + $y = $node->getY(); + + $neighbours = []; + $s0 = false; + $s1 = false; + $s2 = false; + $s3 = false; + $d0 = false; + $d1 = false; + $d2 = false; + $d3 = false; + + $nodes = $this->nodes; + + if ($this->getNode($x, $y - 1)->isWalkable()) { + $neighbours[$x][$y - 1]; + $s0 = true; + } + + if ($this->getNode($x + 1, $y)->isWalkable()) { + $neighbours[$x + 1][$y]; + $s1 = true; + } + + if ($this->getNode($x, $y + 1)->isWalkable()) { + $neighbours[$x][$y + 1]; + $s2 = true; + } + + if ($this->getNode($x - 1, $y)->isWalkable()) { + $neighbours[$x - 1][$y]; + $s3 = true; + } + + if ($movement === MovementType::STRAIGHT) { + return $neighbours; + } + + if ($movement === MovementType::DIAGONAL_NO_OBSTACLE) { + $d0 = $s3 && $s0; + $d1 = $s0 && $s1; + $d2 = $s1 && $s2; + $d3 = $s2 && $s3; + } elseif ($movement === MovementType::DIAGONAL_ONE_OBSTACLE) { + $d0 = $s3 || $s0; + $d1 = $s0 || $s1; + $d2 = $s1 || $s2; + $d3 = $s2 || $s3; + } else if ($movement === MovementType::DIAGONAL) { + $d0 = true; + $d1 = true; + $d2 = true; + $d3 = true; + } } }