| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721 |
- <?php
- namespace App\Module\Farm\Logics;
- use App\Module\Farm\Dtos\CropInfoDto;
- use App\Module\Farm\Dtos\HarvestResultDto;
- use App\Module\Farm\Enums\GROWTH_STAGE;
- use App\Module\Farm\Enums\LAND_STATUS;
- use App\Module\Farm\Events\CropGrowthStageChangedEvent;
- use App\Module\Farm\Events\CropHarvestedEvent;
- use App\Module\Farm\Events\CropPlantedEvent;
- use App\Module\Farm\Events\DisasterClearedEvent;
- use App\Module\Farm\Models\FarmCrop;
- use App\Module\Farm\Models\FarmHarvestLog;
- use App\Module\Farm\Models\FarmLand;
- use App\Module\Farm\Models\FarmSeed;
- use App\Module\Farm\Models\FarmSeedOutput;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use UCore\Db\Helper;
- /**
- * 作物管理逻辑
- */
- class CropLogic
- {
- /**
- * 获取作物信息
- *
- * @param int $cropId
- * @return CropInfoDto|null
- */
- public function getCropInfo(int $cropId): ?CropInfoDto
- {
- try {
- $crop = FarmCrop::find($cropId);
- if (!$crop) {
- return null;
- }
- return CropInfoDto::fromModel($crop);
- } catch (\Exception $e) {
- Log::error('获取作物信息失败', [
- 'crop_id' => $cropId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return null;
- }
- }
- /**
- * 获取土地上的作物信息
- *
- * @param int $landId
- * @return CropInfoDto|null
- */
- public function getCropByLandId(int $landId): ?CropInfoDto
- {
- try {
- $crop = FarmCrop::where('land_id', $landId)->first();
- if (!$crop) {
- return null;
- }
- return CropInfoDto::fromModel($crop);
- } catch (\Exception $e) {
- Log::error('获取土地作物信息失败', [
- 'land_id' => $landId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return null;
- }
- }
- /**
- * 种植作物
- *
- * @param int $userId
- * @param int $landId
- * @param int $seedId
- * @return CropInfoDto|null
- */
- public function plantCrop(int $userId, int $landId, int $seedId): ?CropInfoDto
- {
- try {
- // 开启事务
- DB::beginTransaction();
- // 获取土地信息
- $land = FarmLand::where('id', $landId)
- ->where('user_id', $userId)
- ->first();
- if (!$land) {
- throw new \Exception('土地不存在');
- }
- // 检查土地状态
- if ($land->status !== LAND_STATUS::IDLE->value) {
- throw new \Exception('土地状态不允许种植');
- }
- // 获取种子信息
- $seed = FarmSeed::find($seedId);
- if (!$seed) {
- throw new \Exception('种子不存在');
- }
- // 创建作物记录
- $crop = new FarmCrop();
- $crop->land_id = $landId;
- $crop->user_id = $userId;
- $crop->seed_id = $seedId;
- $crop->plant_time = now();
- $crop->growth_stage = GROWTH_STAGE::SEED->value;
- $crop->stage_start_time = now(); // 设置当前阶段开始时间
- $crop->stage_end_time = now()->addSeconds($seed->seed_time);
- $crop->disasters = [];
- $crop->fertilized = false;
- $crop->save();
- // 更新土地状态
- $land->status = LAND_STATUS::PLANTING->value;
- $land->save();
- // 提交事务
- DB::commit();
- // 触发作物种植事件
- event(new CropPlantedEvent($userId, $land, $crop));
- Log::info('作物种植成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'seed_id' => $seedId,
- 'crop_id' => $crop->id
- ]);
- return CropInfoDto::fromModel($crop);
- } catch (\Exception $e) {
- // 回滚事务
- DB::rollBack();
- Log::error('作物种植失败', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'seed_id' => $seedId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return null;
- }
- }
- /**
- * 收获作物
- *
- * @param int $userId
- * @param int $landId
- * @return HarvestResultDto|null
- */
- public function harvestCrop(int $userId, int $landId): ?HarvestResultDto
- {
- try {
- // 开启事务
- DB::beginTransaction();
- // 获取土地信息
- $land = FarmLand::where('id', $landId)
- ->where('user_id', $userId)
- ->first();
- if (!$land) {
- throw new \Exception('土地不存在');
- }
- // 检查土地状态
- if ($land->status !== LAND_STATUS::HARVESTABLE->value) {
- throw new \Exception('土地状态不允许收获');
- }
- // 获取作物信息
- $crop = FarmCrop::where('land_id', $landId)->first();
- if (!$crop) {
- throw new \Exception('作物不存在');
- }
- // 检查作物生长阶段
- if ($crop->growth_stage !== GROWTH_STAGE::MATURE->value) {
- throw new \Exception('作物未成熟,不能收获');
- }
- // 获取种子信息
- $seed = $crop->seed;
- if (!$seed) {
- throw new \Exception('种子信息不存在');
- }
- // 随机选择产出物品
- $outputInfo = $this->getRandomOutput($seed->id);
- $outputItemId = $outputInfo['item_id'];
- $outputAmount = mt_rand($outputInfo['min_amount'], $outputInfo['max_amount']);
- // 创建收获记录
- $harvestLog = new FarmHarvestLog();
- $harvestLog->user_id = $userId;
- $harvestLog->land_id = $landId;
- $harvestLog->crop_id = $crop->id;
- $harvestLog->seed_id = $seed->id;
- $harvestLog->output_amount = $outputAmount;
- $harvestLog->harvest_time = now();
- $harvestLog->created_at = now();
- $harvestLog->save();
- // 删除作物记录
- $crop->delete();
- // 更新土地状态
- $land->status = LAND_STATUS::IDLE;
- $land->save();
- // 提交事务
- DB::commit();
- // 触发作物收获事件
- event(new CropHarvestedEvent($userId, $land, $crop, $harvestLog, $outputItemId, $outputAmount));
- Log::info('作物收获成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'crop_id' => $crop->id,
- 'seed_id' => $seed->id,
- 'output_item_id' => $outputItemId,
- 'output_amount' => $outputAmount,
- 'harvest_log_id' => $harvestLog->id
- ]);
- return HarvestResultDto::fromModel($harvestLog, $outputItemId);
- } catch (\Exception $e) {
- // 回滚事务
- DB::rollBack();
- Log::error('作物收获失败', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return null;
- }
- }
- /**
- * 使用化肥
- *
- * @param int $userId
- * @param int $landId
- * @return bool
- */
- public function useFertilizer(int $userId, int $landId,int $crop_growth_time): bool
- {
- try {
- Helper::check_tr();
- // 获取土地信息
- /**
- * @var FarmLand $land
- */
- $land = FarmLand::where('id', $landId)
- ->where('user_id', $userId)
- ->first();
- if (!$land) {
- throw new \Exception('土地不存在');
- }
- // 检查土地状态
- if ($land->status !== LAND_STATUS::PLANTING->valueInt()) {
- throw new \Exception('土地状态不允许使用化肥');
- }
- // 获取作物信息
- $crop = FarmCrop::where('land_id', $landId)->first();
- if (!$crop) {
- throw new \Exception('作物不存在');
- }
- // 检查作物生长阶段
- if (!GROWTH_STAGE::canUseFertilizer($crop->growth_stage)) {
- throw new \Exception('当前生长阶段不能使用化肥');
- }
- // 检查是否已经使用过化肥
- if ($crop->fertilized) {
- throw new \Exception('当前阶段已经使用过化肥');
- }
- // 更新作物信息
- $crop->fertilized = true;
- // 根据 crop_growth_time 参数减少当前阶段时间
- if ($crop->stage_end_time) {
- $currentTime = now();
- $endTime = $crop->stage_end_time;
- $remainingTime = $currentTime->diffInSeconds($endTime, false);
- if ($remainingTime > 0) {
- // 确保减少的时间不超过剩余时间
- $reducedTime = min($crop_growth_time, $remainingTime);
- $crop->stage_end_time = $endTime->subSeconds($reducedTime);
- Log::info('化肥减少生长时间', [
- 'crop_id' => $crop->id,
- 'reduced_time' => $reducedTime,
- 'original_end_time' => $endTime->toDateTimeString(),
- 'new_end_time' => $crop->stage_end_time->toDateTimeString(),
- 'stage_start_time' => $crop->stage_start_time->toDateTimeString()
- ]);
- }
- }
- $crop->save();
- Log::info('使用化肥成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'crop_id' => $crop->id,
- 'growth_stage' => $crop->growth_stage,
- 'stage_end_time' => $crop->stage_end_time
- ]);
- return true;
- } catch (\Exception $e) {
- Log::error('使用化肥失败', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return false;
- }
- }
- /**
- * 清理灾害
- *
- * @param int $userId
- * @param int $landId
- * @param int $disasterType
- * @return bool
- */
- public function clearDisaster(int $userId, int $landId, int $disasterType): bool
- {
- try {
- // 获取土地信息
- $land = FarmLand::where('id', $landId)
- ->where('user_id', $userId)
- ->first();
- if (!$land) {
- throw new \Exception('土地不存在');
- }
- // 检查土地状态
- if ($land->status !== LAND_STATUS::DISASTER->value) {
- throw new \Exception('土地没有灾害');
- }
- // 获取作物信息
- $crop = FarmCrop::where('land_id', $landId)->first();
- if (!$crop) {
- throw new \Exception('作物不存在');
- }
- // 检查灾害是否存在
- $disasters = $crop->disasters ?? [];
- $disasterIndex = -1;
- $disasterInfo = null;
- foreach ($disasters as $index => $disaster) {
- if (($disaster['type'] ?? 0) == $disasterType && ($disaster['status'] ?? '') === 'active') {
- $disasterIndex = $index;
- $disasterInfo = $disaster;
- break;
- }
- }
- if ($disasterIndex === -1 || !$disasterInfo) {
- throw new \Exception('指定类型的灾害不存在');
- }
- // 更新灾害状态
- $disasters[$disasterIndex]['status'] = 'cleared';
- $disasters[$disasterIndex]['cleared_at'] = now()->toDateTimeString();
- $crop->disasters = $disasters;
- // 检查是否还有其他活跃灾害
- $hasActiveDisaster = false;
- foreach ($disasters as $disaster) {
- if (($disaster['status'] ?? '') === 'active') {
- $hasActiveDisaster = true;
- break;
- }
- }
- // 如果没有其他活跃灾害,更新土地状态
- if (!$hasActiveDisaster) {
- $land->status = LAND_STATUS::PLANTING->value;
- }
- // 保存更改
- $crop->save();
- $land->save();
- // 触发灾害清理事件
- event(new DisasterClearedEvent($userId, $crop, $disasterType, $disasterInfo));
- Log::info('灾害清理成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'crop_id' => $crop->id,
- 'disaster_type' => $disasterType
- ]);
- return true;
- } catch (\Exception $e) {
- Log::error('灾害清理失败', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'disaster_type' => $disasterType,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return false;
- }
- }
- /**
- * 铲除作物
- *
- * @param int $userId
- * @param int $landId
- * @return bool
- */
- public function removeCrop(int $userId, int $landId): bool
- {
- try {
- // 开启事务
- DB::beginTransaction();
- // 获取土地信息
- $land = FarmLand::where('id', $landId)
- ->where('user_id', $userId)
- ->first();
- if (!$land) {
- throw new \Exception('土地不存在');
- }
- // 检查土地状态
- if ($land->status === LAND_STATUS::IDLE->value) {
- throw new \Exception('土地上没有作物');
- }
- // 获取作物信息
- $crop = FarmCrop::where('land_id', $landId)->first();
- if (!$crop) {
- // 如果没有作物但土地状态不是空闲,修正土地状态
- $land->status = LAND_STATUS::IDLE->value;
- $land->save();
- DB::commit();
- return true;
- }
- // 删除作物记录
- $crop->delete();
- // 更新土地状态
- $land->status = LAND_STATUS::IDLE->value;
- $land->save();
- // 提交事务
- DB::commit();
- Log::info('铲除作物成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'crop_id' => $crop->id
- ]);
- return true;
- } catch (\Exception $e) {
- // 回滚事务
- DB::rollBack();
- Log::error('铲除作物失败', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return false;
- }
- }
- /**
- * 更新作物生长阶段
- *
- * @param int $cropId
- * @return bool
- */
- public function updateGrowthStage(int $cropId): bool
- {
- try {
- // 获取作物信息
- $crop = FarmCrop::find($cropId);
- if (!$crop) {
- throw new \Exception('作物不存在');
- }
- // 检查是否需要更新
- if (!$crop->stage_end_time || $crop->stage_end_time > now()) {
- return false;
- }
- // 获取当前生长阶段
- $oldStage = $crop->growth_stage;
- // 计算新的生长阶段
- $newStage = $this->calculateNextStage($crop);
- // 如果阶段没有变化,不需要更新
- if ($newStage === $oldStage) {
- return false;
- }
- // 计算新阶段的结束时间
- $stageEndTime = $this->calculateStageEndTime($crop, $newStage);
- // 更新作物信息
- $crop->growth_stage = $newStage;
- $crop->stage_start_time = now(); // 设置新阶段的开始时间
- $crop->stage_end_time = $stageEndTime;
- $crop->fertilized = false; // 重置施肥状态
- $crop->save();
- // 触发生长阶段变更事件
- event(new CropGrowthStageChangedEvent($crop->user_id, $crop, $oldStage, $newStage));
- Log::info('作物生长阶段更新成功', [
- 'crop_id' => $cropId,
- 'user_id' => $crop->user_id,
- 'old_stage' => $oldStage,
- 'new_stage' => $newStage,
- 'stage_end_time' => $stageEndTime
- ]);
- return true;
- } catch (\Exception $e) {
- Log::error('作物生长阶段更新失败', [
- 'crop_id' => $cropId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return false;
- }
- }
- /**
- * 计算下一个生长阶段
- *
- * @param FarmCrop $crop
- * @return int
- */
- private function calculateNextStage(FarmCrop $crop): int
- {
- $currentStage = $crop->growth_stage;
- // 如果当前是成熟期,且超过一定时间,则进入枯萎期
- if ($currentStage === GROWTH_STAGE::MATURE->value) {
- // 成熟期持续时间,默认为24小时
- $matureDuration = 24 * 60 * 60;
- // 如果成熟期已经超过指定时间,则进入枯萎期
- if ($crop->stage_end_time && $crop->stage_end_time instanceof \Carbon\Carbon) {
- $endTimeMinusDuration = $crop->stage_end_time->copy()->subSeconds($matureDuration);
- if (now()->diffInSeconds($endTimeMinusDuration) > $matureDuration) {
- return GROWTH_STAGE::WITHERED->value;
- }
- }
- return GROWTH_STAGE::MATURE->value;
- }
- // 正常阶段递增
- return $currentStage + 1;
- }
- /**
- * 计算阶段结束时间
- *
- * @param FarmCrop $crop
- * @param int $stage
- * @return \Carbon\Carbon|null
- */
- private function calculateStageEndTime(FarmCrop $crop, int $stage)
- {
- $seed = $crop->seed;
- if (!$seed) {
- return null;
- }
- $now = now();
- switch ($stage) {
- case GROWTH_STAGE::SEED->value:
- return $now->addSeconds($seed->seed_time);
- case GROWTH_STAGE::SPROUT->value:
- return $now->addSeconds($seed->sprout_time);
- case GROWTH_STAGE::GROWTH->value:
- return $now->addSeconds($seed->growth_time);
- case GROWTH_STAGE::MATURE->value:
- // 成熟期持续24小时后进入枯萎期
- return $now->addHours(24);
- case GROWTH_STAGE::WITHERED->value:
- // 枯萎期没有结束时间
- return null;
- default:
- return null;
- }
- }
- /**
- * 获取随机产出
- *
- * @param int $seedId
- * @return array
- */
- private function getRandomOutput(int $seedId): array
- {
- // 获取种子的所有产出配置
- $outputs = FarmSeedOutput::where('seed_id', $seedId)->get();
- if ($outputs->isEmpty()) {
- // 如果没有产出配置,使用种子的默认产出
- $seed = FarmSeed::find($seedId);
- return [
- 'item_id' => $seed->item_id,
- 'min_amount' => $seed->min_output,
- 'max_amount' => $seed->max_output,
- ];
- }
- // 按概率排序
- $outputs = $outputs->sortByDesc('probability');
- // 获取默认产出
- $defaultOutput = $outputs->firstWhere('is_default', true);
- // 随机选择产出
- $random = mt_rand(1, 100);
- $cumulativeProbability = 0;
- foreach ($outputs as $output) {
- $cumulativeProbability += $output->probability;
- if ($random <= $cumulativeProbability) {
- return [
- 'item_id' => $output->item_id,
- 'min_amount' => $output->min_amount,
- 'max_amount' => $output->max_amount,
- ];
- }
- }
- // 如果随机值超过了所有概率之和,使用默认产出
- if ($defaultOutput) {
- return [
- 'item_id' => $defaultOutput->item_id,
- 'min_amount' => $defaultOutput->min_amount,
- 'max_amount' => $defaultOutput->max_amount,
- ];
- }
- // 如果没有默认产出,使用第一个产出
- $firstOutput = $outputs->first();
- return [
- 'item_id' => $firstOutput->item_id,
- 'min_amount' => $firstOutput->min_amount,
- 'max_amount' => $firstOutput->max_amount,
- ];
- }
- }
|