SaveDataManager.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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<{coins: 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. coins: 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. coins: 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.coins > 0) {
  808. this.addMoney(configRewards.coins, `level_${levelId}_complete`);
  809. actualCoins = configRewards.coins;
  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. if (completedWaves <= 0 || totalWaves <= 0) {
  828. // 重置最近奖励为0
  829. this.lastRewards = {money: 0, diamonds: 0};
  830. return;
  831. }
  832. // 获取完整奖励数据
  833. const configRewards = await this.getLevelRewardsFromConfig(levelId);
  834. // 计算波数完成比例
  835. const waveRatio = Math.min(completedWaves / totalWaves, 1.0);
  836. let actualCoins = 0;
  837. let actualDiamonds = 0;
  838. if (configRewards) {
  839. // 基于JSON配置计算比例奖励(取整)
  840. const partialCoins = Math.floor(configRewards.coins * waveRatio);
  841. const partialDiamonds = Math.floor(configRewards.diamonds * waveRatio);
  842. if (partialCoins > 0) {
  843. this.addMoney(partialCoins, `level_${levelId}_partial_${completedWaves}/${totalWaves}`);
  844. actualCoins = partialCoins;
  845. }
  846. if (partialDiamonds > 0) {
  847. this.addDiamonds(partialDiamonds, `level_${levelId}_partial_${completedWaves}/${totalWaves}`);
  848. actualDiamonds = partialDiamonds;
  849. }
  850. } else {
  851. // 回退到默认计算
  852. const baseCoins = levelId * 50;
  853. const partialCoins = Math.floor(baseCoins * waveRatio);
  854. if (partialCoins > 0) {
  855. this.addMoney(partialCoins, `level_${levelId}_partial_${completedWaves}/${totalWaves}`);
  856. actualCoins = partialCoins;
  857. }
  858. }
  859. // 存储最近的奖励记录
  860. this.lastRewards = {money: actualCoins, diamonds: actualDiamonds};
  861. }
  862. /**
  863. * 获取最近的奖励记录(用于UI显示)
  864. */
  865. public getLastRewards(): {money: number, diamonds: number} {
  866. return {...this.lastRewards};
  867. }
  868. // === 统计数据更新 ===
  869. public updateStatistic(key: keyof GameStatistics, value: number): void {
  870. if (!this.playerData) return;
  871. if (typeof this.playerData.statistics[key] === 'number') {
  872. (this.playerData.statistics[key] as number) += value;
  873. }
  874. }
  875. // === 设置管理 ===
  876. public updateSetting<K extends keyof PlayerSettings>(key: K, value: PlayerSettings[K]): void {
  877. if (!this.playerData) return;
  878. this.playerData.settings[key] = value;
  879. this.savePlayerData();
  880. }
  881. public getSetting<K extends keyof PlayerSettings>(key: K): PlayerSettings[K] {
  882. return this.playerData?.settings[key];
  883. }
  884. // === 工具方法 ===
  885. /**
  886. * 生成唯一玩家ID
  887. */
  888. private generatePlayerId(): string {
  889. return `player_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  890. }
  891. /**
  892. * 重置所有数据
  893. */
  894. public resetAllData(): void {
  895. sys.localStorage.removeItem(this.SAVE_KEY);
  896. sys.localStorage.removeItem(this.BACKUP_KEY);
  897. this.createNewPlayerData();
  898. }
  899. /**
  900. * 导出存档数据(用于调试)
  901. */
  902. public exportSaveData(): string {
  903. return JSON.stringify(this.playerData, null, 2);
  904. }
  905. /**
  906. * 导入存档数据(用于调试)
  907. */
  908. public importSaveData(dataString: string): boolean {
  909. try {
  910. const data = JSON.parse(dataString);
  911. this.playerData = this.validateAndMigrateData(data);
  912. this.savePlayerData(true);
  913. return true;
  914. } catch (error) {
  915. console.error('❌ 存档数据导入失败:', error);
  916. return false;
  917. }
  918. }
  919. /**
  920. * 获取存档摘要信息
  921. */
  922. public getSaveSummary(): string {
  923. if (!this.playerData) return '无存档数据';
  924. return `墙体等级: ${this.playerData.wallLevel} | ` +
  925. `当前关卡: ${this.playerData.currentLevel} | ` +
  926. `最高关卡: ${this.playerData.maxUnlockedLevel} | ` +
  927. `局外金币: ${this.playerData.money} | ` +
  928. `钻石: ${this.playerData.diamonds} | ` +
  929. `游戏次数: ${this.playerData.statistics.totalGamesPlayed}`;
  930. }
  931. }