Exemplo n.º 1
0
        /// <summary>
        ///     在给定的列表中,挑选出指定个数的随机项<br/>
        ///     比如实现在src中,随机挑出5个并返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="src">随机数据源</param>
        /// <param name="randomCount">需要挑选出的个数,如果为0,则连挑选出的数量也是随机</param>
        /// <returns>返回随机挑选后的数据</returns>
        public static T[] Random <T>(this IList <T> src, int randomCount)
        {
            if (src == null || src.Count <= 0)
            {
                throw new ArgumentNullException("src");
            }

            if (randomCount == 0)
            {
                randomCount = RandomEx.Next(1, src.Count);
            }

            //var newlist = new List<T>(randomCount);

            var newlist = new T[randomCount];

            for (int i = 0; i < randomCount; i++)
            {
                var index = RandomEx.Next(0, src.Count);

                newlist[i] = src[index];
            }

            return(newlist);
        }
Exemplo n.º 2
0
        protected override Transform getPoint()
        {
            pointList.Clear();
            foreach (Transform c in points)
            {
                if (c.childCount > 0)
                {
                    continue;
                }
                if (c.gameObject.activeSelf == false)
                {
                    continue;
                }

                pointList.Add(c);
            }

            if (pointList.Count == 0)
            {
                return(null);
            }

            if (pointList.Count == 1)
            {
                return(pointList[0]);
            }

            return(RandomEx.weightedChoice(pointList, (x) => 1));
        }
Exemplo n.º 3
0
        public static string GenerateRandomName(IList <string> unitNames)
        {
            var first  = unitNames[RandomEx.Next(unitNames.Count)];
            var second = unitNames[RandomEx.Next(unitNames.Count)];

            return(first + " " + second);
        }
Exemplo n.º 4
0
        private List <DraftPlayer> CreatePlayers(int playerCount, CardRatings ratings, bool includeHumanPlayer)
        {
            var aiStrategies = new Func <IDraftingStrategy>[]
            {
                () => new Forcing(ratings),
                () => new Greedy(ratings),
            };

            var players = new List <DraftPlayer>();

            for (var i = 0; i < playerCount; i++)
            {
                players.Add(new DraftPlayer
                {
                    Strategy = aiStrategies[RandomEx.Next(10) >= 3 ? 0 : 1]()
                });
            }

            if (includeHumanPlayer)
            {
                players[0] = new DraftPlayer
                {
                    Strategy = _userInterface
                };
            }


            return(players);
        }
Exemplo n.º 5
0
        public void PlayRandom()
        {
            var decks = ChooseRandomDecks();

            try
            {
                var mp = MatchParameters.Default(
                    player1: new PlayerParameters
                {
                    Name     = YourName,
                    AvatarId = RandomEx.Next(),
                    Deck     = decks[0]
                },
                    player2: new PlayerParameters
                {
                    Name     = NameGenerator.GenerateRandomName(MediaLibrary.GetPlayerUnitNames()),
                    AvatarId = RandomEx.Next(),
                    Deck     = decks[1]
                },
                    isTournament: false
                    );

                Ui.Match = new Match(mp);
                Ui.Match.Start();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }


            Shell.ChangeScreen(this);
        }
Exemplo n.º 6
0
        public static T[] Random <T>(this IEnumerable <T> src, int randomCount)
        {
            var tList = src.ToList();

            if (src == null || tList.Count <= 0)
            {
                throw new ArgumentNullException("src");
            }

            if (randomCount == 0)
            {
                randomCount = RandomEx.Next(1, tList.Count);
            }

            var newlist = new T[randomCount];

            for (int i = 0; i < randomCount; i++)
            {
                var index = RandomEx.Next(0, tList.Count);

                newlist[i] = tList[index];
            }

            return(newlist);
        }
