| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <?php
- namespace App\Module\Pet\Factories;
- use App\Module\Pet\Dtos\PetDataDto;
- use App\Module\Pet\Dtos\PetLifeSkillDto;
- use App\Module\Pet\Models\PetUser;
- use App\Module\Pet\Models\PetSkill;
- use App\Module\Pet\Models\PetLevelConfig;
- use App\Module\Pet\Logic\PetLogic;
- /**
- * 宠物DTO工厂类
- *
- * 负责创建宠物相关的DTO对象
- */
- class PetDtoFactory
- {
- /**
- * 创建宠物数据DTO
- *
- * @param PetUser $pet 宠物模型
- * @param int|null $fightingCapacity 战力值,如果为null则会计算
- * @return PetDataDto 宠物数据DTO
- */
- public static function createPetDataDto(PetUser $pet, ?int $fightingCapacity = null): PetDataDto
- {
- // 创建宠物DTO
- $petDto = new PetDataDto();
- $petDto->id = $pet->id;
- $petDto->type_id = $pet->type_id ?? 0; // 如果模型中没有type_id字段,默认为0
- $petDto->name = $pet->name;
- $petDto->level = $pet->level;
- $petDto->exp = $pet->experience;
- $petDto->power = $pet->stamina;
-
- // 获取宠物等级配置
- $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
- $petDto->maxpower = $levelConfig ? $levelConfig->stamina_max : 100;
-
- // 计算战力
- if ($fightingCapacity === null) {
- $petLogic = new PetLogic();
- $fightingCapacity = $petLogic->calculatePower($pet->id);
- }
-
- $petDto->fighting_capacity = $fightingCapacity;
- $petDto->score = $fightingCapacity; // 暂时使用战力作为评分
-
- // 设置品阶和状态
- $petDto->grade = $pet->grade->value;
- $petDto->status = $pet->status->value;
-
- // 获取宠物生活技能
- $petDto->life_skills = self::createPetLifeSkillDtos($pet);
-
- return $petDto;
- }
-
- /**
- * 创建宠物生活技能DTO数组
- *
- * @param PetUser $pet 宠物模型
- * @return array 生活技能DTO数组
- */
- public static function createPetLifeSkillDtos(PetUser $pet): array
- {
- // 获取所有技能
- $allSkills = PetSkill::all();
-
- // 筛选出宠物等级可用的技能
- $availableSkills = $allSkills->filter(function ($skill) use ($pet) {
- return $pet->level >= $skill->min_level;
- });
-
- // 获取技能使用记录,计算冷却时间
- $skillLogs = $pet->skillLogs()
- ->orderBy('used_at', 'desc')
- ->get()
- ->groupBy('skill_id');
-
- $skillDtos = [];
- foreach ($availableSkills as $skill) {
- $lastUsed = null;
- $cooldownRemaining = 0;
- $canUse = true;
-
- if (isset($skillLogs[$skill->id]) && $skillLogs[$skill->id]->count() > 0) {
- $lastUsed = $skillLogs[$skill->id][0]->used_at;
- $cooldownSeconds = $skill->cool_down;
- $secondsSinceLastUse = now()->diffInSeconds($lastUsed);
- $cooldownRemaining = max(0, $cooldownSeconds - $secondsSinceLastUse);
- $canUse = $cooldownRemaining === 0;
- }
-
- // 检查体力是否足够
- if ($pet->stamina < $skill->stamina_cost) {
- $canUse = false;
- }
-
- $skillDto = new PetLifeSkillDto();
- $skillDto->skill_id = $skill->id;
- $skillDto->canuse = $canUse;
- $skillDto->curnum = $cooldownRemaining;
- $skillDto->maxnum = $skill->cool_down;
-
- $skillDtos[] = $skillDto;
- }
-
- return $skillDtos;
- }
- }
|