public void TakeRandom_IEnumerable_Uniformity(int trialsQty, int toSelectQty, int elementsQty, int inRangeQty)
        {
            // Arrange
            int expectedCount  = trialsQty / (elementsQty / toSelectQty);
            var timesChosen    = new int[elementsQty];
            var randomSelector = new RandomSelector();

            // Act
            for (var trial = 0; trial < trialsQty; trial++)
            {
                foreach (var selected in randomSelector.TakeRandom(Range(0, elementsQty), toSelectQty, timesChosen.Length))
                {
                    timesChosen[selected]++;
                }
            }

            var avg = timesChosen.Average();
            var max = timesChosen.Max();
            var min = timesChosen.Min();
            var allowedDifference = expectedCount / elementsQty;
            var countInRange      = timesChosen.Count(i => i >= expectedCount - allowedDifference && i <= expectedCount + allowedDifference);

            // Assert
            AssertBetween(avg, expectedCount - 2, expectedCount + 2, "Average");
            Assert.True(countInRange >= inRangeQty, string.Format("Not enough were in range: {0}", countInRange));
        }
示例#2
0
        static void Main(string[] args)
        {
            List <string> stringList = new List <string>
            {
                "Bike", "Train", "Boat", "Feet"
            };

            List <Person> personList = new List <Person> {
                new Person("Ted"),
                new Person("Ira"),
                new Person("Ada"),
                new Person("Lea")
            };

            List <int> intList = new List <int> {
                5, 10, 15, 20
            };

            RandomSelector <string> stringSelector = new RandomSelector <string>(stringList);
            RandomSelector <Person> personSelector = new RandomSelector <Person>(personList);
            RandomSelector <int>    intSelector    = new RandomSelector <int>(intList);

            string choice = "";

            while (choice != "q")
            {
                Console.WriteLine("Random string: " + stringSelector.Select().ToString());
                Console.WriteLine("Random person: " + personSelector.Select().ToString());
                Console.WriteLine("Random integer: " + intSelector.Select().ToString());
                Console.Write("Again? Enter to continue, q to quit: ");
                choice = Console.ReadLine();
            }
        }
示例#3
0
        public void ZeroSizeUtilityListSelectTest()
        {
            var uList = new List <Utility>();
            var s     = new RandomSelector();

            Assert.That(s.Select(uList), Is.EqualTo(-1));
        }
示例#4
0
 public Human(CivilizationManager civilManager, string name, HumanSex sex)
 {
     CivilManager  = civilManager;
     Name          = name;
     Sex           = sex;
     DieAge        = RandomSelector.GetRandomDouble(CivilManager.GetSystem <SocialSystem>().Config.MaximumAge);
     _stateMachine = new HumanStateMachine(this);
 }
示例#5
0
        public void CloneTest()
        {
            var s = new RandomSelector();

            Assert.IsNotNull(s);
            var sc = s.Clone();

            Assert.IsNotNull(sc);
        }
示例#6
0
        public void When_running_then_complete_until_sucess_or_failure()
        {
            var s = new RandomSelector(new Helper().RunningTwiceThenSuccess(), new Helper().RunningTwiceThenSuccess(), new Helper().RunningTwiceThenSuccess());

            s.Behave();
            s.Behave();
            s.Behave();

            Assert.AreEqual(BehaviourReturnCode.Success, s.ReturnCode);
        }
示例#7
0
        public void When_completed_then_new_task_starts()
        {
            var s = new RandomSelector(new Helper().RunningTwiceThenSuccess(), new Helper().RunningTwiceThenSuccess(), new Helper().RunningTwiceThenSuccess());

            s.Behave();
            s.Behave();
            s.Behave();
            s.Behave();

            Assert.AreEqual(BehaviourReturnCode.Running, s.ReturnCode);
        }
        private ConcurrentQueue <Candidate> getRandomCandidates(List <Candidate> candList)
        {
            ConcurrentQueue <Candidate> participants = new ConcurrentQueue <Candidate>();

            Parallel.For(0, TournamentSize, i => {
                int index = RandomSelector.Next(0, candList.Count() - 1);
                participants.Enqueue(candList[index]);
            });

            return(participants);
        }
