CropLogic.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. <?php
  2. namespace App\Module\Farm\Logics;
  3. use App\Module\Farm\Dtos\CropInfoDto;
  4. use App\Module\Farm\Dtos\HarvestResultDto;
  5. use App\Module\Farm\Enums\GROWTH_STAGE;
  6. use App\Module\Farm\Enums\LAND_STATUS;
  7. use App\Module\Farm\Events\CropGrowthStageChangedEvent;
  8. use App\Module\Farm\Events\CropHarvestedEvent;
  9. use App\Module\Farm\Events\CropPlantedEvent;
  10. use App\Module\Farm\Events\DisasterClearedEvent;
  11. use App\Module\Farm\Models\FarmCrop;
  12. use App\Module\Farm\Models\FarmHarvestLog;
  13. use App\Module\Farm\Models\FarmLand;
  14. use App\Module\Farm\Models\FarmSeed;
  15. use App\Module\Farm\Models\FarmSeedOutput;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Log;
  18. use UCore\Db\Helper;
  19. /**
  20. * 作物管理逻辑
  21. */
  22. class CropLogic
  23. {
  24. /**
  25. * 获取作物信息
  26. *
  27. * @param int $cropId
  28. * @return CropInfoDto|null
  29. */
  30. public function getCropInfo(int $cropId): ?CropInfoDto
  31. {
  32. try {
  33. $crop = FarmCrop::find($cropId);
  34. if (!$crop) {
  35. return null;
  36. }
  37. return CropInfoDto::fromModel($crop);
  38. } catch (\Exception $e) {
  39. Log::error('获取作物信息失败', [
  40. 'crop_id' => $cropId,
  41. 'error' => $e->getMessage(),
  42. 'trace' => $e->getTraceAsString()
  43. ]);
  44. return null;
  45. }
  46. }
  47. /**
  48. * 获取土地上的作物信息
  49. *
  50. * @param int $landId
  51. * @return CropInfoDto|null
  52. */
  53. public function getCropByLandId(int $landId): ?CropInfoDto
  54. {
  55. try {
  56. $crop = FarmCrop::where('land_id', $landId)->first();
  57. if (!$crop) {
  58. return null;
  59. }
  60. return CropInfoDto::fromModel($crop);
  61. } catch (\Exception $e) {
  62. Log::error('获取土地作物信息失败', [
  63. 'land_id' => $landId,
  64. 'error' => $e->getMessage(),
  65. 'trace' => $e->getTraceAsString()
  66. ]);
  67. return null;
  68. }
  69. }
  70. /**
  71. * 种植作物
  72. *
  73. * @param int $userId
  74. * @param int $landId
  75. * @param int $seedId
  76. * @return CropInfoDto|null
  77. */
  78. public function plantCrop(int $userId, int $landId, int $seedId): ?CropInfoDto
  79. {
  80. try {
  81. // 开启事务
  82. DB::beginTransaction();
  83. // 获取土地信息
  84. $land = FarmLand::where('id', $landId)
  85. ->where('user_id', $userId)
  86. ->first();
  87. if (!$land) {
  88. throw new \Exception('土地不存在');
  89. }
  90. // 检查土地状态
  91. if ($land->status !== LAND_STATUS::IDLE->value) {
  92. throw new \Exception('土地状态不允许种植');
  93. }
  94. // 获取种子信息
  95. $seed = FarmSeed::find($seedId);
  96. if (!$seed) {
  97. throw new \Exception('种子不存在');
  98. }
  99. // 创建作物记录
  100. $crop = new FarmCrop();
  101. $crop->land_id = $landId;
  102. $crop->user_id = $userId;
  103. $crop->seed_id = $seedId;
  104. $crop->plant_time = now();
  105. $crop->growth_stage = GROWTH_STAGE::SEED->value;
  106. $crop->stage_start_time = now(); // 设置当前阶段开始时间
  107. $crop->stage_end_time = now()->addSeconds($seed->seed_time);
  108. $crop->disasters = [];
  109. $crop->fertilized = false;
  110. $crop->save();
  111. // 更新土地状态
  112. $land->status = LAND_STATUS::PLANTING->value;
  113. $land->save();
  114. // 提交事务
  115. DB::commit();
  116. // 触发作物种植事件
  117. event(new CropPlantedEvent($userId, $land, $crop));
  118. Log::info('作物种植成功', [
  119. 'user_id' => $userId,
  120. 'land_id' => $landId,
  121. 'seed_id' => $seedId,
  122. 'crop_id' => $crop->id
  123. ]);
  124. return CropInfoDto::fromModel($crop);
  125. } catch (\Exception $e) {
  126. // 回滚事务
  127. DB::rollBack();
  128. Log::error('作物种植失败', [
  129. 'user_id' => $userId,
  130. 'land_id' => $landId,
  131. 'seed_id' => $seedId,
  132. 'error' => $e->getMessage(),
  133. 'trace' => $e->getTraceAsString()
  134. ]);
  135. return null;
  136. }
  137. }
  138. /**
  139. * 收获作物
  140. *
  141. * @param int $userId
  142. * @param int $landId
  143. * @return HarvestResultDto|null
  144. */
  145. public function harvestCrop(int $userId, int $landId): ?HarvestResultDto
  146. {
  147. try {
  148. // 开启事务
  149. DB::beginTransaction();
  150. // 获取土地信息
  151. $land = FarmLand::where('id', $landId)
  152. ->where('user_id', $userId)
  153. ->first();
  154. if (!$land) {
  155. throw new \Exception('土地不存在');
  156. }
  157. // 检查土地状态
  158. if ($land->status !== LAND_STATUS::HARVESTABLE->value) {
  159. throw new \Exception('土地状态不允许收获');
  160. }
  161. // 获取作物信息
  162. $crop = FarmCrop::where('land_id', $landId)->first();
  163. if (!$crop) {
  164. throw new \Exception('作物不存在');
  165. }
  166. // 检查作物生长阶段
  167. if ($crop->growth_stage !== GROWTH_STAGE::MATURE->value) {
  168. throw new \Exception('作物未成熟,不能收获');
  169. }
  170. // 获取种子信息
  171. $seed = $crop->seed;
  172. if (!$seed) {
  173. throw new \Exception('种子信息不存在');
  174. }
  175. // 随机选择产出物品
  176. $outputInfo = $this->getRandomOutput($seed->id);
  177. $outputItemId = $outputInfo['item_id'];
  178. $outputAmount = mt_rand($outputInfo['min_amount'], $outputInfo['max_amount']);
  179. // 创建收获记录
  180. $harvestLog = new FarmHarvestLog();
  181. $harvestLog->user_id = $userId;
  182. $harvestLog->land_id = $landId;
  183. $harvestLog->crop_id = $crop->id;
  184. $harvestLog->seed_id = $seed->id;
  185. $harvestLog->output_amount = $outputAmount;
  186. $harvestLog->harvest_time = now();
  187. $harvestLog->created_at = now();
  188. $harvestLog->save();
  189. // 删除作物记录
  190. $crop->delete();
  191. // 更新土地状态
  192. $land->status = LAND_STATUS::IDLE;
  193. $land->save();
  194. // 提交事务
  195. DB::commit();
  196. // 触发作物收获事件
  197. event(new CropHarvestedEvent($userId, $land, $crop, $harvestLog, $outputItemId, $outputAmount));
  198. Log::info('作物收获成功', [
  199. 'user_id' => $userId,
  200. 'land_id' => $landId,
  201. 'crop_id' => $crop->id,
  202. 'seed_id' => $seed->id,
  203. 'output_item_id' => $outputItemId,
  204. 'output_amount' => $outputAmount,
  205. 'harvest_log_id' => $harvestLog->id
  206. ]);
  207. return HarvestResultDto::fromModel($harvestLog, $outputItemId);
  208. } catch (\Exception $e) {
  209. // 回滚事务
  210. DB::rollBack();
  211. Log::error('作物收获失败', [
  212. 'user_id' => $userId,
  213. 'land_id' => $landId,
  214. 'error' => $e->getMessage(),
  215. 'trace' => $e->getTraceAsString()
  216. ]);
  217. return null;
  218. }
  219. }
  220. /**
  221. * 使用化肥
  222. *
  223. * @param int $userId
  224. * @param int $landId
  225. * @return bool
  226. */
  227. public function useFertilizer(int $userId, int $landId,int $crop_growth_time): bool
  228. {
  229. try {
  230. Helper::check_tr();
  231. // 获取土地信息
  232. /**
  233. * @var FarmLand $land
  234. */
  235. $land = FarmLand::where('id', $landId)
  236. ->where('user_id', $userId)
  237. ->first();
  238. if (!$land) {
  239. throw new \Exception('土地不存在');
  240. }
  241. // 检查土地状态
  242. if ($land->status !== LAND_STATUS::PLANTING->valueInt()) {
  243. throw new \Exception('土地状态不允许使用化肥');
  244. }
  245. // 获取作物信息
  246. $crop = FarmCrop::where('land_id', $landId)->first();
  247. if (!$crop) {
  248. throw new \Exception('作物不存在');
  249. }
  250. // 检查作物生长阶段
  251. if (!GROWTH_STAGE::canUseFertilizer($crop->growth_stage)) {
  252. throw new \Exception('当前生长阶段不能使用化肥');
  253. }
  254. // 检查是否已经使用过化肥
  255. if ($crop->fertilized) {
  256. throw new \Exception('当前阶段已经使用过化肥');
  257. }
  258. // 更新作物信息
  259. $crop->fertilized = true;
  260. // 根据 crop_growth_time 参数减少当前阶段时间
  261. if ($crop->stage_end_time) {
  262. $currentTime = now();
  263. $endTime = $crop->stage_end_time;
  264. $remainingTime = $currentTime->diffInSeconds($endTime, false);
  265. if ($remainingTime > 0) {
  266. // 确保减少的时间不超过剩余时间
  267. $reducedTime = min($crop_growth_time, $remainingTime);
  268. $crop->stage_end_time = $endTime->subSeconds($reducedTime);
  269. Log::info('化肥减少生长时间', [
  270. 'crop_id' => $crop->id,
  271. 'reduced_time' => $reducedTime,
  272. 'original_end_time' => $endTime->toDateTimeString(),
  273. 'new_end_time' => $crop->stage_end_time->toDateTimeString(),
  274. 'stage_start_time' => $crop->stage_start_time->toDateTimeString()
  275. ]);
  276. }
  277. }
  278. $crop->save();
  279. Log::info('使用化肥成功', [
  280. 'user_id' => $userId,
  281. 'land_id' => $landId,
  282. 'crop_id' => $crop->id,
  283. 'growth_stage' => $crop->growth_stage,
  284. 'stage_end_time' => $crop->stage_end_time
  285. ]);
  286. return true;
  287. } catch (\Exception $e) {
  288. Log::error('使用化肥失败', [
  289. 'user_id' => $userId,
  290. 'land_id' => $landId,
  291. 'error' => $e->getMessage(),
  292. 'trace' => $e->getTraceAsString()
  293. ]);
  294. return false;
  295. }
  296. }
  297. /**
  298. * 清理灾害
  299. *
  300. * @param int $userId
  301. * @param int $landId
  302. * @param int $disasterType
  303. * @return bool
  304. */
  305. public function clearDisaster(int $userId, int $landId, int $disasterType): bool
  306. {
  307. try {
  308. // 获取土地信息
  309. $land = FarmLand::where('id', $landId)
  310. ->where('user_id', $userId)
  311. ->first();
  312. if (!$land) {
  313. throw new \Exception('土地不存在');
  314. }
  315. // 检查土地状态
  316. if ($land->status !== LAND_STATUS::DISASTER->value) {
  317. throw new \Exception('土地没有灾害');
  318. }
  319. // 获取作物信息
  320. $crop = FarmCrop::where('land_id', $landId)->first();
  321. if (!$crop) {
  322. throw new \Exception('作物不存在');
  323. }
  324. // 检查灾害是否存在
  325. $disasters = $crop->disasters ?? [];
  326. $disasterIndex = -1;
  327. $disasterInfo = null;
  328. foreach ($disasters as $index => $disaster) {
  329. if (($disaster['type'] ?? 0) == $disasterType && ($disaster['status'] ?? '') === 'active') {
  330. $disasterIndex = $index;
  331. $disasterInfo = $disaster;
  332. break;
  333. }
  334. }
  335. if ($disasterIndex === -1 || !$disasterInfo) {
  336. throw new \Exception('指定类型的灾害不存在');
  337. }
  338. // 更新灾害状态
  339. $disasters[$disasterIndex]['status'] = 'cleared';
  340. $disasters[$disasterIndex]['cleared_at'] = now()->toDateTimeString();
  341. $crop->disasters = $disasters;
  342. // 检查是否还有其他活跃灾害
  343. $hasActiveDisaster = false;
  344. foreach ($disasters as $disaster) {
  345. if (($disaster['status'] ?? '') === 'active') {
  346. $hasActiveDisaster = true;
  347. break;
  348. }
  349. }
  350. // 如果没有其他活跃灾害,更新土地状态
  351. if (!$hasActiveDisaster) {
  352. $land->status = LAND_STATUS::PLANTING->value;
  353. }
  354. // 保存更改
  355. $crop->save();
  356. $land->save();
  357. // 触发灾害清理事件
  358. event(new DisasterClearedEvent($userId, $crop, $disasterType, $disasterInfo));
  359. Log::info('灾害清理成功', [
  360. 'user_id' => $userId,
  361. 'land_id' => $landId,
  362. 'crop_id' => $crop->id,
  363. 'disaster_type' => $disasterType
  364. ]);
  365. return true;
  366. } catch (\Exception $e) {
  367. Log::error('灾害清理失败', [
  368. 'user_id' => $userId,
  369. 'land_id' => $landId,
  370. 'disaster_type' => $disasterType,
  371. 'error' => $e->getMessage(),
  372. 'trace' => $e->getTraceAsString()
  373. ]);
  374. return false;
  375. }
  376. }
  377. /**
  378. * 铲除作物
  379. *
  380. * @param int $userId
  381. * @param int $landId
  382. * @return bool
  383. */
  384. public function removeCrop(int $userId, int $landId): bool
  385. {
  386. try {
  387. // 开启事务
  388. DB::beginTransaction();
  389. // 获取土地信息
  390. $land = FarmLand::where('id', $landId)
  391. ->where('user_id', $userId)
  392. ->first();
  393. if (!$land) {
  394. throw new \Exception('土地不存在');
  395. }
  396. // 检查土地状态
  397. if ($land->status === LAND_STATUS::IDLE->value) {
  398. throw new \Exception('土地上没有作物');
  399. }
  400. // 获取作物信息
  401. $crop = FarmCrop::where('land_id', $landId)->first();
  402. if (!$crop) {
  403. // 如果没有作物但土地状态不是空闲,修正土地状态
  404. $land->status = LAND_STATUS::IDLE->value;
  405. $land->save();
  406. DB::commit();
  407. return true;
  408. }
  409. // 删除作物记录
  410. $crop->delete();
  411. // 更新土地状态
  412. $land->status = LAND_STATUS::IDLE->value;
  413. $land->save();
  414. // 提交事务
  415. DB::commit();
  416. Log::info('铲除作物成功', [
  417. 'user_id' => $userId,
  418. 'land_id' => $landId,
  419. 'crop_id' => $crop->id
  420. ]);
  421. return true;
  422. } catch (\Exception $e) {
  423. // 回滚事务
  424. DB::rollBack();
  425. Log::error('铲除作物失败', [
  426. 'user_id' => $userId,
  427. 'land_id' => $landId,
  428. 'error' => $e->getMessage(),
  429. 'trace' => $e->getTraceAsString()
  430. ]);
  431. return false;
  432. }
  433. }
  434. /**
  435. * 更新作物生长阶段
  436. *
  437. * @param int $cropId
  438. * @return bool
  439. */
  440. public function updateGrowthStage(int $cropId): bool
  441. {
  442. try {
  443. // 获取作物信息
  444. $crop = FarmCrop::find($cropId);
  445. if (!$crop) {
  446. throw new \Exception('作物不存在');
  447. }
  448. // 检查是否需要更新
  449. if (!$crop->stage_end_time || $crop->stage_end_time > now()) {
  450. return false;
  451. }
  452. // 获取当前生长阶段
  453. $oldStage = $crop->growth_stage;
  454. // 计算新的生长阶段
  455. $newStage = $this->calculateNextStage($crop);
  456. // 如果阶段没有变化,不需要更新
  457. if ($newStage === $oldStage) {
  458. return false;
  459. }
  460. // 计算新阶段的结束时间
  461. $stageEndTime = $this->calculateStageEndTime($crop, $newStage);
  462. // 更新作物信息
  463. $crop->growth_stage = $newStage;
  464. $crop->stage_start_time = now(); // 设置新阶段的开始时间
  465. $crop->stage_end_time = $stageEndTime;
  466. $crop->fertilized = false; // 重置施肥状态
  467. $crop->save();
  468. // 触发生长阶段变更事件
  469. event(new CropGrowthStageChangedEvent($crop->user_id, $crop, $oldStage, $newStage));
  470. Log::info('作物生长阶段更新成功', [
  471. 'crop_id' => $cropId,
  472. 'user_id' => $crop->user_id,
  473. 'old_stage' => $oldStage,
  474. 'new_stage' => $newStage,
  475. 'stage_end_time' => $stageEndTime
  476. ]);
  477. return true;
  478. } catch (\Exception $e) {
  479. Log::error('作物生长阶段更新失败', [
  480. 'crop_id' => $cropId,
  481. 'error' => $e->getMessage(),
  482. 'trace' => $e->getTraceAsString()
  483. ]);
  484. return false;
  485. }
  486. }
  487. /**
  488. * 计算下一个生长阶段
  489. *
  490. * @param FarmCrop $crop
  491. * @return int
  492. */
  493. private function calculateNextStage(FarmCrop $crop): int
  494. {
  495. $currentStage = $crop->growth_stage;
  496. // 如果当前是成熟期,且超过一定时间,则进入枯萎期
  497. if ($currentStage === GROWTH_STAGE::MATURE->value) {
  498. // 成熟期持续时间,默认为24小时
  499. $matureDuration = 24 * 60 * 60;
  500. // 如果成熟期已经超过指定时间,则进入枯萎期
  501. if ($crop->stage_end_time && $crop->stage_end_time instanceof \Carbon\Carbon) {
  502. $endTimeMinusDuration = $crop->stage_end_time->copy()->subSeconds($matureDuration);
  503. if (now()->diffInSeconds($endTimeMinusDuration) > $matureDuration) {
  504. return GROWTH_STAGE::WITHERED->value;
  505. }
  506. }
  507. return GROWTH_STAGE::MATURE->value;
  508. }
  509. // 正常阶段递增
  510. return $currentStage + 1;
  511. }
  512. /**
  513. * 计算阶段结束时间
  514. *
  515. * @param FarmCrop $crop
  516. * @param int $stage
  517. * @return \Carbon\Carbon|null
  518. */
  519. private function calculateStageEndTime(FarmCrop $crop, int $stage)
  520. {
  521. $seed = $crop->seed;
  522. if (!$seed) {
  523. return null;
  524. }
  525. $now = now();
  526. switch ($stage) {
  527. case GROWTH_STAGE::SEED->value:
  528. return $now->addSeconds($seed->seed_time);
  529. case GROWTH_STAGE::SPROUT->value:
  530. return $now->addSeconds($seed->sprout_time);
  531. case GROWTH_STAGE::GROWTH->value:
  532. return $now->addSeconds($seed->growth_time);
  533. case GROWTH_STAGE::MATURE->value:
  534. // 成熟期持续24小时后进入枯萎期
  535. return $now->addHours(24);
  536. case GROWTH_STAGE::WITHERED->value:
  537. // 枯萎期没有结束时间
  538. return null;
  539. default:
  540. return null;
  541. }
  542. }
  543. /**
  544. * 获取随机产出
  545. *
  546. * @param int $seedId
  547. * @return array
  548. */
  549. private function getRandomOutput(int $seedId): array
  550. {
  551. // 获取种子的所有产出配置
  552. $outputs = FarmSeedOutput::where('seed_id', $seedId)->get();
  553. if ($outputs->isEmpty()) {
  554. // 如果没有产出配置,使用种子的默认产出
  555. $seed = FarmSeed::find($seedId);
  556. return [
  557. 'item_id' => $seed->item_id,
  558. 'min_amount' => $seed->min_output,
  559. 'max_amount' => $seed->max_output,
  560. ];
  561. }
  562. // 按概率排序
  563. $outputs = $outputs->sortByDesc('probability');
  564. // 获取默认产出
  565. $defaultOutput = $outputs->firstWhere('is_default', true);
  566. // 随机选择产出
  567. $random = mt_rand(1, 100);
  568. $cumulativeProbability = 0;
  569. foreach ($outputs as $output) {
  570. $cumulativeProbability += $output->probability;
  571. if ($random <= $cumulativeProbability) {
  572. return [
  573. 'item_id' => $output->item_id,
  574. 'min_amount' => $output->min_amount,
  575. 'max_amount' => $output->max_amount,
  576. ];
  577. }
  578. }
  579. // 如果随机值超过了所有概率之和,使用默认产出
  580. if ($defaultOutput) {
  581. return [
  582. 'item_id' => $defaultOutput->item_id,
  583. 'min_amount' => $defaultOutput->min_amount,
  584. 'max_amount' => $defaultOutput->max_amount,
  585. ];
  586. }
  587. // 如果没有默认产出,使用第一个产出
  588. $firstOutput = $outputs->first();
  589. return [
  590. 'item_id' => $firstOutput->item_id,
  591. 'min_amount' => $firstOutput->min_amount,
  592. 'max_amount' => $firstOutput->max_amount,
  593. ];
  594. }
  595. }