ludic/packages/ludic.inventory/state.ludic

67 lines
2.4 KiB
Text

# state.ludic - the pack's port, its facts, and its counts
# what the pack asks the game: how many of a kind fit (unbound: no limit)
export port PackRules {
stack_limit: fn(int) -> int = fn iv_no_limit
}
function iv_no_limit(it: int) -> int { return 2147483647 }
# a count changed, however: added, taken, or set outright
export property ItemChanged {
item: int = 0
before: int = 0
after: int = 0
}
# a change's record comes round again after this many more: far more than a frame makes between drains
const IV_POOL: int = 512
export state InventoryState {
iv_keys: []string = null
@max(1024) iv_counts: []int = null
iv_changes: Queue<ItemChanged> = iv_changes__new()
@max(512) iv_pool: []ItemChanged = new []ItemChanged # the facts' records, made once and taken in turn
iv_at: int = 0
}
# the kinds, by the name each is saved under; the pack starts empty
@alloc_ok("once: the pack's kinds are bound at start")
export function inv_config(inventory_st: mut InventoryState, keys: []string) -> void {
inventory_st.iv_keys = keys
if len(inventory_st.iv_pool) == 0 { for i in 0 .. IV_POOL { push(inventory_st.iv_pool, new ItemChanged) } }
inv_clear(inventory_st)
}
export function inv_changes(inventory_st: InventoryState) -> Queue<ItemChanged> {
return inventory_st.iv_changes
}
function iv_valid(inventory_st: InventoryState, it: int) -> bool { return inventory_st.iv_counts != null and it >= 0 and it < len(inventory_st.iv_counts) }
export function inv_kinds(inventory_st: InventoryState) -> int {
if inventory_st.iv_keys == null { return 0 }
return len(inventory_st.iv_keys)
}
export function inv_count(inventory_st: InventoryState, it: int) -> int {
if not iv_valid(inventory_st, it) { return 0 }
return inventory_st.iv_counts[it]
}
export function inv_limit(it: int) -> int {
return PackRules.stack_limit(it)
}
# how many more fit
export function inv_room(inventory_st: InventoryState, it: int) -> int {
if not iv_valid(inventory_st, it) { return 0 }
return Math.max(inv_limit(it) - inventory_st.iv_counts[it], 0)
}
export function inv_has(inventory_st: InventoryState, it: int, n: int) -> bool { return inv_count(inventory_st, it) >= n }
export function inv_total(inventory_st: InventoryState) -> int {
var t = 0
if inventory_st.iv_counts == null { return 0 }
for i in 0 .. len(inventory_st.iv_counts) { t += inventory_st.iv_counts[i] }
return t
}
function iv_changes__new() -> Queue<ItemChanged> { return queue_new("inventory.changes") }