| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010 |
- <?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\Events\LandStatusChangedEvent;
- 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 App\Module\Farm\Models\FarmSowLog;
- use App\Module\GameItems\Services\ItemService;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use UCore\Db\Helper;
- use UCore\Dto\Res;
- /**
- * 作物管理逻辑
- */
- 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 $itemId 种子物品ID
- * @return array|null 返回包含CropInfoDto和日志ID的数组,格式为['crop' => CropInfoDto, 'log_id' => int]
- * @throws \Exception
- */
- public function plantCrop(int $userId, int $landId, int $itemId): ?array
- {
- try {
- // 检查是否已开启事务
- \UCore\Db\Helper::check_tr();
- // 获取土地信息
- $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('土地状态不允许种植');
- }
- // 根据物品ID获取种子配置信息
- $seed = FarmSeed::where('item_id', $itemId)->first();
- if (!$seed) {
- throw new \Exception('种子配置不存在');
- }
- $seedId = $seed->id;
- // 创建作物记录
- $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->last_disaster_check_time = null; // 初始化灾害检查时间
- $crop->can_disaster = false; // 种子期不能产生灾害
- $crop->save();
- // 创建种植日志
- $sowLog = new FarmSowLog();
- $sowLog->user_id = $userId;
- $sowLog->land_id = $landId;
- $sowLog->crop_id = $crop->id;
- $sowLog->seed_id = $seedId;
- $sowLog->sow_time = now();
- $sowLog->save();
- // 更新土地状态
- $land->status = LAND_STATUS::PLANTING->value;
- $land->updateHasCrop();
- $land->save();
- // 触发作物种植事件
- event(new CropPlantedEvent($userId, $land, $crop));
- Log::info('作物种植成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'seed_id' => $seedId,
- 'crop_id' => $crop->id,
- 'sow_log_id' => $sowLog->id
- ]);
- return [
- 'crop' => CropInfoDto::fromModel($crop),
- 'log_id' => $sowLog->id
- ];
- } 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): Res
- {
- 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::HARVESTABLE->value) {
- // throw new \Exception('土地状态不允许收获');
- // }
- // 获取作物信息
- $crop = FarmCrop::where('land_id', $landId)->first();
- if (!$crop) {
- throw new \Exception('作物不存在');
- }
- // 检查作物生长阶段
- if ($crop->growth_stage !== GROWTH_STAGE::MATURE) {
- throw new \Exception('作物未成熟,不能收获');
- }
- // 获取种子信息
- $seed = $crop->seed;
- if (!$seed) {
- throw new \Exception('种子信息不存在');
- }
- // 使用发芽期确定的最终产出果实ID,如果没有则随机选择
- if ($crop->final_output_item_id) {
- $outputItemId = $crop->final_output_item_id;
- // 获取对应的产出配置来确定数量范围
- $outputInfo = $this->getOutputInfoByItemId($seed->id, $outputItemId);
- $outputAmount = mt_rand($outputInfo['min_amount'], $outputInfo['max_amount']);
- Log::info('使用发芽期确定的最终产出果实', [
- 'crop_id' => $crop->id,
- 'final_output_item_id' => $outputItemId,
- 'output_amount' => $outputAmount
- ]);
- } else {
- // 兼容旧数据:如果没有预设的最终产出果实ID,则随机选择
- $outputInfo = $this->getRandomOutput($seed->id);
- $outputItemId = $outputInfo['item_id'];
- $outputAmount = mt_rand($outputInfo['min_amount'], $outputInfo['max_amount']);
- Log::warning('作物没有预设最终产出果实ID,使用随机选择', [
- 'crop_id' => $crop->id,
- 'seed_id' => $seed->id,
- 'random_output_item_id' => $outputItemId
- ]);
- }
- // 创建收获记录
- $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();
- // 收获后作物进入枯萎期,而不是直接删除
- $oldStage = $crop->growth_stage;
- $crop->growth_stage = GROWTH_STAGE::WITHERED;
- $crop->stage_start_time = now();
- $crop->stage_end_time = null; // 枯萎期没有结束时间
- $crop->fertilized = false; // 重置施肥状态
- $crop->save();
- // 更新土地状态为枯萎状态
- $land->status = LAND_STATUS::WITHERED;
- $land->updateHasCrop();
- $land->save();
- // 触发作物生长阶段变更事件(从成熟期到枯萎期)
- event(new CropGrowthStageChangedEvent($userId, $crop, $oldStage->value, GROWTH_STAGE::WITHERED->value));
- // 触发作物收获事件
- 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,
- 'old_stage' => $oldStage->value,
- 'new_stage' => GROWTH_STAGE::WITHERED->value,
- 'land_status' => LAND_STATUS::WITHERED->value
- ]);
- // 物品入包
- ItemService::addItem($userId, $outputItemId, $outputAmount,[
- 'source'=>'FarmHarve',
- 'FarmHarvestLog'=>$harvestLog->id
- ]);
- return Res::success();
- } catch (\Exception $e) {
- // 回滚事务
- Log::error('作物收获失败', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return Res::error('');
- }
- }
- /**
- * 使用化肥(通过作物ID)
- *
- * @param int $cropId 作物ID
- * @param int $cropGrowthTime 减少的生长时间(秒)
- * @return Res
- */
- public function useFertilizerByCropId(int $cropId, int $cropGrowthTime): Res
- {
- try {
- Helper::check_tr();
- // 获取作物信息(防错误机制:确保作物存在)
- /**
- * @var FarmCrop $crop
- */
- $crop = FarmCrop::find($cropId);
- if (!$crop) {
- throw new \Exception('作物不存在');
- }
- // 防错误机制:基本状态检查,避免意外执行
- if ($crop->fertilized) {
- throw new \Exception('作物已施肥');
- }
- // 更新作物信息
- $crop->fertilized = true;
- // 根据 cropGrowthTime 参数减少当前阶段时间
- if ($crop->stage_end_time) {
- $currentTime = now();
- $endTime = $crop->stage_end_time;
- $remainingTime = $currentTime->diffInSeconds($endTime, false);
- if ($remainingTime > 0) {
- // 确保减少的时间不超过剩余时间
- $reducedTime = min($cropGrowthTime, $remainingTime);
- // 使用copy()方法创建副本,避免修改原始对象
- $newEndTime = $endTime->copy()->subSeconds($reducedTime);
- $crop->stage_end_time = $newEndTime;
- Log::info('化肥减少生长时间', [
- 'crop_id' => $crop->id,
- 'reduced_time' => $reducedTime,
- 'original_end_time' => $endTime->format('Y-m-d H:i:s'),
- 'new_end_time' => $crop->stage_end_time->format('Y-m-d H:i:s'),
- 'stage_start_time' => $crop->stage_start_time ? $crop->stage_start_time->format('Y-m-d H:i:s') : null
- ]);
- event(new CropGrowthStageChangedEvent($crop->user_id, $crop, $crop->growth_stage->value, $crop->growth_stage->value));
- } else {
- Log::warning('作物已经到达或超过结束时间,无法减少生长时间', [
- 'crop_id' => $crop->id,
- 'current_time' => $currentTime->format('Y-m-d H:i:s'),
- 'stage_end_time' => $endTime->format('Y-m-d H:i:s'),
- 'remaining_time' => $remainingTime
- ]);
- }
- }
- $crop->save();
- Log::info('使用化肥成功', [
- 'crop_id' => $crop->id,
- 'user_id' => $crop->user_id,
- 'land_id' => $crop->land_id,
- 'growth_stage' => $crop->growth_stage,
- 'stage_end_time' => $crop->stage_end_time
- ]);
- return Res::success('', [
- 'crop_id' => $crop->id,
- ]);
- } catch (\Exception $e) {
- Log::error('使用化肥失败', [
- 'crop_id' => $cropId,
- 'crop_growth_time' => $cropGrowthTime,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return Res::error('使用化肥失败');
- }
- }
- /**
- * 使用化肥(通过土地ID,兼容旧接口)
- *
- * @param int $userId
- * @param int $landId
- * @param int $crop_growth_time
- * @return Res
- * @deprecated 建议使用 useFertilizerByCropId($cropId, $cropGrowthTime) 方法
- */
- public function useFertilizer(int $userId, int $landId, int $crop_growth_time): Res
- {
- try {
- Helper::check_tr();
- // 获取土地信息(防错误机制:确保土地存在)
- /**
- * @var FarmLand $land
- */
- $land = FarmLand::where('id', $landId)
- ->where('user_id', $userId)
- ->first();
- if (!$land) {
- throw new \Exception('土地不存在');
- }
- // 获取作物信息(防错误机制:确保作物存在)
- /**
- * @var FarmCrop $crop
- */
- $crop = FarmCrop::where('land_id', $landId)->first();
- if (!$crop) {
- throw new \Exception('作物不存在');
- }
- // 防错误机制:基本状态检查,避免意外执行
- // 不进行土地状态验证,只进行作物状态验证
- // if ($land->status !== LAND_STATUS::PLANTING->valueInt()) {
- // Log::warning('土地状态异常,但继续执行施肥', [
- // 'land_id' => $landId,
- // 'expected_status' => LAND_STATUS::PLANTING->valueInt(),
- // 'actual_status' => $land->status
- // ]);
- // }
- 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);
- // 使用copy()方法创建副本,避免修改原始对象
- $newEndTime = $endTime->copy()->subSeconds($reducedTime);
- $crop->stage_end_time = $newEndTime;
- 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()
- ]);
- } else {
- Log::warning('作物已经到达或超过结束时间,无法减少生长时间', [
- 'crop_id' => $crop->id,
- 'current_time' => $currentTime->toDateTimeString(),
- 'stage_end_time' => $endTime->toDateTimeString(),
- 'remaining_time' => $remainingTime
- ]);
- }
- }
- $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 Res::success('',[
- 'crop_id' => $crop->id,
- ]);
- } catch (\Exception $e) {
- Log::error('使用化肥失败', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return Res::error('使用化肥失败');
- }
- }
- /**
- * 清理灾害
- *
- * @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;
- }
- }
- // 如果没有其他活跃灾害,更新土地状态
- $oldLandStatus = $land->status;
- if (!$hasActiveDisaster) {
- $land->status = LAND_STATUS::PLANTING->value;
- $land->updateHasCrop();
- }
- // 保存更改
- $crop->save();
- $land->save();
- // 如果土地状态发生了变化,触发土地状态变更事件
- if ($oldLandStatus !== $land->status) {
- event(new LandStatusChangedEvent($userId, $landId, $oldLandStatus, $land->status));
- }
- // 触发灾害清理事件
- 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 {
- // 检查是否已开启事务
- \UCore\Db\Helper::check_tr();
- // 获取土地信息
- $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) {
- // 如果没有作物但土地状态不是空闲,修正土地状态
- $oldLandStatus = $land->status;
- $land->status = LAND_STATUS::IDLE->value;
- $land->updateHasCrop();
- $land->save();
- // 记录状态变更信息,由调用方处理事件触发
- Log::info('土地状态已修正', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'old_status' => $oldLandStatus,
- 'new_status' => $land->status
- ]);
- return true;
- }
- // 删除作物记录
- $crop->delete();
- // 记录旧状态
- $oldLandStatus = $land->status;
- // 更新土地状态
- $land->status = LAND_STATUS::IDLE->value;
- $land->updateHasCrop();
- $land->save();
- // 记录状态变更信息,由调用方处理事件触发和事务提交
- Log::info('铲除作物成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'crop_id' => $crop->id,
- 'old_status' => $oldLandStatus,
- 'new_status' => $land->status
- ]);
- return true;
- } catch (\Exception $e) {
- Log::error('铲除作物失败', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- throw $e; // 重新抛出异常,由调用方处理事务回滚
- }
- }
- /**
- * 更新作物生长阶段
- *
- * @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; // 重置施肥状态
- // 如果进入发芽期,必须确定最终产出果实ID
- if ($newStage === GROWTH_STAGE::SPROUT->value) {
- if (!$crop->final_output_item_id) {
- $seed = $crop->seed;
- // 如果是神秘种子,使用土地影响逻辑
- if ($seed && $seed->type == \App\Module\Farm\Enums\SEED_TYPE::MYSTERIOUS->value) {
- $land = $crop->land;
- $mysteryLogic = new \App\Module\Farm\Logics\MysterySeeLLogic();
- $selectedOutput = $mysteryLogic->selectFinalOutput($seed->id, $land->land_type);
- $crop->final_output_item_id = $selectedOutput['item_id'];
- Log::info('神秘种子确定最终产出(基于土地影响)', [
- 'crop_id' => $crop->id,
- 'user_id' => $crop->user_id,
- 'seed_id' => $seed->id,
- 'land_type' => $land->land_type,
- 'final_output_item_id' => $selectedOutput['item_id']
- ]);
- } else {
- // 普通种子使用原有逻辑
- $outputInfo = $this->getRandomOutput($crop->seed_id);
- $crop->final_output_item_id = $outputInfo['item_id'];
- Log::info('作物进入发芽期,确定最终产出果实', [
- 'crop_id' => $crop->id,
- 'user_id' => $crop->user_id,
- 'seed_id' => $crop->seed_id,
- 'final_output_item_id' => $crop->final_output_item_id
- ]);
- }
- }
- }
- // 验证:如果进入成熟期但没有final_output_item_id,这是一个严重错误
- if ($newStage === GROWTH_STAGE::MATURE->value && !$crop->final_output_item_id) {
- Log::error('严重错误:作物进入成熟期但没有确定最终产出果实ID', [
- 'crop_id' => $crop->id,
- 'user_id' => $crop->user_id,
- 'seed_id' => $crop->seed_id,
- 'current_stage' => $oldStage,
- 'new_stage' => $newStage
- ]);
- throw new \Exception("作物ID {$crop->id} 进入成熟期但没有确定最终产出果实ID,这是系统错误");
- }
- $crop->save();
- // 如果进入枯萎期,需要更新土地状态
- if ($newStage === GROWTH_STAGE::WITHERED->value) {
- $land = $crop->land;
- if ($land) {
- $land->status = LAND_STATUS::WITHERED;
- $land->updateHasCrop();
- $land->save();
- Log::info('作物进入枯萎期,更新土地状态', [
- 'crop_id' => $crop->id,
- 'land_id' => $land->id,
- 'land_status' => LAND_STATUS::WITHERED->value
- ]);
- }
- }
- // 触发生长阶段变更事件
- event(new CropGrowthStageChangedEvent($crop->user_id, $crop, $oldStage->value, $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
- */
- public function calculateNextStage(FarmCrop $crop): int
- {
- $currentStage = $crop->growth_stage;
- // 如果当前是成熟期,检查是否应该进入枯萎期
- $currentStageValue = is_object($currentStage) ? $currentStage->value : $currentStage;
- if ($currentStageValue === GROWTH_STAGE::MATURE->value) {
- // 如果成熟期已经超过结束时间,则进入枯萎期
- if ($crop->stage_end_time && now() >= $crop->stage_end_time) {
- return GROWTH_STAGE::WITHERED->value;
- }
- // 否则保持成熟期
- return GROWTH_STAGE::MATURE->value;
- }
- // 使用阶段映射确定下一个阶段
- $stageMap = [
- GROWTH_STAGE::SEED->value => GROWTH_STAGE::SPROUT->value,
- GROWTH_STAGE::SPROUT->value => GROWTH_STAGE::GROWTH->value,
- GROWTH_STAGE::GROWTH->value => GROWTH_STAGE::MATURE->value,
- GROWTH_STAGE::MATURE->value => GROWTH_STAGE::WITHERED->value,
- GROWTH_STAGE::WITHERED->value => GROWTH_STAGE::WITHERED->value, // 枯萎期保持不变
- ];
- // 确保返回整数值
- $currentStageValue = is_object($currentStage) ? $currentStage->value : $currentStage;
- return $stageMap[$currentStageValue] ?? GROWTH_STAGE::WITHERED->value;
- }
- /**
- * 计算阶段结束时间
- *
- * @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:
- // 成熟期没有 时间限制
- // return $now->addHours(24);
- return null;
- case GROWTH_STAGE::WITHERED->value:
- // 枯萎期没有结束时间
- return null;
- default:
- return null;
- }
- }
- /**
- * 获取随机产出
- *
- * @param int $seedId
- * @return array
- */
- public 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,
- ];
- }
- /**
- * 根据物品ID获取产出配置信息
- *
- * @param int $seedId
- * @param int $itemId
- * @return array
- */
- private function getOutputInfoByItemId(int $seedId, int $itemId): array
- {
- // 获取种子的所有产出配置
- $outputs = FarmSeedOutput::where('seed_id', $seedId)->get();
- // 查找匹配的产出配置
- $targetOutput = $outputs->firstWhere('item_id', $itemId);
- if ($targetOutput) {
- return [
- 'item_id' => $targetOutput->item_id,
- 'min_amount' => $targetOutput->min_amount,
- 'max_amount' => $targetOutput->max_amount,
- ];
- }
- // 如果没有找到匹配的产出配置,使用种子的默认产出
- $seed = FarmSeed::find($seedId);
- return [
- 'item_id' => $itemId, // 使用传入的物品ID
- 'min_amount' => $seed->min_output,
- 'max_amount' => $seed->max_output,
- ];
- }
- }
|