Created
May 3, 2023 08:56
-
-
Save crispy-computing-machine/11b819f7eb12b55c0ba74983717cd4e8 to your computer and use it in GitHub Desktop.
PHP Random Walk Path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class LatticeRandomWalk { | |
private int $width; | |
private int $height; | |
private int $steps; | |
private array $color; | |
private int $stepLength; | |
public function __construct(int $width, int $height, int $steps, int $stepLength = 1, array $color = [0, 0, 0]) { | |
$this->width = $width; | |
$this->height = $height; | |
$this->steps = $steps; | |
$this->color = $color; | |
$this->stepLength = $stepLength; | |
} | |
private function isValidMove(int $x, int $y, array &$visited): bool { | |
return $x >= 0 && $x < $this->width && $y >= 0 && $y < $this->height && !isset($visited["$x,$y"]); | |
} | |
public function generateImage(string $filename): void { | |
$image = imagecreatetruecolor($this->width, $this->height); | |
$backgroundColor = imagecolorallocate($image, 255, 255, 255); | |
imagefill($image, 0, 0, $backgroundColor); | |
$lineColor = imagecolorallocate($image, $this->color[0], $this->color[1], $this->color[2]); | |
// Set the initial x and y coordinates to random values within the image bounds | |
$x = rand(0, $this->width - 1); | |
$y = rand(0, $this->height - 1); | |
$visited = []; | |
$visited["$x,$y"] = true; | |
for ($i = 0; $i < $this->steps; $i++) { | |
$validMove = false; | |
$directions = range(0, 3); | |
shuffle($directions); | |
foreach ($directions as $direction) { | |
$newX = $x; | |
$newY = $y; | |
$intermediatePoints = []; | |
for ($j = 0; $j < $this->stepLength; $j++) { | |
switch ($direction) { | |
case 0: | |
$newX++; // Move right | |
break; | |
case 1: | |
$newY++; // Move down | |
break; | |
case 2: | |
$newX--; // Move left | |
break; | |
case 3: | |
$newY--; // Move up | |
break; | |
} | |
if ($this->isValidMove($newX, $newY, $visited)) { | |
$intermediatePoints[] = ["$newX,$newY"]; | |
} else { | |
break; | |
} | |
} | |
if (count($intermediatePoints) === $this->stepLength) { | |
$validMove = true; | |
break; | |
} | |
} | |
if (!$validMove) { | |
continue; | |
} | |
imageline($image, $x, $y, $newX, $newY, $lineColor); | |
foreach ($intermediatePoints as $point) { | |
#die(print_r($point)); | |
$visited[implode(',', $point)] = true; | |
} | |
$x = $newX; | |
$y = $newY; | |
} | |
imagepng($image, $filename); | |
imagedestroy($image); | |
} | |
} | |
$randomWalk = new LatticeRandomWalk(500, 500, 100, 10); | |
$randomWalk->generateImage('walk.png'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment