MainUIControlller.ts 17 KB

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