예제 #1
0
        public void LINQSingle()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            for (int i = 0; i < LOOP_COUNT; i++)
            {
                Player topPlayer = (from p in db.Players
                                    where p.PlayerId == 1
                                    select p).SingleOrDefault();
            }
        }
예제 #2
0
        /// <summary>
        /// Sets the delay before the next action will be taken for this Npc again.
        /// </summary>
        /// <param name="delay">The delay before the next scheduled action.</param>
        /// <returns>true is time has been set, false if another thread has already ran (Npc should exit)</returns>
        protected bool SetNextActionDelay(TimeSpan delay)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Mark the next time this NPC will need to do an action
            this.npcRow.NextActionTime = DateTime.UtcNow.Add(delay);

            db.SaveChanges();

            return(true);
        }
예제 #3
0
        public void SkummHomeSystem()
        {
            // Test that the created Skumm player starts in the correct home system
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            Race skummRace = (from r in db.Races
                              where r.Name == "Skumm"
                              select r).SingleOrDefault();

            this.CheckPlayerHomeSystem(skummRace);
        }
예제 #4
0
        public void DecapodianHomeSystem()
        {
            // Test that the created Decapodian player starts in the correct home system
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            Race decapodianRace = (from r in db.Races
                                   where r.Name == "Decapodian"
                                   select r).SingleOrDefault();

            this.CheckPlayerHomeSystem(decapodianRace);
        }
예제 #5
0
        public void LINQWhereObjectId()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();
            Player topPlayer            = db.Players.First();

            for (int i = 0; i < LOOP_COUNT; i++)
            {
                IQueryable <Player> matchingPlayer = (from p in db.Players
                                                      where p.PlayerId == topPlayer.PlayerId
                                                      select p);
            }
        }
예제 #6
0
        private Player CreateTestPlayer(string baseTestUsername, string baseTestEmail, string baseTestPlayerName)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Default to Human race
            Race humanRace = (from r in db.Races
                              where r.Name == "Human"
                              select r).SingleOrDefault();

            Assert.IsNotNull(humanRace, "Human Race needs to be present in the database");

            return(this.CreateTestPlayer(baseTestUsername, baseTestEmail, baseTestPlayerName, humanRace));
        }
예제 #7
0
        public void LINQToList()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            for (int i = 0; i < LOOP_COUNT; i++)
            {
                List <Player> players = (from p in db.Players
                                         where p.Alive
                                         select p).ToList();
                foreach (Player player in players)
                {
                    player.NetWorth++;
                }
            }
        }
예제 #8
0
        private Player CreateTestPlayer(string baseTestUsername, string baseTestEmail, string baseTestPlayerName, Race playerRace)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            CosmoMongerMembershipProvider provider = new CosmoMongerMembershipProvider();
            MembershipCreateStatus        status;
            CosmoMongerMembershipUser     testUser = (CosmoMongerMembershipUser)provider.CreateUser(baseTestUsername, "test1000", baseTestEmail, null, null, true, null, out status);

            Assert.IsNotNull(testUser, "Test User was created. status = {0}", new object[] { status });

            User testUserModel = testUser.GetUserModel();

            Assert.IsNotNull(testUserModel, "Able to get model object for user");

            return(testUserModel.CreatePlayer(baseTestUsername, playerRace));
        }
예제 #9
0
        private void SetPlayerShip(Player player, string shipName)
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Assign the default base ship type
            BaseShip baseShip = (from bs in db.BaseShips
                                 where bs.Name == shipName
                                 select bs).SingleOrDefault();

            player.Ship.BaseShip = baseShip;

            // Setup default upgrades
            player.Ship.JumpDrive = player.Ship.BaseShip.InitialJumpDrive;
            player.Ship.Shield    = player.Ship.BaseShip.InitialShield;
            player.Ship.Weapon    = player.Ship.BaseShip.InitialWeapon;
        }
