SaveDataManager.ts 34 KB

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