コード例 #1
0
        Contact GenerateContact(IModel m)
        {
            Random rng = new Random();

            MarkovNameGenerator firstNameGenerator = new MarkovNameGenerator(new List <string> {
                "Hans", "Peter", "Marie", "Maria", "Tina", "Tim", "Lukas", "Emma", "Tom", "Alina", "Mia", "Emma", "Siegfried", "Judith", "Karl", "Stefan", "Markus", "Martin", "Alfred", "Anton"
            }, 3, 5);
            string firstName = firstNameGenerator.NextName;

            List <string> additionalNames = new List <string>();

            for (int i = rng.Next(0, 3); i > 0; i--)
            {
                additionalNames.Add(firstNameGenerator.NextName);
            }

            MarkovNameGenerator lastNameGenerator = new MarkovNameGenerator(new List <string> {
                "Maier", "Meier", "Schmied", "Schmidt", "Schulz", "Roßman", "Müller", "Klein", "Fischer", "Schwarz", "Weber", "Hofman", "Hartman", "Braun", "Koch", "Krüger", "Schröder", "Wolf", "Mayer", "Jung", "Vogel", "Lang", "Fuchs", "Huber"
            }, 3, 5);
            string lastName = lastNameGenerator.NextName;

            DateTime start     = new DateTime(1950, 1, 1);
            int      range     = ((TimeSpan)(new DateTime(1995, 1, 1) - start)).Days;
            DateTime birthDate = start.AddDays(rng.Next(range));

            string emailAddress = string.Format("{0}.{1}@gmx.de", firstName, lastName);

            return(CreateContact(m, firstName, additionalNames, lastName, birthDate, emailAddress, "Deutschland", "Teststraße 27", "123456", "Testhausen"));
        }
コード例 #2
0
        /// <summary>
        /// Creates a name generator.
        /// </summary>
        /// <returns>The name generator.</returns>
        /// <param name="cultureId">Culture identifier.</param>
        INameGenerator CreateNameGenerator(string cultureId)
        {
            INameGenerator nameGenerator;
            Culture        culture = cultures[cultureId];

            List <List <string> > wordLists = culture.PlaceNameSchema.Split(' ').ToList()
                                              .Select(x => File.ReadAllLines(Path.Combine(ApplicationPaths.WordListsDirectory,
                                                                                          $"{x}.txt")).ToList())
                                              .ToList();

            if (culture.PlaceNameGenerator == Models.Enumerations.NameGenerator.RandomMixerNameGenerator && wordLists.Count == 2)
            {
                nameGenerator = new RandomMixerNameGenerator(wordLists[0], wordLists[1]);
            }
            else if (culture.PlaceNameGenerator == Models.Enumerations.NameGenerator.RandomMixerNameGenerator && wordLists.Count == 3)
            {
                nameGenerator = new RandomMixerNameGenerator(wordLists[0], wordLists[1], wordLists[2]);
            }
            else // Default: Markov
            {
                nameGenerator = new MarkovNameGenerator(wordLists[0]);
            }

            return(nameGenerator);
        }
コード例 #3
0
ファイル: Galaxy.cs プロジェクト: ArnautS/Aetheria-Economy
    private void GenerateNames(CultCache cache,
                               NameGeneratorSettings nameGeneratorSettings,
                               ref Random random,
                               Action <string> progressCallback = null)
    {
        for (var i = 0; i < Factions.Length; i++)
        {
            progressCallback?.Invoke($"Feeding Markov Chains: {i + 1} / {Factions.Length}");
            //if(progressCallback!=null) Thread.Sleep(250); // Inserting Delay to make it seem like it's doing more work lmao
            var faction = Factions[i];
            _nameGenerators[faction] = new MarkovNameGenerator(ref random, cache.Get <NameFile>(faction.GeonameFile).Names, nameGeneratorSettings);
        }

        // Generate zone name using the owner's name generator, otherwise assign catalogue ID
        foreach (var zone in Zones)
        {
            if (zone.Owner != null)
            {
                zone.Name = _nameGenerators[zone.Owner].NextName.Trim();
            }
            else
            {
                zone.Name = $"EAC-{random.NextInt(9999).ToString()}";
            }
        }
    }
コード例 #4
0
        public void Execute(Settlement settlement)
        {
            var nameGroup = gateway.All();
            var names     = nameGroup.SelectMany(x => x.Names);
            var gen       = new MarkovNameGenerator(names, Order);

            settlement.Name = gen.Generate(MaximumLength);
        }
