Wall.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import { _decorator, Component, Node, Label, find, JsonAsset, Collider2D, RigidBody2D, ERigidBody2DType, BoxCollider2D } from 'cc';
  2. import { SaveDataManager } from '../LevelSystem/SaveDataManager';
  3. import EventBus, { GameEvents } from '../Core/EventBus';
  4. import { JsonConfigLoader } from '../Core/JsonConfigLoader';
  5. import { SkillManager } from './SkillSelection/SkillManager';
  6. const { ccclass, property } = _decorator;
  7. /**
  8. * 墙体组件
  9. * 负责管理墙体的血量、伤害处理、等级升级等功能
  10. */
  11. @ccclass('Wall')
  12. export class Wall extends Component {
  13. @property({
  14. type: Node,
  15. tooltip: '血量显示节点 (HeartLabel)'
  16. })
  17. public heartLabelNode: Node = null;
  18. // @property({
  19. // type: JsonAsset,
  20. // tooltip: '墙体配置文件'
  21. // })
  22. // public wallConfigAsset: JsonAsset = null; // 已改为动态加载
  23. // === 私有属性 ===
  24. private currentHealth: number = 100;
  25. private heartLabel: Label = null;
  26. private saveDataManager: SaveDataManager = null;
  27. // 墙体配置数据
  28. private wallConfig: any = null;
  29. private wallHpMap: Record<number, number> = {};
  30. async start() {
  31. await this.initializeWall();
  32. }
  33. /**
  34. * 加载墙体配置
  35. */
  36. private async loadWallConfig(): Promise<void> {
  37. try {
  38. this.wallConfig = await JsonConfigLoader.getInstance().loadConfig('wall');
  39. if (this.wallConfig && this.wallConfig.wallConfig && this.wallConfig.wallConfig.healthByLevel) {
  40. // 转换字符串键为数字键
  41. const healthByLevel = this.wallConfig.wallConfig.healthByLevel;
  42. this.wallHpMap = {};
  43. for (const level in healthByLevel) {
  44. this.wallHpMap[parseInt(level)] = healthByLevel[level];
  45. }
  46. console.log('[Wall] 墙体配置加载成功:', this.wallHpMap);
  47. } else {
  48. console.warn('[Wall] 配置文件格式错误,使用默认配置');
  49. this.useDefaultConfig();
  50. }
  51. } catch (error) {
  52. console.error('[Wall] 加载wall.json时出错:', error);
  53. this.useDefaultConfig();
  54. }
  55. }
  56. /**
  57. * 使用默认配置
  58. */
  59. private useDefaultConfig(): void {
  60. this.wallHpMap = {
  61. 1: 100,
  62. 2: 500,
  63. 3: 1200,
  64. 4: 1500,
  65. 5: 2000
  66. };
  67. }
  68. /**
  69. * 设置墙体碰撞器
  70. * 确保墙体能够与敌人发生碰撞
  71. */
  72. private setupWallCollider(): void {
  73. // 检查是否已有碰撞器组件
  74. let collider = this.node.getComponent(Collider2D);
  75. if (!collider) {
  76. // 添加BoxCollider2D组件
  77. collider = this.node.addComponent(BoxCollider2D);
  78. console.log(`[Wall] 为墙体节点 ${this.node.name} 添加碰撞器组件`);
  79. }
  80. // 确保有RigidBody2D组件
  81. let rigidBody = this.node.getComponent(RigidBody2D);
  82. if (!rigidBody) {
  83. rigidBody = this.node.addComponent(RigidBody2D);
  84. console.log(`[Wall] 为墙体节点 ${this.node.name} 添加刚体组件`);
  85. }
  86. // 设置刚体属性
  87. if (rigidBody) {
  88. rigidBody.type = ERigidBody2DType.Static; // 静态刚体
  89. rigidBody.enabledContactListener = true; // 启用碰撞监听
  90. }
  91. // 设置碰撞器属性
  92. if (collider) {
  93. collider.sensor = false; // 不是传感器,会产生物理碰撞
  94. }
  95. console.log(`[Wall] 墙体 ${this.node.name} 碰撞器设置完成,碰撞器启用: ${collider?.enabled}, 刚体启用: ${rigidBody?.enabled}`);
  96. }
  97. /**
  98. * 初始化墙体
  99. */
  100. private async initializeWall() {
  101. // 初始化存档管理器
  102. this.saveDataManager = SaveDataManager.getInstance();
  103. if (!this.saveDataManager) {
  104. console.error('[Wall] SaveDataManager not found');
  105. return;
  106. }
  107. // 加载墙体配置
  108. await this.loadWallConfig();
  109. // 查找血量显示节点
  110. this.findHeartLabelNode();
  111. // 从存档读取墙体血量
  112. this.loadWallHealthFromSave();
  113. // 初始化血量显示
  114. this.updateHealthDisplay();
  115. // 设置墙体碰撞器
  116. this.setupWallCollider();
  117. // 监听治疗技能变化
  118. this.setupSkillListeners();
  119. // 设置事件监听器
  120. this.setupEventListeners();
  121. }
  122. /**
  123. * 查找血量显示节点
  124. */
  125. private findHeartLabelNode() {
  126. // 查找心血显示节点
  127. if (!this.heartLabelNode) {
  128. this.heartLabelNode = find('Canvas-001/TopArea/HeartNode/HeartLabel') || find('Canvas/GameLevelUI/HeartNode/HeartLabel');
  129. }
  130. if (this.heartLabelNode) {
  131. this.heartLabel = this.heartLabelNode.getComponent(Label);
  132. }
  133. }
  134. /**
  135. * 从存档加载墙体血量
  136. */
  137. private loadWallHealthFromSave() {
  138. // 直接从SaveDataManager获取当前墙体血量
  139. this.currentHealth = this.saveDataManager.getWallHealth();
  140. console.log('[Wall] 从配置加载墙体血量:', this.currentHealth);
  141. // 确保当前血量不超过最大血量(考虑技能加成)
  142. const maxHealth = this.getMaxHealth();
  143. if (this.currentHealth > maxHealth) {
  144. this.currentHealth = maxHealth;
  145. }
  146. }
  147. /**
  148. * 墙体受到伤害
  149. */
  150. public takeDamage(damage: number) {
  151. if (damage <= 0) return;
  152. const previousHealth = this.currentHealth;
  153. this.currentHealth = Math.max(0, this.currentHealth - damage);
  154. // 触发受到伤害事件
  155. const eventBus = EventBus.getInstance();
  156. eventBus.emit(GameEvents.WALL_TAKE_DAMAGE, {
  157. damage: damage,
  158. previousHealth: previousHealth,
  159. currentHealth: this.currentHealth
  160. });
  161. // 触发血量变化事件
  162. eventBus.emit(GameEvents.WALL_HEALTH_CHANGED, {
  163. previousHealth: previousHealth,
  164. currentHealth: this.currentHealth,
  165. maxHealth: this.getMaxHealth()
  166. });
  167. // 更新血量显示
  168. this.updateHealthDisplay();
  169. console.log(`[Wall] 墙体受到伤害: ${damage}, 当前血量: ${this.currentHealth}`);
  170. // 检查墙体是否被摧毁
  171. if (this.currentHealth <= 0) {
  172. this.onWallDestroyed();
  173. }
  174. }
  175. /**
  176. * 墙体被摧毁时的处理
  177. * 统一与菜单退出的失败处理流程,直接触发GAME_DEFEAT事件
  178. */
  179. private onWallDestroyed() {
  180. console.log('[Wall] 墙体被摧毁,触发游戏失败');
  181. // 通过事件系统触发墙体被摧毁事件(保留用于其他监听器)
  182. const eventBus = EventBus.getInstance();
  183. eventBus.emit(GameEvents.WALL_DESTROYED, {
  184. finalHealth: this.currentHealth,
  185. maxHealth: this.getMaxHealth()
  186. });
  187. // 统一失败处理:直接触发GAME_DEFEAT事件,与菜单退出处理保持一致
  188. console.log('[Wall] 直接触发GAME_DEFEAT事件,与菜单退出失败处理流程一致');
  189. eventBus.emit(GameEvents.GAME_DEFEAT);
  190. }
  191. /**
  192. * 更新血量显示
  193. */
  194. public updateHealthDisplay() {
  195. if (this.heartLabel) {
  196. this.heartLabel.string = Math.floor(this.currentHealth).toString();
  197. }
  198. }
  199. /**
  200. * 设置墙体血量
  201. */
  202. public setHealth(health: number) {
  203. const previousHealth = this.currentHealth;
  204. this.currentHealth = Math.max(0, health);
  205. // 如果血量发生变化,触发血量变化事件
  206. if (previousHealth !== this.currentHealth) {
  207. const eventBus = EventBus.getInstance();
  208. eventBus.emit(GameEvents.WALL_HEALTH_CHANGED, {
  209. previousHealth: previousHealth,
  210. currentHealth: this.currentHealth,
  211. maxHealth: this.getMaxHealth()
  212. });
  213. }
  214. this.updateHealthDisplay();
  215. }
  216. /**
  217. * 获取当前墙体血量
  218. */
  219. public getCurrentHealth(): number {
  220. return this.currentHealth;
  221. }
  222. /**
  223. * 获取最大血量(基于当前等级和技能加成)
  224. */
  225. public getMaxHealth(): number {
  226. const currentLevel = this.getCurrentWallLevel();
  227. const baseMaxHealth = this.getWallHealthByLevel(currentLevel);
  228. // 应用治疗技能的最大血量加成
  229. const skillManager = SkillManager.getInstance();
  230. if (skillManager) {
  231. const healSkillLevel = skillManager.getSkillLevel('heal');
  232. const healthBonus = SkillManager.getHealSkillHealthBonus(healSkillLevel);
  233. return Math.floor(baseMaxHealth * (1 + healthBonus));
  234. }
  235. return baseMaxHealth;
  236. }
  237. /**
  238. * 根据等级获取墙体血量
  239. */
  240. public getWallHealthByLevel(level: number): number {
  241. // 使用本地配置
  242. return this.wallHpMap[level] || (100 + (level - 1) * 200);
  243. }
  244. /**
  245. * 获取当前墙壁等级
  246. */
  247. public getCurrentWallLevel(): number {
  248. return this.saveDataManager?.getWallLevel() || 1;
  249. }
  250. /**
  251. * 恢复墙体血量
  252. */
  253. public heal(amount: number) {
  254. const previousHealth = this.currentHealth;
  255. const maxHealth = this.getMaxHealth();
  256. this.currentHealth = Math.min(maxHealth, this.currentHealth + amount);
  257. // 如果血量发生变化,触发血量变化事件
  258. if (previousHealth !== this.currentHealth) {
  259. const eventBus = EventBus.getInstance();
  260. eventBus.emit(GameEvents.WALL_HEALTH_CHANGED, {
  261. previousHealth: previousHealth,
  262. currentHealth: this.currentHealth,
  263. maxHealth: maxHealth,
  264. healAmount: this.currentHealth - previousHealth
  265. });
  266. }
  267. this.updateHealthDisplay();
  268. }
  269. /**
  270. * 重置墙体血量到满血
  271. */
  272. public resetToFullHealth() {
  273. this.currentHealth = this.getMaxHealth();
  274. this.updateHealthDisplay();
  275. }
  276. /**
  277. * 获取血量百分比
  278. */
  279. public getHealthPercentage(): number {
  280. const maxHealth = this.getMaxHealth();
  281. return maxHealth > 0 ? this.currentHealth / maxHealth : 0;
  282. }
  283. /**
  284. * 检查墙体是否存活
  285. */
  286. public isAlive(): boolean {
  287. return this.currentHealth > 0;
  288. }
  289. /**
  290. * 设置事件监听器
  291. */
  292. private setupEventListeners() {
  293. const eventBus = EventBus.getInstance();
  294. // 监听重置墙体血量事件
  295. eventBus.on(GameEvents.RESET_WALL_HEALTH, this.onResetWallHealthEvent, this);
  296. // 监听墙体血量变化事件(用于升级后更新显示)
  297. eventBus.on(GameEvents.WALL_HEALTH_CHANGED, this.onWallHealthChangedEvent, this);
  298. }
  299. /**
  300. * 处理重置墙体血量事件
  301. */
  302. private onResetWallHealthEvent() {
  303. console.log('[Wall] 接收到重置墙体血量事件,重置到满血');
  304. this.resetToFullHealth();
  305. }
  306. /**
  307. * 处理墙体血量变化事件(用于升级后更新)
  308. */
  309. private onWallHealthChangedEvent(eventData?: any) {
  310. // 只有在特定情况下才重新加载存档数据,避免覆盖受伤后的血量
  311. // 如果事件数据包含isUpgrade标志,说明是升级触发的,需要重新加载
  312. if (eventData && eventData.isUpgrade) {
  313. console.log('[Wall] 接收到墙体升级事件,重新加载血量数据');
  314. this.loadWallHealthFromSave();
  315. this.updateHealthDisplay();
  316. }
  317. // 其他情况(如受伤、治疗)不需要重新加载存档,血量已经在相应方法中更新
  318. }
  319. /**
  320. * 设置技能监听器
  321. */
  322. private setupSkillListeners() {
  323. const skillManager = SkillManager.getInstance();
  324. if (skillManager) {
  325. // 监听治疗技能变化
  326. skillManager.onSkillChanged('heal', this.onHealSkillChanged.bind(this));
  327. }
  328. }
  329. /**
  330. * 治疗技能变化回调
  331. */
  332. private onHealSkillChanged(skillId: string, level: number) {
  333. console.log(`[Wall] 治疗技能等级变化: ${level}`);
  334. // 技能升级时,墙体最大血量可能增加,需要更新显示
  335. this.updateHealthDisplay();
  336. // 如果当前血量低于新的最大血量,可以考虑给予一些额外治疗
  337. // 这里暂时不做额外处理,因为SkillSelectionController已经处理了即时治疗
  338. }
  339. /**
  340. * 清理技能监听器
  341. */
  342. private cleanupSkillListeners() {
  343. const skillManager = SkillManager.getInstance();
  344. if (skillManager) {
  345. skillManager.offSkillChanged('heal', this.onHealSkillChanged.bind(this));
  346. }
  347. }
  348. onDestroy() {
  349. // 清理事件监听
  350. const eventBus = EventBus.getInstance();
  351. eventBus.off(GameEvents.RESET_WALL_HEALTH, this.onResetWallHealthEvent, this);
  352. eventBus.off(GameEvents.WALL_HEALTH_CHANGED, this.onWallHealthChangedEvent, this);
  353. this.cleanupSkillListeners();
  354. }
  355. }