PetLogic.php 49 KB

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