DisasterLogic.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. <?php
  2. namespace App\Module\Farm\Logics;
  3. use App\Module\Farm\Dtos\DisasterInfoDto;
  4. use App\Module\Farm\Enums\DISASTER_TYPE;
  5. use App\Module\Farm\Enums\GROWTH_STAGE;
  6. use App\Module\Farm\Enums\LAND_STATUS;
  7. use App\Module\Farm\Events\DisasterGeneratedEvent;
  8. use App\Module\Farm\Models\FarmCrop;
  9. use App\Module\Farm\Models\FarmGodBuff;
  10. use App\Module\Farm\Models\FarmLand;
  11. use App\Module\Farm\Models\FarmCropLog;
  12. use App\Module\Farm\Services\DisasterService;
  13. use Illuminate\Support\Collection;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. /**
  17. * 灾害管理逻辑
  18. */
  19. class DisasterLogic
  20. {
  21. /**
  22. * 获取作物的灾害信息
  23. *
  24. * @param int $cropId
  25. * @return Collection
  26. */
  27. public function getCropDisasters(int $cropId): Collection
  28. {
  29. try {
  30. $crop = FarmCrop::find($cropId);
  31. if (!$crop || empty($crop->disasters)) {
  32. return collect();
  33. }
  34. $disasters = collect($crop->disasters);
  35. return $disasters->map(function ($disaster) {
  36. return DisasterInfoDto::fromArray($disaster);
  37. });
  38. } catch (\Exception $e) {
  39. Log::error('获取作物灾害信息失败', [
  40. 'crop_id' => $cropId,
  41. 'error' => $e->getMessage(),
  42. 'trace' => $e->getTraceAsString()
  43. ]);
  44. return collect();
  45. }
  46. }
  47. /**
  48. * 获取作物的活跃灾害
  49. *
  50. * @param int $cropId
  51. * @return Collection
  52. */
  53. public function getActiveDisasters(int $cropId): Collection
  54. {
  55. try {
  56. $crop = FarmCrop::find($cropId);
  57. if (!$crop || empty($crop->disasters)) {
  58. return collect();
  59. }
  60. $disasters = collect($crop->disasters)->filter(function ($disaster) {
  61. return ($disaster['status'] ?? '') === 'active';
  62. });
  63. return $disasters->map(function ($disaster) {
  64. return DisasterInfoDto::fromArray($disaster);
  65. });
  66. } catch (\Exception $e) {
  67. Log::error('获取作物活跃灾害失败', [
  68. 'crop_id' => $cropId,
  69. 'error' => $e->getMessage(),
  70. 'trace' => $e->getTraceAsString()
  71. ]);
  72. return collect();
  73. }
  74. }
  75. /**
  76. * 生成灾害
  77. *
  78. * @param int $cropId
  79. * @return DisasterInfoDto|null
  80. */
  81. public function generateDisaster(int $cropId): ?DisasterInfoDto
  82. {
  83. try {
  84. $crop = FarmCrop::find($cropId);
  85. if (!$crop) {
  86. throw new \Exception('作物不存在');
  87. }
  88. /**
  89. * @var FarmLand $land
  90. */
  91. $land = $crop->land;
  92. if (!$land) {
  93. throw new \Exception('土地不存在');
  94. }
  95. // 只在发芽期、生长期和果实期生成灾害
  96. if (!in_array($crop->growth_stage, [ GROWTH_STAGE::SPROUT, GROWTH_STAGE::GROWTH, GROWTH_STAGE::FRUIT ])) {
  97. return null;
  98. }
  99. // 注意:根据文档,作物灾害和土地无关,不需要检查土地状态
  100. $userId = $crop->user_id;
  101. $seed = $crop->seed;
  102. // 获取种子的灾害抵抗属性
  103. $disasterResistance = $seed->disaster_resistance ?? [];
  104. // 获取土地的灾害抵抗属性(数据库存储百分比,需要除以100转换为小数)
  105. $landDisasterResistance = ($land->landType->disaster_resistance ?? 0) / 100;
  106. // 检查用户是否有有效的神灵加持
  107. $activeBuffs = FarmGodBuff::where('user_id', $userId)
  108. ->where('expire_time', '>', now())
  109. ->pluck('buff_type')
  110. ->toArray();
  111. // 尝试生成灾害(支持多种灾害)
  112. $disasterInfos = $this->tryGenerateDisasterForCrop($crop, $disasterResistance, $landDisasterResistance, $activeBuffs);
  113. if (!empty($disasterInfos)) {
  114. $disasterDtos = $this->applyDisastersToCrop($crop, $disasterInfos);
  115. Log::info('灾害生成成功', [
  116. 'user_id' => $userId,
  117. 'crop_id' => $crop->id,
  118. 'land_id' => $land->id,
  119. 'disaster_count' => count($disasterInfos),
  120. 'disaster_types' => array_column($disasterInfos, 'type')
  121. ]);
  122. return $disasterDtos[0] ?? null; // 返回第一个灾害信息保持兼容性
  123. }
  124. return null;
  125. } catch (\Exception $e) {
  126. \UCore\Helper\Logger::exception('灾害生成失败', $e, [
  127. 'crop_id' => $cropId,
  128. ]);
  129. return null;
  130. }
  131. }
  132. /**
  133. * 尝试为作物生成灾害(支持多种灾害同时发生)
  134. *
  135. * @param FarmCrop $crop
  136. * @param mixed $disasterResistance
  137. * @param float $landDisasterResistance
  138. * @param array $activeBuffs
  139. * @return array 生成的灾害信息数组
  140. */
  141. private function tryGenerateDisasterForCrop(FarmCrop $crop, $disasterResistance, float $landDisasterResistance, array $activeBuffs): array
  142. {
  143. // 灾害类型及其基础概率
  144. $disasterTypes = DisasterService::getRate();
  145. $generatedDisasters = [];
  146. // 对每种灾害类型都进行判定
  147. foreach ($disasterTypes as $disasterType => $baseProb) {
  148. // 计算最终概率,考虑种子抵抗、土地抵抗和神灵加持
  149. $seedResistance = 0;
  150. if ($disasterResistance) {
  151. if (is_object($disasterResistance) && method_exists($disasterResistance, 'getResistance')) {
  152. // 如果是 DisasterResistanceCast 对象(数据库存储百分比,需要除以100转换为小数)
  153. $seedResistance = $disasterResistance->getResistance($disasterType) / 100;
  154. } elseif (is_array($disasterResistance)) {
  155. // 如果是数组格式(数据库存储百分比,需要除以100转换为小数)
  156. $seedResistance = ($disasterResistance[DisasterService::getDisasterKey($disasterType)] ?? 0) / 100;
  157. }
  158. }
  159. $finalProb = $baseProb - $seedResistance - $landDisasterResistance;
  160. // 如果有对应的神灵加持,则不生成该类型的灾害
  161. $buffType = DISASTER_TYPE::getPreventBuffType($disasterType);
  162. $hasGodBuff = $buffType && in_array($buffType, $activeBuffs);
  163. if ($hasGodBuff) {
  164. $finalProb = 0;
  165. }
  166. // 确保概率在有效范围内
  167. $finalProb = max(0, min(1, $finalProb));
  168. // 生成随机数
  169. $randomNumber = mt_rand(1, 100);
  170. $threshold = $finalProb * 100;
  171. // 详细的debug日志
  172. Log::debug('灾害生成详细信息', [
  173. 'crop_id' => $crop->id,
  174. 'user_id' => $crop->user_id,
  175. 'growth_stage' => $crop->growth_stage->valueInt(),
  176. 'disaster_type' => $disasterType,
  177. 'disaster_type_name' => DISASTER_TYPE::getName($disasterType),
  178. 'base_probability' => $baseProb,
  179. 'seed_resistance' => $seedResistance,
  180. 'land_resistance' => $landDisasterResistance,
  181. 'active_buffs' => $activeBuffs,
  182. 'god_buff_type' => $buffType,
  183. 'has_god_buff' => $hasGodBuff,
  184. 'final_probability' => $finalProb,
  185. 'threshold' => $threshold,
  186. 'random_number' => $randomNumber,
  187. 'will_generate' => $randomNumber <= $threshold,
  188. 'disaster_resistance_type' => is_object($disasterResistance) ? get_class($disasterResistance) : gettype($disasterResistance),
  189. 'disaster_resistance_raw' => is_object($disasterResistance) ? 'object' : $disasterResistance
  190. ]);
  191. // 随机决定是否生成该类型灾害
  192. if ($randomNumber <= $threshold) {
  193. $disasterInfo = [
  194. 'type' => $disasterType,
  195. 'generated_ts' => now()->toDateTimeString(),
  196. 'status' => 'active'
  197. ];
  198. $generatedDisasters[] = $disasterInfo;
  199. Log::debug('灾害生成成功', [
  200. 'crop_id' => $crop->id,
  201. 'disaster_type' => $disasterType,
  202. 'disaster_type_name' => DISASTER_TYPE::getName($disasterType),
  203. 'final_probability' => $finalProb
  204. ]);
  205. } else {
  206. Log::info('灾害未生成', [
  207. 'crop_id' => $crop->id,
  208. 'disaster_type' => $disasterType,
  209. 'disaster_type_name' => DISASTER_TYPE::getName($disasterType),
  210. 'reason' => '随机数超过阈值',
  211. 'random_number' => $randomNumber,
  212. 'threshold' => $threshold,
  213. 'final_probability' => $finalProb
  214. ]);
  215. }
  216. }
  217. return $generatedDisasters;
  218. }
  219. /**
  220. * 将多个灾害应用到作物上
  221. *
  222. * @param FarmCrop $crop
  223. * @param array $disasterInfos
  224. * @return array
  225. */
  226. private function applyDisastersToCrop(FarmCrop $crop, array $disasterInfos): array
  227. {
  228. if (empty($disasterInfos)) {
  229. return [];
  230. }
  231. // 更新作物灾害信息
  232. $disasters = $crop->disasters ?? [];
  233. $disasters = array_merge($disasters, $disasterInfos);
  234. $crop->disasters = $disasters;
  235. // TODO: 根据文档,作物灾害和土地无关,此处更新土地状态可能需要重新评估
  236. // 更新土地状态为灾害
  237. $land = $crop->land;
  238. $oldLandStatus = $land->status;
  239. $land->status = LAND_STATUS::DISASTER->value;
  240. // 保存更改
  241. $crop->save();
  242. $land->save();
  243. // 如果土地状态发生了变化,触发土地状态变更事件
  244. if ($oldLandStatus !== $land->status) {
  245. event(new \App\Module\Farm\Events\LandStatusChangedEvent($crop->user_id, $land->id, $oldLandStatus, $land->status));
  246. }
  247. // 触发灾害生成事件
  248. $disasterDtos = [];
  249. foreach ($disasterInfos as $disasterInfo) {
  250. event(new DisasterGeneratedEvent($crop->user_id, $crop, $disasterInfo['type'], $disasterInfo));
  251. $disasterDtos[] = DisasterInfoDto::fromArray($disasterInfo);
  252. // 记录灾害产生事件
  253. FarmCropLog::logDisasterOccurred($crop->user_id, $crop->land_id, $crop->id, $crop->seed_id, [
  254. 'disaster_type' => $disasterInfo['type'],
  255. 'disaster_info' => $disasterInfo,
  256. 'growth_stage' => $crop->growth_stage->value,
  257. 'land_type' => $land->land_type ?? 1,
  258. 'old_land_status' => $oldLandStatus,
  259. 'new_land_status' => $land->status,
  260. 'generated_at' => $disasterInfo['generated_ts']
  261. ]);
  262. }
  263. return $disasterDtos;
  264. }
  265. /**
  266. * 批量获取需要检查灾害的作物并处理
  267. *
  268. * @param int|null $checkIntervalMinutes 检查间隔(分钟)
  269. * @return array 生成结果统计
  270. */
  271. public function generateDisasterBatchs(?int $checkIntervalMinutes = null): array
  272. {
  273. if ($checkIntervalMinutes === null) {
  274. $checkIntervalMinutes = DisasterService::getCheckInterval();
  275. }
  276. $checkTime = now()->subMinutes($checkIntervalMinutes);
  277. // 获取需要检查灾害的作物:
  278. // 1. 必须在发芽期、生长期或果实期
  279. // 2. 当前阶段可以产生灾害 (can_disaster = 1)
  280. // 3. 满足时间检查条件(首次检查或超过检查间隔)
  281. $crops = FarmCrop::whereIn('growth_stage', [GROWTH_STAGE::SPROUT, GROWTH_STAGE::GROWTH, GROWTH_STAGE::FRUIT])
  282. ->where('can_disaster', true)
  283. ->where(function ($query) use ($checkTime) {
  284. $query->whereNull('last_disaster_check_time')
  285. ->orWhere('last_disaster_check_time', '<', $checkTime);
  286. })
  287. ->with(['land.landType', 'seed', 'user.buffs' => function ($query) {
  288. $query->where('expire_time', '>', now());
  289. }])
  290. ->get();
  291. $totalCount = $crops->count();
  292. $generatedCount = 0;
  293. $skippedCount = 0;
  294. foreach ($crops as $crop) {
  295. $result = $this->generateDisasters($crop);
  296. if ($result === 'generated') {
  297. $generatedCount++;
  298. } elseif ($result === 'skipped') {
  299. $skippedCount++;
  300. }
  301. }
  302. return [
  303. 'total' => $totalCount,
  304. 'generated' => $generatedCount,
  305. 'skipped' => $skippedCount
  306. ];
  307. }
  308. /**
  309. * 为单个作物生成灾害
  310. *
  311. * @param FarmCrop $crop
  312. * @return string 处理结果:'generated', 'skipped', 'failed'
  313. */
  314. public function generateDisasters(FarmCrop $crop): string
  315. {
  316. try {
  317. // 1. 先进行基础检查和计算(不在事务中,减少锁时间)
  318. // 检查用户是否存在
  319. if (!$crop->user) {
  320. Log::warning('作物关联的用户不存在,跳过灾害生成', [
  321. 'crop_id' => $crop->id,
  322. 'user_id' => $crop->user_id
  323. ]);
  324. return 'skipped';
  325. }
  326. // 注意:根据文档,作物灾害和土地无关,不需要检查土地状态
  327. // 获取相关数据并计算灾害
  328. $disasterResistance = $crop->seed->disaster_resistance ?? null;
  329. $landDisasterResistance = ($crop->land->landType->disaster_resistance ?? 0) / 100;
  330. $activeBuffs = $crop->user->buffs->pluck('buff_type')->toArray();
  331. // 尝试生成灾害(支持多种灾害)
  332. $disasterInfos = $this->tryGenerateDisasterForCrop($crop, $disasterResistance, $landDisasterResistance, $activeBuffs);
  333. // 2. 开启事务进行有锁更新
  334. return DB::transaction(function () use ($crop, $disasterInfos) {
  335. // 使用行锁重新获取作物,确保数据一致性
  336. $lockedCrop = FarmCrop::where('id', $crop->id)
  337. ->lockForUpdate()
  338. ->first();
  339. // 如果作物不存在或已被软删除,跳过处理
  340. if (!$lockedCrop || $lockedCrop->trashed()) {
  341. Log::info('作物已被删除,跳过灾害生成', [
  342. 'crop_id' => $crop->id,
  343. 'user_id' => $crop->user_id
  344. ]);
  345. return 'skipped';
  346. }
  347. // 更新检查时间
  348. $lockedCrop->last_disaster_check_time = now();
  349. // 如果有灾害需要生成,应用到作物
  350. if (!empty($disasterInfos)) {
  351. // 应用灾害到作物
  352. $this->applyDisastersToCrop($lockedCrop, $disasterInfos);
  353. // 生成灾害后,设置当前阶段不能再产生灾害
  354. $lockedCrop->can_disaster = false;
  355. $lockedCrop->save();
  356. Log::info('单个作物灾害生成成功', [
  357. 'crop_id' => $lockedCrop->id,
  358. 'user_id' => $lockedCrop->user_id,
  359. 'disaster_count' => count($disasterInfos),
  360. 'disaster_types' => array_column($disasterInfos, 'type')
  361. ]);
  362. return 'generated';
  363. } else {
  364. // 没有生成灾害,但需要保存检查时间
  365. $lockedCrop->save();
  366. return 'checked';
  367. }
  368. });
  369. } catch (\Exception $e) {
  370. Log::error('单个作物灾害生成失败', [
  371. 'crop_id' => $crop->id,
  372. 'error' => $e->getMessage(),
  373. 'trace' => $e->getTraceAsString()
  374. ]);
  375. return 'failed';
  376. }
  377. }
  378. /**
  379. * 批量检查并生成灾害(兼容性方法)
  380. *
  381. * @param int|null $checkIntervalMinutes 检查间隔(分钟)
  382. * @return array 生成结果统计
  383. */
  384. public function batchGenerateDisasters(?int $checkIntervalMinutes = null): array
  385. {
  386. return $this->generateDisasterBatchs($checkIntervalMinutes);
  387. }
  388. }