Exemplo n.º 7
0
        /// <summary>If the splash text contains '*' then they get replace with a random character else does nothing</summary>
        public void Update()
        {
            if (splashTexts[id].Contains("*"))
            {
                //Do the char swap thingy
                char[] chars = splashTexts[id].ToCharArray();
                text = "";
                for (int i = 0; i < chars.Length; i++)
                {
                    //Change
                    if (chars[i] == '*')
                    {
                        chars[i] = (char)RandomEx.GenerateRandom(0, 128);

                        //Anti space and escape chars
                        while (chars[i] == ' ' || IsEscapeChar(chars[i]))
                        {
                            chars[i] = (char)RandomEx.GenerateRandom(0, 128);
                        }
                    }

                    //Rebuild
                    text = text + chars[i];
                }
            }
        }
 private static IEnumerable <IAlbum> GetRandomAlbums(IReadOnlyList <IAlbum> albums, int count)
 {
     foreach (int index in RandomEx.NonRepeatableRandoms(0, albums.Count, count))
     {
         yield return(albums[index]);
     }
 }
Exemplo n.º 9
0
    public Vector3 spawnPointInsideOfBoundsForEnemySpec(EnemySpec spec)
    {
        var      targetSpawnPointCollection = spec.underwater ? SpawnPointsUnderWater : SpawnPointsAir;
        Collider spawnPointArea             = null;

        //find the corner that is tagged with the same enum as the group
        foreach (var collection in targetSpawnPointCollection)
        {
            foreach (Transform spawnPointTransform in collection.transform)
            {
                var spawnPoint = spawnPointTransform.gameObject;
                var spawnTag   = spawnPoint.GetComponent <EnemySpawnAreaTag>();
                if (spawnTag == null)
                {
                    Debug.LogError(spawnPoint.name + " does not ahave a spawntag!");
                    continue;
                }
                var corner = spawnTag.Corner;
                if (corner == spec.spawnCorner)
                {
                    spawnPointArea = spawnPoint.GetComponent <EnemySpawnAreaTag>().GetComponent <Collider>();
                }
            }
        }

        //null ref means that the air or watter pool wasn't taged with one of the enemy spawn area tags
        return(RandomEx.InsideBounds(spawnPointArea.bounds));
    }
Exemplo n.º 10
0
        public async Task <bool> StartMining(DBKey userId)
        {
            if (userId == GlobalDefine.INVALID_DBKEY)
            {
                return(false);
            }

            UserBasicData userBasicData = new UserBasicData();

            if (await userBasicData.FromDBAsync(userId) == false)
            {
                return(false);
            }

            lock (Items)
            {
                if (Items.ContainsKey(userId))
                {
                    return(false);
                }

                var miningData = new MiningData()
                {
                    UserId         = userId,
                    NextMiningTime = DateTime.UtcNow.AddSeconds(RandomEx.Range(MiningTimeRange.min.TotalSeconds, MiningTimeRange.max.TotalSeconds)),
                    LastMiningTime = DateTime.UtcNow,
                };
                miningData.RefreshSessionExpireTime();

                Items.Add(userId, miningData);
            }
            return(true);
        }
Exemplo n.º 11
0
    // Called in Health.cs by BroadcastMessage("Die")
    void Die()
    {
        int usedPos = 0;

        positions.Shuffle();

        for (byte i = 0; i < drops.Length && i < chance.Length; ++i)
        {
            if (RandomEx.GetEventWithChance(chance[i]))
            {
                if (drops[i] == null)
                {
                    Debug.LogError($"Can't spawn {drops[i]}, prefab is null");
                    continue;
                }

                GameObject go = Instantiate(drops[i], positions[usedPos].position, Quaternion.Euler(0, 0, Random.Range(0, 360)), transform.parent);

                Rigidbody2D objectRb = go.GetComponent <Rigidbody2D>();
                if (objectRb)
                {
                    objectRb.velocity        += rb.velocity;
                    objectRb.velocity        += (Vector2)positions[usedPos].localPosition.normalized * dropForce.GetRandomValue();
                    objectRb.angularVelocity += rb.angularVelocity;
                }

                ++usedPos;
            }
        }
    }
Exemplo n.º 12
0
 public void RandomInBytesTest()
 {
     byte[] bufferRandom         = null; // TODO: 初始化为适当的值
     byte[] bufferRandomExpected = null; // TODO: 初始化为适当的值
     RandomEx.RandomInBytes(ref bufferRandom);
     Assert.AreEqual(bufferRandomExpected, bufferRandom);
     Assert.Inconclusive("无法验证不返回值的方法。");
 }
Exemplo n.º 13
0
        public void CoinTossTestNullCheck()
        {
            // ReSharper disable once AssignNullToNotNullAttribute
            // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
            Action test = () => RandomEx.CoinToss(null);

            Assert.Throws <ArgumentNullException>(test);
        }
