浏览代码

refactor(game): 优化物品合成和奖励发放功能

- 修改 CraftHandler 中的结果处理逻辑
- 更新 RewardLogic 中的奖励发放方法,支持倍率参数
-调整 WeightSelectionReward 以适应倍率发放
- 优化 CraftService 中的异常处理
notfff 7 月之前
父节点
当前提交
f697270993

+ 4 - 7
app/Module/AppGame/Handler/Item/CraftHandler.php

@@ -56,20 +56,17 @@ class CraftHandler extends BaseHandler
             $validation->validated();
 
             // 调用合成服务(服务内部会处理事务)
-            $result = CraftService::craftItem($userId, $recipeId, [
-                'quantity' => $quantity,
+            $result = CraftService::craftItem($userId, $recipeId,$quantity, [
+
                 'source_type' => 'app_craft',
                 'device_info' => request()->userAgent(),
                 'ip_address' => request()->ip(),
             ]);
 
-            if (!$result) {
+            if ($result->error) {
                 throw new LogicException("合成失败,请检查材料是否充足或配方是否解锁");
             }
 
-            // 设置响应状态
-            $this->response->setCode(RESPONSE_CODE::OK);
-            $this->response->setMsg('合成成功');
 
             Log::info('用户物品合成成功', [
                 'user_id' => $userId,
@@ -93,4 +90,4 @@ class CraftHandler extends BaseHandler
 
         return $response;
     }
-}
+}

+ 9 - 4
app/Module/Game/Logics/RewardLogic.php

@@ -16,6 +16,7 @@ use App\Module\Game\Logics\RewardProcessors\RewardProcessorDispatcher;
 use Exception;
 use Illuminate\Support\Facades\Log;
 use UCore\Db\Helper;
+use UCore\Exception\LogicException;
 
 /**
  * 奖励处理逻辑类
@@ -56,7 +57,7 @@ class RewardLogic
      * @param int $sourceId 来源ID
      * @return RewardResultDto 奖励结果
      */
-    public function grantReward(int $userId, $groupIdOrCode, string $sourceType, int $sourceId): RewardResultDto
+    public function grantReward(int $userId, $groupIdOrCode, string $sourceType, int $sourceId,int $multiplier = 1): RewardResultDto
     {
         try {
             // 获取奖励组
@@ -65,8 +66,9 @@ class RewardLogic
                 return RewardResultDto::fail("奖励组不存在: {$groupIdOrCode}");
             }
 
+
             // 确定要发放的奖励项
-            $rewardItems = $this->determineRewardItems($groupDto, $userId);
+            $rewardItems = $this->determineRewardItems($groupDto, $userId,$multiplier);
             if (empty($rewardItems)) {
                 return RewardResultDto::fail("奖励组中没有可发放的奖励项");
             }
@@ -115,17 +117,20 @@ class RewardLogic
      * @param int|null $userId 用户ID(用于保底机制)
      * @return RewardItemDto[] 要发放的奖励项
      */
-    private function determineRewardItems(RewardGroupDto $groupDto, ?int $userId = null): array
+    private function determineRewardItems(RewardGroupDto $groupDto, ?int $userId = null,int $multiplier = 1): array
     {
         // 检查奖励模式
         $rewardMode = $groupDto->rewardMode ?? REWARD_MODE::WEIGHT_SELECTION->value;
 
         if ($rewardMode == REWARD_MODE::INDEPENDENT_PROBABILITY->value) {
+            if($multiplier > 1){
+                throw  new LogicException('倍率,只支持权重模式');
+            }
             // 独立概率模式
             return IndependentProbabilityReward::process($groupDto, $userId);
         } else {
             // 权重选择模式(默认)
-            return WeightSelectionReward::process($groupDto, $userId);
+            return WeightSelectionReward::process($groupDto, $userId,$multiplier);
         }
     }
 

+ 8 - 2
app/Module/Game/Logics/WeightSelectionReward.php

@@ -8,6 +8,7 @@ use App\Module\Game\Logics\Reward\Item;
 use App\Module\Game\Services\PityService;
 use App\Module\Game\Models\GameRewardItem;
 use Illuminate\Support\Facades\Log;
+use UCore\Exception\LogicException;
 
 /**
  * 权重选择模式奖励处理
@@ -22,10 +23,12 @@ class WeightSelectionReward
      * @param int|null $userId 用户ID(用于保底机制)
      * @return RewardItemDto[] 要发放的奖励项
      */
-    public static function process(RewardGroupDto $groupDto, ?int $userId = null): array
+    public static function process(RewardGroupDto $groupDto, ?int $userId = null,$multiplier = 1): array
     {
         $items = $groupDto->items;
-
+        if($multiplier > 1){
+            $userId = null;
+        }
         // 应用保底机制调整(如果有用户ID)
         if ($userId !== null) {
             $items = self::applyPityAdjustments($userId, $items);
@@ -35,6 +38,9 @@ class WeightSelectionReward
         if (!$groupDto->isRandom) {
             return array_map([Item::class, 'processQuantity' ], $items);
         }
+        if($multiplier > 1){
+            throw new LogicException('倍率下,错误的进入了随机发放!');
+        }
 
         // 随机发放:按权重选择指定数量的奖励项
         return self::processRandomSelection($groupDto, $items);

+ 2 - 2
app/Module/Game/Services/RewardService.php

@@ -34,10 +34,10 @@ class RewardService
      * @param int $sourceId 来源ID
      * @return RewardResultDto 奖励结果
      */
-    public static function grantReward(int $userId, $groupIdOrCode, string $sourceType, int $sourceId): RewardResultDto
+    public static function grantReward(int $userId, $groupIdOrCode, string $sourceType, int $sourceId ,int $multiplier = 1): RewardResultDto
     {
         $logic = new RewardLogic();
-        return $logic->grantReward($userId, $groupIdOrCode, $sourceType, $sourceId);
+        return $logic->grantReward($userId, $groupIdOrCode, $sourceType, $sourceId,$multiplier);
     }
 
     /**

+ 20 - 15
app/Module/GameItems/Services/CraftService.php

@@ -11,6 +11,9 @@ use Exception;
 use Illuminate\Database\Eloquent\Collection;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
+use UCore\Dto\Res;
+use UCore\Exception\LogicException;
+use UCore\Exception\ValidateException;
 
 /**
  * 物品合成服务类
@@ -28,9 +31,9 @@ class CraftService
      * @param int $userId 用户ID
      * @param int $recipeId 配方ID
      * @param array $options 选项
-     * @return array|bool 合成结果或失败标志
+     * @return Res
      */
-    public static function craftItem(int $userId, int $recipeId, array $options = [])
+    public static function craftItem(int $userId, int $recipeId,int $quantity, array $options = []):Res
     {
         try {
             // 获取配方信息
@@ -38,27 +41,26 @@ class CraftService
 
             // 检查配方是否激活
             if (!$recipe->is_active) {
-                throw new Exception("配方未激活");
+                throw new ValidateException("配方未激活");
             }
 
             // 检查用户是否可以合成该配方
             $canCraft = $recipe->canCraftByUser($userId);
-            if (!$canCraft['can_craft']) {
+            if (!$canCraft['ValidateException']) {
                 throw new Exception($canCraft['reason']);
             }
 
             // 检查消耗组是否存在
             if (!$recipe->consume_group_id || !$recipe->consumeGroup) {
-                throw new Exception("配方消耗组不存在");
+                throw new ValidateException("配方消耗组不存在");
             }
 
             // 检查奖励组是否存在
             if (!$recipe->reward_group_id || !$recipe->rewardGroup) {
-                throw new Exception("配方奖励组不存在");
+                throw new ValidateException("配方奖励组不存在");
             }
 
             // 获取合成数量
-            $quantity = $options['quantity'] ?? 1;
 
             // 开启事务
             DB::beginTransaction();
@@ -74,7 +76,7 @@ class CraftService
             );
 
             if (!$consumeResult['success']) {
-                throw new Exception("消耗失败: " . $consumeResult['message']);
+                throw new LogicException("消耗失败: " . $consumeResult['message']);
             }
 
             // 判断合成是否成功(基于配方成功率)
@@ -87,7 +89,8 @@ class CraftService
                     $userId,
                     $recipe->reward_group_id,
                     'craft',
-                    $recipeId
+                    $recipeId,
+                    $quantity
                 );
 
                 if ($rewardResult->success) {
@@ -124,11 +127,12 @@ class CraftService
             DB::commit();
 
             // 返回结果
-            return [
-                'success' => $isSuccess,
-                'consumed' => $consumeResult['consumed'] ?? [],
-                'rewards' => $isSuccess ? $rewardItems : []
-            ];
+            return Res::success();
+//            return [
+//                'success' => $isSuccess,
+//                'consumed' => $consumeResult['consumed'] ?? [],
+//                'rewards' => $isSuccess ? $rewardItems : []
+//            ];
 
         } catch (Exception $e) {
             // 回滚事务
@@ -136,6 +140,7 @@ class CraftService
                 DB::rollBack();
             }
 
+
             Log::error('合成物品失败', [
                 'user_id' => $userId,
                 'recipe_id' => $recipeId,
@@ -143,7 +148,7 @@ class CraftService
                 'trace' => $e->getTraceAsString()
             ]);
 
-            return false;
+            return Res::success('合成失败');
         }
     }