public void WhenRunEnoughTimes_ThenReturnAllPossiblities()
            {
                ICollection <int> sut = new List <int> {
                    1, 5, 10
                };

                bool oneFound  = false;
                bool fiveFound = false;
                bool tenFound  = false;

                for (var i = 0; i < 100; i++)
                {
                    var result = sut.TakeRandom();

                    switch (result)
                    {
                    case 1: oneFound = true; break;

                    case 5: fiveFound = true; break;

                    case 10: tenFound = true; break;
                    }
                }

                Assert.That(oneFound, Is.True);
                Assert.That(fiveFound, Is.True);
                Assert.That(tenFound, Is.True);
            }
Example #2
0
    /// <summary>
    /// Image you have two Squares, one big and one small. This method uses (minDistance - 1) as a little square and maxDistance as a big square.
    /// It finds availible open spots by withdrawing from the big square coordinates that is in the small square.
    /// </summary>
    private Coordinate GetRandomOpenCoordinateNear(Coordinate coord, int minDistance, int maxDistance)
    {
        List <Coordinate> openCoords = new List <Coordinate>();

        List <Coordinate> ignoringCoordinates = GetCoordinatesNear(coord, minDistance - 1, TileType.Empty);

        foreach (Coordinate potentialOpenCoord in GetCoordinatesNear(coord, maxDistance, TileType.Empty))
        {
            if (!ignoringCoordinates.Exists(c => c.x == potentialOpenCoord.x && c.z == potentialOpenCoord.z))
            {
                openCoords.Add(potentialOpenCoord);
            }
        }

        //Debug.LogFormat("{0} has {1} nearby open coordinates with minDistance {2} and maxDistance {3} ", coord, openCoords.Count, minDistance, maxDistance);

        if (openCoords.Count == 0)
        {
            throw new Exception(string.Format("Could not find an open coordinate near {0} with minDistance {1} and maxDistance {2}.", coord, minDistance, maxDistance));
        }
        else
        {
            return(openCoords.TakeRandom());
        }
    }
Example #3
0
    public void Start()
    {
        foreach (var markTransform in characterMarkTransforms)
        {
            characterMarks.Add(new CharacterMark()
            {
                transform = markTransform
            });
        }

        mainCharacter = Character.Create(mainCharacterData);

        characters.Add(mainCharacter);

        mainCharacter.transform.SetParent(characterHolder);

        var characterMarksToAddTo = characterMarks.TakeRandom(characters.Count).GetEnumerator();

        foreach (var character in characters)
        {
            characterMarksToAddTo.MoveNext();
            characterMarkSlots.Add(characterMarksToAddTo.Current, character);
        }

        var added = characterMarkSlots.Keys.ToArray();

        foreach (var mark in characterMarks.Except(added))
        {
            characterMarkSlots.Add(mark, null);
        }

        roundTurns = startRoundTurns;

        RunEvent(StartGame());
    }
        public void SpreadPurityFromPoint(int start)
        {
            HashSet <int> toConvert = new HashSet <int>();
            HashSet <int> neighbors = new HashSet <int>();

            toConvert.Add(start);

            List <int> tmpTiles = new List <int>();

            for (int i = 0; i <= 12; i++)
            {
                foreach (int t in toConvert)
                {
                    Find.WorldGrid.GetTileNeighbors(t, tmpTiles);
                    //neighbors.UnionWith(tmpTiles);
                    //neighbors.Add(tmpTiles.RandomElement());

                    neighbors.AddRange(tmpTiles.TakeRandom(2));
                }

                toConvert.UnionWith(neighbors);
            }

            foreach (int t in toConvert)
            {
                Tile tile = Find.WorldGrid[t];
                tile.biome = BiomeDef.Named(cache[t].originalBiome);
                PurifyTile(t);
            }
        }
            public void WhenCountIsLessThanOne_ThenReturnEmpty(int count)
            {
                ICollection <int> sut = new List <int>();

                var result = sut.TakeRandom(count);

                Assert.That(result, Is.Empty);
            }
            public void WhenSourceIsEmpty_AndEvalResult_ThenThrowException()
            {
                ICollection <int> sut = new List <int>();

                var result = sut.TakeRandom(1);

                Assert.Throws <ArgumentOutOfRangeException>(() => _ = result.First());
            }
