LandLogic.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. <?php
  2. namespace App\Module\Farm\Logics;
  3. use App\Module\Farm\Dtos\LandInfoDto;
  4. use App\Module\Farm\Enums\LAND_STATUS;
  5. use App\Module\Farm\Enums\LAND_TYPE;
  6. use App\Module\Farm\Enums\UPGRADE_TYPE;
  7. use App\Module\Farm\Events\LandUpgradedEvent;
  8. use App\Module\Farm\Models\FarmLand;
  9. use App\Module\Farm\Models\FarmLandType;
  10. use App\Module\Farm\Models\FarmLandUpgradeConfig;
  11. use App\Module\Farm\Models\FarmUpgradeLog;
  12. use App\Module\Farm\Models\FarmUser;
  13. use App\Module\Game\Services\ConsumeService;
  14. use Illuminate\Support\Collection;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Log;
  17. use UCore\Dto\Res;
  18. use UCore\Exception\LogicException;
  19. use function Laravel\Prompts\select;
  20. /**
  21. * 土地管理逻辑
  22. */
  23. class LandLogic
  24. {
  25. /**
  26. * 获取用户的所有土地
  27. *
  28. * @param int $userId
  29. * @return Collection|LandInfoDto[]
  30. */
  31. public function getUserLands(int $userId): Collection
  32. {
  33. try {
  34. $lands = FarmLand::where('user_id', $userId)
  35. ->orderBy('position')
  36. ->get();
  37. // dd($lands);
  38. return $lands->map(function ($land) {
  39. return LandInfoDto::fromModel($land);
  40. });
  41. } catch (\Exception $e) {
  42. Log::error('获取用户土地失败', [
  43. 'user_id' => $userId,
  44. 'error' => $e->getMessage(),
  45. 'trace' => $e->getTraceAsString()
  46. ]);
  47. return collect();
  48. }
  49. }
  50. /**
  51. * 获取用户指定位置的土地
  52. *
  53. * @param int $userId
  54. * @param int $position
  55. * @return LandInfoDto|null
  56. */
  57. public function getUserLandByPosition(int $userId, int $position): ?LandInfoDto
  58. {
  59. try {
  60. $land = FarmLand::where('user_id', $userId)
  61. ->where('position', $position)
  62. ->first();
  63. if (!$land) {
  64. return null;
  65. }
  66. return LandInfoDto::fromModel($land);
  67. } catch (\Exception $e) {
  68. Log::error('获取用户指定位置土地失败', [
  69. 'user_id' => $userId,
  70. 'position' => $position,
  71. 'error' => $e->getMessage(),
  72. 'trace' => $e->getTraceAsString()
  73. ]);
  74. return null;
  75. }
  76. }
  77. /**
  78. * 创建土地
  79. *
  80. * @param int $userId
  81. * @param int $position
  82. * @param int $landType
  83. * @return FarmLand|null
  84. */
  85. public function createLand(int $userId, int $position, int $landType): ?FarmLand
  86. {
  87. try {
  88. // 检查位置是否已有土地
  89. $existingLand = FarmLand::where('user_id', $userId)
  90. ->where('position', $position)
  91. ->first();
  92. if ($existingLand) {
  93. return $existingLand;
  94. }
  95. // 创建新土地
  96. $land = new FarmLand();
  97. $land->user_id = $userId;
  98. $land->position = $position;
  99. $land->land_type = $landType;
  100. $land->status = LAND_STATUS::IDLE->value;
  101. $land->save();
  102. Log::info('创建土地成功', [
  103. 'user_id' => $userId,
  104. 'position' => $position,
  105. 'land_type' => $landType,
  106. 'land_id' => $land->id
  107. ]);
  108. return $land;
  109. } catch (\Exception $e) {
  110. Log::error('创建土地失败', [
  111. 'user_id' => $userId,
  112. 'position' => $position,
  113. 'land_type' => $landType,
  114. 'error' => $e->getMessage(),
  115. 'trace' => $e->getTraceAsString()
  116. ]);
  117. return null;
  118. }
  119. }
  120. /**
  121. * 升级土地
  122. * 调用前已经检查,确保用户有足够的材料,且已经检查了升级路径
  123. *
  124. * @param int $userId
  125. * @param int $landId
  126. * @param int $targetType
  127. * @param array $materials 消耗的材料
  128. * @return bool
  129. */
  130. public function upgradeLand(int $userId, int $landId, int $targetType): bool
  131. {
  132. try {
  133. // 开启事务
  134. DB::beginTransaction();
  135. // 获取土地信息
  136. /**
  137. * @var FarmLand $land
  138. */
  139. $land = FarmLand::where('id', $landId)
  140. ->where('user_id', $userId)
  141. ->first();
  142. if (!$land) {
  143. throw new LogicException('土地不存在');
  144. }
  145. // 检查路径可用
  146. $check = self::checkUpgradePath($userId, $land->land_type, $targetType);
  147. if ($check->error) {
  148. throw new LogicException('升级路径检查不通过!');
  149. }
  150. /**
  151. *
  152. * @var FarmLandUpgradeConfig $config
  153. */
  154. $config = $check->data['config'];
  155. // 检查土地状态
  156. if ($land->status !== LAND_STATUS::IDLE->value) {
  157. throw new LogicException('土地状态不允许升级');
  158. }
  159. // 获取当前土地类型
  160. $currentType = $land->land_type;
  161. // 检查是否已经是目标类型
  162. if ($currentType === $targetType) {
  163. throw new LogicException('土地已经是目标类型');
  164. }
  165. // 更新土地类型
  166. $oldType = $land->land_type;
  167. $land->land_type = $targetType;
  168. $land->save();
  169. // 创建升级记录
  170. $upgradeLog = new FarmUpgradeLog();
  171. $upgradeLog->user_id = $userId;
  172. $upgradeLog->upgrade_type = UPGRADE_TYPE::LAND->value;
  173. $upgradeLog->target_id = $landId;
  174. $upgradeLog->old_level = $oldType;
  175. $upgradeLog->new_level = $targetType;
  176. $upgradeLog->materials_consumed = [];
  177. $upgradeLog->upgrade_time = now();
  178. $upgradeLog->created_at = now();
  179. $upgradeLog->save();
  180. // 进行消耗
  181. $ec = ConsumeService::executeConsume($userId, $config->materials, 'land_upgrade', $upgradeLog->id, false);
  182. if ($ec->error) {
  183. throw new LogicException('消耗失败');
  184. }
  185. $upgradeLog->materials_consumed = $ec->data['list'];
  186. $upgradeLog->save();
  187. // 提交事务
  188. DB::commit();
  189. // 触发土地升级事件
  190. event(new LandUpgradedEvent($userId, $land, $oldType, $targetType, $upgradeLog));
  191. Log::info('土地升级成功', [
  192. 'user_id' => $userId,
  193. 'land_id' => $landId,
  194. 'old_type' => $oldType,
  195. 'new_type' => $targetType,
  196. 'upgrade_log_id' => $upgradeLog->id
  197. ]);
  198. return true;
  199. } catch (\Exception $e) {
  200. // 回滚事务
  201. DB::rollBack();
  202. Log::error('土地升级失败', [
  203. 'user_id' => $userId,
  204. 'land_id' => $landId,
  205. 'target_type' => $targetType,
  206. 'error' => $e->getMessage(),
  207. 'trace' => $e->getTraceAsString()
  208. ]);
  209. return false;
  210. }
  211. }
  212. /**
  213. * 检查升级路径
  214. *
  215. * @param $userId
  216. * @param $currentType
  217. * @param $targetType
  218. * @param bool $checkM 是否检查消耗
  219. * @return Res
  220. * @throws \Exception
  221. */
  222. static public function checkUpgradePath(int $userId, int $currentType, int $targetType, bool $checkM = true): Res
  223. {
  224. // 获取升级配置
  225. /**
  226. * @var FarmLandUpgradeConfig $upgradeConfig
  227. */
  228. $upgradeConfig = FarmLandUpgradeConfig::where('from_type_id', $currentType)
  229. ->where('to_type_id', $targetType)
  230. ->first();
  231. if (!$upgradeConfig) {
  232. Log::error('升级路径不存在', [
  233. 'user_id' => $userId,
  234. 'current_type' => $currentType,
  235. 'target_type' => $targetType
  236. ]);
  237. return Res::error('升级路径不存在', [
  238. 'user_id' => $userId,
  239. 'current_type' => $currentType,
  240. 'target_type' => $targetType
  241. ]);
  242. }
  243. // 检查用户房屋等级是否满足要求
  244. $targetLandType = FarmLandType::find($targetType);
  245. $farmUser = FarmUser::where('user_id', $userId)->first();
  246. if (!$farmUser || $farmUser->house_level < $targetLandType->unlock_house_level) {
  247. Log::error('房屋等级不足,无法升级到该土地类型', [
  248. 'user_id' => $userId,
  249. 'current_type' => $currentType,
  250. 'target_type' => $targetType,
  251. 'house_level' => $farmUser->house_level,
  252. 'unlock_house_level' => $targetLandType->unlock_house_level
  253. ]);
  254. return Res::error('房屋等级不足,无法升级到该土地类型', [
  255. 'user_id' => $userId,
  256. 'current_type' => $currentType,
  257. 'target_type' => $targetType,
  258. 'house_level' => $farmUser->house_level,
  259. 'unlock_house_level' => $targetLandType->unlock_house_level
  260. ]);
  261. }
  262. // 检查特殊土地数量限制
  263. if ($targetLandType->is_special) {
  264. $specialLandCount = FarmLand::where('user_id', $userId)
  265. ->whereIn('land_type', [ LAND_TYPE::GOLD->value, LAND_TYPE::BLUE->value, LAND_TYPE::PURPLE->value ])
  266. ->count();
  267. $houseConfig = $farmUser->houseConfig;
  268. if ($specialLandCount >= $houseConfig->special_land_limit) {
  269. Log::error('特殊土地数量已达上限', [
  270. 'user_id' => $userId,
  271. 'current_type' => $currentType,
  272. 'target_type' => $targetType,
  273. 'special_land_count' => $specialLandCount,
  274. 'special_land_limit' => $houseConfig->special_land_limit
  275. ]);
  276. return Res::error('特殊土地数量已达上限', [
  277. 'user_id' => $userId,
  278. 'current_type' => $currentType,
  279. 'target_type' => $targetType,
  280. 'special_land_count' => $specialLandCount,
  281. 'special_land_limit' => $houseConfig->special_land_limit
  282. ]);
  283. }
  284. }
  285. // 检查消耗
  286. if ($checkM) {
  287. $res = ConsumeService::checkConsume($userId, $upgradeConfig->materials);
  288. if ($res->error) {
  289. Log::error('当前路径资源不足', [
  290. 'user_id' => $userId,
  291. 'current_type' => $currentType,
  292. 'target_type' => $targetType,
  293. 'error' => $res->message
  294. ]);
  295. return Res::error('当前路径资源不足', [
  296. 'msg' => $res->message
  297. ]);
  298. }
  299. }
  300. return Res::success('升级路径可用', [
  301. 'config' => $upgradeConfig
  302. ]);
  303. }
  304. /**
  305. * 获取升级所需材料
  306. *
  307. * @param int $currentType 当前土地类型
  308. * @param int $targetType 目标土地类型
  309. * @return array 升级所需材料
  310. */
  311. public function getUpgradeMaterials(int $currentType, int $targetType): array
  312. {
  313. try {
  314. // 从数据库中获取升级配置
  315. $upgradeConfig = FarmLandUpgradeConfig::where('from_type_id', $currentType)
  316. ->where('to_type_id', $targetType)
  317. ->first();
  318. if (!$upgradeConfig) {
  319. return [];
  320. }
  321. // 使用模型的 getUpgradeMaterials 方法获取材料
  322. return $upgradeConfig->getUpgradeMaterials();
  323. } catch (\Exception $e) {
  324. Log::error('获取升级所需材料失败', [
  325. 'current_type' => $currentType,
  326. 'target_type' => $targetType,
  327. 'error' => $e->getMessage(),
  328. 'trace' => $e->getTraceAsString()
  329. ]);
  330. return [];
  331. }
  332. }
  333. /**
  334. * 获取可用的升级路径(不进行消耗检查)
  335. *
  336. * @param int $userId 用户ID
  337. * @param int $landId 土地ID
  338. * @param int|null $toType 目标土地类型ID(可选)
  339. * @return FarmLandUpgradeConfig[]
  340. *
  341. */
  342. public function getAvailableUpgradePaths(int $userId, int $landId, ?int $toType = null): array
  343. {
  344. try {
  345. // 获取土地信息
  346. $land = FarmLand::where('id', $landId)
  347. ->where('user_id', $userId)
  348. ->first();
  349. if (!$land) {
  350. return [];
  351. }
  352. // 获取当前土地类型
  353. $currentType = $land->land_type;
  354. // 获取用户房屋等级
  355. /**
  356. * @var FarmUser $farmUser
  357. */
  358. $farmUser = FarmUser::where('user_id', $userId)->first();
  359. if (!$farmUser) {
  360. return [];
  361. }
  362. $houseLevel = $farmUser->house_level;
  363. // 获取可用的升级路径
  364. $query = FarmLandUpgradeConfig::where('from_type_id', $currentType)
  365. ->with('toType');
  366. // 如果指定了目标类型,则只获取该类型的升级路径
  367. if ($toType !== null) {
  368. $query->where('to_type_id', $toType);
  369. }
  370. $upgradePaths = $query->get();
  371. // 过滤出符合房屋等级要求的升级路径
  372. $availablePaths = $upgradePaths->filter(function ($path) use ($houseLevel) {
  373. return $path->toType->unlock_house_level <= $houseLevel;
  374. });
  375. // 检查特殊土地数量限制
  376. $specialLandCount = FarmLand::where('user_id', $userId)
  377. ->whereIn('land_type', [ LAND_TYPE::GOLD->value, LAND_TYPE::BLUE->value, LAND_TYPE::PURPLE->value ])
  378. ->count();
  379. $houseConfig = $farmUser->houseConfig;
  380. // 如果没有找到对应的房屋配置,使用默认值0
  381. $specialLandLimit = $houseConfig ? $houseConfig->special_land_limit : 0;
  382. // 如果特殊土地已达上限,过滤掉特殊土地升级路径
  383. if ($specialLandCount >= $specialLandLimit) {
  384. $availablePaths = $availablePaths->filter(function ($path) {
  385. return !$path->toType->is_special;
  386. });
  387. }
  388. // 格式化返回结果
  389. return $availablePaths->toArray();
  390. } catch (\Exception $e) {
  391. Log::error('获取可用升级路径失败', [
  392. 'user_id' => $userId,
  393. 'land_id' => $landId,
  394. 'error' => $e->getMessage(),
  395. 'trace' => $e->getTraceAsString()
  396. ]);
  397. return [];
  398. }
  399. }
  400. }