Group.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Module\GameItems\Logics;
  3. use App\Module\GameItems\Models\Item;
  4. use App\Module\GameItems\Models\ItemGroup;
  5. /**
  6. * 物品组逻辑类
  7. *
  8. * 提供物品组相关的逻辑处理,包括根据权重随机获取物品组中的物品等功能。
  9. * 物品组是一组相关物品的集合,通常用于宝箱内容配置、奖励发放等场景,
  10. * 可以根据预设的权重随机选择其中的物品。
  11. */
  12. class Group
  13. {
  14. /**
  15. * 根据权重随机获取物品组中的一个物品
  16. *
  17. * @return Item|null
  18. */
  19. public function getRandomItem(ItemGroup $group): ?Item
  20. {
  21. $groupItems = $group->groupItems()->with('item')->get();
  22. if ($groupItems->isEmpty()) {
  23. return null;
  24. }
  25. // 计算总权重
  26. $totalWeight = $groupItems->sum('weight');
  27. if ($totalWeight <= 0) {
  28. return $groupItems->first()->item;
  29. }
  30. // 随机选择
  31. $randomValue = mt_rand(1, (int)($totalWeight * 1000)) / 1000;
  32. $currentWeight = 0;
  33. foreach ($groupItems as $groupItem) {
  34. $currentWeight += $groupItem->weight;
  35. if ($randomValue <= $currentWeight) {
  36. return $groupItem->item;
  37. }
  38. }
  39. // 如果由于浮点数精度问题没有选中,则返回最后一个
  40. return $groupItems->last()->item;
  41. }
  42. }