CabinGame/Luxe/blocks/resources.wren
2020-09-18 18:49:02 +02:00

65 lines
No EOL
1.6 KiB
Text

import "luxe: assets" for Assets
import "math/event" for Event
import "math/observable" for Observable
import "math/stringUtil" for StringUtil
class Resources is Observable{
construct new(){
super()
_resources = {}
_nameList = Assets.lx("assets/resources.lx")
value_no_update = this
}
list(){
//construct map from name and amount
var list = _nameList.map{ |res| {"name": res, "amount": _resources[res["name"]]}}.//<-- butt dot!
//filter out the ones without an amount
where{ |res| res["amount"] }.
//get correct name and respect plural rules //also this is its own line because each returns void >.>
map{ |res| {"name": res["amount"] != 1 && !res["name"]["alwaysSingular"] ? StringUtil.plural(res["name"]["name"]) : res["name"]["name"],
"amount": res["amount"] }}
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)
}
empty(resource){
var value = get(resource)
if(value > 0){ //this check is to not initialize undefined resource types
set(resource, 0)
}
return value
}
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 than amount
}
}