iwmlib/lib/pixi/maps/maplist.js

79 lines
2.0 KiB
JavaScript

export class MapList {
constructor(active = null, maps = {}) {
this.maps = maps
this.active = active
if (Object.keys(maps).length > 0) this.select(active)
}
/**
* Selects a map from the map list.
*
* @param {string} active - Name of the map to select.
* @returns
* @memberof MapList
*/
select(active) {
let map = null
if (active !== this.active) {
let keys = Object.keys(this.maps)
if (keys.length > 0) {
if (this.maps[active] == null) {
let altActive = keys[0]
console.warn(
`The MapList does not contain the provided active key '${active}'. Used '${altActive}' as fallback.`
)
active = altActive
}
if (this.active !== active) {
this.active = active
map = this.maps[active]
}
} else {
console.error(`Could not provide a fallback map! The map object is empty.`)
}
}
return map
}
clone() {
let maps = {}
for (let name of Object.keys(this.maps)) {
maps[name] = this.maps[name].clone()
}
return new MapList(this.active, maps)
}
add(key, map) {
if (this.maps[key] != null) consol.warn('Key already in mapList. The existing key was overwritten.')
if (this.active == null) this.active = key
map.name = key
this.maps[key] = map
}
get map() {
return this.maps && this.maps[this.active] ? this.maps[this.active] : null
}
next() {
let keys = Object.keys(this.maps)
let idx = keys.indexOf(this.active)
let next = idx + 1 < keys.length ? keys[idx + 1] : keys[0]
return next
}
cleanup() {
for (let key in this.maps) {
let map = this.maps[key]
map.remove()
}
}
}