| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141 |
- <?php
- namespace App\Module\Pet\Logic;
- use App\Module\GameItems\Dtos\ItemDto;
- use App\Module\GameItems\Services\ItemService;
- use App\Module\Pet\Enums\PetStatus;
- use App\Module\Pet\Events\PetCreatedEvent;
- 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\Events\PetUpdateEvent;
- 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 Exception;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use UCore\Dto\Res;
- use UCore\Exception\LogicException;
- use Uraus\Kku\Common\DataPetSimple;
- /**
- * 宠物逻辑类
- *
- * 处理宠物相关的业务逻辑,包括创建宠物、升级宠物、喂养宠物、
- * 洗髓宠物、使用技能等功能。该类是宠物模块内部使用的核心逻辑类,
- * 不对外提供服务,由PetService调用。
- */
- class PetLogic
- {
- /**
- * 构造函数
- */
- public function __construct()
- {
- // 构造函数不需要初始化任何属性
- }
- /**
- * 创建宠物
- *
- * @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();
- $nextLevelConfig = PetLevelConfig::where('level', 2)->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->max_experience = $nextLevelConfig->exp_required;
- $pet->stamina = $petConfig->stamina_max ?? 100;
- $pet->max_stamina = $petConfig->stamina_max ?? 100;
- $pet->status = PetStatus::NORMAL;
- $pet->save();
- // 触发宠物创建事件
- event(new PetCreatedEvent(
- $userId,
- $pet->id
- ));
- Log::info('宠物创建成功', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'name' => $name,
- 'grade' => $grade
- ]);
- 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 升级结果
- */
- public function levelUpPet(PetUser $pet): Res
- {
- $change = false;
- // 记录旧等级
- $oldLevel = $pet->level;
- foreach (range(1, 20) as $level) {
- // 获取当前等级配置
- $currentLevelConfig = PetLevelConfig::where('level', $pet->level)->first();
- if (!$currentLevelConfig) {
- break;
- }
- // 获取下一级配置
- $nextLevelConfig = PetLevelConfig::where('level', $pet->level + 1)->first();
- if (!$nextLevelConfig) {
- break;
- }
- if($pet->experience < $nextLevelConfig->exp_required){
- break;
- }
- // 获取下一级配置
- $nextLevelConfig2 = PetLevelConfig::where('level', $pet->level + 2)->first();
- // 升级宠物
- $pet->level += 1;
- $pet->experience = $pet->experience - $nextLevelConfig->exp_required;
- if ($nextLevelConfig2) {
- $pet->max_experience = $nextLevelConfig2->exp_required;
- } else {
- $pet->max_experience = 0;
- }
- $change = true;
- }
- if ($change) {
- $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
- ));
- // 触发宠物更新事件,表示宠物数据发生重大变更
- event(new PetUpdateEvent(
- $pet->user_id,
- $pet->id
- ));
- Log::info('宠物升级成功', [
- 'pet_id' => $pet->id,
- 'old_level' => $oldLevel,
- 'new_level' => $pet->level,
- 'unlocked_skills' => $unlockedSkills
- ]);
- }
- return Res::success('');
- }
- /**
- * 宠物喂养
- *
- * @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
- {
- // 获取宠物信息
- /**
- * @var PetUser $pet
- */
- $pet = PetUser::findOrFail($petId);
- // 获取物品信息
- /**
- * @var ItemDto $item
- */
- $item = ItemService::getItemInfo($itemId);
- if (!$item) {
- throw new LogicException("物品不存在");
- }
- // 消耗物品
- $consumeResult = ItemService::consumeItem(
- $pet->user_id,
- $itemId,
- null,
- $amount,
- [
- 'source_type' => 'pet_feed',
- 'source_id' => $petId,
- 'details' => [ 'pet_id' => $petId ]
- ]
- );
- if (!$consumeResult['success']) {
- throw new LogicException("物品消耗失败: " . ($consumeResult['message'] ?? '未知错误'));
- }
- // 计算获得的经验值和体力
- $expGained = ($item->numericAttributes['pet_exp'] ?? 0) * $amount;
- $staminaGained = ($item->numericAttributes['pet_power'] ?? 0) * $amount;
- if (!$expGained && !$staminaGained) {
- throw new LogicException('错误的参数');
- }
- // 增加经验值
- $pet->experience += $expGained;
- // 更新体力值
- $pet->stamina += $staminaGained;
- $pet->save();
- // 喂养完成后恢复正常状态
- // $pet->refresh();
- // $pet->status = PetStatus::NORMAL;
- $pet->save();
- // 检查升级
- $this->check_uplevel($pet);
- // 创建旧状态数据
- $oldStatusData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
- $oldStatusData->id = $pet->id;
- $oldStatusData->status = PetStatus::FEEDING->value;
- // 创建新状态数据
- $newStatusData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
- $newStatusData->id = $pet->id;
- $newStatusData->status = PetStatus::NORMAL->value;
- // 创建完整的宠物数据
- $petData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
- $petData->id = $pet->id;
- $petData->name = $pet->name;
- $petData->level = $pet->level;
- // $petData->grade = $pet->grade->value;
- $petData->power = $pet->stamina;
- $petData->exp = $pet->experience;
- // 触发宠物状态变更事件
- event(new PetStatusChangedEvent(
- $pet->user_id,
- $pet->id,
- $oldStatusData,
- $newStatusData,
- 'pet_feed_complete',
- $petData
- ));
- Log::info('宠物喂养成功', [
- 'pet_id' => $petId,
- 'item_id' => $itemId,
- 'amount' => $amount,
- 'exp_gained' => $expGained,
- 'stamina_gained' => $staminaGained,
- ]);
- return [
- 'exp_gained' => $expGained,
- 'stamina_gained' => $staminaGained,
- ];
- }
- /**
- * 增加宠物经验值
- *
- * @param int $petId 宠物ID
- * @param int $expAmount 经验值数量
- * @return bool 是否触发升级
- */
- protected function check_uplevel(PetUser $pet): Res
- {
- if ($pet->max_experience === 0) {
- return Res::error('最高等级,无法升级');
- }
- if ($pet->experience >= $pet->max_experience) {
- return $this->levelUpPet($pet);
- }
- return Res::error('经验不足');
- }
- /**
- * 增加宠物体力
- *
- * @param int $petId 宠物ID
- * @param int $staminaAmount 体力数量
- * @return int 实际增加的体力值
- */
- protected function addStamina(PetUser $pet, int $staminaAmount): int
- {
- // 获取宠物等级配置
- $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
- $maxStamina = $levelConfig ? ($levelConfig->numeric_attributes->stamina_max ?? 100) : 100;
- // 计算实际增加的体力值
- $oldStamina = $pet->stamina;
- $newStamina = max($maxStamina, $oldStamina + $staminaAmount);
- $actualGained = $newStamina - $oldStamina;
- 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 = 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
- ));
- // 触发宠物更新事件,表示宠物数据发生重大变更
- event(new PetUpdateEvent(
- $pet->user_id,
- $pet->id
- ));
- 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;
- $now = now();
- $lastUsedTime = $lastUsed->used_at;
- // 确保时间计算的正确性
- if ($lastUsedTime instanceof \Carbon\Carbon) {
- $secondsSinceLastUse = $now->diffInSeconds($lastUsedTime, false);
- } else {
- // 如果不是Carbon对象,尝试解析
- $lastUsedTime = \Carbon\Carbon::parse($lastUsedTime);
- $secondsSinceLastUse = $now->diffInSeconds($lastUsedTime, false);
- }
- // 如果secondsSinceLastUse为负数,说明lastUsed时间在未来,这是异常情况
- if ($secondsSinceLastUse < 0) {
- Log::warning('检测到异常的技能使用时间', [
- 'pet_id' => $petId,
- 'skill_id' => $skillId,
- 'last_used_at' => $lastUsedTime->toDateTimeString(),
- 'current_time' => $now->toDateTimeString(),
- 'seconds_diff' => $secondsSinceLastUse
- ]);
- // 异常情况下,重置为0,允许技能使用
- $secondsSinceLastUse = 0;
- }
- if ($secondsSinceLastUse < $cooldownSeconds) {
- $remainingCooldown = $cooldownSeconds - $secondsSinceLastUse;
- // 记录详细的冷却信息用于调试
- Log::info('技能冷却检查', [
- 'pet_id' => $petId,
- 'skill_id' => $skillId,
- 'cooldown_seconds' => $cooldownSeconds,
- 'seconds_since_last_use' => $secondsSinceLastUse,
- 'remaining_cooldown' => $remainingCooldown,
- 'last_used_at' => $lastUsedTime->toDateTimeString(),
- 'current_time' => $now->toDateTimeString()
- ]);
- throw new Exception("技能冷却中,还需等待 {$remainingCooldown} 秒");
- }
- }
- // 检查体力是否足够
- if ($pet->stamina < $skill->stamina_cost) {
- throw new Exception("体力不足,无法使用技能");
- }
- // 先执行技能效果,确保技能能够成功激活
- $effectResult = $this->executeSkillEffect($pet, $skill, $params);
- // 检查技能效果是否成功
- if (isset($effectResult['success']) && $effectResult['success'] === false) {
- // 技能效果执行失败,记录失败日志但不消耗体力,不进入冷却
- Log::warning('宠物技能使用失败', [
- 'pet_id' => $petId,
- 'skill_id' => $skillId,
- 'params' => $params,
- 'effect_result' => $effectResult,
- 'reason' => $effectResult['message'] ?? '技能使用失败'
- ]);
- throw new Exception($effectResult['message'] ?? '技能使用失败');
- }
- // 技能效果成功,消耗体力
- $pet->stamina -= $skill->stamina_cost;
- $pet->save();
- // 记录技能使用日志(只有成功时才记录)
- $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 \App\Module\Pet\Enums\PET_SKILL_NAME::AUTO_HARVESTING->value:
- return $this->activateAutoHarvestSkill($pet, $skill, $params);
- case \App\Module\Pet\Enums\PET_SKILL_NAME::AUTO_PLANTING->value:
- return $this->activateAutoPlantSkill($pet, $skill, $params);
- case \App\Module\Pet\Enums\PET_SKILL_NAME::DISASTER_PROTECTION->value:
- return $this->activateDisasterProtectionSkill($pet, $skill, $params);
- case \App\Module\Pet\Enums\PET_SKILL_NAME::AUTO_WEEDING->value:
- return $this->activateAutoWeedingSkill($pet, $skill, $params);
- case \App\Module\Pet\Enums\PET_SKILL_NAME::AUTO_WATERING->value:
- return $this->activateAutoWateringSkill($pet, $skill, $params);
- case \App\Module\Pet\Enums\PET_SKILL_NAME::AUTO_PEST_CONTROL->value:
- return $this->activateAutoPestControlSkill($pet, $skill, $params);
- default:
- return [
- 'success' => false,
- 'message' => '未知技能效果'
- ];
- }
- }
- /**
- * 激活自动收菜技能
- *
- * @param PetUser $pet 宠物对象
- * @param PetSkill $skill 技能对象
- * @param array $params 技能参数
- * @return array 激活结果
- */
- protected function activateAutoHarvestSkill(PetUser $pet, PetSkill $skill, array $params): array
- {
- // 检查是否已有相同技能在激活中
- $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
- ->where('skill_name', $skill->skill_name)
- ->where('status', 'active')
- ->where('end_time', '>', now())
- ->first();
- if ($existingActiveSkill) {
- return [
- 'success' => false,
- 'message' => '该技能已经在激活中,无法重复激活'
- ];
- }
- // 技能持续时间(默认2小时)
- $duration = $params['duration'] ?? 7200; // 2小时
- $endTime = now()->addSeconds($duration);
- // 创建技能激活记录
- $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
- 'pet_id' => $pet->id,
- 'skill_id' => $skill->id,
- 'skill_name' => $skill->skill_name,
- 'start_time' => now(),
- 'end_time' => $endTime,
- 'status' => 'active',
- 'config' => json_encode([
- 'auto_harvest' => true,
- 'check_interval' => 60,
- // 每分钟检查一次
- 'last_check_time' => now()->toDateTimeString()
- ])
- ]);
- Log::info('自动收菜技能激活成功', [
- 'pet_id' => $pet->id,
- 'skill_id' => $skill->id,
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'active_skill_id' => $activeSkill->id
- ]);
- return [
- 'success' => true,
- 'skill_type' => 'auto_harvest',
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'message' => "自动收菜技能已激活,持续时间:{$duration}秒"
- ];
- }
- /**
- * 激活自动播种技能
- *
- * @param PetUser $pet 宠物对象
- * @param PetSkill $skill 技能对象
- * @param array $params 技能参数
- * @return array 激活结果
- */
- protected function activateAutoPlantSkill(PetUser $pet, PetSkill $skill, array $params): array
- {
- // 检查是否已有相同技能在激活中
- $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
- ->where('skill_name', $skill->skill_name)
- ->where('status', 'active')
- ->where('end_time', '>', now())
- ->first();
- if ($existingActiveSkill) {
- return [
- 'success' => false,
- 'message' => '该技能已经在激活中,无法重复激活'
- ];
- }
- // 技能持续时间(默认4小时)
- $duration = $params['duration'] ?? 14400; // 4小时
- $endTime = now()->addSeconds($duration);
- // 创建技能激活记录
- $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
- 'pet_id' => $pet->id,
- 'skill_id' => $skill->id,
- 'skill_name' => $skill->skill_name,
- 'start_time' => now(),
- 'end_time' => $endTime,
- 'status' => 'active',
- 'config' => json_encode([
- 'auto_plant' => true,
- 'check_interval' => 60,
- // 每分钟检查一次
- 'last_check_time' => now()->toDateTimeString(),
- 'preferred_seeds' => $params['preferred_seeds'] ?? []
- // 优先使用的种子ID列表
- ])
- ]);
- Log::info('自动播种技能激活成功', [
- 'pet_id' => $pet->id,
- 'skill_id' => $skill->id,
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'active_skill_id' => $activeSkill->id
- ]);
- return [
- 'success' => true,
- 'skill_type' => 'auto_plant',
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'message' => "自动播种技能已激活,持续时间:{$duration}秒"
- ];
- }
- /**
- * 激活灾害防护技能
- *
- * @param PetUser $pet 宠物对象
- * @param PetSkill $skill 技能对象
- * @param array $params 技能参数
- * @return array 激活结果
- */
- protected function activateDisasterProtectionSkill(PetUser $pet, PetSkill $skill, array $params): array
- {
- // 检查是否已有相同技能在激活中
- $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
- ->where('skill_name', $skill->skill_name)
- ->where('status', 'active')
- ->where('end_time', '>', now())
- ->first();
- if ($existingActiveSkill) {
- return [
- 'success' => false,
- 'message' => '该技能已经在激活中,无法重复激活'
- ];
- }
- // 技能持续时间(默认6小时)
- $duration = $params['duration'] ?? 21600; // 6小时
- $endTime = now()->addSeconds($duration);
- // 创建技能激活记录
- $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
- 'pet_id' => $pet->id,
- 'skill_id' => $skill->id,
- 'skill_name' => $skill->skill_name,
- 'start_time' => now(),
- 'end_time' => $endTime,
- 'status' => 'active',
- 'config' => json_encode([
- 'disaster_protection' => true,
- 'protected_types' => $params['disaster_types'] ?? [ 'all' ],
- // 防护的灾害类型
- 'check_interval' => 300,
- // 每5分钟检查一次
- 'last_check_time' => now()->toDateTimeString()
- ])
- ]);
- Log::info('灾害防护技能激活成功', [
- 'pet_id' => $pet->id,
- 'skill_id' => $skill->id,
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'active_skill_id' => $activeSkill->id
- ]);
- return [
- 'success' => true,
- 'skill_type' => 'disaster_protection',
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'message' => "灾害防护技能已激活,持续时间:{$duration}秒"
- ];
- }
- /**
- * 变更宠物状态
- *
- * @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();
- // 创建旧状态数据
- $oldStatusData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
- $oldStatusData->id = $pet->id;
- $oldStatusData->status = $oldStatus->value;
- // 创建新状态数据
- $newStatusData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
- $newStatusData->id = $pet->id;
- $newStatusData->status = $status->value;
- // 创建完整的宠物数据
- $petData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
- $petData->id = $pet->id;
- $petData->name = $pet->name;
- $petData->typeId = $pet->type_id;
- $petData->level = $pet->level;
- $petData->grade = $pet->grade->value;
- $petData->status = $status->value;
- // 触发宠物状态变更事件
- event(new PetStatusChangedEvent(
- $pet->user_id,
- $pet->id,
- $oldStatusData,
- $newStatusData,
- $reason,
- $petData
- ));
- 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->numeric_attributes->stamina_max ?? 100) : 100;
- $recoveryRate = $levelConfig ? ($levelConfig->numeric_attributes->stamina_recovery ?? 5) : 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;
- }
- /**
- * 激活自动除草技能
- *
- * @param PetUser $pet 宠物对象
- * @param PetSkill $skill 技能对象
- * @param array $params 技能参数
- * @return array 激活结果
- */
- protected function activateAutoWeedingSkill(PetUser $pet, PetSkill $skill, array $params): array
- {
- // 检查是否已有相同技能在激活中
- $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
- ->where('skill_name', $skill->skill_name)
- ->where('status', 'active')
- ->where('end_time', '>', now())
- ->first();
- if ($existingActiveSkill) {
- return [
- 'success' => false,
- 'message' => '该技能已经在激活中,无法重复激活'
- ];
- }
- // 技能持续时间(默认3小时)
- $duration = $params['duration'] ?? 10800; // 3小时
- $endTime = now()->addSeconds($duration);
- // 创建技能激活记录
- $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
- 'pet_id' => $pet->id,
- 'skill_id' => $skill->id,
- 'skill_name' => $skill->skill_name,
- 'start_time' => now(),
- 'end_time' => $endTime,
- 'status' => 'active',
- 'config' => json_encode([
- 'auto_weeding' => true,
- 'disaster_type' => \App\Module\Farm\Enums\DISASTER_TYPE::WEED->value,
- // 专门处理杂草灾害
- 'check_interval' => 300,
- 'last_check_time' => now()->toDateTimeString(),
- 'auto_use_items' => $params['auto_use_items'] ?? true
- // 是否自动使用除草道具
- ])
- ]);
- Log::info('自动除草技能激活成功', [
- 'pet_id' => $pet->id,
- 'skill_id' => $skill->id,
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'active_skill_id' => $activeSkill->id
- ]);
- return [
- 'success' => true,
- 'skill_type' => 'auto_weeding',
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'message' => "自动除草技能已激活,持续时间:{$duration}秒"
- ];
- }
- /**
- * 激活自动浇水技能
- *
- * @param PetUser $pet 宠物对象
- * @param PetSkill $skill 技能对象
- * @param array $params 技能参数
- * @return array 激活结果
- */
- protected function activateAutoWateringSkill(PetUser $pet, PetSkill $skill, array $params): array
- {
- // 检查是否已有相同技能在激活中
- $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
- ->where('skill_name', $skill->skill_name)
- ->where('status', 'active')
- ->where('end_time', '>', now())
- ->first();
- if ($existingActiveSkill) {
- return [
- 'success' => false,
- 'message' => '该技能已经在激活中,无法重复激活'
- ];
- }
- // 技能持续时间(默认4小时)
- $duration = $params['duration'] ?? 14400; // 4小时
- $endTime = now()->addSeconds($duration);
- // 创建技能激活记录
- $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
- 'pet_id' => $pet->id,
- 'skill_id' => $skill->id,
- 'skill_name' => $skill->skill_name,
- 'start_time' => now(),
- 'end_time' => $endTime,
- 'status' => 'active',
- 'config' => json_encode([
- 'auto_watering' => true,
- 'disaster_type' => \App\Module\Farm\Enums\DISASTER_TYPE::DROUGHT->value,
- // 专门处理干旱灾害
- 'check_interval' => 300,
- // 每5分钟检查一次
- 'last_check_time' => now()->toDateTimeString(),
- 'auto_use_items' => $params['auto_use_items'] ?? true
- // 是否自动使用浇水道具
- ])
- ]);
- Log::info('自动浇水技能激活成功', [
- 'pet_id' => $pet->id,
- 'skill_id' => $skill->id,
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'active_skill_id' => $activeSkill->id
- ]);
- return [
- 'success' => true,
- 'skill_type' => 'auto_watering',
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'message' => "自动浇水技能已激活,持续时间:{$duration}秒"
- ];
- }
- /**
- * 激活自动杀虫技能
- *
- * @param PetUser $pet 宠物对象
- * @param PetSkill $skill 技能对象
- * @param array $params 技能参数
- * @return array 激活结果
- */
- protected function activateAutoPestControlSkill(PetUser $pet, PetSkill $skill, array $params): array
- {
- // 检查是否已有相同技能在激活中
- $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
- ->where('skill_name', $skill->skill_name)
- ->where('status', 'active')
- ->where('end_time', '>', now())
- ->first();
- if ($existingActiveSkill) {
- return [
- 'success' => false,
- 'message' => '该技能已经在激活中,无法重复激活'
- ];
- }
- // 技能持续时间(默认3小时)
- $duration = $params['duration'] ?? 10800; // 3小时
- $endTime = now()->addSeconds($duration);
- // 创建技能激活记录
- $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
- 'pet_id' => $pet->id,
- 'skill_id' => $skill->id,
- 'skill_name' => $skill->skill_name,
- 'start_time' => now(),
- 'end_time' => $endTime,
- 'status' => 'active',
- 'config' => json_encode([
- 'auto_pest_control' => true,
- 'disaster_type' => \App\Module\Farm\Enums\DISASTER_TYPE::PEST->value,
- // 专门处理虫害灾害
- 'check_interval' => 300,
- // 每5分钟检查一次
- 'last_check_time' => now()->toDateTimeString(),
- 'auto_use_items' => $params['auto_use_items'] ?? true
- // 是否自动使用杀虫道具
- ])
- ]);
- Log::info('自动杀虫技能激活成功', [
- 'pet_id' => $pet->id,
- 'skill_id' => $skill->id,
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'active_skill_id' => $activeSkill->id
- ]);
- return [
- 'success' => true,
- 'skill_type' => 'auto_pest_control',
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'message' => "自动杀虫技能已激活,持续时间:{$duration}秒"
- ];
- }
- }
|