SaveDataManager.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. import { _decorator, sys, resources, JsonAsset } from 'cc';
  2. import { LevelConfigManager } from './LevelConfigManager';
  3. const { ccclass, property } = _decorator;
  4. /**
  5. * 玩家数据结构
  6. */
  7. export interface PlayerData {
  8. // 基本信息
  9. playerId: string;
  10. playerName: string;
  11. createTime: number;
  12. lastPlayTime: number;
  13. totalPlayTime: number;
  14. // 货币系统
  15. coins: number; // 金币
  16. diamonds: number; // 钻石
  17. gems: number; // 宝石
  18. // 墙体等级系统
  19. wallLevel: number; // 墙体等级
  20. wallBaseHealth: number; // 墙体基础血量
  21. // 关卡进度
  22. currentLevel: number;
  23. maxUnlockedLevel: number;
  24. levelProgress: { [levelId: number]: LevelProgress };
  25. // 道具和装备
  26. inventory: InventoryData;
  27. // 统计数据
  28. statistics: GameStatistics;
  29. // 设置
  30. settings: PlayerSettings;
  31. }
  32. /**
  33. * 关卡进度数据
  34. */
  35. export interface LevelProgress {
  36. levelId: number;
  37. completed: boolean;
  38. bestScore: number;
  39. bestTime: number;
  40. attempts: number;
  41. firstClearTime: number;
  42. lastPlayTime: number;
  43. rewards: RewardData[];
  44. }
  45. /**
  46. * 背包数据
  47. */
  48. export interface InventoryData {
  49. weapons: { [weaponId: string]: WeaponData };
  50. items: { [itemId: string]: ItemData };
  51. materials: { [materialId: string]: number };
  52. capacity: number;
  53. usedSlots: number;
  54. }
  55. /**
  56. * 武器数据
  57. */
  58. export interface WeaponData {
  59. weaponId: string;
  60. level: number;
  61. rarity: string;
  62. obtainTime: number;
  63. upgradeCount: number;
  64. isEquipped: boolean;
  65. }
  66. /**
  67. * 道具数据
  68. */
  69. export interface ItemData {
  70. itemId: string;
  71. count: number;
  72. obtainTime: number;
  73. lastUsedTime: number;
  74. }
  75. /**
  76. * 奖励数据
  77. */
  78. export interface RewardData {
  79. type: 'coins' | 'diamonds' | 'gems' | 'weapon' | 'item';
  80. id?: string;
  81. amount: number;
  82. obtainTime: number;
  83. source: string; // 获得来源:level_complete, daily_reward, shop_purchase等
  84. }
  85. /**
  86. * 游戏统计数据
  87. */
  88. export interface GameStatistics {
  89. totalGamesPlayed: number;
  90. totalWins: number;
  91. totalLosses: number;
  92. totalScore: number;
  93. totalEnemiesDefeated: number;
  94. totalShotsfired: number;
  95. totalDamageDealt: number;
  96. totalTimePlayed: number;
  97. highestLevel: number;
  98. consecutiveWins: number;
  99. bestWinStreak: number;
  100. favoriteWeapon: string;
  101. weaponsUnlocked: number;
  102. itemsCollected: number;
  103. }
  104. /**
  105. * 玩家设置
  106. */
  107. export interface PlayerSettings {
  108. soundEnabled: boolean;
  109. musicEnabled: boolean;
  110. soundVolume: number;
  111. musicVolume: number;
  112. vibrationEnabled: boolean;
  113. autoSaveEnabled: boolean;
  114. language: string;
  115. graphics: 'low' | 'medium' | 'high';
  116. }
  117. /**
  118. * 存档管理器
  119. * 负责玩家数据的保存、加载和管理
  120. */
  121. @ccclass('SaveDataManager')
  122. export class SaveDataManager {
  123. private static instance: SaveDataManager = null;
  124. private playerData: PlayerData = null;
  125. private initialized: boolean = false;
  126. private autoSaveInterval: number = 30; // 自动保存间隔(秒)
  127. private lastSaveTime: number = 0;
  128. // 最近的奖励记录(用于UI显示)
  129. private lastRewards: {coins: number, diamonds: number} = {coins: 0, diamonds: 0};
  130. // 存档文件键名
  131. private readonly SAVE_KEY = 'pong_game_save_data';
  132. private readonly BACKUP_KEY = 'pong_game_save_data_backup';
  133. private readonly SETTINGS_KEY = 'pong_game_settings';
  134. private constructor() {
  135. // 私有构造函数,确保单例模式
  136. }
  137. public static getInstance(): SaveDataManager {
  138. if (SaveDataManager.instance === null) {
  139. SaveDataManager.instance = new SaveDataManager();
  140. }
  141. return SaveDataManager.instance;
  142. }
  143. /**
  144. * 初始化存档管理器
  145. */
  146. public initialize(): void {
  147. if (this.initialized) return;
  148. this.loadPlayerData();
  149. this.initialized = true;
  150. }
  151. /**
  152. * 加载玩家数据
  153. */
  154. private loadPlayerData(): void {
  155. try {
  156. const savedData = sys.localStorage.getItem(this.SAVE_KEY);
  157. if (savedData) {
  158. const data = JSON.parse(savedData);
  159. this.playerData = this.validateAndMigrateData(data);
  160. this.playerData.lastPlayTime = Date.now();
  161. } else {
  162. this.createNewPlayerData();
  163. }
  164. } catch (error) {
  165. console.error('❌ 存档数据加载失败,尝试加载备份:', error);
  166. this.loadBackupData();
  167. }
  168. }
  169. /**
  170. * 加载备份数据
  171. */
  172. private loadBackupData(): void {
  173. try {
  174. const backupData = sys.localStorage.getItem(this.BACKUP_KEY);
  175. if (backupData) {
  176. const data = JSON.parse(backupData);
  177. this.playerData = this.validateAndMigrateData(data);
  178. this.playerData.lastPlayTime = Date.now();
  179. } else {
  180. this.createNewPlayerData();
  181. }
  182. } catch (error) {
  183. console.error('❌ 备份数据加载失败,创建新存档:', error);
  184. this.createNewPlayerData();
  185. }
  186. }
  187. /**
  188. * 创建新的玩家数据
  189. */
  190. private createNewPlayerData(): void {
  191. this.playerData = {
  192. playerId: this.generatePlayerId(),
  193. playerName: 'Player',
  194. createTime: Date.now(),
  195. lastPlayTime: Date.now(),
  196. totalPlayTime: 0,
  197. coins: 45, // 初始金币
  198. diamonds: 0, // 初始钻石
  199. gems: 0,
  200. wallLevel: 1, // 初始墙体等级
  201. wallBaseHealth: 100, // 初始墙体基础血量
  202. currentLevel: 1,
  203. maxUnlockedLevel: 1,
  204. levelProgress: {},
  205. inventory: {
  206. weapons: {},
  207. items: {},
  208. materials: {},
  209. capacity: 50,
  210. usedSlots: 0
  211. },
  212. statistics: {
  213. totalGamesPlayed: 0,
  214. totalWins: 0,
  215. totalLosses: 0,
  216. totalScore: 0,
  217. totalEnemiesDefeated: 0,
  218. totalShotsfired: 0,
  219. totalDamageDealt: 0,
  220. totalTimePlayed: 0,
  221. highestLevel: 1,
  222. consecutiveWins: 0,
  223. bestWinStreak: 0,
  224. favoriteWeapon: '',
  225. weaponsUnlocked: 0,
  226. itemsCollected: 0
  227. },
  228. settings: {
  229. soundEnabled: true,
  230. musicEnabled: true,
  231. soundVolume: 0.8,
  232. musicVolume: 0.6,
  233. vibrationEnabled: true,
  234. autoSaveEnabled: true,
  235. language: 'zh-CN',
  236. graphics: 'medium'
  237. }
  238. };
  239. this.savePlayerData();
  240. }
  241. /**
  242. * 验证和迁移数据(用于版本兼容)
  243. */
  244. private validateAndMigrateData(data: any): PlayerData {
  245. // 确保所有必要字段存在
  246. const defaultData = this.createDefaultPlayerData();
  247. return {
  248. ...defaultData,
  249. ...data,
  250. // 确保嵌套对象也被正确合并
  251. inventory: { ...defaultData.inventory, ...data.inventory },
  252. statistics: { ...defaultData.statistics, ...data.statistics },
  253. settings: { ...defaultData.settings, ...data.settings }
  254. };
  255. }
  256. /**
  257. * 创建默认玩家数据模板
  258. */
  259. private createDefaultPlayerData(): PlayerData {
  260. return {
  261. playerId: this.generatePlayerId(),
  262. playerName: 'Player',
  263. createTime: Date.now(),
  264. lastPlayTime: Date.now(),
  265. totalPlayTime: 0,
  266. coins: 45,
  267. diamonds: 50,
  268. gems: 0,
  269. wallLevel: 1, // 初始墙体等级
  270. wallBaseHealth: 100, // 初始墙体基础血量
  271. currentLevel: 1,
  272. maxUnlockedLevel: 1,
  273. levelProgress: {},
  274. inventory: {
  275. weapons: {},
  276. items: {},
  277. materials: {},
  278. capacity: 50,
  279. usedSlots: 0
  280. },
  281. statistics: {
  282. totalGamesPlayed: 0,
  283. totalWins: 0,
  284. totalLosses: 0,
  285. totalScore: 0,
  286. totalEnemiesDefeated: 0,
  287. totalShotsfired: 0,
  288. totalDamageDealt: 0,
  289. totalTimePlayed: 0,
  290. highestLevel: 1,
  291. consecutiveWins: 0,
  292. bestWinStreak: 0,
  293. favoriteWeapon: '',
  294. weaponsUnlocked: 0,
  295. itemsCollected: 0
  296. },
  297. settings: {
  298. soundEnabled: true,
  299. musicEnabled: true,
  300. soundVolume: 0.8,
  301. musicVolume: 0.6,
  302. vibrationEnabled: true,
  303. autoSaveEnabled: true,
  304. language: 'zh-CN',
  305. graphics: 'medium'
  306. }
  307. };
  308. }
  309. /**
  310. * 保存玩家数据
  311. */
  312. public savePlayerData(force: boolean = false): void {
  313. if (!this.playerData) return;
  314. const currentTime = Date.now();
  315. // 检查是否需要保存(避免频繁保存)
  316. if (!force && currentTime - this.lastSaveTime < 5000) {
  317. return;
  318. }
  319. try {
  320. // 更新最后保存时间
  321. this.playerData.lastPlayTime = currentTime;
  322. // 创建备份
  323. const currentData = sys.localStorage.getItem(this.SAVE_KEY);
  324. if (currentData) {
  325. sys.localStorage.setItem(this.BACKUP_KEY, currentData);
  326. }
  327. // 保存当前数据
  328. const dataToSave = JSON.stringify(this.playerData);
  329. sys.localStorage.setItem(this.SAVE_KEY, dataToSave);
  330. this.lastSaveTime = currentTime;
  331. } catch (error) {
  332. console.error('❌ 玩家数据保存失败:', error);
  333. }
  334. }
  335. /**
  336. * 自动保存检查
  337. */
  338. public checkAutoSave(): void {
  339. if (!this.playerData || !this.playerData.settings.autoSaveEnabled) return;
  340. const currentTime = Date.now();
  341. if (currentTime - this.lastSaveTime > this.autoSaveInterval * 1000) {
  342. this.savePlayerData();
  343. }
  344. }
  345. // === 玩家基本信息管理 ===
  346. public getPlayerData(): PlayerData {
  347. return this.playerData;
  348. }
  349. public getWallLevel(): number {
  350. return this.playerData?.wallLevel || 1;
  351. }
  352. public getCurrentLevel(): number {
  353. return this.playerData?.currentLevel || 1;
  354. }
  355. /**
  356. * 设置当前关卡
  357. */
  358. public setCurrentLevel(level: number): void {
  359. if (!this.playerData) return;
  360. // 确保关卡在有效范围内
  361. if (level >= 1 && level <= this.playerData.maxUnlockedLevel) {
  362. this.playerData.currentLevel = level;
  363. this.savePlayerData();
  364. console.log(`[SaveDataManager] 当前关卡设置为: ${level}`);
  365. } else {
  366. console.warn(`[SaveDataManager] 无效的关卡设置: ${level},当前最大解锁关卡: ${this.playerData.maxUnlockedLevel}`);
  367. }
  368. }
  369. public getMaxUnlockedLevel(): number {
  370. return this.playerData?.maxUnlockedLevel || 1;
  371. }
  372. public getCoins(): number {
  373. return this.playerData?.coins || 0;
  374. }
  375. public getDiamonds(): number {
  376. return this.playerData?.diamonds || 0;
  377. }
  378. public getGems(): number {
  379. return this.playerData?.gems || 0;
  380. }
  381. // === 关卡进度管理 ===
  382. /**
  383. * 完成关卡
  384. */
  385. public completeLevel(levelId: number, score: number, time: number): void {
  386. if (!this.playerData) return;
  387. // 更新关卡进度
  388. if (!this.playerData.levelProgress[levelId]) {
  389. this.playerData.levelProgress[levelId] = {
  390. levelId: levelId,
  391. completed: false,
  392. bestScore: 0,
  393. bestTime: 0,
  394. attempts: 0,
  395. firstClearTime: 0,
  396. lastPlayTime: 0,
  397. rewards: []
  398. };
  399. }
  400. const progress = this.playerData.levelProgress[levelId];
  401. progress.attempts += 1;
  402. progress.lastPlayTime = Date.now();
  403. // 首次完成
  404. if (!progress.completed) {
  405. progress.completed = true;
  406. progress.firstClearTime = Date.now();
  407. // 解锁下一关
  408. if (levelId === this.playerData.maxUnlockedLevel) {
  409. this.playerData.maxUnlockedLevel = levelId + 1;
  410. }
  411. }
  412. // 更新最佳记录
  413. if (score > progress.bestScore) {
  414. progress.bestScore = score;
  415. }
  416. if (time > 0 && (progress.bestTime === 0 || time < progress.bestTime)) {
  417. progress.bestTime = time;
  418. }
  419. // 更新统计数据
  420. this.playerData.statistics.totalGamesPlayed += 1;
  421. this.playerData.statistics.totalWins += 1;
  422. this.playerData.statistics.totalScore += score;
  423. this.playerData.statistics.consecutiveWins += 1;
  424. if (this.playerData.statistics.consecutiveWins > this.playerData.statistics.bestWinStreak) {
  425. this.playerData.statistics.bestWinStreak = this.playerData.statistics.consecutiveWins;
  426. }
  427. if (levelId > this.playerData.statistics.highestLevel) {
  428. this.playerData.statistics.highestLevel = levelId;
  429. }
  430. // 计算并给予奖励
  431. this.giveCompletionRewards(levelId);
  432. this.savePlayerData();
  433. }
  434. /**
  435. * 关卡失败
  436. */
  437. public failLevel(levelId: number): void {
  438. if (!this.playerData) return;
  439. // 更新关卡进度
  440. if (!this.playerData.levelProgress[levelId]) {
  441. this.playerData.levelProgress[levelId] = {
  442. levelId: levelId,
  443. completed: false,
  444. bestScore: 0,
  445. bestTime: 0,
  446. attempts: 0,
  447. firstClearTime: 0,
  448. lastPlayTime: 0,
  449. rewards: []
  450. };
  451. }
  452. const progress = this.playerData.levelProgress[levelId];
  453. progress.attempts += 1;
  454. progress.lastPlayTime = Date.now();
  455. // 更新统计数据
  456. this.playerData.statistics.totalGamesPlayed += 1;
  457. this.playerData.statistics.totalLosses += 1;
  458. this.playerData.statistics.consecutiveWins = 0;
  459. this.savePlayerData();
  460. }
  461. /**
  462. * 获取关卡进度
  463. */
  464. public getLevelProgress(levelId: number): LevelProgress | null {
  465. return this.playerData?.levelProgress[levelId] || null;
  466. }
  467. /**
  468. * 检查关卡是否已解锁
  469. */
  470. public isLevelUnlocked(levelId: number): boolean {
  471. return levelId <= (this.playerData?.maxUnlockedLevel || 1);
  472. }
  473. /**
  474. * 检查关卡是否已完成
  475. */
  476. public isLevelCompleted(levelId: number): boolean {
  477. const progress = this.getLevelProgress(levelId);
  478. return progress?.completed || false;
  479. }
  480. // === 货币管理 ===
  481. /**
  482. * 添加金币
  483. */
  484. public addCoins(amount: number, source: string = 'unknown'): boolean {
  485. if (!this.playerData || amount <= 0) return false;
  486. this.playerData.coins += amount;
  487. this.addReward('coins', '', amount, source);
  488. return true;
  489. }
  490. /**
  491. * 消费金币
  492. */
  493. public spendCoins(amount: number): boolean {
  494. if (!this.playerData || amount <= 0 || this.playerData.coins < amount) {
  495. return false;
  496. }
  497. this.playerData.coins -= amount;
  498. return true;
  499. }
  500. /**
  501. * 添加钻石
  502. */
  503. public addDiamonds(amount: number, source: string = 'unknown'): boolean {
  504. if (!this.playerData || amount <= 0) return false;
  505. this.playerData.diamonds += amount;
  506. this.addReward('diamonds', '', amount, source);
  507. return true;
  508. }
  509. /**
  510. * 消费钻石
  511. */
  512. public spendDiamonds(amount: number): boolean {
  513. if (!this.playerData || amount <= 0 || this.playerData.diamonds < amount) {
  514. return false;
  515. }
  516. this.playerData.diamonds -= amount;
  517. return true;
  518. }
  519. /**
  520. * 添加宝石
  521. */
  522. public addGems(amount: number, source: string = 'unknown'): boolean {
  523. if (!this.playerData || amount <= 0) return false;
  524. this.playerData.gems += amount;
  525. this.addReward('gems', '', amount, source);
  526. return true;
  527. }
  528. // === 墙体等级管理 ===
  529. /**
  530. * 升级墙体等级
  531. */
  532. public upgradeWallLevel(): boolean {
  533. if (!this.playerData) return false;
  534. if (this.playerData.wallLevel >= 5) return false; // 最高5级
  535. this.playerData.wallLevel += 1;
  536. // 根据等级设置墙体血量
  537. const wallHpMap: Record<number, number> = {
  538. 1: 100,
  539. 2: 1000,
  540. 3: 1200,
  541. 4: 1500,
  542. 5: 2000
  543. };
  544. this.playerData.wallBaseHealth = wallHpMap[this.playerData.wallLevel] || (100 + (this.playerData.wallLevel - 1) * 200);
  545. this.savePlayerData(true);
  546. return true;
  547. }
  548. /**
  549. * 获取墙体升级费用
  550. */
  551. public getWallUpgradeCost(): number {
  552. if (!this.playerData) return 0;
  553. const costMap: Record<number, number> = {
  554. 1: 500, // 1级升2级
  555. 2: 1000, // 2级升3级
  556. 3: 2000, // 3级升4级
  557. 4: 4000 // 4级升5级
  558. };
  559. return costMap[this.playerData.wallLevel] || 0;
  560. }
  561. /**
  562. * 检查是否可以升级墙体
  563. */
  564. public canUpgradeWall(): boolean {
  565. if (!this.playerData) return false;
  566. if (this.playerData.wallLevel >= 5) return false;
  567. const cost = this.getWallUpgradeCost();
  568. return this.playerData.coins >= cost;
  569. }
  570. // === 道具和武器管理 ===
  571. /**
  572. * 添加武器
  573. */
  574. public addWeapon(weaponId: string, rarity: string = 'common'): boolean {
  575. if (!this.playerData) return false;
  576. if (!this.playerData.inventory.weapons[weaponId]) {
  577. this.playerData.inventory.weapons[weaponId] = {
  578. weaponId: weaponId,
  579. level: 1,
  580. rarity: rarity,
  581. obtainTime: Date.now(),
  582. upgradeCount: 0,
  583. isEquipped: false
  584. };
  585. this.playerData.statistics.weaponsUnlocked += 1;
  586. this.addReward('weapon', weaponId, 1, 'drop');
  587. return true;
  588. }
  589. return false;
  590. }
  591. /**
  592. * 添加道具
  593. */
  594. public addItem(itemId: string, count: number = 1): boolean {
  595. if (!this.playerData || count <= 0) return false;
  596. if (!this.playerData.inventory.items[itemId]) {
  597. this.playerData.inventory.items[itemId] = {
  598. itemId: itemId,
  599. count: 0,
  600. obtainTime: Date.now(),
  601. lastUsedTime: 0
  602. };
  603. }
  604. this.playerData.inventory.items[itemId].count += count;
  605. this.playerData.statistics.itemsCollected += count;
  606. this.addReward('item', itemId, count, 'drop');
  607. return true;
  608. }
  609. /**
  610. * 使用道具
  611. */
  612. public useItem(itemId: string, count: number = 1): boolean {
  613. if (!this.playerData || count <= 0) return false;
  614. const item = this.playerData.inventory.items[itemId];
  615. if (!item || item.count < count) {
  616. return false;
  617. }
  618. item.count -= count;
  619. item.lastUsedTime = Date.now();
  620. if (item.count === 0) {
  621. delete this.playerData.inventory.items[itemId];
  622. }
  623. return true;
  624. }
  625. // === 奖励管理 ===
  626. /**
  627. * 添加奖励记录
  628. */
  629. private addReward(type: RewardData['type'], id: string, amount: number, source: string): void {
  630. if (!this.playerData) return;
  631. const reward: RewardData = {
  632. type: type,
  633. id: id,
  634. amount: amount,
  635. obtainTime: Date.now(),
  636. source: source
  637. };
  638. // 这里可以添加到全局奖励历史记录中
  639. // 暂时不实现,避免数据过大
  640. }
  641. /**
  642. * 从JSON配置文件获取关卡奖励数据
  643. */
  644. public async getLevelRewardsFromConfig(levelId: number): Promise<{coins: number, diamonds: number} | null> {
  645. try {
  646. // 由于不支持动态导入,改为直接导入
  647. const configManager = LevelConfigManager.getInstance();
  648. if (!configManager) {
  649. console.warn(`LevelConfigManager未初始化,使用默认奖励`);
  650. return null;
  651. }
  652. const levelConfig = await configManager.getLevelConfig(levelId);
  653. if (levelConfig && levelConfig.levelSettings && (levelConfig.levelSettings as any).rewards) {
  654. const rewards = (levelConfig.levelSettings as any).rewards;
  655. return {
  656. coins: rewards.coins || 0,
  657. diamonds: rewards.diamonds || 0
  658. };
  659. }
  660. // 如果JSON中没有奖励配置,尝试直接从JSON文件读取
  661. const jsonPath = `data/levels/Level${levelId}`;
  662. return new Promise((resolve) => {
  663. resources.load(jsonPath, JsonAsset, (err, asset) => {
  664. if (err || !asset) {
  665. console.warn(`无法加载关卡${levelId}的JSON配置:`, err);
  666. resolve(null);
  667. return;
  668. }
  669. const jsonData = asset.json;
  670. if (jsonData && jsonData.rewards) {
  671. resolve({
  672. coins: jsonData.rewards.coins || 0,
  673. diamonds: jsonData.rewards.diamonds || 0
  674. });
  675. } else {
  676. resolve(null);
  677. }
  678. });
  679. });
  680. } catch (error) {
  681. console.error(`获取关卡${levelId}奖励配置失败:`, error);
  682. return null;
  683. }
  684. }
  685. /**
  686. * 给予关卡完成奖励(从JSON配置获取)
  687. */
  688. public async giveCompletionRewards(levelId: number): Promise<void> {
  689. // 尝试从JSON配置文件获取奖励数据
  690. const configRewards = await this.getLevelRewardsFromConfig(levelId);
  691. let actualCoins = 0;
  692. let actualDiamonds = 0;
  693. if (configRewards) {
  694. // 使用JSON配置中的奖励数据
  695. if (configRewards.coins > 0) {
  696. this.addCoins(configRewards.coins, `level_${levelId}_complete`);
  697. actualCoins = configRewards.coins;
  698. }
  699. if (configRewards.diamonds > 0) {
  700. this.addDiamonds(configRewards.diamonds, `level_${levelId}_complete`);
  701. actualDiamonds = configRewards.diamonds;
  702. }
  703. }
  704. // 特殊关卡额外奖励(里程碑奖励)
  705. if (levelId % 10 === 0) {
  706. this.addGems(1, `level_${levelId}_milestone`);
  707. }
  708. // 存储最近的奖励记录
  709. this.lastRewards = {coins: actualCoins, diamonds: actualDiamonds};
  710. }
  711. /**
  712. * 根据波数比例给予失败奖励
  713. */
  714. public async giveFailureRewards(levelId: number, completedWaves: number, totalWaves: number): Promise<void> {
  715. if (completedWaves <= 0 || totalWaves <= 0) {
  716. // 重置最近奖励为0
  717. this.lastRewards = {coins: 0, diamonds: 0};
  718. return;
  719. }
  720. // 获取完整奖励数据
  721. const configRewards = await this.getLevelRewardsFromConfig(levelId);
  722. // 计算波数完成比例
  723. const waveRatio = Math.min(completedWaves / totalWaves, 1.0);
  724. let actualCoins = 0;
  725. let actualDiamonds = 0;
  726. if (configRewards) {
  727. // 基于JSON配置计算比例奖励(取整)
  728. const partialCoins = Math.floor(configRewards.coins * waveRatio);
  729. const partialDiamonds = Math.floor(configRewards.diamonds * waveRatio);
  730. if (partialCoins > 0) {
  731. this.addCoins(partialCoins, `level_${levelId}_partial_${completedWaves}/${totalWaves}`);
  732. actualCoins = partialCoins;
  733. }
  734. if (partialDiamonds > 0) {
  735. this.addDiamonds(partialDiamonds, `level_${levelId}_partial_${completedWaves}/${totalWaves}`);
  736. actualDiamonds = partialDiamonds;
  737. }
  738. } else {
  739. // 回退到默认计算
  740. const baseCoins = levelId * 50;
  741. const partialCoins = Math.floor(baseCoins * waveRatio);
  742. if (partialCoins > 0) {
  743. this.addCoins(partialCoins, `level_${levelId}_partial_${completedWaves}/${totalWaves}`);
  744. actualCoins = partialCoins;
  745. }
  746. }
  747. // 存储最近的奖励记录
  748. this.lastRewards = {coins: actualCoins, diamonds: actualDiamonds};
  749. }
  750. /**
  751. * 获取最近的奖励记录(用于UI显示)
  752. */
  753. public getLastRewards(): {coins: number, diamonds: number} {
  754. return {...this.lastRewards};
  755. }
  756. // === 统计数据更新 ===
  757. public updateStatistic(key: keyof GameStatistics, value: number): void {
  758. if (!this.playerData) return;
  759. if (typeof this.playerData.statistics[key] === 'number') {
  760. (this.playerData.statistics[key] as number) += value;
  761. }
  762. }
  763. // === 设置管理 ===
  764. public updateSetting<K extends keyof PlayerSettings>(key: K, value: PlayerSettings[K]): void {
  765. if (!this.playerData) return;
  766. this.playerData.settings[key] = value;
  767. this.savePlayerData();
  768. }
  769. public getSetting<K extends keyof PlayerSettings>(key: K): PlayerSettings[K] {
  770. return this.playerData?.settings[key];
  771. }
  772. // === 工具方法 ===
  773. /**
  774. * 生成唯一玩家ID
  775. */
  776. private generatePlayerId(): string {
  777. return `player_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  778. }
  779. /**
  780. * 重置所有数据
  781. */
  782. public resetAllData(): void {
  783. sys.localStorage.removeItem(this.SAVE_KEY);
  784. sys.localStorage.removeItem(this.BACKUP_KEY);
  785. this.createNewPlayerData();
  786. }
  787. /**
  788. * 导出存档数据(用于调试)
  789. */
  790. public exportSaveData(): string {
  791. return JSON.stringify(this.playerData, null, 2);
  792. }
  793. /**
  794. * 导入存档数据(用于调试)
  795. */
  796. public importSaveData(dataString: string): boolean {
  797. try {
  798. const data = JSON.parse(dataString);
  799. this.playerData = this.validateAndMigrateData(data);
  800. this.savePlayerData(true);
  801. return true;
  802. } catch (error) {
  803. console.error('❌ 存档数据导入失败:', error);
  804. return false;
  805. }
  806. }
  807. /**
  808. * 获取存档摘要信息
  809. */
  810. public getSaveSummary(): string {
  811. if (!this.playerData) return '无存档数据';
  812. return `墙体等级: ${this.playerData.wallLevel} | ` +
  813. `当前关卡: ${this.playerData.currentLevel} | ` +
  814. `最高关卡: ${this.playerData.maxUnlockedLevel} | ` +
  815. `金币: ${this.playerData.coins} | ` +
  816. `钻石: ${this.playerData.diamonds} | ` +
  817. `游戏次数: ${this.playerData.statistics.totalGamesPlayed}`;
  818. }
  819. }