Exemplo n.º 14
0
        public void RandomOneTestNullCheck()
        {
            // ReSharper disable once AssignNullToNotNullAttribute
            // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
            Action test = () => RandomEx.RandomOne(null, "", "");

            test.ShouldThrow <ArgumentNullException>();
        }
 public void GenerateRoundInfo()
 {
     // Choose Correct Answer & Set Question Number Text
     answersList.Clear();
     answersList        = RandomEx.GetRandomNumbersList(maxAnswers);
     correctAnswerIndex = Random.Range(0, answersList.Count);
     EventManager.instance.TriggerEvent(MyEventType.RoundDataGenerated, null);
 }
Exemplo n.º 16
0
        public void Play()
        {
            SelectDeck.ViewModel selectDeck1 = null;
            SelectDeck.ViewModel selectDeck2 = null;

            var configuration1 = new Configuration
            {
                ScreenTitle    = "Select your deck",
                ForwardText    = "Next",
                PreviousScreen = this,
                Forward        = (deck1) =>
                {
                    if (selectDeck2 == null)
                    {
                        selectDeck2 = ViewModels.SelectDeck.Create(new Configuration
                        {
                            ScreenTitle    = "Select your opponent deck",
                            ForwardText    = "Start the game",
                            PreviousScreen = selectDeck1,
                            Forward        = (deck2) =>
                            {
                                try
                                {
                                    var mp = MatchParameters.Default(
                                        player1: new PlayerParameters
                                    {
                                        Name     = YourName,
                                        AvatarId = RandomEx.Next(),
                                        Deck     = deck1
                                    },
                                        player2: new PlayerParameters
                                    {
                                        Name     = NameGenerator.GenerateRandomName(MediaLibrary.GetPlayerUnitNames()),
                                        AvatarId = RandomEx.Next(),
                                        Deck     = deck2
                                    },
                                        isTournament: false);

                                    Ui.Match = new Match(mp);
                                    Ui.Match.Start();
                                }
                                catch (Exception ex)
                                {
                                    HandleException(ex);
                                }

                                Shell.ChangeScreen(this);
                            }
                        });
                    }

                    Shell.ChangeScreen(selectDeck2);
                }
            };

            selectDeck1 = ViewModels.SelectDeck.Create(configuration1);
            Shell.ChangeScreen(selectDeck1);
        }
Exemplo n.º 17
0
        public void RandomDoubleTest()
        {
            double expected = 0F; // TODO: 初始化为适当的值
            double actual;

            actual = RandomEx.RandomDouble();
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("验证此测试方法的正确性。");
        }
Exemplo n.º 18
0
        public void RandomBoolTest()
        {
            bool expected = false; // TODO: 初始化为适当的值
            bool actual;

            actual = RandomEx.RandomBool();
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("验证此测试方法的正确性。");
        }
Exemplo n.º 19
0
    private void MakeKast(float damageMultiper, float heal, float defence, int crit)
    {
        bool  critChance    = RandomEx.GetEventWithChance(crit);
        float currentDamage = this.currentMonster.Stats[(int)StatType.Attack];

        this.currentMonster.TakeDamage((critChance) ?(currentDamage * damageMultiper * 1.5f) : currentDamage *damageMultiper);

        this.currentMonster.Heal((critChance) ? heal * crit : heal);
    }
Exemplo n.º 20
0
    protected virtual void Update()
    {
        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

        cube.transform.position    = RandomEx.OnUnitSphere() * 5;
        cube.transform.localScale *= RandomEx.Value;

        GameObject.Destroy(cube, RandomEx.Range(0, 1.5f));
    }
Exemplo n.º 21
0
        protected PhotoScreenSaverBase(Window owner, Model3DGroup model3DGroup, double worldWidth, double worldHeight)
        {
            Random = RandomEx.Instance;

            Owner        = owner;
            Model3DGroup = model3DGroup;
            WorldWidth   = worldWidth;
            WorldHeight  = worldHeight;
        }
 public void ShowView(IColorCalculatorView view, bool showRandomPixel = false)
 {
     this.view = view;
     if (showRandomPixel)
     {
         var random = new RandomEx();
         view.SetPixel(random.NextPixel32());
     }
 }
