Example #1
0
    public override void StartFn()
    {
        Messenger.Fire(SpawnController.MESSAGE_SET_BALLOONS_PER_SECOND, new object[] { 0f });

        //Collect all of the data
        NumbersText.text = string.Format(
            "{0}\n{1}\n{2}",
            GameData.BalloonsPopped.ToString("N0"),
            GameData.ShotsFired.ToString("N0"),
            GameData.ExplosiveBalloonsPopped.ToString("N0"));

        EventChain = EventChain.Begin(new List <EventLink> {
            new CallFunctionLink(delegate(object[] args) {
                Messenger.Fire(SpawnController.MESSAGE_REMOVE_BALLOONS);
                AudioManager.StopMusic();
            }),
            new WaitLink(2f),
            new CallFunctionLink(delegate(object[] args) {
                AudioManager.PlaySound("Yay", 1, 1.5f);
                EndScreenUIGroup.SetVisible(true);
            }),
            new WaitLink(2.5f),
            new CallFunctionLink(delegate(object[] args) {
                AudioManager.PlayMusic("MenuMusic", true, false, 0.5f);
            })
        });
    }
Example #2
0
        /// <summary>
        /// Opens an outlet at a given position on a settlement (or a random one).
        /// </summary>
        public void OpenOutlet(Vector2 position = null)
        {
            //Need to generate a random position?
            if (position == null)
            {
                position = settlement.GetFreeRandomPosition();
            }
            else
            {
                //Check if the position is occupied.
                if (settlement.IsOccupied(position))
                {
                    throw new Exception("Cannot open an outlet there, the space is occupied.");
                }
            }

            //Sufficient balance?
            if (Balance < OutletCost)
            {
                throw new Exception("Cannot open an outlet, insufficient company balance.");
            }

            //Open the outlet.
            Balance -= Math.Round(OutletCost, 2);
            outlets.Add(new Outlet(settlement, this, position, OutletCapacity, DailyCost));

            //Log in the event chain.
            EventChain.AddEvent(new OutletCreateEvent()
            {
                Position = position,
                Capacity = OutletCapacity
            });
        }
        public void AcceptingEvents_GivenAggregateWithUncommittedEvents_ShouldClearUncommittedEvents()
        {
            // Arrange
            var user = new User();

            user.Register();
            user.ChangePassword("newpassword");

            // Act
            IEnumerable <IEvent> expectedBefore = new EventChain {
                new UserRegistered(user.Id), new UserChangedPassword("newpassword")
            };
            IEnumerable <IEvent> expectedAfter = new IEvent[0];

            IEnumerable <IEvent> before = user.GetUncommittedEvents();

            user.AcceptUncommittedEvents();
            IEnumerable <IEvent> after = user.GetUncommittedEvents();

            // Assert
            var result = _comparer.AreEqual(expectedBefore, before);

            if (!result.AreEqual)
            {
                throw new AssertionException(string.Format("Actual events did not match expected events. {0}", result.InequalityReason));
            }
            _comparer.AreEqual(expectedAfter, after);
        }
Example #4
0
        bool Run(DoScriptEvent doScriptEvent, Action continuation)
        {
            var assets     = Resolve <IAssetManager>();
            var mapManager = Resolve <IMapManager>();

            var events = assets.LoadScript(doScriptEvent.ScriptId);
            var nodes  = new EventNode[events.Count];
            var chain  = new EventChain(0);

            // Create, link and add all the nodes.
            for (ushort i = 0; i < events.Count; i++)
            {
                nodes[i] = new EventNode(i, events[i]);
            }
            for (ushort i = 0; i < events.Count - 1; i++)
            {
                nodes[i].Next = nodes[i + 1];
            }
            for (ushort i = 0; i < events.Count; i++)
            {
                chain.Events.Add(nodes[i]);
            }

            var source  = new EventSource.Map(mapManager.Current.MapId, TriggerType.Default, 0, 0); // TODO: Is there a better trigger type for this?
            var trigger = new TriggerChainEvent(chain, chain.FirstEvent, source);

            return(RaiseAsync(trigger, continuation) > 0);
        }
    public override void Trigger(EventChain parent, Action finishedCallback)
    {
        Messenger.Fire(Message, Args);

        if (finishedCallback != null) {
            finishedCallback();
        }
    }
