Пример #1
0
        private void Start()
        {
            randomContentPicker = new DynamicRandomSelector <GameObject>();
            randomContentItems.ForEach(item => randomContentPicker.Add(item.contentToSpawn, item.weight));
            randomContentPicker.Build();

            var        picked         = randomContentPicker.SelectRandomItem();
            GameObject spawnedContent = Instantiate(picked, transform.position, Quaternion.identity, contentParent.transform);
        }
Пример #2
0
        private void Awake()
        {
            _selector = new DynamicRandomSelector <ItemRarity>();

            var index = 0;

            foreach (var pair in itemRarity)
            {
                _selector.Add(pair.Key, pair.Value);

                index++;
            }

            _selector.Build((int)seed);
        }
Пример #3
0
        void TestDynamicSelector()
        {
            //seed = 42, expected number of item = 32
            DynamicRandomSelector <float> selector = new DynamicRandomSelector <float>(42, 32);

            // add items
            for (int i = 0; i < 32; i++)
            {
                selector.Add(i, Mathf.Sqrt(i + 1));
            }

            // Build internals
            // pair (item, unnormalized probability)
            selector.Build();

            string print = "";

            for (int i = 0; i < 100; i++)
            {
                print += i.ToString() + " " + selector.SelectRandomItem() + "\n";
            }

            Debug.Log(print);

            /// LONG version, to test binary search

            //we can just keep adding new members
            for (int i = 0; i < 1024; i++)
            {
                selector.Add(i, Mathf.Sqrt(i));
            }

            //do not forget to (re)build
            selector.Build();

            //just test it this way
            for (int i = 0; i < 10000; i++)
            {
                selector.SelectRandomItem();
            }
            // wont print long version, would spam console too much
        }
Пример #4
0
        private void Awake()
        {
            // Spawn the start room
            Instantiate(startRoom, transform.position, Quaternion.identity, transform);

            // Don't forget to call .Build, otherwise the picker isn't initialised.
            randomBottom = new DynamicRandomSelector <GameObject>();
            bottomRooms.ForEach(item => randomBottom.Add(item.roomTemplate, item.weight));
            randomBottom.Build();

            randomTop = new DynamicRandomSelector <GameObject>();
            topRooms.ForEach(item => randomTop.Add(item.roomTemplate, item.weight));
            randomTop.Build();

            randomRight = new DynamicRandomSelector <GameObject>();
            rightRooms.ForEach(item => randomRight.Add(item.roomTemplate, item.weight));
            randomRight.Build();

            randomLeft = new DynamicRandomSelector <GameObject>();
            leftRooms.ForEach(item => randomLeft.Add(item.roomTemplate, item.weight));
            randomLeft.Build();
        }
Пример #5
0
        private void OnDeserialized(StreamingContext context)
        {
            if (!(context.Context is ActionHandler handler))
            {
                return;
            }
            var actions = _additionalData["actions"].ToObject <List <JToken> >();

            _actions = new DynamicRandomSelector <BaseAction>();
            Message  = "No action to randomize from";
            foreach (var action in actions)
            {
                if (handler.GetAction((string)action["type"], action["action"], out var baseAction))
                {
                    var weight = (float)(action["weight"] ?? 1.0F);
                    _actions.Add(baseAction, weight);
                }
            }

            if (_actions.Count > 0)
            {
                _actions.Build();
            }
        }
Пример #6
0
        /// <summary>
        /// Main application logic
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // keep a running timer for phrase activation/inactivation
            runningTime.Start();

            // Read in the phrases
            using (TextFieldParser csvParser = new TextFieldParser("phrases.csv"))
            {
                csvParser.CommentTokens = new string[] { "#" };
                csvParser.SetDelimiters(new string[] { "," });
                csvParser.HasFieldsEnclosedInQuotes = true;

                // Skip the row with the column names
                csvParser.ReadLine();

                while (!csvParser.EndOfData)
                {
                    // Read current line fields, pointer moves to the next line.
                    string[] fields = csvParser.ReadFields();
                    phrases.Add(new Phrase
                    {
                        Message             = fields[0],
                        Weight              = int.Parse(fields[1]),
                        ActivateTimeInMin   = fields.Length > 2 && !string.IsNullOrWhiteSpace(fields[2]) ? int.Parse(fields[2]) : 0,
                        InactivateTimeInMin = fields.Length > 3 && !string.IsNullOrWhiteSpace(fields[3]) ? int.Parse(fields[3]) : (int?)null,
                        AudioFile           = fields.Length > 4 && !string.IsNullOrWhiteSpace(fields[4]) ? fields[4] : null
                    });
                }
            }

            // Read in config
            using (StreamReader r = new StreamReader("config.json"))
            {
                string json = r.ReadToEnd();
                cfg = JsonConvert.DeserializeObject <Configuration>(json);
            }

            // Setup voice
            Dictionary <string, int> countCheck  = new Dictionary <string, int>();
            SpeechSynthesizer        synthesizer = new SpeechSynthesizer
            {
                Volume = cfg.Volume,    // 0...100
                Rate   = cfg.SpeechRate // -10...10
            };

            // Chose the voice once here in case they don't want random voice option
            synthesizer.SelectVoice(synthesizer.GetInstalledVoices().OrderBy(x => Guid.NewGuid()).FirstOrDefault().VoiceInfo.Name);

            // Build the random phrase selector
            var selector = new DynamicRandomSelector <Phrase>();

            foreach (var phrase in phrases)
            {
                countCheck.Add(phrase.Message, 0);
                selector.Add(phrase, phrase.Weight);
            }
            selector.Build();

            bool   isValidSelection;
            Phrase selection = null;

            // Begin speaking
            while (true)
            {
                // Choose a random voice if needed
                if (cfg.RandomizeVoice)
                {
                    synthesizer.SelectVoice(synthesizer.GetInstalledVoices().OrderBy(x => Guid.NewGuid()).FirstOrDefault().VoiceInfo.Name);
                }
                isValidSelection = false;

                // Make sure the selected phrase is valid for the current game time
                while (!isValidSelection)
                {
                    selection = selector.SelectRandomItem();
                    if (runningTime.Elapsed.TotalMinutes > selection.ActivateTimeInMin &&
                        (selection.InactivateTimeInMin == null || runningTime.Elapsed.TotalMinutes < selection.InactivateTimeInMin))
                    {
                        isValidSelection = true;
                    }
                }

                // Print the phrase
                Console.WriteLine(selection);
                // Speak the phrase
                if (selection.AudioFile != null)
                {
                    using (var audioFile = new AudioFileReader(selection.AudioFile))
                        using (var outputDevice = new WaveOutEvent())
                        {
                            outputDevice.Init(audioFile);
                            outputDevice.Play();
                            while (outputDevice.PlaybackState == PlaybackState.Playing)
                            {
                                Thread.Sleep(500);
                            }
                        }
                }
                else
                {
                    synthesizer.Speak(selection.Message);
                }

                // Wait before speaking the next phrase
                Thread.Sleep(cfg.IntervalInSec * 1000);
            }
        }