SaveDataManager.ts 40 KB

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