示例#9
0
        public static BComponent BuildComponent(XmlNode xmlDoc, BComponent parent, Behaviors behavior)
        {
            string name = xmlDoc.Name;

            if (ActionBool.NAME == name)
            {
                return(ActionBool.Build(xmlDoc, parent, behavior));
            }
            else if (ActionProperty.NAME == name)
            {
                return(ActionProperty.Build(xmlDoc, parent, behavior));
            }
            else if (ActionVoid.NAME == name)
            {
                return(ActionVoid.Build(xmlDoc, parent, behavior));
            }
            else if (ActionEnumerator.NAME == name)
            {
                return(ActionEnumerator.Build(xmlDoc, parent, behavior));
            }
            else if (RandomSelector.NAME == name)
            {
                return(RandomSelector.Build(xmlDoc, parent, behavior));
            }
            else if (RootSelector.NAME == name)
            {
                return(RootSelector.Build(xmlDoc, parent, behavior));
            }
            else if (Selector.NAME == name)
            {
                return(Selector.Build(xmlDoc, parent, behavior));
            }
            else if (Sequence.NAME == name)
            {
                return(Sequence.Build(xmlDoc, parent, behavior));
            }
            else if (Inverter.NAME == name)
            {
                return(Inverter.Build(xmlDoc, parent, behavior));
            }
            else if (UntilTrue.NAME == name)
            {
                return(UntilTrue.Build(xmlDoc, parent, behavior));
            }
            else if (UntilFalse.NAME == name)
            {
                return(UntilFalse.Build(xmlDoc, parent, behavior));
            }
            else
            {
                Debug.LogErrorFormat("I did not find the item: {0}", name);
                return(null);
            }
        }
示例#10
0
        private List <Candidate> getRandomCandidates(List <Candidate> candList)
        {
            List <Candidate> participants = new List <Candidate>();

            for (int i = 0; i < TournamentSize; i++)
            {
                int index = RandomSelector.Next(0, candList.Count() - 1);
                participants.Add(candList[index]);
            }
            return(participants);
        }
示例#11
0
            public void AnItemIsReturned()
            {
                var itemList = new List <int>()
                {
                    1, 2, 3
                };
                var selector = new RandomSelector <int>(new Random(), itemList);

                var next = selector.PeekNext();

                Assert.True(itemList.Contains(next));
            }
示例#12
0
        public void SelectTest([Range(-1, 21, 1)] int selIdx)
        {
            var rn = new MockRandom();

            rn.IntValue = selIdx;
            var uList = SelectorTestsHelper.CreateRandomUtilityList(20);
            var s     = new RandomSelector(rn);

            var aIdx = s.Select(uList);
            var cIdx = selIdx.Clamp(0, 19);

            Assert.That(aIdx, Is.EqualTo(cIdx));
        }
