| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220 |
- <?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 UCore\Helper\Logger;
- 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;
- $nextLevelConfigOld = null;
- 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;
- $nextLevelConfigOld = $nextLevelConfig;
- }
- if ($change) {
- $pet->save();
- // 获取新解锁的技能
- $unlockedSkills = [];
- if($nextLevelConfig){
- if ($nextLevelConfig->unlock_skills) {
- $unlockedSkills = json_decode($nextLevelConfig->unlock_skills, true);
- }
- }
- if($nextLevelConfigOld){
- if ($nextLevelConfigOld->unlock_skills) {
- $unlockedSkills = json_decode($nextLevelConfigOld->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::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);
- case \App\Module\Pet\Enums\PET_SKILL_NAME::AUTO_FERTILIZING->value:
- return $this->activateAutoFertilizingSkill($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' => '该技能已经在激活中,无法重复激活'
- ];
- }
- // 技能持续时间,
- $duration = $params['duration'] ?? $skill->duration_time; // 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'] ?? $skill->duration_time; // 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_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'] ?? $skill->duration_time; // 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_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'] ?? $skill->duration_time;
- $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'] ?? $skill->duration_time; // 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_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}秒"
- ];
- }
- /**
- * 激活自动施肥技能
- *
- * @param PetUser $pet 宠物对象
- * @param PetSkill $skill 技能对象
- * @param array $params 技能参数
- * @return array 激活结果
- */
- protected function activateAutoFertilizingSkill(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'] ?? $skill->duration_time;
- $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_fertilizing' => true,
- 'check_interval' => 300,
- // 每5分钟检查一次
- 'last_check_time' => now()->toDateTimeString(),
- 'auto_use_items' => $params['auto_use_items'] ?? true,
- // 是否自动使用肥料道具
- 'fertilizer_types' => $params['fertilizer_types'] ?? ['fertilizer'],
- // 允许使用的肥料类型
- ])
- ]);
- 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_fertilizing',
- 'duration' => $duration,
- 'end_time' => $endTime->toDateTimeString(),
- 'message' => "自动施肥技能已激活,持续时间:{$duration}秒"
- ];
- }
- }
|