Exemplo n.º 23
0
        protected void HandleException(Exception ex)
        {
            LogFile.Error(ex.ToString());
            SaveGame();

            var message = ErrorMessages[RandomEx.Next(ErrorMessages.Length)];

            Shell.ShowMessageBox(message,
                                 MessageBoxButton.OK, DialogType.Large, title: "Enraged Monkey Error", icon: MessageBoxImage.Error);
        }
Exemplo n.º 24
0
        public void RandomTest()
        {
            int iMaxValue = 0; // TODO: 初始化为适当的值
            int expected  = 0; // TODO: 初始化为适当的值
            int actual;

            actual = RandomEx.Random(iMaxValue);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("验证此测试方法的正确性。");
        }
Exemplo n.º 25
0
        /// <summary>
        ///RandomList 的测试
        ///</summary>
        public void RandomListTestHelper <T>()
        {
            List <T> listT    = null;       // TODO: 初始化为适当的值
            T        expected = default(T); // TODO: 初始化为适当的值
            T        actual;

            actual = RandomEx.RandomList <T>(listT);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("验证此测试方法的正确性。");
        }
Exemplo n.º 26
0
        /// <summary>
        ///RandomArray 的测试
        ///</summary>
        public void RandomArrayTestHelper <T>()
        {
            T[] arrayT   = null;       // TODO: 初始化为适当的值
            T   expected = default(T); // TODO: 初始化为适当的值
            T   actual;

            actual = RandomEx.RandomArray <T>(arrayT);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("验证此测试方法的正确性。");
        }
Exemplo n.º 27
0
        public async Task <IEnumerable <Amazon.Route53.Model.ResourceRecordSet> > ListResourceRecordSetsAsync(string zoneId, CancellationToken cancellationToken = default(CancellationToken))
        {
            var list = new List <Amazon.Route53.Model.ResourceRecordSet>();

            Amazon.Route53.Model.ListResourceRecordSetsResponse response = null;
            bool rateLimitExceeded = false;
            int  rateLimit         = 5000;

            do
            {
                try
                {
                    rateLimitExceeded = false;
                    response          = await _client.ListResourceRecordSetsAsync(
                        new Amazon.Route53.Model.ListResourceRecordSetsRequest()
                    {
                        StartRecordIdentifier = response?.NextRecordIdentifier,
                        StartRecordName       = response?.NextRecordName,
                        StartRecordType       = response?.NextRecordType,
                        HostedZoneId          = zoneId,
                        MaxItems = "1000",
                    }, cancellationToken);
                }
                catch (AmazonRoute53Exception ex)
                {
                    if (!(ex.Message ?? "").ToLower().Contains("rate exceeded"))
                    {
                        throw;
                    }
                    else
                    {
                        rateLimitExceeded = true;
                        await Task.Delay(rateLimit);

                        rateLimit += rateLimit + RandomEx.Next(1, 500);
                        continue;
                    }
                }

                if (!response.ResourceRecordSets.IsNullOrEmpty())
                {
                    list.AddRange(response.ResourceRecordSets);
                }

                if (!response.IsTruncated)
                {
                    break;
                }

                await Task.Delay(100);
            } while (rateLimitExceeded || response?.HttpStatusCode == System.Net.HttpStatusCode.OK);

            response.EnsureSuccess();
            return(list);
        }
Exemplo n.º 28
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public override bool IsDrop()
 {
     if (RandomEx.RandomDouble() * 100 < base.Probability * OneTreasure.DropGoldMultiplier)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemplo n.º 29
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public virtual bool IsDrop()
 {
     if (RandomEx.RandomDouble() * 100 < m_fProbability * OneTreasure.DropMultiplier)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemplo n.º 30
0
        public string GetPublicGethConnectionString()
        {
            publicGEthConnectionStrings = publicGEthConnectionStrings?.Where(x => !x.IsNullOrWhitespace())?.ToArray();

            if (publicGEthConnectionStrings.IsNullOrEmpty())
            {
                throw new Exception("publicGEthConnectionStrings were not defined in 'GEthManagerConfig.json'");
            }

            return(publicGEthConnectionStrings[RandomEx.Next(0, publicGEthConnectionStrings.Length)]);
        }