示例#13
0
        internal static ICollectionSelector InitializeContentManager(TestContext testContext)
        {
            string                sourceFolder             = string.Empty;
            string                targetFolder             = string.Empty;
            bool                  reportsCreated           = false;
            List <string>         scenarioList             = null;
            string                runtimeResourcesSelector = null;
            List <BadCombination> badCombinations          = null;
            List <ReportWeight>   reportsWeight            = null;

            Logging.Log("Initialize Content for the test");

            // Get runtime parameters
            LoadContextProperty(testContext, SharedConstants.SourceReportFolderKey, ref sourceFolder);
            LoadContextProperty(testContext, SharedConstants.TargetReportFolderKey, ref targetFolder);
            LoadContextProperty(testContext, SharedConstants.ScenarioListKey, ref scenarioList);
            LoadContextProperty(testContext, SharedConstants.RuntimeResourcesSelectorKey, ref runtimeResourcesSelector);
            LoadContextProperty(testContext, SharedConstants.InitializedResourcesKey, ref reportsCreated);
            LoadContextProperty <List <BadCombination> >(testContext, SharedConstants.BadCombinationsKey, ref badCombinations);
            LoadContextProperty <List <ReportWeight> >(testContext, SharedConstants.ReportsWeightKey, ref reportsWeight);

            ICollectionSelector itemSelector = null;

            if (String.IsNullOrEmpty(runtimeResourcesSelector))
            {
                itemSelector = new RandomSelector();
            }
            else
            {
                if (runtimeResourcesSelector.Equals("random", StringComparison.InvariantCultureIgnoreCase))
                {
                    itemSelector = new RandomSelector();
                }
                else
                {
                    itemSelector = new SequentialSelector();
                }
            }

            foreach (string scenario in scenarioList)
            {
                IContentManager contentManager = ContentManagerFactory.GetInstance(scenario);
                contentManager.Initialize(scenario, scenario);
                contentManager.ItemSelector = itemSelector;
                contentManager.PopulateReportListFromServer();
                contentManager.BadReportMethodCombinations = badCombinations;
                contentManager.ReporstWeight = reportsWeight;
            }

            return(itemSelector);
        }
示例#14
0
        public override bool InitializeSystem()
        {
            HumanSex sex            = RandomSelector.GetRandomEnumValue <HumanSex>();
            var      family1Husband = HumanRecords.CreateRecord(null, RandomSelector.GetRandomName(HumanSex.Male), HumanSex.Male);
            var      family1Wife    = HumanRecords.CreateRecord(null, RandomSelector.GetRandomName(HumanSex.Female), HumanSex.Female);

            var family2Husband = HumanRecords.CreateRecord(null, RandomSelector.GetRandomName(HumanSex.Male), HumanSex.Male);
            var family2Wife    = HumanRecords.CreateRecord(null, RandomSelector.GetRandomName(HumanSex.Female), HumanSex.Female);

            MarriageRecords.CreateRecord(family1Husband.Human as Man, family1Wife.Human as Woman);
            MarriageRecords.CreateRecord(family2Husband.Human as Man, family2Wife.Human as Woman);

            return(base.InitializeSystem());
        }
        private void fillBreedingPool(ConcurrentQueue <RouletteResult> results)
        {
            var TempBreeginPool = new ConcurrentQueue <Candidate>();

            Parallel.For(0, selectionSize, i => {
                double randomRouletteNumber;
                randomRouletteNumber = RandomSelector.NextDouble();
                Candidate temp       = FindCandidate(results, randomRouletteNumber);
                if (temp != null)
                {
                    TempBreeginPool.Enqueue(temp);
                }
            });
            BreedingPool = TempBreeginPool.ToList();
        }
示例#16
0
        private static void randomMethodCalls()
        {
            Console.WriteLine("-- Random Method Calls --");

            //add actions to the selector
            var selector = RandomSelector
                           .Add(() => { Console.WriteLine("do first thing"); })
                           .Add(() => { Console.WriteLine("do other thing"); });

            for (int i = 0; i < 5; i++)
            {
                selector.Choose(); //randomly picks an action to run
            }

            Console.WriteLine();
        }
        public override void Enter()
        {
            SocialSystem socialSystem = Controlled.CivilManager.GetSystem <SocialSystem>();

            var   suitableWomen = socialSystem.GetSuitableWomenForMarriage((Man)Controlled);
            bool  accepted      = false;
            Woman selectedWife  = null;

            while (!accepted && suitableWomen.Count > 0)
            {
                selectedWife = RandomSelector.SelectRandomSample(suitableWomen);
                suitableWomen.Remove(selectedWife);
                accepted = selectedWife.ResponseForMarriageProposal((Man)Controlled);
            }

            base.Enter();
        }
