| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699 |
- <?php
- namespace App\Module\Pet\Logic;
- use App\Module\GameItems\Services\ItemService;
- use App\Module\Pet\Enums\PetStatus;
- use App\Module\Pet\Events\PetLevelUpEvent;
- use App\Module\Pet\Events\PetRemouldEvent;
- use App\Module\Pet\Events\PetSkillUsedEvent;
- use App\Module\Pet\Events\PetStatusChangedEvent;
- use App\Module\Pet\Models\PetConfig;
- use App\Module\Pet\Models\PetLevelConfig;
- use App\Module\Pet\Models\PetRemouldLog;
- use App\Module\Pet\Models\PetSkill;
- use App\Module\Pet\Models\PetSkillLog;
- use App\Module\Pet\Models\PetUser;
- use App\Module\Pet\Validators\PetFoodValidator;
- use Exception;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- /**
- * 宠物逻辑类
- *
- * 处理宠物相关的业务逻辑,包括创建宠物、升级宠物、喂养宠物、
- * 洗髓宠物、使用技能等功能。该类是宠物模块内部使用的核心逻辑类,
- * 不对外提供服务,由PetService调用。
- */
- class PetLogic
- {
- /**
- * 物品服务
- *
- * @var ItemService
- */
- protected $itemService;
- /**
- * 宠物食物验证器
- *
- * @var PetFoodValidator
- */
- protected $petFoodValidator;
- /**
- * 构造函数
- */
- public function __construct()
- {
- $this->itemService = new ItemService();
- $this->petFoodValidator = new PetFoodValidator();
- }
- /**
- * 创建宠物
- *
- * @param int $userId 用户ID
- * @param string $name 宠物名称
- * @param int|null $grade 宠物品阶,如果为null则随机生成(1一品,2二品,3三品,4四品)
- * @param array $options 其他选项
- * @return array 创建结果
- * @throws Exception
- */
- public function createPet(int $userId, string $name, ?int $grade = null, array $options = []): array
- {
- // 验证宠物名称
- if (empty($name) || mb_strlen($name) > 20) {
- throw new Exception("宠物名称不能为空且不能超过20个字符");
- }
- // 检查用户宠物数量限制
- $petCount = PetUser::where('user_id', $userId)->count();
- $maxPets = config('pet.max_pets_per_user', 3);
- if ($petCount >= $maxPets) {
- throw new Exception("已达到最大宠物数量限制: {$maxPets}");
- }
- // 如果未指定品阶,则根据概率随机生成
- if ($grade === null) {
- $grade = $this->generateRandomGrade();
- }
- // 获取宠物配置
- $petConfig = PetConfig::where('pet_type', $options['pet_type'] ?? 'default')->first();
- if (!$petConfig) {
- $petConfig = PetConfig::first(); // 使用默认配置
- if (!$petConfig) {
- throw new Exception("宠物配置不存在");
- }
- }
- // 创建宠物
- $pet = new PetUser();
- $pet->user_id = $userId;
- $pet->name = $name;
- $pet->grade = $grade;
- $pet->level = 1;
- $pet->experience = 0;
- $pet->stamina = $petConfig->stamina_max ?? 100;
- $pet->status = PetStatus::NORMAL;
- $pet->save();
- Log::info('宠物创建成功', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'name' => $name,
- 'grade' => $grade->value
- ]);
- return [
- 'pet_id' => $pet->id,
- 'grade' => $grade
- ];
- }
- /**
- * 根据概率随机生成宠物品阶
- *
- * @return int 品阶值(1一品,2二品,3三品,4四品)
- */
- protected function generateRandomGrade(): int
- {
- $probabilities = config('pet.grade_probability', [
- 1 => 0.6, // 一品阶:60%
- 2 => 0.25, // 二品阶:25%
- 3 => 0.1, // 三品阶:10%
- 4 => 0.05 // 四品阶:5%
- ]);
- $rand = mt_rand(1, 100) / 100;
- $cumulative = 0;
- foreach ($probabilities as $grade => $probability) {
- $cumulative += $probability;
- if ($rand <= $cumulative) {
- return $grade;
- }
- }
- // 默认返回一品
- return 1;
- }
- /**
- * 宠物升级
- *
- * @param int $petId 宠物ID
- * @return array 升级结果
- * @throws Exception
- */
- public function levelUpPet(int $petId): array
- {
- // 获取宠物信息
- $pet = PetUser::findOrFail($petId);
- // 获取当前等级配置
- $currentLevelConfig = PetLevelConfig::where('level', $pet->level)->first();
- if (!$currentLevelConfig) {
- throw new Exception("宠物等级配置不存在");
- }
- // 获取下一级配置
- $nextLevelConfig = PetLevelConfig::where('level', $pet->level + 1)->first();
- if (!$nextLevelConfig) {
- throw new Exception("宠物已达到最大等级");
- }
- // 检查经验值是否足够
- if ($pet->experience < $nextLevelConfig->exp_required) {
- throw new Exception("经验值不足,无法升级");
- }
- // 记录旧等级
- $oldLevel = $pet->level;
- // 升级宠物
- $pet->level += 1;
- $pet->save();
- // 获取新解锁的技能
- $unlockedSkills = [];
- if ($nextLevelConfig->unlock_skills) {
- $unlockedSkills = json_decode($nextLevelConfig->unlock_skills, true);
- }
- // 触发宠物升级事件
- event(new PetLevelUpEvent(
- $pet->user_id,
- $pet->id,
- $oldLevel,
- $pet->level,
- $unlockedSkills
- ));
- Log::info('宠物升级成功', [
- 'pet_id' => $petId,
- 'old_level' => $oldLevel,
- 'new_level' => $pet->level,
- 'unlocked_skills' => $unlockedSkills
- ]);
- return [
- 'old_level' => $oldLevel,
- 'new_level' => $pet->level,
- 'unlocked_skills' => $unlockedSkills
- ];
- }
- /**
- * 宠物喂养
- *
- * @param int $petId 宠物ID
- * @param int $itemId 物品ID(狗粮)
- * @param int $amount 数量
- * @return array 喂养结果
- * @throws Exception
- */
- public function feedPet(int $petId, int $itemId, int $amount): array
- {
- // 获取宠物信息
- $pet = PetUser::findOrFail($petId);
- // 验证物品是否为宠物口粮
- if (!$this->petFoodValidator->validate($itemId, [])) {
- throw new Exception("该物品不是宠物口粮");
- }
- // 获取物品信息
- $item = $this->itemService->getItemInfo($itemId);
- if (!$item) {
- throw new Exception("物品不存在");
- }
- // 消耗物品
- $consumeResult = $this->itemService->consumeItem(
- $pet->user_id,
- $itemId,
- null,
- $amount,
- [
- 'source_type' => 'pet_feed',
- 'source_id' => $petId,
- 'details' => ['pet_id' => $petId]
- ]
- );
- if (!$consumeResult['success']) {
- throw new Exception("物品消耗失败: " . ($consumeResult['message'] ?? '未知错误'));
- }
- // 计算获得的经验值和体力
- $expGained = $item->pet_exp * $amount;
- $staminaGained = $item->pet_power * $amount;
- // 更新宠物状态为喂养中
- $oldStatus = $pet->status;
- $pet->status = PetStatus::FEEDING;
- $pet->save();
- // 触发宠物状态变更事件
- event(new PetStatusChangedEvent(
- $pet->user_id,
- $pet->id,
- $oldStatus,
- PetStatus::FEEDING,
- 'pet_feed',
- ['item_id' => $itemId, 'amount' => $amount]
- ));
- // 增加经验值
- $levelUpOccurred = $this->addExperience($petId, $expGained);
- // 恢复体力
- $this->addStamina($petId, $staminaGained);
- // 喂养完成后恢复正常状态
- $pet->refresh();
- $pet->status = PetStatus::NORMAL;
- $pet->save();
- // 触发宠物状态变更事件
- event(new PetStatusChangedEvent(
- $pet->user_id,
- $pet->id,
- PetStatus::FEEDING,
- PetStatus::NORMAL,
- 'pet_feed_complete',
- ['item_id' => $itemId, 'amount' => $amount]
- ));
- Log::info('宠物喂养成功', [
- 'pet_id' => $petId,
- 'item_id' => $itemId,
- 'amount' => $amount,
- 'exp_gained' => $expGained,
- 'stamina_gained' => $staminaGained,
- 'level_up' => $levelUpOccurred
- ]);
- return [
- 'exp_gained' => $expGained,
- 'stamina_gained' => $staminaGained,
- 'level_up' => $levelUpOccurred
- ];
- }
- /**
- * 增加宠物经验值
- *
- * @param int $petId 宠物ID
- * @param int $expAmount 经验值数量
- * @return bool 是否触发升级
- */
- protected function addExperience(int $petId, int $expAmount): bool
- {
- // 获取宠物信息
- $pet = PetUser::findOrFail($petId);
- // 增加经验值
- $pet->experience += $expAmount;
- $pet->save();
- // 检查是否可以升级
- $nextLevelConfig = PetLevelConfig::where('level', $pet->level + 1)->first();
- if ($nextLevelConfig && $pet->experience >= $nextLevelConfig->exp_required) {
- try {
- $this->levelUpPet($petId);
- return true;
- } catch (Exception $e) {
- Log::error('宠物升级失败', [
- 'pet_id' => $petId,
- 'error' => $e->getMessage()
- ]);
- return false;
- }
- }
- return false;
- }
- /**
- * 增加宠物体力
- *
- * @param int $petId 宠物ID
- * @param int $staminaAmount 体力数量
- * @return int 实际增加的体力值
- */
- protected function addStamina(int $petId, int $staminaAmount): int
- {
- // 获取宠物信息
- $pet = PetUser::findOrFail($petId);
- // 获取宠物等级配置
- $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
- $maxStamina = $levelConfig ? $levelConfig->stamina_max : 100;
- // 计算实际增加的体力值
- $oldStamina = $pet->stamina;
- $newStamina = min($maxStamina, $oldStamina + $staminaAmount);
- $actualGained = $newStamina - $oldStamina;
- // 更新体力值
- $pet->stamina = $newStamina;
- $pet->save();
- return $actualGained;
- }
- /**
- * 宠物洗髓
- *
- * @param int $petId 宠物ID
- * @param int $itemId 洗髓道具ID,如果为0则使用钻石
- * @return array 洗髓结果
- * @throws Exception
- */
- public function remouldPet(int $petId, int $itemId = 0): array
- {
- // 获取宠物信息
- $pet = PetUser::findOrFail($petId);
- // 记录旧品阶
- $oldGrade = $pet->grade;
- // 如果使用道具
- if ($itemId > 0) {
- // 验证物品是否为洗髓道具
- $remouldItemId = config('pet.remould_cost.item_id');
- if ($itemId != $remouldItemId) {
- throw new Exception("该物品不是洗髓道具");
- }
- // 消耗物品
- $consumeResult = $this->itemService->consumeItem(
- $pet->user_id,
- $itemId,
- null,
- 1,
- [
- 'source_type' => 'pet_remould',
- 'source_id' => $petId,
- 'details' => ['pet_id' => $petId]
- ]
- );
- if (!$consumeResult['success']) {
- throw new Exception("物品消耗失败: " . ($consumeResult['message'] ?? '未知错误'));
- }
- } else {
- // 使用钻石
- $diamondCost = config('pet.remould_cost.diamond', 50);
- // TODO: 消耗钻石的逻辑,需要调用相关服务
- // 这里需要根据实际项目中的钻石消耗方式进行实现
- // 暂时使用占位代码
- $diamondConsumeSuccess = true;
- if (!$diamondConsumeSuccess) {
- throw new Exception("钻石不足,无法进行洗髓");
- }
- }
- // 随机生成新品阶
- $newGrade = $this->generateRandomGrade();
- // 更新宠物品阶
- $pet->grade = $newGrade;
- $pet->save();
- // 记录洗髓日志
- PetRemouldLog::create([
- 'pet_id' => $petId,
- 'old_grade' => $oldGrade,
- 'new_grade' => $newGrade,
- 'remould_time' => now()
- ]);
- // 触发宠物洗髓事件
- event(new PetRemouldEvent(
- $pet->user_id,
- $pet->id,
- $oldGrade,
- $newGrade
- ));
- Log::info('宠物洗髓成功', [
- 'pet_id' => $petId,
- 'old_grade' => $oldGrade,
- 'new_grade' => $newGrade,
- 'item_id' => $itemId
- ]);
- return [
- 'old_grade' => $oldGrade,
- 'new_grade' => $newGrade
- ];
- }
- /**
- * 使用宠物技能
- *
- * @param int $petId 宠物ID
- * @param int $skillId 技能ID
- * @param array $params 技能参数
- * @return array 技能使用结果
- * @throws Exception
- */
- public function useSkill(int $petId, int $skillId, array $params = []): array
- {
- // 获取宠物信息
- $pet = PetUser::findOrFail($petId);
- // 获取技能信息
- $skill = PetSkill::findOrFail($skillId);
- // 检查技能冷却时间
- $lastUsed = PetSkillLog::where('pet_id', $petId)
- ->where('skill_id', $skillId)
- ->orderBy('used_at', 'desc')
- ->first();
- if ($lastUsed) {
- $cooldownSeconds = $skill->cool_down;
- $secondsSinceLastUse = now()->diffInSeconds($lastUsed->used_at);
- if ($secondsSinceLastUse < $cooldownSeconds) {
- $remainingCooldown = $cooldownSeconds - $secondsSinceLastUse;
- throw new Exception("技能冷却中,还需等待 {$remainingCooldown} 秒");
- }
- }
- // 检查体力是否足够
- if ($pet->stamina < $skill->stamina_cost) {
- throw new Exception("体力不足,无法使用技能");
- }
- // 消耗体力
- $pet->stamina -= $skill->stamina_cost;
- $pet->save();
- // 执行技能效果
- $effectResult = $this->executeSkillEffect($pet, $skill, $params);
- // 记录技能使用日志
- $skillLog = PetSkillLog::create([
- 'pet_id' => $petId,
- 'skill_id' => $skillId,
- 'used_at' => now(),
- 'effect_result' => json_encode($effectResult)
- ]);
- // 触发宠物技能使用事件
- event(new PetSkillUsedEvent(
- $pet->user_id,
- $pet->id,
- $skillId,
- $params
- ));
- Log::info('宠物技能使用成功', [
- 'pet_id' => $petId,
- 'skill_id' => $skillId,
- 'params' => $params,
- 'effect_result' => $effectResult
- ]);
- return [
- 'effect_result' => $effectResult
- ];
- }
- /**
- * 执行技能效果
- *
- * @param PetUser $pet 宠物对象
- * @param PetSkill $skill 技能对象
- * @param array $params 技能参数
- * @return array 技能效果结果
- */
- protected function executeSkillEffect(PetUser $pet, PetSkill $skill, array $params): array
- {
- // 根据技能名称执行不同的效果
- switch ($skill->skill_name) {
- case '自动收菜':
- // 调用农场模块的收获接口
- // 这里需要根据实际项目中的农场模块接口进行实现
- // 暂时使用占位代码
- $harvestResult = [
- 'success' => true,
- 'harvested_count' => mt_rand(1, 5),
- 'items' => []
- ];
- return $harvestResult;
- case '自动播种':
- // 调用农场模块的播种接口
- // 这里需要根据实际项目中的农场模块接口进行实现
- // 暂时使用占位代码
- $plantResult = [
- 'success' => true,
- 'planted_count' => mt_rand(1, 5),
- 'seeds' => []
- ];
- return $plantResult;
- case '灾害防护':
- // 设置农场模块的灾害防护标志
- // 这里需要根据实际项目中的农场模块接口进行实现
- // 暂时使用占位代码
- $protectResult = [
- 'success' => true,
- 'protected_type' => $params['disaster_type'] ?? 'all',
- 'duration' => 3600 // 1小时
- ];
- return $protectResult;
- default:
- return [
- 'success' => false,
- 'message' => '未知技能效果'
- ];
- }
- }
- /**
- * 变更宠物状态
- *
- * @param int $petId 宠物ID
- * @param PetStatus $status 新状态
- * @param string $reason 变更原因
- * @return bool 是否变更成功
- */
- public function changeStatus(int $petId, PetStatus $status, string $reason = ''): bool
- {
- // 获取宠物信息
- $pet = PetUser::findOrFail($petId);
- // 记录旧状态
- $oldStatus = $pet->status;
- // 如果状态相同,则不需要变更
- if ($oldStatus === $status) {
- return true;
- }
- // 更新状态
- $pet->status = $status;
- $pet->save();
- // 触发宠物状态变更事件
- event(new PetStatusChangedEvent(
- $pet->user_id,
- $pet->id,
- $oldStatus,
- $status,
- $reason
- ));
- Log::info('宠物状态变更成功', [
- 'pet_id' => $petId,
- 'old_status' => $oldStatus->value,
- 'new_status' => $status->value,
- 'reason' => $reason
- ]);
- return true;
- }
- /**
- * 恢复宠物体力
- *
- * @param int $petId 宠物ID
- * @param int $minutes 经过的分钟数
- * @return int 恢复的体力值
- */
- public function recoverStamina(int $petId, int $minutes): int
- {
- // 获取宠物信息
- $pet = PetUser::findOrFail($petId);
- // 获取宠物等级配置
- $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
- $maxStamina = $levelConfig ? $levelConfig->stamina_max : 100;
- $recoveryRate = $levelConfig ? $levelConfig->stamina_recovery_rate : 5;
- // 计算恢复的体力值
- $recoveryAmount = $recoveryRate * $minutes;
- $oldStamina = $pet->stamina;
- $newStamina = min($maxStamina, $oldStamina + $recoveryAmount);
- $actualRecovered = $newStamina - $oldStamina;
- // 更新体力值
- if ($actualRecovered > 0) {
- $pet->stamina = $newStamina;
- $pet->save();
- Log::info('宠物体力恢复成功', [
- 'pet_id' => $petId,
- 'minutes' => $minutes,
- 'recovery_rate' => $recoveryRate,
- 'old_stamina' => $oldStamina,
- 'new_stamina' => $newStamina,
- 'actual_recovered' => $actualRecovered
- ]);
- }
- return $actualRecovered;
- }
- /**
- * 计算宠物战力
- *
- * @param int $petId 宠物ID
- * @return int 战力值
- */
- public function calculatePower(int $petId): int
- {
- // 获取宠物信息
- $pet = PetUser::findOrFail($petId);
- // 获取宠物等级配置
- $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
- // 基础战力
- $basePower = $levelConfig ? ($levelConfig->numeric_attributes['base_power'] ?? 100) : 100;
- // 品阶加成
- $gradeBonus = config('pet.grade_attribute_bonus.' . $pet->grade, 0);
- // 计算最终战力
- $power = $basePower * (1 + $gradeBonus);
- return (int)$power;
- }
- }
|