Example #6
0
 public void AddToChain(EventChainLink link)
 {
     EventChain.Add(link);
     if (HandledBy == null && link.Handled)
     {
         HandledBy = link;
     }
 }
    public static EventChain GetInstance()
    {
        if (Instance == null) {
            Instance = new GameObject("EventChain").AddComponent<EventChain>();
        }

        return Instance;
    }
    public override void Trigger(EventChain parent, Action finishedCallback)
    {
        Messenger.Fire(Message, Args);

        if (finishedCallback != null)
        {
            finishedCallback();
        }
    }
Example #9
0
        private void EventChain_CreateItem(EventChain evChain)
        {
            var lvItem = new ListViewItem();

            lvItem.Text = evChain.Name;
            lvItem.Tag  = evChain;

            listViewEventChains.Items.Add(lvItem);
        }
 public override void Trigger(EventChain parent, Action finishedCallback)
 {
     if (CallFunction != null) {
         CallFunction(Args);
     }
     if (finishedCallback != null) {
         finishedCallback();
     }
 }
Example #11
0
    public static EventChain GetInstance()
    {
        if (Instance == null)
        {
            Instance = new GameObject("EventChain").AddComponent <EventChain>();
        }

        return(Instance);
    }
 public override void Trigger(EventChain parent, Action finishedCallback)
 {
     if (CallFunction != null)
     {
         CallFunction(Args);
     }
     if (finishedCallback != null)
     {
         finishedCallback();
     }
 }
Example #13
0
        /// <summary>
        /// Visit the outlet (increments visits for today).
        /// </summary>
        public void Visit(Vector2 origin)
        {
            visitsToday++;

            //Log event.
            EventChain.AddEvent(new VisitOutletEvent()
            {
                Company   = ParentCompany.Name,
                Household = origin,
                OutletPos = Position
            });
        }
Example #14
0
        private void Event_CreateItem(EventChain evChain)
        {
            listViewEvents.Clear();

            foreach (var ev in evChain.Events)
            {
                var lvItem = new ListViewItem();

                lvItem.Text = ev.ToString();
                lvItem.Tag  = ev;

                listViewEvents.Items.Add(lvItem);
            }
        }
