ShopController.ts 20 KB

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