iwmlib/lib/pixi/maps/maplist.js

79 lines
2.0 KiB
JavaScript
Raw Normal View History

2019-11-05 11:07:36 +01:00
export class MapList {
constructor(active = null, maps = {}) {
2019-11-05 11:07:36 +01:00
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)
}
2019-11-05 11:07:36 +01:00
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
2019-11-05 11:07:36 +01:00
map.name = key
this.maps[key] = map
}
get map() {
return this.maps && this.maps[this.active] ? this.maps[this.active] : null
2019-11-05 11:07:36 +01:00
}
next() {
let keys = Object.keys(this.maps)
let idx = keys.indexOf(this.active)
let next = idx + 1 < keys.length ? keys[idx + 1] : keys[0]
2019-11-05 11:07:36 +01:00
return next
}
cleanup() {
for (let key in this.maps) {
let map = this.maps[key]
map.remove()
}
}
2019-11-05 11:07:36 +01:00
}