예제 #10
0
        public void GetSystemDistance()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            Player testPlayer = this.CreateTestPlayer();

            CosmoSystem [] inRangeSystems = testPlayer.Ship.GetInRangeSystems();
            int            range          = testPlayer.Ship.JumpDrive.Range;

            // Check the distance of all the in-range systems
            foreach (CosmoSystem system in inRangeSystems)
            {
                double distance = testPlayer.Ship.GetSystemDistance(system);
                Assert.That(distance, Is.LessThan(range), "All in range systems should be within JumpDrive range");
            }
        }
예제 #11
0
        public void SellNotSold()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Setup player
            Player      testPlayer     = this.CreateTestPlayer();
            Ship        testShip       = testPlayer.Ship;
            CosmoSystem startingSystem = testShip.CosmoSystem;
            GameManager manager        = new GameManager(testPlayer.User.UserName);

            // Store the player starting cash
            int playerStartingCash = testPlayer.Ship.Credits;

            // Add some water to this ship for us to sell
            Good water = (from g in db.Goods
                          where g.Name == "Water"
                          select g).SingleOrDefault();

            Assert.That(water, Is.Not.Null, "We should have a Water good");
            ShipGood shipGood = new ShipGood();

            shipGood.Good     = water;
            shipGood.Quantity = 10;
            shipGood.Ship     = testShip;
            testShip.ShipGoods.Add(shipGood);

            // Verify that the good is for sell in the current system
            SystemGood systemWater = startingSystem.GetGood(water.GoodId);

            if (systemWater != null)
            {
                // Remove the good from the system
                db.SystemGoods.DeleteOnSubmit(systemWater);
                db.SubmitChanges();
            }
            try
            {
                shipGood.Sell(testShip, 10, systemWater.Price);
            }
            catch (InvalidOperationException ex)
            {
                // Correct
                Assert.That(ex, Is.Not.Null, "InvalidOperationException should be valid");
                return;
            }
            Assert.Fail("Player should not been able to sell in the system when the good was not sold in the system");
        }
예제 #12
0
        public void BankWithdrawNoBank()
        {
            // Arrange
            Player testPlayer = this.CreateTestPlayer();

            // Move the player to a system without a bank
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();
            CosmoSystem noBankSystem    = (from s in db.CosmoSystems
                                           where !s.HasBank
                                           select s).FirstOrDefault();

            Assert.That(noBankSystem, Is.Not.Null, "There should be at least one system in the galaxy without a bank");
            testPlayer.Ship.CosmoSystem = noBankSystem;

            // Act, should throw an exception
            testPlayer.BankWithdraw(1000);
        }
예제 #13
0
        public void BuyNotEnoughCash()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Setup player
            Player      testPlayer     = this.CreateTestPlayer();
            Ship        testShip       = testPlayer.Ship;
            CosmoSystem startingSystem = testShip.CosmoSystem;
            GameManager manager        = new GameManager(testPlayer.User.UserName);

            // Reduce the player starting cash
            testPlayer.Ship.Credits = 10;

            // Check that the ship is empty
            Assert.That(testShip.ShipGoods.Count, Is.EqualTo(0), "Ship should start out with no goods on-board");

            // Add some water to the starting system for this ship to buy
            Good water = (from g in db.Goods
                          where g.Name == "Water"
                          select g).SingleOrDefault();

            Assert.That(water, Is.Not.Null, "We should have a Water good");
            startingSystem.AddGood(water.GoodId, 20);

            // Verify that the good was added to the system
            SystemGood systemWater = startingSystem.GetGood(water.GoodId);

            Assert.That(systemWater, Is.Not.Null, "System should now have a water SystemGood");
            Assert.That(systemWater.Quantity, Is.GreaterThanOrEqualTo(20), "System should now have at least 20 water goods");

            int playerCost          = (int)(systemWater.PriceMultiplier * water.BasePrice) * systemWater.Quantity;
            int systemStartingCount = systemWater.Quantity;

            try
            {
                systemWater.Buy(testShip, 20, systemWater.Price);
            }
            catch (ArgumentException ex)
            {
                Assert.That(ex.ParamName, Is.EqualTo("quantity"), "Quantity to buy should be the invalid argument");
                return;
            }

            Assert.Fail("Player should not been able to buy more goods than they can afford");
        }
