Skip to content

Commit

Permalink
don't store tiny:air in inv
Browse files Browse the repository at this point in the history
  • Loading branch information
j0code committed Nov 30, 2024
1 parent 6af8422 commit 96b9460
Showing 1 changed file with 13 additions and 16 deletions.
29 changes: 13 additions & 16 deletions src/Inventory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,13 @@ export default class Inventory implements HasData {

readonly size: number
readonly columns: number
private slots: ItemStack[]
private slots: (ItemStack | undefined)[]

constructor(size: number, columns: number = 9, data: InventoryData = []) {
this.size = size
this.columns = columns
this.slots = []

// fill with air (default)
for (let i = 0; i < this.size; i++) this.slots[i] = new ItemStack(new Item("tiny:air"), 1)


// fill slots with data
data.forEach(stack => {
this.slots[stack.slot] = new ItemStack(stack.item.id, stack.amount)
Expand All @@ -28,21 +24,21 @@ export default class Inventory implements HasData {
else throw new Error(`IndexOutOfBounds: Inventory slot ${index} (0..${this.size})`)
}

get(index: number) {
if (index >= 0 && index < this.size) return this.slots[index]
get(index: number): ItemStack {
if (index >= 0 && index < this.size) return this.slots[index] ?? new ItemStack("tiny:air")

throw new Error(`IndexOutOfBounds: Inventory slot ${index} (0..${this.size})`)
}

each(cb: (value: ItemStack, index: number) => void) {
return this.slots.forEach(cb)
return this.slots.forEach((stack, index) => cb(stack || new ItemStack("tiny:air"), index))
}

addItems(stack: ItemStack): ItemStack | null {
let { amount } = stack

for (const i in this.slots) {
const slot = this.slots[i]
for (const i of this.slots.keys()) {
const slot = this.get(i)

if (amount <= 0) break

Expand All @@ -67,30 +63,31 @@ export default class Inventory implements HasData {
}

find(item: Item): number {
for (const i in this.slots) if (this.slots[i].match(item)) return Number(i)
for (const i of this.slots.keys()) if (this.get(i).match(item)) return Number(i)

return -1
}

emptySlots(): number {
let count = 0
for (const slot of this.slots) {
if (slot.item.id.matches("tiny:air")) count++
}

this.each(stack => {
if (stack.item.id.matches("tiny:air")) count++
})

return count
}

firstEmptySlot(): number {
for (const i in this.slots) if (this.slots[i].item.id.matches("tiny:air")) return Number(i)
for (const i of this.slots.keys()) if (this.get(i).item.id.matches("tiny:air")) return Number(i)

return -1
}

getData() {
const arr: (ReturnType<ItemStack["getData"]> & {slot: number})[] = []

this.slots.forEach((slot, index) => {
this.each((slot, index) => {
if (slot.item.id.matches("tiny:air")) return

arr.push({ ...slot.getData(), slot: index })
Expand Down

0 comments on commit 96b9460

Please sign in to comment.