| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152 |
- <?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);
- 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}秒"
- ];
- }
- }
|