SaveDataManager.ts 32 KB

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