So I have a problem with my C++ game. If I try to use an item that has the quantity <= than 0, it will work. How can I prevent the function from using the item if it's quantity is <= than 0? Here is some of the code:
Use item function
void Inventory::useItem(int id, int quantity, Character &character)
{
if (id == 2 && !isNull())
{
removeQuantity(2, 1);
cout << "\n" << "You used the item with Id 2!" << endl;
character.addOrbs(100);
}
else
{
setColor(0x0C);
cout << "\n" << "ERROR! ";
setColor(0x07);
cout << "There is no item with such ID!" << endl;
}
}
Check if item quantity is 0 function
bool Inventory::isNull()
{
for(auto &item : inventoryVec)
{
if (item.quantity <= 0)
return true;
else
return false;
}
}
Your isNull()
method is checking if only the 1st item in the inventory, regardless of its id
, has a quantity of <= 0
. It is ignoring all other items.
What you should be doing instead is looking specifically for the item with an id of 2, and then checking if that item has a quantity of <= 0
, eg:
bool Inventory::isNull(int id)
{
for(auto &item : inventoryVec)
{
if (item.id == id)
return (item.quantity <= 0);
}
return true;
}
void Inventory::useItem(int id, int quantity, Character &character)
{
if ((id == 2) && !isNull(id))
{
removeQuantity(2, 1);
cout << "\n" << "You used the item with Id 2!" << endl;
character.addOrbs(100);
}
else
{
setColor(0x0C);
cout << "\n" << "ERROR! ";
setColor(0x07);
cout << "There is no item with such ID!" << endl;
}
}
Though, I would suggest changing useItem()
to be more like this instead:
void Inventory::useItem(int id, int quantity, Character &character)
{
if (!isNull(id))
{
removeQuantity(id, 1);
cout << "\n" << "You used the item with Id " << id << "!" << endl;
if (id == 2)
character.addOrbs(100);
else
... // handle other ids as needed...
}
else
{
setColor(0x0C);
cout << "\n" << "ERROR! ";
setColor(0x07);
cout << "There is no item with such ID!" << endl;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.