Hello, I need help with my plugin. So how do you guys make it so when you mine a block you have a 20% Chance of getting a dye. I know you have to use mt_rand but just don't know how, please can you send me some code?
PHP: public function onBreak(BlockBreakEvent $event){ $player = $event->getPlayer(); $block = $event->getBlock(); if($event->isCancelled()){ return; } if($block->getId() == /*Your Block*/){ $rand = mt_rand(0, 20); switch($rand){ case 20: $player->getInventory()->addItem(/*Dye*/); $player->sendMessage("You win a dye"); break; } }}
*Ignoring the fact that mt_rand generates psuedo-random numbers* 20% would be mt_rand(1, 5) (simplification of 20/100) mt_rand(0, 20) means there's 1 in a 21 possibility of getting any number between 0 and 20. You might have meant mt_rand(1, 20) but that'd still not be a 20% chance. That would mean there's a possibility of getting 1 at least once on an average in 20 chances (which is 5%).
Let's generate a number in the closed range [1, 100]: PHP: $random = mt_rand(1, 100); We get a number in this range: Now, if $random is less than or equal to 20, i.e. PHP: if($random <= 20) The overlapping area is exactly 20% of the range. Let's look at the extreme cases. If we want 0% probability: PHP: if($random <= 0) There is no overlap at all (because the red area is defined as a half-open range 0 < x <= 100). If we want 1%: And if we want 100%: Complete overlap. Conclusion: To do something by $x% probability, the code should be: PHP: $random = mt_rand(1, 100);if($random <= $x){ // random execution here} Note that $x must be an integer. If you want 0.1% probability, you have to change $random to mt_rand(1, 1000) and multiply $x by 10. So, a more generic conclusion: To do something by $m/$n probability, where $m and $n are both integers, the code should be: PHP: if(mt_rand(1, $n) <= $m){ // random execution here}