Difference between revisions of "Limit the number of items that can be held in the inventory"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(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...")
 
(Method)
 
Line 1: Line 1:
 
=Method=
 
=Method=
 +
==Checking the limit==
 
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.
 
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#>
 
<syntaxhighlight lang=c#>
Line 22: Line 23:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 +
==Applying the check==
 
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
 
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
  

Latest revision as of 11:24, 18 December 2018

Method

Checking the limit

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;
        }

Applying the check

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.