Example #15
0
        /// <summary>
        /// Processes the end of the day for this company.
        /// </summary>
        public void ProcessDayEnd()
        {
            //Set up locals.
            double deliveryCosts = 0, profitLossFromOutlets = 0;

            //Move all the food trucks first.
            foreach (var outlet in outlets)
            {
                if (outlet is FoodTruck)
                {
                    //Move it.
                    ((FoodTruck)outlet).Move();
                }
            }

            //Calculate delivery costs.
            deliveryCosts += BaseDeliveryCost + CalculateDeliveryCost();
            Balance       -= Math.Round(deliveryCosts, 2);
            EventChain.AddEvent(new DeliveryEvent()
            {
                CompanyName = Name,
                Cost        = Math.Round(deliveryCosts, 2),
                Type        = EventType.Delivery
            });

            //Calculate outlet profit and loss.
            foreach (var outlet in outlets)
            {
                double thisOutletProfit = outlet.GetDailyProfit(avgCostPerMeal, avgPricePerMeal);
                profitLossFromOutlets += thisOutletProfit;

                //Log an outlet's profits/losses.
                EventChain.AddEvent(new OutletProfitEvent()
                {
                    ProfitLoss = Math.Round(thisOutletProfit, 2),
                    Company    = Name
                });

                outlet.ProcessDayEnd();
            }

            //Update balance.
            Balance += Math.Round(profitLossFromOutlets, 2);

            //Close the company?
            if (Balance <= 0)
            {
                CloseAllOutlets();
            }
        }
        public void GivenAggregateWithMultipleEvents_WhenLoadingMaxVersion_ThenShouldReturnAllEvents()
        {
            // Arrange
            IEventStore store        = new SqlServerEventStoreTestDataBuilder().Build();
            var         customerId   = Guid.NewGuid();
            var         storedEvents = new EventChain().Add(new CustomerSignedUp(customerId))
                                       .Add(new SubscribedToNewsletter("latest"))
                                       .Add(new SubscribedToNewsletter("top"));

            store.Save <Customer>(customerId.ToString(), EventStreamVersion.NoStream, storedEvents);

            // Act
            var stream = store.Load <Customer>(customerId.ToString(), EventStreamVersion.Max);

            // Assert
            CollectionAssert.AreEqual(storedEvents, stream.Events, "Events loaded from store do not match version requested.");
        }
        public void GivenAggregateWithMultipleEvents_WhenLoadingSpecialNoStreamVersion_ThenShouldFail()
        {
            // Arrange
            IEventStore store        = new EventStoreEventStore(_eventStoreConnection, new ConsoleLogger());
            var         customerId   = Guid.NewGuid();
            var         storedEvents = new EventChain
            {
                new CustomerSignedUp(customerId),
                new SubscribedToNewsletter("latest"),
                new SubscribedToNewsletter("top")
            };

            store.Save <Customer>(customerId.ToString(), EntityVersion.New, storedEvents);

            // Act / Assert
            Assert.Throws <ArgumentOutOfRangeException>(() => store.Load <Customer>(customerId.ToString(), EntityVersion.New));
        }
        public void GivenAggregateWithMultipleEvents_WhenLoadingSpecificVersion_ThenShouldOnlyReturnRequestedEvents()
        {
            // Arrange
            IEventStore store        = new DelayedWriteRavenEventStore(_documentStore);
            var         customerId   = Guid.NewGuid();
            var         storedEvents = new EventChain().Add(new CustomerSignedUp(customerId))
                                       .Add(new SubscribedToNewsletter("latest"))
                                       .Add(new SubscribedToNewsletter("top"));

            store.Save <Customer>(customerId.ToString(), 0, storedEvents);

            // Act
            var stream = store.Load <Customer>(customerId.ToString(), storedEvents[1].Version);

            // Assert
            CollectionAssert.AreEqual(storedEvents.Take(2), stream.Events, "Events loaded from store do not match version requested.");
        }
Example #19
0
        /// <summary>
        /// Adds a random number of households (default 1-5) to the settlement.
        /// </summary>
        private void ProcessAddHouseholdsEvent()
        {
            int newHouseholds = Random.Next(Settings.Get.MinNewHouseholds, Settings.Get.MaxNewHouseholds);
            int stored        = newHouseholds;

            while (newHouseholds > 0)
            {
                Settlement.AddHousehold();
                newHouseholds--;
            }

            //Log to the event chain.
            EventChain.AddEvent(new AddHouseholdsEvent()
            {
                NumHouses = stored
            });
        }
        public void GivenAggregateWithMultipleEvents_WhenLoadingSpecificVersion_ThenShouldOnlyReturnRequestedEvents(int version)
        {
            // Arrange
            IEventStore store        = new EventStoreEventStore(_eventStoreSession, new ConsoleLogger());
            var         customerId   = Guid.NewGuid();
            var         storedEvents = new EventChain().Add(new CustomerSignedUp(customerId))
                                       .Add(new SubscribedToNewsletter("latest"))
                                       .Add(new SubscribedToNewsletter("top"));

            store.Save <Customer>(customerId.ToString(), EventStreamVersion.NoStream, storedEvents);
            _eventStoreSession.Commit();

            // Act
            var stream = store.Load <Customer>(customerId.ToString(), version);

            // Assert
            CollectionAssert.AreEqual(storedEvents.Take(version + 1), stream.Events, "Events loaded from store do not match version requested.");
        }
        public void GivenAggregateWithMultipleEvents_WhenLoadingMaxVersion_ThenShouldReturnAllEvents()
        {
            // Arrange
            var store        = new EventStoreEventStore(_eventStoreConnection, new ConsoleLogger());
            var customerId   = Guid.NewGuid();
            var storedEvents = new EventChain().Add(new CustomerSignedUp(customerId))
                               .Add(new SubscribedToNewsletter("latest"))
                               .Add(new SubscribedToNewsletter("top"));

            store.Save <Customer>(customerId.ToString(), EntityVersion.New, storedEvents);
            store.Flush();

            // Act
            var stream = store.Load <Customer>(customerId.ToString(), EntityVersion.Latest);

            // Assert
            CollectionAssert.AreEqual(storedEvents, stream.Events, "Events loaded from store do not match version requested.");
        }
