DisasterLogic.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. Log::error('灾害生成失败', [
  128. 'crop_id' => $cropId,
  129. 'error' => $e->getMessage(),
  130. 'trace' => $e->getTraceAsString()
  131. ]);
  132. return null;
  133. }
  134. }
  135. /**
  136. * 尝试为作物生成灾害(支持多种灾害同时发生)
  137. *
  138. * @param FarmCrop $crop
  139. * @param mixed $disasterResistance
  140. * @param float $landDisasterResistance
  141. * @param array $activeBuffs
  142. * @return array 生成的灾害信息数组
  143. */
  144. private function tryGenerateDisasterForCrop(FarmCrop $crop, $disasterResistance, float $landDisasterResistance, array $activeBuffs): array
  145. {
  146. // 灾害类型及其基础概率
  147. $disasterTypes = DisasterService::getRate();
  148. $generatedDisasters = [];
  149. // 对每种灾害类型都进行判定
  150. foreach ($disasterTypes as $disasterType => $baseProb) {
  151. // 计算最终概率,考虑种子抵抗、土地抵抗和神灵加持
  152. $seedResistance = 0;
  153. if ($disasterResistance) {
  154. if (is_object($disasterResistance) && method_exists($disasterResistance, 'getResistance')) {
  155. // 如果是 DisasterResistanceCast 对象(数据库存储百分比,需要除以100转换为小数)
  156. $seedResistance = $disasterResistance->getResistance($disasterType) / 100;
  157. } elseif (is_array($disasterResistance)) {
  158. // 如果是数组格式(数据库存储百分比,需要除以100转换为小数)
  159. $seedResistance = ($disasterResistance[DisasterService::getDisasterKey($disasterType)] ?? 0) / 100;
  160. }
  161. }
  162. $finalProb = $baseProb - $seedResistance - $landDisasterResistance;
  163. // 如果有对应的神灵加持,则不生成该类型的灾害
  164. $buffType = DISASTER_TYPE::getPreventBuffType($disasterType);
  165. $hasGodBuff = $buffType && in_array($buffType, $activeBuffs);
  166. if ($hasGodBuff) {
  167. $finalProb = 0;
  168. }
  169. // 确保概率在有效范围内
  170. $finalProb = max(0, min(1, $finalProb));
  171. // 生成随机数
  172. $randomNumber = mt_rand(1, 100);
  173. $threshold = $finalProb * 100;
  174. // 详细的debug日志
  175. Log::debug('灾害生成详细信息', [
  176. 'crop_id' => $crop->id,
  177. 'user_id' => $crop->user_id,
  178. 'growth_stage' => $crop->growth_stage->valueInt(),
  179. 'disaster_type' => $disasterType,
  180. 'disaster_type_name' => DISASTER_TYPE::getName($disasterType),
  181. 'base_probability' => $baseProb,
  182. 'seed_resistance' => $seedResistance,
  183. 'land_resistance' => $landDisasterResistance,
  184. 'active_buffs' => $activeBuffs,
  185. 'god_buff_type' => $buffType,
  186. 'has_god_buff' => $hasGodBuff,
  187. 'final_probability' => $finalProb,
  188. 'threshold' => $threshold,
  189. 'random_number' => $randomNumber,
  190. 'will_generate' => $randomNumber <= $threshold,
  191. 'disaster_resistance_type' => is_object($disasterResistance) ? get_class($disasterResistance) : gettype($disasterResistance),
  192. 'disaster_resistance_raw' => is_object($disasterResistance) ? 'object' : $disasterResistance
  193. ]);
  194. // 随机决定是否生成该类型灾害
  195. if ($randomNumber <= $threshold) {
  196. $disasterInfo = [
  197. 'type' => $disasterType,
  198. 'generated_ts' => now()->toDateTimeString(),
  199. 'status' => 'active'
  200. ];
  201. $generatedDisasters[] = $disasterInfo;
  202. Log::debug('灾害生成成功', [
  203. 'crop_id' => $crop->id,
  204. 'disaster_type' => $disasterType,
  205. 'disaster_type_name' => DISASTER_TYPE::getName($disasterType),
  206. 'final_probability' => $finalProb
  207. ]);
  208. } else {
  209. Log::info('灾害未生成', [
  210. 'crop_id' => $crop->id,
  211. 'disaster_type' => $disasterType,
  212. 'disaster_type_name' => DISASTER_TYPE::getName($disasterType),
  213. 'reason' => '随机数超过阈值',
  214. 'random_number' => $randomNumber,
  215. 'threshold' => $threshold,
  216. 'final_probability' => $finalProb
  217. ]);
  218. }
  219. }
  220. return $generatedDisasters;
  221. }
  222. /**
  223. * 将多个灾害应用到作物上
  224. *
  225. * @param FarmCrop $crop
  226. * @param array $disasterInfos
  227. * @return array
  228. */
  229. private function applyDisastersToCrop(FarmCrop $crop, array $disasterInfos): array
  230. {
  231. if (empty($disasterInfos)) {
  232. return [];
  233. }
  234. // 更新作物灾害信息
  235. $disasters = $crop->disasters ?? [];
  236. $disasters = array_merge($disasters, $disasterInfos);
  237. $crop->disasters = $disasters;
  238. // 更新土地状态为灾害
  239. $land = $crop->land;
  240. $land->status = LAND_STATUS::DISASTER;
  241. // 保存更改
  242. $crop->save();
  243. $land->save();
  244. // 触发灾害生成事件
  245. $disasterDtos = [];
  246. foreach ($disasterInfos as $disasterInfo) {
  247. event(new DisasterGeneratedEvent($crop->user_id, $crop, $disasterInfo['type'], $disasterInfo));
  248. $disasterDtos[] = DisasterInfoDto::fromArray($disasterInfo);
  249. }
  250. return $disasterDtos;
  251. }
  252. /**
  253. * 批量获取需要检查灾害的作物并处理
  254. *
  255. * @param int|null $checkIntervalMinutes 检查间隔(分钟)
  256. * @return array 生成结果统计
  257. */
  258. public function generateDisasterBatchs(?int $checkIntervalMinutes = null): array
  259. {
  260. if ($checkIntervalMinutes === null) {
  261. $checkIntervalMinutes = DisasterService::getCheckInterval();
  262. }
  263. $checkTime = now()->subMinutes($checkIntervalMinutes);
  264. // 获取需要检查灾害的作物:
  265. // 1. 必须在发芽期或生长期
  266. // 2. 当前阶段可以产生灾害 (can_disaster = 1)
  267. // 3. 满足时间检查条件(首次检查或超过检查间隔)
  268. $crops = FarmCrop::whereIn('growth_stage', [GROWTH_STAGE::SPROUT, GROWTH_STAGE::GROWTH])
  269. ->where('can_disaster', true)
  270. ->where(function ($query) use ($checkTime) {
  271. $query->whereNull('last_disaster_check_time')
  272. ->orWhere('last_disaster_check_time', '<', $checkTime);
  273. })
  274. ->with(['land.landType', 'seed', 'user.buffs' => function ($query) {
  275. $query->where('expire_time', '>', now());
  276. }])
  277. ->get();
  278. $totalCount = $crops->count();
  279. $generatedCount = 0;
  280. $skippedCount = 0;
  281. foreach ($crops as $crop) {
  282. $result = $this->generateDisasters($crop);
  283. if ($result === 'generated') {
  284. $generatedCount++;
  285. } elseif ($result === 'skipped') {
  286. $skippedCount++;
  287. }
  288. }
  289. return [
  290. 'total' => $totalCount,
  291. 'generated' => $generatedCount,
  292. 'skipped' => $skippedCount
  293. ];
  294. }
  295. /**
  296. * 为单个作物生成灾害
  297. *
  298. * @param FarmCrop $crop
  299. * @return string 处理结果:'generated', 'skipped', 'failed'
  300. */
  301. public function generateDisasters(FarmCrop $crop): string
  302. {
  303. try {
  304. // 更新检查时间
  305. $crop->last_disaster_check_time = now();
  306. // 跳过已经有灾害的土地
  307. if ($crop->land->status === LAND_STATUS::DISASTER) {
  308. $crop->save(); // 仍需更新检查时间
  309. return 'skipped';
  310. }
  311. // 获取相关数据
  312. $disasterResistance = $crop->seed->disaster_resistance ?? null;
  313. $landDisasterResistance = ($crop->land->landType->disaster_resistance ?? 0) / 100; // 数据库存储百分比,需要除以100
  314. $activeBuffs = $crop->user->buffs->pluck('buff_type')->toArray();
  315. // 尝试生成灾害(支持多种灾害)
  316. $disasterInfos = $this->tryGenerateDisasterForCrop($crop, $disasterResistance, $landDisasterResistance, $activeBuffs);
  317. if (!empty($disasterInfos)) {
  318. // 应用灾害到作物
  319. $this->applyDisastersToCrop($crop, $disasterInfos);
  320. // 生成灾害后,设置当前阶段不能再产生灾害
  321. $crop->can_disaster = false;
  322. $crop->save();
  323. Log::info('单个作物灾害生成成功', [
  324. 'crop_id' => $crop->id,
  325. 'user_id' => $crop->user_id,
  326. 'disaster_count' => count($disasterInfos),
  327. 'disaster_types' => array_column($disasterInfos, 'type')
  328. ]);
  329. return 'generated';
  330. } else {
  331. // 没有生成灾害,但需要保存检查时间
  332. $crop->save();
  333. return 'checked';
  334. }
  335. } catch (\Exception $e) {
  336. Log::error('单个作物灾害生成失败', [
  337. 'crop_id' => $crop->id,
  338. 'error' => $e->getMessage(),
  339. 'trace' => $e->getTraceAsString()
  340. ]);
  341. return 'failed';
  342. }
  343. }
  344. /**
  345. * 批量检查并生成灾害(兼容性方法)
  346. *
  347. * @param int|null $checkIntervalMinutes 检查间隔(分钟)
  348. * @return array 生成结果统计
  349. */
  350. public function batchGenerateDisasters(?int $checkIntervalMinutes = null): array
  351. {
  352. return $this->generateDisasterBatchs($checkIntervalMinutes);
  353. }
  354. }