MainUIControlller.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. // MainUIController.ts
  2. import { _decorator, Component, Node, Button, Label, JsonAsset, resources } from 'cc';
  3. import { SaveDataManager } from '../../LevelSystem/SaveDataManager';
  4. import { GameManager, AppState } from '../../LevelSystem/GameManager';
  5. import { GameState } from '../../LevelSystem/IN_game';
  6. import { GameStartMove } from '../../Animations/GameStartMove';
  7. import { TopBarController } from '../TopBarController';
  8. import { MoneyAni } from '../../Animations/MoneyAni';
  9. import EventBus, { GameEvents } from '../../Core/EventBus';
  10. import { Audio } from '../../AudioManager/AudioManager';
  11. import { BundleLoader } from '../../Core/BundleLoader';
  12. const { ccclass, property } = _decorator;
  13. @ccclass('MainUIController')
  14. export class MainUIController extends Component {
  15. /* 奖励节点 */
  16. @property(Node) rewardMoneyNode: Node = null; // 左钞票奖励
  17. @property(Node) rewardDiamondNode: Node = null; // 右钻石奖励
  18. @property(Label) levelNumberLabel: Label = null; // 第 X 关文本
  19. /* 升级 */
  20. @property(Button) upgradeBtn: Button = null; // 升级按钮
  21. @property(Node) upgradeCostLabel: Node = null; // 消耗钞票数字
  22. @property(Node) upgradeHpLabel: Node = null; // 升级后血量数字
  23. @property(Label) upgradeCurrentHpLabel: Label = null; // 当前血量Label
  24. @property(Label) upgradeNextHpLabel: Label = null; // 升级后血量Label
  25. /* 墙体配置 */
  26. // @property(JsonAsset) wallConfigAsset: JsonAsset = null; // 墙体配置JSON资源 - 已改为动态加载
  27. /* 主功能按钮 */
  28. @property(Node) battleBtn: Node = null; // 战斗
  29. // 底栏按钮由 NavBarController 统一管理,这里不再需要引用
  30. @property(Node) topArea: Node = null; // Canvas-001/TopArea
  31. /* UI节点引用 - 替换find查找 */
  32. @property(Node) mainUI: Node = null; // Canvas/MainUI
  33. @property(Node) gameUI: Node = null; // Canvas/GameLevelUI
  34. @property(Node) gameManagerNode: Node = null; // Canvas/GameLevelUI/GameManager
  35. @property(Node) navBarNode: Node = null; // Canvas/NavBar
  36. @property(Node) topBarNode: Node = null; // Canvas/TopBar
  37. @property(Node) cameraNode: Node = null; // Canvas/Camera
  38. /* 奖励动画系统 */
  39. @property(Node) moneyAniNode: Node = null; // MoneyAni节点
  40. private sdm: SaveDataManager = null;
  41. private wallConfig: any = null;
  42. async onLoad () {
  43. console.log('[MainUIController] onLoad 开始执行');
  44. this.sdm = SaveDataManager.getInstance();
  45. await this.loadWallConfig();
  46. this.sdm.initialize();
  47. console.log('[MainUIController] SaveDataManager 初始化完成');
  48. this.bindButtons();
  49. this.refreshAll();
  50. // TopArea 默认隐藏,在点击战斗后再显示
  51. if (this.topArea) this.topArea.active = false;
  52. // 播放主界面背景音乐(等待bundle加载完成)
  53. await this.playMainUIBGM();
  54. console.log('[MainUIController] onLoad 执行完成');
  55. }
  56. /* 绑定按钮事件 */
  57. private bindButtons () {
  58. console.log('[MainUIController] bindButtons 开始执行');
  59. console.log('[MainUIController] upgradeBtn 状态:', this.upgradeBtn ? '已设置' : '未设置');
  60. console.log('[MainUIController] battleBtn 状态:', this.battleBtn ? '已设置' : '未设置');
  61. // 升级按钮绑定 - upgradeBtn是Button类型
  62. if (this.upgradeBtn) {
  63. console.log('[MainUIController] upgradeBtn.node:', this.upgradeBtn.node ? '存在' : '不存在');
  64. this.upgradeBtn.node.on(Button.EventType.CLICK, this.upgradeWallHp, this);
  65. console.log('[MainUIController] 升级按钮事件已绑定');
  66. } else {
  67. console.error('[MainUIController] upgradeBtn未设置,无法绑定升级事件');
  68. }
  69. // 战斗按钮绑定 - battleBtn是Node类型
  70. if (this.battleBtn) {
  71. this.battleBtn.on(Button.EventType.CLICK, this.onBattle, this);
  72. console.log('[MainUIController] 战斗按钮事件已绑定');
  73. } else {
  74. console.error('[MainUIController] battleBtn未设置,无法绑定战斗事件');
  75. }
  76. console.log('[MainUIController] bindButtons 执行完成');
  77. }
  78. /* ================= 配置加载 ================= */
  79. /**
  80. * 加载墙体配置
  81. */
  82. private async loadWallConfig(): Promise<void> {
  83. try {
  84. const bundleLoader = BundleLoader.getInstance();
  85. const wallData = await bundleLoader.loadDataJson('wall');
  86. if (!wallData) {
  87. console.error('[MainUIController] 墙体配置文件内容为空');
  88. return;
  89. }
  90. this.wallConfig = wallData.json;
  91. console.log('[MainUIController] 墙体配置加载成功:', this.wallConfig);
  92. // 将配置传递给SaveDataManager
  93. this.sdm.setWallConfig(this.wallConfig);
  94. } catch (error) {
  95. console.error('[MainUIController] 加载墙体配置失败:', error);
  96. }
  97. }
  98. /**
  99. * 获取墙体升级费用
  100. */
  101. private getWallUpgradeCost(level: number): number {
  102. if (this.wallConfig && this.wallConfig.wallConfig && this.wallConfig.wallConfig.upgradeCosts) {
  103. const costs = this.wallConfig.wallConfig.upgradeCosts;
  104. return costs[level.toString()] || 0;
  105. }
  106. return 0;
  107. }
  108. /**
  109. * 获取墙体血量
  110. */
  111. private getWallHealthByLevel(level: number): number {
  112. if (this.wallConfig && this.wallConfig.wallConfig && this.wallConfig.wallConfig.healthByLevel) {
  113. const healthByLevel = this.wallConfig.wallConfig.healthByLevel;
  114. return healthByLevel[level.toString()] || 100;
  115. }
  116. return 100;
  117. }
  118. /**
  119. * 获取墙体最大等级
  120. */
  121. private getWallMaxLevel(): number {
  122. if (this.wallConfig && this.wallConfig.wallConfig && this.wallConfig.wallConfig.maxLevel) {
  123. return this.wallConfig.wallConfig.maxLevel;
  124. }
  125. return 5;
  126. }
  127. /* ================= 业务逻辑 ================= */
  128. private upgradeWallHp () {
  129. // 播放UI点击音效
  130. Audio.playUISound('data/弹球音效/level up 2');
  131. console.log('[MainUIController] 升级墙体按钮被点击');
  132. // 检查SaveDataManager是否初始化
  133. if (!this.sdm) {
  134. console.error('[MainUIController] SaveDataManager未初始化');
  135. return;
  136. }
  137. // 打印当前状态用于调试
  138. const currentMoney = this.sdm.getMoney();
  139. const currentWallLevel = this.sdm.getWallLevel();
  140. const upgradeCost = this.getWallUpgradeCost(currentWallLevel);
  141. console.log(`[MainUIController] 当前状态: 钞票=${currentMoney}, 墙体等级=${currentWallLevel}, 升级费用=${upgradeCost}`);
  142. // 检查墙体等级是否已达到最大值
  143. const maxLevel = this.getWallMaxLevel();
  144. if (currentWallLevel >= maxLevel) {
  145. console.log('[MainUIController] 墙体已达到最大等级');
  146. EventBus.getInstance().emit(GameEvents.SHOW_TOAST, {
  147. message: '墙体已达到最大等级',
  148. duration: 2.0
  149. });
  150. return;
  151. }
  152. // 检查钞票是否足够
  153. if (currentMoney < upgradeCost) {
  154. EventBus.getInstance().emit(GameEvents.SHOW_RESOURCE_TOAST, {
  155. message: `钞票不足,需要${upgradeCost}钞票`,
  156. duration: 2.0
  157. });
  158. return;
  159. }
  160. // 执行升级
  161. if (!this.sdm.spendMoney(upgradeCost)) {
  162. console.log('[MainUIController] 扣除钞票失败');
  163. return;
  164. }
  165. if (!this.sdm.upgradeWallLevel()) {
  166. console.log('[MainUIController] 墙体升级失败');
  167. return;
  168. }
  169. console.log('[MainUIController] 墙体升级成功');
  170. // 刷新所有UI显示
  171. this.refreshAll();
  172. // 通过事件系统通知UI更新
  173. EventBus.getInstance().emit(GameEvents.CURRENCY_CHANGED);
  174. // 通知墙体组件更新血量显示
  175. const newLevel = this.sdm.getWallLevel();
  176. const newHealth = this.getWallHealthByLevel(newLevel);
  177. EventBus.getInstance().emit(GameEvents.WALL_HEALTH_CHANGED, {
  178. previousHealth: 0,
  179. currentHealth: newHealth,
  180. maxHealth: newHealth
  181. });
  182. }
  183. private onBattle () {
  184. // 停止主界面背景音乐,避免与游戏内音效冲突
  185. Audio.stopMusic();
  186. // 播放战斗背景音乐,音量较小
  187. setTimeout(() => {
  188. Audio.playMusic('data/弹球音效/fight bgm', true);
  189. Audio.setMusicVolume(0.4); // 设置较小的音量
  190. console.log('[MainUIController] 开始播放战斗背景音乐');
  191. }, 500); // 延迟500ms等start zombie音效播放
  192. // 显示 TopArea(拖拽引用),避免使用 find()
  193. if (this.topArea) this.topArea.active = true;
  194. // 若上一关已完成则自动+1
  195. const lvl = this.sdm.getCurrentLevel();
  196. if (this.sdm.isLevelCompleted(lvl)) {
  197. const pd = this.sdm.getPlayerData();
  198. pd.currentLevel = lvl + 1;
  199. this.sdm.savePlayerData();
  200. }
  201. this.refreshLevelNumber();
  202. // 切场景 UI - 使用装饰器引用
  203. if (this.mainUI) this.mainUI.active = false;
  204. if (this.gameUI) this.gameUI.active = true;
  205. const gm = this.gameManagerNode?.getComponent(GameManager);
  206. // 设置应用状态为游戏中(会自动隐藏TopBar和NavBar)
  207. gm?.setAppState(AppState.IN_GAME);
  208. // 统一使用StartGame启动游戏流程
  209. const eventBus = EventBus.getInstance();
  210. eventBus.emit(GameEvents.GAME_START);
  211. gm?.loadCurrentLevelConfig();
  212. // 镜头下移动画现在已集成到StartGame流程中的slideUpFromBottom方法里
  213. }
  214. /* ================= 刷新 ================= */
  215. private refreshLevelNumber(){
  216. if (this.levelNumberLabel) this.levelNumberLabel.string = `第 ${this.sdm.getCurrentLevel()} 关`;
  217. }
  218. private refreshAll(){
  219. this.refreshLevelNumber();
  220. this.refreshUpgradeInfo();
  221. this.refreshRewardDisplay();
  222. }
  223. /** 刷新奖励显示 - 从JSON配置读取 */
  224. private async refreshRewardDisplay() {
  225. const currentLevel = this.sdm.getCurrentLevel();
  226. try {
  227. // 从SaveDataManager获取关卡奖励配置
  228. const rewards = await this.sdm.getLevelRewardsFromConfig(currentLevel);
  229. if (rewards) {
  230. // 更新钞票奖励显示
  231. if (this.rewardMoneyNode) {
  232. const coinLabel = this.rewardMoneyNode.getComponent(Label) || this.rewardMoneyNode.getComponentInChildren(Label);
  233. if (coinLabel) {
  234. coinLabel.string = rewards.money.toString();
  235. }
  236. }
  237. // 更新钻石奖励显示
  238. if (this.rewardDiamondNode) {
  239. const diamondLabel = this.rewardDiamondNode.getComponent(Label) || this.rewardDiamondNode.getComponentInChildren(Label);
  240. if (diamondLabel) {
  241. diamondLabel.string = rewards.diamonds.toString();
  242. }
  243. }
  244. } else {
  245. console.warn(`无法获取关卡${currentLevel}的奖励配置,使用默认值`);
  246. // 使用默认奖励值
  247. this.setDefaultRewards();
  248. }
  249. } catch (error) {
  250. console.error('刷新奖励显示时出错:', error);
  251. this.setDefaultRewards();
  252. }
  253. }
  254. /** 设置默认奖励值 */
  255. private setDefaultRewards() {
  256. // 钞票奖励默认值
  257. if (this.rewardMoneyNode) {
  258. const coinLabel = this.rewardMoneyNode.getComponent(Label) || this.rewardMoneyNode.getComponentInChildren(Label);
  259. if (coinLabel) {
  260. coinLabel.string = '50';
  261. }
  262. }
  263. // 钻石奖励默认值
  264. if (this.rewardDiamondNode) {
  265. const diamondLabel = this.rewardDiamondNode.getComponent(Label) || this.rewardDiamondNode.getComponentInChildren(Label);
  266. if (diamondLabel) {
  267. diamondLabel.string = '5';
  268. }
  269. }
  270. }
  271. /** 刷新升级信息显示 */
  272. private refreshUpgradeInfo () {
  273. console.log('[MainUIController] refreshUpgradeInfo 开始执行');
  274. const costLbl = this.upgradeCostLabel?.getComponent(Label);
  275. const hpLbl = this.upgradeHpLabel?.getComponent(Label);
  276. // 显示升级费用
  277. const currentLevel = this.sdm.getWallLevel();
  278. const cost = this.getWallUpgradeCost(currentLevel);
  279. if (costLbl) {
  280. costLbl.string = cost.toString();
  281. console.log(`[MainUIController] 升级费用: ${cost}`);
  282. }
  283. // 显示当前和下一级血量
  284. const currentHp = this.getWallHealthByLevel(currentLevel);
  285. // 计算下一级血量 - 使用配置数据
  286. const nextHp = this.getWallHealthByLevel(currentLevel + 1);
  287. // 如果有新的分离Label,使用分离显示
  288. if (this.upgradeCurrentHpLabel && this.upgradeNextHpLabel) {
  289. this.upgradeCurrentHpLabel.string = `${currentHp}>>`;
  290. this.upgradeNextHpLabel.string = `${nextHp}`;
  291. console.log(`[MainUIController] 分离血量显示: 当前=${currentHp}, 升级后=${nextHp}, 当前等级: ${currentLevel}`);
  292. }else {
  293. console.error('[MainUIController] 升级信息标签未找到');
  294. return;
  295. }
  296. // 升级按钮始终保持可点击状态,通过Toast显示各种提示
  297. console.log(`[MainUIController] 升级按钮保持可交互状态`);
  298. }
  299. // 供外部(如 GameManager)调用的公共刷新接口
  300. public updateUI (): void {
  301. this.refreshAll();
  302. // 通过事件系统通知UI更新
  303. EventBus.getInstance().emit(GameEvents.CURRENCY_CHANGED);
  304. }
  305. /**
  306. * 游戏失败或成功返回MainUI后的UI状态管理
  307. * 隐藏Canvas-001并显示Canvas/TopBar和Canvas/NavBar
  308. */
  309. public onReturnToMainUI(): void {
  310. console.log('MainUIController.onReturnToMainUI 开始执行');
  311. // 注意:应用状态已在GameManager中设置,这里不需要重复设置
  312. // 隐藏 TopArea (Canvas-001)
  313. if (this.topArea) {
  314. this.topArea.active = false;
  315. console.log('TopArea (Canvas-001) 已隐藏');
  316. }
  317. // 显示主UI
  318. if (this.mainUI) {
  319. this.mainUI.active = true;
  320. console.log('MainUI 已显示');
  321. }
  322. // 隐藏游戏UI
  323. if (this.gameUI) {
  324. this.gameUI.active = false;
  325. console.log('GameUI 已隐藏');
  326. }
  327. // 显示顶部钱币栏 TopBar
  328. if (this.topBarNode) {
  329. this.topBarNode.active = true;
  330. console.log('TopBar 已显示');
  331. }
  332. // 显示底部导航栏 NavBar
  333. if (this.navBarNode) {
  334. this.navBarNode.active = true;
  335. console.log('NavBar 已显示');
  336. }
  337. // 播放主界面背景音乐
  338. this.playMainUIBGM();
  339. // 刷新UI显示
  340. this.refreshAll();
  341. // 通过事件系统通知UI更新
  342. EventBus.getInstance().emit(GameEvents.CURRENCY_CHANGED);
  343. console.log('MainUIController.onReturnToMainUI 执行完成');
  344. }
  345. /**
  346. * 游戏成功返回MainUI并播放奖励动画
  347. */
  348. public onReturnToMainUIWithReward(): void {
  349. console.log('MainUIController.onReturnToMainUIWithReward 开始执行');
  350. // 先执行基本的UI状态管理
  351. this.onReturnToMainUI();
  352. // 延迟播放奖励动画,确保UI已经完全显示
  353. this.scheduleOnce(() => {
  354. this.playRewardAnimation();
  355. }, 0.5);
  356. }
  357. /**
  358. * 播放奖励动画
  359. */
  360. private async playRewardAnimation(): Promise<void> {
  361. console.log('MainUIController.playRewardAnimation 开始播放奖励动画');
  362. const currentLevel = this.sdm.getCurrentLevel();
  363. try {
  364. // 直接获取SaveDataManager中已经计算好的奖励数据
  365. // 注意:不再依赖当前游戏状态判断,因为游戏数据清理可能已经重置了状态
  366. // SaveDataManager.getLastRewards()已经包含了正确的奖励信息(成功或失败奖励)
  367. const rewards = this.sdm.getLastRewards();
  368. console.log('获取已计算的奖励:', rewards);
  369. if (rewards && (rewards.money > 0 || rewards.diamonds > 0)) {
  370. // 使用MoneyAni播放奖励动画
  371. if (this.moneyAniNode) {
  372. const moneyAni = this.moneyAniNode.getComponent(MoneyAni);
  373. if (moneyAni) {
  374. moneyAni.playRewardAnimation(rewards.money, rewards.diamonds, () => {
  375. console.log('奖励动画播放完成');
  376. });
  377. } else {
  378. console.error('MoneyAni组件未找到');
  379. // 使用静态方法作为备选
  380. MoneyAni.playReward(rewards.money, rewards.diamonds);
  381. }
  382. } else {
  383. console.warn('MoneyAni节点未设置,使用静态方法播放动画');
  384. MoneyAni.playReward(rewards.money, rewards.diamonds);
  385. }
  386. } else {
  387. console.log('当前关卡没有奖励或奖励为0');
  388. }
  389. } catch (error) {
  390. console.error('播放奖励动画时出错:', error);
  391. // 使用默认奖励
  392. MoneyAni.playReward(25, 2);
  393. }
  394. }
  395. /**
  396. * 播放主界面背景音乐
  397. */
  398. private async playMainUIBGM(): Promise<void> {
  399. console.log('[MainUIController] 开始播放主界面背景音乐');
  400. try {
  401. // 获取BundleLoader实例
  402. const bundleLoader = BundleLoader.getInstance();
  403. // 确保data bundle已加载完成
  404. await bundleLoader.loadBundle('data');
  405. console.log('[MainUIController] data bundle加载完成,开始播放音乐');
  406. // 先停止当前音乐(包括战斗背景音乐)
  407. Audio.stopMusic();
  408. // 恢复正常音乐音量
  409. Audio.setMusicVolume(0.8);
  410. // 播放主界面BGM,循环播放
  411. Audio.playMusic('data/弹球音效/ui bgm', true);
  412. console.log('[MainUIController] 主界面背景音乐播放完成');
  413. } catch (error) {
  414. console.error('[MainUIController] 播放主界面背景音乐失败:', error);
  415. }
  416. }
  417. /* =============== Util =============== */
  418. private format(n:number){ return n>=1000000? (n/1e6).toFixed(1)+'M' : n>=1000? (n/1e3).toFixed(1)+'K' : n.toString(); }
  419. }