ShopController.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. const remainingCount = maxCount - totalCount;
  224. this.moneyCountLabel.string = `${remainingCount}/${maxCount}`;
  225. // 观看广告时显示图标
  226. if (this.moneyIconNode) {
  227. this.moneyIconNode.active = true;
  228. }
  229. }
  230. }
  231. }
  232. }
  233. private updateDiamondRewardUI() {
  234. if (!this.shopConfig || !this.dailyRewardData) return;
  235. const config = this.shopConfig.dailyRewards.diamond;
  236. const freeCount = this.dailyRewardData.diamondsFreeCount;
  237. const adCount = this.dailyRewardData.diamondsAdCount;
  238. const totalCount = freeCount + adCount;
  239. const maxCount = config.maxClaimsPerDay;
  240. const freeUsed = this.dailyRewardData.diamondFreeUsed;
  241. // 计算当前次数索引(免费机会未使用时为0,否则为总次数)
  242. const currentIndex = freeUsed ? totalCount : 0;
  243. const currentReward = config.rewards[currentIndex] || config.rewards[config.rewards.length - 1];
  244. // 更新金额显示
  245. if (this.diamondAmountLabel) {
  246. this.diamondAmountLabel.string = this.formatNumberWithSpaces(currentReward);
  247. }
  248. // 更新按钮状态和显示
  249. if (this.diamondButton) {
  250. const canClaim = totalCount < maxCount;
  251. this.diamondButton.interactable = canClaim;
  252. // 更新按钮文本
  253. const buttonLabel = this.diamondButton.node.getChildByName('Label')?.getComponent(Label);
  254. if (buttonLabel) {
  255. if (!canClaim) {
  256. buttonLabel.string = "今日已达上限";
  257. } else if (!freeUsed) {
  258. buttonLabel.string = "免 费";
  259. } else {
  260. buttonLabel.string = "观看广告";
  261. }
  262. }
  263. // 更新次数显示和图标
  264. if (this.diamondCountLabel) {
  265. if (!freeUsed) {
  266. this.diamondCountLabel.string = "免 费";
  267. // 免费时隐藏图标
  268. if (this.diamondIconNode) {
  269. this.diamondIconNode.active = false;
  270. }
  271. } else {
  272. const remainingCount = maxCount - totalCount;
  273. this.diamondCountLabel.string = `${remainingCount}/${maxCount}`;
  274. // 观看广告时显示图标
  275. if (this.diamondIconNode) {
  276. this.diamondIconNode.active = true;
  277. }
  278. }
  279. }
  280. }
  281. }
  282. // 钞票奖励按钮点击事件
  283. public onMoneyRewardClick() {
  284. if (!this.shopConfig || !this.dailyRewardData) return;
  285. const config = this.shopConfig.dailyRewards.money;
  286. const freeCount = this.dailyRewardData.moneyFreeCount;
  287. const adCount = this.dailyRewardData.moneyAdCount;
  288. const totalCount = freeCount + adCount;
  289. const maxCount = config.maxClaimsPerDay;
  290. const freeUsed = this.dailyRewardData.moneyFreeUsed;
  291. if (totalCount >= maxCount) {
  292. console.log('[ShopController] 钞票奖励已达每日上限');
  293. return;
  294. }
  295. // 如果免费机会未使用,直接发放奖励
  296. if (!freeUsed) {
  297. console.log('[ShopController] 使用免费机会获取钞票奖励');
  298. this.dailyRewardData.moneyFreeUsed = true;
  299. // 免费奖励不计入freeCount,只标记为已使用
  300. this.saveDailyRewardData();
  301. this.updateUI();
  302. // 播放奖励动画并添加货币
  303. const amount = config.rewards[0] || config.rewards[config.rewards.length - 1];
  304. this.saveDataManager.addMoney(amount, 'daily_free_reward');
  305. this.playMoneyRewardAnimation(amount, () => {
  306. console.log(`[ShopController] 钞票免费奖励动画播放完成: ${amount}`);
  307. });
  308. } else {
  309. // 看广告增加次数
  310. this.showAdForMoneyReward();
  311. }
  312. }
  313. // 钻石奖励按钮点击事件
  314. public onDiamondRewardClick() {
  315. if (!this.shopConfig || !this.dailyRewardData) return;
  316. const config = this.shopConfig.dailyRewards.diamond;
  317. const freeCount = this.dailyRewardData.diamondsFreeCount;
  318. const adCount = this.dailyRewardData.diamondsAdCount;
  319. const totalCount = freeCount + adCount;
  320. const maxCount = config.maxClaimsPerDay;
  321. const freeUsed = this.dailyRewardData.diamondFreeUsed;
  322. if (totalCount >= maxCount) {
  323. console.log('[ShopController] 钻石奖励已达每日上限');
  324. return;
  325. }
  326. // 如果免费机会未使用,直接发放奖励
  327. if (!freeUsed) {
  328. console.log('[ShopController] 使用免费机会获取钻石奖励');
  329. this.dailyRewardData.diamondFreeUsed = true;
  330. // 免费奖励不计入freeCount,只标记为已使用
  331. this.saveDailyRewardData();
  332. this.updateUI();
  333. // 播放奖励动画并添加货币
  334. const amount = config.rewards[0] || config.rewards[config.rewards.length - 1];
  335. this.saveDataManager.addDiamonds(amount, 'daily_free_reward');
  336. this.playDiamondRewardAnimation(amount, () => {
  337. console.log(`[ShopController] 钻石免费奖励动画播放完成: ${amount}`);
  338. });
  339. } else {
  340. // 看广告增加次数
  341. this.showAdForDiamondReward();
  342. }
  343. }
  344. private claimMoneyReward(isFromAd: boolean) {
  345. const config = this.shopConfig.dailyRewards.money;
  346. // 更新领取次数(先更新数据)
  347. if (isFromAd) {
  348. this.dailyRewardData.moneyAdCount++;
  349. } else {
  350. this.dailyRewardData.moneyFreeCount++;
  351. }
  352. // 计算当前次数索引和对应奖励
  353. const totalCount = this.dailyRewardData.moneyFreeCount + this.dailyRewardData.moneyAdCount;
  354. const currentIndex = totalCount - 1; // 减1因为已经增加了次数
  355. const amount = config.rewards[currentIndex] || config.rewards[config.rewards.length - 1];
  356. this.saveDailyRewardData();
  357. this.updateUI();
  358. console.log(`[ShopController] 开始播放钞票奖励动画: ${amount}, 来源: ${isFromAd ? '广告' : '免费'}`);
  359. // 添加货币到账户并播放奖励动画
  360. this.saveDataManager.addMoney(amount, isFromAd ? 'daily_ad_reward' : 'daily_free_reward');
  361. this.playMoneyRewardAnimation(amount, () => {
  362. console.log(`[ShopController] 钞票奖励动画播放完成: ${amount}`);
  363. });
  364. }
  365. private claimDiamondReward(isFromAd: boolean) {
  366. const config = this.shopConfig.dailyRewards.diamond;
  367. // 更新领取次数(先更新数据)
  368. if (isFromAd) {
  369. this.dailyRewardData.diamondsAdCount++;
  370. } else {
  371. this.dailyRewardData.diamondsFreeCount++;
  372. }
  373. // 计算当前次数索引和对应奖励
  374. const totalCount = this.dailyRewardData.diamondsFreeCount + this.dailyRewardData.diamondsAdCount;
  375. const currentIndex = totalCount - 1; // 减1因为已经增加了次数
  376. const amount = config.rewards[currentIndex] || config.rewards[config.rewards.length - 1];
  377. this.saveDailyRewardData();
  378. this.updateUI();
  379. console.log(`[ShopController] 开始播放钻石奖励动画: ${amount}, 来源: ${isFromAd ? '广告' : '免费'}`);
  380. // 播放奖励动画,动画完成后会自动添加钻石
  381. this.playDiamondRewardAnimation(amount, () => {
  382. console.log(`[ShopController] 钻石奖励动画播放完成: ${amount}`);
  383. });
  384. }
  385. private showAdForMoneyReward() {
  386. console.log('[ShopController] 显示钞票奖励广告');
  387. // 显示激励视频广告
  388. AdManager.getInstance().showRewardedVideoAd(
  389. () => {
  390. // 广告观看完成,发放钞票奖励
  391. console.log('[ShopController] 广告观看完成,发放钞票奖励');
  392. this.claimMoneyReward(true);
  393. },
  394. (error) => {
  395. console.error('[ShopController] 钞票奖励广告显示失败:', error);
  396. // 广告失败时不给予奖励
  397. }
  398. );
  399. }
  400. private showAdForDiamondReward() {
  401. console.log('[ShopController] 显示钻石奖励广告');
  402. // 显示激励视频广告
  403. AdManager.getInstance().showRewardedVideoAd(
  404. () => {
  405. // 广告观看完成,发放钻石奖励
  406. console.log('[ShopController] 广告观看完成,发放钻石奖励');
  407. this.claimDiamondReward(true);
  408. },
  409. (error) => {
  410. console.error('[ShopController] 钻石奖励广告显示失败:', error);
  411. // 广告失败时不给予奖励
  412. }
  413. );
  414. }
  415. // showRewardEffect方法已被MoneyAni.playReward替代,不再需要
  416. // Cost按钮相关方法已移除,功能已整合到主按钮中
  417. // 从配置JSON更新钞票数值显示
  418. private updateMoneyAmountFromConfig() {
  419. if (this.moneyAmountLabel && this.shopConfig) {
  420. // 从配置中读取下一次的钞票数值
  421. const nextMoneyAmount = this.shopConfig.dailyRewards.money.rewards[0] || 100;
  422. this.moneyAmountLabel.string = this.formatNumberWithSpaces(nextMoneyAmount);
  423. console.log('[ShopController] 从配置更新钞票数值:', nextMoneyAmount);
  424. }
  425. }
  426. // 从配置JSON更新钻石数值显示
  427. private updateDiamondAmountFromConfig() {
  428. if (this.diamondAmountLabel && this.shopConfig) {
  429. // 从配置中读取下一次的钻石数值
  430. const nextDiamondAmount = this.shopConfig.dailyRewards.diamond.rewards[0] || 10;
  431. this.diamondAmountLabel.string = this.formatNumberWithSpaces(nextDiamondAmount);
  432. console.log('[ShopController] 从配置更新钻石数值:', nextDiamondAmount);
  433. }
  434. }
  435. /**
  436. * 播放钞票奖励动画
  437. */
  438. private playMoneyRewardAnimation(amount: number, onComplete?: () => void) {
  439. // 查找场景中的MoneyAni组件
  440. const scene = director.getScene();
  441. if (!scene) {
  442. console.error('[ShopController] 无法获取当前场景');
  443. if (onComplete) onComplete();
  444. return;
  445. }
  446. const findMoneyAni = (node: Node): MoneyAni | null => {
  447. const moneyAni = node.getComponent(MoneyAni);
  448. if (moneyAni) return moneyAni;
  449. for (const child of node.children) {
  450. const result = findMoneyAni(child);
  451. if (result) return result;
  452. }
  453. return null;
  454. };
  455. const moneyAni = findMoneyAni(scene);
  456. if (!moneyAni) {
  457. console.error('[ShopController] 场景中未找到MoneyAni组件');
  458. if (onComplete) onComplete();
  459. return;
  460. }
  461. // 临时设置钞票起始位置
  462. if (this.billSpriteNode) {
  463. moneyAni.coinStartNode = this.billSpriteNode;
  464. }
  465. // 播放钞票动画
  466. moneyAni.playRewardAnimation(amount, 0, onComplete);
  467. }
  468. /**
  469. * 播放钻石奖励动画
  470. */
  471. private playDiamondRewardAnimation(amount: number, onComplete?: () => void) {
  472. // 查找场景中的MoneyAni组件
  473. const scene = director.getScene();
  474. if (!scene) {
  475. console.error('[ShopController] 无法获取当前场景');
  476. if (onComplete) onComplete();
  477. return;
  478. }
  479. const findMoneyAni = (node: Node): MoneyAni | null => {
  480. const moneyAni = node.getComponent(MoneyAni);
  481. if (moneyAni) return moneyAni;
  482. for (const child of node.children) {
  483. const result = findMoneyAni(child);
  484. if (result) return result;
  485. }
  486. return null;
  487. };
  488. const moneyAni = findMoneyAni(scene);
  489. if (!moneyAni) {
  490. console.error('[ShopController] 场景中未找到MoneyAni组件');
  491. if (onComplete) onComplete();
  492. return;
  493. }
  494. // 临时设置钻石起始位置
  495. if (this.diamondSpriteNode) {
  496. moneyAni.diamondStartNode = this.diamondSpriteNode;
  497. }
  498. // 播放钻石动画
  499. moneyAni.playRewardAnimation(0, amount, onComplete);
  500. }
  501. onDestroy() {
  502. // 移除事件监听
  503. EventBus.getInstance().off(GameEvents.CURRENCY_CHANGED, this.updateUI, this);
  504. }
  505. // 调试方法:重置每日奖励数据
  506. public resetDailyRewards() {
  507. const today = this.getCurrentDateString();
  508. this.resetDailyRewardData(today);
  509. this.updateUI();
  510. console.log('[ShopController] 每日奖励数据已重置');
  511. }
  512. // 获取当前每日奖励状态(用于调试)
  513. public getDailyRewardStatus() {
  514. return {
  515. config: this.shopConfig,
  516. data: this.dailyRewardData,
  517. today: this.getCurrentDateString()
  518. };
  519. }
  520. }