예제 #14
0
        public void SellNotEnoughGoods()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Setup player
            Player      testPlayer     = this.CreateTestPlayer();
            Ship        testShip       = testPlayer.Ship;
            CosmoSystem startingSystem = testShip.CosmoSystem;
            GameManager manager        = new GameManager(testPlayer.User.UserName);

            // Add some water to this ship for us to sell
            Good water = (from g in db.Goods
                          where g.Name == "Water"
                          select g).SingleOrDefault();

            Assert.That(water, Is.Not.Null, "We should have a Water good");
            ShipGood shipGood = new ShipGood();

            shipGood.Good     = water;
            shipGood.Quantity = 10;
            shipGood.Ship     = testShip;
            testShip.ShipGoods.Add(shipGood);
            db.SubmitChanges();

            // Verify that the good is for sell in the current system
            SystemGood systemWater = startingSystem.GetGood(water.GoodId);

            if (systemWater == null)
            {
                startingSystem.AddGood(water.GoodId, 0);
                systemWater = startingSystem.GetGood(water.GoodId);
            }

            try
            {
                shipGood.Sell(testShip, 20, systemWater.Price);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.That(ex.ParamName, Is.EqualTo("quantity"), "Quantity to sell should be the invalid argument");
                return;
            }

            Assert.Fail("Player should not been able to sell more goods than aboard");
        }
예제 #15
0
        public void FindUserJory()
        {
            Player      testPlayer = this.CreateTestPlayer();
            GameManager manager    = new GameManager(testPlayer.User.UserName);

            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            //db.Log = Console.Out;

            IEnumerable <User> users      = manager.FindUser("jory");
            IPagination <User> usersPaged = users.AsPagination(1);

            usersPaged.ToArray();

            //db.Log = null;

            Assert.That(users, Is.Not.Empty, "Should find me");
        }
예제 #16
0
        public void Sell()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Setup player
            Player      testPlayer     = this.CreateTestPlayer();
            Ship        testShip       = testPlayer.Ship;
            CosmoSystem startingSystem = testShip.CosmoSystem;
            GameManager manager        = new GameManager(testPlayer.User.UserName);

            // Store the player starting cash
            int playerStartingCash = testPlayer.Ship.Credits;

            // Add some water to this ship for us to sell
            Good water = (from g in db.Goods
                          where g.Name == "Water"
                          select g).SingleOrDefault();

            Assert.That(water, Is.Not.Null, "We should have a Water good");
            ShipGood shipGood = new ShipGood();

            shipGood.Good     = water;
            shipGood.Quantity = 10;
            shipGood.Ship     = testShip;
            testShip.ShipGoods.Add(shipGood);

            // Verify that the good is for sell in the current system
            SystemGood systemWater = startingSystem.GetGood(water.GoodId);

            if (systemWater == null)
            {
                startingSystem.AddGood(water.GoodId, 0);
                systemWater = startingSystem.GetGood(water.GoodId);
            }
            int playerProfit        = systemWater.Price * 10;
            int systemStartingCount = systemWater.Quantity;

            shipGood.Sell(testShip, 10, systemWater.Price);

            Assert.That(systemWater.Quantity, Is.EqualTo(systemStartingCount + 10), "System should now have 10 more water goods");
            Assert.That(testPlayer.Ship.Credits, Is.EqualTo(playerStartingCash + playerProfit), "Player should have more cash credits now after selling");
        }
예제 #17
0
        public void AcceptSearchNoGoods()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();
            Good nonContrabandGood      = (from g in db.Goods
                                           where !g.Contraband
                                           select g).FirstOrDefault();

            // Add non-contraband good to player 2
            player2.Ship.AddGood(nonContrabandGood.GoodId, 5);

            // Player 1 starts search
            combat.StartSearch();

            // Player 2 accepts search
            combat.AcceptSearch();

            ShipGood good2 = player2.Ship.GetGood(nonContrabandGood.GoodId);

            Assert.That(good2.Quantity, Is.EqualTo(5), "Player 2 should still have 5 of the non-contraband good now");
        }
