naev 0.12.6
player_inventory.c
Go to the documentation of this file.
1/*
2 * See Licensing and Copyright notice in naev.h
3 */
10#include "naev.h"
12
13#include "player_inventory.h"
14
15#include "array.h"
16
17static PlayerItem *inventory = NULL;
18
19static void item_free( PlayerItem *pi )
20{
21 free( pi->name );
22}
23
28{
29 for ( int i = 0; i < array_size( inventory ); i++ )
30 item_free( &inventory[i] );
32 inventory = NULL;
33}
34
39{
40 return inventory;
41}
42
49int player_inventoryAmount( const char *name )
50{
51 for ( int i = 0; i < array_size( inventory ); i++ ) {
52 const PlayerItem *pi = &inventory[i];
53 if ( strcmp( pi->name, name ) == 0 )
54 return pi->quantity;
55 }
56 return 0;
57}
58
65int player_inventoryAdd( const char *name, int amount )
66{
67 PlayerItem npi;
68 if ( inventory == NULL )
70
71 for ( int i = 0; i < array_size( inventory ); i++ ) {
72 PlayerItem *pi = &inventory[i];
73 if ( strcmp( pi->name, name ) == 0 ) {
74 pi->quantity += amount;
75 return amount;
76 }
77 }
78
79 npi.name = strdup( name );
80 npi.quantity = amount;
82
83 return 0;
84}
85
92int player_inventoryRemove( const char *name, int amount )
93{
94 for ( int i = 0; i < array_size( inventory ); i++ ) {
95 PlayerItem *pi = &inventory[i];
96 if ( strcmp( pi->name, name ) == 0 ) {
97 int q = pi->quantity;
98 pi->quantity = MAX( 0, pi->quantity - amount );
99 q -= pi->quantity;
100 if ( pi->quantity == 0 ) {
101 item_free( pi );
102 array_erase( &inventory, &pi[0], &pi[1] );
103 }
104 return q;
105 }
106 }
107 return 0;
108}
Provides macros to work with dynamic arrays.
#define array_free(ptr_array)
Frees memory allocated and sets array to NULL.
Definition array.h:170
#define array_erase(ptr_array, first, last)
Erases elements in interval [first, last).
Definition array.h:148
static ALWAYS_INLINE int array_size(const void *array)
Returns number of elements in the array.
Definition array.h:179
#define array_push_back(ptr_array, element)
Adds a new element at the end of the array.
Definition array.h:134
#define array_create(basic_type)
Creates a new dynamic array of ‘basic_type’.
Definition array.h:93
Header file with generic functions and naev-specifics.
#define MAX(x, y)
Definition naev.h:37
int player_inventoryAdd(const char *name, int amount)
Adds an item to the player inventory.
static PlayerItem * inventory
void player_inventoryClear(void)
Clears the inventory and frees memory.
int player_inventoryRemove(const char *name, int amount)
Removes an item from the player inventory.
const PlayerItem * player_inventory(void)
Gets the whole player inventory.
int player_inventoryAmount(const char *name)
Gets the amount of an item the player has.
Represents an item in the player inventory.