-
-
Save NhanAZ/2f340cd0a782790a55f6c6f14681ad19 to your computer and use it in GitHub Desktop.
RandomBlock template
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 | |
declare(strict_types=1); | |
namespace ShutTheFuckUp; | |
use InvalidArgumentException; | |
use pocketmine\block\Block; | |
use pocketmine\block\VanillaBlocks; | |
class RandomBlock { | |
/** @var array */ | |
protected array $cumulativeArray = []; | |
/** @var Block[] */ | |
protected array $block_list; | |
/** @var int[] */ | |
protected array $percent_list; | |
public function __construct(){ | |
// Define the blocks and their respective percentages | |
$this->block_list = [ | |
'DIRT' => VanillaBlocks::DIRT(), | |
'STONE' => VanillaBlocks::STONE(), | |
'COAL_ORE' => VanillaBlocks::COAL_ORE() | |
]; | |
$this->percent_list = [ | |
'DIRT' => 20, // 20% DIRT | |
'STONE' => 70, // 70% STONE | |
'COAL_ORE' => 10 // 10% COAL ORE | |
]; | |
// Validate the sum of percentages | |
if (array_sum($this->percent_list) !== 100){ | |
throw new InvalidArgumentException("Total of percent must be = 100"); | |
} | |
$this->generateCumulativeArray(); | |
} | |
private function generateCumulativeArray() : void{ | |
$cumulative = 0; | |
foreach($this->block_list as $name => $block){ | |
$cumulative += $this->percent_list[$name]; | |
$this->cumulativeArray[] = [$cumulative, $block]; | |
} | |
} | |
public function get() : Block{ | |
$rand = mt_rand(1, 100); | |
foreach ($this->cumulativeArray as [$percent, $block]) { | |
if ($rand <= $percent) { | |
return $block; | |
} | |
} | |
// This point should never be reached because the percentages sum to 100 | |
throw new RuntimeException("Failed to retrieve a block"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment