ShopController.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. import { _decorator, Component, Node, Label, Button, JsonAsset, Sprite, Color, SpriteFrame, director } from 'cc';
  2. import { SaveDataManager } from '../../LevelSystem/SaveDataManager';
  3. import EventBus, { GameEvents } from '../../Core/EventBus';
  4. import { TopBarController } from '../TopBarController';
  5. import { MoneyAni } from '../../Animations/MoneyAni';
  6. import { AdManager } from '../../Ads/AdManager';
  7. import { JsonConfigLoader } from '../../Core/JsonConfigLoader';
  8. const { ccclass, property } = _decorator;
  9. interface ShopConfig {
  10. dailyRewards: {
  11. money: {
  12. rewards: number[];
  13. maxClaimsPerDay: number;
  14. };
  15. diamond: {
  16. rewards: number[];
  17. maxClaimsPerDay: number;
  18. };
  19. }
  20. }
  21. interface DailyRewardData {
  22. lastResetDate: string;
  23. moneyFreeCount: number;
  24. moneyAdCount: number;
  25. diamondsFreeCount: number;
  26. diamondsAdCount: number;
  27. // 每日免费机会是否已使用
  28. moneyFreeUsed: boolean;
  29. diamondFreeUsed: boolean;
  30. }
  31. @ccclass('ShopController')
  32. export class ShopController extends Component {
  33. @property(Node)
  34. moneyRewardNode: Node = null;
  35. @property(Node)
  36. diamondRewardNode: Node = null;
  37. @property(Button)
  38. moneyButton: Button = null;
  39. @property(Button)
  40. diamondButton: Button = null;
  41. @property(Label)
  42. moneyCountLabel: Label = null;
  43. @property(Label)
  44. diamondCountLabel: Label = null;
  45. @property(Label)
  46. moneyAmountLabel: Label = null;
  47. @property(Label)
  48. diamondAmountLabel: Label = null;
  49. // @property(JsonAsset) shopConfigAsset: JsonAsset = null; // 已改为动态加载
  50. @property(Node)
  51. billSpriteNode: Node = null; // Canvas/ShopUI/ScrollView/view/content/bill/Sprite/Sprite
  52. @property(Node)
  53. diamondSpriteNode: Node = null; // Canvas/ShopUI/ScrollView/view/content/diamond/Sprite/Sprite
  54. @property(Node)
  55. moneyIconNode: Node = null; // Canvas/ShopUI/ScrollView/view/content/bill/Sprite/次数/antb-02
  56. @property(Node)
  57. diamondIconNode: Node = null; // Canvas/ShopUI/ScrollView/view/content/diamond/Sprite/次数/antb-02
  58. private shopConfig: ShopConfig = null;
  59. private dailyRewardData: DailyRewardData = null;
  60. private saveDataManager: SaveDataManager = null;
  61. private readonly DAILY_REWARD_KEY = 'daily_reward_data';
  62. /**
  63. * 格式化数字显示,在数字之间添加空格
  64. * @param num 要格式化的数字
  65. * @returns 格式化后的字符串,如 "50" -> "5 0"
  66. */
  67. private formatNumberWithSpaces(num: number): string {
  68. return num.toString().split('').join(' ');
  69. }
  70. async onLoad() {
  71. this.saveDataManager = SaveDataManager.getInstance();
  72. await this.loadShopConfig();
  73. this.loadDailyRewardData();
  74. this.setupEventListeners();
  75. }
  76. start() {
  77. this.updateUI();
  78. }
  79. private async loadShopConfig() {
  80. try {
  81. const shopData = await JsonConfigLoader.getInstance().loadConfig('shop');
  82. if (shopData) {
  83. this.shopConfig = shopData as ShopConfig;
  84. console.log('[ShopController] shop.json加载成功:', this.shopConfig);
  85. this.updateUI();
  86. } else {
  87. console.warn('[ShopController] shop.json加载失败,使用默认配置');
  88. this.useDefaultConfig();
  89. }
  90. } catch (error) {
  91. console.error('[ShopController] 加载shop.json时出错:', error);
  92. this.useDefaultConfig();
  93. }
  94. }
  95. /**
  96. * 使用默认商店配置
  97. */
  98. private useDefaultConfig() {
  99. this.shopConfig = {
  100. dailyRewards: {
  101. money: {
  102. rewards: [100, 200, 300, 400, 500],
  103. maxClaimsPerDay: 5
  104. },
  105. diamond: {
  106. rewards: [10, 20, 30, 40, 50],
  107. maxClaimsPerDay: 5
  108. }
  109. }
  110. };
  111. console.log('[ShopController] 使用默认商店配置:', this.shopConfig);
  112. this.updateUI();
  113. }
  114. private loadDailyRewardData() {
  115. const savedData = localStorage.getItem(this.DAILY_REWARD_KEY);
  116. const today = this.getCurrentDateString();
  117. if (savedData) {
  118. const data = JSON.parse(savedData) as DailyRewardData;
  119. // 兼容旧数据:如果存在旧的costFreeUsed字段,迁移到新字段
  120. if (data.hasOwnProperty('costFreeUsed')) {
  121. const oldCostFreeUsed = (data as any).costFreeUsed;
  122. data.moneyFreeUsed = oldCostFreeUsed || false;
  123. data.diamondFreeUsed = oldCostFreeUsed || false;
  124. delete (data as any).costFreeUsed;
  125. console.log('[ShopController] 迁移旧的costFreeUsed数据到新字段');
  126. }
  127. // 确保新字段存在,设置默认值
  128. if (data.moneyFreeUsed === undefined) {
  129. data.moneyFreeUsed = false; // 默认为false(未使用)
  130. console.log('[ShopController] 设置moneyFreeUsed默认值: false');
  131. }
  132. if (data.diamondFreeUsed === undefined) {
  133. data.diamondFreeUsed = false; // 默认为false(未使用)
  134. console.log('[ShopController] 设置diamondFreeUsed默认值: false');
  135. }
  136. // 检查是否需要重置(新的一天)
  137. if (data.lastResetDate !== today) {
  138. console.log('[ShopController] 检测到新的一天,重置每日奖励数据');
  139. this.resetDailyRewardData(today);
  140. } else {
  141. this.dailyRewardData = data;
  142. console.log('[ShopController] 加载已有的每日奖励数据');
  143. }
  144. } else {
  145. console.log('[ShopController] 首次运行,创建新的每日奖励数据');
  146. this.resetDailyRewardData(today);
  147. }
  148. console.log('[ShopController] 每日奖励数据:', this.dailyRewardData);
  149. }
  150. private resetDailyRewardData(date: string) {
  151. this.dailyRewardData = {
  152. lastResetDate: date,
  153. moneyFreeCount: 0,
  154. moneyAdCount: 0,
  155. diamondsFreeCount: 0,
  156. diamondsAdCount: 0,
  157. moneyFreeUsed: false,
  158. diamondFreeUsed: false
  159. };
  160. this.saveDailyRewardData();
  161. }
  162. private saveDailyRewardData() {
  163. localStorage.setItem(this.DAILY_REWARD_KEY, JSON.stringify(this.dailyRewardData));
  164. }
  165. private getCurrentDateString(): string {
  166. const now = new Date();
  167. const month = (now.getMonth() + 1).toString();
  168. const day = now.getDate().toString();
  169. const paddedMonth = month.length === 1 ? '0' + month : month;
  170. const paddedDay = day.length === 1 ? '0' + day : day;
  171. return `${now.getFullYear()}-${paddedMonth}-${paddedDay}`;
  172. }
  173. private setupEventListeners() {
  174. // 监听货币变化事件,更新UI
  175. EventBus.getInstance().on(GameEvents.CURRENCY_CHANGED, this.updateUI, this);
  176. }
  177. private updateUI() {
  178. if (!this.shopConfig || !this.dailyRewardData) return;
  179. // 更新钞票奖励UI
  180. this.updateMoneyRewardUI();
  181. // 更新钻石奖励UI
  182. this.updateDiamondRewardUI();
  183. }
  184. private updateMoneyRewardUI() {
  185. if (!this.shopConfig || !this.dailyRewardData) return;
  186. const config = this.shopConfig.dailyRewards.money;
  187. const freeCount = this.dailyRewardData.moneyFreeCount;
  188. const adCount = this.dailyRewardData.moneyAdCount;
  189. const totalCount = freeCount + adCount;
  190. const maxCount = config.maxClaimsPerDay;
  191. const freeUsed = this.dailyRewardData.moneyFreeUsed;
  192. // 计算当前次数索引(免费机会未使用时为0,否则为总次数)
  193. const currentIndex = freeUsed ? totalCount : 0;
  194. const currentReward = config.rewards[currentIndex] || config.rewards[config.rewards.length - 1];
  195. // 更新金额显示
  196. if (this.moneyAmountLabel) {
  197. this.moneyAmountLabel.string = this.formatNumberWithSpaces(currentReward);
  198. }
  199. // 更新按钮状态和显示
  200. if (this.moneyButton) {
  201. const canClaim = totalCount < maxCount;
  202. this.moneyButton.interactable = canClaim;
  203. // 更新按钮文本
  204. const buttonLabel = this.moneyButton.node.getChildByName('Label')?.getComponent(Label);
  205. if (buttonLabel) {
  206. if (!canClaim) {
  207. buttonLabel.string = "今日已达上限";
  208. } else if (!freeUsed) {
  209. buttonLabel.string = "免 费";
  210. } else {
  211. buttonLabel.string = "观看广告";
  212. }
  213. }
  214. // 更新次数显示和图标
  215. if (this.moneyCountLabel) {
  216. if (!freeUsed) {
  217. this.moneyCountLabel.string = "免 费";
  218. // 免费时隐藏图标
  219. if (this.moneyIconNode) {
  220. this.moneyIconNode.active = false;
  221. }
  222. } else {
  223. this.moneyCountLabel.string = `${totalCount}/${maxCount}`;
  224. // 观看广告时显示图标
  225. if (this.moneyIconNode) {
  226. this.moneyIconNode.active = true;
  227. }
  228. }
  229. }
  230. }
  231. }
  232. private updateDiamondRewardUI() {
  233. if (!this.shopConfig || !this.dailyRewardData) return;
  234. const config = this.shopConfig.dailyRewards.diamond;
  235. const freeCount = this.dailyRewardData.diamondsFreeCount;
  236. const adCount = this.dailyRewardData.diamondsAdCount;
  237. const totalCount = freeCount + adCount;
  238. const maxCount = config.maxClaimsPerDay;
  239. const freeUsed = this.dailyRewardData.diamondFreeUsed;
  240. // 计算当前次数索引(免费机会未使用时为0,否则为总次数)
  241. const currentIndex = freeUsed ? totalCount : 0;
  242. const currentReward = config.rewards[currentIndex] || config.rewards[config.rewards.length - 1];
  243. // 更新金额显示
  244. if (this.diamondAmountLabel) {
  245. this.diamondAmountLabel.string = this.formatNumberWithSpaces(currentReward);
  246. }
  247. // 更新按钮状态和显示
  248. if (this.diamondButton) {
  249. const canClaim = totalCount < maxCount;
  250. this.diamondButton.interactable = canClaim;
  251. // 更新按钮文本
  252. const buttonLabel = this.diamondButton.node.getChildByName('Label')?.getComponent(Label);
  253. if (buttonLabel) {
  254. if (!canClaim) {
  255. buttonLabel.string = "今日已达上限";
  256. } else if (!freeUsed) {
  257. buttonLabel.string = "免 费";
  258. } else {
  259. buttonLabel.string = "观看广告";
  260. }
  261. }
  262. // 更新次数显示和图标
  263. if (this.diamondCountLabel) {
  264. if (!freeUsed) {
  265. this.diamondCountLabel.string = "免 费";
  266. // 免费时隐藏图标
  267. if (this.diamondIconNode) {
  268. this.diamondIconNode.active = false;
  269. }
  270. } else {
  271. this.diamondCountLabel.string = `${totalCount}/${maxCount}`;
  272. // 观看广告时显示图标
  273. if (this.diamondIconNode) {
  274. this.diamondIconNode.active = true;
  275. }
  276. }
  277. }
  278. }
  279. }
  280. // 钞票奖励按钮点击事件
  281. public onMoneyRewardClick() {
  282. if (!this.shopConfig || !this.dailyRewardData) return;
  283. const config = this.shopConfig.dailyRewards.money;
  284. const freeCount = this.dailyRewardData.moneyFreeCount;
  285. const adCount = this.dailyRewardData.moneyAdCount;
  286. const totalCount = freeCount + adCount;
  287. const maxCount = config.maxClaimsPerDay;
  288. const freeUsed = this.dailyRewardData.moneyFreeUsed;
  289. if (totalCount >= maxCount) {
  290. console.log('[ShopController] 钞票奖励已达每日上限');
  291. return;
  292. }
  293. // 如果免费机会未使用,直接发放奖励
  294. if (!freeUsed) {
  295. console.log('[ShopController] 使用免费机会获取钞票奖励');
  296. this.dailyRewardData.moneyFreeUsed = true;
  297. // 免费奖励不计入freeCount,只标记为已使用
  298. this.saveDailyRewardData();
  299. this.updateUI();
  300. // 播放奖励动画并添加货币
  301. const amount = config.rewards[0] || config.rewards[config.rewards.length - 1];
  302. this.saveDataManager.addMoney(amount, 'daily_free_reward');
  303. this.playMoneyRewardAnimation(amount, () => {
  304. console.log(`[ShopController] 钞票免费奖励动画播放完成: ${amount}`);
  305. });
  306. } else {
  307. // 看广告增加次数
  308. this.showAdForMoneyReward();
  309. }
  310. }
  311. // 钻石奖励按钮点击事件
  312. public onDiamondRewardClick() {
  313. if (!this.shopConfig || !this.dailyRewardData) return;
  314. const config = this.shopConfig.dailyRewards.diamond;
  315. const freeCount = this.dailyRewardData.diamondsFreeCount;
  316. const adCount = this.dailyRewardData.diamondsAdCount;
  317. const totalCount = freeCount + adCount;
  318. const maxCount = config.maxClaimsPerDay;
  319. const freeUsed = this.dailyRewardData.diamondFreeUsed;
  320. if (totalCount >= maxCount) {
  321. console.log('[ShopController] 钻石奖励已达每日上限');
  322. return;
  323. }
  324. // 如果免费机会未使用,直接发放奖励
  325. if (!freeUsed) {
  326. console.log('[ShopController] 使用免费机会获取钻石奖励');
  327. this.dailyRewardData.diamondFreeUsed = true;
  328. // 免费奖励不计入freeCount,只标记为已使用
  329. this.saveDailyRewardData();
  330. this.updateUI();
  331. // 播放奖励动画并添加货币
  332. const amount = config.rewards[0] || config.rewards[config.rewards.length - 1];
  333. this.saveDataManager.addDiamonds(amount, 'daily_free_reward');
  334. this.playDiamondRewardAnimation(amount, () => {
  335. console.log(`[ShopController] 钻石免费奖励动画播放完成: ${amount}`);
  336. });
  337. } else {
  338. // 看广告增加次数
  339. this.showAdForDiamondReward();
  340. }
  341. }
  342. private claimMoneyReward(isFromAd: boolean) {
  343. const config = this.shopConfig.dailyRewards.money;
  344. // 更新领取次数(先更新数据)
  345. if (isFromAd) {
  346. this.dailyRewardData.moneyAdCount++;
  347. } else {
  348. this.dailyRewardData.moneyFreeCount++;
  349. }
  350. // 计算当前次数索引和对应奖励
  351. const totalCount = this.dailyRewardData.moneyFreeCount + this.dailyRewardData.moneyAdCount;
  352. const currentIndex = totalCount - 1; // 减1因为已经增加了次数
  353. const amount = config.rewards[currentIndex] || config.rewards[config.rewards.length - 1];
  354. this.saveDailyRewardData();
  355. this.updateUI();
  356. console.log(`[ShopController] 开始播放钞票奖励动画: ${amount}, 来源: ${isFromAd ? '广告' : '免费'}`);
  357. // 添加货币到账户并播放奖励动画
  358. this.saveDataManager.addMoney(amount, isFromAd ? 'daily_ad_reward' : 'daily_free_reward');
  359. this.playMoneyRewardAnimation(amount, () => {
  360. console.log(`[ShopController] 钞票奖励动画播放完成: ${amount}`);
  361. });
  362. }
  363. private claimDiamondReward(isFromAd: boolean) {
  364. const config = this.shopConfig.dailyRewards.diamond;
  365. // 更新领取次数(先更新数据)
  366. if (isFromAd) {
  367. this.dailyRewardData.diamondsAdCount++;
  368. } else {
  369. this.dailyRewardData.diamondsFreeCount++;
  370. }
  371. // 计算当前次数索引和对应奖励
  372. const totalCount = this.dailyRewardData.diamondsFreeCount + this.dailyRewardData.diamondsAdCount;
  373. const currentIndex = totalCount - 1; // 减1因为已经增加了次数
  374. const amount = config.rewards[currentIndex] || config.rewards[config.rewards.length - 1];
  375. this.saveDailyRewardData();
  376. this.updateUI();
  377. console.log(`[ShopController] 开始播放钻石奖励动画: ${amount}, 来源: ${isFromAd ? '广告' : '免费'}`);
  378. // 播放奖励动画,动画完成后会自动添加钻石
  379. this.playDiamondRewardAnimation(amount, () => {
  380. console.log(`[ShopController] 钻石奖励动画播放完成: ${amount}`);
  381. });
  382. }
  383. private showAdForMoneyReward() {
  384. console.log('[ShopController] 显示钞票奖励广告');
  385. // 显示激励视频广告
  386. AdManager.getInstance().showRewardedVideoAd(
  387. () => {
  388. // 广告观看完成,发放钞票奖励
  389. console.log('[ShopController] 广告观看完成,发放钞票奖励');
  390. this.claimMoneyReward(true);
  391. },
  392. (error) => {
  393. console.error('[ShopController] 钞票奖励广告显示失败:', error);
  394. // 广告失败时不给予奖励
  395. }
  396. );
  397. }
  398. private showAdForDiamondReward() {
  399. console.log('[ShopController] 显示钻石奖励广告');
  400. // 显示激励视频广告
  401. AdManager.getInstance().showRewardedVideoAd(
  402. () => {
  403. // 广告观看完成,发放钻石奖励
  404. console.log('[ShopController] 广告观看完成,发放钻石奖励');
  405. this.claimDiamondReward(true);
  406. },
  407. (error) => {
  408. console.error('[ShopController] 钻石奖励广告显示失败:', error);
  409. // 广告失败时不给予奖励
  410. }
  411. );
  412. }
  413. // showRewardEffect方法已被MoneyAni.playReward替代,不再需要
  414. // Cost按钮相关方法已移除,功能已整合到主按钮中
  415. // 从配置JSON更新钞票数值显示
  416. private updateMoneyAmountFromConfig() {
  417. if (this.moneyAmountLabel && this.shopConfig) {
  418. // 从配置中读取下一次的钞票数值
  419. const nextMoneyAmount = this.shopConfig.dailyRewards.money.rewards[0] || 100;
  420. this.moneyAmountLabel.string = this.formatNumberWithSpaces(nextMoneyAmount);
  421. console.log('[ShopController] 从配置更新钞票数值:', nextMoneyAmount);
  422. }
  423. }
  424. // 从配置JSON更新钻石数值显示
  425. private updateDiamondAmountFromConfig() {
  426. if (this.diamondAmountLabel && this.shopConfig) {
  427. // 从配置中读取下一次的钻石数值
  428. const nextDiamondAmount = this.shopConfig.dailyRewards.diamond.rewards[0] || 10;
  429. this.diamondAmountLabel.string = this.formatNumberWithSpaces(nextDiamondAmount);
  430. console.log('[ShopController] 从配置更新钻石数值:', nextDiamondAmount);
  431. }
  432. }
  433. /**
  434. * 播放钞票奖励动画
  435. */
  436. private playMoneyRewardAnimation(amount: number, onComplete?: () => void) {
  437. // 查找场景中的MoneyAni组件
  438. const scene = director.getScene();
  439. if (!scene) {
  440. console.error('[ShopController] 无法获取当前场景');
  441. if (onComplete) onComplete();
  442. return;
  443. }
  444. const findMoneyAni = (node: Node): MoneyAni | null => {
  445. const moneyAni = node.getComponent(MoneyAni);
  446. if (moneyAni) return moneyAni;
  447. for (const child of node.children) {
  448. const result = findMoneyAni(child);
  449. if (result) return result;
  450. }
  451. return null;
  452. };
  453. const moneyAni = findMoneyAni(scene);
  454. if (!moneyAni) {
  455. console.error('[ShopController] 场景中未找到MoneyAni组件');
  456. if (onComplete) onComplete();
  457. return;
  458. }
  459. // 临时设置钞票起始位置
  460. if (this.billSpriteNode) {
  461. moneyAni.coinStartNode = this.billSpriteNode;
  462. }
  463. // 播放钞票动画
  464. moneyAni.playRewardAnimation(amount, 0, onComplete);
  465. }
  466. /**
  467. * 播放钻石奖励动画
  468. */
  469. private playDiamondRewardAnimation(amount: number, onComplete?: () => void) {
  470. // 查找场景中的MoneyAni组件
  471. const scene = director.getScene();
  472. if (!scene) {
  473. console.error('[ShopController] 无法获取当前场景');
  474. if (onComplete) onComplete();
  475. return;
  476. }
  477. const findMoneyAni = (node: Node): MoneyAni | null => {
  478. const moneyAni = node.getComponent(MoneyAni);
  479. if (moneyAni) return moneyAni;
  480. for (const child of node.children) {
  481. const result = findMoneyAni(child);
  482. if (result) return result;
  483. }
  484. return null;
  485. };
  486. const moneyAni = findMoneyAni(scene);
  487. if (!moneyAni) {
  488. console.error('[ShopController] 场景中未找到MoneyAni组件');
  489. if (onComplete) onComplete();
  490. return;
  491. }
  492. // 临时设置钻石起始位置
  493. if (this.diamondSpriteNode) {
  494. moneyAni.diamondStartNode = this.diamondSpriteNode;
  495. }
  496. // 播放钻石动画
  497. moneyAni.playRewardAnimation(0, amount, onComplete);
  498. }
  499. onDestroy() {
  500. // 移除事件监听
  501. EventBus.getInstance().off(GameEvents.CURRENCY_CHANGED, this.updateUI, this);
  502. }
  503. // 调试方法:重置每日奖励数据
  504. public resetDailyRewards() {
  505. const today = this.getCurrentDateString();
  506. this.resetDailyRewardData(today);
  507. this.updateUI();
  508. console.log('[ShopController] 每日奖励数据已重置');
  509. }
  510. // 获取当前每日奖励状态(用于调试)
  511. public getDailyRewardStatus() {
  512. return {
  513. config: this.shopConfig,
  514. data: this.dailyRewardData,
  515. today: this.getCurrentDateString()
  516. };
  517. }
  518. }