コード例 #5
0
        public void ShouldBuildAStringBasedOnValuesNotToExceedASpecifiedLength()
        {
            var names = new string[] { "Alpha", "Bravo", "Charlie", "Delta" };
            var gen   = new MarkovNameGenerator(names, 1);
            var name  = gen.Generate(6);

            Assert.True(name.Length <= 6);
        }
コード例 #6
0
    void Start()
    {
        //namesFromFile = File.ReadAllLines("./Assets/Resources/Names.txt");// funktioniert so nicht im Build
        TextAsset nameAsset = Resources.Load("Names") as TextAsset;

        namesFromAsset = new List <string>(nameAsset.text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
        generator      = new MarkovNameGenerator(namesFromAsset, order, minLenght);
        for (int i = 0; i < 10; i++)
        {
            var name = generator.NextName;
            Debug.Log(name);
        }
    }
コード例 #7
0
 public CharacterSelectionScreen()
     : base()
 {
     nameGenerator = new MarkovNameGenerator(MarkovNameGenerator.SAMPLES, 3, 5);
     newCharacterOptions.AddRange(Enum.GetNames(typeof(PlayerTypes)));
     foreach (PlayerIndex playerIndex in Enum.GetValues(typeof(PlayerIndex)))
     {
         newCharacterOption.Add(playerIndex, 0);
         if (!selectedMenuIndex.ContainsKey(playerIndex))
         {
             selectedMenuIndex.Add(playerIndex, -1);
         }
     }
 }
コード例 #8
0
        // A generalized entity generator which assembles entities from random properties and tags
        // could be used for generating everything from randomized monsters to randomized agents with personalities
        public static GameAgent GenerateEntity()
        {
            GameAgent newEntity = new GameAgent();

            newEntity.T = new Dictionary <string, HashSet <string> >();
            newEntity.T.Add("Personality_hidden", new HashSet <string>());
            newEntity.T.Add("Personality", new HashSet <string>());
            // Ensure that the newly generated character has at least 4 traits.
            while (newEntity.T["Personality_hidden"].Count < 4)
            {
                newEntity.T["Personality_hidden"].Clear();
                foreach (List <string> currTags in PersonalityTags)
                {
                    int roll = rnd.Next(100);
                    if (roll > 94)
                    {
                        string newTrait = currTags.ToArray()[rnd.Next(currTags.Count)];
                        if (!newEntity.T["Personality_hidden"].Contains(newTrait))
                        {
                            if (roll > 98)
                            {
                                newTrait = "profoundly " + newTrait;
                            }
                            newEntity.T["Personality_hidden"].Add(newTrait);
                        }
                    }
                }
            }

            // Generate name based on gender
            string gender = GenderTypes.ToArray()[rnd.Next(GenderTypes.Count)];
            MarkovNameGenerator nameGenerator = gender == "Male" ?
                                                new MarkovNameGenerator(File.ReadAllLines(@"EntityLibrary\census-dist-male-first.csv"), 3, 1) :
                                                new MarkovNameGenerator(File.ReadAllLines(@"EntityLibrary\census-dist-female-first.csv"), 3, 1);
            string newName = nameGenerator.NextName;

            newEntity.S = new Dictionary <string, string>()
            {
                { "Class", CharacterTypes.ToArray()[rnd.Next(CharacterTypes.Count)] },
                { "Gender", gender },
                { "Name", newName }
            };
            newEntity.T.Add("Conditions", new HashSet <string>());

            // Add default judgements
            newEntity.Morals = DefaultJudgements.Judgements;

            return(newEntity);
        }
コード例 #9
0
 void Update()
 {
     if (Input.GetKey(KeyCode.KeypadEnter))
     {
         TextAsset nameAsset = Resources.Load("Names") as TextAsset;
         namesFromAsset = new List <string>(nameAsset.text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
         //namesFromAsset = new List<string>(nameAsset.text.Split(new[] { '\n', ','}));
         generator = new MarkovNameGenerator(namesFromAsset, order, minLength);
         for (int i = 0; i < 10; i++)
         {
             var name = generator.NextName;
             Debug.Log(name);
         }
     }
 }
コード例 #10
0
        public void OrderCanBeIncreasedToProvideMoreConsistencyOfTokens()
        {
            /*
             *  Given abacad with an order of 2
             *  Then we should generate tokens like
             *  __ => a, _a => b, ab => a, ba => c, ac => a, ca => d, ad
             */
            var names = new string[] { "abacad" };
            var gen   = new MarkovNameGenerator(names, 2);
            var tok   = gen.States.First(x => x.Key == "ab");

            Assert.NotNull(tok);
            Assert.Equal("a", tok.Tokens.Keys.First());

            //With this model, the only valid generation is the input string
            Assert.Equal("Abacad", gen.Generate(6));
        }
コード例 #11
0
ファイル: WorldController.cs プロジェクト: Cylindric/Sim
        // RemoteDebuggerService remoteDebugger;

        /// <summary>
        /// Called by Unity when the controller is created.
        /// We're using OnEnable() instead of Start() just to make sure it's ready before anything else.
        /// </summary>
        private void OnEnable()
        {
            MarkovNameGenerator.Initialise();

            if (Instance != null)
            {
                Debug.LogError("There shouldn't be an instance already!");
            }
            Instance = this;

            if (_loadWorld)
            {
                CreateWorldFromSave();
            }
            else
            {
                CreateEmptyWorld();
            }
        }
コード例 #12
0
        public void UsesASeedOfDataToBuildChainsInLowerCase()
        {
            /*
             * A => A
             * A => B
             * A => Terminator
             * B => A
             * B => B
             * B => C
             * C => Terminator
             */
            var names  = new string [] { "AAA", "ABA", "ABB", "ABC" };
            var gen    = new MarkovNameGenerator(names, 1);
            var aToken = gen.States.First(x => x.Key == "a");

            Assert.NotNull(aToken);
            Assert.Equal(3, aToken.Tokens.Keys.Count);
            Assert.Equal(3, aToken.Tokens["b"]); //Score for A=>B should be 3

            var bToken = gen.States.First(x => x.Key == "b");

            Assert.NotNull(bToken);
            Assert.Equal(4, bToken.Tokens.Keys.Count);
        }
コード例 #13
0
    void OnGUI()
    {
        ScriptableObject   target          = this;
        SerializedObject   so              = new SerializedObject(target);
        SerializedProperty stringsProperty = so.FindProperty("NameFiles");

        EditorGUILayout.PropertyField(stringsProperty, true); // True means show children
        so.ApplyModifiedProperties();                         // Remember to apply modified properties

        if (GUILayout.Button("Save Name Files"))
        {
            RegisterResolver.Register();
            var nameFilesDirectory = ActionGameManager.GameDataDirectory.CreateSubdirectory("NameFile");
            foreach (var nameFile in NameFiles)
            {
                var entry = new NameFile
                {
                    Name  = nameFile.name,
                    Names = nameFile.text.Split('\n')
                };
                File.WriteAllBytes(Path.Combine(nameFilesDirectory.FullName, $"{entry.ID.ToString()}.msgpack"), MessagePackSerializer.Serialize((DatabaseEntry)entry));
            }
        }

        nameFile               = (TextAsset)EditorGUILayout.ObjectField("Name File", nameFile, typeof(TextAsset), false);
        minWordLength          = EditorGUILayout.IntField("Minimum File Word Length", minWordLength);
        NameGeneratorMinLength = EditorGUILayout.IntField("Generated Minimum Word Length", NameGeneratorMinLength);
        NameGeneratorMaxLength = EditorGUILayout.IntField("Generated Maximum Word Length", NameGeneratorMaxLength);
        NameGeneratorOrder     = EditorGUILayout.IntField("Generator Order", NameGeneratorOrder);
        _stripNumberTokens     = GUILayout.Toggle(_stripNumberTokens, "Strip Number Tokens");

        if (GUILayout.Button("Clean Name File"))
        {
            var lines = nameFile.text.Split('\n');
            using StreamWriter outputFile = new StreamWriter(Path.Combine(Application.dataPath, nameFile.name + ".csv"));
            var names = new HashSet <string>();
            foreach (var line in lines)
            {
                var tokens = line.Split(',', ' ');
                foreach (var t in tokens)
                {
                    if (!HasNonASCIIChars(t))
                    {
                        var s = new string(t.Where(c => char.IsLetter(c) || c == '-' || c == '`' || c == '\'').ToArray()).Trim().Trim('`', '-');
                        if (s.Length >= minWordLength && !names.Contains(s))
                        {
                            names.Add(s);
                            outputFile.WriteLine(s);
                        }
                    }
                }
            }
        }

        if (GUILayout.Button("Process Name File") && nameFile != null)
        {
            var names = new HashSet <string>();
            var lines = nameFile.text.Split('\n');
            foreach (var line in lines)
            {
                foreach (var word in line.ToUpperInvariant().Split(' ', ',', '.', '"'))
                {
                    if (word.Length >= minWordLength && !names.Contains(word))
                    {
                        names.Add(word);
                    }
                }
            }
            Debug.Log($"Found {lines.Length} lines, with {names.Count} unique names!");
            var random = new Random(1337);
            _nameGenerator = new MarkovNameGenerator(ref random, names, NameGeneratorOrder, NameGeneratorMinLength, NameGeneratorMaxLength);
        }

        if (_nameGenerator != null)
        {
            if (GUILayout.Button("Generate Name"))
            {
                Debug.Log(_nameGenerator.NextName);
            }
        }
    }
コード例 #14
0
ファイル: Character.cs プロジェクト: Cylindric/Sim
        /* #################################################################### */
        /* #                        CONSTRUCTORS                              # */
        /* #################################################################### */

        public Character()
        {
            this._speed       = BaseMovementSpeed;
            this.Name         = MarkovNameGenerator.GetNextName("male") + ' ' + MarkovNameGenerator.GetNextName("last");
            this.CurrentState = State.Idle;
            _conditions       = new Dictionary <string, float> {
                { "energy", 1f }, { "health", 1f }, { "suit_air", 1f }
            };
            _timeSinceLastJobSearch = TimeBetweenJobSearches;

            // This Behaviour Tree handles the environmental state of this character.
            var environmentBehaviour = new BehaviourTreeBuilder()
                                       .Selector("breathe_or_flee")
                                       .Sequence("breathe")
                                       .Condition("breathable", t => CanBreathe_Condition())
                                       .Do("do_breathing", t => Breathe_Action(t.deltaTime))
                                       .Do("replenish_suit", t => ReplenishSuit_Action(t.deltaTime))
                                       .End()
                                       .Do("breathe_suit", t => BreatheSuit_Action(t.deltaTime))
                                       .Sequence("flee")
                                       .Do("find_safety", t => FindSafety_Action())
                                       .Do("flee", t => MoveTowardsDestination_Action(t.deltaTime))
                                       .End()
                                       .End()
                                       .Build();

            // This Behaviour Tree specifies the process for getting a job, fetching any materials it needs, and then executing that job.
            var jobBehaviour = new BehaviourTreeBuilder()
                               .Succeeder()
                               .Sequence("work")

                               // Fails if there are no jobs.
                               .Selector("get_job")
                               .Condition("have_a_job", t => DoesCharacterHaveAJob_Condition())
                               .Do("get_next_job", t => GetNextJob_Action(t.deltaTime)) // Fails if there are no jobs.
                               .End()

                               // Fails if no materials available
                               .Selector("get_materials")
                               .Condition("job_has_materials", t => JobHasAllNeedMaterials_Condition())
                               .Condition("am_carrying_materials", t => IsCarryingMaterials_Condition())
                               .Inverter().Do("find_material", t => FindRequiredStock_Action()).End()
                               .Inverter().Do("move_to_material", t => MoveTowardsDestination_Action(t.deltaTime)).End()
                               .Do("pickup_material", t => PickUpStock_Action())
                               .End()

                               // Succeeds when job complete
                               .Sequence("work_job")
                               .Do("movesetup_move_to_jobsite", t => SetupMoveToJobSite_Action())
                               .Do("move_to_jobsite", t => MoveTowardsDestination_Action(t.deltaTime))
                               .Do("drop_stock", t => TransferStockToJob_Action())
                               .Do("do_work", t => DoWork_Action(t.deltaTime))
                               .End()
                               .End()
                               .End()
                               .Build();

            var idleBehaviour = new BehaviourTreeBuilder()
                                .Selector("ensure_in_room")
                                .Condition("is_in_room", t => AmIndoors_Condition())
                                .Inverter("").Do("find_nearrest_room", t => FindNearestRoom_Action(t.deltaTime)).End()
                                .Do("move_to_room", t => MoveTowardsDestination_Action(t.deltaTime))
                                .End()
                                .Build();

            // Combine all the BTs.
            _tree = new BehaviourTreeBuilder()
                    .Sequence("worker")
                    .Do("drain_suit", t => DrainSuit_Action(t.deltaTime))
                    .Splice(environmentBehaviour)
                    .Splice(jobBehaviour)
                    .Splice(idleBehaviour)
                    .End()
                    .Build();
        }