SaveDataManager.ts 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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: 20, // 初始局外金币
  198. diamonds: 0, // 初始钻石
  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: 0,
  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. public spendCoins(amount: number): boolean {
  532. return this.spendMoney(amount);
  533. }
  534. /**
  535. * 添加钻石
  536. */
  537. public addDiamonds(amount: number, source: string = 'unknown'): boolean {
  538. if (!this.playerData || amount <= 0) return false;
  539. this.playerData.diamonds += amount;
  540. this.addReward('diamonds', '', amount, source);
  541. // 触发货币变化事件
  542. EventBus.getInstance().emit(GameEvents.CURRENCY_CHANGED);
  543. return true;
  544. }
  545. /**
  546. * 消费钻石
  547. */
  548. public spendDiamonds(amount: number): boolean {
  549. if (!this.playerData || amount <= 0 || this.playerData.diamonds < amount) {
  550. return false;
  551. }
  552. this.playerData.diamonds -= amount;
  553. // 触发货币变化事件
  554. EventBus.getInstance().emit(GameEvents.CURRENCY_CHANGED);
  555. return true;
  556. }
  557. // === 墙体等级管理 ===
  558. /**
  559. * 升级墙体等级
  560. */
  561. public upgradeWallLevel(): boolean {
  562. if (!this.playerData) return false;
  563. if (this.playerData.wallLevel >= 5) return false; // 最高5级
  564. this.playerData.wallLevel += 1;
  565. // 根据等级设置墙体血量
  566. const wallHpMap: Record<number, number> = {
  567. 1: 100,
  568. 2: 1000,
  569. 3: 1200,
  570. 4: 1500,
  571. 5: 2000
  572. };
  573. this.playerData.wallBaseHealth = wallHpMap[this.playerData.wallLevel] || (100 + (this.playerData.wallLevel - 1) * 200);
  574. this.savePlayerData(true);
  575. return true;
  576. }
  577. /**
  578. * 获取墙体升级费用
  579. */
  580. public getWallUpgradeCost(): number {
  581. if (!this.playerData) return 0;
  582. const costMap: Record<number, number> = {
  583. 1: 500, // 1级升2级
  584. 2: 1000, // 2级升3级
  585. 3: 2000, // 3级升4级
  586. 4: 4000 // 4级升5级
  587. };
  588. return costMap[this.playerData.wallLevel] || 0;
  589. }
  590. /**
  591. * 检查是否可以升级墙体
  592. */
  593. public canUpgradeWall(): boolean {
  594. if (!this.playerData) return false;
  595. if (this.playerData.wallLevel >= 5) return false;
  596. const cost = this.getWallUpgradeCost();
  597. return this.playerData.money >= cost;
  598. }
  599. // === 道具和武器管理 ===
  600. /**
  601. * 添加武器
  602. */
  603. public addWeapon(weaponId: string, rarity: string = 'common'): boolean {
  604. if (!this.playerData) return false;
  605. if (!this.playerData.inventory.weapons[weaponId]) {
  606. this.playerData.inventory.weapons[weaponId] = {
  607. weaponId: weaponId,
  608. level: 1, // 初始等级为1,符合游戏设计
  609. rarity: rarity,
  610. obtainTime: Date.now(),
  611. upgradeCount: 0,
  612. isEquipped: false
  613. };
  614. this.playerData.statistics.weaponsUnlocked += 1;
  615. this.addReward('weapon', weaponId, 1, 'drop');
  616. return true;
  617. }
  618. return false;
  619. }
  620. /**
  621. * 获取武器数据
  622. */
  623. public getWeapon(weaponId: string): WeaponData | null {
  624. if (!this.playerData) return null;
  625. return this.playerData.inventory.weapons[weaponId] || null;
  626. }
  627. /**
  628. * 获取所有武器数据
  629. */
  630. public getAllWeapons(): { [weaponId: string]: WeaponData } {
  631. if (!this.playerData) return {};
  632. return this.playerData.inventory.weapons;
  633. }
  634. /**
  635. * 升级武器
  636. */
  637. public upgradeWeapon(weaponId: string): boolean {
  638. if (!this.playerData) return false;
  639. const weapon = this.playerData.inventory.weapons[weaponId];
  640. if (!weapon || weapon.level === 0) return false; // 0级武器需要先解锁
  641. const cost = this.getWeaponUpgradeCost(weaponId);
  642. if (!this.spendMoney(cost)) return false;
  643. weapon.level += 1;
  644. weapon.upgradeCount += 1;
  645. return true;
  646. }
  647. /**
  648. * 获取武器升级费用
  649. */
  650. public getWeaponUpgradeCost(weaponId: string): number {
  651. const weapon = this.getWeapon(weaponId);
  652. if (!weapon || weapon.level === 0) return 0; // 0级武器需要解锁,不是升级
  653. // 金币消耗:升级消耗金币 = 25 × 升级前武器等级
  654. return 25 * weapon.level;
  655. }
  656. /**
  657. * 检查是否可以升级武器
  658. */
  659. public canUpgradeWeapon(weaponId: string): boolean {
  660. const weapon = this.getWeapon(weaponId);
  661. if (!weapon || weapon.level === 0) return false; // 0级武器需要先解锁
  662. const cost = this.getWeaponUpgradeCost(weaponId);
  663. return this.getMoney() >= cost;
  664. }
  665. /**
  666. * 解锁武器(将等级从0提升到1)
  667. */
  668. public unlockWeapon(weaponId: string): boolean {
  669. if (!this.playerData) return false;
  670. // 如果武器不存在,先添加(添加时已经是等级1)
  671. if (!this.playerData.inventory.weapons[weaponId]) {
  672. this.addWeapon(weaponId);
  673. return true; // 添加武器即表示解锁成功
  674. }
  675. const weapon = this.playerData.inventory.weapons[weaponId];
  676. if (!weapon) return false;
  677. // 武器已经存在且等级>=1,表示已解锁
  678. return weapon.level >= 1;
  679. }
  680. /**
  681. * 检查武器是否已解锁
  682. */
  683. public isWeaponUnlocked(weaponId: string): boolean {
  684. // 根据关卡进度判断武器是否应该解锁
  685. const requiredLevel = this.getWeaponUnlockLevel(weaponId);
  686. const maxUnlockedLevel = this.getMaxUnlockedLevel();
  687. console.log(`[PreviewInEditor] 检查武器解锁: ${weaponId}, 需要关卡: ${requiredLevel}, 当前最大解锁关卡: ${maxUnlockedLevel}`);
  688. return maxUnlockedLevel >= requiredLevel;
  689. }
  690. /**
  691. * 获取武器解锁所需的关卡等级
  692. */
  693. private getWeaponUnlockLevel(weaponId: string): number {
  694. const weaponUnlockMap: { [key: string]: number } = {
  695. 'pea_shooter': 1, // 毛豆射手 - 第1关
  696. 'sharp_carrot': 2, // 尖胡萝卜 - 第2关
  697. 'saw_grass': 3, // 锯齿草 - 第3关
  698. 'watermelon_bomb': 4, // 西瓜炸弹 - 第4关
  699. 'boomerang_plant': 5, // 回旋镖植物 - 第5关
  700. 'hot_pepper': 6, // 炙热辣椒 - 第6关
  701. 'cactus_shotgun': 7, // 仙人散弹 - 第7关
  702. 'okra_missile': 8, // 秋葵导弹 - 第8关
  703. 'mace_club': 9 // 狼牙棒 - 第9关
  704. };
  705. return weaponUnlockMap[weaponId] || 1;
  706. }
  707. /**
  708. * 添加道具
  709. */
  710. public addItem(itemId: string, count: number = 1): boolean {
  711. if (!this.playerData || count <= 0) return false;
  712. if (!this.playerData.inventory.items[itemId]) {
  713. this.playerData.inventory.items[itemId] = {
  714. itemId: itemId,
  715. count: 0,
  716. obtainTime: Date.now(),
  717. lastUsedTime: 0
  718. };
  719. }
  720. this.playerData.inventory.items[itemId].count += count;
  721. this.playerData.statistics.itemsCollected += count;
  722. this.addReward('item', itemId, count, 'drop');
  723. return true;
  724. }
  725. /**
  726. * 使用道具
  727. */
  728. public useItem(itemId: string, count: number = 1): boolean {
  729. if (!this.playerData || count <= 0) return false;
  730. const item = this.playerData.inventory.items[itemId];
  731. if (!item || item.count < count) {
  732. return false;
  733. }
  734. item.count -= count;
  735. item.lastUsedTime = Date.now();
  736. if (item.count === 0) {
  737. delete this.playerData.inventory.items[itemId];
  738. }
  739. return true;
  740. }
  741. // === 奖励管理 ===
  742. /**
  743. * 添加奖励记录
  744. */
  745. private addReward(type: RewardData['type'], id: string, amount: number, source: string): void {
  746. if (!this.playerData) return;
  747. const reward: RewardData = {
  748. type: type,
  749. id: id,
  750. amount: amount,
  751. obtainTime: Date.now(),
  752. source: source
  753. };
  754. // 这里可以添加到全局奖励历史记录中
  755. // 暂时不实现,避免数据过大
  756. }
  757. /**
  758. * 从JSON配置文件获取关卡奖励数据
  759. */
  760. public async getLevelRewardsFromConfig(levelId: number): Promise<{coins: number, diamonds: number} | null> {
  761. try {
  762. // 由于不支持动态导入,改为直接导入
  763. const configManager = LevelConfigManager.getInstance();
  764. if (!configManager) {
  765. console.warn(`LevelConfigManager未初始化,使用默认奖励`);
  766. return null;
  767. }
  768. const levelConfig = await configManager.getLevelConfig(levelId);
  769. if (levelConfig && levelConfig.levelSettings && (levelConfig.levelSettings as any).rewards) {
  770. const rewards = (levelConfig.levelSettings as any).rewards;
  771. return {
  772. coins: rewards.coins || 0,
  773. diamonds: rewards.diamonds || 0
  774. };
  775. }
  776. // 如果JSON中没有奖励配置,尝试直接从JSON文件读取
  777. const jsonPath = `data/levels/Level${levelId}`;
  778. return new Promise((resolve) => {
  779. resources.load(jsonPath, JsonAsset, (err, asset) => {
  780. if (err || !asset) {
  781. console.warn(`无法加载关卡${levelId}的JSON配置:`, err);
  782. resolve(null);
  783. return;
  784. }
  785. const jsonData = asset.json;
  786. if (jsonData && jsonData.rewards) {
  787. resolve({
  788. coins: jsonData.rewards.coins || 0,
  789. diamonds: jsonData.rewards.diamonds || 0
  790. });
  791. } else {
  792. resolve(null);
  793. }
  794. });
  795. });
  796. } catch (error) {
  797. console.error(`获取关卡${levelId}奖励配置失败:`, error);
  798. return null;
  799. }
  800. }
  801. /**
  802. * 给予关卡完成奖励(从JSON配置获取)
  803. */
  804. public async giveCompletionRewards(levelId: number): Promise<void> {
  805. // 尝试从JSON配置文件获取奖励数据
  806. const configRewards = await this.getLevelRewardsFromConfig(levelId);
  807. let actualCoins = 0;
  808. let actualDiamonds = 0;
  809. if (configRewards) {
  810. // 使用JSON配置中的奖励数据
  811. if (configRewards.coins > 0) {
  812. this.addMoney(configRewards.coins, `level_${levelId}_complete`);
  813. actualCoins = configRewards.coins;
  814. }
  815. if (configRewards.diamonds > 0) {
  816. this.addDiamonds(configRewards.diamonds, `level_${levelId}_complete`);
  817. actualDiamonds = configRewards.diamonds;
  818. }
  819. }
  820. // 特殊关卡额外奖励(里程碑奖励)
  821. // if (levelId % 10 === 0) {
  822. // this.addGems(1, `level_${levelId}_milestone`);
  823. // }
  824. // 存储最近的奖励记录
  825. this.lastRewards = {money: actualCoins, diamonds: actualDiamonds};
  826. }
  827. /**
  828. * 根据波数比例给予失败奖励
  829. */
  830. public async giveFailureRewards(levelId: number, completedWaves: number, totalWaves: number): Promise<void> {
  831. if (completedWaves <= 0 || totalWaves <= 0) {
  832. // 重置最近奖励为0
  833. this.lastRewards = {money: 0, diamonds: 0};
  834. return;
  835. }
  836. // 获取完整奖励数据
  837. const configRewards = await this.getLevelRewardsFromConfig(levelId);
  838. // 计算波数完成比例
  839. const waveRatio = Math.min(completedWaves / totalWaves, 1.0);
  840. let actualCoins = 0;
  841. let actualDiamonds = 0;
  842. if (configRewards) {
  843. // 基于JSON配置计算比例奖励(取整)
  844. const partialCoins = Math.floor(configRewards.coins * waveRatio);
  845. const partialDiamonds = Math.floor(configRewards.diamonds * waveRatio);
  846. if (partialCoins > 0) {
  847. this.addMoney(partialCoins, `level_${levelId}_partial_${completedWaves}/${totalWaves}`);
  848. actualCoins = partialCoins;
  849. }
  850. if (partialDiamonds > 0) {
  851. this.addDiamonds(partialDiamonds, `level_${levelId}_partial_${completedWaves}/${totalWaves}`);
  852. actualDiamonds = partialDiamonds;
  853. }
  854. } else {
  855. // 回退到默认计算
  856. const baseCoins = levelId * 50;
  857. const partialCoins = Math.floor(baseCoins * waveRatio);
  858. if (partialCoins > 0) {
  859. this.addMoney(partialCoins, `level_${levelId}_partial_${completedWaves}/${totalWaves}`);
  860. actualCoins = partialCoins;
  861. }
  862. }
  863. // 存储最近的奖励记录
  864. this.lastRewards = {money: actualCoins, diamonds: actualDiamonds};
  865. }
  866. /**
  867. * 获取最近的奖励记录(用于UI显示)
  868. */
  869. public getLastRewards(): {money: number, diamonds: number} {
  870. return {...this.lastRewards};
  871. }
  872. // === 统计数据更新 ===
  873. public updateStatistic(key: keyof GameStatistics, value: number): void {
  874. if (!this.playerData) return;
  875. if (typeof this.playerData.statistics[key] === 'number') {
  876. (this.playerData.statistics[key] as number) += value;
  877. }
  878. }
  879. // === 设置管理 ===
  880. public updateSetting<K extends keyof PlayerSettings>(key: K, value: PlayerSettings[K]): void {
  881. if (!this.playerData) return;
  882. this.playerData.settings[key] = value;
  883. this.savePlayerData();
  884. }
  885. public getSetting<K extends keyof PlayerSettings>(key: K): PlayerSettings[K] {
  886. return this.playerData?.settings[key];
  887. }
  888. // === 工具方法 ===
  889. /**
  890. * 生成唯一玩家ID
  891. */
  892. private generatePlayerId(): string {
  893. return `player_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  894. }
  895. /**
  896. * 重置所有数据
  897. */
  898. public resetAllData(): void {
  899. sys.localStorage.removeItem(this.SAVE_KEY);
  900. sys.localStorage.removeItem(this.BACKUP_KEY);
  901. this.createNewPlayerData();
  902. }
  903. /**
  904. * 导出存档数据(用于调试)
  905. */
  906. public exportSaveData(): string {
  907. return JSON.stringify(this.playerData, null, 2);
  908. }
  909. /**
  910. * 导入存档数据(用于调试)
  911. */
  912. public importSaveData(dataString: string): boolean {
  913. try {
  914. const data = JSON.parse(dataString);
  915. this.playerData = this.validateAndMigrateData(data);
  916. this.savePlayerData(true);
  917. return true;
  918. } catch (error) {
  919. console.error('❌ 存档数据导入失败:', error);
  920. return false;
  921. }
  922. }
  923. /**
  924. * 获取存档摘要信息
  925. */
  926. public getSaveSummary(): string {
  927. if (!this.playerData) return '无存档数据';
  928. return `墙体等级: ${this.playerData.wallLevel} | ` +
  929. `当前关卡: ${this.playerData.currentLevel} | ` +
  930. `最高关卡: ${this.playerData.maxUnlockedLevel} | ` +
  931. `局外金币: ${this.playerData.money} | ` +
  932. `钻石: ${this.playerData.diamonds} | ` +
  933. `游戏次数: ${this.playerData.statistics.totalGamesPlayed}`;
  934. }
  935. }