Created
May 4, 2023 07:20
-
-
Save crispy-computing-machine/da527667516113528fe67e9b99af6ae2 to your computer and use it in GitHub Desktop.
PerlinNoise RPG Map Generator
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 | |
require 'vendor/autoload.php'; | |
/** | |
* composer require martinlindhe/php-noisegenerator | |
*/ | |
class RPGMapGenerator | |
{ | |
private int $width; | |
private int $height; | |
private float $scale; | |
private array $biomes = [ | |
'Water' => [0, 0, 255], | |
'Surface' => [0, 128, 255], | |
'Sand' => [255, 166, 87], | |
'Road' => [128, 128, 128], | |
'Stone' => [105, 105, 105], | |
'Dirt' => [104, 109, 29], | |
'Forest' => [34, 139, 34], | |
]; | |
public function __construct(int $width, int $height, float $scale = 1.0) | |
{ | |
$this->width = $width; | |
$this->height = $height; | |
$this->scale = $scale; | |
} | |
public function generateMap(string $outputFile): void | |
{ | |
#$noise = new PerlinNoise(); | |
$noise = new \NoiseGenerator\PerlinNoise(3000); | |
$octaves = array(64, 64, 2, 2, 2, 2, 2); | |
$image = imagecreatetruecolor($this->width, $this->height); | |
for ($y = 0; $y < $this->height; $y++) { | |
for ($x = 0; $x < $this->width; $x++) { | |
$value = $noise->noise($x * $this->scale, $y * $this->scale, 0, $octaves); | |
$biomeColor = $this->getBiomeColor($value); | |
$color = imagecolorallocate($image, $biomeColor[0], $biomeColor[1], $biomeColor[2]); | |
imagesetpixel($image, $x, $y, $color); | |
} | |
} | |
imagepng($image, $outputFile); | |
imagedestroy($image); | |
} | |
private function getBiomeColor(float $value): array | |
{ | |
if ($value < -0.3) { | |
return $this->biomes['Water']; | |
} elseif ($value < -0.2) { | |
return $this->biomes['Surface']; | |
} elseif ($value < -0.1) { | |
return $this->biomes['Sand']; | |
} elseif ($value < 0.1) { | |
return $this->biomes['Road']; | |
} elseif ($value < 0.2) { | |
return $this->biomes['Stone']; | |
} elseif ($value < 0.3) { | |
return $this->biomes['Dirt']; | |
} else { | |
return $this->biomes['Forest']; | |
} | |
} | |
} | |
// Example usage: | |
$mapGenerator = new RPGMapGenerator(512, 512, 1.0); | |
$mapGenerator->generateMap('output_map.png'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment