Example #1
0
        /// <summary>
        /// Run through all purchasing that takes place.
        /// </summary>
        public void BuyPhase()
        {
            // go through each pop in order of priority
            foreach (var buyer in Populous.PopsByPriority)
            {
                // go through their list of needs
                foreach (var needPair in buyer.TotalNeeds)
                {
                    // Check that there is stuff that the pop
                    // can trade for goods
                    if (buyer.ForSale.All(x => x.Item2 <= 0))
                    {
                        break; // if they don't they stop
                    }
                    // get the product and amount
                    var need    = needPair.Item1;
                    var desired = needPair.Item2; // the units desired

                    try
                    {
                        // Check if the product is available to buy
                        if (ProductSupply.GetProductValue(need) <= 0)
                        {
                            // if nothing is available, add it to the shortfall.
                            Shortfall.AddProducts(need, desired);
                            continue; // and go to the next need
                        }
                    }
                    catch (KeyNotFoundException) // If it doesn't exist in the supply at all.
                    {
                        // Add it in at 0
                        ProductSupply.IncludeProduct(need);
                        // Subtract the missing product from shortfall.
                        Shortfall.AddProducts(need, desired);
                        continue; // and skip it here.
                    }

                    // Go to the market and buy what we can.
                    var reciept = BuyGoodsFromMarket(buyer, need, desired);

                    // process our reciept, getting how satisfied our need was.
                    var satisfaction = reciept.GetProductValue(need);

                    // Add satisfaction to our purchased good recorder
                    _purchasedGoods.AddProducts(need, satisfaction);

                    // Remove bought good from supply
                    ProductSupply.SubtractProducts(need, satisfaction);

                    // get the number of goods that couldn't be bought.
                    var shortfall = desired - satisfaction;

                    // add that to shortfall
                    Shortfall.AddProducts(need, shortfall);
                }
            }

            // with all buying done, get surplus supply available by removing bought goods.
            _surplus.AddProducts(PurchasedGoods.Multiply(-1));
        }