Example #1
0
        private Particle2D SpawnParticle()
        {
            Particle2D particle = new Particle2D(_textures[_randomEx.Next(_textures.Count)])
            {
                LifeTime        = TimeSpan.FromSeconds(_randomEx.Next((int)StartLifeTimeMin.TotalSeconds, (int)StartLifeTimeMax.TotalSeconds)),
                Position        = Position,
                Velocity        = new Vector2(_randomEx.NextFloat(StartVelocityMultiplyMin, StartVelocityMultiplyMax), _randomEx.NextFloat(StartVelocityMultiplyMin, StartVelocityMultiplyMax)),
                Angle           = _randomEx.NextFloat(StartAngleMin, StartAngleMax),
                AngularVelocity = _randomEx.NextFloat(StartAngularVelocityMin, StartAngularVelocityMax),
                Scale           = _randomEx.NextFloat(StartScaleMin, StartScaleMax)
            };

            return(particle);
        }
Example #2
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);
        }
Example #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);
        }
Example #4
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);
        }
Example #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);
        }
Example #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);
        }
Example #7
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);
        }
Example #8
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);
        }
Example #9
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);
        }
Example #10
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)]);
        }
Example #11
0
        /// <summary>
        /// 乱序输出一个列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static IEnumerable <T> Shuffle <T>(this IEnumerable <T> source)
        {
            var elements = source.ToArray();

            for (int i = elements.Length - 1; i > 0; i--)
            {
                int swapIndex = RandomEx.Next(i + 1);
                yield return(elements[swapIndex]);

                elements[swapIndex] = elements[i];
            }

            yield return(elements[0]);
        }
Example #12
0
        private Deck[] ChooseRandomDecks()
        {
            var decks = DeckLibrary.ReadDecks().ToList();

            var first = decks[RandomEx.Next(0, decks.Count)];

            var decksWithSameRating = decks
                                      .Where(x => x.Rating == first.Rating)
                                      .ToList();

            var second = decksWithSameRating[RandomEx.Next(0, decksWithSameRating.Count)];

            return(new[] { first, second });
        }
Example #13
0
        private List <CardInfo> GeneratePack(Dictionary <string, int> settings)
        {
            var  cards      = new Dictionary <string, CardInfo>();
            bool hasMythics = _mythics.Count > 0;

            for (var i = 0; i < settings["Rares"]; i++)
            {
                CardInfo random;
                do
                {
                    var isMythic = RandomEx.Next(8) == 0;

                    if (hasMythics && isMythic)
                    {
                        random = GetRandomMythic();
                    }
                    else
                    {
                        random = GetRandomRare();
                    }
                } while (cards.ContainsKey(random.Name));

                cards.Add(random.Name, random);
            }

            for (var i = 0; i < settings["Uncommons"]; i++)
            {
                CardInfo random;
                do
                {
                    random = GetRandomUncommon();
                } while (cards.ContainsKey(random.Name));

                cards.Add(random.Name, random);
            }

            for (var i = 0; i < settings["Commons"]; i++)
            {
                CardInfo random;
                do
                {
                    random = GetRandomCommon();
                } while (cards.ContainsKey(random.Name));

                cards.Add(random.Name, random);
            }

            return(cards.Values.ToList());
        }
Example #14
0
        public override void Initialize()
        {
            IsSaved = true;

            if (_deck == null)
            {
                _deck = new Deck {
                    Name = NewDeckName
                };
                SelectedCard = null;
                IsNew        = true;
                return;
            }

            SelectedCard = _deck[RandomEx.Next(_deck.CardCount)];
        }
Example #15
0
        public void RotateApiKeys()
        {
            if (etherscanApiKeys.IsNullOrEmpty())
            {
                etherscanApiKeys = new string[] { etherscanApiKey }
            }
            ;

            if (infuraApiKeys.IsNullOrEmpty())
            {
                infuraApiKeys = new string[] { infuraApiKey }
            }
            ;

            etherscanApiKey = etherscanApiKeys[RandomEx.Next(0, etherscanApiKeys.Length)];
            infuraApiKey    = infuraApiKeys[RandomEx.Next(0, infuraApiKeys.Length)];
        }
Example #16
0
        private List <TournamentMatch> CreateSwissPairings()
        {
            var pairings = _players
                           .OrderByDescending(x => x.MatchPoints)
                           .ThenBy(x => RandomEx.Next(0, _players.Count))
                           .ToArray();

            var matches = new List <TournamentMatch>();

            for (var i = 0; i < pairings.Length; i = i + 2)
            {
                var player1 = pairings[i];
                var player2 = pairings[i + 1];

                matches.Add(new TournamentMatch(player1, player2));
            }
            return(matches);
        }
Example #17
0
        public static Deck GetBestDeck(List <Deck> decks)
        {
            var bestDecks = decks
                            .Select((x, i) => new NumberedDeck {
                Number = i + 1, Deck = x
            })
                            .OrderBy(x => RandomEx.Next())
                            .ToList();

            var round = 1;

            while (bestDecks.Count > 1)
            {
                NumberedDeck bye = null;

                if (bestDecks.Count % 2 != 0)
                {
                    bye = bestDecks[0];
                    bestDecks.RemoveAt(0);
                }

                Console.WriteLine("Round {0}", round);
                Console.WriteLine("--------------------------------");

                bestDecks = PlayOneRound(bestDecks);

                Console.WriteLine();

                if (bye != null)
                {
                    bestDecks.Add(bye);
                }

                round++;
            }

            return(bestDecks[0].Deck);
        }
