PetLogic.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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. default:
  540. return [
  541. 'success' => false,
  542. 'message' => '未知技能效果'
  543. ];
  544. }
  545. }
  546. /**
  547. * 激活自动收菜技能
  548. *
  549. * @param PetUser $pet 宠物对象
  550. * @param PetSkill $skill 技能对象
  551. * @param array $params 技能参数
  552. * @return array 激活结果
  553. */
  554. protected function activateAutoHarvestSkill(PetUser $pet, PetSkill $skill, array $params): array
  555. {
  556. // 检查是否已有相同技能在激活中
  557. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  558. ->where('skill_name', $skill->skill_name)
  559. ->where('status', 'active')
  560. ->where('end_time', '>', now())
  561. ->first();
  562. if ($existingActiveSkill) {
  563. return [
  564. 'success' => false,
  565. 'message' => '该技能已经在激活中,无法重复激活'
  566. ];
  567. }
  568. // 技能持续时间,
  569. $duration = $params['duration'] ?? $skill->duration_time; // 2小时
  570. $endTime = now()->addSeconds($duration);
  571. // 创建技能激活记录
  572. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  573. 'pet_id' => $pet->id,
  574. 'skill_id' => $skill->id,
  575. 'skill_name' => $skill->skill_name,
  576. 'start_time' => now(),
  577. 'end_time' => $endTime,
  578. 'status' => 'active',
  579. 'config' => json_encode([
  580. 'auto_harvest' => true,
  581. 'check_interval' => 60,
  582. // 每分钟检查一次
  583. 'last_check_time' => now()->toDateTimeString()
  584. ])
  585. ]);
  586. Log::info('自动收菜技能激活成功', [
  587. 'pet_id' => $pet->id,
  588. 'skill_id' => $skill->id,
  589. 'duration' => $duration,
  590. 'end_time' => $endTime->toDateTimeString(),
  591. 'active_skill_id' => $activeSkill->id
  592. ]);
  593. return [
  594. 'success' => true,
  595. 'skill_type' => 'auto_harvest',
  596. 'duration' => $duration,
  597. 'end_time' => $endTime->toDateTimeString(),
  598. 'message' => "自动收菜技能已激活,持续时间:{$duration}秒"
  599. ];
  600. }
  601. /**
  602. * 激活自动播种技能
  603. *
  604. * @param PetUser $pet 宠物对象
  605. * @param PetSkill $skill 技能对象
  606. * @param array $params 技能参数
  607. * @return array 激活结果
  608. */
  609. protected function activateAutoPlantSkill(PetUser $pet, PetSkill $skill, array $params): array
  610. {
  611. // 检查是否已有相同技能在激活中
  612. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  613. ->where('skill_name', $skill->skill_name)
  614. ->where('status', 'active')
  615. ->where('end_time', '>', now())
  616. ->first();
  617. if ($existingActiveSkill) {
  618. return [
  619. 'success' => false,
  620. 'message' => '该技能已经在激活中,无法重复激活'
  621. ];
  622. }
  623. // 技能持续时间(默认4小时)
  624. $duration = $params['duration'] ?? $skill->duration_time; // 2小时
  625. $endTime = now()->addSeconds($duration);
  626. // 创建技能激活记录
  627. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  628. 'pet_id' => $pet->id,
  629. 'skill_id' => $skill->id,
  630. 'skill_name' => $skill->skill_name,
  631. 'start_time' => now(),
  632. 'end_time' => $endTime,
  633. 'status' => 'active',
  634. 'config' => json_encode([
  635. 'auto_plant' => true,
  636. 'check_interval' => 60,
  637. // 每分钟检查一次
  638. 'last_check_time' => now()->toDateTimeString(),
  639. 'preferred_seeds' => $params['preferred_seeds'] ?? []
  640. // 优先使用的种子ID列表
  641. ])
  642. ]);
  643. Log::info('自动播种技能激活成功', [
  644. 'pet_id' => $pet->id,
  645. 'skill_id' => $skill->id,
  646. 'duration' => $duration,
  647. 'end_time' => $endTime->toDateTimeString(),
  648. 'active_skill_id' => $activeSkill->id
  649. ]);
  650. return [
  651. 'success' => true,
  652. 'skill_type' => 'auto_plant',
  653. 'duration' => $duration,
  654. 'end_time' => $endTime->toDateTimeString(),
  655. 'message' => "自动播种技能已激活,持续时间:{$duration}秒"
  656. ];
  657. }
  658. /**
  659. * 激活灾害防护技能
  660. *
  661. * @param PetUser $pet 宠物对象
  662. * @param PetSkill $skill 技能对象
  663. * @param array $params 技能参数
  664. * @return array 激活结果
  665. */
  666. protected function activateDisasterProtectionSkill(PetUser $pet, PetSkill $skill, array $params): array
  667. {
  668. // 检查是否已有相同技能在激活中
  669. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  670. ->where('skill_name', $skill->skill_name)
  671. ->where('status', 'active')
  672. ->where('end_time', '>', now())
  673. ->first();
  674. if ($existingActiveSkill) {
  675. return [
  676. 'success' => false,
  677. 'message' => '该技能已经在激活中,无法重复激活'
  678. ];
  679. }
  680. // 技能持续时间(默认6小时)
  681. $duration = $params['duration'] ?? 21600; // 6小时
  682. $endTime = now()->addSeconds($duration);
  683. // 创建技能激活记录
  684. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  685. 'pet_id' => $pet->id,
  686. 'skill_id' => $skill->id,
  687. 'skill_name' => $skill->skill_name,
  688. 'start_time' => now(),
  689. 'end_time' => $endTime,
  690. 'status' => 'active',
  691. 'config' => json_encode([
  692. 'disaster_protection' => true,
  693. 'protected_types' => $params['disaster_types'] ?? [ 'all' ],
  694. // 防护的灾害类型
  695. 'check_interval' => 300,
  696. // 每5分钟检查一次
  697. 'last_check_time' => now()->toDateTimeString()
  698. ])
  699. ]);
  700. Log::info('灾害防护技能激活成功', [
  701. 'pet_id' => $pet->id,
  702. 'skill_id' => $skill->id,
  703. 'duration' => $duration,
  704. 'end_time' => $endTime->toDateTimeString(),
  705. 'active_skill_id' => $activeSkill->id
  706. ]);
  707. return [
  708. 'success' => true,
  709. 'skill_type' => 'disaster_protection',
  710. 'duration' => $duration,
  711. 'end_time' => $endTime->toDateTimeString(),
  712. 'message' => "灾害防护技能已激活,持续时间:{$duration}秒"
  713. ];
  714. }
  715. /**
  716. * 变更宠物状态
  717. *
  718. * @param int $petId 宠物ID
  719. * @param PetStatus $status 新状态
  720. * @param string $reason 变更原因
  721. * @return bool 是否变更成功
  722. */
  723. public function changeStatus(int $petId, PetStatus $status, string $reason = ''): bool
  724. {
  725. // 获取宠物信息
  726. $pet = PetUser::findOrFail($petId);
  727. // 记录旧状态
  728. $oldStatus = $pet->status;
  729. // 如果状态相同,则不需要变更
  730. if ($oldStatus === $status) {
  731. return true;
  732. }
  733. // 更新状态
  734. $pet->status = $status;
  735. $pet->save();
  736. // 创建旧状态数据
  737. $oldStatusData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
  738. $oldStatusData->id = $pet->id;
  739. $oldStatusData->status = $oldStatus->value;
  740. // 创建新状态数据
  741. $newStatusData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
  742. $newStatusData->id = $pet->id;
  743. $newStatusData->status = $status->value;
  744. // 创建完整的宠物数据
  745. $petData = new \App\Module\Pet\Dtos\DataPetSimpleDto();
  746. $petData->id = $pet->id;
  747. $petData->name = $pet->name;
  748. $petData->typeId = $pet->type_id;
  749. $petData->level = $pet->level;
  750. $petData->grade = $pet->grade->value;
  751. $petData->status = $status->value;
  752. // 触发宠物状态变更事件
  753. event(new PetStatusChangedEvent(
  754. $pet->user_id,
  755. $pet->id,
  756. $oldStatusData,
  757. $newStatusData,
  758. $reason,
  759. $petData
  760. ));
  761. Log::info('宠物状态变更成功', [
  762. 'pet_id' => $petId,
  763. 'old_status' => $oldStatus->value,
  764. 'new_status' => $status->value,
  765. 'reason' => $reason
  766. ]);
  767. return true;
  768. }
  769. /**
  770. * 恢复宠物体力
  771. *
  772. * @param int $petId 宠物ID
  773. * @param int $minutes 经过的分钟数
  774. * @return int 恢复的体力值
  775. */
  776. public function recoverStamina(int $petId, int $minutes): int
  777. {
  778. // 获取宠物信息
  779. $pet = PetUser::findOrFail($petId);
  780. // 获取宠物等级配置
  781. $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
  782. $maxStamina = $levelConfig ? ($levelConfig->numeric_attributes->stamina_max ?? 100) : 100;
  783. $recoveryRate = $levelConfig ? ($levelConfig->numeric_attributes->stamina_recovery ?? 5) : 5;
  784. // 计算恢复的体力值
  785. $recoveryAmount = $recoveryRate * $minutes;
  786. $oldStamina = $pet->stamina;
  787. $newStamina = min($maxStamina, $oldStamina + $recoveryAmount);
  788. $actualRecovered = $newStamina - $oldStamina;
  789. // 更新体力值
  790. if ($actualRecovered > 0) {
  791. $pet->stamina = $newStamina;
  792. $pet->save();
  793. Log::info('宠物体力恢复成功', [
  794. 'pet_id' => $petId,
  795. 'minutes' => $minutes,
  796. 'recovery_rate' => $recoveryRate,
  797. 'old_stamina' => $oldStamina,
  798. 'new_stamina' => $newStamina,
  799. 'actual_recovered' => $actualRecovered
  800. ]);
  801. }
  802. return $actualRecovered;
  803. }
  804. /**
  805. * 计算宠物战力
  806. *
  807. * @param int $petId 宠物ID
  808. * @return int 战力值
  809. */
  810. public function calculatePower(int $petId): int
  811. {
  812. // 获取宠物信息
  813. $pet = PetUser::findOrFail($petId);
  814. // 获取宠物等级配置
  815. $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
  816. // 基础战力
  817. $basePower = $levelConfig ? ($levelConfig->numeric_attributes->base_power ?? 100) : 100;
  818. // 品阶加成
  819. $gradeBonus = config('pet.grade_attribute_bonus.' . $pet->grade, 0);
  820. // 计算最终战力
  821. $power = $basePower * (1 + $gradeBonus);
  822. return (int)$power;
  823. }
  824. /**
  825. * 激活自动除草技能
  826. *
  827. * @param PetUser $pet 宠物对象
  828. * @param PetSkill $skill 技能对象
  829. * @param array $params 技能参数
  830. * @return array 激活结果
  831. */
  832. protected function activateAutoWeedingSkill(PetUser $pet, PetSkill $skill, array $params): array
  833. {
  834. // 检查是否已有相同技能在激活中
  835. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  836. ->where('skill_name', $skill->skill_name)
  837. ->where('status', 'active')
  838. ->where('end_time', '>', now())
  839. ->first();
  840. if ($existingActiveSkill) {
  841. return [
  842. 'success' => false,
  843. 'message' => '该技能已经在激活中,无法重复激活'
  844. ];
  845. }
  846. // 技能持续时间(默认3小时)
  847. $duration = $params['duration'] ?? $skill->duration_time; // 2小时
  848. $endTime = now()->addSeconds($duration);
  849. // 创建技能激活记录
  850. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  851. 'pet_id' => $pet->id,
  852. 'skill_id' => $skill->id,
  853. 'skill_name' => $skill->skill_name,
  854. 'start_time' => now(),
  855. 'end_time' => $endTime,
  856. 'status' => 'active',
  857. 'config' => json_encode([
  858. 'auto_weeding' => true,
  859. 'disaster_type' => \App\Module\Farm\Enums\DISASTER_TYPE::WEED->value,
  860. // 专门处理杂草灾害
  861. 'check_interval' => 300,
  862. 'last_check_time' => now()->toDateTimeString(),
  863. 'auto_use_items' => $params['auto_use_items'] ?? true
  864. // 是否自动使用除草道具
  865. ])
  866. ]);
  867. Log::info('自动除草技能激活成功', [
  868. 'pet_id' => $pet->id,
  869. 'skill_id' => $skill->id,
  870. 'duration' => $duration,
  871. 'end_time' => $endTime->toDateTimeString(),
  872. 'active_skill_id' => $activeSkill->id
  873. ]);
  874. return [
  875. 'success' => true,
  876. 'skill_type' => 'auto_weeding',
  877. 'duration' => $duration,
  878. 'end_time' => $endTime->toDateTimeString(),
  879. 'message' => "自动除草技能已激活,持续时间:{$duration}秒"
  880. ];
  881. }
  882. /**
  883. * 激活自动浇水技能
  884. *
  885. * @param PetUser $pet 宠物对象
  886. * @param PetSkill $skill 技能对象
  887. * @param array $params 技能参数
  888. * @return array 激活结果
  889. */
  890. protected function activateAutoWateringSkill(PetUser $pet, PetSkill $skill, array $params): array
  891. {
  892. // 检查是否已有相同技能在激活中
  893. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  894. ->where('skill_name', $skill->skill_name)
  895. ->where('status', 'active')
  896. ->where('end_time', '>', now())
  897. ->first();
  898. if ($existingActiveSkill) {
  899. return [
  900. 'success' => false,
  901. 'message' => '该技能已经在激活中,无法重复激活'
  902. ];
  903. }
  904. // 技能持续时间(默认4小时)
  905. $duration = $params['duration'] ?? $skill->duration_time;
  906. $endTime = now()->addSeconds($duration);
  907. // 创建技能激活记录
  908. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  909. 'pet_id' => $pet->id,
  910. 'skill_id' => $skill->id,
  911. 'skill_name' => $skill->skill_name,
  912. 'start_time' => now(),
  913. 'end_time' => $endTime,
  914. 'status' => 'active',
  915. 'config' => json_encode([
  916. 'auto_watering' => true,
  917. 'disaster_type' => \App\Module\Farm\Enums\DISASTER_TYPE::DROUGHT->value,
  918. // 专门处理干旱灾害
  919. 'check_interval' => 300,
  920. // 每5分钟检查一次
  921. 'last_check_time' => now()->toDateTimeString(),
  922. 'auto_use_items' => $params['auto_use_items'] ?? true
  923. // 是否自动使用浇水道具
  924. ])
  925. ]);
  926. Log::info('自动浇水技能激活成功', [
  927. 'pet_id' => $pet->id,
  928. 'skill_id' => $skill->id,
  929. 'duration' => $duration,
  930. 'end_time' => $endTime->toDateTimeString(),
  931. 'active_skill_id' => $activeSkill->id
  932. ]);
  933. return [
  934. 'success' => true,
  935. 'skill_type' => 'auto_watering',
  936. 'duration' => $duration,
  937. 'end_time' => $endTime->toDateTimeString(),
  938. 'message' => "自动浇水技能已激活,持续时间:{$duration}秒"
  939. ];
  940. }
  941. /**
  942. * 激活自动杀虫技能
  943. *
  944. * @param PetUser $pet 宠物对象
  945. * @param PetSkill $skill 技能对象
  946. * @param array $params 技能参数
  947. * @return array 激活结果
  948. */
  949. protected function activateAutoPestControlSkill(PetUser $pet, PetSkill $skill, array $params): array
  950. {
  951. // 检查是否已有相同技能在激活中
  952. $existingActiveSkill = \App\Module\Pet\Models\PetActiveSkill::where('pet_id', $pet->id)
  953. ->where('skill_name', $skill->skill_name)
  954. ->where('status', 'active')
  955. ->where('end_time', '>', now())
  956. ->first();
  957. if ($existingActiveSkill) {
  958. return [
  959. 'success' => false,
  960. 'message' => '该技能已经在激活中,无法重复激活'
  961. ];
  962. }
  963. // 技能持续时间(默认3小时)
  964. $duration = $params['duration'] ?? $skill->duration_time; // 2小时
  965. $endTime = now()->addSeconds($duration);
  966. // 创建技能激活记录
  967. $activeSkill = \App\Module\Pet\Models\PetActiveSkill::create([
  968. 'pet_id' => $pet->id,
  969. 'skill_id' => $skill->id,
  970. 'skill_name' => $skill->skill_name,
  971. 'start_time' => now(),
  972. 'end_time' => $endTime,
  973. 'status' => 'active',
  974. 'config' => json_encode([
  975. 'auto_pest_control' => true,
  976. 'disaster_type' => \App\Module\Farm\Enums\DISASTER_TYPE::PEST->value,
  977. // 专门处理虫害灾害
  978. 'check_interval' => 300,
  979. // 每5分钟检查一次
  980. 'last_check_time' => now()->toDateTimeString(),
  981. 'auto_use_items' => $params['auto_use_items'] ?? true
  982. // 是否自动使用杀虫道具
  983. ])
  984. ]);
  985. Log::info('自动杀虫技能激活成功', [
  986. 'pet_id' => $pet->id,
  987. 'skill_id' => $skill->id,
  988. 'duration' => $duration,
  989. 'end_time' => $endTime->toDateTimeString(),
  990. 'active_skill_id' => $activeSkill->id
  991. ]);
  992. return [
  993. 'success' => true,
  994. 'skill_type' => 'auto_pest_control',
  995. 'duration' => $duration,
  996. 'end_time' => $endTime->toDateTimeString(),
  997. 'message' => "自动杀虫技能已激活,持续时间:{$duration}秒"
  998. ];
  999. }
  1000. }