| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- <?php
- namespace App\Module\GameItems\Logics;
- use App\Module\GameItems\Models\Item;
- use App\Module\GameItems\Models\ItemGroup;
- /**
- * 物品组逻辑类
- *
- * 提供物品组相关的逻辑处理,包括根据权重随机获取物品组中的物品等功能。
- * 物品组是一组相关物品的集合,通常用于宝箱内容配置、奖励发放等场景,
- * 可以根据预设的权重随机选择其中的物品。
- */
- class Group
- {
- /**
- * 根据权重随机获取物品组中的一个物品
- *
- * @return Item|null
- */
- public function getRandomItem(ItemGroup $group): ?Item
- {
- $groupItems = $group->groupItems()->with('item')->get();
- if ($groupItems->isEmpty()) {
- return null;
- }
- // 计算总权重
- $totalWeight = $groupItems->sum('weight');
- if ($totalWeight <= 0) {
- return $groupItems->first()->item;
- }
- // 随机选择
- $randomValue = mt_rand(1, (int)($totalWeight * 1000)) / 1000;
- $currentWeight = 0;
- foreach ($groupItems as $groupItem) {
- $currentWeight += $groupItem->weight;
- if ($randomValue <= $currentWeight) {
- return $groupItem->item;
- }
- }
- // 如果由于浮点数精度问题没有选中,则返回最后一个
- return $groupItems->last()->item;
- }
- }
|