82 lines
2.5 KiB
TypeScript
82 lines
2.5 KiB
TypeScript
export class LevelCompressedManager {
|
|
private static instance: LevelCompressedManager;
|
|
private levelDataCache: Map<number, any> = new Map();
|
|
private allLevelsData: any = null;
|
|
private compressedData: string = null;
|
|
private isLoading: boolean = false;
|
|
|
|
private static get LZString(): any {
|
|
return (window as any).LZString;
|
|
}
|
|
|
|
public static getInstance(): LevelCompressedManager {
|
|
if (!LevelCompressedManager.instance) {
|
|
LevelCompressedManager.instance = new LevelCompressedManager();
|
|
}
|
|
return LevelCompressedManager.instance;
|
|
}
|
|
|
|
public setCompressedData(compressed: string): void {
|
|
this.compressedData = compressed;
|
|
this.allLevelsData = null;
|
|
this.levelDataCache.clear();
|
|
}
|
|
|
|
public async loadLevel(level: number): Promise<any> {
|
|
if (this.levelDataCache.has(level)) {
|
|
return this.levelDataCache.get(level);
|
|
}
|
|
|
|
await this.ensureDataLoaded();
|
|
|
|
if (this.allLevelsData && this.allLevelsData[level]) {
|
|
const levelData = this.allLevelsData[level];
|
|
this.levelDataCache.set(level, levelData);
|
|
return levelData;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private async ensureDataLoaded(): Promise<void> {
|
|
if (this.allLevelsData !== null) {
|
|
return;
|
|
}
|
|
|
|
if (this.isLoading) {
|
|
return;
|
|
}
|
|
|
|
this.isLoading = true;
|
|
|
|
try {
|
|
if (this.compressedData) {
|
|
const decompressed = LevelCompressedManager.LZString.decompressFromUTF16(this.compressedData);
|
|
if (decompressed) {
|
|
this.allLevelsData = JSON.parse(decompressed);
|
|
console.log(`关卡数据解压成功,共 ${Object.keys(this.allLevelsData).length} 个关卡`);
|
|
} else {
|
|
console.error('关卡数据解压失败');
|
|
this.allLevelsData = {};
|
|
}
|
|
} else {
|
|
console.warn('没有设置压缩数据');
|
|
this.allLevelsData = {};
|
|
}
|
|
} catch (e) {
|
|
console.error('关卡数据解析失败:', e);
|
|
this.allLevelsData = {};
|
|
} finally {
|
|
this.isLoading = false;
|
|
}
|
|
}
|
|
|
|
public clearCache(): void {
|
|
this.levelDataCache.clear();
|
|
}
|
|
|
|
public getLevelCount(): number {
|
|
return this.allLevelsData ? Object.keys(this.allLevelsData).length : 0;
|
|
}
|
|
}
|