Example #18
0
        public string GetNext()
        {
            if (_photoPath == null)
            {
                lock (InstSync)
                {
                    if (_photoPath == null)
                    {
                        var path = ScreenSaverConfigure.Instance.PhotoPath;
                        _photoPath = Directory.GetFiles(path).Where(
                            s => Regex.IsMatch(s, @"(\.bmp|\.png|\.jpg|\.jpeg|\.jpe|\.gif|\.tif|\.tiff)$", RegexOptions.IgnoreCase)).ToArray();
                    }
                }
            }

            if (_photoPath.Length == 0)
            {
                return(string.Empty);
            }

            var index = Random.Next() % _photoPath.Length;

            return(_photoPath[index]);
        }
Example #19
0
 public static string GetRandom()
 {
     return(Messages[RandomEx.Next(Messages.Length)]);
 }
Example #20
0
 public static string GetRandomName(this HttpPostedFile file)
 {
     return
         ($"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}{RandomEx.Next(100, 999)}{Path.GetExtension(file.FileName)}");
 }
Example #21
0
        static IAsyncPolicy <HttpResponseMessage> GetRetryPolicy()
        {
            return(HttpPolicyExtensions
                   .HandleTransientHttpError()
                   .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
                   .WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2,
                                                                                       retryAttempt)) + +TimeSpan.FromMilliseconds(RandomEx.Next(0, 100))

                                      ));
        }
Example #22
0
 private CardInfo GetRandomMythic()
 {
     return(new CardInfo(_mythics[RandomEx.Next(0, _mythics.Count)], Rarity.M, Name));
 }
Example #23
0
 private CardInfo GetRandomRare()
 {
     return(new CardInfo(_rares[RandomEx.Next(0, _rares.Count)], Rarity.R, Name));
 }
Example #24
0
 private CardInfo GetRandomUncommon()
 {
     return(new CardInfo(_uncommons[RandomEx.Next(0, _uncommons.Count)], Rarity.U, Name));
 }
Example #25
0
 public int CalculateHash(HashCalculator calc)
 {
     return(RandomEx.Next());
 }
Example #26
0
        public static MagicSet RandomSet()
        {
            var sets = Sets.Values.ToList();

            return(sets[RandomEx.Next(sets.Count)]);
        }
        public static async Task <bool> Vpnx()
        {
            using (var client = new HttpClient()
            {
                Timeout = TimeSpan.FromMinutes(60), MaxResponseContentBufferSize = int.MaxValue
            })
            {
                var address = $"0x{RandomEx.NextHexString(40)}";
                var apiKEY  = "Y5BJ5VA3XZ59F63XQCQDDUWU2C29144MMM";

                var url1 = $"https://api-rinkeby.etherscan.io/api?apikey={apiKEY}&module=account&action=balance&tag=latest&address={address}";

                var balance   = client.GET <Etherscan>(new Uri(url1), System.Net.HttpStatusCode.OK, true, ("Accept", "application/json"), ("Content-type", "application/json"));
                var list      = client.GET <VpnxList>(new Uri("https://api.sentinelgroup.io/client/vpn/list"), System.Net.HttpStatusCode.OK);
                var available = client.GET <VpnxAvailable>(new Uri("https://api.sentinelgroup.io/swaps/available"), System.Net.HttpStatusCode.OK);
                var content   = new StringContent($"{{\"account_addr\": \"{address}\"}}", encoding: Encoding.UTF8);
                var usage     = await client.POST <VpnxUsage>("https://api.sentinelgroup.io/client/vpn/usage", content, System.Net.HttpStatusCode.OK, true,
                                                              ("accept", "application/json"),
                                                              ("Accept-Encoding", "gzip, deflate"),
                                                              ("Accept-Language", "en-US"),
                                                              ("Connection", "keep-alive"),
                                                              ("Host", "api.sentinelgroup.io"),
                                                              ("Origin", "null"),
                                                              ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Sentinel/0.0.41 Chrome/59.0.3071.115 Electron/1.8.7 Safari/537.36"),
                                                              ("X-DevTools-Request-Id", $"{RandomEx.Next(1000,10000)}.{RandomEx.Next(100, 1000)}"));

                if ((await balance).message == "OK" && (await list).success && (await available).success && usage.success)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
Example #28
0
 public TournamentPlayer(string name, bool isHuman, int?avatarId = null)
 {
     Name     = name;
     IsHuman  = isHuman;
     AvatarId = avatarId ?? RandomEx.Next();
 }
Example #29
0
 public ViewModel(IEnumerable <TournamentPlayer> participants)
 {
     _participants.AddRange(participants.Rotate(
                                RandomEx.Next(participants.Count())));
 }
Example #30
0
 /// <summary>
 /// 生成一个随机文件名,带扩展名
 /// </summary>
 /// <param name="file"></param>
 /// <returns></returns>
 public static string GetRandomName(this IFormFile file, bool containExtension = true)
 {
     return
         ($"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}{RandomEx.Next(100, 999)}{(containExtension? Path.GetExtension(file.FileName):"")}");
 }