示例#18
0
        private static void weightedRandomMethodCalls()
        {
            Console.WriteLine("-- Weighted Random Method Calls --");

            //add actions to the selector (must add up to 1.0)
            var selector = RandomSelector
                           .Add(0.7, () => { Console.WriteLine("0.7 - probably do this"); })
                           .Add(0.2, () => { Console.WriteLine("0.2 - maybe do this"); })
                           .Add(0.1, () => { Console.WriteLine("0.1 - small chance of this"); });

            for (int i = 0; i < 5; i++)
            {
                selector.Choose(); //randomly picks an action to run
            }

            Console.WriteLine();
        }
示例#19
0
            public void WhenCalledMultipleTimesTheSameItemIsReturned()
            {
                var itemList = new List <int>()
                {
                    1, 2, 3
                };
                var random = new Mock <Random>();

                random.SetupSequence(r => r.Next(It.IsAny <int>())).Returns(0).Returns(2);
                var selector = new RandomSelector <int>(random.Object, itemList);

                var first  = selector.PeekNext();
                var second = selector.PeekNext();

                Assert.AreEqual(first, itemList[0]);
                Assert.AreEqual(second, first);
            }
示例#20
0
		public void test_1(){
			_log.enterScope ();

			RandomSelector rs = new RandomSelector (new BehaviorAction(component_1),
				new BehaviorAction(component_2),
				new BehaviorAction(component_3),
				new BehaviorAction(component_4));


			for (int i = 0; i < 100000; i++)
				rs.Behave ();

			_log.logMessage ("1:" + counts[0] +", 2:" + counts[1]+ ", 3:" + counts[2]+ ", 4:" + counts [3]);

			Verify.VerifyTrue ("verify last component actioned", true, counts [3] > 0);

			_log.exitScope ();
		}
示例#21
0
        private static void weightedGeneric()
        {
            Console.WriteLine("-- Weighted Random Return Values --");

            //add actions to the selector (must add up to 1.0)
            var selector = RandomSelector <int>
                           .Add(0.7, 1)
                           .Add(0.2, 2)
                           .Add(0.1, 3);

            for (int i = 0; i < 5; i++)
            {
                var val = selector.Choose(); //randomly picks an action to run
                Console.WriteLine("chose " + val);
            }

            Console.WriteLine();
        }
示例#22
0
        public void ProduceBaby()
        {
            SocialSystem socialSystem = CivilManager.GetSystem <SocialSystem>();

            var marriageRecord = socialSystem.MarriageRecords.GetRecord(this);
            var dieRecord      = socialSystem.DieRecords.GetRecord(this);

            if (marriageRecord == null || marriageRecord.RecordState == RecordState.Obselete ||
                dieRecord != null)
            {
                return;
            }

            HumanSex childSex  = RandomSelector.GetRandomEnumValue <HumanSex>();
            string   childName = RandomSelector.GetRandomName(childSex);

            socialSystem.HumanRecords.CreateRecord(marriageRecord, childName, childSex);
        }
示例#23
0
            public void WhenCalledMultipleTimesItemsAreRandom()
            {
                var itemList = new List <int>()
                {
                    1, 2, 3
                };
                var random = new Mock <Random>();

                random.SetupSequence(r => r.Next(It.IsAny <int>())).Returns(0).Returns(2).Returns(1);
                var selector = new RandomSelector <int>(random.Object, itemList);

                var first  = selector.GetNext();
                var second = selector.GetNext();
                var third  = selector.GetNext();

                Assert.AreEqual(first, itemList[0]);
                Assert.AreEqual(second, itemList[2]);
                Assert.AreEqual(third, itemList[1]);
            }
示例#24
0
        /// <summary>
        /// Reproduction process
        /// </summary>
        private void Reproduce()
        {
            RandomSelector <Species> selector = new RandomSelector <Species>();

            foreach (Species s in AllSpecies)
            {
                selector.Add(s, s.Score);
            }

            foreach (Client c in AllClients)
            {
                if (c.Species == null)
                {
                    Species s = selector.Random();
                    c.Genome = s.Breed();
                    s.ForcePut(c);
                }
            }
        }
        private void fillBreedingPool(List <RouletteResult> results)
        {
            var    TempBreedingPool = new List <Candidate>();
            double randomRouletteNumber;

            for (int i = 0; i < selectionSize; i++)
            {
                randomRouletteNumber = RandomSelector.NextDouble();
                Candidate temp = FindCandidate(results, randomRouletteNumber);
                if (temp != null)
                {
                    TempBreedingPool.Add(temp);
                }
                else
                {
                    i--;
                }
            }
            BreedingPool = TempBreedingPool.ToList();
        }