Example #7
0
        internal static IList <CardSet> ReadCardsFromData(ushort numberOfSets, string deckName)
        {
            List <CardSet> result = GetAllCardSets(deckName);

            AddDirectoryToFileNames(result, DeckReader.ReadDirectory(deckName));

            return(result.TakeRandom(numberOfSets));
        }
            public void WhenHasThreeElements_ThenReturnRandomElement()
            {
                ICollection <int> sut = new List <int> {
                    1, 5, 10
                };

                var result = sut.TakeRandom();

                Assert.That(result, Is.EqualTo(1).Or.EqualTo(5).Or.EqualTo(10));
            }
            public void WhenHasOneElements_ThenReturnElement()
            {
                ICollection <int> sut = new List <int> {
                    1
                };

                var result = sut.TakeRandom();

                Assert.That(result, Is.EqualTo(1));
            }
            public void WhenHasOneElement_AndCountOne_ThenReturnSequence()
            {
                ICollection <int> sut = new List <int> {
                    10
                };

                var result = sut.TakeRandom(1);

                Assert.That(result.Single(), Is.EqualTo(10));
            }
        private static string RandomColor(string boardId)
        {
            List <string> taken = UserManager.GetBoardUsers(boardId).Select(a => a.DisplayColor).ToList();

            List <string> notTaken = colors.Where(a => !taken.Contains(a)).ToList();

            string color = notTaken.Count > 0 ? notTaken.TakeRandom() : taken.TakeRandom();

            return(color);
        }
        public static Card TakeRandom(this List <Card> list)
        {
            if (list.Count == 0)
            {
                Debug.LogError("Attempted to TakeRandom from Empty Card List.");
                return(null);
            }

            return(list.TakeRandom(1).Single());
        }
        private static string RandomName(string boardId)
        {
            List <string> taken = UserManager.GetBoardUsers(boardId).Select(a => a.DisplayName).ToList();

            List <string> notTaken = names.Where(a => !taken.Contains(a)).ToList();

            string name = notTaken.Count > 0 ? notTaken.TakeRandom() : taken.TakeRandom();

            return(name);
        }
Example #14
0
        public void TakeRandomShouldAlwaysReturnSameForSpecificSeed(int seed, int value)
        {
            ImmgateRandom.SetSeed(seed);
            var r = new List <int>()
            {
                1, 2, 3, 4
            };
            int v = r.TakeRandom();

            Assert.IsTrue(v == value);
        }
Example #15
0
        public static string GetRandomCardTestNumber()
        {
            if (_allCards == null)
            {
                _allCards = new List <string>();
                _allCards.AddRange(_visaCards);
                _allCards.AddRange(_masterCards);
                _allCards.AddRange(_amexCards);
            }

            return(_allCards.TakeRandom(1).First());
        }
            public void WhenHasThreeElements_AndCountTwo_ThenReturnSequence()
            {
                ICollection <int> sut = new List <int> {
                    1, 5, 10
                };

                var result = sut.TakeRandom(2);

                Assert.That(result.Count(), Is.EqualTo(2));
                Assert.That(result.First(), Is.EqualTo(1).Or.EqualTo(5).Or.EqualTo(10));
                Assert.That(result.Second(), Is.EqualTo(1).Or.EqualTo(5).Or.EqualTo(10));
            }
Example #17
0
        public List <Def> RemoveRandom(int v)
        {
            var randomInfusions = infusions.TakeRandom(v).ToList();

            foreach (var infusion in randomInfusions)
            {
                infusions.Remove(infusion);
            }

            InvalidateCache();

            return(randomInfusions);
        }
Example #18
0
        public void SetupFactory(int botCount)
        {
            Log("Setting up bot factory with " + botCount + " bots");
            int            createdBots = 0;
            List <BotInfo> infos;

            if (Settings.Default.RandomBots)
            {
                infos = botInfos.TakeRandom(botCount).ToList();
            }
            else
            {
                infos = botInfos.Take(botCount).ToList();
            }
            Parallel.ForEach <BotInfo>(infos, info =>
            {
                bots.Add(LoadBot(info));
                createdBots++;
            });

            for (; createdBots < botCount; createdBots++)
            {
                bots.Add(CreateBot());
            }

            Log("Finished setting up bot factory with " + botCount + " bots");

            for (; ;)
            {
                string line = Console.ReadLine();
                switch (line)
                {
                case "quit":
                case "exit":
                case "close":
                case "shutdown":
                    return;

                case "info":
                case "infos":
                case "stats":
                case "statistics":
                    Console.WriteLine(bots.Where(bot => bot.Running).Count() + " bots are active");
                    Console.WriteLine(bots.Where(bot => bot.Connected).Count() + " bots are connected");
                    Console.WriteLine(bots.Where(bot => bot.LoggedIn).Count() + " bots are ingame");
                    break;
                }
            }
        }
Example #19
0
        static AuthInfo GetRandomAuth()
        {
#if false // in case passwords are not all 1
            if (!auths.Any())
            {
                Debug.Print("No player auth info available.");
                return(new AuthInfo());
            }
            var auth = auths.TakeRandom();
            if (Program.Random.Next(0, 5) == 3)
            {
                return(new AuthInfo(auth.Login, "wrong password"));
            }

            return(auth);
#endif
            return(new AuthInfo(GalaxyMap.Instance.Galaxy.Players.TakeRandom().Name, "1"));
        }
Example #20
0
 private static void FillBackstorySlotShuffled(Pawn pawn, BackstorySlot slot, ref Backstory backstory, List <string> backstoryCategories, FactionDef factionType)
 {
     tmpBackstories.Clear();
     BackstoryDatabase.ShuffleableBackstoryList(slot, backstoryCategories, tmpBackstories);
     if (!tmpBackstories.TakeRandom(20).Where(delegate(Backstory bs)
     {
         if (slot == BackstorySlot.Adulthood && bs.requiredWorkTags.OverlapsWithOnAnyWorkType(pawn.story.childhood.workDisables))
         {
             return(false);
         }
         return(true);
     }).TryRandomElementByWeight(BackstorySelectionWeight, out backstory))
     {
         Log.Error("No shuffled " + slot + " found for " + pawn.ToStringSafe() + " of " + factionType.ToStringSafe() + ". Defaulting.");
         backstory = (from kvp in BackstoryDatabase.allBackstories
                      where kvp.Value.slot == slot
                      select kvp).RandomElement().Value;
     }
     tmpBackstories.Clear();
 }
		void KillFleetsAndUpgrades(Faction victoriousFaction, Planet planet)
		{
			// kill orbiting spacefleets
			var fleetsToKill = new List<SpaceFleet>();
			foreach (var fleet in Galaxy.Fleets.Where(x => x.TargetPlanetID == planet.ID)) {
				PointF loc;
				if (fleet.GetCurrentPosition(out loc, Galaxy.Turn)) {
					if (Galaxy.GetPlayer(fleet.OwnerName).FactionName != victoriousFaction.Name) {
						fleetsToKill.Add(fleet);
					}
				}
			}
			if (fleetsToKill.Count > 0) {
				var f = fleetsToKill.TakeRandom(); // pick random one to kill
				Galaxy.Fleets.Remove(f);
				List<UpgradeDef> upgrades;
				if (UpgradeData.TryGetValue(f.OwnerName, out upgrades)) {
					var upgrade = upgrades.SingleOrDefault(u => u.UnitChoice == "fleet_blockade");
					if (upgrade != null) {
						upgrades.Remove(upgrade);
					}
				}
			}

			// occupied planet - delete deployed structures
			if (planet.OwnerName != null && Galaxy.GetPlayer(planet.OwnerName).FactionName != planet.FactionName) {
				RemoveAllUpgradesFromPlanet(planet.ID);
			}
		}
        private void RunNodeQueries(QueryGraph graph)
        {
            foreach (var node in graph.Nodes.Select(x => x.Value).Where(x => !x.AvoidQuery))
            //The other complex queries. Try endpoint first, if timeout, try with the index.
            //If the user has a timeout, is because his query is still too broad.
            //Some suggestions will be proposed with the local index, until the query can be completed by the endpoint.
            {
                if (node.IsInstanceOf)
                {
                    //Intersect (Not if any, we want only the results of that instance, even if there are none):
                    var instanceOfResults = new BatchIdEntityInstanceQuery(graph.EntitiesIndexPath, node.ParentTypes, 200).Query(20).ToList();
                    node.Results = instanceOfResults;
                    //TODO: Not sure if the previous run should consider this:
                    //node.Results = node.Results.Intersect(instanceOfResults).ToList();
                }
                else
                {
                    //Take domainTypes and intersect with rangeTypes.
                    var intersectTypes = new List <string>();

                    //Outgoing edges candidates, take their domain
                    var outgoingEdges = node.GetOutgoingEdges(graph).Where(x => !x.IsInstanceOf);
                    var domainTypes   = new List <string>();
                    foreach (var outgoingEdge in outgoingEdges)
                    {
                        domainTypes = domainTypes.IntersectIfAny(outgoingEdge.DomainTypes).ToList();
                    }

                    intersectTypes = intersectTypes.IntersectIfAny(domainTypes).ToList();

                    //Incoming edges candidates, take their range.
                    var incomingEdges = node.GetIncomingEdges(graph).Where(x => !x.IsInstanceOf);
                    var rangeTypes    = new List <string>();
                    foreach (var incomingEdge in incomingEdges)
                    {
                        rangeTypes = rangeTypes.IntersectIfAny(incomingEdge.RangeTypes).ToList();
                    }

                    intersectTypes = intersectTypes.IntersectIfAny(rangeTypes).ToList();

                    if (intersectTypes.Any())
                    {
                        //Combine domain & range, take a random sample and get those results:
                        //TODO: Why sort them randomly? What is wrong with their current sorting?
                        intersectTypes = intersectTypes.TakeRandom(100000).ToList();
                        node.Results   = new BatchIdEntityInstanceQuery(graph.EntitiesIndexPath, intersectTypes, 200)
                                         .Query(1000).ToList();
                    }
                    else
                    {
                        //If the instance is of a specific type, intersect a random sample of the instances with the previous results filter out the valid results:
                        var rnd            = new Random();
                        var randomEntities =
                            Enumerable.Repeat(1, 100).Select(_ => rnd.Next(99999)).Select(x => $"Q{x}");
                        node.Results = new BatchIdEntityQuery(graph.EntitiesIndexPath, randomEntities).Query().ToList();
                        //TODO: Temporary, for not getting empty results if there were none.
                        if (node.Results.Count < 20)
                        {
                            node.Results = node.Results
                                           .IntersectIfAny(new MultiLabelEntityQuery(graph.EntitiesIndexPath, "*").Query())
                                           .ToList();
                        }
                    }
                }
            }
        }
