DisasterLogic.php 15 KB

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