SaveDataManager.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. import { _decorator, sys, resources, JsonAsset } from 'cc';
  2. import { LevelConfigManager } from './LevelConfigManager';
  3. import EventBus, { GameEvents } from '../Core/EventBus';
  4. const { ccclass, property } = _decorator;
  5. /**
  6. * 武器配置数据接口
  7. */
  8. interface WeaponConfig {
  9. id: string;
  10. name: string;
  11. description: string;
  12. rarity: string;
  13. unlockLevel: number;
  14. baseDamage: number;
  15. baseSpeed: number;
  16. upgradeCosts: number[];
  17. maxLevel: number;
  18. }
  19. /**
  20. * 玩家数据结构
  21. */
  22. export interface PlayerData {
  23. // 基本信息
  24. playerId: string;
  25. playerName: string;
  26. createTime: number;
  27. lastPlayTime: number;
  28. totalPlayTime: number;
  29. // 货币系统
  30. money: number; // 局外钞票
  31. diamonds: number; // 钻石
  32. // 墙体等级系统
  33. wallLevel: number; // 墙体等级
  34. // 关卡进度
  35. currentLevel: number;
  36. maxUnlockedLevel: number;
  37. levelProgress: { [levelId: number]: LevelProgress };
  38. // 道具和装备
  39. inventory: InventoryData;
  40. // 统计数据
  41. statistics: GameStatistics;
  42. // 设置
  43. settings: PlayerSettings;
  44. }
  45. /**
  46. * 关卡进度数据
  47. */
  48. export interface LevelProgress {
  49. levelId: number;
  50. completed: boolean;
  51. bestScore: number;
  52. bestTime: number;
  53. attempts: number;
  54. firstClearTime: number;
  55. lastPlayTime: number;
  56. rewards: RewardData[];
  57. }
  58. /**
  59. * 背包数据
  60. */
  61. export interface InventoryData {
  62. weapons: { [weaponId: string]: WeaponData };
  63. items: { [itemId: string]: ItemData };
  64. materials: { [materialId: string]: number };
  65. capacity: number;
  66. usedSlots: number;
  67. }
  68. /**
  69. * 武器数据
  70. */
  71. export interface WeaponData {
  72. weaponId: string;
  73. level: number;
  74. rarity: string;
  75. obtainTime: number;
  76. upgradeCount: number;
  77. isEquipped: boolean;
  78. }
  79. /**
  80. * 道具数据
  81. */
  82. export interface ItemData {
  83. itemId: string;
  84. count: number;
  85. obtainTime: number;
  86. lastUsedTime: number;
  87. }
  88. /**
  89. * 奖励数据
  90. */
  91. export interface RewardData {
  92. type: 'money' | 'coins' | 'diamonds' | 'weapon' | 'item';
  93. id?: string;
  94. amount: number;
  95. obtainTime: number;
  96. source: string; // 获得来源:level_complete, daily_reward, shop_purchase等
  97. }
  98. /**
  99. * 游戏统计数据
  100. */
  101. export interface GameStatistics {
  102. totalGamesPlayed: number;
  103. totalWins: number;
  104. totalLosses: number;
  105. totalScore: number;
  106. totalEnemiesDefeated: number;
  107. totalShotsfired: number;
  108. totalDamageDealt: number;
  109. totalTimePlayed: number;
  110. highestLevel: number;
  111. consecutiveWins: number;
  112. bestWinStreak: number;
  113. favoriteWeapon: string;
  114. weaponsUnlocked: number;
  115. itemsCollected: number;
  116. }
  117. /**
  118. * 玩家设置
  119. */
  120. export interface PlayerSettings {
  121. soundEnabled: boolean;
  122. musicEnabled: boolean;
  123. soundVolume: number;
  124. musicVolume: number;
  125. vibrationEnabled: boolean;
  126. autoSaveEnabled: boolean;
  127. language: string;
  128. graphics: 'low' | 'medium' | 'high';
  129. }
  130. /**
  131. * 存档管理器
  132. * 负责玩家数据的保存、加载和管理
  133. */
  134. @ccclass('SaveDataManager')
  135. export class SaveDataManager {
  136. private static instance: SaveDataManager = null;
  137. private playerData: PlayerData = null;
  138. private initialized: boolean = false;
  139. private autoSaveInterval: number = 30; // 自动保存间隔(秒)
  140. private lastSaveTime: number = 0;
  141. // 私有属性
  142. private weaponsConfig: { weapons: any[] } = null;
  143. private wallConfig: any = null;
  144. /**
  145. * 设置墙体配置(从MainUIController传递)
  146. */
  147. public setWallConfig(config: any): void {
  148. this.wallConfig = config;
  149. console.log('[SaveDataManager] 接收到墙体配置:', this.wallConfig);
  150. }
  151. // 最近的奖励记录(用于UI显示)
  152. private lastRewards: {money: number, diamonds: number} = {money: 0, diamonds: 0};
  153. // 存档文件键名
  154. private readonly SAVE_KEY = 'pong_game_save_data';
  155. private readonly BACKUP_KEY = 'pong_game_save_data_backup';
  156. private readonly SETTINGS_KEY = 'pong_game_settings';
  157. private constructor() {
  158. // 私有构造函数,确保单例模式
  159. }
  160. public static getInstance(): SaveDataManager {
  161. if (SaveDataManager.instance === null) {
  162. SaveDataManager.instance = new SaveDataManager();
  163. }
  164. return SaveDataManager.instance;
  165. }
  166. /**
  167. * 初始化存档管理器
  168. */
  169. public async initialize(): Promise<void> {
  170. if (this.initialized) return;
  171. this.loadPlayerData();
  172. await this.loadWeaponsConfig();
  173. this.initialized = true;
  174. }
  175. /**
  176. * 加载武器配置
  177. */
  178. private async loadWeaponsConfig(): Promise<void> {
  179. try {
  180. const jsonAsset = await new Promise<any>((resolve, reject) => {
  181. resources.load('data/weapons', (err, asset) => {
  182. if (err) reject(err);
  183. else resolve(asset);
  184. });
  185. });
  186. this.weaponsConfig = jsonAsset.json;
  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: 20,
  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. const weaponUnlockMap: { [key: string]: number } = {
  717. 'pea_shooter': 1, // 毛豆射手 - 第1关
  718. 'sharp_carrot': 2, // 尖胡萝卜 - 第2关
  719. 'saw_grass': 3, // 锯齿草 - 第3关
  720. 'watermelon_bomb': 4, // 西瓜炸弹 - 第4关
  721. 'boomerang_plant': 5, // 回旋镖植物 - 第5关
  722. 'hot_pepper': 6, // 炙热辣椒 - 第6关
  723. 'cactus_shotgun': 7, // 仙人散弹 - 第7关
  724. 'okra_missile': 8, // 秋葵导弹 - 第8关
  725. 'mace_club': 9 // 狼牙棒 - 第9关
  726. };
  727. return weaponUnlockMap[weaponId] || 1;
  728. }
  729. /**
  730. * 添加道具
  731. */
  732. public addItem(itemId: string, count: number = 1): boolean {
  733. if (!this.playerData || count <= 0) return false;
  734. if (!this.playerData.inventory.items[itemId]) {
  735. this.playerData.inventory.items[itemId] = {
  736. itemId: itemId,
  737. count: 0,
  738. obtainTime: Date.now(),
  739. lastUsedTime: 0
  740. };
  741. }
  742. this.playerData.inventory.items[itemId].count += count;
  743. this.playerData.statistics.itemsCollected += count;
  744. this.addReward('item', itemId, count, 'drop');
  745. return true;
  746. }
  747. /**
  748. * 使用道具
  749. */
  750. public useItem(itemId: string, count: number = 1): boolean {
  751. if (!this.playerData || count <= 0) return false;
  752. const item = this.playerData.inventory.items[itemId];
  753. if (!item || item.count < count) {
  754. return false;
  755. }
  756. item.count -= count;
  757. item.lastUsedTime = Date.now();
  758. if (item.count === 0) {
  759. delete this.playerData.inventory.items[itemId];
  760. }
  761. return true;
  762. }
  763. // === 奖励管理 ===
  764. /**
  765. * 添加奖励记录
  766. */
  767. private addReward(type: RewardData['type'], id: string, amount: number, source: string): void {
  768. if (!this.playerData) return;
  769. const reward: RewardData = {
  770. type: type,
  771. id: id,
  772. amount: amount,
  773. obtainTime: Date.now(),
  774. source: source
  775. };
  776. // 这里可以添加到全局奖励历史记录中
  777. // 暂时不实现,避免数据过大
  778. }
  779. /**
  780. * 从JSON配置文件获取关卡奖励数据
  781. */
  782. public async getLevelRewardsFromConfig(levelId: number): Promise<{money: number, diamonds: number} | null> {
  783. try {
  784. console.log(`[SaveDataManager] 开始获取关卡${levelId}的奖励配置`);
  785. // 由于不支持动态导入,改为直接导入
  786. const configManager = LevelConfigManager.getInstance();
  787. if (!configManager) {
  788. console.warn(`LevelConfigManager未初始化,使用默认奖励`);
  789. return null;
  790. }
  791. const levelConfig = await configManager.getLevelConfig(levelId);
  792. if (levelConfig && levelConfig.levelSettings && (levelConfig.levelSettings as any).rewards) {
  793. const rewards = (levelConfig.levelSettings as any).rewards;
  794. console.log(`[SaveDataManager] 从LevelConfigManager获取到奖励:`, rewards);
  795. return {
  796. money: rewards.coins || 0,
  797. diamonds: rewards.diamonds || 0
  798. };
  799. }
  800. // 如果JSON中没有奖励配置,尝试直接从JSON文件读取
  801. const jsonPath = `data/levels/Level${levelId}`;
  802. console.log(`[SaveDataManager] 尝试从JSON文件加载: ${jsonPath}`);
  803. return new Promise((resolve) => {
  804. resources.load(jsonPath, JsonAsset, (err, asset) => {
  805. if (err || !asset) {
  806. console.warn(`无法加载关卡${levelId}的JSON配置:`, err);
  807. resolve(null);
  808. return;
  809. }
  810. const jsonData = asset.json;
  811. console.log(`[SaveDataManager] JSON数据:`, jsonData);
  812. // 修复字段名称映射:直接从JSON根级别读取coinReward和diamondReward
  813. if (jsonData && (jsonData.coinReward !== undefined || jsonData.diamondReward !== undefined)) {
  814. const rewardData = {
  815. money: jsonData.coinReward || 0,
  816. diamonds: jsonData.diamondReward || 0
  817. };
  818. resolve(rewardData);
  819. } else if (jsonData && jsonData.rewards) {
  820. // 兼容嵌套在rewards对象中的情况
  821. const rewardData = {
  822. money: jsonData.rewards.coins || jsonData.rewards.coinReward || 0,
  823. diamonds: jsonData.rewards.diamonds || jsonData.rewards.diamondReward || 0
  824. };
  825. console.log(`[SaveDataManager] 从JSON.rewards获取到奖励:`, rewardData);
  826. resolve(rewardData);
  827. } else {
  828. console.warn(`[SaveDataManager] JSON中未找到奖励配置`);
  829. resolve(null);
  830. }
  831. });
  832. });
  833. } catch (error) {
  834. console.error(`获取关卡${levelId}奖励配置失败:`, error);
  835. return null;
  836. }
  837. }
  838. /**
  839. * 给予关卡完成奖励(从JSON配置获取)
  840. */
  841. public async giveCompletionRewards(levelId: number): Promise<void> {
  842. console.log(`[SaveDataManager] 开始给予关卡${levelId}完成奖励`);
  843. // 尝试从JSON配置文件获取奖励数据
  844. const configRewards = await this.getLevelRewardsFromConfig(levelId);
  845. console.log(`[SaveDataManager] 获取到的配置奖励:`, configRewards);
  846. let actualCoins = 0;
  847. let actualDiamonds = 0;
  848. if (configRewards) {
  849. // 使用JSON配置中的奖励数据
  850. if (configRewards.money > 0) {
  851. this.addMoney(configRewards.money, `level_${levelId}_complete`);
  852. actualCoins = configRewards.money;
  853. console.log(`[SaveDataManager] 添加钞票: ${configRewards.money}`);
  854. }
  855. if (configRewards.diamonds > 0) {
  856. this.addDiamonds(configRewards.diamonds, `level_${levelId}_complete`);
  857. actualDiamonds = configRewards.diamonds;
  858. console.log(`[SaveDataManager] 添加钻石: ${configRewards.diamonds}`);
  859. }
  860. } else {
  861. console.warn(`[SaveDataManager] 未获取到配置奖励,使用默认值0`);
  862. }
  863. // 特殊关卡额外奖励(里程碑奖励)
  864. // if (levelId % 10 === 0) {
  865. // this.addGems(1, `level_${levelId}_milestone`);
  866. // }
  867. // 存储最近的奖励记录
  868. this.lastRewards = {money: actualCoins, diamonds: actualDiamonds};
  869. console.log(`[SaveDataManager] 最终奖励记录:`, this.lastRewards);
  870. }
  871. /**
  872. * 根据波数比例给予失败奖励
  873. */
  874. public async giveFailureRewards(levelId: number, completedWaves: number, totalWaves: number): Promise<void> {
  875. console.log(`[SaveDataManager] 计算失败奖励 - 关卡: ${levelId}, 完成波数: ${completedWaves}/${totalWaves}`);
  876. if (totalWaves <= 0) {
  877. console.warn('[SaveDataManager] 总波数无效,重置奖励为0');
  878. this.lastRewards = {money: 0, diamonds: 0};
  879. return;
  880. }
  881. // 如果完成波数为0,则不给予任何奖励
  882. if (completedWaves <= 0) {
  883. console.log('[SaveDataManager] 完成波数为0,不给予任何奖励');
  884. this.lastRewards = {money: 0, diamonds: 0};
  885. return;
  886. }
  887. const actualCompletedWaves = Math.max(completedWaves, 0);
  888. const waveRatio = actualCompletedWaves / totalWaves;
  889. console.log(`[SaveDataManager] 波数完成情况: ${actualCompletedWaves}/${totalWaves} = ${(waveRatio * 100).toFixed(1)}%`);
  890. // 获取完整奖励数据
  891. const configRewards = await this.getLevelRewardsFromConfig(levelId);
  892. let actualCoins = 0;
  893. let actualDiamonds = 0;
  894. if (configRewards) {
  895. // 基于JSON配置计算比例奖励(取整)
  896. const partialCoins = Math.floor(configRewards.money * waveRatio);
  897. const partialDiamonds = Math.floor(configRewards.diamonds * waveRatio);
  898. console.log(`[SaveDataManager] 基于配置计算奖励 - 原始钞票: ${configRewards.money}, 原始钻石: ${configRewards.diamonds}`);
  899. console.log(`[SaveDataManager] 计算出的失败奖励 - 钞票: ${partialCoins}, 钻石: ${partialDiamonds}`);
  900. if (partialCoins > 0) {
  901. this.addMoney(partialCoins, `level_${levelId}_partial_${actualCompletedWaves}/${totalWaves}`);
  902. actualCoins = partialCoins;
  903. }
  904. if (partialDiamonds > 0) {
  905. this.addDiamonds(partialDiamonds, `level_${levelId}_partial_${actualCompletedWaves}/${totalWaves}`);
  906. actualDiamonds = partialDiamonds;
  907. }
  908. } else {
  909. // 回退到默认计算
  910. const baseCoins = levelId * 50;
  911. const partialCoins = Math.floor(baseCoins * waveRatio);
  912. console.log(`[SaveDataManager] 使用默认计算 - 基础钞票: ${baseCoins}, 计算出的失败奖励: ${partialCoins}`);
  913. if (partialCoins > 0) {
  914. this.addMoney(partialCoins, `level_${levelId}_partial_${actualCompletedWaves}/${totalWaves}`);
  915. actualCoins = partialCoins;
  916. }
  917. }
  918. console.log(`[SaveDataManager] 最终失败奖励 - 钞票: ${actualCoins}, 钻石: ${actualDiamonds}`);
  919. // 存储最近的奖励记录
  920. this.lastRewards = {money: actualCoins, diamonds: actualDiamonds};
  921. }
  922. /**
  923. * 获取最近的奖励记录(用于UI显示)
  924. */
  925. public getLastRewards(): {money: number, diamonds: number} {
  926. return {...this.lastRewards};
  927. }
  928. // === 统计数据更新 ===
  929. public updateStatistic(key: keyof GameStatistics, value: number): void {
  930. if (!this.playerData) return;
  931. if (typeof this.playerData.statistics[key] === 'number') {
  932. (this.playerData.statistics[key] as number) += value;
  933. }
  934. }
  935. // === 设置管理 ===
  936. public updateSetting<K extends keyof PlayerSettings>(key: K, value: PlayerSettings[K]): void {
  937. if (!this.playerData) return;
  938. this.playerData.settings[key] = value;
  939. this.savePlayerData();
  940. }
  941. public getSetting<K extends keyof PlayerSettings>(key: K): PlayerSettings[K] {
  942. return this.playerData?.settings[key];
  943. }
  944. // === 工具方法 ===
  945. /**
  946. * 生成唯一玩家ID
  947. */
  948. private generatePlayerId(): string {
  949. return `player_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  950. }
  951. /**
  952. * 重置所有数据
  953. */
  954. public resetAllData(): void {
  955. sys.localStorage.removeItem(this.SAVE_KEY);
  956. sys.localStorage.removeItem(this.BACKUP_KEY);
  957. this.createNewPlayerData();
  958. }
  959. /**
  960. * 导出存档数据(用于调试)
  961. */
  962. public exportSaveData(): string {
  963. return JSON.stringify(this.playerData, null, 2);
  964. }
  965. /**
  966. * 导入存档数据(用于调试)
  967. */
  968. public importSaveData(dataString: string): boolean {
  969. try {
  970. const data = JSON.parse(dataString);
  971. this.playerData = this.validateAndMigrateData(data);
  972. this.savePlayerData(true);
  973. return true;
  974. } catch (error) {
  975. console.error('❌ 存档数据导入失败:', error);
  976. return false;
  977. }
  978. }
  979. /**
  980. * 获取存档摘要信息
  981. */
  982. public getSaveSummary(): string {
  983. if (!this.playerData) return '无存档数据';
  984. return `墙体等级: ${this.playerData.wallLevel} | ` +
  985. `当前关卡: ${this.playerData.currentLevel} | ` +
  986. `最高关卡: ${this.playerData.maxUnlockedLevel} | ` +
  987. `局外钞票: ${this.playerData.money} | ` +
  988. `钻石: ${this.playerData.diamonds} | ` +
  989. `游戏次数: ${this.playerData.statistics.totalGamesPlayed}`;
  990. }
  991. }