SaveDataManager.ts 37 KB

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