예제 #18
0
        public void AddGood()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();
            CosmoSystem firstSystem     = (from s in db.CosmoSystems select s).FirstOrDefault();

            Assert.That(firstSystem, Is.Not.Null, "We need at least one system in the galaxy");

            // Add some water to the the system
            Good water = (from g in db.Goods
                          where g.Name == "Water"
                          select g).SingleOrDefault();

            Assert.That(water, Is.Not.Null, "We should have a Water good");
            firstSystem.AddGood(water.GoodId, 100);

            // Verify that the good was added to the system
            SystemGood systemWater = firstSystem.GetGood(water.GoodId);

            Assert.That(systemWater, Is.Not.Null, "System should now have a water SystemGood");
            Assert.That(systemWater.Quantity, Is.GreaterThanOrEqualTo(100), "System should now have at least 100 water goods");
        }
예제 #19
0
        public void BuyNotEnoughGoods()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Setup player
            Player      testPlayer     = this.CreateTestPlayer();
            Ship        testShip       = testPlayer.Ship;
            CosmoSystem startingSystem = testShip.CosmoSystem;
            GameManager manager        = new GameManager(testPlayer.User.UserName);

            // Check that the ship is empty
            Assert.That(testShip.ShipGoods.Count, Is.EqualTo(0), "Ship should start out with no goods on-board");

            // Add some water to the starting system for this ship to buy
            Good water = (from g in db.Goods
                          where g.Name == "Water"
                          select g).SingleOrDefault();

            Assert.That(water, Is.Not.Null, "We should have a Water good");
            startingSystem.AddGood(water.GoodId, 5);

            // Verify that the good was added to the system
            SystemGood systemWater = startingSystem.GetGood(water.GoodId);

            // Make sure only 5 are at the system
            systemWater.Quantity = 5;

            try
            {
                systemWater.Buy(testShip, 20, systemWater.Price);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.That(ex.ParamName, Is.EqualTo("quantity"), "Quantity to buy should be the invalid argument");
                return;
            }

            Assert.Fail("Player should not been able to buy more goods than at the system");
        }
예제 #20
0
        public void Buy()
        {
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Setup player
            Player      testPlayer     = this.CreateTestPlayer();
            Ship        testShip       = testPlayer.Ship;
            CosmoSystem startingSystem = testShip.CosmoSystem;
            GameManager manager        = new GameManager(testPlayer.User.UserName);

            // Store the player starting cash
            int playerStartingCash = testPlayer.Ship.Credits;

            // Check that the ship is empty
            Assert.That(testShip.ShipGoods.Count, Is.EqualTo(0), "Ship should start out with no goods on-board");

            // Add some water to the starting system for this ship to buy
            Good water = (from g in db.Goods
                          where g.Name == "Water"
                          select g).SingleOrDefault();

            Assert.That(water, Is.Not.Null, "We should have a Water good");
            startingSystem.AddGood(water.GoodId, 20);

            // Verify that the good was added to the system
            SystemGood systemWater = startingSystem.GetGood(water.GoodId);

            Assert.That(systemWater, Is.Not.Null, "System should now have a water SystemGood");
            Assert.That(systemWater.Quantity, Is.GreaterThanOrEqualTo(20), "System should now have at least 20 water goods");

            int playerCost          = systemWater.Price * 20;
            int systemStartingCount = systemWater.Quantity;

            systemWater.Buy(testShip, 20, systemWater.Price);

            Assert.That(systemWater.Quantity, Is.EqualTo(systemStartingCount - 20), "System should now have 20 few water goods");
            Assert.That(testPlayer.Ship.Credits, Is.EqualTo(playerStartingCash - playerCost), "Player should have less cash credits now after buying");
        }
