SaveDataManager.ts 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  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: 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. }