Example #23
0
        public void SetupFactory(int botCount)
        {
            while (!factoryGame.LoggedIn)
            {
                Log("Waiting for BotFactory account to login");
                Thread.Sleep(1000);
            }

            Log("Setting up bot factory with " + botCount + " bots");
            Stopwatch watch = new Stopwatch();

            watch.Start();

            int            createdBots = 0;
            List <BotInfo> infos;

            if (Settings.Default.RandomBots)
            {
                infos = botInfos.TakeRandom(botCount).ToList();
            }
            else
            {
                infos = botInfos.Take(botCount).ToList();
            }
            Parallel.ForEach <BotInfo>(infos, info =>
            {
                var bot = LoadBot(info);
                lock (bots)
                    bots.Add(bot);
                Interlocked.Increment(ref createdBots);
            });

            Parallel.For(createdBots, botCount, index =>
            {
                try
                {
                    var bot = CreateBot();
                    lock (bots)
                    {
                        bots.Add(bot);
                        if (bots.Count % 100 == 0)
                        {
                            SaveBotInfos();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log("Error creating new bot: " + ex.Message + "\n" + ex.StackTrace, LogLevel.Error);
                }
            });

            watch.Stop();
            Log("Finished setting up bot factory with " + botCount + " bots in " + watch.Elapsed);

            SaveBotInfos();

            for (; ;)
            {
                string line = Console.ReadLine();
                if (line == null)
                {
                    return;
                }
                string[] lineSplit = line.Split(' ');
                switch (lineSplit[0])
                {
                case "quit":
                case "exit":
                case "close":
                case "shutdown":
                    return;

                case "info":
                case "infos":
                case "stats":
                case "statistics":
                    DisplayStatistics(lineSplit.Length > 1 ? lineSplit[1] : "");
                    break;
                }
            }
        }
Example #24
0
        private static Task RequestPersonalTask(Dwarf d)
        {
            if (d.SkipPersonalForOneTask || DebugRules.SkipPersonalTasks)
                return null;

            List<Task> tasksToChooseFrom = new List<Task>();

            if (d.NeedFood())
            {
                tasksToChooseFrom.Add(new GetFoodTask());
            }
            if (d.NeedTool())
            {
                tasksToChooseFrom.Add(new GetToolTask());
            }
            if (d.NeedSleep())
            {
                tasksToChooseFrom.Add(new GetSleepTask());
            }
            if (d.NeedCloth())
            {
            }

            if (tasksToChooseFrom.Count == 0)
                return null;
            else
                return tasksToChooseFrom.TakeRandom();
        }
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            DarkNet darkNet = Current.Game.GetComponent <DarkNet>();

            if (darkNet == null || darkNet.Traders == null)
            {
                return(false);
            }

            DarkNetTrader trader          = darkNet.Traders.RandomElement();
            List <Thing>  allTraderThings = new List <Thing>();
            Faction       attacker        = Find.FactionManager.RandomEnemyFaction();

            if (attacker == null)
            {
                return(false);
            }

            if (!TileFinder.TryFindPassableTileWithTraversalDistance(Find.AnyPlayerHomeMap.Tile, 5, 12, out int newTile, (int i) => !Find.WorldObjects.AnyWorldObjectAt(i)))
            {
                return(false);
            }

            if (!trader.TryGetGoods(allTraderThings))
            {
                return(false);
            }

            Quest_DarkNetSupplyAttack quest = new Quest_DarkNetSupplyAttack(trader.def);
            int takeCount = Rand.Range(1, (int)Mathf.Max(1, allTraderThings.Count * 0.4f));
            IEnumerable <Thing> rewards = allTraderThings.TakeRandom(takeCount);

            quest.Rewards = new List <Thing>();
            foreach (var reward in rewards)
            {
                Thing copy = ThingMaker.MakeThing(reward.def, reward.Stuff);
                copy.stackCount = (int)Mathf.Max(1, reward.stackCount * 0.6f);

                quest.Rewards.Add(copy);
            }

            if (quest.Rewards.Count == 0)
            {
                return(false);
            }

            quest.id            = QuestsManager.Communications.UniqueIdManager.GetNextQuestID();
            quest.TicksToPass   = 6 * 60000;
            quest.ShowInConsole = false; //release = false
            quest.Faction       = attacker;

            string title = string.Format(def.letterLabel, trader.def.LabelCap);
            string desc  = string.Format(def.letterText, trader.def.LabelCap);

            CommunicationDialog dialog = QuestsManager.Communications.AddCommunication(QuestsManager.Communications.UniqueIdManager.GetNextDialogID(), title, desc, incident: def);

            dialog.KnownFaction       = false;
            quest.CommunicationDialog = dialog;

            QuestSite site = QuestsHandler.CreateSiteFor(quest, newTile, quest.Faction);

            Find.WorldObjects.Add(site);

            QuestsManager.Communications.AddQuest(quest);

            Find.LetterStack.ReceiveLetter(title, desc, def.letterDef, new LookTargets(site));

            return(true);
        }
Example #26
0
 private static TestResult ReadItemsById(DocumentStore documentStore, List<string> generatedIds)
 {
     var ids = generatedIds.TakeRandom().ToList();
     var time = Stopwatch.StartNew();
     foreach (var id in ids)
     {
         var jsonDocument = documentStore.DatabaseCommands.Get(id);
         // we need to convert it to entity to do the same level of work as mongo test
         var p = jsonDocument.DataAsJson.Deserialize<Person>(documentStore.Conventions);
         if (p.Id != null)
             throw new ArgumentException();
     }
     time.Stop();
     var result = new TestResult { Count = ids.Count, TotalMs = time.ElapsedMilliseconds };
     Console.WriteLine("Reading total time: {0} ms, avg item: {1} ms, #records: {2}",
                       result.TotalMs, result.ItemAvgMs, ids.Count);
     return result;
 }
Example #27
0
        public void SetupFactory(int botCount)
        {
            while (!factoryGame.LoggedIn)
            {
                Log("Waiting for BotFactory account to login");
                Thread.Sleep(1000);
            }

            Log("Setting up bot factory with " + botCount + " bots");
            int            createdBots = 0;
            List <BotInfo> infos;

            if (Settings.Default.RandomBots)
            {
                infos = botInfos.TakeRandom(botCount).ToList();
            }
            else
            {
                infos = botInfos.Take(botCount).ToList();
            }
            Parallel.ForEach <BotInfo>(infos, info =>
            {
                var bot = LoadBot(info);
                lock (bots)
                    bots.Add(bot);
                Interlocked.Increment(ref createdBots);
            });

            Parallel.For(createdBots, botCount, index =>
            {
                try
                {
                    var bot = CreateBot();
                    lock (bots)
                        bots.Add(bot);
                }
                catch (Exception ex)
                {
                    Log("Error creating new bot: " + ex.Message + "\n" + ex.StackTrace, LogLevel.Error);
                }
            });

            Log("Finished setting up bot factory with " + botCount + " bots");

            for (; ;)
            {
                string line = Console.ReadLine();
                switch (line)
                {
                case "quit":
                case "exit":
                case "close":
                case "shutdown":
                    return;

                case "info":
                case "infos":
                case "stats":
                case "statistics":
                    Console.WriteLine(bots.Where(bot => bot.Running).Count() + " bots are active");
                    Console.WriteLine(bots.Where(bot => bot.Connected).Count() + " bots are connected");
                    Console.WriteLine(bots.Where(bot => bot.LoggedIn).Count() + " bots are ingame");
                    break;
                }
            }
        }
            public void WhenSourceIsEmpty_ThenThrowException()
            {
                ICollection <int> sut = new List <int>();

                Assert.Throws <InvalidOperationException>(() => sut.TakeRandom());
            }