Ver Fonte

refactor(pet): 重构宠物战斗逻辑

- 移除了未使用的 PetGrade 枚举
- 更新了 PetRemouldEvent 事件,使用整数表示品阶- 新增 PetBattleLogic 类,实现了宠物战斗相关的业务逻辑
- 添加了多种战斗类型的执行方法和计算逻辑
- 实现了宠物战力计算、成功率计算、奖励计算等功能
Your Name há 8 meses atrás
pai
commit
ed184e1a4e

+ 5 - 0
UCore/Db/Helper.php

@@ -7,6 +7,11 @@ use Illuminate\Support\Facades\DB;
 class Helper
 {
 
+    /**
+     * 检查是否已经开启事务
+     * @throws \LogicException
+     * @return void
+     */
     static public function check_tr()
     {
         $level = DB::transactionLevel();

+ 514 - 0
app/Module/Pet/DEV.md

@@ -0,0 +1,514 @@
+# 宠物模块开发计划
+
+## 1. 当前状态分析
+
+宠物模块已经完成了基础框架的搭建,包括:
+
+- 数据库表结构设计和SQL文件生成
+- 基础模型类定义
+- 枚举类定义(PetGrade、PetStatus)
+- 事件类定义(PetBattleEvent、PetLevelUpEvent、PetRemouldEvent、PetSkillUsedEvent、PetStatusChangedEvent)
+- 部分监听器实现(ItemChangedListener、LoginSuccessListener)
+- 后台管理控制器实现
+- 仓库类基础结构
+
+目前模块处于初始阶段,核心业务逻辑尚未实现,包括服务层、逻辑层、验证器等。
+
+## 2. 开发目标
+
+完成宠物模块的核心功能实现,包括:
+
+1. 宠物基础功能:创建、升级、喂养、洗髓
+2. 宠物技能系统:技能解锁、使用、冷却
+3. 与其他模块的集成:物品系统、农场系统、任务系统
+
+注:宠物战斗系统和争霸赛系统暂不开发
+
+## 3. 开发计划
+
+### 3.1 第一阶段:核心服务和逻辑实现(当前)
+
+#### 3.1.1 服务层实现
+
+- [x] **PetService**:对外提供宠物相关服务
+  - [x] 获取用户宠物列表
+  - [x] 创建宠物
+  - [x] 宠物升级
+  - [x] 宠物喂养
+  - [x] 宠物洗髓
+  - [x] 宠物技能使用
+  - [x] 宠物状态管理
+
+#### 3.1.2 逻辑层实现
+
+- [x] **PetLogic**:内部宠物逻辑处理
+  - [x] 宠物创建逻辑
+  - [x] 宠物升级逻辑
+  - [x] 宠物经验计算
+  - [x] 宠物体力恢复
+  - [x] 宠物状态变更
+  - [x] 宠物技能逻辑
+  - [x] 宠物洗髓逻辑
+
+#### 3.1.3 验证器实现
+
+- [x] **PetCreateValidator**:宠物创建验证
+  - [x] 宠物名称验证
+  - [x] 宠物数量限制验证
+
+- [x] **PetLevelUpValidator**:宠物升级验证
+  - [x] 宠物状态验证
+  - [x] 宠物经验验证
+
+- [x] **PetFeedValidator**:宠物喂养验证
+  - [x] 宠物状态验证
+  - [x] 物品类型验证
+
+- [x] **PetRemouldValidator**:宠物洗髓验证
+  - [x] 宠物状态验证
+  - [x] 洗髓道具验证
+
+- [x] **PetSkillUseValidator**:宠物技能使用验证
+  - [x] 技能使用条件验证
+  - [x] 技能冷却验证
+
+- [x] **PetStatusChangeValidator**:宠物状态变更验证
+  - [x] 状态变更规则验证
+
+- [x] **PetFoodValidator**:宠物口粮验证
+  - [x] 根据物品属性判断是否为宠物口粮
+
+### 3.2 第二阶段:事件系统完善
+
+#### 3.2.1 事件系统实现
+
+- [x] **对内监听器**:监听其他模块的事件
+  - [x] **ItemChangedListener**:监听物品变更事件,处理宠物口粮和洗髓道具
+  - [x] **LoginSuccessListener**:监听登录成功事件,处理宠物体力恢复等
+
+- [x] **对外事件**:提供给其他模块监听的事件
+  - [x] **PetStatusChangedEvent**:宠物状态变更事件
+  - [x] **PetLevelUpEvent**:宠物升级事件
+  - [x] **PetRemouldEvent**:宠物洗髓事件
+  - [x] **PetSkillUsedEvent**:宠物技能使用事件
+
+#### 3.2.2 事件注册
+
+- [x] 在PetServiceProvider中注册模块间通信的事件和监听器
+
+### 3.3 第三阶段:宠物技能系统完善
+
+- [ ] **技能效果实现**:实现各种宠物技能效果
+- [ ] **技能解锁机制**:完善技能解锁条件和机制
+- [ ] **技能冷却管理**:优化技能冷却时间管理
+- [ ] **技能使用记录**:完善技能使用记录和统计
+
+### 3.4 第四阶段:与其他模块集成
+
+- [ ] 与物品模块集成:狗粮、洗髓道具等物品处理
+- [ ] 与农场模块集成:宠物技能对农场的影响
+- [ ] 与任务模块集成:宠物相关任务
+
+### 3.5 第五阶段:测试和优化
+
+- [ ] 单元测试编写
+- [ ] 性能优化
+- [ ] 代码重构和优化
+
+## 4. 当前任务
+
+### 4.1 优先实现的功能
+
+1. **宠物技能系统**:完善宠物技能功能
+   - 技能效果实现
+   - 技能解锁机制
+   - 技能冷却管理
+   - 技能使用记录
+
+2. **与农场模块集成**:实现宠物技能对农场的影响
+   - 自动收菜技能
+   - 自动播种技能
+   - 灾害防护技能
+
+3. **与物品模块集成**:完善物品使用效果
+   - 宠物口粮使用效果
+   - 洗髓道具使用效果
+   - 技能道具使用效果
+
+### 4.2 具体实现步骤
+
+1. 完善PetLogic类中的技能效果实现
+2. 实现与农场模块的接口调用
+3. 完善ItemChangedListener,处理更多物品类型
+4. 优化宠物状态管理和事件处理
+5. 添加更多宠物技能类型和效果
+
+## 5. 开发进度跟踪
+
+| 功能模块 | 状态 | 开始日期 | 完成日期 | 备注 |
+|---------|------|---------|---------|------|
+| 数据库设计 | 已完成 | - | - | 包括10个数据表 |
+| 模型定义 | 已完成 | - | - | 包括10个模型类 |
+| 枚举定义 | 已完成 | - | - | PetGrade、PetStatus |
+| 事件定义 | 已完成 | - | - | 5个事件类 |
+| 监听器 | 已完成 | - | - | 已实现5个监听器 |
+| 后台控制器 | 已完成 | - | - | 10个控制器 |
+| 仓库类 | 已完成 | - | - | 10个仓库类 |
+| 服务层 | 已完成 | - | - | 已实现PetService |
+| 逻辑层 | 已完成 | - | - | 已实现PetLogic |
+| 验证器 | 已完成 | - | - | 已实现7个验证器 |
+| 技能系统 | 部分完成 | - | - | 已实现基础功能 |
+| 与其他模块集成 | 部分完成 | - | - | 已实现物品变更监听 |
+
+## 6. 下一步工作计划
+
+1. 完善宠物技能系统
+   - 实现更多技能效果
+   - 优化技能解锁机制
+   - 完善技能冷却管理
+
+2. 加强与农场模块的集成
+   - 实现自动收菜技能
+   - 实现自动播种技能
+   - 实现灾害防护技能
+
+3. 完善与物品模块的集成
+   - 增加更多宠物口粮类型
+   - 增加更多洗髓道具效果
+   - 增加技能道具系统
+
+4. 优化宠物状态管理
+   - 完善状态变更逻辑
+   - 增加状态效果系统
+   - 优化状态变更事件处理
+
+## 7. 注意事项
+
+1. 所有模型类中需要保持无业务逻辑,业务逻辑应放在逻辑层
+2. 服务层类中的所有方法应该是静态方法,对外提供服务
+3. 服务层不负责事务管理,调用方需要自行开启和管理事务
+4. 验证器类应单独实现,不应在模型中进行验证
+5. 事件用于模块间通信,模块内部不应使用事件机制
+6. 宠物模块与物品模块的集成应通过监听物品变更事件实现
+7. 宠物口粮验证应根据物品的pet_power/pet_exp属性判断
+
+## 8. 宠物模块与其他模块的交互
+
+### 8.1 与物品模块的交互
+
+- **监听物品变更事件**:处理宠物口粮、洗髓道具等物品的变更
+- **调用物品服务**:消耗宠物口粮、洗髓道具等物品
+
+### 8.2 与农场模块的交互
+
+- **提供宠物技能服务**:供农场模块调用宠物技能
+- **监听农场事件**:响应农场中的特定事件(如灾害发生)
+
+### 8.3 与任务模块的交互
+
+- **提供宠物状态查询服务**:供任务模块检查宠物相关任务条件
+- **触发任务完成事件**:当宠物达成特定条件时
+
+## 9. 宠物技能系统详细设计
+
+### 9.1 技能类型
+
+1. **自动收菜**:消耗50点体力,冷却2小时,自动收获成熟作物
+2. **自动播种**:消耗50点体力,冷却4小时,自动补种空闲土地
+3. **灾害防护**:消耗30点体力,冷却6小时,防止指定类型自然灾害
+
+### 9.2 技能解锁条件
+
+- **自动收菜**:宠物等级≥5
+- **自动播种**:宠物等级≥10
+- **灾害防护**:宠物等级≥15
+
+### 9.3 技能效果实现
+
+- **自动收菜**:调用农场模块的收获接口
+- **自动播种**:调用农场模块的播种接口
+- **灾害防护**:设置农场模块的灾害防护标志
+
+## 10. 宠物争霸赛系统详细设计
+
+### 10.1 赛季管理
+
+- 赛季创建、开始、结束
+- 奖池设置
+- Boss战力设置
+
+### 10.2 队伍管理
+
+- 队伍创建、解散
+- 成员加入、退出
+- 队伍战力计算
+
+### 10.3 战斗系统
+
+- Boss战斗机制
+- 伤害计算
+- 战斗结果记录
+
+### 10.4 奖励分配
+
+- 首胜奖励模式
+- 伤害占比奖励模式
+- 奖励发放机制
+
+## 11. 宠物喂养系统详细设计
+
+### 11.1 喂养机制
+
+- **普通狗粮**:提供基础经验值
+- **优质狗粮**:提供双倍经验值
+- **特殊狗粮**:提供额外属性加成
+
+### 11.2 喂养效果
+
+- **经验获取**:根据狗粮类型和品质获得不同经验值
+- **体力恢复**:部分狗粮可以恢复宠物体力
+- **状态变更**:喂养过程中宠物状态变为FEEDING
+
+### 11.3 喂养限制
+
+- **冷却时间**:每次喂养后有短暂冷却时间
+- **每日上限**:每日喂养次数有上限
+- **体力消耗**:喂养过程消耗少量体力
+
+## 12. 宠物洗髓系统详细设计
+
+### 12.1 洗髓机制
+
+- **消耗资源**:钻石或特定道具
+- **概率计算**:根据配置的品阶概率进行随机
+- **品阶变更**:可能提升或降低品阶
+
+### 12.2 洗髓效果
+
+- **属性重置**:根据新品阶重新计算属性加成
+- **技能影响**:部分技能可能受品阶影响
+- **外观变化**:不同品阶可能有不同外观
+
+### 12.3 洗髓记录
+
+- **记录保存**:每次洗髓结果记录到pet_remould_logs表
+- **历史查询**:玩家可查看历史洗髓记录
+
+## 13. 宠物战斗系统详细设计
+
+### 13.1 战斗类型
+
+- **偷菜战斗**:宠物参与偷取其他玩家农场作物的战斗
+- **守护战斗**:宠物守护自己农场的战斗
+- **争霸赛战斗**:宠物参与争霸赛的战斗
+
+### 13.2 战力计算
+
+- **基础战力**:根据宠物等级和品阶计算
+- **属性加成**:根据宠物数值属性计算加成
+- **品阶加成**:不同品阶有不同战力加成系数
+- **装备加成**:特殊装备可提供额外战力
+
+### 13.3 战斗结果计算
+
+- **偷菜战斗**:根据攻守双方战力差计算成功率
+- **守护战斗**:根据守护宠物战力计算防御成功率
+- **争霸赛战斗**:根据队伍总战力与Boss战力对比计算伤害
+
+### 13.4 战斗奖励
+
+- **偷菜战斗**:获得作物、经验值
+- **守护战斗**:获得守护奖励、经验值
+- **争霸赛战斗**:根据伤害排名获得奖池奖励
+
+## 14. 宠物模块实现计划
+
+### 14.1 第一周:基础功能实现
+
+| 日期 | 计划任务 | 负责人 |
+|------|---------|-------|
+| 第1天 | 实现PetService基础方法 | - |
+| 第2天 | 实现PetLogic基础逻辑 | - |
+| 第3天 | 实现PetValidator验证器 | - |
+| 第4天 | 实现PetFoodValidator验证器 | - |
+| 第5天 | 完善事件监听器 | - |
+
+### 14.2 第二周:技能系统实现
+
+| 日期 | 计划任务 | 负责人 |
+|------|---------|-------|
+| 第1天 | 实现PetSkillLogic基础逻辑 | - |
+| 第2天 | 实现技能解锁机制 | - |
+| 第3天 | 实现技能冷却管理 | - |
+| 第4天 | 实现技能效果 | - |
+| 第5天 | 与农场模块集成 | - |
+
+### 14.3 第三周:战斗系统实现
+
+| 日期 | 计划任务 | 负责人 |
+|------|---------|-------|
+| 第1天 | 实现PetBattleLogic基础逻辑 | - |
+| 第2天 | 实现战力计算 | - |
+| 第3天 | 实现战斗结果计算 | - |
+| 第4天 | 实现战斗奖励发放 | - |
+| 第5天 | 完善战斗记录 | - |
+
+### 14.4 第四周:争霸赛系统实现
+
+| 日期 | 计划任务 | 负责人 |
+|------|---------|-------|
+| 第1天 | 实现赛季管理 | - |
+| 第2天 | 实现队伍管理 | - |
+| 第3天 | 实现Boss战斗机制 | - |
+| 第4天 | 实现奖励分配 | - |
+| 第5天 | 系统测试与优化 | - |
+
+## 15. 接口设计
+
+### 15.1 服务层接口
+
+```php
+// PetService.php
+class PetService
+{
+    // 获取用户宠物列表
+    public static function getUserPets(int $userId): array;
+
+    // 创建宠物
+    public static function createPet(int $userId, string $name): array;
+
+    // 宠物升级
+    public static function levelUpPet(int $userId, int $petId): array;
+
+    // 宠物喂养
+    public static function feedPet(int $userId, int $petId, int $itemId, int $amount = 1): array;
+
+    // 宠物洗髓
+    public static function remouldPet(int $userId, int $petId, int $itemId = 0): array;
+
+    // 使用宠物技能
+    public static function useSkill(int $userId, int $petId, int $skillId, array $params = []): array;
+
+    // 获取宠物状态
+    public static function getPetStatus(int $userId, int $petId): array;
+
+    // 更新宠物状态
+    public static function updatePetStatus(int $userId, int $petId, int $status, string $reason = ''): bool;
+}
+
+// PetBattleService.php
+class PetBattleService
+{
+    // 获取战斗记录
+    public static function getBattleLogs(int $userId, int $petId, int $page = 1, int $pageSize = 20): array;
+
+    // 发起战斗
+    public static function startBattle(int $userId, int $petId, int $battleType, int $targetId = 0): array;
+
+    // 获取战斗结果
+    public static function getBattleResult(int $battleId): array;
+
+    // 获取当前赛季信息
+    public static function getCurrentSeason(): array;
+
+    // 创建/加入队伍
+    public static function joinTeam(int $userId, int $petId, int $teamId = 0, string $teamName = ''): array;
+
+    // 退出队伍
+    public static function leaveTeam(int $userId, int $petId): bool;
+
+    // 获取队伍信息
+    public static function getTeamInfo(int $teamId): array;
+}
+```
+
+### 15.2 逻辑层接口
+
+```php
+// PetLogic.php
+class PetLogic
+{
+    // 创建宠物
+    public static function createPet(int $userId, string $name): array;
+
+    // 宠物升级
+    public static function levelUpPet(int $petId): array;
+
+    // 计算宠物经验
+    public static function calculateExp(int $petId, int $expGain): array;
+
+    // 恢复宠物体力
+    public static function recoverStamina(int $petId, int $minutes): int;
+
+    // 变更宠物状态
+    public static function changeStatus(int $petId, int $status, string $reason = ''): bool;
+}
+
+// PetSkillLogic.php
+class PetSkillLogic
+{
+    // 检查技能是否解锁
+    public static function checkSkillUnlocked(int $petId, int $skillId): bool;
+
+    // 管理技能冷却
+    public static function manageSkillCooldown(int $petId, int $skillId): array;
+
+    // 执行技能效果
+    public static function executeSkillEffect(int $petId, int $skillId, array $params = []): array;
+}
+```
+
+## 16. 数据结构示例
+
+### 16.1 宠物数据结构
+
+```json
+{
+  "id": 1,
+  "user_id": 1001,
+  "name": "小松狮",
+  "grade": "THIRD",
+  "level": 15,
+  "experience": 2500,
+  "stamina": 85,
+  "status": 1,
+  "created_at": "2023-05-01 10:00:00",
+  "updated_at": "2023-05-05 15:30:00"
+}
+```
+
+### 16.2 技能数据结构
+
+```json
+{
+  "id": 1,
+  "skill_name": "自动收菜",
+  "stamina_cost": 50,
+  "cool_down": 7200,
+  "effect_desc": "自动收获成熟作物",
+  "min_level": 5,
+  "created_at": "2023-05-01 10:00:00",
+  "updated_at": "2023-05-01 10:00:00"
+}
+```
+
+### 16.3 战斗记录数据结构
+
+```json
+{
+  "id": 1,
+  "pet_id": 1,
+  "battle_type": 1,
+  "opponent_id": 2,
+  "result": 1,
+  "reward": {
+    "exp": 100,
+    "items": [
+      {"id": 1001, "amount": 2},
+      {"id": 1002, "amount": 1}
+    ]
+  },
+  "battle_time": "2023-05-05 14:30:00",
+  "created_at": "2023-05-05 14:30:00"
+}
+```

+ 0 - 11
app/Module/Pet/Enums/PetGrade.php

@@ -1,11 +0,0 @@
-<?php
-
-namespace App\Module\Pet\Enums;
-
-enum PetGrade: string
-{
-    case FIRST = 'FIRST';   // 一品
-    case SECOND = 'SECOND'; // 二品
-    case THIRD = 'THIRD';   // 三品
-    case FOURTH = 'FOURTH'; // 四品
-}

+ 9 - 9
app/Module/Pet/Events/PetRemouldEvent.php

@@ -2,14 +2,14 @@
 
 namespace App\Module\Pet\Events;
 
-use App\Module\Pet\Enums\PetGrade;
+
 use Illuminate\Broadcasting\InteractsWithSockets;
 use Illuminate\Foundation\Events\Dispatchable;
 use Illuminate\Queue\SerializesModels;
 
 /**
  * 宠物洗髓事件
- * 
+ *
  * 当宠物进行洗髓操作时触发此事件,允许其他系统响应宠物品阶的变化。
  * 此事件可用于更新宠物属性、记录洗髓日志、处理品阶变化效果等。
  */
@@ -34,27 +34,27 @@ class PetRemouldEvent
     /**
      * 旧品阶
      *
-     * @var PetGrade
+     * @var int
      */
-    public PetGrade $oldGrade;
+    public int $oldGrade;
 
     /**
      * 新品阶
      *
-     * @var PetGrade
+     * @var int
      */
-    public PetGrade $newGrade;
+    public int $newGrade;
 
     /**
      * 创建一个新的事件实例
      *
      * @param int $userId 用户ID
      * @param int $petId 宠物ID
-     * @param PetGrade $oldGrade 旧品阶
-     * @param PetGrade $newGrade 新品阶
+     * @param int $oldGrade 旧品阶
+     * @param int $newGrade 新品阶
      * @return void
      */
-    public function __construct(int $userId, int $petId, PetGrade $oldGrade, PetGrade $newGrade)
+    public function __construct(int $userId, int $petId, int $oldGrade, int $newGrade)
     {
         $this->userId = $userId;
         $this->petId = $petId;

+ 552 - 0
app/Module/Pet/Logic/PetBattleLogic.php

@@ -0,0 +1,552 @@
+<?php
+
+namespace App\Module\Pet\Logic;
+
+use App\Module\Pet\Enums\PetGrade;
+use App\Module\Pet\Models\PetLevelConfig;
+use App\Module\Pet\Models\PetUser;
+use Exception;
+use Illuminate\Support\Facades\Log;
+
+/**
+ * 宠物战斗逻辑类
+ * 
+ * 处理宠物战斗相关的业务逻辑,包括战力计算、战斗结果计算、
+ * 奖励发放等功能。该类是宠物战斗模块内部使用的核心逻辑类,
+ * 不对外提供服务,由PetBattleService调用。
+ */
+class PetBattleLogic
+{
+    /**
+     * 获取战斗体力消耗
+     * 
+     * @param int $battleType 战斗类型
+     * @return int 体力消耗
+     */
+    public function getBattleStaminaCost(int $battleType): int
+    {
+        // 根据战斗类型返回不同的体力消耗
+        switch ($battleType) {
+            case 1: // 偷菜战斗
+                return config('pet.battle_stamina_cost.steal', 10);
+                
+            case 2: // 守护战斗
+                return config('pet.battle_stamina_cost.defend', 15);
+                
+            case 3: // 争霸赛战斗
+                return config('pet.battle_stamina_cost.royale', 20);
+                
+            default:
+                return 10; // 默认消耗10点体力
+        }
+    }
+    
+    /**
+     * 执行战斗
+     * 
+     * @param int $petId 宠物ID
+     * @param int $battleType 战斗类型
+     * @param int $targetId 目标ID
+     * @return array 战斗结果
+     * @throws Exception
+     */
+    public function executeBattle(int $petId, int $battleType, int $targetId): array
+    {
+        // 获取宠物信息
+        $pet = PetUser::findOrFail($petId);
+        
+        // 根据战斗类型执行不同的战斗逻辑
+        switch ($battleType) {
+            case 1: // 偷菜战斗
+                return $this->executeStealBattle($pet, $targetId);
+                
+            case 2: // 守护战斗
+                return $this->executeDefendBattle($pet, $targetId);
+                
+            case 3: // 争霸赛战斗
+                return $this->executeRoyaleBattle($pet, $targetId);
+                
+            default:
+                throw new Exception("未知的战斗类型");
+        }
+    }
+    
+    /**
+     * 执行偷菜战斗
+     * 
+     * @param PetUser $pet 宠物对象
+     * @param int $targetId 目标用户ID
+     * @return array 战斗结果
+     */
+    protected function executeStealBattle(PetUser $pet, int $targetId): array
+    {
+        // 计算宠物战力
+        $petPower = $this->calculatePetPower($pet->id);
+        
+        // 获取目标用户的守护宠物
+        // 这里需要根据实际项目中的农场模块接口进行实现
+        // 暂时使用模拟数据
+        $targetPetPower = 0;
+        $targetPet = null;
+        
+        // 模拟获取目标用户的守护宠物
+        $targetPets = PetUser::where('user_id', $targetId)
+            ->where('status', 1) // 正常状态
+            ->get();
+        
+        if ($targetPets->isNotEmpty()) {
+            // 找出战力最高的宠物作为守护宠物
+            foreach ($targetPets as $tp) {
+                $tp_power = $this->calculatePetPower($tp->id);
+                if ($tp_power > $targetPetPower) {
+                    $targetPetPower = $tp_power;
+                    $targetPet = $tp;
+                }
+            }
+        }
+        
+        // 计算成功率
+        $successRate = $this->calculateStealSuccessRate($petPower, $targetPetPower);
+        
+        // 随机决定是否成功
+        $random = mt_rand(1, 100);
+        $success = $random <= $successRate;
+        
+        // 计算奖励
+        $rewards = [];
+        if ($success) {
+            // 成功偷菜,获得奖励
+            $rewards = $this->calculateStealRewards($pet, $targetId);
+        }
+        
+        // 记录战斗详情
+        $details = [
+            'pet_power' => $petPower,
+            'target_pet_power' => $targetPetPower,
+            'success_rate' => $successRate,
+            'random_roll' => $random,
+            'success' => $success
+        ];
+        
+        // 返回战斗结果
+        return [
+            'success' => $success,
+            'opponent_id' => $targetId,
+            'opponent' => [
+                'user_id' => $targetId,
+                'pet_id' => $targetPet ? $targetPet->id : null,
+                'pet_name' => $targetPet ? $targetPet->name : '无守护宠物',
+                'pet_power' => $targetPetPower
+            ],
+            'rewards' => $rewards,
+            'details' => $details
+        ];
+    }
+    
+    /**
+     * 执行守护战斗
+     * 
+     * @param PetUser $pet 宠物对象
+     * @param int $targetId 目标用户ID
+     * @return array 战斗结果
+     */
+    protected function executeDefendBattle(PetUser $pet, int $targetId): array
+    {
+        // 计算宠物战力
+        $petPower = $this->calculatePetPower($pet->id);
+        
+        // 获取目标用户的偷菜宠物
+        // 这里需要根据实际项目中的农场模块接口进行实现
+        // 暂时使用模拟数据
+        $targetPetPower = mt_rand(800, 1500); // 模拟目标宠物战力
+        
+        // 计算成功率
+        $successRate = $this->calculateDefendSuccessRate($petPower, $targetPetPower);
+        
+        // 随机决定是否成功
+        $random = mt_rand(1, 100);
+        $success = $random <= $successRate;
+        
+        // 计算奖励
+        $rewards = [];
+        if ($success) {
+            // 成功守护,获得奖励
+            $rewards = $this->calculateDefendRewards($pet);
+        }
+        
+        // 记录战斗详情
+        $details = [
+            'pet_power' => $petPower,
+            'target_pet_power' => $targetPetPower,
+            'success_rate' => $successRate,
+            'random_roll' => $random,
+            'success' => $success
+        ];
+        
+        // 返回战斗结果
+        return [
+            'success' => $success,
+            'opponent_id' => $targetId,
+            'opponent' => [
+                'user_id' => $targetId,
+                'pet_power' => $targetPetPower
+            ],
+            'rewards' => $rewards,
+            'details' => $details
+        ];
+    }
+    
+    /**
+     * 执行争霸赛战斗
+     * 
+     * @param PetUser $pet 宠物对象
+     * @param int $targetId 目标Boss ID或对手宠物ID
+     * @return array 战斗结果
+     */
+    protected function executeRoyaleBattle(PetUser $pet, int $targetId): array
+    {
+        // 计算宠物战力
+        $petPower = $this->calculatePetPower($pet->id);
+        
+        // 获取目标Boss或对手宠物信息
+        // 这里需要根据实际项目中的争霸赛系统进行实现
+        // 暂时使用模拟数据
+        $targetPetPower = 0;
+        $targetPet = null;
+        
+        if ($targetId > 0) {
+            // 对战其他宠物
+            $targetPet = PetUser::find($targetId);
+            if ($targetPet) {
+                $targetPetPower = $this->calculatePetPower($targetId);
+            }
+        } else {
+            // 对战Boss
+            $targetPetPower = 5000; // 模拟Boss战力
+        }
+        
+        // 计算成功率
+        $successRate = $this->calculateRoyaleSuccessRate($petPower, $targetPetPower);
+        
+        // 随机决定是否成功
+        $random = mt_rand(1, 100);
+        $success = $random <= $successRate;
+        
+        // 计算奖励
+        $rewards = [];
+        if ($success) {
+            // 战斗胜利,获得奖励
+            $rewards = $this->calculateRoyaleRewards($pet, $targetId);
+        }
+        
+        // 计算造成的伤害(用于争霸赛排名)
+        $damage = $this->calculateRoyaleDamage($petPower, $targetPetPower, $success);
+        
+        // 记录战斗详情
+        $details = [
+            'pet_power' => $petPower,
+            'target_pet_power' => $targetPetPower,
+            'success_rate' => $successRate,
+            'random_roll' => $random,
+            'success' => $success,
+            'damage' => $damage
+        ];
+        
+        // 返回战斗结果
+        return [
+            'success' => $success,
+            'opponent_id' => $targetId,
+            'opponent' => $targetPet ? [
+                'pet_id' => $targetPet->id,
+                'pet_name' => $targetPet->name,
+                'pet_grade' => $targetPet->grade->value,
+                'pet_level' => $targetPet->level,
+                'pet_power' => $targetPetPower
+            ] : [
+                'boss_id' => 0,
+                'boss_name' => 'Boss',
+                'boss_power' => $targetPetPower
+            ],
+            'rewards' => $rewards,
+            'damage' => $damage,
+            'details' => $details
+        ];
+    }
+    
+    /**
+     * 计算宠物战力
+     * 
+     * @param int $petId 宠物ID
+     * @return int 战力值
+     */
+    public function calculatePetPower(int $petId): int
+    {
+        // 获取宠物信息
+        $pet = PetUser::findOrFail($petId);
+        
+        // 获取宠物等级配置
+        $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
+        
+        // 基础战力
+        $basePower = $levelConfig ? ($levelConfig->numeric_attributes['base_power'] ?? 100) : 100;
+        
+        // 品阶加成
+        $gradeBonus = config('pet.grade_attribute_bonus.' . $pet->grade->value, 0);
+        
+        // 计算最终战力
+        $power = $basePower * (1 + $gradeBonus);
+        
+        // 记录日志
+        Log::info('计算宠物战力', [
+            'pet_id' => $petId,
+            'level' => $pet->level,
+            'grade' => $pet->grade->value,
+            'base_power' => $basePower,
+            'grade_bonus' => $gradeBonus,
+            'final_power' => $power
+        ]);
+        
+        return (int)$power;
+    }
+    
+    /**
+     * 计算偷菜成功率
+     * 
+     * @param int $petPower 宠物战力
+     * @param int $targetPetPower 目标宠物战力
+     * @return int 成功率(百分比)
+     */
+    protected function calculateStealSuccessRate(int $petPower, int $targetPetPower): int
+    {
+        // 如果目标没有守护宠物,成功率较高
+        if ($targetPetPower <= 0) {
+            return 80;
+        }
+        
+        // 基础成功率
+        $baseRate = 50;
+        
+        // 根据战力差计算成功率
+        $powerDiff = $petPower - $targetPetPower;
+        $rateAdjustment = $powerDiff / 100; // 每100点战力差调整1%成功率
+        
+        // 最终成功率,限制在10%-90%之间
+        $finalRate = max(10, min(90, $baseRate + $rateAdjustment));
+        
+        return (int)$finalRate;
+    }
+    
+    /**
+     * 计算守护成功率
+     * 
+     * @param int $petPower 宠物战力
+     * @param int $targetPetPower 目标宠物战力
+     * @return int 成功率(百分比)
+     */
+    protected function calculateDefendSuccessRate(int $petPower, int $targetPetPower): int
+    {
+        // 基础成功率
+        $baseRate = 60;
+        
+        // 根据战力差计算成功率
+        $powerDiff = $petPower - $targetPetPower;
+        $rateAdjustment = $powerDiff / 100; // 每100点战力差调整1%成功率
+        
+        // 最终成功率,限制在20%-95%之间
+        $finalRate = max(20, min(95, $baseRate + $rateAdjustment));
+        
+        return (int)$finalRate;
+    }
+    
+    /**
+     * 计算争霸赛成功率
+     * 
+     * @param int $petPower 宠物战力
+     * @param int $targetPetPower 目标宠物战力
+     * @return int 成功率(百分比)
+     */
+    protected function calculateRoyaleSuccessRate(int $petPower, int $targetPetPower): int
+    {
+        // 基础成功率
+        $baseRate = 40;
+        
+        // 根据战力差计算成功率
+        $powerDiff = $petPower - $targetPetPower;
+        $rateAdjustment = $powerDiff / 150; // 每150点战力差调整1%成功率
+        
+        // 最终成功率,限制在5%-85%之间
+        $finalRate = max(5, min(85, $baseRate + $rateAdjustment));
+        
+        return (int)$finalRate;
+    }
+    
+    /**
+     * 计算偷菜奖励
+     * 
+     * @param PetUser $pet 宠物对象
+     * @param int $targetId 目标用户ID
+     * @return array 奖励列表
+     */
+    protected function calculateStealRewards(PetUser $pet, int $targetId): array
+    {
+        // 这里需要根据实际项目中的农场模块接口进行实现
+        // 暂时使用模拟数据
+        
+        // 模拟获取可偷取的作物
+        $availableCrops = [
+            ['item_id' => 1001, 'name' => '小麦', 'max_amount' => 5],
+            ['item_id' => 1002, 'name' => '胡萝卜', 'max_amount' => 3],
+            ['item_id' => 1003, 'name' => '土豆', 'max_amount' => 2]
+        ];
+        
+        // 随机选择1-2种作物
+        $cropCount = mt_rand(1, min(2, count($availableCrops)));
+        $selectedCrops = array_rand($availableCrops, $cropCount);
+        
+        if (!is_array($selectedCrops)) {
+            $selectedCrops = [$selectedCrops];
+        }
+        
+        // 计算偷取数量和经验值
+        $rewards = [
+            'exp' => mt_rand(5, 15), // 获得5-15点经验
+            'items' => []
+        ];
+        
+        foreach ($selectedCrops as $index) {
+            $crop = $availableCrops[$index];
+            $amount = mt_rand(1, $crop['max_amount']);
+            
+            $rewards['items'][] = [
+                'item_id' => $crop['item_id'],
+                'name' => $crop['name'],
+                'amount' => $amount
+            ];
+        }
+        
+        return $rewards;
+    }
+    
+    /**
+     * 计算守护奖励
+     * 
+     * @param PetUser $pet 宠物对象
+     * @return array 奖励列表
+     */
+    protected function calculateDefendRewards(PetUser $pet): array
+    {
+        // 这里需要根据实际项目中的奖励系统进行实现
+        // 暂时使用模拟数据
+        
+        // 计算守护奖励和经验值
+        $rewards = [
+            'exp' => mt_rand(10, 20), // 获得10-20点经验
+            'items' => []
+        ];
+        
+        // 随机获得守护奖励物品
+        $rewardItems = [
+            ['item_id' => 2001, 'name' => '守护徽章', 'probability' => 0.3, 'amount' => 1],
+            ['item_id' => 2002, 'name' => '防御药水', 'probability' => 0.5, 'amount' => 1],
+            ['item_id' => 2003, 'name' => '农场币', 'probability' => 1.0, 'amount_min' => 10, 'amount_max' => 50]
+        ];
+        
+        foreach ($rewardItems as $item) {
+            $random = mt_rand(1, 100) / 100;
+            if ($random <= $item['probability']) {
+                $amount = isset($item['amount_min']) ? 
+                    mt_rand($item['amount_min'], $item['amount_max']) : 
+                    $item['amount'];
+                
+                $rewards['items'][] = [
+                    'item_id' => $item['item_id'],
+                    'name' => $item['name'],
+                    'amount' => $amount
+                ];
+            }
+        }
+        
+        return $rewards;
+    }
+    
+    /**
+     * 计算争霸赛奖励
+     * 
+     * @param PetUser $pet 宠物对象
+     * @param int $targetId 目标ID
+     * @return array 奖励列表
+     */
+    protected function calculateRoyaleRewards(PetUser $pet, int $targetId): array
+    {
+        // 这里需要根据实际项目中的争霸赛系统进行实现
+        // 暂时使用模拟数据
+        
+        // 计算争霸赛奖励和经验值
+        $rewards = [
+            'exp' => mt_rand(20, 40), // 获得20-40点经验
+            'items' => []
+        ];
+        
+        // 如果是击败Boss,获得更多奖励
+        if ($targetId <= 0) {
+            // Boss战奖励
+            $bossRewardItems = [
+                ['item_id' => 3001, 'name' => '争霸徽章', 'amount' => 1],
+                ['item_id' => 3002, 'name' => '高级狗粮', 'amount' => mt_rand(1, 3)],
+                ['item_id' => 3003, 'name' => '钻石', 'amount' => mt_rand(10, 30)]
+            ];
+            
+            foreach ($bossRewardItems as $item) {
+                $rewards['items'][] = [
+                    'item_id' => $item['item_id'],
+                    'name' => $item['name'],
+                    'amount' => $item['amount']
+                ];
+            }
+        } else {
+            // PVP战奖励
+            $pvpRewardItems = [
+                ['item_id' => 3001, 'name' => '争霸徽章', 'amount' => 1],
+                ['item_id' => 3004, 'name' => '荣誉点数', 'amount' => mt_rand(5, 15)]
+            ];
+            
+            foreach ($pvpRewardItems as $item) {
+                $rewards['items'][] = [
+                    'item_id' => $item['item_id'],
+                    'name' => $item['name'],
+                    'amount' => $item['amount']
+                ];
+            }
+        }
+        
+        return $rewards;
+    }
+    
+    /**
+     * 计算争霸赛造成的伤害
+     * 
+     * @param int $petPower 宠物战力
+     * @param int $targetPetPower 目标宠物战力
+     * @param bool $success 是否成功
+     * @return int 造成的伤害
+     */
+    protected function calculateRoyaleDamage(int $petPower, int $targetPetPower, bool $success): int
+    {
+        // 基础伤害
+        $baseDamage = $petPower * 0.1;
+        
+        // 如果战斗成功,额外增加伤害
+        if ($success) {
+            $baseDamage *= 1.5;
+        }
+        
+        // 根据目标战力调整伤害
+        $powerRatio = $petPower / max(1, $targetPetPower);
+        $damageAdjustment = $powerRatio * 0.5;
+        
+        // 最终伤害,加入随机因素
+        $finalDamage = $baseDamage * (1 + $damageAdjustment) * (0.8 + mt_rand(0, 40) / 100);
+        
+        return (int)$finalDamage;
+    }
+}

+ 699 - 0
app/Module/Pet/Logic/PetLogic.php

@@ -0,0 +1,699 @@
+<?php
+
+namespace App\Module\Pet\Logic;
+
+use App\Module\GameItems\Services\ItemService;
+use App\Module\Pet\Enums\PetStatus;
+use App\Module\Pet\Events\PetLevelUpEvent;
+use App\Module\Pet\Events\PetRemouldEvent;
+use App\Module\Pet\Events\PetSkillUsedEvent;
+use App\Module\Pet\Events\PetStatusChangedEvent;
+use App\Module\Pet\Models\PetConfig;
+use App\Module\Pet\Models\PetLevelConfig;
+use App\Module\Pet\Models\PetRemouldLog;
+use App\Module\Pet\Models\PetSkill;
+use App\Module\Pet\Models\PetSkillLog;
+use App\Module\Pet\Models\PetUser;
+use App\Module\Pet\Validators\PetFoodValidator;
+use Exception;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+
+/**
+ * 宠物逻辑类
+ *
+ * 处理宠物相关的业务逻辑,包括创建宠物、升级宠物、喂养宠物、
+ * 洗髓宠物、使用技能等功能。该类是宠物模块内部使用的核心逻辑类,
+ * 不对外提供服务,由PetService调用。
+ */
+class PetLogic
+{
+    /**
+     * 物品服务
+     *
+     * @var ItemService
+     */
+    protected $itemService;
+
+    /**
+     * 宠物食物验证器
+     *
+     * @var PetFoodValidator
+     */
+    protected $petFoodValidator;
+
+    /**
+     * 构造函数
+     */
+    public function __construct()
+    {
+        $this->itemService = new ItemService();
+        $this->petFoodValidator = new PetFoodValidator();
+    }
+
+    /**
+     * 创建宠物
+     *
+     * @param int $userId 用户ID
+     * @param string $name 宠物名称
+     * @param int|null $grade 宠物品阶,如果为null则随机生成(1一品,2二品,3三品,4四品)
+     * @param array $options 其他选项
+     * @return array 创建结果
+     * @throws Exception
+     */
+    public function createPet(int $userId, string $name, ?int $grade = null, array $options = []): array
+    {
+        // 验证宠物名称
+        if (empty($name) || mb_strlen($name) > 20) {
+            throw new Exception("宠物名称不能为空且不能超过20个字符");
+        }
+
+        // 检查用户宠物数量限制
+        $petCount = PetUser::where('user_id', $userId)->count();
+        $maxPets = config('pet.max_pets_per_user', 3);
+
+        if ($petCount >= $maxPets) {
+            throw new Exception("已达到最大宠物数量限制: {$maxPets}");
+        }
+
+        // 如果未指定品阶,则根据概率随机生成
+        if ($grade === null) {
+            $grade = $this->generateRandomGrade();
+        }
+
+        // 获取宠物配置
+        $petConfig = PetConfig::where('pet_type', $options['pet_type'] ?? 'default')->first();
+        if (!$petConfig) {
+            $petConfig = PetConfig::first(); // 使用默认配置
+            if (!$petConfig) {
+                throw new Exception("宠物配置不存在");
+            }
+        }
+
+        // 创建宠物
+        $pet = new PetUser();
+        $pet->user_id = $userId;
+        $pet->name = $name;
+        $pet->grade = $grade;
+        $pet->level = 1;
+        $pet->experience = 0;
+        $pet->stamina = $petConfig->stamina_max ?? 100;
+        $pet->status = PetStatus::NORMAL;
+        $pet->save();
+
+        Log::info('宠物创建成功', [
+            'user_id' => $userId,
+            'pet_id' => $pet->id,
+            'name' => $name,
+            'grade' => $grade->value
+        ]);
+
+        return [
+            'pet_id' => $pet->id,
+            'grade' => $grade
+        ];
+    }
+
+    /**
+     * 根据概率随机生成宠物品阶
+     *
+     * @return int 品阶值(1一品,2二品,3三品,4四品)
+     */
+    protected function generateRandomGrade(): int
+    {
+        $probabilities = config('pet.grade_probability', [
+            1 => 0.6,   // 一品阶:60%
+            2 => 0.25,  // 二品阶:25%
+            3 => 0.1,   // 三品阶:10%
+            4 => 0.05   // 四品阶:5%
+        ]);
+
+        $rand = mt_rand(1, 100) / 100;
+        $cumulative = 0;
+
+        foreach ($probabilities as $grade => $probability) {
+            $cumulative += $probability;
+            if ($rand <= $cumulative) {
+                return $grade;
+            }
+        }
+
+        // 默认返回一品
+        return 1;
+    }
+
+    /**
+     * 宠物升级
+     *
+     * @param int $petId 宠物ID
+     * @return array 升级结果
+     * @throws Exception
+     */
+    public function levelUpPet(int $petId): array
+    {
+        // 获取宠物信息
+        $pet = PetUser::findOrFail($petId);
+
+        // 获取当前等级配置
+        $currentLevelConfig = PetLevelConfig::where('level', $pet->level)->first();
+        if (!$currentLevelConfig) {
+            throw new Exception("宠物等级配置不存在");
+        }
+
+        // 获取下一级配置
+        $nextLevelConfig = PetLevelConfig::where('level', $pet->level + 1)->first();
+        if (!$nextLevelConfig) {
+            throw new Exception("宠物已达到最大等级");
+        }
+
+        // 检查经验值是否足够
+        if ($pet->experience < $nextLevelConfig->exp_required) {
+            throw new Exception("经验值不足,无法升级");
+        }
+
+        // 记录旧等级
+        $oldLevel = $pet->level;
+
+        // 升级宠物
+        $pet->level += 1;
+        $pet->save();
+
+        // 获取新解锁的技能
+        $unlockedSkills = [];
+        if ($nextLevelConfig->unlock_skills) {
+            $unlockedSkills = json_decode($nextLevelConfig->unlock_skills, true);
+        }
+
+        // 触发宠物升级事件
+        event(new PetLevelUpEvent(
+            $pet->user_id,
+            $pet->id,
+            $oldLevel,
+            $pet->level,
+            $unlockedSkills
+        ));
+
+        Log::info('宠物升级成功', [
+            'pet_id' => $petId,
+            'old_level' => $oldLevel,
+            'new_level' => $pet->level,
+            'unlocked_skills' => $unlockedSkills
+        ]);
+
+        return [
+            'old_level' => $oldLevel,
+            'new_level' => $pet->level,
+            'unlocked_skills' => $unlockedSkills
+        ];
+    }
+
+    /**
+     * 宠物喂养
+     *
+     * @param int $petId 宠物ID
+     * @param int $itemId 物品ID(狗粮)
+     * @param int $amount 数量
+     * @return array 喂养结果
+     * @throws Exception
+     */
+    public function feedPet(int $petId, int $itemId, int $amount): array
+    {
+        // 获取宠物信息
+        $pet = PetUser::findOrFail($petId);
+
+        // 验证物品是否为宠物口粮
+        if (!$this->petFoodValidator->validate($itemId, [])) {
+            throw new Exception("该物品不是宠物口粮");
+        }
+
+        // 获取物品信息
+        $item = $this->itemService->getItemInfo($itemId);
+        if (!$item) {
+            throw new Exception("物品不存在");
+        }
+
+        // 消耗物品
+        $consumeResult = $this->itemService->consumeItem(
+            $pet->user_id,
+            $itemId,
+            null,
+            $amount,
+            [
+                'source_type' => 'pet_feed',
+                'source_id' => $petId,
+                'details' => ['pet_id' => $petId]
+            ]
+        );
+
+        if (!$consumeResult['success']) {
+            throw new Exception("物品消耗失败: " . ($consumeResult['message'] ?? '未知错误'));
+        }
+
+        // 计算获得的经验值和体力
+        $expGained = $item->pet_exp * $amount;
+        $staminaGained = $item->pet_power * $amount;
+
+        // 更新宠物状态为喂养中
+        $oldStatus = $pet->status;
+        $pet->status = PetStatus::FEEDING;
+        $pet->save();
+
+        // 触发宠物状态变更事件
+        event(new PetStatusChangedEvent(
+            $pet->user_id,
+            $pet->id,
+            $oldStatus,
+            PetStatus::FEEDING,
+            'pet_feed',
+            ['item_id' => $itemId, 'amount' => $amount]
+        ));
+
+        // 增加经验值
+        $levelUpOccurred = $this->addExperience($petId, $expGained);
+
+        // 恢复体力
+        $this->addStamina($petId, $staminaGained);
+
+        // 喂养完成后恢复正常状态
+        $pet->refresh();
+        $pet->status = PetStatus::NORMAL;
+        $pet->save();
+
+        // 触发宠物状态变更事件
+        event(new PetStatusChangedEvent(
+            $pet->user_id,
+            $pet->id,
+            PetStatus::FEEDING,
+            PetStatus::NORMAL,
+            'pet_feed_complete',
+            ['item_id' => $itemId, 'amount' => $amount]
+        ));
+
+        Log::info('宠物喂养成功', [
+            'pet_id' => $petId,
+            'item_id' => $itemId,
+            'amount' => $amount,
+            'exp_gained' => $expGained,
+            'stamina_gained' => $staminaGained,
+            'level_up' => $levelUpOccurred
+        ]);
+
+        return [
+            'exp_gained' => $expGained,
+            'stamina_gained' => $staminaGained,
+            'level_up' => $levelUpOccurred
+        ];
+    }
+
+    /**
+     * 增加宠物经验值
+     *
+     * @param int $petId 宠物ID
+     * @param int $expAmount 经验值数量
+     * @return bool 是否触发升级
+     */
+    protected function addExperience(int $petId, int $expAmount): bool
+    {
+        // 获取宠物信息
+        $pet = PetUser::findOrFail($petId);
+
+        // 增加经验值
+        $pet->experience += $expAmount;
+        $pet->save();
+
+        // 检查是否可以升级
+        $nextLevelConfig = PetLevelConfig::where('level', $pet->level + 1)->first();
+        if ($nextLevelConfig && $pet->experience >= $nextLevelConfig->exp_required) {
+            try {
+                $this->levelUpPet($petId);
+                return true;
+            } catch (Exception $e) {
+                Log::error('宠物升级失败', [
+                    'pet_id' => $petId,
+                    'error' => $e->getMessage()
+                ]);
+                return false;
+            }
+        }
+
+        return false;
+    }
+
+    /**
+     * 增加宠物体力
+     *
+     * @param int $petId 宠物ID
+     * @param int $staminaAmount 体力数量
+     * @return int 实际增加的体力值
+     */
+    protected function addStamina(int $petId, int $staminaAmount): int
+    {
+        // 获取宠物信息
+        $pet = PetUser::findOrFail($petId);
+
+        // 获取宠物等级配置
+        $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
+        $maxStamina = $levelConfig ? $levelConfig->stamina_max : 100;
+
+        // 计算实际增加的体力值
+        $oldStamina = $pet->stamina;
+        $newStamina = min($maxStamina, $oldStamina + $staminaAmount);
+        $actualGained = $newStamina - $oldStamina;
+
+        // 更新体力值
+        $pet->stamina = $newStamina;
+        $pet->save();
+
+        return $actualGained;
+    }
+
+    /**
+     * 宠物洗髓
+     *
+     * @param int $petId 宠物ID
+     * @param int $itemId 洗髓道具ID,如果为0则使用钻石
+     * @return array 洗髓结果
+     * @throws Exception
+     */
+    public function remouldPet(int $petId, int $itemId = 0): array
+    {
+        // 获取宠物信息
+        $pet = PetUser::findOrFail($petId);
+
+        // 记录旧品阶
+        $oldGrade = $pet->grade;
+
+        // 如果使用道具
+        if ($itemId > 0) {
+            // 验证物品是否为洗髓道具
+            $remouldItemId = config('pet.remould_cost.item_id');
+            if ($itemId != $remouldItemId) {
+                throw new Exception("该物品不是洗髓道具");
+            }
+
+            // 消耗物品
+            $consumeResult = $this->itemService->consumeItem(
+                $pet->user_id,
+                $itemId,
+                null,
+                1,
+                [
+                    'source_type' => 'pet_remould',
+                    'source_id' => $petId,
+                    'details' => ['pet_id' => $petId]
+                ]
+            );
+
+            if (!$consumeResult['success']) {
+                throw new Exception("物品消耗失败: " . ($consumeResult['message'] ?? '未知错误'));
+            }
+        } else {
+            // 使用钻石
+            $diamondCost = config('pet.remould_cost.diamond', 50);
+
+            // TODO: 消耗钻石的逻辑,需要调用相关服务
+            // 这里需要根据实际项目中的钻石消耗方式进行实现
+            // 暂时使用占位代码
+            $diamondConsumeSuccess = true;
+
+            if (!$diamondConsumeSuccess) {
+                throw new Exception("钻石不足,无法进行洗髓");
+            }
+        }
+
+        // 随机生成新品阶
+        $newGrade = $this->generateRandomGrade();
+
+        // 更新宠物品阶
+        $pet->grade = $newGrade;
+        $pet->save();
+
+        // 记录洗髓日志
+        PetRemouldLog::create([
+            'pet_id' => $petId,
+            'old_grade' => $oldGrade,
+            'new_grade' => $newGrade,
+            'remould_time' => now()
+        ]);
+
+        // 触发宠物洗髓事件
+        event(new PetRemouldEvent(
+            $pet->user_id,
+            $pet->id,
+            $oldGrade,
+            $newGrade
+        ));
+
+        Log::info('宠物洗髓成功', [
+            'pet_id' => $petId,
+            'old_grade' => $oldGrade,
+            'new_grade' => $newGrade,
+            'item_id' => $itemId
+        ]);
+
+        return [
+            'old_grade' => $oldGrade,
+            'new_grade' => $newGrade
+        ];
+    }
+
+    /**
+     * 使用宠物技能
+     *
+     * @param int $petId 宠物ID
+     * @param int $skillId 技能ID
+     * @param array $params 技能参数
+     * @return array 技能使用结果
+     * @throws Exception
+     */
+    public function useSkill(int $petId, int $skillId, array $params = []): array
+    {
+        // 获取宠物信息
+        $pet = PetUser::findOrFail($petId);
+
+        // 获取技能信息
+        $skill = PetSkill::findOrFail($skillId);
+
+        // 检查技能冷却时间
+        $lastUsed = PetSkillLog::where('pet_id', $petId)
+            ->where('skill_id', $skillId)
+            ->orderBy('used_at', 'desc')
+            ->first();
+
+        if ($lastUsed) {
+            $cooldownSeconds = $skill->cool_down;
+            $secondsSinceLastUse = now()->diffInSeconds($lastUsed->used_at);
+
+            if ($secondsSinceLastUse < $cooldownSeconds) {
+                $remainingCooldown = $cooldownSeconds - $secondsSinceLastUse;
+                throw new Exception("技能冷却中,还需等待 {$remainingCooldown} 秒");
+            }
+        }
+
+        // 检查体力是否足够
+        if ($pet->stamina < $skill->stamina_cost) {
+            throw new Exception("体力不足,无法使用技能");
+        }
+
+        // 消耗体力
+        $pet->stamina -= $skill->stamina_cost;
+        $pet->save();
+
+        // 执行技能效果
+        $effectResult = $this->executeSkillEffect($pet, $skill, $params);
+
+        // 记录技能使用日志
+        $skillLog = PetSkillLog::create([
+            'pet_id' => $petId,
+            'skill_id' => $skillId,
+            'used_at' => now(),
+            'effect_result' => json_encode($effectResult)
+        ]);
+
+        // 触发宠物技能使用事件
+        event(new PetSkillUsedEvent(
+            $pet->user_id,
+            $pet->id,
+            $skillId,
+            $params
+        ));
+
+        Log::info('宠物技能使用成功', [
+            'pet_id' => $petId,
+            'skill_id' => $skillId,
+            'params' => $params,
+            'effect_result' => $effectResult
+        ]);
+
+        return [
+            'effect_result' => $effectResult
+        ];
+    }
+
+    /**
+     * 执行技能效果
+     *
+     * @param PetUser $pet 宠物对象
+     * @param PetSkill $skill 技能对象
+     * @param array $params 技能参数
+     * @return array 技能效果结果
+     */
+    protected function executeSkillEffect(PetUser $pet, PetSkill $skill, array $params): array
+    {
+        // 根据技能名称执行不同的效果
+        switch ($skill->skill_name) {
+            case '自动收菜':
+                // 调用农场模块的收获接口
+                // 这里需要根据实际项目中的农场模块接口进行实现
+                // 暂时使用占位代码
+                $harvestResult = [
+                    'success' => true,
+                    'harvested_count' => mt_rand(1, 5),
+                    'items' => []
+                ];
+
+                return $harvestResult;
+
+            case '自动播种':
+                // 调用农场模块的播种接口
+                // 这里需要根据实际项目中的农场模块接口进行实现
+                // 暂时使用占位代码
+                $plantResult = [
+                    'success' => true,
+                    'planted_count' => mt_rand(1, 5),
+                    'seeds' => []
+                ];
+
+                return $plantResult;
+
+            case '灾害防护':
+                // 设置农场模块的灾害防护标志
+                // 这里需要根据实际项目中的农场模块接口进行实现
+                // 暂时使用占位代码
+                $protectResult = [
+                    'success' => true,
+                    'protected_type' => $params['disaster_type'] ?? 'all',
+                    'duration' => 3600 // 1小时
+                ];
+
+                return $protectResult;
+
+            default:
+                return [
+                    'success' => false,
+                    'message' => '未知技能效果'
+                ];
+        }
+    }
+
+    /**
+     * 变更宠物状态
+     *
+     * @param int $petId 宠物ID
+     * @param PetStatus $status 新状态
+     * @param string $reason 变更原因
+     * @return bool 是否变更成功
+     */
+    public function changeStatus(int $petId, PetStatus $status, string $reason = ''): bool
+    {
+        // 获取宠物信息
+        $pet = PetUser::findOrFail($petId);
+
+        // 记录旧状态
+        $oldStatus = $pet->status;
+
+        // 如果状态相同,则不需要变更
+        if ($oldStatus === $status) {
+            return true;
+        }
+
+        // 更新状态
+        $pet->status = $status;
+        $pet->save();
+
+        // 触发宠物状态变更事件
+        event(new PetStatusChangedEvent(
+            $pet->user_id,
+            $pet->id,
+            $oldStatus,
+            $status,
+            $reason
+        ));
+
+        Log::info('宠物状态变更成功', [
+            'pet_id' => $petId,
+            'old_status' => $oldStatus->value,
+            'new_status' => $status->value,
+            'reason' => $reason
+        ]);
+
+        return true;
+    }
+
+    /**
+     * 恢复宠物体力
+     *
+     * @param int $petId 宠物ID
+     * @param int $minutes 经过的分钟数
+     * @return int 恢复的体力值
+     */
+    public function recoverStamina(int $petId, int $minutes): int
+    {
+        // 获取宠物信息
+        $pet = PetUser::findOrFail($petId);
+
+        // 获取宠物等级配置
+        $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
+        $maxStamina = $levelConfig ? $levelConfig->stamina_max : 100;
+        $recoveryRate = $levelConfig ? $levelConfig->stamina_recovery_rate : 5;
+
+        // 计算恢复的体力值
+        $recoveryAmount = $recoveryRate * $minutes;
+        $oldStamina = $pet->stamina;
+        $newStamina = min($maxStamina, $oldStamina + $recoveryAmount);
+        $actualRecovered = $newStamina - $oldStamina;
+
+        // 更新体力值
+        if ($actualRecovered > 0) {
+            $pet->stamina = $newStamina;
+            $pet->save();
+
+            Log::info('宠物体力恢复成功', [
+                'pet_id' => $petId,
+                'minutes' => $minutes,
+                'recovery_rate' => $recoveryRate,
+                'old_stamina' => $oldStamina,
+                'new_stamina' => $newStamina,
+                'actual_recovered' => $actualRecovered
+            ]);
+        }
+
+        return $actualRecovered;
+    }
+
+    /**
+     * 计算宠物战力
+     *
+     * @param int $petId 宠物ID
+     * @return int 战力值
+     */
+    public function calculatePower(int $petId): int
+    {
+        // 获取宠物信息
+        $pet = PetUser::findOrFail($petId);
+
+        // 获取宠物等级配置
+        $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
+
+        // 基础战力
+        $basePower = $levelConfig ? ($levelConfig->numeric_attributes['base_power'] ?? 100) : 100;
+
+        // 品阶加成
+        $gradeBonus = config('pet.grade_attribute_bonus.' . $pet->grade, 0);
+
+        // 计算最终战力
+        $power = $basePower * (1 + $gradeBonus);
+
+        return (int)$power;
+    }
+}

+ 11 - 12
app/Module/Pet/Models/PetRemouldLog.php

@@ -3,19 +3,18 @@
 namespace App\Module\Pet\Models;
 
 use UCore\ModelCore;
-use App\Module\Pet\Enums\PetGrade;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
 
 /**
  * 宠物洗髓记录模型
  *
- * field start 
- * @property   int  $id  
- * @property   int  $pet_id  
- * @property   string  $old_grade  
- * @property   string  $new_grade  
- * @property   string  $remould_time  
- * @property   \Carbon\Carbon  $created_at  
+ * field start
+ * @property   int  $id
+ * @property   int  $pet_id
+ * @property   int  $old_grade  原品阶(1一品,2二品,3三品,4四品)
+ * @property   int  $new_grade  新品阶(1一品,2二品,3三品,4四品)
+ * @property   string  $remould_time
+ * @property   \Carbon\Carbon  $created_at
  * field end
  */
 class PetRemouldLog extends ModelCore
@@ -27,7 +26,7 @@ class PetRemouldLog extends ModelCore
      */
     protected $table = 'pet_remould_logs';
 
-    // attrlist start 
+    // attrlist start
     protected $fillable = [
         'id',
         'pet_id',
@@ -54,8 +53,8 @@ class PetRemouldLog extends ModelCore
      */
     protected $casts = [
         'pet_id' => 'integer',
-        'old_grade' => PetGrade::class,
-        'new_grade' => PetGrade::class,
+        'old_grade' => 'integer',
+        'new_grade' => 'integer',
     ];
 
     /**
@@ -65,7 +64,7 @@ class PetRemouldLog extends ModelCore
      */
     public function pet(): BelongsTo
     {
-        return $this->belongsTo(Pet::class, 'pet_id');
+        return $this->belongsTo(PetUser::class, 'pet_id');
     }
 
 }

+ 10 - 11
app/Module/Pet/Models/PetUser.php

@@ -3,7 +3,6 @@
 namespace App\Module\Pet\Models;
 
 use UCore\ModelCore;
-use App\Module\Pet\Enums\PetGrade;
 use App\Module\Pet\Enums\PetStatus;
 use Illuminate\Database\Eloquent\Relations\HasMany;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -11,17 +10,17 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
 /**
  * 宠物模型
  *
- * field start 
- * @property   int  $id  
+ * field start
+ * @property   int  $id
  * @property   int  $user_id  用户ID
  * @property   string  $name  宠物名称
- * @property   string  $grade  
- * @property   int  $level  
- * @property   int  $experience  
- * @property   int  $stamina  
+ * @property   int  $grade  宠物品阶:1一品,2二品,3三品,4四品
+ * @property   int  $level
+ * @property   int  $experience
+ * @property   int  $stamina
  * @property   int  $status  宠物状态:0未知,1正常,2战斗中,3死亡
- * @property   \Carbon\Carbon  $created_at  
- * @property   \Carbon\Carbon  $updated_at  
+ * @property   \Carbon\Carbon  $created_at
+ * @property   \Carbon\Carbon  $updated_at
  * field end
  */
 class PetUser extends ModelCore
@@ -38,7 +37,7 @@ class PetUser extends ModelCore
      *
      * @var array
      */
-    // attrlist start 
+    // attrlist start
     protected $fillable = [
         'id',
         'user_id',
@@ -62,7 +61,7 @@ class PetUser extends ModelCore
         'experience' => 'integer',
         'stamina' => 'integer',
         'status' => PetStatus::class,
-        'grade' => PetGrade::class,
+        'grade' => 'integer',
         'created_at' => 'datetime',
         'updated_at' => 'datetime',
     ];

+ 81 - 0
app/Module/Pet/Providers/PetServiceProvider.php

@@ -0,0 +1,81 @@
+<?php
+
+namespace App\Module\Pet\Providers;
+
+use App\Module\Pet\Events\PetBattleEvent;
+use App\Module\Pet\Events\PetLevelUpEvent;
+use App\Module\Pet\Events\PetRemouldEvent;
+use App\Module\Pet\Events\PetSkillUsedEvent;
+use App\Module\Pet\Events\PetStatusChangedEvent;
+use App\Module\Pet\Listeners\ItemChangedListener;
+use App\Module\Pet\Listeners\LoginSuccessListener;
+use App\Module\Pet\Listeners\PetStatusChangedListener;
+use App\Module\Pet\Logic\PetLogic;
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\ServiceProvider;
+
+/**
+ * 宠物模块服务提供者
+ *
+ * 负责注册宠物模块的服务、事件监听器、命令等
+ */
+class PetServiceProvider extends ServiceProvider
+{
+    /**
+     * 事件到监听器的映射
+     *
+     * @var array
+     */
+    protected $listen = [
+        // 监听来自其他模块的事件
+        \App\Module\GameItems\Events\ItemChangedEvent::class => [
+            ItemChangedListener::class,
+        ],
+        \App\Module\AppGame\Events\LoginSuccessEvent::class => [
+            LoginSuccessListener::class,
+        ]
+    ];
+
+    /**
+     * 注册服务
+     *
+     * @return void
+     */
+    public function register()
+    {
+       
+        
+    }
+
+    /**
+     * 启动服务
+     *
+     * @return void
+     */
+    public function boot()
+    {
+        // 注册事件监听器
+        $this->registerEventListeners();
+
+        // 注册命令
+        if ($this->app->runningInConsole()) {
+            $this->commands([
+                // 可以在这里添加宠物模块的命令
+            ]);
+        }
+    }
+
+    /**
+     * 注册事件监听器
+     *
+     * @return void
+     */
+    protected function registerEventListeners()
+    {
+        foreach ($this->listen as $event => $listeners) {
+            foreach ($listeners as $listener) {
+                Event::listen($event, $listener);
+            }
+        }
+    }
+}

+ 547 - 0
app/Module/Pet/Services/PetService.php

@@ -0,0 +1,547 @@
+<?php
+
+namespace App\Module\Pet\Services;
+
+use App\Module\Pet\Enums\PetStatus;
+use App\Module\Pet\Logic\PetLogic;
+use App\Module\Pet\Models\PetUser;
+use App\Module\Pet\Models\PetSkill;
+use App\Module\Pet\Models\PetLevelConfig;
+use Exception;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+use UCore\Db\Helper;
+
+/**
+ * 宠物服务类
+ *
+ * 提供宠物相关的服务,包括获取用户宠物列表、创建宠物、宠物升级、
+ * 宠物喂养、宠物洗髓、宠物技能使用等功能。该类是宠物模块对外提供
+ * 服务的主要入口,封装了宠物操作的复杂逻辑。
+ *
+ * 注意:本服务类不负责事务管理,调用方需要自行开启和管理事务。
+ * 对于涉及数据修改的方法,强烈建议在调用前开启事务,以确保数据一致性。
+ */
+class PetService
+{
+    /**
+     * 获取用户宠物列表
+     *
+     * @param int $userId 用户ID
+     * @param array $filters 过滤条件
+     * @return Collection|PetUser[]
+     */
+    public static function getUserPets(int $userId, array $filters = []): Collection
+    {
+        $query = PetUser::where('user_id', $userId);
+
+        // 应用过滤条件
+        if (isset($filters['status'])) {
+            $query->where('status', $filters['status']);
+        }
+
+        if (isset($filters['grade'])) {
+            $query->where('grade', $filters['grade']);
+        }
+
+        if (isset($filters['min_level'])) {
+            $query->where('level', '>=', $filters['min_level']);
+        }
+
+        if (isset($filters['max_level'])) {
+            $query->where('level', '<=', $filters['max_level']);
+        }
+
+        return $query->get();
+    }
+
+    /**
+     * 创建宠物
+     *
+     * 注意:调用此方法前,请确保已开启数据库事务
+     *
+     * @param int $userId 用户ID
+     * @param string $name 宠物名称
+     * @param int|null $grade 宠物品阶,如果为null则随机生成(1一品,2二品,3三品,4四品)
+     * @param array $options 其他选项
+     * @return array 创建结果
+     * @throws Exception
+     */
+    public static function createPet(int $userId, string $name, ?int $grade = null, array $options = []): array
+    {
+        // 验证事务是否已开启
+        Helper::check_tr();
+
+        try {
+            // 创建宠物逻辑
+            $petLogic = new PetLogic();
+
+            // 创建宠物
+            $result = $petLogic->createPet($userId, $name, $grade, $options);
+
+            return [
+                'success' => true,
+                'pet_id' => $result['pet_id'],
+                'name' => $name,
+                'grade' => $result['grade'],
+                'level' => 1,
+                'message' => '宠物创建成功'
+            ];
+        } catch (Exception $e) {
+            Log::error('创建宠物失败', [
+                'user_id' => $userId,
+                'name' => $name,
+                'error' => $e->getMessage()
+            ]);
+
+            throw $e;
+        }
+    }
+
+    /**
+     * 宠物升级
+     *
+     * 注意:调用此方法前,请确保已开启数据库事务
+     *
+     * @param int $userId 用户ID
+     * @param int $petId 宠物ID
+     * @return array 升级结果
+     * @throws Exception
+     */
+    public static function levelUpPet(int $userId, int $petId): array
+    {
+        // 验证事务是否已开启
+        Helper::check_tr();
+
+        try {
+            // 宠物逻辑
+            $petLogic = new PetLogic();
+
+            // 获取宠物信息
+            $pet = PetUser::where('id', $petId)
+                ->where('user_id', $userId)
+                ->first();
+
+            if (!$pet) {
+                throw new Exception("宠物不存在或不属于该用户");
+            }
+
+            // 执行升级逻辑
+            $result = $petLogic->levelUpPet($petId);
+
+            return [
+                'success' => true,
+                'pet_id' => $petId,
+                'old_level' => $result['old_level'],
+                'new_level' => $result['new_level'],
+                'unlocked_skills' => $result['unlocked_skills'] ?? [],
+                'message' => '宠物升级成功'
+            ];
+        } catch (Exception $e) {
+            Log::error('宠物升级失败', [
+                'user_id' => $userId,
+                'pet_id' => $petId,
+                'error' => $e->getMessage()
+            ]);
+
+            throw $e;
+        }
+    }
+
+    /**
+     * 宠物喂养
+     *
+     * 注意:调用此方法前,请确保已开启数据库事务
+     *
+     * @param int $userId 用户ID
+     * @param int $petId 宠物ID
+     * @param int $itemId 物品ID(狗粮)
+     * @param int $amount 数量
+     * @return array 喂养结果
+     * @throws Exception
+     */
+    public static function feedPet(int $userId, int $petId, int $itemId, int $amount = 1): array
+    {
+        // 验证事务是否已开启
+        Helper::check_tr();
+
+        try {
+            // 宠物逻辑
+            $petLogic = new PetLogic();
+
+            // 获取宠物信息
+            $pet = PetUser::where('id', $petId)
+                ->where('user_id', $userId)
+                ->first();
+
+            if (!$pet) {
+                throw new Exception("宠物不存在或不属于该用户");
+            }
+
+            // 检查宠物状态
+            if ($pet->status !== PetStatus::NORMAL) {
+                throw new Exception("宠物当前状态不允许喂养");
+            }
+
+            // 执行喂养逻辑
+            $result = $petLogic->feedPet($petId, $itemId, $amount);
+
+            return [
+                'success' => true,
+                'pet_id' => $petId,
+                'item_id' => $itemId,
+                'amount' => $amount,
+                'exp_gained' => $result['exp_gained'],
+                'stamina_gained' => $result['stamina_gained'],
+                'level_up' => $result['level_up'],
+                'message' => '宠物喂养成功'
+            ];
+        } catch (Exception $e) {
+            Log::error('宠物喂养失败', [
+                'user_id' => $userId,
+                'pet_id' => $petId,
+                'item_id' => $itemId,
+                'amount' => $amount,
+                'error' => $e->getMessage()
+            ]);
+
+            throw $e;
+        }
+    }
+
+    /**
+     * 宠物洗髓
+     *
+     * 注意:调用此方法前,请确保已开启数据库事务
+     *
+     * @param int $userId 用户ID
+     * @param int $petId 宠物ID
+     * @param int $itemId 洗髓道具ID,如果为0则使用钻石
+     * @return array 洗髓结果
+     * @throws Exception
+     */
+    public static function remouldPet(int $userId, int $petId, int $itemId = 0): array
+    {
+        // 验证事务是否已开启
+        Helper::check_tr();
+
+        try {
+            // 宠物逻辑
+            $petLogic = new PetLogic();
+
+            // 获取宠物信息
+            $pet = PetUser::where('id', $petId)
+                ->where('user_id', $userId)
+                ->first();
+
+            if (!$pet) {
+                throw new Exception("宠物不存在或不属于该用户");
+            }
+
+            // 检查宠物状态
+            if ($pet->status !== PetStatus::NORMAL) {
+                throw new Exception("宠物当前状态不允许洗髓");
+            }
+
+            // 执行洗髓逻辑
+            $result = $petLogic->remouldPet($petId, $itemId);
+
+            return [
+                'success' => true,
+                'pet_id' => $petId,
+                'old_grade' => $result['old_grade'],
+                'new_grade' => $result['new_grade'],
+                'item_id' => $itemId,
+                'message' => '宠物洗髓成功'
+            ];
+        } catch (Exception $e) {
+            Log::error('宠物洗髓失败', [
+                'user_id' => $userId,
+                'pet_id' => $petId,
+                'item_id' => $itemId,
+                'error' => $e->getMessage()
+            ]);
+
+            throw $e;
+        }
+    }
+
+    /**
+     * 使用宠物技能
+     *
+     * 注意:调用此方法前,请确保已开启数据库事务
+     *
+     * @param int $userId 用户ID
+     * @param int $petId 宠物ID
+     * @param int $skillId 技能ID
+     * @param array $params 技能参数
+     * @return array 技能使用结果
+     * @throws Exception
+     */
+    public static function useSkill(int $userId, int $petId, int $skillId, array $params = []): array
+    {
+        // 验证事务是否已开启
+        Helper::check_tr();
+
+        try {
+            // 宠物逻辑
+            $petLogic = new PetLogic();
+
+            // 获取宠物信息
+            $pet = PetUser::where('id', $petId)
+                ->where('user_id', $userId)
+                ->first();
+
+            if (!$pet) {
+                throw new Exception("宠物不存在或不属于该用户");
+            }
+
+            // 获取技能信息
+            $skill = PetSkill::find($skillId);
+            if (!$skill) {
+                throw new Exception("技能不存在");
+            }
+
+            // 检查宠物状态
+            if ($pet->status !== PetStatus::NORMAL) {
+                throw new Exception("宠物当前状态不允许使用技能");
+            }
+
+            // 检查宠物等级是否满足技能要求
+            if ($pet->level < $skill->min_level) {
+                throw new Exception("宠物等级不足,无法使用该技能");
+            }
+
+            // 检查宠物体力是否足够
+            if ($pet->stamina < $skill->stamina_cost) {
+                throw new Exception("宠物体力不足,无法使用该技能");
+            }
+
+            // 执行技能使用逻辑
+            $result = $petLogic->useSkill($petId, $skillId, $params);
+
+            return [
+                'success' => true,
+                'pet_id' => $petId,
+                'skill_id' => $skillId,
+                'stamina_cost' => $skill->stamina_cost,
+                'effect_result' => $result['effect_result'],
+                'message' => '技能使用成功'
+            ];
+        } catch (Exception $e) {
+            Log::error('使用宠物技能失败', [
+                'user_id' => $userId,
+                'pet_id' => $petId,
+                'skill_id' => $skillId,
+                'params' => $params,
+                'error' => $e->getMessage()
+            ]);
+
+            throw $e;
+        }
+    }
+
+    /**
+     * 获取宠物状态
+     *
+     * @param int $userId 用户ID
+     * @param int $petId 宠物ID
+     * @return array 宠物状态信息
+     * @throws Exception
+     */
+    public static function getPetStatus(int $userId, int $petId): array
+    {
+        // 获取宠物信息
+        $pet = PetUser::where('id', $petId)
+            ->where('user_id', $userId)
+            ->first();
+
+        if (!$pet) {
+            throw new Exception("宠物不存在或不属于该用户");
+        }
+
+        // 获取宠物等级配置
+        $levelConfig = PetLevelConfig::where('level', $pet->level)->first();
+
+        // 计算距离下一级所需经验
+        $nextLevelConfig = PetLevelConfig::where('level', $pet->level + 1)->first();
+        $expToNextLevel = $nextLevelConfig ? $nextLevelConfig->exp_required - $pet->experience : 0;
+
+        return [
+            'pet_id' => $pet->id,
+            'name' => $pet->name,
+            'grade' => $pet->grade->value,
+            'level' => $pet->level,
+            'experience' => $pet->experience,
+            'exp_to_next_level' => $expToNextLevel,
+            'stamina' => $pet->stamina,
+            'max_stamina' => $levelConfig ? $levelConfig->stamina_max : 100,
+            'status' => $pet->status->value,
+            'created_at' => $pet->created_at->format('Y-m-d H:i:s'),
+            'updated_at' => $pet->updated_at->format('Y-m-d H:i:s')
+        ];
+    }
+
+    /**
+     * 更新宠物状态
+     *
+     * 注意:调用此方法前,请确保已开启数据库事务
+     *
+     * @param int $userId 用户ID
+     * @param int $petId 宠物ID
+     * @param PetStatus $status 新状态
+     * @param string $reason 变更原因
+     * @return bool 是否更新成功
+     * @throws Exception
+     */
+    public static function updatePetStatus(int $userId, int $petId, PetStatus $status, string $reason = ''): bool
+    {
+        // 验证事务是否已开启
+        Helper::check_tr();
+
+        try {
+            // 宠物逻辑
+            $petLogic = new PetLogic();
+
+            // 获取宠物信息
+            $pet = PetUser::where('id', $petId)
+                ->where('user_id', $userId)
+                ->first();
+
+            if (!$pet) {
+                throw new Exception("宠物不存在或不属于该用户");
+            }
+
+            // 记录旧状态
+            $oldStatus = $pet->status;
+
+            // 执行状态变更逻辑
+            $result = $petLogic->changeStatus($petId, $status, $reason);
+
+            return true;
+        } catch (Exception $e) {
+            Log::error('更新宠物状态失败', [
+                'user_id' => $userId,
+                'pet_id' => $petId,
+                'status' => $status->value,
+                'reason' => $reason,
+                'error' => $e->getMessage()
+            ]);
+
+            throw $e;
+        }
+    }
+
+    /**
+     * 恢复宠物体力
+     *
+     * 注意:调用此方法前,请确保已开启数据库事务
+     *
+     * @param int $userId 用户ID
+     * @param int $petId 宠物ID
+     * @param int $minutes 经过的分钟数
+     * @return array 恢复结果
+     * @throws Exception
+     */
+    public static function recoverStamina(int $userId, int $petId, int $minutes): array
+    {
+        // 验证事务是否已开启
+        Helper::check_tr();
+
+        try {
+            // 宠物逻辑
+            $petLogic = new PetLogic();
+
+            // 获取宠物信息
+            $pet = PetUser::where('id', $petId)
+                ->where('user_id', $userId)
+                ->first();
+
+            if (!$pet) {
+                throw new Exception("宠物不存在或不属于该用户");
+            }
+
+            // 执行体力恢复逻辑
+            $recoveredStamina = $petLogic->recoverStamina($petId, $minutes);
+
+            return [
+                'success' => true,
+                'pet_id' => $petId,
+                'recovered_stamina' => $recoveredStamina,
+                'current_stamina' => $pet->fresh()->stamina,
+                'message' => '宠物体力恢复成功'
+            ];
+        } catch (Exception $e) {
+            Log::error('恢复宠物体力失败', [
+                'user_id' => $userId,
+                'pet_id' => $petId,
+                'minutes' => $minutes,
+                'error' => $e->getMessage()
+            ]);
+
+            throw $e;
+        }
+    }
+
+    /**
+     * 获取宠物可用技能列表
+     *
+     * @param int $userId 用户ID
+     * @param int $petId 宠物ID
+     * @return array 技能列表
+     * @throws Exception
+     */
+    public static function getPetSkills(int $userId, int $petId): array
+    {
+        // 获取宠物信息
+        $pet = PetUser::where('id', $petId)
+            ->where('user_id', $userId)
+            ->first();
+
+        if (!$pet) {
+            throw new Exception("宠物不存在或不属于该用户");
+        }
+
+        // 获取所有技能
+        $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');
+
+        $result = [];
+        foreach ($availableSkills as $skill) {
+            $lastUsed = null;
+            $cooldownRemaining = 0;
+
+            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);
+            }
+
+            $result[] = [
+                'skill_id' => $skill->id,
+                'skill_name' => $skill->skill_name,
+                'stamina_cost' => $skill->stamina_cost,
+                'cool_down' => $skill->cool_down,
+                'effect_desc' => $skill->effect_desc,
+                'min_level' => $skill->min_level,
+                'last_used' => $lastUsed ? $lastUsed->format('Y-m-d H:i:s') : null,
+                'cooldown_remaining' => $cooldownRemaining,
+                'is_available' => $cooldownRemaining === 0 && $pet->stamina >= $skill->stamina_cost
+            ];
+        }
+
+        return $result;
+    }
+}

+ 52 - 0
app/Module/Pet/Validators/PetCreateValidator.php

@@ -0,0 +1,52 @@
+<?php
+
+namespace App\Module\Pet\Validators;
+
+use App\Module\Pet\Models\PetUser;
+use UCore\Validator;
+use UCore\Validator\ValidationMessage;
+
+/**
+ * 宠物创建验证器
+ * 
+ * 用于验证宠物创建参数的合法性
+ */
+class PetCreateValidator extends Validator
+{
+    use ValidationMessage;
+    
+    /**
+     * 验证方法
+     * 
+     * @param mixed $value 宠物名称
+     * @param array $data 所有数据
+     * @return bool 验证是否通过
+     */
+    public function validate(mixed $value, array $data): bool
+    {
+        $name = $value;
+        $userId = $data['userId'] ?? 0;
+        
+        // 验证宠物名称
+        if (empty($name)) {
+            $this->throwMessage([], '宠物名称不能为空');
+            return false;
+        }
+        
+        if (mb_strlen($name) > 20) {
+            $this->throwMessage([], '宠物名称不能超过20个字符');
+            return false;
+        }
+        
+        // 检查用户宠物数量限制
+        $petCount = PetUser::where('user_id', $userId)->count();
+        $maxPets = config('pet.max_pets_per_user', 3);
+        
+        if ($petCount >= $maxPets) {
+            $this->throwMessage(['max' => $maxPets], "已达到最大宠物数量限制: {max}");
+            return false;
+        }
+        
+        return true;
+    }
+}

+ 59 - 0
app/Module/Pet/Validators/PetFeedValidator.php

@@ -0,0 +1,59 @@
+<?php
+
+namespace App\Module\Pet\Validators;
+
+use App\Module\Pet\Enums\PetStatus;
+use App\Module\Pet\Models\PetUser;
+use UCore\Validator;
+use UCore\Validator\ValidationMessage;
+
+/**
+ * 宠物喂养验证器
+ * 
+ * 用于验证宠物喂养条件的合法性
+ */
+class PetFeedValidator extends Validator
+{
+    use ValidationMessage;
+    
+    /**
+     * 验证方法
+     * 
+     * @param mixed $value 宠物ID
+     * @param array $data 所有数据
+     * @return bool 验证是否通过
+     */
+    public function validate(mixed $value, array $data): bool
+    {
+        $petId = $value;
+        $itemId = $data['itemId'] ?? 0;
+        
+        try {
+            // 获取宠物信息
+            $pet = PetUser::find($petId);
+            
+            if (!$pet) {
+                $this->throwMessage([], '宠物不存在');
+                return false;
+            }
+            
+            // 检查宠物状态
+            if ($pet->status !== PetStatus::NORMAL) {
+                $this->throwMessage(['status' => $pet->status->value], '宠物当前状态({status})不允许喂养');
+                return false;
+            }
+            
+            // 验证物品是否为宠物口粮
+            $petFoodValidator = new PetFoodValidator($this->validation);
+            if (!$petFoodValidator->validate($itemId, [])) {
+                $this->throwMessage(['itemId' => $itemId], '物品({itemId})不是宠物口粮');
+                return false;
+            }
+            
+            return true;
+        } catch (\Exception $e) {
+            $this->throwMessage(['error' => $e->getMessage()], '验证过程发生错误: {error}');
+            return false;
+        }
+    }
+}

+ 193 - 0
app/Module/Pet/Validators/PetFoodValidator.php

@@ -0,0 +1,193 @@
+<?php
+
+namespace App\Module\Pet\Validators;
+
+use App\Module\GameItems\Models\Item;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Log;
+use UCore\Validator;
+use UCore\Validator\ValidationMessage;
+
+/**
+ * 宠物口粮验证器
+ *
+ * 用于验证物品是否为宠物口粮,根据物品的pet_power/pet_exp属性判断。
+ * 该类提供了验证方法,用于在宠物喂养过程中验证物品是否可用作宠物口粮。
+ */
+class PetFoodValidator extends Validator
+{
+    use ValidationMessage;
+    /**
+     * 缓存键前缀
+     *
+     * @var string
+     */
+    protected $cachePrefix = 'pet_food_validator_';
+
+    /**
+     * 缓存过期时间(秒)
+     *
+     * @var int
+     */
+    protected $cacheExpiration = 3600; // 1小时
+
+    /**
+     * 验证物品是否为宠物口粮
+     *
+     * @param mixed $value 物品ID
+     * @param array $data 所有数据
+     * @return bool 验证是否通过
+     */
+    public function validate(mixed $value, array $data): bool
+    {
+        $itemId = (int)$value;
+
+        // 尝试从缓存获取结果
+        $cacheKey = "{$this->cachePrefix}{$itemId}";
+        $cachedResult = Cache::get($cacheKey);
+
+        if ($cachedResult !== null) {
+            if (!$cachedResult) {
+                $this->throwMessage(['itemId' => $itemId], '物品({itemId})不是宠物口粮');
+            }
+            return $cachedResult;
+        }
+
+        try {
+            // 获取物品信息
+            $item = Item::find($itemId);
+
+            if (!$item) {
+                // 物品不存在
+                Cache::put($cacheKey, false, $this->cacheExpiration);
+                $this->throwMessage(['itemId' => $itemId], '物品({itemId})不存在');
+                return false;
+            }
+
+            // 检查物品是否有宠物相关属性
+            $isPetFood = $this->checkPetFoodAttributes($item);
+
+            // 缓存结果
+            Cache::put($cacheKey, $isPetFood, $this->cacheExpiration);
+
+            if (!$isPetFood) {
+                $this->throwMessage(['itemId' => $itemId], '物品({itemId})不是宠物口粮');
+            }
+
+            return $isPetFood;
+        } catch (\Exception $e) {
+            Log::error('验证宠物口粮失败', [
+                'item_id' => $itemId,
+                'error' => $e->getMessage()
+            ]);
+
+            $this->throwMessage(['error' => $e->getMessage()], '验证过程发生错误: {error}');
+            return false;
+        }
+    }
+
+    /**
+     * 检查物品是否具有宠物口粮属性
+     *
+     * @param Item $item 物品对象
+     * @return bool 是否具有宠物口粮属性
+     */
+    protected function checkPetFoodAttributes(Item $item): bool
+    {
+        // 检查物品是否有pet_power或pet_exp属性
+        $numericAttributes = $item->numeric_attributes ?? [];
+
+        if (is_string($numericAttributes)) {
+            $numericAttributes = json_decode($numericAttributes, true) ?? [];
+        }
+
+        // 检查是否有宠物相关属性
+        $hasPetPower = isset($numericAttributes['pet_power']) && $numericAttributes['pet_power'] > 0;
+        $hasPetExp = isset($numericAttributes['pet_exp']) && $numericAttributes['pet_exp'] > 0;
+
+        // 如果有任一宠物属性,则认为是宠物口粮
+        return $hasPetPower || $hasPetExp;
+    }
+
+    /**
+     * 获取物品的宠物属性
+     *
+     * @param int $itemId 物品ID
+     * @return array 宠物属性
+     */
+    public function getPetFoodAttributes(int $itemId): array
+    {
+        try {
+            // 获取物品信息
+            $item = Item::find($itemId);
+
+            if (!$item) {
+                return [
+                    'pet_power' => 0,
+                    'pet_exp' => 0
+                ];
+            }
+
+            // 获取物品的宠物属性
+            $numericAttributes = $item->numeric_attributes ?? [];
+
+            if (is_string($numericAttributes)) {
+                $numericAttributes = json_decode($numericAttributes, true) ?? [];
+            }
+
+            return [
+                'pet_power' => $numericAttributes['pet_power'] ?? 0,
+                'pet_exp' => $numericAttributes['pet_exp'] ?? 0
+            ];
+        } catch (\Exception $e) {
+            Log::error('获取宠物口粮属性失败', [
+                'item_id' => $itemId,
+                'error' => $e->getMessage()
+            ]);
+
+            return [
+                'pet_power' => 0,
+                'pet_exp' => 0
+            ];
+        }
+    }
+
+    /**
+     * 清除物品的缓存结果
+     *
+     * @param int $itemId 物品ID
+     * @return void
+     */
+    public function clearCache(int $itemId): void
+    {
+        $cacheKey = "{$this->cachePrefix}{$itemId}";
+        Cache::forget($cacheKey);
+    }
+
+    /**
+     * 清除所有缓存结果
+     *
+     * @return void
+     */
+    public function clearAllCache(): void
+    {
+        // 注意:这种方式可能不适用于所有缓存驱动
+        // 对于生产环境,可能需要更精细的缓存清理方式
+        $pattern = "{$this->cachePrefix}*";
+
+        // 使用Redis的模式匹配删除键(如果使用Redis缓存)
+        if (config('cache.default') === 'redis') {
+            $redis = Cache::getRedis();
+            $keys = $redis->keys($pattern);
+
+            if (!empty($keys)) {
+                $redis->del($keys);
+            }
+        } else {
+            // 对于其他缓存驱动,可能需要单独实现
+            Log::warning('清除所有宠物口粮验证缓存可能不完全', [
+                'cache_driver' => config('cache.default')
+            ]);
+        }
+    }
+}

+ 75 - 0
app/Module/Pet/Validators/PetLevelUpValidator.php

@@ -0,0 +1,75 @@
+<?php
+
+namespace App\Module\Pet\Validators;
+
+use App\Module\Pet\Enums\PetStatus;
+use App\Module\Pet\Models\PetLevelConfig;
+use App\Module\Pet\Models\PetUser;
+use UCore\Validator;
+use UCore\Validator\ValidationMessage;
+
+/**
+ * 宠物升级验证器
+ * 
+ * 用于验证宠物升级条件的合法性
+ */
+class PetLevelUpValidator extends Validator
+{
+    use ValidationMessage;
+    
+    /**
+     * 验证方法
+     * 
+     * @param mixed $value 宠物ID
+     * @param array $data 所有数据
+     * @return bool 验证是否通过
+     */
+    public function validate(mixed $value, array $data): bool
+    {
+        $petId = $value;
+        
+        try {
+            // 获取宠物信息
+            $pet = PetUser::find($petId);
+            
+            if (!$pet) {
+                $this->throwMessage([], '宠物不存在');
+                return false;
+            }
+            
+            // 检查宠物状态
+            if ($pet->status !== PetStatus::NORMAL) {
+                $this->throwMessage(['status' => $pet->status->value], '宠物当前状态({status})不允许升级');
+                return false;
+            }
+            
+            // 获取当前等级配置
+            $currentLevelConfig = PetLevelConfig::where('level', $pet->level)->first();
+            if (!$currentLevelConfig) {
+                $this->throwMessage([], '宠物等级配置不存在');
+                return false;
+            }
+            
+            // 获取下一级配置
+            $nextLevelConfig = PetLevelConfig::where('level', $pet->level + 1)->first();
+            if (!$nextLevelConfig) {
+                $this->throwMessage(['level' => $pet->level], '宠物已达到最大等级({level})');
+                return false;
+            }
+            
+            // 检查经验值是否足够
+            if ($pet->experience < $nextLevelConfig->exp_required) {
+                $this->throwMessage([
+                    'current' => $pet->experience,
+                    'required' => $nextLevelConfig->exp_required
+                ], '经验值不足,无法升级,当前({current}),需要({required})');
+                return false;
+            }
+            
+            return true;
+        } catch (\Exception $e) {
+            $this->throwMessage(['error' => $e->getMessage()], '验证过程发生错误: {error}');
+            return false;
+        }
+    }
+}

+ 62 - 0
app/Module/Pet/Validators/PetRemouldValidator.php

@@ -0,0 +1,62 @@
+<?php
+
+namespace App\Module\Pet\Validators;
+
+use App\Module\Pet\Enums\PetStatus;
+use App\Module\Pet\Models\PetUser;
+use UCore\Validator;
+use UCore\Validator\ValidationMessage;
+
+/**
+ * 宠物洗髓验证器
+ * 
+ * 用于验证宠物洗髓条件的合法性
+ */
+class PetRemouldValidator extends Validator
+{
+    use ValidationMessage;
+    
+    /**
+     * 验证方法
+     * 
+     * @param mixed $value 宠物ID
+     * @param array $data 所有数据
+     * @return bool 验证是否通过
+     */
+    public function validate(mixed $value, array $data): bool
+    {
+        $petId = $value;
+        $itemId = $data['itemId'] ?? 0;
+        
+        try {
+            // 获取宠物信息
+            $pet = PetUser::find($petId);
+            
+            if (!$pet) {
+                $this->throwMessage([], '宠物不存在');
+                return false;
+            }
+            
+            // 检查宠物状态
+            if ($pet->status !== PetStatus::NORMAL) {
+                $this->throwMessage(['status' => $pet->status->value], '宠物当前状态({status})不允许洗髓');
+                return false;
+            }
+            
+            // 如果使用道具
+            if ($itemId > 0) {
+                // 验证物品是否为洗髓道具
+                $remouldItemId = config('pet.remould_cost.item_id');
+                if ($itemId != $remouldItemId) {
+                    $this->throwMessage(['itemId' => $itemId], '物品({itemId})不是洗髓道具');
+                    return false;
+                }
+            }
+            
+            return true;
+        } catch (\Exception $e) {
+            $this->throwMessage(['error' => $e->getMessage()], '验证过程发生错误: {error}');
+            return false;
+        }
+    }
+}

+ 95 - 0
app/Module/Pet/Validators/PetSkillUseValidator.php

@@ -0,0 +1,95 @@
+<?php
+
+namespace App\Module\Pet\Validators;
+
+use App\Module\Pet\Enums\PetStatus;
+use App\Module\Pet\Models\PetSkill;
+use App\Module\Pet\Models\PetUser;
+use UCore\Validator;
+use UCore\Validator\ValidationMessage;
+
+/**
+ * 宠物技能使用验证器
+ * 
+ * 用于验证宠物技能使用条件的合法性
+ */
+class PetSkillUseValidator extends Validator
+{
+    use ValidationMessage;
+    
+    /**
+     * 验证方法
+     * 
+     * @param mixed $value 宠物ID
+     * @param array $data 所有数据
+     * @return bool 验证是否通过
+     */
+    public function validate(mixed $value, array $data): bool
+    {
+        $petId = $value;
+        $skillId = $data['skillId'] ?? 0;
+        
+        try {
+            // 获取宠物信息
+            $pet = PetUser::find($petId);
+            
+            if (!$pet) {
+                $this->throwMessage([], '宠物不存在');
+                return false;
+            }
+            
+            // 获取技能信息
+            $skill = PetSkill::find($skillId);
+            if (!$skill) {
+                $this->throwMessage(['skillId' => $skillId], '技能({skillId})不存在');
+                return false;
+            }
+            
+            // 检查宠物状态
+            if ($pet->status !== PetStatus::NORMAL) {
+                $this->throwMessage(['status' => $pet->status->value], '宠物当前状态({status})不允许使用技能');
+                return false;
+            }
+            
+            // 检查宠物等级是否满足技能要求
+            if ($pet->level < $skill->min_level) {
+                $this->throwMessage([
+                    'level' => $pet->level,
+                    'required' => $skill->min_level
+                ], '宠物等级({level})不足,需要等级({required})才能使用该技能');
+                return false;
+            }
+            
+            // 检查宠物体力是否足够
+            if ($pet->stamina < $skill->stamina_cost) {
+                $this->throwMessage([
+                    'stamina' => $pet->stamina,
+                    'required' => $skill->stamina_cost
+                ], '宠物体力({stamina})不足,需要体力({required})才能使用该技能');
+                return false;
+            }
+            
+            // 检查技能冷却时间
+            $lastUsed = $pet->skillLogs()
+                ->where('skill_id', $skillId)
+                ->orderBy('used_at', 'desc')
+                ->first();
+            
+            if ($lastUsed) {
+                $cooldownSeconds = $skill->cool_down;
+                $secondsSinceLastUse = now()->diffInSeconds($lastUsed->used_at);
+                
+                if ($secondsSinceLastUse < $cooldownSeconds) {
+                    $remainingCooldown = $cooldownSeconds - $secondsSinceLastUse;
+                    $this->throwMessage(['remaining' => $remainingCooldown], '技能冷却中,还需等待{remaining}秒');
+                    return false;
+                }
+            }
+            
+            return true;
+        } catch (\Exception $e) {
+            $this->throwMessage(['error' => $e->getMessage()], '验证过程发生错误: {error}');
+            return false;
+        }
+    }
+}

+ 66 - 0
app/Module/Pet/Validators/PetStatusChangeValidator.php

@@ -0,0 +1,66 @@
+<?php
+
+namespace App\Module\Pet\Validators;
+
+use App\Module\Pet\Enums\PetStatus;
+use App\Module\Pet\Models\PetUser;
+use UCore\Validator;
+use UCore\Validator\ValidationMessage;
+
+/**
+ * 宠物状态变更验证器
+ * 
+ * 用于验证宠物状态变更条件的合法性
+ */
+class PetStatusChangeValidator extends Validator
+{
+    use ValidationMessage;
+    
+    /**
+     * 验证方法
+     * 
+     * @param mixed $value 宠物ID
+     * @param array $data 所有数据
+     * @return bool 验证是否通过
+     */
+    public function validate(mixed $value, array $data): bool
+    {
+        $petId = $value;
+        $newStatus = $data['newStatus'] ?? null;
+        
+        if (!$newStatus instanceof PetStatus) {
+            $this->throwMessage([], '新状态无效');
+            return false;
+        }
+        
+        try {
+            // 获取宠物信息
+            $pet = PetUser::find($petId);
+            
+            if (!$pet) {
+                $this->throwMessage([], '宠物不存在');
+                return false;
+            }
+            
+            // 检查状态变更是否合法
+            // 这里可以根据业务需求添加更多的状态变更规则
+            
+            // 例如:死亡状态的宠物不能变为其他状态
+            if ($pet->status === PetStatus::DEAD && $newStatus !== PetStatus::DEAD) {
+                $this->throwMessage([], '死亡状态的宠物不能变更为其他状态');
+                return false;
+            }
+            
+            // 例如:战斗中的宠物不能直接变为训练中
+            if ($pet->status === PetStatus::FIGHTING && $newStatus === PetStatus::TRAINING) {
+                $this->throwMessage([], '战斗中的宠物不能直接变更为训练中状态');
+                return false;
+            }
+            
+            return true;
+        } catch (\Exception $e) {
+            $this->throwMessage(['error' => $e->getMessage()], '验证过程发生错误: {error}');
+            return false;
+        }
+    }
+}