ludic/packages/ludic.inventory/verbs.ludic

55 lines
2.2 KiB
Text

# verbs.ludic - the only way a count changes, and each change is said once
function iv_change(inventory_st: mut InventoryState, it: int, after: int) -> void {
let before = inventory_st.iv_counts[it]
if before == after { return }
inventory_st.iv_counts[it] = after
var c: ItemChanged = null
if len(inventory_st.iv_pool) > 0 {
c = inventory_st.iv_pool[inventory_st.iv_at]
inventory_st.iv_at = (inventory_st.iv_at + 1) % len(inventory_st.iv_pool)
} else {
@alloc_ok("never after inv_config: the ring is made there")
c = new ItemChanged
}
c.item = it
c.before = before
c.after = after
q_push(inv_changes(inventory_st), c)
}
# as many of n as there is room for; returns how many went in
export function inv_add(inventory_st: mut InventoryState, it: int, n: int) -> int {
if not iv_valid(inventory_st, it) or n <= 0 { return 0 }
let k = Math.min(n, inv_room(inventory_st, it))
if k > 0 { iv_change(inventory_st, it, inventory_st.iv_counts[it] + k) }
return k
}
# all n or none
export function inv_take(inventory_st: mut InventoryState, it: int, n: int) -> bool {
if not iv_valid(inventory_st, it) or inventory_st.iv_counts[it] < n { return false }
if n > 0 { iv_change(inventory_st, it, inventory_st.iv_counts[it] - n) }
return true
}
# a count outright, room or not (a starting kit, a correction, the network's word); never below 0
export function inv_set(inventory_st: mut InventoryState, it: int, n: int) -> void {
if not iv_valid(inventory_st, it) { return }
iv_change(inventory_st, it, Math.max(n, 0))
}
# everything gone, silently: a new trip, or before a load
export function inv_clear(inventory_st: mut InventoryState) -> void {
if inventory_st.iv_counts == null { inventory_st.iv_counts = iv_counts__new(inv_kinds(inventory_st)) }
List.clear(inventory_st.iv_counts)
for i in 0 .. inv_kinds(inventory_st) { kept_push(inventory_st.iv_counts, 0) }
}
# the counts made at their full length at once: a list grown a push at a time in play is a new block
@alloc_ok("once: the counts are made the first time the pack is cleared")
function iv_counts__new(n: int) -> []int {
let xs = new []int
for i in 0 .. n { push(xs, 0) }
List.clear(xs)
return xs
}