public void ReadOnlyValueShouldNotExposeOriginal()
        {
            var mutable = new MutableValue<int>(10);
            var value = new ReadOnlyValue<int>(mutable);

            Object.ReferenceEquals(mutable, value.Changed).Should().BeFalse();
        }
Пример #2
0
        /// <summary>
        /// Gives money to bank (as deposit or loan payment). Checks inside.
        /// Just wouldn't take money if giver hasn't enough money.
        /// Don't provide variables like Cash as argument!! It would default to zero!
        /// </summary>
        internal void ReceiveMoney(Agent giver, ReadOnlyValue sum)
        {
            if (giver.PayWithoutRecord(this, sum))
            {
                if (giver.loans.isNotZero())              //has debt (meaning has no deposits)
                {
                    if (sum.isBiggerOrEqual(giver.loans)) // cover debt
                    {
                        Value extraMoney = sum.Copy().Subtract(giver.loans);
                        this.givenCredits.Subtract(giver.loans);

                        giver.loans.Set(0f); //put extra money on deposit
                        giver.deposits.Set(extraMoney);
                    }
                    else// not cover debt, just decrease loan
                    {
                        giver.loans.Subtract(sum);
                        this.givenCredits.Subtract(sum);
                    }
                }
                else
                {
                    giver.deposits.Add(sum);
                }
            }
        }
Пример #3
0
        public static IList <IBlock> Parse(string text)
        {
            IList <IBlock> blocks = new List <IBlock>();

            for (int index = 0; index < text.Length;)
            {
                string subText = text.Substring(index);

                using (ReadOnlyValue <int> currentIndex = ReadOnly <int> .Register(index))
                {
                    foreach (var parser in Parsers)
                    {
                        if (TryParse(text.Substring(index), parser, out IBlock block))
                        {
                            index += block.Content.Length;

                            if (0 < block.Content.Length)
                            {
                                blocks.Add(block);
                            }

                            block = BlockBase.Null;
                        }
                    }

                    if (currentIndex.Value == index)
                    {
                        break;
                    }
                }
            }

            return(blocks);
        }
Пример #4
0
        /// <summary>
        /// Result is how much deposit was really returned. Checks inside. Just wouldn't give money if can't
        /// Can return less than was prompted
        /// </summary>
        internal ReadOnlyValue ReturnDeposit(Agent toWhom, ReadOnlyValue howMuchWants)
        {
            if (toWhom.Country.Invented(Invention.Banking))// find money in bank? //todo remove checks, make bank==null if uninvented
            {
                var maxReturnLimit = HowMuchDepositCanReturn(toWhom);
                if (maxReturnLimit.isBiggerOrEqual(howMuchWants))
                {
                    ReadOnlyValue returnMoney;
                    if (howMuchWants.isBiggerThan(maxReturnLimit))
                    {
                        returnMoney = maxReturnLimit;
                    }
                    else
                    {
                        returnMoney = howMuchWants;
                    }

                    if (returnMoney.isNotZero())// return deposit
                    {
                        //giveMoney(toWhom, moneyToReturn);
                        toWhom.deposits.Subtract(returnMoney);
                        PayWithoutRecord(toWhom, returnMoney);
                    }
                    return(returnMoney);
                }
            }
            return(Value.Zero);
        }
Пример #5
0
 /// <summary>
 /// Higher procent - higher chance
 /// </summary>
 public static bool Chance(ReadOnlyValue chance)
 {
     //if (chance.isZero())
     //    return false;
     //else
     //excluding Procent.Precision
     return(Get.Next(Procent.Precision) < chance.RawUIntValue);
 }
Пример #6
0
 /// <summary>
 /// Gives credit. Checks inside. Just wouldn't give money if can't
 /// </summary>
 internal bool GiveLackingMoneyInCredit(Agent taker, ReadOnlyValue desirableSum)
 {
     if (taker.Country.Invented(Invention.Banking))// find money in bank?
     {
         Value lackOfSum = desirableSum.Copy().Subtract(taker.Cash);
         return(GiveCredit(taker, lackOfSum));
     }
     return(false);
 }
