LocalStorage for levels

This commit is contained in:
Nikita Iryupin 2021-06-05 17:41:26 +02:00
parent 89a504641a
commit b807825832
3 changed files with 33 additions and 5 deletions

View File

@ -29,6 +29,7 @@ export class GameField {
this.map = null;
this.soundManager = new SoundManager();
this.mapParser = new MapParser();
this.collisionManager = new CollisionManager(this.soundManager);
this.tank = new Tank(Constants.PLAYER_TANK_ID_IMAGE.getValue(), 0, 18 * 16, this.collisionManager);
@ -82,7 +83,7 @@ export class GameField {
await this.setupTileset();
}
this.map = await new MapParser().getMap(level, this.tileset);
this.map = await this.mapParser.getMap(level, this.tileset);
this.canvas.height = this.height;
this.canvas.width = this.width;
this.collisionManager.attachMap(this.map);

View File

@ -0,0 +1,18 @@
export class LevelStorage {
constructor(){
this.localStorage = window.localStorage;
}
/**
* @param {number} level
* @param {string} json
*/
setLevel(level, json){
this.localStorage.setItem(level.toString(), json.toString());
}
getLevel(level) {
return this.localStorage.getItem(level.toString());
}
}

View File

@ -2,17 +2,26 @@ import { BlockBuilder } from "./../../Blocks/blockBuilder"
import { Map } from "./map";
import { Constants } from "./../../constants"
import { BlockTypeEnum } from "./../../Blocks/blockTypeEnum"
import { LevelStorage } from "./levelStorage"
export class MapParser {
constructor() {
this.levelStorage = new LevelStorage();
}
async getMap(levelNumber, tileset) {
let json = this.levelStorage.getLevel(levelNumber);
if (!json) {
let fetchResult = await fetch(`./stages/stage-${levelNumber}.json`);
if (!fetchResult.ok)
return null;
let mapObject = await fetchResult.json();
json = await fetchResult.text();
this.levelStorage.setLevel(levelNumber, json);
}
let mapObject = JSON.parse(json);
var map = new Map(mapObject.size.width, mapObject.size.height, mapObject.bots, mapObject.name);