SaveDataManager.ts 37 KB

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