예제 #21
0
        /// <summary>
        /// Does the action.
        /// </summary>
        public override void DoAction()
        {
            if (!this.SetNextActionDelay(NpcShipBase.DelayBeforeNextAction))
            {
                return;
            }

            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();
            Ship npcShip = this.npcRow.Ship;

            // Check if we are still traveling
            npcShip.CheckIfTraveling();

            // Check if we are currently in combat
            if (npcShip.InProgressCombat != null)
            {
                // In Combat!
                this.DoCombat();
            }
            else if (this.npcRow.NextTravelTime < DateTime.UtcNow)
            {
                // Search?
                if (this.rnd.SelectByProbablity(new bool[] { true, false }, new double[] { 0.50, 0.50 }))
                {
                    this.DoSearch();
                }
                else
                {
                    this.DoTravel();
                }

                this.SetNextTravelTime();
            }

            db.SaveChanges();
        }
예제 #22
0
 protected void Application_Start()
 {
     Logger.Write("CosmoMonger Application Start (r" + CosmoManager.GetCodeVersion().ToString() + " db" + CosmoManager.GetDatabaseVersion().ToString() + ")", "ASP.NET Core", 1000, 0, TraceEventType.Information, "CosmoMonger Application Start");
     RegisterRoutes(RouteTable.Routes);
 }
예제 #23
0
        /// <summary>
        /// Updates the system good count, causing systems to produce goods as needed.
        /// </summary>
        private void UpdateSystemGoodCount()
        {
            CosmoMongerDbDataContext    db = CosmoManager.GetDbContext();
            Dictionary <string, object> props;

            foreach (Good good in db.Goods)
            {
                // Get the total number of this good type available in all systems
                int    totalSystemGoodCount = good.SystemGoods.Sum(x => x.Quantity);
                double targetBreak          = (((double)good.TargetCount) / 10.0);

                // Check if we need to add some of this good to the galaxy
                while (totalSystemGoodCount < good.TargetCount)
                {
                    // Randomly select a system with  equal to or fewer than targetBreak number of goods to produce.
                    var goodProducingSystems = (from g in good.SystemGoods
                                                where g.ProductionFactor > 0 && g.Quantity <= targetBreak
                                                select g);
                    if (goodProducingSystems.Count() == 0)
                    {
                        // No systems produce this good?
                        // Continue on to the next good type
                        break;
                    }

                    SystemGood selectedProducingSystemGood = goodProducingSystems.ElementAt(rnd.Next(goodProducingSystems.Count()));

                    // Produce the good, using the count needed and the production factor
                    double adjustedProductionFactor = (rnd.NextDouble() + selectedProducingSystemGood.ProductionFactor) / 2;
                    int    lackingGoodCount         = (int)(rnd.Next(10) * adjustedProductionFactor);
                    selectedProducingSystemGood.Quantity += lackingGoodCount;

                    props = new Dictionary <string, object>
                    {
                        { "SystemId", selectedProducingSystemGood.SystemId },
                        { "GoodId", selectedProducingSystemGood.GoodId },
                        { "Quantity", selectedProducingSystemGood.Quantity },
                        { "AddedQuantity", lackingGoodCount }
                    };
                    Logger.Write("Producing Goods", "NPC", 400, 0, TraceEventType.Verbose, "Producing Goods", props);

                    // Update the total good count
                    totalSystemGoodCount += lackingGoodCount;

                    try
                    {
                        // Send changes to database
                        db.SubmitChanges(ConflictMode.ContinueOnConflict);
                    }
                    catch (ChangeConflictException ex)
                    {
                        ExceptionPolicy.HandleException(ex, "SQL Policy");

                        // Another thread has made changes to this SystemGood row,
                        // which could be from someone buying or selling the good at a system
                        // Best case to resolve this would be to simply start over in the good production,
                        // because the good quantity has been changed by another method.
                        foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                        {
                            // Refresh values from database
                            occ.Resolve(RefreshMode.OverwriteCurrentValues);
                        }

                        continue;
                    }
                }

                // Now consume some of this good in the galaxy
                // Randomly select a good at a system to consume where the quantity is equal to or higher
                // than targetBreak number of goods
                var goodConsumingSystems = (from g in good.SystemGoods
                                            where g.ConsumptionFactor > 0 && g.Quantity >= targetBreak &&
                                            g.Quantity > 0
                                            select g);
                if (goodConsumingSystems.Count() == 0)
                {
                    // No systems consume this good?
                    // Continue on to the next good type
                    continue;
                }

                SystemGood selectedConsumingSystemGood = goodConsumingSystems.ElementAt(rnd.Next(goodConsumingSystems.Count()));

                // Consuming the good, using the count needed and the consumption factor
                double adjustedConsumptionFactor = (rnd.NextDouble() + selectedConsumingSystemGood.ConsumptionFactor) / 2;
                int    usageGoodCount            = (int)(rnd.Next(10) * adjustedConsumptionFactor);
                usageGoodCount = Math.Min(usageGoodCount, selectedConsumingSystemGood.Quantity);
                selectedConsumingSystemGood.Quantity -= usageGoodCount;

                props = new Dictionary <string, object>
                {
                    { "SystemId", selectedConsumingSystemGood.SystemId },
                    { "GoodId", selectedConsumingSystemGood.GoodId },
                    { "Quantity", selectedConsumingSystemGood.Quantity },
                    { "RemovedQuantity", usageGoodCount }
                };
                Logger.Write("Consuming Goods", "NPC", 400, 0, TraceEventType.Verbose, "Consuming Goods", props);

                try
                {
                    // Send changes to database
                    db.SubmitChanges(ConflictMode.ContinueOnConflict);
                }
                catch (ChangeConflictException ex)
                {
                    ExceptionPolicy.HandleException(ex, "SQL Policy");

                    // Another thread has made changes to this SystemGood row,
                    // which could be from someone buying or selling the good at a system
                    // Best case to resolve this would be to simply ignore the good consumption,
                    // we like to produce more than we consume
                    foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                    {
                        // Refresh values from database
                        occ.Resolve(RefreshMode.OverwriteCurrentValues);
                    }
                }
            }
        }
