SaveDataManager.ts 23 KB

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