Example #22
0
        public void GivenEventStorePopulatedWithManyEventsForAnAggregate_WhenLoadingForSpecificVersion_ThenShouldOnlyLoadEventsUpToAndIncludingThatVersion()
        {
            // Arrange
            IEventStore store     = new InMemoryEventStore(new ConsoleLogger());
            var         id        = Guid.NewGuid();
            var         allEvents = new EventChain().Add(new UserRegistered(id))
                                    .Add(new UserChangedPassword("pwd1"))
                                    .Add(new UserChangedPassword("pwd2"))
                                    .Add(new UserChangedPassword("pwd3"))
                                    .Add(new UserChangedPassword("pwd4"));

            store.Save <User>(id.ToString(), 0, allEvents);

            // Act
            IEnumerable <IEvent> version3 = store.Load <User>(id.ToString(), allEvents[2].Version).Events;

            // Assert
            CollectionAssert.AreEqual(allEvents.Take(3).ToArray(), version3);
        }
Example #23
0
        /// <summary>
        /// Moves one square in a random direction.
        /// </summary>
        public void Move()
        {
            //Calculate a random direction.
            int x    = base.Position.x;
            int y    = base.Position.y;
            int rand = Simulation.Random.Next(0, 3);

            switch (rand)
            {
            case 0: x--; break;

            case 1: x++; break;

            case 2: y--; break;

            case 3: y++; break;
            }

            //Clamp inside the settlement.
            x.Clamp(0, base.settlement.Width - 1);
            y.Clamp(0, base.settlement.Height - 1);

            //Is the position occupied? Don't move.
            if (settlement.IsOccupied(new Vector2(x, y)))
            {
                return;
            }

            //Set position, update on settlement too.
            Vector2 old = Position;

            Position = new Vector2(x, y);
            settlement.Unoccupy(old);
            settlement.Occupy(Position);

            //Log the event.
            EventChain.AddEvent(new FoodTruckMoveEvent()
            {
                From    = old,
                To      = Position,
                Company = base.ParentCompany.Name
            });
        }
Example #24
0
        public string FormatChain(EventChain chain)
        {
            if (chain == null)
            {
                return(null);
            }
            var sb = new StringBuilder();

            var uniqueEvents = new HashSet <IEventNode>();

            void Visit(IEventNode e)
            {
                while (true)
                {
                    if (e == null)
                    {
                        return;
                    }

                    if (!uniqueEvents.Add(e))
                    {
                        break;
                    }

                    if (e is IBranchNode branch)
                    {
                        Visit(branch.NextIfFalse);
                    }
                    e = e.Next;
                }
            }

            Visit(chain.FirstEvent);
            var sorted = uniqueEvents.OrderBy(x => x.Id).ToList();

            foreach (var e in sorted)
            {
                sb.AppendLine(Format(e, sorted[0].Id));
            }

            return(sb.ToString());
        }
        public void Disposing_a_delayedwriteeventstore_with_pending_changes_should_throw_exception()
        {
            Assert.Throws <InvalidOperationException>(
                () =>
            {
                using (var eventStore = new RavenEventStore(_documentStore))
                {
                    var customerId = Guid.NewGuid();

                    var storedEvents = new EventChain
                    {
                        new CustomerSignedUp(customerId),
                        new SubscribedToNewsletter("latest"),
                        new SubscribedToNewsletter("top")
                    };

                    eventStore.Save <Customer>(customerId.ToString(), 0, storedEvents);
                }
            });
        }
