1
0
Fork 0
lasertank-js/lib/MapSet.js

120 lines
3.3 KiB
JavaScript

/**
* Handles the loading of LVL files
*
* Copyright (C) 2012 Mike Gerwitz
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* Maps (the term "level" is used in the game) are stored in a fixed-width LVL
* file.
*/
/**
* Handles delegation of LVL data
*
* This acts as a Map factory, leaving all processing responsibilities to the
* Map instance. Consequently, any custom map format would be supported,
* provided that the appropriate Map is handling it.
*/
ltjs.MapSet = Class( 'MapSet',
{
/**
* Raw level set data (binary)
* @type {string}
*/
'private _data': '',
/**
* Constructor used to create new map instances
* @type {Function}
*/
'private _mapCtor': null,
/**
* Number of maps in the given LVL data
* @type {number}
*/
'private _mapCount': 0,
/**
* Initialize map set with LVL data and a Map constructor
*
* The Map constructor is used in place of a separate Map factory.
*
* @param {string} data binary LVL data
* @param {ltjs.Map} map_ctor Map constructor
*/
__construct: function( data, map_ctor )
{
this._data = ''+( data );
this._mapCtor = map_ctor;
// perform a simple integrity check on the provided data
this._mapDataCheck();
},
/**
* Perform a simple map data integrity check
*
* This is intended to throw an error if we believe the LVL data to be
* invalid, or if the LVL data is invalid for the given Map constructor.
* The check will simply ensure that the map size (in bytes) divides into
* the total LVL size (in bytes) without any remainder.
*
* This is by no means fool-proof, but it should catch most.
*
* @return {undefined}
*/
'private _mapDataCheck': function()
{
var n = ( this._data.length / this._mapCtor.getMapSize() );
// if the result is not an integer, then it is either not an LVL, the
// file is corrupt, or we were given the wrong Map constructor
if ( n % 1 )
{
throw Error( 'Invalid or corrupt LVL data' );
}
// we already calculated it, so we may as well store it
this._mapCount = n;
},
/**
* Load a level by the given number (e.g. level 1)
*
* @param {number} id number of level to load, 1-indexed
*/
'public getMapByNumber': function( id )
{
return this._mapCtor( this._data, id );
},
/**
* Retrieve the number of maps in the LVL file
*
* @return {number} number of maps
*/
'public getMapCount': function()
{
return this._mapCount;
},
} );