SaveDataManager.ts 27 KB

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