Example #26
0
        /// <summary>
        /// Process all of the leavers from the settlement.
        /// </summary>
        public void ProcessLeavers()
        {
            int removed = 0;

            for (int i = 0; i < Households.Count; i++)
            {
                //2% chance for a household to leave by default.
                if (Simulation.Random.NextDouble() < Settings.Get.ChanceOfHouseholdLeaving)
                {
                    Households.RemoveAt(i);
                    i--;
                    removed++;
                }
            }

            //Log to event chain.
            EventChain.AddEvent(new HouseholdLeavingEvent()
            {
                NumHouseholds = removed
            });
        }
Example #27
0
        /// <summary>
        /// Changes the price of fuel randomly.
        /// </summary>
        protected virtual void ProcessChangeFuelCostEvent()
        {
            //Check if fuel price increases or decreases, get by how much.
            bool   increases = (Random.NextDouble() < Settings.Get.ChanceOfFuelPriceIncrease);
            double amt       = Random.Next(1, 10) / 10.0;

            //Which company is it for?
            int companyIndex = Random.Next(0, Companies.Count - 1);

            //Complete the change, log.
            if (!increases)
            {
                amt = -amt;
            }
            Companies[companyIndex].ChangeFuelCostBy(amt);

            EventChain.AddEvent(new FuelCostChangeEvent()
            {
                AmountBy = amt,
                Company  = Companies[companyIndex].Name,
            });
        }
Example #28
0
        public void GivenPopulatedEventStore_WhenLoadingSpecificVersionOfAggregate_ThenRepositoryShouldRebuildThatAggregateToThatVersion()
        {
            // Arrange
            var eventStore = new InMemoryEventStore(new ConsoleLogger());
            var userId     = Guid.NewGuid();
            var events     = new EventChain
            {
                new UserRegistered(userId),
                new UserChangedPassword("newpassword"),
                new UserChangedPassword("newnewpassword")
            };

            eventStore.Save <User>(EventStreamIdFormatter.GetStreamId <User>(userId.ToString()), 0, events);

            var repository = new EventSourcingRepository <User>(eventStore, new Mock <IConcurrencyMonitor>().Object, _logger);

            // Act
            User user = repository.Get(userId, events[1].Version);

            // Assert
            Assert.AreEqual(events[1].Version, user.BaseVersion);
        }
Example #29
0
        /// <summary>
        /// Updates the event list from the events chain, from the "currentDaysAgo" property.
        /// </summary>
        private void UpdateEventList()
        {
            events = EventChain.GetChain(currentDaysAgo);
            eventsList.Clear();
            eventDayLabel.Text = "Viewing events from " + currentDaysAgo + " days ago.";

            //Did any events return?
            if (events == null)
            {
                if (currentDaysAgo == 0)
                {
                    return;
                }
                currentDaysAgo--; UpdateEventList();
                return;
            }

            foreach (var e in events)
            {
                eventsList.Items.Add(e.Stringify());
            }
        }