示例#26
0
        static void Main(string[] args)
        {
            IEnumerable <AMenu> menus = new List <AMenu>()
            {
                new 국밥(),
                new 돈까스(),
                new 라면(),
                new 스파게티()
            };

            ISelectable selectable = new HighPriceSelector();

            Console.WriteLine(new MenuSelector(menus, selectable).GetMenu().Explain());

            selectable = new LowPriceSelector();
            Console.WriteLine(new MenuSelector(menus, selectable).GetMenu().Explain());

            selectable = new RandomSelector();
            Console.WriteLine(new MenuSelector(menus, selectable).GetMenu().Explain());
        }
示例#27
0
        public void test_1()
        {
            _log.enterScope();

            RandomSelector rs = new RandomSelector(new BehaviorAction(component_1),
                                                   new BehaviorAction(component_2),
                                                   new BehaviorAction(component_3),
                                                   new BehaviorAction(component_4));


            for (int i = 0; i < 100000; i++)
            {
                rs.Behave();
            }

            _log.logMessage("1:" + counts[0] + ", 2:" + counts[1] + ", 3:" + counts[2] + ", 4:" + counts [3]);

            Verify.VerifyTrue("verify last component actioned", true, counts [3] > 0);

            _log.exitScope();
        }
示例#28
0
    public void chooseOption()
    {
        StatusWindowText.text = "The Enemy is Contemplating...";

        int[]       rootWeights = { 40, 40, 20 };
        List <Node> level2      = new List <Node>();
        List <Node> level3_1    = new List <Node>();
        List <Node> level3_2    = new List <Node>();

        level2.Add(new Call(basicAttack));
        level3_1.Add(new Call(debuffDefense));
        level3_2.Add(new Call(shoot));
        level2.Add(new If(playerBuffedDefense, level3_1));
        level2.Add(new IfInt(enoughSP, 10, level3_2));
        RandomSelector Root = new RandomSelector(3, level2, rootWeights);

        /*Current implementation: First check if player buffed defense.  If yes, debuff defense defense.  If no, attack
         */

        //if (PlayerStats.GetComponent<UnitStats>().defense > 10)
        //{
        //    CombatStateMachine.GetComponent<CombatStateM>().movePower = 0;
        //    PlayerStats.GetComponent<UnitStats>().defense = PlayerStats.GetComponent<UnitStats>().defense / 2;
        //    StatusWindowText.text = "The enemy screeched, lowering your defense";
        //}
        //else
        //{
        //    CombatStateMachine.GetComponent<CombatStateM>().movePower = 5;
        //    StatusWindowText.text = "The enemy strikes";

        //}

        if (Root.Evaluate() == Node.NodeStates.SUCCESS)
        {
            CombatStateMachine.GetComponent <CombatStateM>().currState = CombatStateM.CombatState.EnemyCombat;
        }
    }
示例#29
0
        public void RandomSelector_Normal_Test()
        {
            int length   = 10;
            int attempts = 1000;

            //на большом числе проходов мы "убеждаемся" что получены все числа от 0...length-1
            //Тест не-дерерминирован, и на самом деле интеграционный

            Dictionary <int, object> randomResults = new Dictionary <int, object>();

            var selector = new RandomSelector();

            for (int i = 0; i < attempts; i++)
            {
                int result = selector.GetRandomIndex(length);
                randomResults[result] = null;
            }

            //теперь проверка что все варианты "вошли" в набор
            for (int i = 0; i < length; i++)
            {
                Assert.IsTrue(randomResults.ContainsKey(i), $"Очікувалося що в результаті буде {i}");
            }
        }
