Limit the number of items that can be held in the inventory

From TRCCompSci - AQA Computer Science
Revision as of 11:22, 18 December 2018 by LealWilliams (talk | contribs) (Created page with "=Method= To create an inventory limit, we should check if the inventory is full first. So we will create a method that checks if the inventory is full. <syntaxhighlight lang=c...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Method

To create an inventory limit, we should check if the inventory is full first. So we will create a method that checks if the inventory is full.

private static bool CheckInventoryFull(List<Item> items)
        {
            bool isFull = false;
            int itemsInInventory = 0; //counter for how many items have been found in the inventory
            int maxItems = 5; //the maximum amount of items in the inventory
            foreach (Item i in items) //foreach loop to check each item in the game
            {
                if (i.Location == Inventory)
                {
                    itemsInInventory++; //each item in the inventory will increment the counter
                }
            }
            if (itemsInInventory >= maxItems) //checking to see if the limit has been reached
            {
                isFull = true;
            }
            return isFull;
        }

Next, we will want to use this method for when we are getting new items. Find the "GetItem" method and we will want to add this code to the if statement as an additional check

else if (CheckInventoryFull(items))
{
    Console.WriteLine("Your inventory is full.");
}

This is best placed after the check for gettable items, and must be placed before the "else". The method created before is run during this if statement, and the result is used to determine the outcome during the check.