예제 #24
0
        /// <summary>
        /// Does the action.
        /// </summary>
        public override void DoAction()
        {
            if (!this.SetNextActionDelay(NpcTrader.DelayBeforeNextAction))
            {
                return;
            }

            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();
            Ship npcShip = this.npcRow.Ship;

            // Check if we are still traveling
            npcShip.CheckIfTraveling();

            // Check if we are currently in combat
            if (npcShip.InProgressCombat != null)
            {
                // In Combat!
                this.DoCombat();
            }
            else if (this.npcRow.NextTravelTime < DateTime.UtcNow)
            {
                // Create an array of goods that the Trader has onboard
                ShipGood[] goods = npcShip.GetGoods().Where(g => g.Quantity > 0).ToArray();

                // goodCount != 0, sell all the trader's goods
                foreach (ShipGood good in goods)
                {
                    // Get the number of this good type onboard the Trader's ship
                    int shipGoodQuantity = good.Quantity;

                    // Find the price of the good
                    int shipGoodPrice = 0;

                    try
                    {
                        good.Sell(npcShip, shipGoodQuantity, shipGoodPrice);
                    }
                    catch (InvalidOperationException ex)
                    {
                        // Log this exception
                        ExceptionPolicy.HandleException(ex, "NPC Policy");
                    }
                }

                // This is the minimum amount of money a trader should have before buying goods
                int baseCreditsSizeAdjusted = BaseCreditMultiplier * npcShip.CargoSpaceTotal;

                // Check if we need to give this trader some credits
                if (npcShip.Credits < baseCreditsSizeAdjusted)
                {
                    // Poor trader has no credits, give him some to start
                    npcShip.Credits = baseCreditsSizeAdjusted;
                }

                // Trader buys first good
                SystemGood good1 = (from g in npcShip.CosmoSystem.SystemGoods
                                    orderby(g.PriceMultiplier) ascending
                                    select g).FirstOrDefault();

                // This is the maximum number a Trader can purchase
                double numberCanBuy = Math.Floor((double)npcShip.Credits / good1.Price);

                // This is the maximum number we want the Trader to purchase
                double numberToBuy = Math.Ceiling((double)npcShip.CargoSpaceFree / 2);

                // Make sure that the Trader buys as many of good1 as credits allow
                int numberBuying = (int)Math.Min(numberCanBuy, numberToBuy);

                // Insures that Traders attempt to buy the proper number of good1
                int properNumber = (int)Math.Min(numberBuying, good1.Quantity);

                try
                {
                    good1.Buy(npcShip, properNumber, good1.Price);
                }
                catch (InvalidOperationException ex)
                {
                    // Log this exception
                    ExceptionPolicy.HandleException(ex, "NPC Policy");
                }

                // Find all the systems within range
                CosmoSystem[] inRangeSystems = npcShip.GetInRangeSystems();

                // Finds the system with the highest PriceMultiplier
                CosmoSystem targetSystem = (from g in db.SystemGoods
                                            where inRangeSystems.Contains(g.CosmoSystem) &&
                                            g.Good == good1.Good
                                            orderby(g.PriceMultiplier) descending
                                            select g.CosmoSystem).FirstOrDefault();

                // Get references to the Good entities for all the SystemGoods sold in the target system
                IEnumerable <Good> goodsInTargetSystem = targetSystem.SystemGoods.Select(g => g.Good);

                // Get references to the Good entites for the all the SystemGoods sold in the current system
                IEnumerable <Good> goodsInCurrentSystem = npcShip.CosmoSystem.SystemGoods.Select(g => g.Good);

                // Do an intersetion of both, getting a list of goods sold in both systems
                IEnumerable <Good> goodsInBoth = goodsInTargetSystem.Intersect(goodsInCurrentSystem);

                // Look in the current system for goods sold in both, sorting by PriceMultiplier (lowest at top)
                // and taking the top good in the results
                SystemGood good2 = (from g in npcShip.CosmoSystem.SystemGoods
                                    where goodsInBoth.Contains(g.Good) &&
                                    g != good1
                                    orderby g.PriceMultiplier ascending
                                    select g).FirstOrDefault();

                // This is the maximum number a Trader can purchase
                numberCanBuy = Math.Floor((double)npcShip.Credits / good2.Price);

                // This is the maximum number we want the Trader to purchase
                numberToBuy = Math.Ceiling((double)npcShip.CargoSpaceFree);

                // Make sure that the Trader buys as many of good1 as credits allow
                numberBuying = (int)Math.Min(numberCanBuy, numberToBuy);

                // Insures that Traders attempt to buy the proper number of good1
                properNumber = (int)Math.Min(numberBuying, good2.Quantity);

                try
                {
                    good2.Buy(npcShip, properNumber, good2.Price);
                }
                catch (InvalidOperationException ex)
                {
                    // Log this exception
                    ExceptionPolicy.HandleException(ex, "NPC Policy");
                }

                this.DoTravel(targetSystem);

                // Set next travel time
                this.npcRow.NextTravelTime = DateTime.UtcNow.AddSeconds(this.rnd.Next(60, 120));
            }
            else
            {
                Dictionary <string, object> props = new Dictionary <string, object>
                {
                    { "NpcId", this.npcRow.NpcId },
                    { "NextTravelTime", this.npcRow.NextTravelTime },
                    { "UtcNow", DateTime.UtcNow }
                };
                Logger.Write("Waiting for NextTravelTime", "NPC", 200, 0, TraceEventType.Verbose, "Trader Wait", props);
            }

            db.SaveChanges();
        }