示例#30
0
        /// <summary>
        /// Solves the problem using a GA.
        /// </summary>
        /// <param name="problem"></param>
        /// <returns></returns>
        protected override IRoute DoSolve(OsmSharp.Tools.Math.TSP.Problems.IProblem problem)
        {
            //int population_size = 10;
            //if (problem.Size < 100)
            //{
            //    population_size = System.Math.Max(problem.Size * 3, 10);
            //    if (problem.Size < 10)
            //    {
            //        population_size = 1;
            //    }
            //}
            //if (problem.Size < 1000)
            //{
            //    population_size = problem.Size / 4;
            //}

            // create the settings.
            SolverSettings settings = new SolverSettings(
                _stagnation_count,
                _population,
                1000000000,
                _eltism,
                _cross,
                _mutation);

            //List<IMutationOperation<List<int>, GeneticProblem, Fitness>> mutators = new List<IMutationOperation<int,GeneticProblem,Fitness>>();
            ////mutators.Add(new DefaultMutationOperation());
            ////mutators.Add(new BestPlacementMutationOperation());
            //mutators.Add(new BestDetailedPlacementMutationOperation());
            //List<double> probabilities = new List<double>();
            //probabilities.Add(1);
            ////probabilities.Add(0.5);
            ////probabilities.Add(0.3);

            //CombinedMutation<List<int>, GeneticProblem, Fitness> mutation = new CombinedMutation<int,GeneticProblem,Fitness>(
            //    StaticRandomGenerator.Get(),
            //    mutators,
            //    probabilities);

            ////SequentialContructiveCrossoverOperator cross_over = new SequentialContructiveCrossoverOperator();
            //BestDetailedPlacementCrossOverOperation cross_over = new BestDetailedPlacementCrossOverOperation();
            ////BestPlacementCrossOverOperation cross_over = new BestPlacementCrossOverOperation();
            ////EdgeRecombinationCrossOverOperation cross_over = new EdgeRecombinationCrossOverOperation();

            //BestPlacementGenerationOperation generation = new BestPlacementGenerationOperation();
            ////RandomGenerationOperation generation = new RandomGenerationOperation();
            ISelector<List<int>, GeneticProblem, Fitness> selector = new RandomSelector<List<int>, GeneticProblem, Fitness>();
            //ISelector<List<int>, GeneticProblem, Fitness> selector = new TournamentBasedSelector<List<int>, GeneticProblem, Fitness>(75, 0.01);
            solver =
                new Solver<List<int>, GeneticProblem, Fitness>(
                    new GeneticProblem(problem),
                    settings,
                    selector,
                    _mutation_operation,
                    _cross_over_operation,
                    _generation_operation,
                    new FitnessCalculator(),
                    true, false);

            solver.NewFittest += new Solver<List<int>, GeneticProblem, Fitness>.NewFittestDelegate(solver_NewFittest);
            solver.NewGeneration += new Solver<List<int>, GeneticProblem, Fitness>.NewGenerationDelegate(solver_NewGeneration);
            List<int> result = new List<int>(solver.Start(null).Genomes);
            result.Insert(0, 0);
            return new SimpleAsymmetricRoute(result, true);
        }
示例#31
0
 public void DrawInspector(RandomSelector node)
 {
     EditorGUILayout.LabelField(new GUIContent("Random Selector"), TitleStyle);
     EditorGUILayout.Space ();
     if (node.ChildCount > 0) {
         float chance = 100f / node.ChildCount;
         EditorGUILayout.LabelField(new GUIContent("Each child has a " + chance.ToString ("F1") + "% chance of being selected."), SubtitleStyle);
     }
     string message = "The Random Selector sends the tick signal to one of its children, selected at random, and returns the state returned by that child.";
     EditorGUILayout.HelpBox(message, MessageType.Info);
     EditorGUILayout.HelpBox("Not yet implemented!", MessageType.Error);
 }
