PetLogic.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. <?php
  2. namespace App\Module\Pet\Logic;
  3. use App\Module\GameItems\Dtos\ItemDto;
  4. use App\Module\GameItems\Services\ItemService;
  5. use App\Module\Pet\Enums\PetStatus;
  6. use App\Module\Pet\Events\PetCreatedEvent;
  7. use App\Module\Pet\Events\PetExpGainedEvent;
  8. use App\Module\Pet\Events\PetLevelUpEvent;
  9. use App\Module\Pet\Events\PetSkillUsedEvent;
  10. use App\Module\Pet\Events\PetStatusChangedEvent;
  11. use App\Module\Pet\Events\PetUpdateEvent;
  12. use App\Module\Pet\Models\PetConfig;
  13. use App\Module\Pet\Models\PetLevelConfig;
  14. use App\Module\Pet\Models\PetSkill;
  15. use App\Module\Pet\Models\PetSkillLog;
  16. use App\Module\Pet\Models\PetUser;
  17. use Exception;
  18. use Illuminate\Support\Facades\DB;
  19. use Illuminate\Support\Facades\Log;
  20. use UCore\Dto\Res;
  21. use UCore\Exception\LogicException;
  22. use UCore\Helper\Logger;
  23. use Uraus\Kku\Common\DataPetSimple;
  24. /**
  25. * 宠物逻辑类
  26. *
  27. * 处理宠物相关的业务逻辑,包括创建宠物、升级宠物、喂养宠物、
  28. * 洗髓宠物、使用技能等功能。该类是宠物模块内部使用的核心逻辑类,
  29. * 不对外提供服务,由PetService调用。
  30. */
  31. class PetLogic
  32. {
  33. /**
  34. * 宠物技能检查间隔时间(秒)
  35. */
  36. public const SKILL_CHECK_INTERVAL = 58;
  37. /**
  38. * 构造函数
  39. */
  40. public function __construct()
  41. {
  42. // 构造函数不需要初始化任何属性
  43. }
  44. /**
  45. * 创建宠物
  46. *
  47. * @param int $userId 用户ID
  48. * @param string $name 宠物名称
  49. * @param array $options 其他选项
  50. * @return array 创建结果
  51. * @throws Exception
  52. */
  53. public function createPet(int $userId, string $name, array $options = []): array
  54. {
  55. // 验证宠物名称
  56. if (empty($name) || mb_strlen($name) > 20) {
  57. throw new Exception("宠物名称不能为空且不能超过20个字符");
  58. }
  59. // 检查用户宠物数量限制 - 一人一宠限制
  60. $petCount = PetUser::where('user_id', $userId)->count();
  61. $maxPets = 1; // 强制限制为1只宠物
  62. if ($petCount >= $maxPets) {
  63. throw new Exception("每人只能拥有一只宠物");
  64. }
  65. // 获取宠物配置
  66. $petConfig = PetConfig::where('pet_type', $options['pet_type'] ?? 'default')->first();
  67. $nextLevelConfig = PetLevelConfig::where('level', 2)->first();
  68. if (!$petConfig) {
  69. $petConfig = PetConfig::first(); // 使用默认配置
  70. if (!$petConfig) {
  71. throw new Exception("宠物配置不存在");
  72. }
  73. }
  74. // 创建宠物
  75. $pet = new PetUser();
  76. $pet->user_id = $userId;
  77. $pet->name = $name;
  78. $pet->level = 1;
  79. $pet->experience = 0;
  80. // 体力值从等级配置获取
  81. $levelConfig = PetLevelConfig::where('level', 1)->first();
  82. $pet->stamina = $levelConfig ? ($levelConfig->numeric_attributes->stamina_max ?? 100) : 100;
  83. $pet->status = PetStatus::NORMAL;
  84. $pet->save();
  85. // 触发宠物创建事件
  86. event(new PetCreatedEvent(
  87. $userId,
  88. $pet->id
  89. ));
  90. Log::info('宠物创建成功', [
  91. 'user_id' => $userId,
  92. 'pet_id' => $pet->id,
  93. 'name' => $name
  94. ]);
  95. return [
  96. 'pet_id' => $pet->id
  97. ];
  98. }
  99. /**
  100. * 宠物升级
  101. *
  102. * @param int $petId 宠物ID
  103. * @return array 升级结果
  104. */
  105. public function levelUpPet(PetUser $pet): Res
  106. {
  107. $change = false;
  108. // 记录旧等级
  109. $oldLevel = $pet->level;
  110. $nextLevelConfigOld = null;
  111. foreach (range(1, 20) as $level) {
  112. // 获取当前等级配置
  113. $currentLevelConfig = PetLevelConfig::where('level', $pet->level)->first();
  114. if (!$currentLevelConfig) {
  115. break;
  116. }
  117. // 获取下一级配置
  118. $nextLevelConfig = PetLevelConfig::where('level', $pet->level + 1)->first();
  119. if (!$nextLevelConfig) {
  120. break;
  121. }
  122. if($pet->experience < $nextLevelConfig->exp_required){
  123. break;
  124. }
  125. // 升级宠物
  126. $pet->level += 1;
  127. $pet->experience = $pet->experience - $nextLevelConfig->exp_required;
  128. $change = true;
  129. $nextLevelConfigOld = $nextLevelConfig;
  130. }
  131. if ($change) {
  132. $pet->save();
  133. // 获取新解锁的技能
  134. $unlockedSkills = [];
  135. if($nextLevelConfig){
  136. if ($nextLevelConfig->unlock_skills) {
  137. $unlockedSkills = json_decode($nextLevelConfig->unlock_skills, true);
  138. }
  139. }
  140. if($nextLevelConfigOld){
  141. if ($nextLevelConfigOld->unlock_skills) {
  142. $unlockedSkills = json_decode($nextLevelConfigOld->unlock_skills, true);
  143. }
  144. }
  145. // 触发宠物升级事件
  146. event(new PetLevelUpEvent(
  147. $pet->user_id,
  148. $pet->id,
  149. $oldLevel,
  150. $pet->level,
  151. $unlockedSkills
  152. ));
  153. // 触发宠物更新事件,表示宠物数据发生重大变更
  154. event(new PetUpdateEvent(
  155. $pet->user_id,
  156. $pet->id
  157. ));
  158. Log::info('宠物升级成功', [
  159. 'pet_id' => $pet->id,
  160. 'old_level' => $oldLevel,
  161. 'new_level' => $pet->level,
  162. 'unlocked_skills' => $unlockedSkills
  163. ]);
  164. }
  165. return Res::success('');
  166. }
  167. /**
  168. * 宠物喂养
  169. *
  170. * @param int $petId 宠物ID
  171. * @param int $itemId 物品ID(狗粮)
  172. * @param int $amount 数量
  173. * @return array 喂养结果
  174. * @throws Exception
  175. */
  176. public function feedPet(int $petId, int $itemId, int $amount): array
  177. {
  178. // 获取宠物信息
  179. /**
  180. * @var PetUser $pet
  181. */
  182. $pet = PetUser::findOrFail($petId);
  183. // 获取物品信息
  184. /**
  185. * @var ItemDto $item
  186. */
  187. $item = ItemService::getItemInfo($itemId);
  188. if (!$item) {
  189. throw new LogicException("物品不存在");
  190. }
  191. // 消耗物品
  192. $consumeResult = ItemService::consumeItem(
  193. $pet->user_id,
  194. $itemId,
  195. null,
  196. $amount,
  197. [
  198. 'source_type' => 'pet_feed',
  199. 'source_id' => $petId,
  200. 'details' => [ 'pet_id' => $petId ]
  201. ]
  202. );
  203. if (!$consumeResult['success']) {
  204. throw new LogicException("物品消耗失败: " . ($consumeResult['message'] ?? '未知错误'));
  205. }
  206. // 计算获得的经验值和体力
  207. $expGained = ($item->numericAttributes['pet_exp'] ?? 0) * $amount;
  208. $staminaGained = ($item->numericAttributes['pet_power'] ?? 0) * $amount;
  209. if (!$expGained && !$staminaGained) {
  210. throw new LogicException('错误的参数');
  211. }
  212. // 增加经验值
  213. $pet->experience += $expGained;
  214. // 更新体力值,确保不超过上限
  215. $pet->stamina = min($pet->max_stamina, $pet->stamina + $staminaGained);
  216. $pet->save();
  217. // 喂养完成后恢复正常状态
  218. // $pet->refresh();
  219. // $pet->status = PetStatus::NORMAL;
  220. $pet->save();
  221. // 检查升级
  222. $this->check_uplevel($pet);
  223. // 如果有经验增加,触发宠物经验增加事件
  224. if ($expGained > 0) {
  225. $petExpEvent = new PetExpGainedEvent(
  226. $pet->user_id,
  227. $pet->id,
  228. $expGained,
  229. 'pet_feed',
  230. $itemId
  231. );
  232. // 异步事件处理(放入队列)
  233. event($petExpEvent);
  234. // 同步任务进度更新(立即执行,确保响应中包含最新进度)
  235. \App\Module\Task\Listeners\PetExpGainedListener::handleSync($petExpEvent);
  236. }
  237. // 创建旧状态数据
  238. $oldStatusData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
  239. $oldStatusData->id = $pet->id;
  240. $oldStatusData->status = PetStatus::FEEDING->value;
  241. // 创建新状态数据
  242. $newStatusData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
  243. $newStatusData->id = $pet->id;
  244. $newStatusData->status = PetStatus::NORMAL->value;
  245. // 创建完整的宠物数据
  246. $petData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
  247. $petData->id = $pet->id;
  248. $petData->name = $pet->name;
  249. $petData->level = $pet->level;
  250. $petData->power = $pet->stamina;
  251. $petData->exp = $pet->experience;
  252. // 触发宠物状态变更事件
  253. event(new PetStatusChangedEvent(
  254. $pet->user_id,
  255. $pet->id,
  256. $oldStatusData,
  257. $newStatusData,
  258. 'pet_feed_complete',
  259. $petData
  260. ));
  261. Log::info('宠物喂养成功', [
  262. 'pet_id' => $petId,
  263. 'item_id' => $itemId,
  264. 'amount' => $amount,
  265. 'exp_gained' => $expGained,
  266. 'stamina_gained' => $staminaGained,
  267. ]);
  268. return [
  269. 'exp_gained' => $expGained,
  270. 'stamina_gained' => $staminaGained,
  271. ];
  272. }
  273. /**
  274. * 增加宠物经验值
  275. *
  276. * @param int $petId 宠物ID
  277. * @param int $expAmount 经验值数量
  278. * @return bool 是否触发升级
  279. */
  280. protected function check_uplevel(PetUser $pet): Res
  281. {
  282. if ($pet->max_experience === 0) {
  283. return Res::error('最高等级,无法升级');
  284. }
  285. if ($pet->experience >= $pet->max_experience) {
  286. return $this->levelUpPet($pet);
  287. }
  288. return Res::error('经验不足');
  289. }
  290. /**
  291. * 增加宠物体力
  292. *
  293. * @param int $petId 宠物ID
  294. * @param int $staminaAmount 体力数量
  295. * @return int 实际增加的体力值
  296. */
  297. protected function addStamina(PetUser $pet, int $staminaAmount): int
  298. {
  299. // 使用模型的访问器获取最大体力值
  300. $maxStamina = $pet->max_stamina;
  301. // 计算实际增加的体力值
  302. $oldStamina = $pet->stamina;
  303. $newStamina = min($maxStamina, $oldStamina + $staminaAmount);
  304. $actualGained = $newStamina - $oldStamina;
  305. return $actualGained;
  306. }
  307. /**
  308. * 增加宠物经验值(用于奖励系统)
  309. *
  310. * @param int $petId 宠物ID
  311. * @param int $expAmount 经验值数量
  312. * @param string $sourceType 经验来源类型
  313. * @param int|null $sourceId 经验来源ID
  314. * @return bool 是否触发升级
  315. * @throws Exception
  316. */
  317. public function addExperienceReward(int $petId, int $expAmount, string $sourceType = 'reward', ?int $sourceId = null): bool
  318. {
  319. // 获取宠物信息
  320. $pet = PetUser::findOrFail($petId);
  321. // 验证经验值
  322. if ($expAmount <= 0) {
  323. throw new Exception('经验值必须大于0');
  324. }
  325. // 增加经验值
  326. $pet->experience += $expAmount;
  327. $pet->save();
  328. // 检查升级
  329. $levelUpResult = $this->check_uplevel($pet);
  330. // 触发宠物经验增加事件
  331. event(new PetExpGainedEvent(
  332. $pet->user_id,
  333. $pet->id,
  334. $expAmount,
  335. $sourceType,
  336. $sourceId
  337. ));
  338. Log::info('宠物经验奖励增加', [
  339. 'pet_id' => $petId,
  340. 'user_id' => $pet->user_id,
  341. 'exp_gained' => $expAmount,
  342. 'new_experience' => $pet->experience,
  343. 'source_type' => $sourceType,
  344. 'source_id' => $sourceId,
  345. 'level_up' => $levelUpResult->success
  346. ]);
  347. return $levelUpResult->success;
  348. }
  349. /**
  350. * 使用宠物技能
  351. *
  352. * @param int $petId 宠物ID
  353. * @param int $skillId 技能ID
  354. * @param array $params 技能参数
  355. * @return array 技能使用结果
  356. * @throws Exception
  357. */
  358. public function useSkill(int $petId, int $skillId, array $params = []): array
  359. {
  360. // 获取宠物信息
  361. $pet = PetUser::findOrFail($petId);
  362. // 获取技能信息
  363. $skill = PetSkill::findOrFail($skillId);
  364. // 检查技能冷却时间
  365. $lastUsed = PetSkillLog::where('pet_id', $petId)
  366. ->where('skill_id', $skillId)
  367. ->orderBy('used_at', 'desc')
  368. ->first();
  369. if ($lastUsed) {
  370. $cooldownSeconds = $skill->cool_down;
  371. $now = now();
  372. $lastUsedTime = $lastUsed->used_at;
  373. // 确保时间计算的正确性
  374. if ($lastUsedTime instanceof \Carbon\Carbon) {
  375. $secondsSinceLastUse = $now->diffInSeconds($lastUsedTime, false);
  376. } else {
  377. // 如果不是Carbon对象,尝试解析
  378. $lastUsedTime = \Carbon\Carbon::parse($lastUsedTime);
  379. $secondsSinceLastUse = $now->diffInSeconds($lastUsedTime, false);
  380. }
  381. // 如果secondsSinceLastUse为负数,说明lastUsed时间在未来,这是异常情况
  382. if ($secondsSinceLastUse < 0) {
  383. Log::warning('检测到异常的技能使用时间', [
  384. 'pet_id' => $petId,
  385. 'skill_id' => $skillId,
  386. 'last_used_at' => $lastUsedTime->toDateTimeString(),
  387. 'current_time' => $now->toDateTimeString(),
  388. 'seconds_diff' => $secondsSinceLastUse
  389. ]);
  390. // 异常情况下,重置为0,允许技能使用
  391. $secondsSinceLastUse = 0;
  392. }
  393. if ($secondsSinceLastUse < $cooldownSeconds) {
  394. $remainingCooldown = $cooldownSeconds - $secondsSinceLastUse;
  395. // 记录详细的冷却信息用于调试
  396. Log::info('技能冷却检查', [
  397. 'pet_id' => $petId,
  398. 'skill_id' => $skillId,
  399. 'cooldown_seconds' => $cooldownSeconds,
  400. 'seconds_since_last_use' => $secondsSinceLastUse,
  401. 'remaining_cooldown' => $remainingCooldown,
  402. 'last_used_at' => $lastUsedTime->toDateTimeString(),
  403. 'current_time' => $now->toDateTimeString()
  404. ]);
  405. throw new Exception("技能冷却中,还需等待 {$remainingCooldown} 秒");
  406. }
  407. }
  408. // 检查体力是否足够
  409. if ($pet->stamina < $skill->stamina_cost) {
  410. throw new Exception("体力不足,无法使用技能");
  411. }
  412. // 先执行技能效果,确保技能能够成功激活
  413. $effectResult = $this->executeSkillEffect($pet, $skill, $params);
  414. // 检查技能效果是否成功
  415. if (isset($effectResult['success']) && $effectResult['success'] === false) {
  416. // 技能效果执行失败,记录失败日志但不消耗体力,不进入冷却
  417. Log::warning('宠物技能使用失败', [
  418. 'pet_id' => $petId,
  419. 'skill_id' => $skillId,
  420. 'params' => $params,
  421. 'effect_result' => $effectResult,
  422. 'reason' => $effectResult['message'] ?? '技能使用失败'
  423. ]);
  424. throw new Exception($effectResult['message'] ?? '技能使用失败');
  425. }
  426. // 技能效果成功,消耗体力
  427. $pet->stamina -= $skill->stamina_cost;
  428. $pet->save();
  429. // 记录技能使用日志(只有成功时才记录)
  430. $skillLog = PetSkillLog::create([
  431. 'pet_id' => $petId,
  432. 'skill_id' => $skillId,
  433. 'used_at' => now(),
  434. 'effect_result' => json_encode($effectResult)
  435. ]);
  436. // 触发宠物技能使用事件
  437. event(new PetSkillUsedEvent(
  438. $pet->user_id,
  439. $pet->id,
  440. $skillId,
  441. $params
  442. ));
  443. Log::info('宠物技能使用成功', [
  444. 'pet_id' => $petId,
  445. 'skill_id' => $skillId,
  446. 'params' => $params,
  447. 'effect_result' => $effectResult
  448. ]);
  449. return [
  450. 'effect_result' => $effectResult
  451. ];
  452. }
  453. /**
  454. * 执行技能效果
  455. *
  456. * @param PetUser $pet 宠物对象
  457. * @param PetSkill $skill 技能对象
  458. * @param array $params 技能参数
  459. * @return array 技能效果结果
  460. */
  461. protected function executeSkillEffect(PetUser $pet, PetSkill $skill, array $params): array
  462. {
  463. // 根据技能名称执行不同的效果
  464. switch ($skill->skill_name) {
  465. case \App\Module\Pet\Enums\PET_SKILL_NAME::AUTO_HARVESTING->value:
  466. return $this->activateAutoHarvestSkill($pet, $skill, $params);
  467. case \App\Module\Pet\Enums\PET_SKILL_NAME::AUTO_PLANTING->value:
  468. return $this->activateAutoPlantSkill($pet, $skill, $params);
  469. case \App\Module\Pet\Enums\PET_SKILL_NAME::AUTO_WEEDING->value:
  470. return $this->activateAutoWeedingSkill($pet, $skill, $params);
  471. case \App\Module\Pet\Enums\PET_SKILL_NAME::AUTO_WATERING->value:
  472. return $this->activateAutoWateringSkill($pet, $skill, $params);
  473. case \App\Module\Pet\Enums\PET_SKILL_NAME::AUTO_PEST_CONTROL->value:
  474. return $this->activateAutoPestControlSkill($pet, $skill, $params);
  475. case \App\Module\Pet\Enums\PET_SKILL_NAME::AUTO_FERTILIZING->value:
  476. return $this->activateAutoFertilizingSkill($pet, $skill, $params);
  477. default:
  478. return [
  479. 'success' => false,
  480. 'message' => '未知技能效果'
  481. ];
  482. }
  483. }
  484. /**
  485. * 激活自动收菜技能
  486. *
  487. * @param PetUser $pet 宠物对象
  488. * @param PetSkill $skill 技能对象
  489. * @param array $params 技能参数
  490. * @return array 激活结果
  491. */
  492. protected function activateAutoHarvestSkill(PetUser $pet, PetSkill $skill, array $params): array
  493. {
  494. // 检查是否已有相同技能在激活中
  495. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  496. ->where('skill_name', $skill->skill_name)
  497. ->where('status', 'active')
  498. ->where('end_time', '>', now())
  499. ->first();
  500. if ($existingActiveSkill) {
  501. return [
  502. 'success' => false,
  503. 'message' => '该技能已经在激活中,无法重复激活'
  504. ];
  505. }
  506. // 技能持续时间,
  507. $duration = $params['duration'] ?? $skill->duration_time; // 2小时
  508. $endTime = now()->addSeconds($duration);
  509. // 创建技能激活记录
  510. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  511. 'pet_id' => $pet->id,
  512. 'skill_id' => $skill->id,
  513. 'skill_name' => $skill->skill_name,
  514. 'start_time' => now(),
  515. 'end_time' => $endTime,
  516. 'status' => 'active',
  517. 'config' => json_encode([
  518. 'auto_harvest' => true,
  519. 'check_interval' => self::SKILL_CHECK_INTERVAL,
  520. // 每58秒检查一次
  521. 'last_check_time' => now()->toDateTimeString()
  522. ])
  523. ]);
  524. Log::info('自动收菜技能激活成功', [
  525. 'pet_id' => $pet->id,
  526. 'skill_id' => $skill->id,
  527. 'duration' => $duration,
  528. 'end_time' => $endTime->toDateTimeString(),
  529. 'active_skill_id' => $activeSkill->id
  530. ]);
  531. return [
  532. 'success' => true,
  533. 'skill_type' => 'auto_harvest',
  534. 'duration' => $duration,
  535. 'end_time' => $endTime->toDateTimeString(),
  536. 'message' => "自动收菜技能已激活,持续时间:{$duration}秒"
  537. ];
  538. }
  539. /**
  540. * 激活自动播种技能
  541. *
  542. * @param PetUser $pet 宠物对象
  543. * @param PetSkill $skill 技能对象
  544. * @param array $params 技能参数
  545. * @return array 激活结果
  546. */
  547. protected function activateAutoPlantSkill(PetUser $pet, PetSkill $skill, array $params): array
  548. {
  549. // 检查是否已有相同技能在激活中
  550. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  551. ->where('skill_name', $skill->skill_name)
  552. ->where('status', 'active')
  553. ->where('end_time', '>', now())
  554. ->first();
  555. if ($existingActiveSkill) {
  556. return [
  557. 'success' => false,
  558. 'message' => '该技能已经在激活中,无法重复激活'
  559. ];
  560. }
  561. // 技能持续时间(默认4小时)
  562. $duration = $params['duration'] ?? $skill->duration_time; // 2小时
  563. $endTime = now()->addSeconds($duration);
  564. // 创建技能激活记录
  565. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  566. 'pet_id' => $pet->id,
  567. 'skill_id' => $skill->id,
  568. 'skill_name' => $skill->skill_name,
  569. 'start_time' => now(),
  570. 'end_time' => $endTime,
  571. 'status' => 'active',
  572. 'config' => json_encode([
  573. 'auto_plant' => true,
  574. 'check_interval' => self::SKILL_CHECK_INTERVAL,
  575. // 每58秒检查一次
  576. 'last_check_time' => now()->toDateTimeString(),
  577. 'preferred_seeds' => $params['preferred_seeds'] ?? []
  578. // 优先使用的种子ID列表
  579. ])
  580. ]);
  581. Log::info('自动播种技能激活成功', [
  582. 'pet_id' => $pet->id,
  583. 'skill_id' => $skill->id,
  584. 'duration' => $duration,
  585. 'end_time' => $endTime->toDateTimeString(),
  586. 'active_skill_id' => $activeSkill->id
  587. ]);
  588. return [
  589. 'success' => true,
  590. 'skill_type' => 'auto_plant',
  591. 'duration' => $duration,
  592. 'end_time' => $endTime->toDateTimeString(),
  593. 'message' => "自动播种技能已激活,持续时间:{$duration}秒"
  594. ];
  595. }
  596. /**
  597. * 激活灾害防护技能
  598. *
  599. * @param PetUser $pet 宠物对象
  600. * @param PetSkill $skill 技能对象
  601. * @param array $params 技能参数
  602. * @return array 激活结果
  603. */
  604. protected function activateDisasterProtectionSkill(PetUser $pet, PetSkill $skill, array $params): array
  605. {
  606. // 检查是否已有相同技能在激活中
  607. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  608. ->where('skill_name', $skill->skill_name)
  609. ->where('status', 'active')
  610. ->where('end_time', '>', now())
  611. ->first();
  612. if ($existingActiveSkill) {
  613. return [
  614. 'success' => false,
  615. 'message' => '该技能已经在激活中,无法重复激活'
  616. ];
  617. }
  618. // 技能持续时间(默认6小时)
  619. $duration = $params['duration'] ?? 21600; // 6小时
  620. $endTime = now()->addSeconds($duration);
  621. // 创建技能激活记录
  622. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  623. 'pet_id' => $pet->id,
  624. 'skill_id' => $skill->id,
  625. 'skill_name' => $skill->skill_name,
  626. 'start_time' => now(),
  627. 'end_time' => $endTime,
  628. 'status' => 'active',
  629. 'config' => json_encode([
  630. 'disaster_protection' => true,
  631. 'protected_types' => $params['disaster_types'] ?? [ 'all' ],
  632. // 防护的灾害类型
  633. 'check_interval' => self::SKILL_CHECK_INTERVAL,
  634. // 每58秒检查一次
  635. 'last_check_time' => now()->toDateTimeString()
  636. ])
  637. ]);
  638. Log::info('灾害防护技能激活成功', [
  639. 'pet_id' => $pet->id,
  640. 'skill_id' => $skill->id,
  641. 'duration' => $duration,
  642. 'end_time' => $endTime->toDateTimeString(),
  643. 'active_skill_id' => $activeSkill->id
  644. ]);
  645. return [
  646. 'success' => true,
  647. 'skill_type' => 'disaster_protection',
  648. 'duration' => $duration,
  649. 'end_time' => $endTime->toDateTimeString(),
  650. 'message' => "灾害防护技能已激活,持续时间:{$duration}秒"
  651. ];
  652. }
  653. /**
  654. * 变更宠物状态
  655. *
  656. * @param int $petId 宠物ID
  657. * @param PetStatus $status 新状态
  658. * @param string $reason 变更原因
  659. * @return bool 是否变更成功
  660. */
  661. public function changeStatus(int $petId, PetStatus $status, string $reason = ''): bool
  662. {
  663. // 获取宠物信息
  664. $pet = PetUser::findOrFail($petId);
  665. // 记录旧状态
  666. $oldStatus = $pet->status;
  667. // 如果状态相同,则不需要变更
  668. if ($oldStatus === $status) {
  669. return true;
  670. }
  671. // 更新状态
  672. $pet->status = $status;
  673. $pet->save();
  674. // 创建旧状态数据
  675. $oldStatusData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
  676. $oldStatusData->id = $pet->id;
  677. $oldStatusData->status = $oldStatus->value;
  678. // 创建新状态数据
  679. $newStatusData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
  680. $newStatusData->id = $pet->id;
  681. $newStatusData->status = $status->value;
  682. // 创建完整的宠物数据
  683. $petData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
  684. $petData->id = $pet->id;
  685. $petData->name = $pet->name;
  686. $petData->typeId = $pet->type_id;
  687. $petData->level = $pet->level;
  688. $petData->status = $status->value;
  689. // 触发宠物状态变更事件
  690. event(new PetStatusChangedEvent(
  691. $pet->user_id,
  692. $pet->id,
  693. $oldStatusData,
  694. $newStatusData,
  695. $reason,
  696. $petData
  697. ));
  698. Log::info('宠物状态变更成功', [
  699. 'pet_id' => $petId,
  700. 'old_status' => $oldStatus->value,
  701. 'new_status' => $status->value,
  702. 'reason' => $reason
  703. ]);
  704. return true;
  705. }
  706. /**
  707. * 恢复宠物体力
  708. *
  709. * @param int $petId 宠物ID
  710. * @param int $minutes 经过的分钟数
  711. * @return int 恢复的体力值
  712. */
  713. public function recoverStamina(int $petId, int $minutes): int
  714. {
  715. // 获取宠物信息
  716. $pet = PetUser::findOrFail($petId);
  717. // 使用模型的访问器获取最大体力值
  718. $maxStamina = $pet->max_stamina;
  719. // 获取宠物等级配置中的恢复速度
  720. $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
  721. $recoveryRate = $levelConfig ? ($levelConfig->numeric_attributes->stamina_recovery ?? 5) : 5;
  722. // 计算恢复的体力值
  723. $recoveryAmount = $recoveryRate * $minutes;
  724. $oldStamina = $pet->stamina;
  725. $newStamina = min($maxStamina, $oldStamina + $recoveryAmount);
  726. $actualRecovered = $newStamina - $oldStamina;
  727. // 更新体力值
  728. if ($actualRecovered > 0) {
  729. $pet->stamina = $newStamina;
  730. $pet->save();
  731. Log::info('宠物体力恢复成功', [
  732. 'pet_id' => $petId,
  733. 'minutes' => $minutes,
  734. 'recovery_rate' => $recoveryRate,
  735. 'old_stamina' => $oldStamina,
  736. 'new_stamina' => $newStamina,
  737. 'actual_recovered' => $actualRecovered
  738. ]);
  739. }
  740. return $actualRecovered;
  741. }
  742. /**
  743. * 计算宠物战力
  744. *
  745. * @param int $petId 宠物ID
  746. * @return int 战力值
  747. */
  748. public function calculatePower(int $petId): int
  749. {
  750. // 获取宠物信息
  751. $pet = PetUser::findOrFail($petId);
  752. // 获取宠物等级配置
  753. $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
  754. // 基础战力
  755. $basePower = $levelConfig ? ($levelConfig->numeric_attributes->base_power ?? 100) : 100;
  756. // 计算最终战力
  757. $power = $basePower;
  758. return (int)$power;
  759. }
  760. /**
  761. * 激活自动除草技能
  762. *
  763. * @param PetUser $pet 宠物对象
  764. * @param PetSkill $skill 技能对象
  765. * @param array $params 技能参数
  766. * @return array 激活结果
  767. */
  768. protected function activateAutoWeedingSkill(PetUser $pet, PetSkill $skill, array $params): array
  769. {
  770. // 检查是否已有相同技能在激活中
  771. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  772. ->where('skill_name', $skill->skill_name)
  773. ->where('status', 'active')
  774. ->where('end_time', '>', now())
  775. ->first();
  776. if ($existingActiveSkill) {
  777. return [
  778. 'success' => false,
  779. 'message' => '该技能已经在激活中,无法重复激活'
  780. ];
  781. }
  782. // 技能持续时间(默认3小时)
  783. $duration = $params['duration'] ?? $skill->duration_time; // 2小时
  784. $endTime = now()->addSeconds($duration);
  785. // 创建技能激活记录
  786. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  787. 'pet_id' => $pet->id,
  788. 'skill_id' => $skill->id,
  789. 'skill_name' => $skill->skill_name,
  790. 'start_time' => now(),
  791. 'end_time' => $endTime,
  792. 'status' => 'active',
  793. 'config' => json_encode([
  794. 'auto_weeding' => true,
  795. 'disaster_type' => \App\Module\Farm\Enums\DISASTER_TYPE::WEED->value,
  796. // 专门处理杂草灾害
  797. 'check_interval' => self::SKILL_CHECK_INTERVAL,
  798. 'last_check_time' => now()->toDateTimeString(),
  799. 'auto_use_items' => $params['auto_use_items'] ?? true
  800. // 是否自动使用除草道具
  801. ])
  802. ]);
  803. Log::info('自动除草技能激活成功', [
  804. 'pet_id' => $pet->id,
  805. 'skill_id' => $skill->id,
  806. 'duration' => $duration,
  807. 'end_time' => $endTime->toDateTimeString(),
  808. 'active_skill_id' => $activeSkill->id
  809. ]);
  810. return [
  811. 'success' => true,
  812. 'skill_type' => 'auto_weeding',
  813. 'duration' => $duration,
  814. 'end_time' => $endTime->toDateTimeString(),
  815. 'message' => "自动除草技能已激活,持续时间:{$duration}秒"
  816. ];
  817. }
  818. /**
  819. * 激活自动浇水技能
  820. *
  821. * @param PetUser $pet 宠物对象
  822. * @param PetSkill $skill 技能对象
  823. * @param array $params 技能参数
  824. * @return array 激活结果
  825. */
  826. protected function activateAutoWateringSkill(PetUser $pet, PetSkill $skill, array $params): array
  827. {
  828. // 检查是否已有相同技能在激活中
  829. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  830. ->where('skill_name', $skill->skill_name)
  831. ->where('status', 'active')
  832. ->where('end_time', '>', now())
  833. ->first();
  834. if ($existingActiveSkill) {
  835. return [
  836. 'success' => false,
  837. 'message' => '该技能已经在激活中,无法重复激活'
  838. ];
  839. }
  840. // 技能持续时间(默认4小时)
  841. $duration = $params['duration'] ?? $skill->duration_time;
  842. $endTime = now()->addSeconds($duration);
  843. // 创建技能激活记录
  844. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  845. 'pet_id' => $pet->id,
  846. 'skill_id' => $skill->id,
  847. 'skill_name' => $skill->skill_name,
  848. 'start_time' => now(),
  849. 'end_time' => $endTime,
  850. 'status' => 'active',
  851. 'config' => json_encode([
  852. 'auto_watering' => true,
  853. 'disaster_type' => \App\Module\Farm\Enums\DISASTER_TYPE::DROUGHT->value,
  854. // 专门处理干旱灾害
  855. 'check_interval' => self::SKILL_CHECK_INTERVAL,
  856. // 每58秒检查一次
  857. 'last_check_time' => now()->toDateTimeString(),
  858. 'auto_use_items' => $params['auto_use_items'] ?? true
  859. // 是否自动使用浇水道具
  860. ])
  861. ]);
  862. Log::info('自动浇水技能激活成功', [
  863. 'pet_id' => $pet->id,
  864. 'skill_id' => $skill->id,
  865. 'duration' => $duration,
  866. 'end_time' => $endTime->toDateTimeString(),
  867. 'active_skill_id' => $activeSkill->id
  868. ]);
  869. return [
  870. 'success' => true,
  871. 'skill_type' => 'auto_watering',
  872. 'duration' => $duration,
  873. 'end_time' => $endTime->toDateTimeString(),
  874. 'message' => "自动浇水技能已激活,持续时间:{$duration}秒"
  875. ];
  876. }
  877. /**
  878. * 激活自动杀虫技能
  879. *
  880. * @param PetUser $pet 宠物对象
  881. * @param PetSkill $skill 技能对象
  882. * @param array $params 技能参数
  883. * @return array 激活结果
  884. */
  885. protected function activateAutoPestControlSkill(PetUser $pet, PetSkill $skill, array $params): array
  886. {
  887. // 检查是否已有相同技能在激活中
  888. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  889. ->where('skill_name', $skill->skill_name)
  890. ->where('status', 'active')
  891. ->where('end_time', '>', now())
  892. ->first();
  893. if ($existingActiveSkill) {
  894. return [
  895. 'success' => false,
  896. 'message' => '该技能已经在激活中,无法重复激活'
  897. ];
  898. }
  899. // 技能持续时间(默认3小时)
  900. $duration = $params['duration'] ?? $skill->duration_time; // 2小时
  901. $endTime = now()->addSeconds($duration);
  902. // 创建技能激活记录
  903. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  904. 'pet_id' => $pet->id,
  905. 'skill_id' => $skill->id,
  906. 'skill_name' => $skill->skill_name,
  907. 'start_time' => now(),
  908. 'end_time' => $endTime,
  909. 'status' => 'active',
  910. 'config' => json_encode([
  911. 'auto_pest_control' => true,
  912. 'disaster_type' => \App\Module\Farm\Enums\DISASTER_TYPE::PEST->value,
  913. // 专门处理虫害灾害
  914. 'check_interval' => self::SKILL_CHECK_INTERVAL,
  915. // 每58秒检查一次
  916. 'last_check_time' => now()->toDateTimeString(),
  917. 'auto_use_items' => $params['auto_use_items'] ?? true
  918. // 是否自动使用杀虫道具
  919. ])
  920. ]);
  921. Log::info('自动杀虫技能激活成功', [
  922. 'pet_id' => $pet->id,
  923. 'skill_id' => $skill->id,
  924. 'duration' => $duration,
  925. 'end_time' => $endTime->toDateTimeString(),
  926. 'active_skill_id' => $activeSkill->id
  927. ]);
  928. return [
  929. 'success' => true,
  930. 'skill_type' => 'auto_pest_control',
  931. 'duration' => $duration,
  932. 'end_time' => $endTime->toDateTimeString(),
  933. 'message' => "自动杀虫技能已激活,持续时间:{$duration}秒"
  934. ];
  935. }
  936. /**
  937. * 激活自动施肥技能
  938. *
  939. * @param PetUser $pet 宠物对象
  940. * @param PetSkill $skill 技能对象
  941. * @param array $params 技能参数
  942. * @return array 激活结果
  943. */
  944. protected function activateAutoFertilizingSkill(PetUser $pet, PetSkill $skill, array $params): array
  945. {
  946. // 检查是否已有相同技能在激活中
  947. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  948. ->where('skill_name', $skill->skill_name)
  949. ->where('status', 'active')
  950. ->where('end_time', '>', now())
  951. ->first();
  952. if ($existingActiveSkill) {
  953. return [
  954. 'success' => false,
  955. 'message' => '该技能已经在激活中,无法重复激活'
  956. ];
  957. }
  958. // 技能持续时间(默认2小时)
  959. $duration = $params['duration'] ?? $skill->duration_time;
  960. $endTime = now()->addSeconds($duration);
  961. // 创建技能激活记录
  962. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  963. 'pet_id' => $pet->id,
  964. 'skill_id' => $skill->id,
  965. 'skill_name' => $skill->skill_name,
  966. 'start_time' => now(),
  967. 'end_time' => $endTime,
  968. 'status' => 'active',
  969. 'config' => json_encode([
  970. 'auto_fertilizing' => true,
  971. 'check_interval' => self::SKILL_CHECK_INTERVAL,
  972. // 每58秒检查一次
  973. 'last_check_time' => now()->toDateTimeString(),
  974. 'auto_use_items' => $params['auto_use_items'] ?? true,
  975. // 是否自动使用肥料道具
  976. 'fertilizer_types' => $params['fertilizer_types'] ?? ['fertilizer'],
  977. // 允许使用的肥料类型
  978. ])
  979. ]);
  980. Log::info('自动施肥技能激活成功', [
  981. 'pet_id' => $pet->id,
  982. 'skill_id' => $skill->id,
  983. 'duration' => $duration,
  984. 'end_time' => $endTime->toDateTimeString(),
  985. 'active_skill_id' => $activeSkill->id
  986. ]);
  987. return [
  988. 'success' => true,
  989. 'skill_type' => 'auto_fertilizing',
  990. 'duration' => $duration,
  991. 'end_time' => $endTime->toDateTimeString(),
  992. 'message' => "自动施肥技能已激活,持续时间:{$duration}秒"
  993. ];
  994. }
  995. }