| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073 |
- <?php
- namespace App\Module\Pet\Logic;
- use App\Module\Farm\Dtos\LandInfoDto;
- use App\Module\Pet\Models\PetActiveSkill;
- use App\Module\Farm\Services\CropService;
- use App\Module\Farm\Services\LandService;
- use App\Module\GameItems\Services\ItemService;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use UCore\Dto\Res;
- /**
- * 宠物自动技能处理逻辑
- *
- * 处理宠物激活技能的自动执行逻辑
- */
- class PetAutoSkillLogic
- {
- /**
- * 处理自动收菜技能
- *
- * @param PetActiveSkill $activeSkill 激活的技能
- * @return void
- */
- public function processAutoHarvest(PetActiveSkill $activeSkill): void
- {
- try {
- $pet = $activeSkill->pet;
- $userId = $pet->user_id;
- Log::info('开始处理自动收菜技能', [
- 'active_skill_id' => $activeSkill->id,
- 'pet_id' => $pet->id,
- 'user_id' => $userId
- ]);
- // 首先清理所有枯萎的作物(不使用道具)
- $witheredClearCount = $this->clearAllWitheredCrops($userId);
- // 获取用户所有可收获的土地
- $harvestableLands = LandService::getHarvestableLands($userId);
- $harvestCount = 0;
- $harvestResults = [];
- if (!$harvestableLands->isEmpty()) {
- foreach ($harvestableLands as $land) {
- try {
- // 开启事务处理单个土地的收获
- DB::beginTransaction();
- // 调用收获服务
- $result = CropService::harvestCrop($userId, $land->id);
- if ($result instanceof Res && !$result->error) {
- $harvestCount++;
- $harvestResults[] = [
- 'land_id' => $land->id,
- 'success' => true,
- 'auto_cleared' => false
- ];
- Log::info('自动收菜成功', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id
- ]);
- // 收获后自动铲除枯萎的作物
- $clearResult = $this->autoClearWitheredCrop($userId, $land->id);
- if ($clearResult) {
- $harvestResults[count($harvestResults) - 1]['auto_cleared'] = true;
- Log::info('自动铲除枯萎作物成功', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id
- ]);
- }
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Log::warning('自动收菜失败', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id,
- 'error' => $e->getMessage()
- ]);
- }
- }
- }
- // 统计自动铲除的数量
- $autoClearedCount = array_sum(array_column($harvestResults, 'auto_cleared'));
- // 记录统计信息
- $this->recordSkillStatistics($activeSkill, 'auto_harvest', [
- 'harvest_count' => $harvestCount,
- 'auto_cleared_count' => $autoClearedCount,
- 'withered_cleared_count' => $witheredClearCount,
- 'total_lands_checked' => $harvestableLands->count(),
- 'harvest_results' => $harvestResults
- ]);
- Log::info('自动收菜技能处理完成', [
- 'active_skill_id' => $activeSkill->id,
- 'pet_id' => $pet->id,
- 'user_id' => $userId,
- 'harvest_count' => $harvestCount,
- 'auto_cleared_count' => $autoClearedCount,
- 'withered_cleared_count' => $witheredClearCount,
- 'total_lands' => $harvestableLands->count()
- ]);
- } catch (\Exception $e) {
- Log::error('处理自动收菜技能失败', [
- 'active_skill_id' => $activeSkill->id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- }
- /**
- * 处理自动播种技能
- *
- * @param PetActiveSkill $activeSkill 激活的技能
- * @return void
- */
- public function processAutoPlant(PetActiveSkill $activeSkill): void
- {
- try {
- $pet = $activeSkill->pet;
- $userId = $pet->user_id;
- Log::info('开始处理自动播种技能', [
- 'active_skill_id' => $activeSkill->id,
- 'pet_id' => $pet->id,
- 'user_id' => $userId
- ]);
- // 获取用户所有空闲的土地
- $idleLands = LandService::getIdleLands($userId);
- if ($idleLands->isEmpty()) {
- Log::info('没有空闲的土地', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id
- ]);
- return;
- }
- // 获取优先使用的种子列表
- $preferredSeeds = $activeSkill->getConfigValue('preferred_seeds', []);
- // 获取用户拥有的种子物品
- $availableSeeds = $this->getAvailableSeeds($userId, $preferredSeeds);
- if (empty($availableSeeds)) {
- Log::info('没有可用的种子', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id
- ]);
- return;
- }
- $plantCount = 0;
- $plantResults = [];
- foreach ($idleLands as $land) {
- if (empty($availableSeeds)) {
- break; // 种子用完了
- }
- try {
- // 选择种子(优先使用配置的种子)
- $seedItemId = array_shift($availableSeeds);
- // 开启事务处理单个土地的播种
- DB::beginTransaction();
- // 先消耗种子物品
- ItemService::consumeItem($userId, $seedItemId, null, 1, [
- 'source' => 'pet_auto_plant'
- ]);
- // 调用种植服务
- $result = CropService::plantCrop($userId, $land->id, $seedItemId);
- if ($result) {
- $plantCount++;
- $plantResults[] = [
- 'land_id' => $land->id,
- 'seed_item_id' => $seedItemId,
- 'result' => $result
- ];
- Log::info('自动播种成功', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id,
- 'seed_item_id' => $seedItemId
- ]);
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Log::warning('自动播种失败', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id,
- 'seed_item_id' => $seedItemId ?? null,
- 'error' => $e->getMessage()
- ]);
- }
- }
- // 记录统计信息
- $this->recordSkillStatistics($activeSkill, 'auto_plant', [
- 'plant_count' => $plantCount,
- 'total_lands_checked' => $idleLands->count(),
- 'plant_results' => $plantResults
- ]);
- Log::info('自动播种技能处理完成', [
- 'active_skill_id' => $activeSkill->id,
- 'pet_id' => $pet->id,
- 'user_id' => $userId,
- 'plant_count' => $plantCount,
- 'total_lands' => $idleLands->count()
- ]);
- } catch (\Exception $e) {
- Log::error('处理自动播种技能失败', [
- 'active_skill_id' => $activeSkill->id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- }
- /**
- * 获取用户可用的种子
- *
- * @param int $userId 用户ID
- * @param array $preferredSeeds 优先种子列表
- * @return array 可用种子ID列表
- */
- protected function getAvailableSeeds(int $userId, array $preferredSeeds = []): array
- {
- // 调用物品服务获取用户拥有的种子
- $allSeeds = ItemService::getUserSeedItems($userId);
- $availableSeeds = [];
- // 优先添加配置的种子
- foreach ($preferredSeeds as $seedId) {
- if (isset($allSeeds[$seedId]) && $allSeeds[$seedId] > 0) {
- for ($i = 0; $i < $allSeeds[$seedId]; $i++) {
- $availableSeeds[] = $seedId;
- }
- }
- }
- // 添加其他种子
- foreach ($allSeeds as $seedId => $quantity) {
- if (!in_array($seedId, $preferredSeeds) && $quantity > 0) {
- for ($i = 0; $i < $quantity; $i++) {
- $availableSeeds[] = $seedId;
- }
- }
- }
- return $availableSeeds;
- }
- /**
- * 获取清除灾害的道具
- *
- * @param int $userId 用户ID
- * @param int $disasterType 灾害类型
- * @return array|null 道具信息
- */
- protected function getDisasterClearItem(int $userId, int $disasterType): ?array
- {
- // 根据灾害类型获取对应的清除道具ID
- $clearItemMap = [
- \App\Module\Farm\Enums\DISASTER_TYPE::DROUGHT->value => 24, // 干旱清除道具ID(洒水壶)
- \App\Module\Farm\Enums\DISASTER_TYPE::PEST->value => 23, // 虫害清除道具ID(杀虫剂)
- \App\Module\Farm\Enums\DISASTER_TYPE::WEED->value => 22, // 杂草清除道具ID(除草剂)
- ];
- $itemId = $clearItemMap[$disasterType] ?? null;
- if (!$itemId) {
- return null;
- }
- // 检查用户是否拥有该道具
- $checkResult = \App\Module\GameItems\Services\ItemService::checkItemQuantity($userId, $itemId, 1);
- if ($checkResult->error) {
- return null;
- }
- return [
- 'item_id' => $itemId,
- 'disaster_type' => $disasterType
- ];
- }
- /**
- * 处理自动除草技能
- *
- * @param PetActiveSkill $activeSkill 激活的技能
- * @return void
- */
- public function processAutoWeeding(PetActiveSkill $activeSkill): void
- {
- try {
- $pet = $activeSkill->pet;
- $userId = $pet->user_id;
- Log::info('开始处理自动除草技能', [
- 'active_skill_id' => $activeSkill->id,
- 'pet_id' => $pet->id,
- 'user_id' => $userId
- ]);
- // 获取用户所有有作物的土地
- $landsWithCrops = LandService::getLandsWithCrops($userId);
- if ($landsWithCrops->isEmpty()) {
- Log::info('没有种植作物的土地', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id
- ]);
- return;
- }
- $weedingCount = 0;
- $disasterType = \App\Module\Farm\Enums\DISASTER_TYPE::WEED->value;
- foreach ($landsWithCrops as $land) {
- try {
- // 检查土地是否有杂草灾害
- $hasWeedDisaster = $this->checkSpecificDisaster($land, $disasterType);
- if ($hasWeedDisaster) {
- // 自动清除杂草灾害
- $cleared = $this->autoClearSpecificDisaster($userId, $land, $disasterType);
- if ($cleared) {
- $weedingCount++;
- Log::info('自动除草成功', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id
- ]);
- }
- }
- } catch (\Exception $e) {
- Log::warning('自动除草处理失败', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id,
- 'error' => $e->getMessage()
- ]);
- }
- }
- // 记录统计信息
- $this->recordSkillStatistics($activeSkill, 'auto_weeding', [
- 'weeding_count' => $weedingCount,
- 'total_lands_checked' => $landsWithCrops->count()
- ]);
- Log::info('自动除草技能处理完成', [
- 'active_skill_id' => $activeSkill->id,
- 'pet_id' => $pet->id,
- 'user_id' => $userId,
- 'weeding_count' => $weedingCount,
- 'total_lands' => $landsWithCrops->count()
- ]);
- } catch (\Exception $e) {
- Log::error('处理自动除草技能失败', [
- 'active_skill_id' => $activeSkill->id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- }
- /**
- * 处理自动浇水技能
- *
- * @param PetActiveSkill $activeSkill 激活的技能
- * @return void
- */
- public function processAutoWatering(PetActiveSkill $activeSkill): void
- {
- try {
- $pet = $activeSkill->pet;
- $userId = $pet->user_id;
- Log::info('开始处理自动浇水技能', [
- 'active_skill_id' => $activeSkill->id,
- 'pet_id' => $pet->id,
- 'user_id' => $userId
- ]);
- // 获取用户所有有作物的土地
- $landsWithCrops = LandService::getLandsWithCrops($userId);
- if ($landsWithCrops->isEmpty()) {
- Log::info('没有种植作物的土地', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id
- ]);
- return;
- }
- $wateringCount = 0;
- $disasterType = \App\Module\Farm\Enums\DISASTER_TYPE::DROUGHT->value;
- foreach ($landsWithCrops as $land) {
- try {
- // 检查土地是否有干旱灾害
- $hasDroughtDisaster = $this->checkSpecificDisaster($land, $disasterType);
- if ($hasDroughtDisaster) {
- // 自动清除干旱灾害
- $cleared = $this->autoClearSpecificDisaster($userId, $land, $disasterType);
- if ($cleared) {
- $wateringCount++;
- Log::info('自动浇水成功', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id
- ]);
- }
- }
- } catch (\Exception $e) {
- Log::warning('自动浇水处理失败', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id,
- 'error' => $e->getMessage()
- ]);
- }
- }
- // 记录统计信息
- $this->recordSkillStatistics($activeSkill, 'auto_watering', [
- 'watering_count' => $wateringCount,
- 'total_lands_checked' => $landsWithCrops->count()
- ]);
- Log::info('自动浇水技能处理完成', [
- 'active_skill_id' => $activeSkill->id,
- 'pet_id' => $pet->id,
- 'user_id' => $userId,
- 'watering_count' => $wateringCount,
- 'total_lands' => $landsWithCrops->count()
- ]);
- } catch (\Exception $e) {
- Log::error('处理自动浇水技能失败', [
- 'active_skill_id' => $activeSkill->id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- }
- /**
- * 处理自动杀虫技能
- *
- * @param PetActiveSkill $activeSkill 激活的技能
- * @return void
- */
- public function processAutoPestControl(PetActiveSkill $activeSkill): void
- {
- try {
- $pet = $activeSkill->pet;
- $userId = $pet->user_id;
- Log::info('开始处理自动杀虫技能', [
- 'active_skill_id' => $activeSkill->id,
- 'pet_id' => $pet->id,
- 'user_id' => $userId
- ]);
- // 获取用户所有有作物的土地
- $landsWithCrops = LandService::getLandsWithCrops($userId);
- if ($landsWithCrops->isEmpty()) {
- Log::info('没有种植作物的土地', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id
- ]);
- return;
- }
- Log::info('开始处理自动杀虫技能', [
- 'land——number' => $landsWithCrops->count()
- ]);
- $pestControlCount = 0;
- $disasterType = \App\Module\Farm\Enums\DISASTER_TYPE::PEST->value;
- foreach ($landsWithCrops as $land) {
- try {
- // 检查土地是否有虫害灾害
- $hasPestDisaster = $this->checkSpecificDisaster($land, $disasterType);
- if ($hasPestDisaster) {
- // 自动清除虫害灾害
- $cleared = $this->autoClearSpecificDisaster($userId, $land, $disasterType);
- if ($cleared) {
- $pestControlCount++;
- Log::info('自动杀虫成功', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id
- ]);
- }
- }
- } catch (\Exception $e) {
- Log::warning('自动杀虫处理失败', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id,
- 'error' => $e->getMessage()
- ]);
- }
- }
- // 记录统计信息
- $this->recordSkillStatistics($activeSkill, 'auto_pest_control', [
- 'pest_control_count' => $pestControlCount,
- 'total_lands_checked' => $landsWithCrops->count()
- ]);
- Log::info('自动杀虫技能处理完成', [
- 'active_skill_id' => $activeSkill->id,
- 'pet_id' => $pet->id,
- 'user_id' => $userId,
- 'pest_control_count' => $pestControlCount,
- 'total_lands' => $landsWithCrops->count()
- ]);
- } catch (\Exception $e) {
- Log::error('处理自动杀虫技能失败', [
- 'active_skill_id' => $activeSkill->id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- }
- /**
- * 检查特定类型的灾害
- *
- * @param mixed $land 土地对象
- * @param int $disasterType 灾害类型
- * @return bool
- */
- protected function checkSpecificDisaster(LandInfoDto $land, int $disasterType): bool
- {
- // 检查土地状态是否为灾害状态
- if ($land->status !== \App\Module\Farm\Enums\LAND_STATUS::DISASTER->value) {
- return false;
- }
- // 获取土地上的作物
- $crop = $land->crop;
- if (!$crop) {
- return false;
- }
- // 检查作物是否有指定类型的活跃灾害
- $disasters = $crop->disasters ?? [];
- foreach ($disasters as $disaster) {
- if (($disaster['status'] ?? '') === 'active' && ($disaster['type'] ?? 0) == $disasterType) {
- return true;
- }
- }
- return false;
- }
- /**
- * 自动清除特定类型的灾害
- *
- * @param int $userId 用户ID
- * @param mixed $land 土地对象
- * @param int $disasterType 灾害类型
- * @return bool
- */
- protected function autoClearSpecificDisaster(int $userId, $land, int $disasterType): bool
- {
- try {
- // 获取对应的清除道具
- $clearItem = $this->getDisasterClearItem($userId, $disasterType);
- if (!$clearItem) {
- Log::debug('没有找到清除道具', [
- 'user_id' => $userId,
- 'land_id' => $land->id,
- 'disaster_type' => $disasterType
- ]);
- return false;
- }
- // 开启事务
- DB::beginTransaction();
- // 先消耗道具
- \App\Module\GameItems\Services\ItemService::consumeItem(
- $userId,
- $clearItem['item_id'],
- null,
- 1,
- ['source' => 'pet_auto_specific_disaster_clear']
- );
- // 调用农场服务清除灾害
- $result = \App\Module\Farm\Services\CropService::clearDisaster($userId, $land->id, $disasterType);
- if ($result) {
- DB::commit();
- Log::info('宠物自动清除特定灾害成功', [
- 'user_id' => $userId,
- 'land_id' => $land->id,
- 'disaster_type' => $disasterType,
- 'item_id' => $clearItem['item_id']
- ]);
- return true;
- } else {
- DB::rollback();
- return false;
- }
- } catch (\Exception $e) {
- DB::rollback();
- Log::warning('宠物自动清除特定灾害失败', [
- 'user_id' => $userId,
- 'land_id' => $land->id,
- 'disaster_type' => $disasterType,
- 'error' => $e->getMessage()
- ]);
- return false;
- }
- }
- /**
- * 记录技能统计信息
- *
- * @param PetActiveSkill $activeSkill 激活的技能
- * @param string $actionType 操作类型
- * @param array $statistics 统计数据
- * @return void
- */
- protected function recordSkillStatistics(PetActiveSkill $activeSkill, string $actionType, array $statistics): void
- {
- $config = $activeSkill->config;
- // 确保config是数组类型
- if (!is_array($config)) {
- // 如果是字符串,尝试解析JSON
- if (is_string($config)) {
- $config = json_decode($config, true);
- if (json_last_error() !== JSON_ERROR_NONE) {
- $config = [];
- }
- } else {
- $config = [];
- }
- }
- if (!isset($config['statistics'])) {
- $config['statistics'] = [];
- }
- $config['statistics'][] = [
- 'action_type' => $actionType,
- 'timestamp' => now()->toDateTimeString(),
- 'data' => $statistics
- ];
- // 只保留最近10条统计记录
- if (count($config['statistics']) > 10) {
- $config['statistics'] = array_slice($config['statistics'], -10);
- }
- $activeSkill->config = $config;
- $activeSkill->save();
- }
- /**
- * 清理所有枯萎的作物(不使用道具)
- *
- * @param int $userId 用户ID
- * @return int 清理的数量
- */
- protected function clearAllWitheredCrops(int $userId): int
- {
- try {
- // 获取所有枯萎状态的土地
- $witheredLands = \App\Module\Farm\Models\FarmLand::where('user_id', $userId)
- ->where('status', \App\Module\Farm\Enums\LAND_STATUS::WITHERED->value)
- ->get();
- $clearedCount = 0;
- foreach ($witheredLands as $land) {
- try {
- // 开启事务处理单个土地的清理
- DB::beginTransaction();
- $cleared = $this->autoClearWitheredCrop($userId, $land->id);
- if ($cleared) {
- $clearedCount++;
- Log::info('自动清理枯萎作物成功', [
- 'user_id' => $userId,
- 'land_id' => $land->id
- ]);
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Log::warning('自动清理枯萎作物失败', [
- 'user_id' => $userId,
- 'land_id' => $land->id,
- 'error' => $e->getMessage()
- ]);
- }
- }
- if ($clearedCount > 0) {
- Log::info('批量清理枯萎作物完成', [
- 'user_id' => $userId,
- 'cleared_count' => $clearedCount,
- 'total_withered_lands' => $witheredLands->count()
- ]);
- }
- return $clearedCount;
- } catch (\Exception $e) {
- Log::error('批量清理枯萎作物失败', [
- 'user_id' => $userId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return 0;
- }
- }
- /**
- * 自动铲除枯萎的作物
- *
- * @param int $userId 用户ID
- * @param int $landId 土地ID
- * @return bool 是否成功铲除
- */
- protected function autoClearWitheredCrop(int $userId, int $landId): bool
- {
- try {
- // 获取土地信息
- $land = \App\Module\Farm\Models\FarmLand::where('id', $landId)
- ->where('user_id', $userId)
- ->first();
- if (!$land) {
- return false;
- }
- // 检查土地状态是否为枯萎状态
- if ($land->status !== \App\Module\Farm\Enums\LAND_STATUS::WITHERED->value) {
- return false;
- }
- // 获取土地上的作物
- $crop = \App\Module\Farm\Models\FarmCrop::where('land_id', $landId)->first();
- if (!$crop) {
- // 如果没有作物但土地状态是枯萎,修正土地状态为空闲
- $land->status = \App\Module\Farm\Enums\LAND_STATUS::IDLE->value;
- $land->save();
- return true;
- }
- // 检查作物是否为枯萎状态
- $cropStageValue = is_object($crop->growth_stage) ? $crop->growth_stage->value : $crop->growth_stage;
- if ($cropStageValue !== \App\Module\Farm\Enums\GROWTH_STAGE::WITHERED->value) {
- return false;
- }
- // 调用农场服务铲除作物
- $result = \App\Module\Farm\Services\CropService::removeCrop($userId, $landId);
- if ($result) {
- Log::info('宠物自动铲除枯萎作物成功', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'crop_id' => $crop->id
- ]);
- return true;
- }
- return false;
- } catch (\Exception $e) {
- Log::warning('宠物自动铲除枯萎作物失败', [
- 'user_id' => $userId,
- 'land_id' => $landId,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return false;
- }
- }
- /**
- * 处理自动施肥技能
- *
- * @param PetActiveSkill $activeSkill 激活的技能
- * @return void
- */
- public function processAutoFertilizing(PetActiveSkill $activeSkill): void
- {
- try {
- $pet = $activeSkill->pet;
- $userId = $pet->user_id;
- Log::info('开始处理自动施肥技能', [
- 'active_skill_id' => $activeSkill->id,
- 'pet_id' => $pet->id,
- 'user_id' => $userId
- ]);
- // 获取用户所有有作物的土地
- $landsWithCrops = LandService::getLandsWithCrops($userId);
- if ($landsWithCrops->isEmpty()) {
- Log::info('没有种植作物的土地', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id
- ]);
- return;
- }
- $fertilizingCount = 0;
- $fertilizingResults = [];
- foreach ($landsWithCrops as $land) {
- try {
- // 检查土地是否可以施肥
- $canFertilize = $this->checkCanFertilize($land);
- if ($canFertilize) {
- // 自动施肥
- $fertilized = $this->autoFertilizeCrop($userId, $land);
- if ($fertilized) {
- $fertilizingCount++;
- $fertilizingResults[] = [
- 'land_id' => $land->id,
- 'success' => true
- ];
- Log::info('自动施肥成功', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id
- ]);
- }
- }
- } catch (\Exception $e) {
- Log::warning('自动施肥处理失败', [
- 'user_id' => $userId,
- 'pet_id' => $pet->id,
- 'land_id' => $land->id,
- 'error' => $e->getMessage()
- ]);
- }
- }
- // 记录技能统计信息
- $this->recordSkillStatistics($activeSkill, 'auto_fertilizing', [
- 'fertilizing_count' => $fertilizingCount,
- 'total_lands_checked' => $landsWithCrops->count(),
- 'fertilizing_results' => $fertilizingResults
- ]);
- Log::info('自动施肥技能处理完成', [
- 'active_skill_id' => $activeSkill->id,
- 'pet_id' => $pet->id,
- 'user_id' => $userId,
- 'fertilizing_count' => $fertilizingCount,
- 'total_lands_checked' => $landsWithCrops->count()
- ]);
- } catch (\Exception $e) {
- Log::error('自动施肥技能处理异常', [
- 'active_skill_id' => $activeSkill->id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- }
- /**
- * 检查作物是否可以施肥
- *
- * @param mixed $land 土地对象
- * @return bool
- */
- protected function checkCanFertilize($land): bool
- {
- try {
- // 获取土地上的作物
- $crop = \App\Module\Farm\Models\FarmCrop::where('land_id', $land->id)->first();
- if (!$crop) {
- return false;
- }
- // 检查作物是否已经施肥
- if ($crop->fertilized) {
- return false;
- }
- // 检查作物生长阶段是否允许施肥(种子期、发芽期、生长期可以施肥)
- $growthStage = is_object($crop->growth_stage) ? $crop->growth_stage->value : $crop->growth_stage;
- $allowedStages = [
- \App\Module\Farm\Enums\GROWTH_STAGE::SEED->value,
- \App\Module\Farm\Enums\GROWTH_STAGE::SPROUT->value,
- \App\Module\Farm\Enums\GROWTH_STAGE::GROWTH->value
- ];
- return in_array($growthStage, $allowedStages);
- } catch (\Exception $e) {
- Log::warning('检查施肥条件失败', [
- 'land_id' => $land->id,
- 'error' => $e->getMessage()
- ]);
- return false;
- }
- }
- /**
- * 自动为作物施肥
- *
- * @param int $userId 用户ID
- * @param mixed $land 土地对象
- * @return bool
- */
- protected function autoFertilizeCrop(int $userId, $land): bool
- {
- try {
- // 获取用户的肥料道具
- $fertilizerItem = $this->getFertilizerItem($userId);
- if (!$fertilizerItem) {
- Log::debug('没有找到肥料道具', [
- 'user_id' => $userId,
- 'land_id' => $land->id
- ]);
- return false;
- }
- // 获取作物信息
- $crop = \App\Module\Farm\Models\FarmCrop::where('land_id', $land->id)->first();
- if (!$crop) {
- return false;
- }
- // 开启事务
- DB::beginTransaction();
- // 先消耗肥料道具
- ItemService::consumeItem(
- $userId,
- $fertilizerItem['item_id'],
- null,
- 1,
- ['source' => 'pet_auto_fertilizing', 'land_id' => $land->id]
- );
- // 使用肥料
- $result = CropService::useFertilizer($crop->id, $fertilizerItem['crop_growth_time']);
- if ($result instanceof Res && !$result->error) {
- DB::commit();
- return true;
- } else {
- DB::rollBack();
- return false;
- }
- } catch (\Exception $e) {
- DB::rollBack();
- Log::warning('自动施肥失败', [
- 'user_id' => $userId,
- 'land_id' => $land->id,
- 'error' => $e->getMessage()
- ]);
- return false;
- }
- }
- /**
- * 获取用户的肥料道具
- *
- * @param int $userId 用户ID
- * @return array|null
- */
- protected function getFertilizerItem(int $userId): ?array
- {
- try {
- // 获取用户所有物品
- $userItems = ItemService::getUserItems($userId);
- foreach ($userItems as $userItem) {
- // 检查物品是否为肥料类型
- $cropGrowthTime = ItemService::getItemNumericAttribute($userItem->itemId, 'crop_growth_time', 0);
- if ($cropGrowthTime > 0 && $userItem->quantity > 0) {
- return [
- 'item_id' => $userItem->itemId,
- 'crop_growth_time' => $cropGrowthTime
- ];
- }
- }
- return null;
- } catch (\Exception $e) {
- Log::warning('获取肥料道具失败', [
- 'user_id' => $userId,
- 'error' => $e->getMessage()
- ]);
- return null;
- }
- }
- }
|