SaveDataManager.ts 25 KB

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