CabinGame/Luxe/blocks/resources.wren
2020-10-31 15:13:01 +01:00

96 lines
No EOL
2.3 KiB
Text

import "luxe: assets" for Assets
import "luxe: world" for Entity
import "math/event" for Event
import "math/observable" for Observable
import "math/stringUtil" for StringUtil
import "math/util" for Actions
class Resources is Observable{
construct new(){
super()
_resources = {}
_nameList = Assets.lx("assets/resources.lx")
value_no_update = this
}
toString{
return list().map{|resource| "%(resource["amount"]) %(resource["name"])"}.toList.toString
}
list(){
//construct map from name and amount
var list = _nameList.map{ |res| {"name": res, "amount": _resources[res["name"]]}}.
//filter out the ones without an amount
where{ |res| res["amount"] }.
toList //toList makes the each work ^^ otherwise the result sequence runs map twice
//get correct name and respect plural rules //also this is its own line because each returns void >.>
list.each{ |res|
var name = res["name"]["name"]
var singular = res["amount"] == 1 || res["name"]["alwaysSingular"]
res["name"] = singular ? name : StringUtil.plural(name)
res["base_name"] = name
}
return list
}
get(resource){
return _resources[resource] || 0
}
set(resource, amount){
_resources[resource] = amount
emit()
}
add(resource, amount){
var value = get(resource)
set(resource, value + amount)
}
remove(resource, amount){
add(resource, -amount)
}
clear(resource){
var value = get(resource)
if(value > 0){ //this check is to not initialize undefined resource types
set(resource, 0)
}
return value
}
empty(resource){
return !has(resource, 1) //returns true if resource doesn't exist or is 0 (or negative??)
}
exists(resource){
return _resources.containsKey(resource)
}
removeEmpty(){
for(key in _resources.keys){
if(empty(key)){
Actions.queue{
_resources.remove(key)
}
}
}
Actions.execute()
}
tryRemove(resource, amount){
if(has(resource, amount)){
remove(resource, amount)
return true
} else {
return false
}
}
has(resource, amount){
var value = _resources[resource]
return value && value >= amount //check if not null, and bigger/equal than amount
}
}