Пример #7
0
        /// <summary>
        /// Gives money in credit or returns deposit, if possible.
        /// Gives whole sum or gives nothing.
        /// Checks inside. Return false if didn't give credit.
        /// </summary>
        internal bool GiveCredit(Agent taker, ReadOnlyValue desiredCredit) // todo check
        {
            if (taker.deposits.isNotZero())                                // has deposit (meaning, has no loans)
            {
                if (desiredCredit.isBiggerThan(taker.deposits))            // loan is bigger than this deposit
                {
                    ReadOnlyValue returnedDeposit = ReturnDeposit(taker, taker.deposits);
                    if (returnedDeposit.isSmallerThan(taker.deposits))
                    {
                        return(false);// if can't return deposit than can't give credit for sure
                    }
                    //returnedMoney = new ReadOnlyValue(0f);

                    Value restOfTheSum = desiredCredit.Copy().Subtract(returnedDeposit);
                    if (CanGiveCredit(taker, restOfTheSum))
                    {
                        taker.loans.Set(restOfTheSum);//important
                        this.givenCredits.Add(restOfTheSum);
                        PayWithoutRecord(taker, restOfTheSum);
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else // no need for credit, just return deposit
                {
                    // if can't return deposit than can't give credit for sure
                    if (CanReturnDeposit(taker, desiredCredit))
                    {
                        ReturnDeposit(taker, desiredCredit);
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            else
            {
                if (CanGiveCredit(taker, desiredCredit))
                {
                    taker.loans.Add(desiredCredit);
                    this.givenCredits.Add(desiredCredit);
                    PayWithoutRecord(taker, desiredCredit);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
Пример #8
0
 internal static bool Call(Action action, ReadOnlyValue chance)
 {
     if (Chance(chance))
     {
         action();
         return(true);
     }
     else
     {
         return(false);
     }
 }
Пример #9
0
 /// <summary>
 ///checks outside
 /// </summary>
 //internal bool giveMoneyIf(Consumer taker, Value howMuch)
 //{
 //
 //        Value needLoan = howMuch.subtractOutside(taker.cash);
 //        if (this.canGiveMoney(taker, needLoan))
 //        {
 //            this.giveMoney(taker, needLoan);
 //            return true;
 //        }
 //
 //    return false;
 //}
 /// <summary>
 /// Gives credit. Checks inside. Just wouldn't give money if can't
 /// </summary>
 internal bool giveLackingMoney(Agent taker, ReadOnlyValue sum)
 {
     if (taker.GetCountry().Invented(Invention.Banking))// find money in bank?
     {
         Value lackOfSum = sum.Copy().subtract(taker.cash);
         if (canGiveMoney(taker, lackOfSum))
         {
             giveMoney(taker, lackOfSum);
             return(true);
         }
     }
     return(false);
 }
Пример #10
0
        /// <summary> Including deposits </summary>
        internal Storage HowMuchCanAfford(Storage need)
        {
            ReadOnlyValue cost = Game.market.getCost(need);

            if (CanPay(cost))
            {
                return(new Storage(need));
            }
            else
            {
                return(new Storage(need.Product, getMoneyAvailable().Divide(Game.market.getPrice(need.Product))));
            }
        }
        public void ReadOnlyValueShouldReturnValueOfOriginal()
        {
            var mutable = new MutableValue<int>(10);
            var value = new ReadOnlyValue<int>(mutable);
            var changedValues = new List<int>();
            var changedCompleted = false;

            value.Changed.Subscribe((v) => changedValues.Add(v), () => changedCompleted = true);

            value.GetValue().Should().Be(10);
            changedValues.Count.Should().Be(1);
            changedValues[0].Should().Be(10);
            changedCompleted.Should().BeFalse();
        }
Пример #12
0
 public void Add(IShareOwner owner, ReadOnlyValue value)
 {
     //if (IsCorrectData(value.))
     {
         Share record;
         if (ownership.TryGetValue(owner, out record))
         {
             record.Increase(value);
         }
         else
         {
             ownership.Add(owner, new Share(value));
         }
         totallyInvested.Add(value);
         //owner.GetOwnership().Add(parent, value);
     }
 }
Пример #13
0
        public void getMoneyForSoldProduct()
        {
            foreach (var sent in sentToMarket)
            {
                if (sent.isNotZero())
                {
                    Value DSB = new Value(Game.market.getDemandSupplyBalance(sent.Product));
                    if (DSB.get() == Options.MarketInfiniteDSB)
                    {
                        DSB.SetZero();// real DSB is unknown
                    }
                    else
                    if (DSB.get() > Options.MarketEqualityDSB)
                    {
                        DSB.Set(Options.MarketEqualityDSB);
                    }
                    Storage realSold = new Storage(sent);
                    realSold.Multiply(DSB);
                    if (realSold.isNotZero())
                    {
                        ReadOnlyValue cost = Game.market.getCost(realSold);
                        //soldByGovernment.addMy(realSold.Product, realSold);
                        soldByGovernment[realSold.Product].Set(realSold);
                        //returning back unsold product
                        //if (sent.isBiggerThan(realSold))
                        //{
                        //    var unSold = sent.subtractOutside(realSold);
                        //    countryStorageSet.add(unSold);
                        //}


                        if (Game.market.CanPay(cost)) //&& Game.market.tmpMarketStorage.has(realSold))
                        {
                            Game.market.Pay(this, cost);
                            //Game.market.sentToMarket.subtract(realSold);
                        }
                        else if (Game.market.HowMuchLacksMoneyIncludingDeposits(cost).get() > 10f && Game.devMode)
                        {
                            Debug.Log("Failed market - can't pay " + Game.market.HowMuchLacksMoneyIncludingDeposits(cost)
                                      + " for " + realSold); // money in market ended... Only first lucky get money
                        }
                    }
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Checks inside. Wouldn't pay if can't. Takes back deposit from bank if needed
        /// Registers moneyIncomeThisTurn, pays tax. Returns true if was able to pay
        /// </summary>
        public bool Pay(Agent incomeReceiver, ReadOnlyValue howMuch, bool showMessageAboutNegativeValue = true)
        {
            if (howMuch.isNotZero())
            {
                if (PayWithoutRecord(incomeReceiver, howMuch, showMessageAboutNegativeValue))
                {
                    // income tax calculation
                    Value howMuchPayReally = howMuch.Copy();
                    incomeReceiver.moneyIncomeThisTurn.Add(howMuchPayReally);
                    if (incomeReceiver is Market) // Market wouldn't pay taxes cause it's abstract entity
                    {
                        return(true);
                    }
                    Agent payer = this;

                    if (payer is Market == false && //&& incomeReceiver is Market == false
                        payer.country != incomeReceiver.country &&
                        payer is Factory)    // pay taxes in enterprise jurisdiction only if it's factory
                    {
                        var payed = payer.country.TakeIncomeTaxFrom(incomeReceiver, howMuchPayReally, false);
                        howMuchPayReally.Subtract(payed);//and reduce taxable base
                    }

                    // in rest cases only pops pay taxes
                    var popReceiver = incomeReceiver as PopUnit;
                    if (popReceiver != null)
                    {
                        incomeReceiver.country.TakeIncomeTaxFrom(popReceiver, howMuchPayReally, popReceiver.Type.isPoorStrata());
                    }
                    //else // if it's not Pop than it should by dividends from enterprise..
                    //{
                    //    //var countryPayer = incomeReceiver as Country;
                    //    //if (countryPayer != null)
                    //        incomeReceiver.Country.TakeIncomeTaxFrom(incomeReceiver, howMuchPayReally, false);
                    //}
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }
Пример #15
0
        //todo put it and duplicate in market?
        public void getMoneyForSoldProduct()
        {
            if (sentToMarket.get() > 0f)
            {
                Value DSB = new Value(Game.market.getDemandSupplyBalance(sentToMarket.Product));
                if (DSB.get() == Options.MarketInfiniteDSB)
                {
                    DSB.SetZero(); // real DSB is unknown
                }
                else
                if (DSB.get() > Options.MarketEqualityDSB)
                {
                    DSB.Set(Options.MarketEqualityDSB);
                }
                Storage realSold = new Storage(sentToMarket);
                realSold.Multiply(DSB);
                if (realSold.isNotZero())
                {
                    ReadOnlyValue cost = Game.market.getCost(realSold);

                    // adding unsold product
                    // assuming gainGoodsThisTurn & realSold have same product
                    if (storage.isExactlySameProduct(gainGoodsThisTurn))
                    {
                        storage.add(gainGoodsThisTurn);
                    }
                    else
                    {
                        storage = new Storage(gainGoodsThisTurn);
                    }
                    storage.Subtract(realSold.get());

                    if (Game.market.CanPay(cost)) //&& Game.market.tmpMarketStorage.has(realSold))
                    {
                        Game.market.Pay(this, cost);
                    }
                    else if (Game.market.HowMuchLacksMoneyCashOnly(cost).get() > 10f && Game.devMode)
                    {
                        Debug.Log("Failed market - can't pay " + Game.market.HowMuchLacksMoneyCashOnly(cost)
                                  + " for " + realSold); // money in market ended... Only first lucky get money
                    }
                }
            }
        }
Пример #16
0
    protected override void OnUpdate()
    {
        var t = new ReadOnlyValue <ComponentDataFromEntity <SnakeBodyData> >();

        t.Value = GetComponentDataFromEntity <SnakeBodyData>(true);
        var deltaTime           = UnityEngine.Time.deltaTime;
        var entityCommandBuffer = m_commandBufferSystem.CreateCommandBuffer();
        var mapInfoData         = GetSingleton <MapInfoData>();

        Entities.WithAll <SnkaeHeadTag>().ForEach((Entity entity, ref TimerData timer, in DirData dirData) =>
        {
            timer.currnetTime += deltaTime;
            if (timer.currnetTime < timer.targetTime)
            {
                return;
            }
            timer.currnetTime = 0;
            Entity curEntity  = entity;
            var bodyData      = t.Value[curEntity];
            int2 lastpos      = bodyData.pos;
            bodyData.lastpos  = bodyData.pos;
            int2 curpos       = bodyData.pos + dirData.dir;
            curpos.x          = (curpos.x + mapInfoData.width) % mapInfoData.width;
            curpos.y          = (curpos.y + mapInfoData.height) % mapInfoData.height;
            bodyData.pos      = curpos;
            entityCommandBuffer.SetComponent(curEntity, bodyData);
            curEntity = bodyData.nextEntity;
            while (curEntity != Entity.Null)
            {
                bodyData         = t.Value[curEntity];
                bodyData.lastpos = bodyData.pos;
                curpos           = bodyData.pos;
                bodyData.pos     = lastpos;
                entityCommandBuffer.SetComponent(curEntity, bodyData);
                lastpos   = curpos;
                curEntity = bodyData.nextEntity;
            }
        }).Schedule();
        m_commandBufferSystem.AddJobHandleForProducer(this.Dependency);
    }
Пример #17
0
        /// <summary>
        /// For artisans. Not including salary
        /// </summary>
        internal ReadOnlyValue getPossibleProfit()
        {
            if (Game.market.getDemandSupplyBalance(basicProduction.Product) == Options.MarketZeroDSB)
            {
                return(new Value(0)); // no demand for result product
            }
            ReadOnlyValue income = Game.market.getCost(basicProduction);

            if (hasInput())
            {
                // change to minimal hire limits
                foreach (Storage inputProduct in resourceInput)
                {
                    if (!Game.market.isAvailable(inputProduct.Product))
                    {
                        return(new Value(0));// inputs are unavailable
                    }
                }
                return(income.Copy().Subtract(Game.market.getCost(resourceInput), false));
            }
            return(income);
        }
Пример #18
0
        /// <summary>
        /// Don't call it directly
        /// </summary>

        public Factory(Province province, IShareOwner investor, ProductionType type, ReadOnlyValue cost)
            : base(type, province)
        {
            //this.buildByPlannedEconomy = buildByPlannedEconomy;
            ownership = new Owners(this);
            if (investor != null) // that mean that factory is a fake
            {
                currentInvestor = investor;
                //assuming this is level 0 building
                constructionNeeds = new StorageSet(Type.GetBuildNeeds());

                ownership.Add(investor, cost);

                salary.set(province.getLocalMinSalary());
                if (Country.economy.getValue() == Economy.PlannedEconomy)
                {
                    setPriorityAutoWithPlannedEconomy();
                }
                //else
                //    Debug.Log(investor + " invested " + cost + " in building new " + this);
            }
        }
Пример #19
0
 /// <summary>
 /// checks inside. Wouldn't pay if can't. Takes credits from bank
 /// Doesn't pay tax, doesn't register transaction
 /// </summary>
 public bool payWithoutRecord(Agent whom, ReadOnlyValue howMuch, bool showMessageAboutNegativeValue = true)
 {
     if (canPay(howMuch))
     {
         if (!canPayCashOnly(howMuch) && bank != null)// checked for bank inv
         {
             bank.giveLackingMoney(this, howMuch);
             bank.giveLackingMoney(this, howMuch.Copy().multiply(5));
         }
         whom.cash.Add(howMuch); // rise warning if have enough money to pay (with deposits) but didn't get enough from bank
         this.cash.subtract(howMuch);
         return(true);
     }
     else
     {
         if (showMessageAboutNegativeValue)
         {
             Debug.Log("Not enough money to pay in Agent.payWithoutRecord");
         }
         return(false);
     }
 }
Пример #20
0
        /// <summary>
        /// For 1 level / 1000 workers. Not includes tax. Includes modifiers. New value
        /// </summary>
        internal Value getPossibleProfit(Province province)
        {
            if (Game.market.getDemandSupplyBalance(basicProduction.Product) == Options.MarketZeroDSB)
            {
                return(new Value(0)); // no demand for result product
            }
            ReadOnlyValue income = Game.market.getCost(basicProduction);

            income.Copy().Multiply(Factory.modifierEfficiency.getModifier(new Factory(province, null, this, null)), false);
            var outCome = new Value(0f);// = province.getLocalMinSalary();//salary

            if (hasInput())
            {
                foreach (Storage inputProduct in resourceInput)
                {
                    if (!Game.market.isAvailable(inputProduct.Product))
                    {
                        return(new Value(0));// inputs are unavailable
                    }
                }
                outCome.Add(Game.market.getCost(resourceInput));
            }
            return(income.Copy().Subtract(outCome, false));
        }
Пример #21
0
 /// <summary>
 /// Checks inside. Wouldn't pay if can't. Takes back deposits from bank, if needed
 /// Doesn't pay tax, doesn't register transaction
 /// </summary>
 public bool PayWithoutRecord(Money whom, ReadOnlyValue howMuch, bool showMessageAboutNegativeValue = true)
 {
     if (CanPay(howMuch))// It does has enough cash or deposit
     {
         if (CanPayCashOnly(howMuch))
         {
             whom.Add(howMuch);
             this.cash.Subtract(howMuch);
         }
         else
         {
             Bank.ReturnDeposit(this, HowMuchLacksMoneyCashOnly(howMuch));
         }
         return(true);
     }
     else
     {
         if (showMessageAboutNegativeValue)
         {
             Debug.Log("Not enough money to pay in Agent.payWithoutRecord");
         }
         return(false);
     }
 }
Пример #22
0
 public void Decrease(ReadOnlyValue sum)
 {
     howMuchOwns.Subtract(sum);
 }
Пример #23
0
 public Share(ReadOnlyValue initialSumm)
 {
     howMuchOwns = initialSumm.Copy();
 }
Пример #24
0
 public void Increase(ReadOnlyValue sum)
 {
     howMuchOwns.Add(sum);
 }
Пример #25
0
 internal bool CanPayCashOnly(ReadOnlyValue howMuchPay)
 {
     return(cash.isBiggerOrEqual(howMuchPay));
 }
Пример #26
0
        //internal Value HowMuchMoneyCanNotPay(Value value)
        //{
        //    return new Value(value.get() - this.cash.get());
        //}
        /// <summary>WARNING! Can overflow if money > cost of need. use CanAfford before </summary>
        //internal Value HowMuchCanNotAfford(Storage need)
        //{
        //    return new Value(Game.market.getCost(need) - this.cash.get());
        //}


        //private float get()
        //{
        //    throw new NotImplementedException();
        //}

        //internal bool canPay(Value howMuchPay)
        //{
        //    if (this.cash.get() >= howMuchPay.get())
        //        return true;
        //    else return false;
        //}
        //internal bool canPay(float howMuchPay)
        //{
        //    if (this.cash.get() >= howMuchPay)
        //        return true;
        //    else
        //        return false;
        //}
        /// <summary> Counting deposit and cash </summary>
        internal bool CanPay(ReadOnlyValue howMuchPay)
        {
            return(getMoneyAvailable().isBiggerOrEqual(howMuchPay));
        }
Пример #27
0
 /// <summary>
 /// Says how much money lack of desiredSum (counting cash only). New value
 /// Says zero if cash >= desiredSum, no need for extra money
 /// </summary>
 internal Value HowMuchLacksMoneyCashOnly(ReadOnlyValue desiredSum)
 {
     return(desiredSum.Copy().Subtract(cash, false));
 }
Пример #28
0
        /// <summary>WARNING! Can overflow if money > cost of need. use CanAfford before </summary>
        //internal Value HowMuchCanNotAfford(PrimitiveStorageSet need)
        //{
        //    return new Value(Game.market.getCost(need).get() - this.cash.get());
        //}
        /// <summary>WARNING! Can overflow if money > cost of need. use CanAfford before </summary>
        //internal Value HowMuchCanNotAfford(float need)
        //{
        //    return new Value(need - this.cash.get());
        //}

        /// <summary> Says how much money lack of desiredSum (counting cash and deposits in bank). New value.
        /// Goes nut if cash + deposits >= desiredSum, no need for extra money, check that outside
        /// </summary>
        internal Value HowMuchLacksMoneyIncludingDeposits(ReadOnlyValue desiredSum)
        {
            return(desiredSum.Copy().Subtract(getMoneyAvailable(), false));
        }
Пример #29
0
 internal void CancelBuyOrder(ReadOnlyValue sum)
 {
     howMuchWantsToSell.Subtract(sum, false);
 }
Пример #30
0
 public Education(ReadOnlyValue numerator, ReadOnlyValue denominator, bool showMessageAboutOperationFails = true) : base(numerator, denominator, showMessageAboutOperationFails)
 {
 }