MainUIControlller.ts 17 KB

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