Skip to content

Instantly share code, notes, and snippets.

@NhanAZ
Forked from NgLam2911/RandomBlock.php
Last active June 11, 2024 03:08
Show Gist options
  • Save NhanAZ/2f340cd0a782790a55f6c6f14681ad19 to your computer and use it in GitHub Desktop.
Save NhanAZ/2f340cd0a782790a55f6c6f14681ad19 to your computer and use it in GitHub Desktop.
RandomBlock template
<?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