示例#32
0
文件: DungeonMap.cs 项目: himapo/ccm
        /// <summary>
        /// 消えた部屋につながっていた袋小路の処理
        /// </summary>
        /// <param name="room"></param>
        void ProcessDeadEnd(DungeonRoom room)
        {
            var deadends = new List<DungeonPath>();

            UpdateAccessibility();

            foreach (var portal in room.Portals)
            {
                if (portal.ConnectedPaths.Count == 0)
                    continue;

                var path = portal.ConnectedPaths[0];

                if (path.Accessible)
                {
                    // 袋小路をリストアップ
                    deadends.Add(path);
                }
                else
                {
                    // 孤立している通路は消す
                    RemovePath(path);
                }
            }

            var selector = new RandomSelector<DeadEndDisposal>(Rand);
            selector.Add(40, DeadEndDisposal.CONNECT);
            selector.Add(55, DeadEndDisposal.REMOVE);
            selector.Add(5, DeadEndDisposal.LEAVE);

            while (deadends.Count > 0)
            {
                var disposal = selector.Get();

                if (disposal == DeadEndDisposal.CONNECT && deadends.Count >= 2)
                {
                    var another = Rand.Next(1, deadends.Count);

                    var portals = new DungeonPortal[2]{
                        deadends[0].GetTerminalPortal(),
                        deadends[another].GetTerminalPortal()
                    };

                    var path = GeneratePath(
                        portals[0],
                        portals[1],
                        IsHorizontalPortals(portals[0], portals[1])
                        );

                    if (path != null)
                    {
                        AddPath(path);
                        deadends.RemoveAt(another);
                    }
                    deadends.RemoveAt(0);

                }
                else if (disposal == DeadEndDisposal.REMOVE)
                {
                    RemovePath(deadends[0]);
                    deadends.RemoveAt(0);
                }
                else if (disposal == DeadEndDisposal.LEAVE)
                {
                    deadends.RemoveAt(0);
                }
            }

        }
示例#33
0
        private static BT CreateStreetBT(DataModel d)
        {
            Sequence wander = new Sequence {
                new While(
                    new Sequence {
                    new RandomSelector
                    {
                        new Sequence         //wandersteer
                        {
                            new SetMovementSpeed(d, false),
                            new Wander(d),
                            new RandomWait(0.5f, 1.0f)
                        },
                        new Sequence         //move to poi
                        {
                            new SetMovementSpeed(d, false),
                            new SetTarget(d, PointType.Interest, PointList.GetRandomPoint),
                            new Seek(d, x => x.Target),
                            new RandomWait(0.5f, 1.0f)
                        }
                    }
                },
                    new Sequence
                {
                }
                    )
            };

            Sequence attack = new Sequence
            {
                new ReloadWeapon(d),
                new UseItem(d),
                new CausePanic(d),
                new Wait(1f),
                new Succeeder(new While
                              (
                                  new CanSeeTarget(d, true),
                                  new Seek(d, x => x.Target)
                              )),
            };

            Selector equipWeapon = new Selector //Equiping a weapon
            {
                new IsWeaponEquipped(d),        //If NPC has a weapon, do nothing else equip
                new Sequence
                {
                    new EquipRandomWeapon(d),
                    new Wait(3f)
                }
            };

            While runIntoRange = new While( //movetotarget
                new Sequence
            {
                new IsWithinWeaponsRange(d, true),
                // new CanSeeTarget(d, true)
            },
                new Seek(d, x => x.Target) //If the target is not visable, seek the target.
                );

            RandomSelector selectTarget = new RandomSelector
            {
                new SetTarget(d),
                new SetTarget(d, true)
            };

            Sequence canAttack = new Sequence //use conditions
            {
                new IsWithinWeaponsRange(d),
                new IsTargetAlive(d),
                new TurnToFaceTarget(d, 180),
            };

            Sequence flee = new Sequence //run away
            {
                new SetMovementSpeed(d, true),
                new SetTarget(d, PointType.Despawn, PointList.GetSafestPoint),
                new Succeeder(new Seek(d, x => x.Target)),
                new Despawn(d)
            };

            Sequence rootSelector = new Sequence
            {
                new While(
                    new IsPanicking(d), //panic
                    flee
                    ),
                new Sequence {
                    new While(       //Continues as long as everthing returns true
                        new Sequence //Step 1. If NPC is hostile continue
                    {
                        new IsHostile(d),
                        new CanAttack(d)
                    },
                        new Sequence                   //Step 2, starting attack
                    {
                        new SetMovementSpeed(d, true), //Allows npc to run
                        new While(new IsTargetAlive(d, true), selectTarget),
                        equipWeapon,
                        runIntoRange,
                        new While(

                            canAttack,
                            new Repeater(attack, true)
                            ),
                    }
                        )
                },
                wander,
            };

            return(new BT(rootSelector));
        }