Example #30
0
        /// <summary>
        /// Changes a random cost for a single company by a random amount.
        /// </summary>
        private void ProcessCostChangeEvent()
        {
            //How much to change by, should it go up or down, and which company should it be applied to?
            bool   increases = (Random.NextDouble() < Settings.Get.ChanceOfCostIncrease);
            double amt       = Random.NextDouble() * 10.0;

            if (!increases)
            {
                amt = -amt;
            }
            int companyIndex = Random.Next(0, Companies.Count - 1);

            //Figured it out, determine which cost to increase/decrease.
            int    costType = Random.Next(0, 1);
            string costTypeStr;

            if (costType == 0)
            {
                //Change the daily cost for the company.
                costTypeStr = "daily cost";
                amt        *= 2;
                Companies[companyIndex].ChangeDailyCostBy(amt);
            }
            else
            {
                //Change the average meal costs for a company.
                costTypeStr = "average meal cost";
                Companies[companyIndex].ChangeAvgMealCostBy(amt);
            }

            //Log as an event.
            EventChain.AddEvent(new CostChangeEvent()
            {
                AmountBy = amt,
                Company  = Companies[companyIndex].Name,
                CostType = costTypeStr
            });
        }
Example #31
0
        /// <summary>
        /// Changes a single company's reputation randomly.
        /// </summary>
        private void ProcessChangeReputationEvent()
        {
            //Calculate the amount, and whether it's increasing or decreasing.
            bool   increases = (Random.NextDouble() < Settings.Get.ChanceOfReputationIncrease);
            double amt       = Random.Next(1, 10) / 10.0;

            if (!increases)
            {
                amt = -amt;
            }

            //Which company is this for?
            int companyIndex = Random.Next(0, Companies.Count - 1);

            //Apply and log.
            Companies[companyIndex].ChangeReputationBy(amt);

            EventChain.AddEvent(new ReputationChangeEvent()
            {
                Company  = Companies[companyIndex].Name,
                AmountBy = amt
            });
        }
Example #32
0
 private static void UpdateMouseButtonState(ButtonState bState, ButtonState bStateOld
     , EventChain<MouseEventChainArgs> pressed
     , EventChain<MouseEventChainArgs> hold
     , EventChain<MouseEventChainArgs> released)
 {
     // button state is now pressed
     if (bState == ButtonState.Pressed)
     {
         // button state was hold
         if (bStateOld == ButtonState.Pressed)
         {
             hold.Invoke(new MouseEventChainArgs(_mState, _mStateOld));
         }
         else // button state was just pressed
         {
             pressed.Invoke(new MouseEventChainArgs(_mState, _mStateOld));
         }
     }
     // button state is now released
     else if (bStateOld == ButtonState.Pressed)
     {
         released.Invoke(new MouseEventChainArgs(_mState, _mStateOld));
     }
 }
        public void InvokingBehaviour_GivenSimpleAggregateRootThatInheritsAnother_ShouldRecordEvents()
        {
            // Arrange
            var user = new SuperUser();

            user.Register();

            // Act
            user.ChangePassword("newpassword");
            IEnumerable <IEvent> actual = user.GetUncommittedEvents();

            var expected = new EventChain
            {
                new UserRegistered(user.Id),
                new UserChangedPassword("newpassword")
            };

            ObjectComparisonResult result = _comparer.AreEqual(expected, actual);

            if (!result.AreEqual)
            {
                throw new AssertionException(string.Format("Actual events did not match expected events. {0}", result.InequalityReason));
            }
        }
 public override void Trigger(EventChain parent, System.Action finishedCallback)
 {
     parent.StartCoroutine(Fade(finishedCallback));
 }
Example #35
0
 public TriggerChainEvent(EventChain chain, IEventNode node, EventSource source)
 {
     Chain  = chain ?? throw new ArgumentNullException(nameof(chain));
     Node   = node ?? throw new ArgumentNullException(nameof(node));
     Source = source ?? throw new ArgumentNullException(nameof(source));
 }
 public virtual void Trigger(EventChain parent, Action finishedCallback)
 {
 }
Example #37
0
 public override void Trigger(EventChain parent, Action finishedCallback)
 {
     parent.StartCoroutine(Wait(finishedCallback));
 }