cloned / luckybox
从一些项目中选择具有指定概率的一个的库。
v0.9.0
2013-10-20 05:52 UTC
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-24 01:27:56 UTC
README
LuckyBox 是一个用于PHP的库,可以从一些项目中选择具有指定概率的一个。
要求
- PHP 5.3.0 及以上
安装
在你的应用程序或依赖库的根目录下,创建一个 composer.json 文件。在 require 或 require-dev 部分,添加以下依赖项
"cloned/luckybox": "$VERSION"
其中 $VERSION 是 Packagist 上可用的版本之一 Packagist。
用法
示例
以下是一个简单示例,从3个项目中选择一个,这些项目是硬币、蘑菇和星星。每个项目的概率如下。
- 硬币:60%
- 蘑菇:35%
- 星星:5%
<?php use LuckyBox\LuckyBox; use LuckyBox\Card\IdCard; // Items $items = array( 1 => array('name' => 'Coin', 'rate' => 60), // 60% 2 => array('name' => 'Mushroom', 'rate' => 35), // 35% 3 => array('name' => 'Star', 'rate' => 5), // 5% ); // Setup $luckyBox = new LuckyBox(); foreach ($items as $id => $item) { $card = new IdCard(); $card->setId($id) ->setRate($item['rate']); $luckyBox->add($card); } // Draw $card = $luckyBox->draw(); $item = $items[$card->getId()]; echo "You got {$item['name']}" . PHP_EOL;
消耗卡片
LuckyBox 中的卡片默认不可消耗。这意味着卡片可以无限期地抽取。如果你想消耗 LuckyBox 中的卡片,将可消耗设置为 true。
$luckyBox = new LuckyBox(); // Add some cards. $luckyBox->setConsumable(true); while (!$luckyBox->isEmpty()) { $card = $luckyBox->draw(); // Do something. }
提高精确度
你可能需要一个比百分比(0到100)更高的精确度。你可以将比率设置为超过100。
$card1 = new IdCard(); $card2 = new IdCard(); $card1->setRate(1023); // 10.23% $card2->setRate(8977); // 89.77%
移除一张卡片
- 移除一张卡片
$luckyBox->remove($card);
- 移除所有卡片
$luckyBox->clear();
许可证
LuckyBox 在 MIT 许可证下发布 - 有关详细信息,请参阅 LICENSE
文件