예제 #25
0
 public void DoPendingNPCActions()
 {
     CosmoManager.DoPendingNPCActions(null);
 }
예제 #26
0
 public void GetDatabaseVersion()
 {
     Assert.That(CosmoManager.GetDatabaseVersion(), Is.GreaterThan(0), "Database Version should be greater than zero");
 }
예제 #27
0
 public void GetDbContext()
 {
     Assert.That(CosmoManager.GetDbContext(), Is.Not.Null, "We should always be able to get a database context");
 }
예제 #28
0
        /// <summary>
        /// Balances the number of NPCs vs Active Players to keep the galaxy alive.
        /// </summary>
        public override void DoAction()
        {
            // Set next run time to 1 hour
            if (!this.SetNextActionDelay(new TimeSpan(1, 0, 0)))
            {
                return;
            }

            // Balance Npcs
            CosmoMongerDbDataContext db = CosmoManager.GetDbContext();

            // Find the number of players active in the last hour on the galaxy
            int activePlayerCount = (from p in db.Players
                                     where p.LastPlayed > DateTime.UtcNow.AddHours(-1)
                                     select p).Count();

            // Calculate how many Npcs we need
            int neededNpcs = NpcBalancer.TargetActivePlayers - activePlayerCount;

            // Make sure we don't go below the min amount
            neededNpcs = Math.Max(neededNpcs, NpcBalancer.MinNpcs);

            // Grab the active NPCs we currently have
            IQueryable <Npc> activeNpcs = (from n in db.Npcs
                                           where n.NType == Npc.NpcType.Pirate ||
                                           n.NType == Npc.NpcType.Police ||
                                           n.NType == Npc.NpcType.Trader
                                           select n);

            // Calculate how many NPCs we need to create/delete
            int npcAdjustment = neededNpcs - activeNpcs.Count();

            if (npcAdjustment > 0)
            {
                while (npcAdjustment-- > 0)
                {
                    // Produce NPCs
                    Npc     newNpc = new Npc();
                    NpcBase npc    = null;

                    // Which type will we produce?
                    Npc.NpcType[] npcTypes      = { Npc.NpcType.Pirate, Npc.NpcType.Trader, Npc.NpcType.Police };
                    double[]      npcProbablity = { NpcBalancer.PercentPirates, NpcBalancer.PercentTraders, NpcBalancer.PercentPolice };
                    newNpc.NType = this.rnd.SelectByProbablity(npcTypes, npcProbablity);

                    switch (newNpc.NType)
                    {
                    case Npc.NpcType.Pirate:
                        // Produce pirate
                        npc = new NpcPirate(newNpc);
                        break;

                    case Npc.NpcType.Trader:
                        // Produce trader
                        npc = new NpcTrader(newNpc);
                        break;

                    case Npc.NpcType.Police:
                        // Produce Police
                        npc = new NpcPolice(newNpc);
                        break;

                    default:
                        throw new InvalidOperationException("Unknown NpcType selected");
                    }

                    // Give the NPC a good name
                    string npcName = (from name in db.NpcNames
                                      where name.NType == newNpc.NType &&
                                      !(from n in db.Npcs
                                        select n.Name)
                                      .Contains(name.Name)
                                      select name.Name).FirstOrDefault();

                    // Break out if we couldn't find a new name
                    if (npcName == null)
                    {
                        Logger.Write(newNpc.NType.ToString(), "NPC", 1000, 0, TraceEventType.Critical, "Out of NPC Names");
                        break;
                    }

                    // Give the NPC the cool name
                    newNpc.Name = npcName;

                    // Add to the database
                    db.Npcs.InsertOnSubmit(newNpc);

                    // Setup the NPC
                    npc.Setup();

                    db.SaveChanges();
                }
            }
            else if (npcAdjustment < 0)
            {
                // TODO: Delete or inactive NPCs

                /*
                 * // Query the NPCs to delete
                 * IQueryable<Npc> npcsToDelete = activeNpcs.Take(Math.Abs(npcAdjustment));
                 * if (npcsToDelete.Any())
                 * {
                 *  // Remove the NPCs
                 *  db.Npcs.DeleteAllOnSubmit(npcsToDelete);
                 *
                 *  IQueryable<Ship> npcShips = (from n in activeNpcs
                 *                               select n.Ship);
                 *  if (npcShips.Any())
                 *  {
                 *      IQueryable<ShipGood> npcShipGoods = (from g in db.ShipGoods
                 *                                           where npcShips.Contains(g.Ship)
                 *                                           select g);
                 *      if (npcShipGoods.Any())
                 *      {
                 *          // Remove the ship goods
                 *          db.ShipGoods.DeleteAllOnSubmit(npcShipGoods);
                 *      }
                 *
                 *      // Remove the ships
                 *      db.Ships.DeleteAllOnSubmit(npcShips);
                 *  }
                 * }
                 */
            }

            db.SaveChanges();
        }