bubble sort for inventory

This commit is contained in:
bgiraudr 2022-07-05 23:00:55 +02:00
parent 1513502e0b
commit 1aa2b6c90b
5 changed files with 35 additions and 3 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@ -13,4 +13,5 @@ bool add_item_to_inventory(struct Game *game, struct Inventory *inventory, struc
int get_first_free_space(struct Inventory *inventory);
void display_inventory(struct Inventory *inventory);
int open_inventory(struct Game *game, struct Inventory *inventory, char* context, bool keep_open);
int get_nb_items(struct Inventory *inventory);
int get_nb_items(struct Inventory *inventory);
void sort_inventory(struct Inventory *inventory);

View File

@ -19,4 +19,5 @@ struct Items {
struct Item *get_item_id(int id);
bool select_item(struct Game *game, int pos);
void remove_item_pos(struct Inventory *inventory, int pos);
struct Item *get_item_from_name(const char *name);
struct Item *get_item_from_name(const char *name);
int compare(struct Item *item1, struct Item *item2);

View File

@ -32,6 +32,29 @@ int get_nb_items(struct Inventory *inventory) {
return ret;
}
void sort_inventory(struct Inventory *inventory) {
const int n = NB_PLAYER_ITEMS;
int i = 0, j = 0;
struct Item *tmp;
for (i = 0; i < n; i++) {
for (j = 0; j < n - i - 1; j++) {
if (inventory->items[j+1] != NULL) {
if (inventory->items[j] != NULL) {
if (compare(inventory->items[j], inventory->items[j+1]) > 0) {
tmp = inventory->items[j];
inventory->items[j] = inventory->items[j + 1];
inventory->items[j + 1] = tmp;
}
} else {
tmp = inventory->items[j];
inventory->items[j] = inventory->items[j + 1];
inventory->items[j + 1] = tmp;
}
}
}
}
}
bool add_item_to_inventory(struct Game *game, struct Inventory *inventory, struct Item *item) {
int index = get_first_free_space(inventory);
@ -125,11 +148,14 @@ int open_inventory(struct Game *game, struct Inventory *inventory, char* context
if(keydown(KEY_OPTN)) {
suppression = suppression ? 0 : 1;
}
if(keydown(KEY_F6)) {
sort_inventory(inventory);
}
if(keydown(KEY_EXIT)) {
pos = -1;
break;
}
while(keydown_any(KEY_RIGHT, KEY_LEFT, KEY_DOWN, KEY_UP, KEY_SHIFT, KEY_OPTN, 0)) clearevents();
while(keydown_any(KEY_RIGHT, KEY_LEFT, KEY_DOWN, KEY_UP, KEY_SHIFT, KEY_OPTN, KEY_F6, 0)) clearevents();
}
return pos;
}

View File

@ -38,4 +38,8 @@ struct Item *get_item_from_name(const char *name) {
if(!strcmp(items.items[i]->name, name)) return items.items[i];
}
return items.items[0];
}
int compare(struct Item *item1, struct Item *item2) {
return strcmp(item1->name, item2->name);
}