示例#34
0
        /// <summary>
        /// Solves the problem using a GA.
        /// </summary>
        /// <param name="problem"></param>
        /// <returns></returns>
        protected override IRoute DoSolve(OsmSharp.Math.TSP.Problems.IProblem problem)
        {
            //int population_size = 10;
            //if (problem.Size < 100)
            //{
            //    population_size = System.Math.Max(problem.Size * 3, 10);
            //    if (problem.Size < 10)
            //    {
            //        population_size = 1;
            //    }
            //}
            //if (problem.Size < 1000)
            //{
            //    population_size = problem.Size / 4;
            //}

            // create the settings.
            SolverSettings settings = new SolverSettings(
                _stagnation_count,
                _population,
                1000000000,
                _eltism,
                _cross,
                _mutation);

            //List<IMutationOperation<List<int>, GeneticProblem, Fitness>> mutators = new List<IMutationOperation<int,GeneticProblem,Fitness>>();
            ////mutators.Add(new DefaultMutationOperation());
            ////mutators.Add(new BestPlacementMutationOperation());
            //mutators.Add(new BestDetailedPlacementMutationOperation());
            //List<double> probabilities = new List<double>();
            //probabilities.Add(1);
            ////probabilities.Add(0.5);
            ////probabilities.Add(0.3);

            //CombinedMutation<List<int>, GeneticProblem, Fitness> mutation = new CombinedMutation<int,GeneticProblem,Fitness>(
            //    StaticRandomGenerator.Get(),
            //    mutators,
            //    probabilities);

            ////SequentialContructiveCrossoverOperator cross_over = new SequentialContructiveCrossoverOperator();
            //BestDetailedPlacementCrossOverOperation cross_over = new BestDetailedPlacementCrossOverOperation();
            ////BestPlacementCrossOverOperation cross_over = new BestPlacementCrossOverOperation();
            ////EdgeRecombinationCrossOverOperation cross_over = new EdgeRecombinationCrossOverOperation();

            //BestPlacementGenerationOperation generation = new BestPlacementGenerationOperation();
            ////RandomGenerationOperation generation = new RandomGenerationOperation();
            ISelector <List <int>, GeneticProblem, Fitness> selector = new RandomSelector <List <int>, GeneticProblem, Fitness>();

            //ISelector<List<int>, GeneticProblem, Fitness> selector = new TournamentBasedSelector<List<int>, GeneticProblem, Fitness>(75, 0.01);
            solver =
                new Solver <List <int>, GeneticProblem, Fitness>(
                    new GeneticProblem(problem),
                    settings,
                    selector,
                    _mutation_operation,
                    _cross_over_operation,
                    _generation_operation,
                    new FitnessCalculator(),
                    true, false);

            solver.NewFittest += new Solver <List <int>, GeneticProblem, Fitness> .NewFittestDelegate(solver_NewFittest);

            solver.NewGeneration += new Solver <List <int>, GeneticProblem, Fitness> .NewGenerationDelegate(solver_NewGeneration);

            List <int> result = new List <int>(solver.Start(null).Genomes);

            result.Insert(0, 0);
            return(new SimpleAsymmetricRoute(result, true));
        }