68 lines
2.0 KiB
C
68 lines
2.0 KiB
C
/**
|
|
* Copyright (c) 2025 Dominic Masters
|
|
*
|
|
* This software is released under the MIT License.
|
|
* https://opensource.org/licenses/MIT
|
|
*/
|
|
|
|
#include "inventory.h"
|
|
#include "util/memory.h"
|
|
#include "assert/assert.h"
|
|
|
|
void inventoryInit(inventory_t *inventory, const uint8_t size) {
|
|
assertNotNull(inventory, "inventory must not be NULL");
|
|
assertTrue(size <= INVENTORY_SIZE_MAX, "size exceeding INVENTORY_SIZE_MAX");
|
|
assertTrue(size > 0, "size must be greater than 0");
|
|
|
|
memoryZero(inventory, sizeof(inventory_t));
|
|
inventory->size = size;
|
|
}
|
|
|
|
uint8_t inventoryItemIndexByType(
|
|
const inventory_t *inventory,
|
|
const itemtype_t type
|
|
) {
|
|
assertNotNull(inventory, "inventory must not be NULL");
|
|
assertTrue(type > ITEM_TYPE_NULL, "type must be greater than ITEM_TYPE_NULL");
|
|
|
|
uint8_t item = inventory->itemCount;
|
|
while(item--) {
|
|
if(inventory->items[item].type == type) return item;
|
|
}
|
|
return INVENTORY_SIZE_MAX;
|
|
}
|
|
|
|
uint8_t inventoryItemCount(
|
|
const inventory_t *inventory,
|
|
const itemtype_t type
|
|
) {
|
|
assertNotNull(inventory, "inventory must not be NULL");
|
|
assertTrue(type > ITEM_TYPE_NULL, "type must be greater than ITEM_TYPE_NULL");
|
|
|
|
const uint8_t index = inventoryItemIndexByType(inventory, type);
|
|
if(index == INVENTORY_SIZE_MAX) return 0;
|
|
return inventory->items[index].count;
|
|
}
|
|
|
|
void inventoryItemSet(
|
|
inventory_t *inventory,
|
|
const itemtype_t type,
|
|
const uint8_t count
|
|
) {
|
|
assertNotNull(inventory, "inventory must not be NULL");
|
|
assertTrue(type > ITEM_TYPE_NULL, "type must be greater than ITEM_TYPE_NULL");
|
|
assertTrue(count > 0, "count must be greater than 0");
|
|
|
|
const uint8_t index = inventoryItemIndexByType(inventory, type);
|
|
|
|
if(index == INVENTORY_SIZE_MAX) {
|
|
// Item does not exist, add it
|
|
assertTrue(inventory->itemCount < inventory->size, "inventory is full");
|
|
inventory->items[inventory->itemCount].type = type;
|
|
inventory->items[inventory->itemCount].count = count;
|
|
inventory->itemCount++;
|
|
} else {
|
|
// Item exists, update the count
|
|
inventory->items[index].count = count;
|
|
}
|
|
} |