Next() public method

Returns a nonnegative random number.
public Next ( ) : int
return int
Beispiel #1
0
        public CharWithType GetChar()
        {
            charType type = (charType)4;

            char charToReturn = availableChars[rnd.Next(availableChars.Length)];

            foreach (charType t in types)
            {
                if (LOWERCASE.Contains(charToReturn))
                {
                    type = charType.lowerCase;
                    break;
                }
                else if (UPPERCASE.Contains(charToReturn))
                {
                    type = charType.upperCase;
                    break;
                }
                else if (SPECIAL.Contains(charToReturn))
                {
                    type = charType.special;
                    break;
                }
                else if (NUMBER.Contains(charToReturn))
                {
                    type = charType.number;
                    break;
                }
            }

            return(new CharWithType(charToReturn, type));
        }
Beispiel #2
0
        public void SerialAddGetAll()
        {
            var rnd = new CryptoRandom();
            // using 2 BVectors cause of the extensive length required
            BVector d  = new BVector();
            BVector d2 = new BVector();

            for (ushort i = 0; i < ushort.MaxValue; i++)
            {
                if (i % 2 == 0)
                {
                    d.SerialAdd(i);
                    d.Add1(rnd.Next(100) < 50);
                }
                else
                {
                    d2.SerialAdd(i);
                    d2.Add1(rnd.Next(100) < 50);
                }
            }

            for (ushort i = 0; i < ushort.MaxValue; i++)
            {
                if (i % 2 == 0)
                {
                    Assert.AreEqual(d.SerialGet(), i);
                    d.Get1();
                }
                else
                {
                    Assert.AreEqual(d2.SerialGet(), i);
                    d2.Get1();
                }
            }
        }
Beispiel #3
0
        public DbItem GetNextImageId(int?nLabel)
        {
            if (!nLabel.HasValue)
            {
                int nLabelIdx = m_random.Next(m_rgItemsByLabel.Count);
                nLabel = m_rgItemsByLabel.ElementAt(nLabelIdx).Key;
            }

            if (!m_rgLoadedIdx.ContainsKey(nLabel.Value))
            {
                m_rgLoadedIdx.Add(nLabel.Value, new List <int>());
            }

            List <int> rgLoadedIdx    = m_rgLoadedIdx[nLabel.Value];
            List <int> rgNotLoadedIdx = m_rgNotLoadedIdx[nLabel.Value];

            if (rgNotLoadedIdx.Count == 0)
            {
                rgLoadedIdx.Clear();
                rgNotLoadedIdx = m_rgItemsByLabel[nLabel.Value].Select(p => (int)p.Tag).ToList();
            }

            int    nIdx     = m_random.Next(rgNotLoadedIdx.Count);
            int    nMainIdx = rgNotLoadedIdx[nIdx];
            DbItem item     = m_rgItems[nMainIdx];

            rgNotLoadedIdx.RemoveAt(nIdx);
            rgLoadedIdx.Add(nMainIdx);

            return(item);
        }
Beispiel #4
0
        private void btnGenerateSequenceToFile_Click(object sender, EventArgs e)
        {
            if (!IsFilterOpen)
            {
                return;
            }

            string filename = FormHelper.SaveFileDlg(FormHelper.FiletypeFilters.SequenceFiles);

            if (!string.IsNullOrWhiteSpace(filename))
            {
                int randomNumber = rand.Next(50000);

                BigInteger randomIncrementValue = PrimeHelper.GetPreviousPrime(randomNumber);

                ByteGenerator.SequenceGenerator randomSequence = new ByteGenerator.SequenceGenerator(8, randomNumber, (int)randomIncrementValue);

                int           counter            = 0;
                int           maxElements        = filter.MaxElementsToHash / 2;
                List <string> elementsCollection = new List <string>();
                while (counter < maxElements)
                {
                    string nextElement = randomSequence.GetNext();
                    elementsCollection.Add(nextElement);
                    counter++;
                }

                File.WriteAllLines(filename, elementsCollection);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Gets the damage
        /// </summary>
        private int GetDamage(GameClient Client, GameClient TargetClient)
        {
            CryptoRandom Randomizer = new CryptoRandom();
            Weapon       Weapon     = Client.GetRoleplay().EquippedWeapon;

            int MinDamage = Weapon.MinDamage;
            int MaxDamage = Weapon.MaxDamage;

            int Damage = Randomizer.Next(MinDamage, MaxDamage);

            if (Client.GetRoleplay().Class.ToLower() == "gunner")
            {
                Damage += Randomizer.Next(1, 3);
            }

            if (Client.GetRoleplay().GangId > 1000)
            {
                if (GroupManager.HasGangCommand(Client, "gunner"))
                {
                    if (RoleplayManager.GenerateRoom(Client.GetHabbo().CurrentRoomId, false).TurfEnabled || GroupManager.HasJobCommand(TargetClient, "guide"))
                    {
                        Damage += Randomizer.Next(0, 2);
                    }
                }
            }

            return(Damage);
        }
        private int getAction(int nIteration, SimpleDatum sd, SimpleDatum sdClip, int nActionCount, TRAIN_STEP step)
        {
            if (step == TRAIN_STEP.NONE)
            {
                switch (m_state)
                {
                case STATE.EXPLORING:
                    return(m_random.Next(nActionCount));

                case STATE.TRAINING:
                    if (m_dfExplorationRate > m_dfEpsEnd)
                    {
                        m_dfExplorationRate -= m_dfEpsDelta;
                    }

                    if (m_random.NextDouble() < m_dfExplorationRate)
                    {
                        return(m_random.Next(nActionCount));
                    }
                    break;
                }
            }

            return(m_brain.act(sd, sdClip, nActionCount));
        }
Beispiel #7
0
    private void CreateApple()
    {
        var random = new CryptoRandom();
        var color  = AppleColor;

        foreach (var target in Targets)
        {
            if (Snake.Count + 1 == target)
            {
                color = GreenAppleColor;
            }
        }

        while (true)
        {
            Apple = new Vector2(random.Next(0, (int)Engine.Field.Size.x),
                                random.Next(0, (int)Engine.Field.Size.y));

            if (!Snake.Contains(Apple))
            {
                break;
            }
        }

        TweenColor.Begin(Engine.Field.Sprites[(int)Apple.x, (int)Apple.y].gameObject, DeltaTime, color);
    }
Beispiel #8
0
        public int?GetNext(SELECTION_TYPE type, bool bRemove = false)
        {
            if (m_rgItems.Count == 0)
            {
                return(null);
            }

            if (type == SELECTION_TYPE.SEQUENTIAL)
            {
                int nIdx = m_rgItems[m_nIdx].Index;

                m_nIdx++;
                if (m_nIdx >= m_rgItems.Count)
                {
                    m_nIdx = 0;
                }

                return(nIdx);
            }
            else
            {
                lock (m_objSync)
                {
                    int nCount = m_rgItems.Count;
                    if (nCount == 0)
                    {
                        return(null);
                    }

                    int nIdx = m_random.Next(nCount);
                    if (m_rgItems[nIdx] == null)
                    {
                        m_rgItems.RemoveAt(nIdx);
                        nCount = m_rgItems.Count;
                        if (nCount == 0)
                        {
                            return(null);
                        }

                        nIdx = m_random.Next(nCount);
                    }

                    int nFinalIdx = m_rgItems[nIdx].Index;

                    if (bRemove)
                    {
                        m_rgItems.RemoveAt(nIdx);
                    }

                    m_nIdx = nIdx + 1;
                    if (m_nIdx == m_rgItems.Count)
                    {
                        m_nIdx = 0;
                    }

                    return(nFinalIdx);
                }
            }
        }
Beispiel #9
0
        public static T GetRandomElement <T>(this IEnumerable <T> collection)
        {
            var random = _random.Next(collection.Count());

            var item = collection.ElementAt(random);

            return(item);
        }
Beispiel #10
0
        public void NextWithMax()
        {
            var rng = new CryptoRandom();

            Assert.LessOrEqual(rng.Next(int.MaxValue), int.MaxValue);
            Assert.LessOrEqual(rng.Next(10), 10);
            Assert.AreEqual(0, rng.Next(0));
        }
Beispiel #11
0
        /// <summary>
        /// Returns an image from a list of images.
        /// </summary>
        /// <param name="rgImages">Specifies the image list to select from.</param>
        /// <param name="nCount">Specifies the maximum count to use.</param>
        /// <param name="nIdx">Specifies the index to use when selecting sequentially or in pair selection.</param>
        /// <param name="random">Specifies the random number generator to use.</param>
        /// <param name="selectionMethod">Specifies the image selection method.</param>
        /// <param name="nLastIndex">Specifies the last index used.</param>
        /// <param name="nFixedIndex">Specifies the fixed index to use.</param>
        /// <param name="nImageIdx">Returns the image index used.</param>
        /// <returns></returns>
        public static SimpleDatum GetImage(SimpleDatum[] rgImages, int nCount, int nIdx, CryptoRandom random, IMGDB_IMAGE_SELECTION_METHOD selectionMethod, ref int nLastIndex, ref int nFixedIndex, out int nImageIdx)
        {
            if ((selectionMethod & IMGDB_IMAGE_SELECTION_METHOD.BOOST) == IMGDB_IMAGE_SELECTION_METHOD.BOOST)
            {
                IEnumerable <SimpleDatum> iQuery  = rgImages.Where(p => p != null && p.Boost > 0);
                List <SimpleDatum>        rgItems = new List <SimpleDatum>(iQuery);

                if (rgItems.Count > 0)
                {
                    if ((selectionMethod & IMGDB_IMAGE_SELECTION_METHOD.RANDOM) == IMGDB_IMAGE_SELECTION_METHOD.RANDOM)
                    {
                        nIdx = random.Next(rgItems.Count);
                    }

                    SimpleDatum sd = rgItems[nIdx];
                    nImageIdx = nIdx;

                    return(sd);
                }
            }

            if ((selectionMethod & IMGDB_IMAGE_SELECTION_METHOD.PAIR) == IMGDB_IMAGE_SELECTION_METHOD.PAIR)
            {
                nIdx = nLastIndex + 1;

                if (nIdx == nCount)
                {
                    nIdx = 0;
                }
            }
            else if ((selectionMethod & IMGDB_IMAGE_SELECTION_METHOD.RANDOM) == IMGDB_IMAGE_SELECTION_METHOD.RANDOM)
            {
                nIdx = random.Next(nCount);
            }
            else if (selectionMethod == IMGDB_IMAGE_SELECTION_METHOD.FIXEDINDEX)
            {
                nFixedIndex = nIdx;
            }
            else if ((selectionMethod & IMGDB_IMAGE_SELECTION_METHOD.CLEARFIXEDINDEX) == IMGDB_IMAGE_SELECTION_METHOD.CLEARFIXEDINDEX)
            {
                nFixedIndex = -1;
            }

            if (nFixedIndex >= 0)
            {
                nIdx = nFixedIndex;
            }

            if (nIdx >= rgImages.Length)
            {
                nIdx = nIdx % rgImages.Length;
            }

            nLastIndex = nIdx;
            nImageIdx  = nIdx;

            return(rgImages[nIdx]);
        }
Beispiel #12
0
        public void NextWithMax_Throws()
        {
            var rng = new CryptoRandom();

            // ReSharper disable ReturnValueOfPureMethodIsNotUsed
            Assert.Throws <ArgumentOutOfRangeException>(() => rng.Next(-1));
            Assert.Throws <ArgumentOutOfRangeException>(() => rng.Next(-12));
            // ReSharper restore ReturnValueOfPureMethodIsNotUsed
        }
Beispiel #13
0
        public void Next()
        {
            var rng = new CryptoRandom();

            // ReSharper disable ReturnValueOfPureMethodIsNotUsed
            Assert.DoesNotThrow(() => rng.Next());
            Assert.DoesNotThrow(() => rng.Next());
            // ReSharper restore ReturnValueOfPureMethodIsNotUsed
        }
Beispiel #14
0
    public async void Splat(AdditionalParameters ap)
    {
        if (_splatcount > 20)
        {
            return;
        }

        //r=1050
        //1050=baseradius * intervals
        int intervals = 9999;
        int radiusx = 1680 * r.Next(intervals + 1) / intervals + 1, radiusy = 1050 * r.Next(intervals + 1) / intervals + 1;

        _splatcount++;
        OverlayImage oi = new OverlayImage("splat.png", 255);

//        oi.TopMost = true;
        {
            //oi.ShowInTaskbar = false;

            int x = 1680 / 2 + r.Next(radiusx / 2) - r.Next(radiusx / 2) - 168;
            int y = 1050 / 2 + r.Next(radiusy / 2) - r.Next(radiusy / 2) - 149;

            oi.Location = new Point(x, y);
            await Task.Delay(1000 + r.Next(3000));

            int speed = 10 + r.Next(40);
            for (int i = 0; i < r.Next(50) + 150; i++)
            {
                oi.Location = new Point(oi.Location.X, oi.Location.Y + 1);
                await Task.Delay(speed);
            }
        }
        oi.Close();
        _splatcount--;
    }
        private MaeBiasAndVariance TestRecommendationSystem(out MaeBiasAndVariance[] mbvsByRatings)
        {
            var maeBC = new BlockingCollection <float> [5];

            for (var i = 0; i < maeBC.Length; i++)
            {
                maeBC[i] = new BlockingCollection <float>();
            }

            var biasBC = new BlockingCollection <float> [5];

            for (var i = 0; i < biasBC.Length; i++)
            {
                biasBC[i] = new BlockingCollection <float>();
            }

            Parallel.For(0, NumberOfTests, i =>
            {
                IUser user;
                do
                {
                    user = TestUsers[rng.Next(TestUsers.Count)];
                } while (user.Ratings.Count < 2);

                lock (user)
                {
                    var ratingIndex = rng.Next(user.Ratings.Count);
                    var rating      = user.Ratings[ratingIndex];

                    var originalRatings = user.Ratings;
                    user.Ratings        = user.Ratings.Where(r => r != rating).ToList();

                    var predictedRating = RecommendationSystem.Recommender.PredictRatingForArtist(user, Model, Artists, rating.ArtistIndex);
                    var error           = predictedRating - rating.Value;
                    biasBC[(int)rating.Value - 1].Add(error);
                    maeBC[(int)rating.Value - 1].Add(Math.Abs(error));

                    user.Ratings = originalRatings;

                    Write(string.Format("{0}\t{1}", predictedRating, rating.Value), false);

                    if (maeBC.Sum(bc => bc.Count) % writeFrequency == 0)
                    {
                        Write(string.Format("Test {0} with {1} ({2})", TestName, GetMaeBiasAndVariance(biasBC, maeBC), DateTime.Now), toFile: false);
                    }
                }
            });

            while (maeBC.Sum(bc => bc.Count) < NumberOfTests)
            {
            }

            return(GetMaeBiasAndVariance(out mbvsByRatings, biasBC, maeBC));
        }
Beispiel #16
0
        public void Next_minvalue_maxvalue()
        {
            var random = new CryptoRandom();
            int next = 0;
            Assert.DoesNotThrow(() => next = random.Next(20, 100));
            Assert.That(next, Is.GreaterThanOrEqualTo(20));
            Assert.That(next, Is.LessThan(100));

            next = 0;
            Assert.DoesNotThrow(() => next = random.Next(-40, -20));
            Assert.That(next, Is.GreaterThanOrEqualTo(-40));
            Assert.That(next, Is.LessThan(-20));
        }
Beispiel #17
0
        public void Next_maxvalue()
        {
            var random = new CryptoRandom();
            int next = -1;
            Assert.DoesNotThrow(() => next = random.Next(1000));
            Assert.That(next, Is.GreaterThanOrEqualTo(0));
            Assert.That(next, Is.LessThan(1000));

            next = -1;
            Assert.DoesNotThrow(() => next = random.Next(500));
            Assert.That(next, Is.GreaterThanOrEqualTo(0));
            Assert.That(next, Is.LessThan(500));
        }
Beispiel #18
0
        /// <summary>Adds the specified entity to the scene.</summary>
        /// <param name="entity">The entity to add to the scene.</param>
        public int AddEntity()
        {
            /*
             * DebugUtil.Assert(AtomicUtil.CAS(ref entity.m_Scene, this, null),
             *           "entity.m_Scene is not null!");*/

            EntityCounter = rnd.Next(0, int.MaxValue);
            while (m_Entities.Contains(EntityCounter))
            {
                EntityCounter = rnd.Next(0, int.MaxValue);
            }
            m_Entities.Add(EntityCounter);
            return(EntityCounter);
        }
Beispiel #19
0
        /// <summary>
        /// Gets the coins from the users dead body
        /// </summary>
        public int GetCoins(GameClient TargetClient, RoleplayBot Bot = null)
        {
            if (TargetClient != null && TargetClient.GetHabbo() != null)
            {
                if (TargetClient.GetHabbo().VIPRank > 1)
                {
                    return(0);
                }

                if (TargetClient.GetHabbo().Credits < 3)
                {
                    return(0);
                }
            }

            if (Bot != null)
            {
                int MinMoney = Convert.ToInt32(RoleplayData.GetData("bots", "minmoney"));
                int MaxMoney = Convert.ToInt32(RoleplayData.GetData("bots", "maxmoney"));

                if (MaxMoney == 0)
                {
                    return(0);
                }

                CryptoRandom Random = new CryptoRandom();
                return(Random.Next(MinMoney, (MaxMoney + 1)));
            }

            return(TargetClient.GetHabbo().Credits / 3);
        }
Beispiel #20
0
        public async Task <Item> OpenCrateAsync(Crate crate, User dbUser = null)
        {
            int cumulative = 0;
            int roll       = CryptoRandom.Next(1, Data.CrateItemOdds);

            if (crate.ItemOdds >= CryptoRandom.Roll())
            {
                foreach (var item in Data.CrateItems)
                {
                    cumulative += item.CrateOdds;

                    if (roll < cumulative)
                    {
                        if (dbUser != null)
                        {
                            await ModifyInventoryAsync(dbUser, crate.Name, -1);
                            await ModifyInventoryAsync(dbUser, item.Name);
                        }
                        return(item);
                    }
                }
            }
            else
            {
                if (dbUser != null)
                {
                    await ModifyInventoryAsync(dbUser, crate.Name, -1);
                    await ModifyInventoryAsync(dbUser, "Bullet");
                }
                return(Data.Items.First(x => x.Name == "Bullet"));
            }
            return(null);
        }
Beispiel #21
0
        public async Task <Food> AcquireFoodAsync(Type type, int weaponAccuracy, User dbUser = null)
        {
            if (type != typeof(Meat) && type != typeof(Fish))
            {
                throw new Exception("Invalid food type.");
            }

            if (CryptoRandom.Roll() <= weaponAccuracy)
            {
                int cumulative = 0;
                int sum        = type == typeof(Meat) ? Data.MeatAcquireOdds : Data.FishAcquireOdds;
                int roll       = CryptoRandom.Next(1, sum + 1);

                foreach (var item in type == typeof(Meat) ? (Food[])Data.Meat : Data.Fish)
                {
                    cumulative += item.AcquireOdds;
                    if (roll < cumulative)
                    {
                        if (dbUser != null)
                        {
                            await ModifyInventoryAsync(dbUser, item.Name);
                        }
                        return(item);
                    }
                }
                return(null);
            }
            else
            {
                return(null);
            }
        }
        public static int GeneratePlayerTorsoColor()
        {
            CryptoRandom random   = new CryptoRandom();
            int          randmode = random.Next(1, 8);

            return(randmode);
        }
Beispiel #23
0
 public void Next()
 {
     var random = new CryptoRandom();
     int next = -1;
     Assert.DoesNotThrow(() => next = random.Next());
     Assert.That(next, Is.GreaterThanOrEqualTo(0));
 }
        private void LauncherFormStylish_Load(object sender, EventArgs e)
        {
            try
            {
                //splash loader
                CryptoRandom rand      = new CryptoRandom();
                int          randColor = rand.Next(0, 3);

                if (randColor == 0)
                {
                    splashLabel.BackColor = Color.FromArgb(245, 135, 13);
                }
                else if (randColor == 1)
                {
                    splashLabel.BackColor = Color.FromArgb(255, 3, 2);
                }
                else if (randColor == 2)
                {
                    splashLabel.BackColor = Color.FromArgb(238, 154, 181);
                }

                launcherFormStylishInterface1.mapsBox.BackColor = Color.FromArgb(237, 237, 237);

                launcherFormStylishInterface1.launcherForm.SplashLabel = splashLabel;
                launcherFormStylishInterface1.launcherForm.InitForm();

                if (File.Exists(GlobalPaths.RootPath + "\\changelog.txt"))
                {
                    launcherFormStylishInterface1.changelogBox.Text = File.ReadAllText(GlobalPaths.RootPath + "\\changelog.txt");
                }

                if (File.Exists(GlobalPaths.RootPath + "\\README-AND-CREDITS.TXT"))
                {
                    launcherFormStylishInterface1.readmeBox.Text = File.ReadAllText(GlobalPaths.RootPath + "\\README-AND-CREDITS.TXT");
                }

                launcherFormStylishInterface1.versionLabel.Content        = Application.ProductVersion;
                launcherFormStylishInterface1.versionNovetusLabel.Content = GlobalVars.ProgramInformation.Version;

                ReadConfigValues(true);

                if (launcherFormStylishInterface1.playTab != null && launcherFormStylishInterface1.playTab.IsSelected)
                {
                    if (launcherFormStylishInterface1.mapsBox.Nodes.Count == 0)
                    {
                        launcherFormStylishInterface1.launcherForm.RefreshMaps();
                        launcherFormStylishInterface1.LoadMapDesc();
                    }
                }

                launcherFormStylishInterface1.ToggleServerOptions();

                LocalVars.launcherInitState = false;
                CenterToScreen();
            }
            catch (Exception ex)
            {
                GlobalFuncs.LogExceptions(ex);
            }
        }
Beispiel #25
0
        public void GenerateDamages()
        {
            if (Generated)
            {
                return;
            }

            switch (EffectGenerationType)
            {
            case EffectGenerationType.MaxEffects:
                Amount = BaseMaxDamages;
                break;

            case EffectGenerationType.MinEffects:
                Amount = BaseMinDamages;
                break;

            default:
            {
                var rand = new CryptoRandom();

                Amount = rand.Next(BaseMinDamages, BaseMaxDamages + 1);
            }
            break;
            }
        }
Beispiel #26
0
        /// <summary>
        /// Returns the next image in the Index set based on the selection criteria.
        /// </summary>
        /// <param name="type">Specifies the selection type (e.g. RANDOM, SEQUENTIAL).</param>
        /// <param name="nLabel">Optionally, specifies a label (default = null).</param>
        /// <param name="bBoosted">Optionally, specifies to query boosted images (default = false).</param>
        /// <param name="nDirectIdx">Optionally, specifies to query the image at this index (only applies when type = DIRECT).</param>
        /// <returns>The next image index is returned.</returns>
        public virtual int?GetNextImage(Index.SELECTION_TYPE type, int?nLabel = null, bool bBoosted = false, int nDirectIdx = -1)
        {
            if (m_nLoadLimit == 0)
            {
                Index idx = GetIndex(nLabel, bBoosted);
                return(idx.GetNext(type));
            }
            else
            {
                if (type != Index.SELECTION_TYPE.RANDOM)
                {
                    throw new Exception("Only RANDOM selections are valid when using LoadLimit > 0.");
                }

                if (nLabel.HasValue)
                {
                    throw new Exception("Label selections are not valid when using LoadLimit > 0");
                }

                if (bBoosted != false)
                {
                    throw new Exception("Boosted qeruies are not valid when using LoadLimit > 0.");
                }

                if (nDirectIdx != -1)
                {
                    throw new Exception("DirectIndex queries are not valid when using LoadLimit > 0.");
                }

                return(m_random.Next(m_nLoadLimit));
            }
        }
Beispiel #27
0
 public async Task <bool> RegisterSystem(SystemRegistration registration)
 {
     return(await Task.Run(() =>
     {
         lock (Sync)
         {
             if (registration.Id > 0)
             {
                 var storedRegistration = Repo.Read(registration.Id);
                 if (storedRegistration != null)
                 {
                     registration = storedRegistration;
                 }
             }
             if (registration.Id < 1)
             {
                 registration.Id = NextId;
                 NextId++;
             }
             if (registration.Port == 0)
             {
                 registration.Port = (ushort)Random.Next(5000, 65000);
             }
             if (registration.IpAddress == null)
             {
                 registration.IpAddress = UseLocalHost
                                        ? IpAddress.LocalHost
                                        : (IpAddress) new byte[] { Subnet[0], Subnet[1], Subnet[2], (byte)NextIp };
             }
             Logger?.WriteLine($"System Registration: Id = {registration.Id}, Name = {registration.Name} ");
             var createdregistration = Repo.Create(registration);
             return true;
         }
     }));
 }
Beispiel #28
0
        // Prepare for a shuffle
        public void Shuffle()
        {
            if (Locked || Count == 0)
            {
                return;
            }

            lock (cards)
            {
                var cardIds = new int[cards.Count];
                //var cardAliases = new ulong[cards.Count];
                var rnd          = new CryptoRandom();
                var posit        = new short[cards.Count];
                var availPosList = new List <short>(cards.Count);
                for (var i = 0; i < cards.Count; i++)
                {
                    //availPosList[i] = (short)i;
                    availPosList.Add((short)i);
                }
                for (int i = cards.Count - 1; i >= 0; i--)
                {
                    var availPos = rnd.Next(availPosList.Count);
                    var pos      = availPosList[availPos];
                    availPosList.RemoveAt(availPos);
                    cardIds[i] = cards[pos].Id;
                    //cardAliases[i] = cis[r].Visible ? ulong.MaxValue : Crypto.ModExp(cis[r].Key);
                    //cis[pos] = cis[i];
                    posit[i] = pos;
                }
                // move own cards to new positions
                DoShuffle(cardIds, posit);
                // Inform other players
                Program.Client.Rpc.Shuffled(Player.LocalPlayer, this, cardIds, posit);
            }
        }
Beispiel #29
0
        /// <summary>
        /// Creates a random date between the sent date range
        /// </summary>
        /// <param name="startDate">The start date</param>
        /// <param name="endDate">The end date</param>
        /// <returns>The generated date</returns>
        public static DateTime RandomDate(DateTime startDate, DateTime endDate)
        {
            //get milliseconds between dates
            TimeSpan duration = endDate.Subtract(startDate);

            if (duration.Ticks <= 0)
            {
                return(startDate);
            }
            //see if we can fit milliseconds to int
            bool usingMilliseconds = (duration.TotalMilliseconds < int.MaxValue + 0.5);
            bool usingSeconds      = false;

            //if not then try seconds
            if (!usingMilliseconds)
            {
                usingSeconds = (duration.TotalSeconds < int.MaxValue + 0.5);
            }
            //create span
            int span = (usingMilliseconds) ? Convert.ToInt32(duration.TotalMilliseconds) : (usingSeconds) ? Convert.ToInt32(duration.TotalSeconds) : Convert.ToInt32(duration.TotalMinutes);
            //use crypto random for more randomness
            var rand   = new CryptoRandom();
            var result = rand.Next(span);

            //add milliseconds and return
            return((usingMilliseconds) ? startDate.AddMilliseconds(result) : (usingSeconds) ? startDate.AddSeconds(result) : startDate.AddMinutes(result));
        }
        protected override Task Handle(LoginRequest packet, ISession session)
        {
            var userAccount = _accountService.GetByUsername(packet.Username);

            if (userAccount == null)
            {
                Thread.Sleep(
                    _rng.Next(
                        _hasherConfiguration.HashingMinimumTimeWait, _hasherConfiguration.HashingMaximumTimeWait));
                return(Failed(session));
            }

            var serverArgon2 = new Argon2Hasher(userAccount.EncodedHash);

            if (!serverArgon2.CheckString(packet.PasswordHash))
            {
                return(Failed(session));
            }

            var randomGuid = Guid.NewGuid();

            userAccount.SessionId           = randomGuid;
            userAccount.SessionIdExpiryDate = DateTime.UtcNow.AddMinutes(5d);
            _accountService.Save(userAccount);

            session.SendPacket(
                new LoginSucceeded
            {
                SessionId = randomGuid.ToString()
            });

            return(Task.CompletedTask);
        }
Beispiel #31
0
        public void Reader(string filePath)
        {
            var lineCount = 0;
            CryptoRandom rng = new CryptoRandom();
            HeightGen format = new HeightGen();

            using (var reader = File.OpenText(filePath))
            {
                while (reader.ReadLine() != null)
                {
                    lineCount++;
                }
            }

            int phrase = rng.Next(lineCount);
            string[] values = File.ReadAllText(filePath).Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            string outputString = values[phrase];
            if (VarStorage.Globals.percentDelta != "")
            {
                outputString = outputString.Replace("mainName", VarStorage.Globals.mainName).Replace("otherName", VarStorage.Globals.otherName).Replace("mainSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.mainSize))).Replace("otherSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.otherSize))).Replace("mainFinalSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.mainFinalSize))).Replace("otherFinalSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.otherFinalSize))).Replace("changeDelta", format.totalHeight(Convert.ToInt32(VarStorage.Globals.changeDelta))).Replace("percentDelta", Convert.ToString(VarStorage.Globals.percentDelta) + "%").Replace("mainCompSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.mainCompSize))).Replace("otherCompSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.otherCompSize)));
            }
            else
            {
                outputString = outputString.Replace("mainName", VarStorage.Globals.mainName).Replace("otherName", VarStorage.Globals.otherName).Replace("mainSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.mainSize))).Replace("otherSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.otherSize))).Replace("mainFinalSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.mainFinalSize))).Replace("otherFinalSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.otherFinalSize))).Replace("(changeDelta)", format.totalHeight(Convert.ToInt32(VarStorage.Globals.changeDelta))).Replace("percentDelta", "").Replace("mainCompSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.mainCompSize))).Replace("otherCompSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.otherCompSize)));
            }
            VarStorage.Globals.textLine1 = outputString;
        }
Beispiel #32
0
        /// <summary>
        /// Computes a cryptographically secure random Kademlia key that matches the boundaries of this <see cref="IBucket"/>.
        /// </summary>
        /// <returns></returns>
        public static string GetRandomKey(string key, int index)
        {
            byte[] keyBytes = EncryptionProvider.GetBytes(key);
            byte[] bytes    = GetRandomKey();

            int sharedPrefixLengthBytes = (int)Math.Floor((index / (decimal)8));
            int sharedPrefixLengthBits  = index % 8;

            CryptoRandom cryptoRandom = new CryptoRandom();

            for (int i = 0; i < keyBytes.Length; i++)
            {
                if (i > sharedPrefixLengthBytes)
                {
                    // Keep randomness
                    bytes[i] = (byte)(bytes[i] ^ keyBytes[i]);
                }
                else if (i < sharedPrefixLengthBytes)
                {
                    // Use the bytes from the given key
                    bytes[i] = keyBytes[i];
                }
                else if (i == sharedPrefixLengthBytes)
                {
                    // Preserve some random bits without modifying the most significant bit index
                    int min   = (255 >> (sharedPrefixLengthBits + 1)) + 1;
                    int max   = (255 >> sharedPrefixLengthBits) + 1;
                    int shift = cryptoRandom.Next(min, max);
                    bytes[i] = (byte)(shift ^ keyBytes[i]);
                }
            }
            return(EncryptionProvider.GetString(bytes));
        }
Beispiel #33
0
    private static string RandomSplash()
    {
        string[] splashes = File.ReadAllLines(GlobalPaths.ConfigDir + "\\splashes.txt");
        string   splash   = "";

        try
        {
            splash = splashes[new CryptoRandom().Next(0, splashes.Length - 1)];
        }
        catch (Exception)
        {
            try
            {
                splash = splashes[0];
            }
            catch (Exception)
            {
                splash = "missingno";
                return(splash);
            }
        }

        CryptoRandom random = new CryptoRandom();

        string formattedsplash = splash
                                 .Replace("%name%", GlobalVars.UserConfiguration.PlayerName)
                                 .Replace("%randomtext%", SecurityFuncs.RandomString(random.Next(2, 32)));

        return(formattedsplash);
    }
Beispiel #34
0
        public async Task Gelbooru([Remainder] string tag = "")
        {
            tag = tag?.Replace(" ", "_");

            using (var http = new HttpClient())
            {
                var data = await http.GetStreamAsync($"http://gelbooru.com/index.php?page=dapi&s=post&q=index&limit=100&tags={tag}");

                var doc = new XmlDocument();
                doc.Load(data);

                var node = doc.LastChild.ChildNodes[CryptoRandom.Next(doc.LastChild.ChildNodes.Count)];
                if (node == null)
                {
                    ReplyError("No result found.");
                }

                var url = node.Attributes["file_url"].Value;

                if (!url.StartsWith("http"))
                {
                    url = "https:" + url;
                }

                await Context.Channel.SendMessageAsync(url);
            }
        }
        static void Main(string[] args)
        {
            string[] noun = { "She", "He", "It", "The cat", "The mongoose", "The orange", "The trampoline", "Musicians", "Programmers", "The shake" };
            string[] verb = { "ate", "barbequed", "chirped", "collided", "sang", "spoke", "cartwheeled", "dined", "watched", "directed" };
            string[] where = { "With the monkeys", "on the porch", "under the moon", "after the storm", "before the prince, over the lake", "in the gazebo", "between the lines", "during the festival", "with them all." };

            CryptoRandom rng = new CryptoRandom();
            int nouns = rng.Next(1, 11);
            StringBuilder sentence = new StringBuilder();

            sentence.Append(noun[nouns - 1]+" ");

            int verbs = rng.Next(1, 11);
            sentence.Append(verb[verbs - 1] + " ");

            int wheres = rng.Next(1, 11);
            sentence.Append(where[wheres - 1] + " ");
            Console.Write(sentence);
        }
Beispiel #36
0
        public static string IdNumber(int maxAge = 100, int minAge = 18)
        {
            var random = new CryptoRandom();
            int year = random.Next(DateTime.Today.Year - maxAge, DateTime.Today.Year - minAge);
            int month = random.Next(1, 12);
            int day = random.Next(1, DateTime.DaysInMonth(year, month));
            int gender = random.Next(1, 9999); // If < 5000 Then Female. If >= 5000 Then Male
            int countryId = 0; // 0 = South Africa, 1 = Other
            int secondLastDigit = random.Next(0, 9);
            int controlDigit = 0;

            var dateAndGender = string.Format("{0}{1}{2}{3}", year.ToString().Substring(2, 2), month.ToString().PadLeft(2, '0'), day.ToString().PadLeft(2, '0'), gender.ToString().PadLeft(4, '0'));

            string idNumber = dateAndGender + countryId + secondLastDigit;
            controlDigit = GetControlDigit(idNumber);
            idNumber = idNumber + controlDigit;

            return idNumber;
        }
Beispiel #37
0
 static void Main(string[] args)
 {
     StreamReader reader = new StreamReader("..\\..\\SentenceParts.txt");
     StringBuilder words = new StringBuilder();
     StringBuilder sentence = new StringBuilder();
     using (reader)
     {
         string line = reader.ReadLine();
         words.Append(line);
         while (line != null)
         {
             line = reader.ReadLine();
             words.Append(line);
         }
         string all = words.ToString();           
         string[] allWords =all.Split(',');
         string[] nouns = new string[10];
         string[] verbs = new string[2];
         string[] phrases = new string[3];
         for (int i = 0; i < nouns.Length; i++)
            {
             nouns[i] = allWords[i]; 
             }                
         for (int n = 0; n<verbs.Length; n++)
         {
             verbs[n] = allWords[n + 10];
         }
         for(int p= 0; p<phrases.Length; p++)
         {
             phrases[p] = allWords[p + 12];
         }
         CryptoRandom randomNum = new CryptoRandom();
         int noun = randomNum.Next(1, 11);
         int verb = randomNum.Next(1, 3);
         int phrase = randomNum.Next(1, 4);                
         sentence.Append(nouns[noun-1] + " ");
         sentence.Append(verbs[verb-1] + " ");
         sentence.Append(phrases[phrase-1]);
         Console.WriteLine(sentence);
     }
     
 }
Beispiel #38
0
 static void Main(string[] args)
 {
     bool play = true;
     while (play == true)
     {
         string line = "";                                       //create variable to store text read from file
         StreamReader reader = new StreamReader("nouns.txt");    //declare StreamReader and file name to be read
         using (reader)
         {                                                       //read line from file(if necessary add while loop
             line = reader.ReadLine();                           //and additional ReadLine to continue while
         }                                                       //line is not null)
         CryptoRandom randnum = new CryptoRandom();  //random number generator
         int noun = randnum.Next(1, 11);         //set number variable for noun   
         int verb = randnum.Next(1, 11);         //set number variable for verb
         int phrase = randnum.Next(1, 11);       //set number variable for prepositional phrase                                 
         string[] nounList = line.Split(',');    //split text from line along commas and store in array       
         string[] verbList = { "ate", "barbecued", "chirped", "collided", "sang",    //create array with list of 10 verbs
             "spoke", "cartwheeled", "dined", "watched", "directed" };
         string[] phraseList = {"with the monkeys", "on the porch", "under the moon", "after the storm", "before the prince", "over the lake",
         "in the gazebo", "between the lines", "during the festival", "with them all"};   //create array with list of 10 phrases 
         StringBuilder sentence = new StringBuilder();       //create new stringbuilder to make the sentence
         sentence.Append(nounList[noun - 1] + " ");          //add chosen noun # to sentence  (subtract 1 for index)
         sentence.Append(verbList[verb - 1] + " ");          //add chosen verb # to sentence
         sentence.Append(phraseList[phrase - 1]);            //add chosen phrase # to sentence
         Console.WriteLine(sentence);                         //print out the sentence
         StreamWriter writer = new StreamWriter("FunnySentence.txt");
         using (writer)                                      //establish Streamwriter and name of file to write to
         {
             writer.WriteLine(sentence);                     //write result to the file
         }
         Console.WriteLine("Would you like to play again? Please enter \"yes\" or \"no\":");
         string answer = Console.ReadLine();                 //ask user if they want to play again
         answer.ToLower();                                   //convert answer to lower case if needed
         if (answer == "yes")
         {
             continue;                                       //run program again if user says they want to play again
         }
         else
             break;                                          //exit the program if the user doesn't say yes
     }
 }
        public IEnumerable<char> Generate(int numericBase, CharsetGenerator charsetGenerator)
        {
            numericBase = charsetGenerator.NumericSystemLimiter(numericBase);
            List<char> result = new List<char>(numericBase);

            List<char> buffer = new List<char>(numericBase);
            buffer.AddRange(charsetGenerator.AvailableCharacters);

            CryptoRandom rnd = new CryptoRandom();

            while (buffer.Count > 0) {
                byte index = rnd.Next((byte)(buffer.Count));
                result.Add(buffer[index]);
                buffer.RemoveAt(index);
            }
            return result;
        }
		public void Base64_ToB64Url_Test()
		{
			var rnd = new CryptoRandom();
			Parallel.For(1, 5000, i =>
			{
				var byteArray = rnd.NextBytes(i);
				var offset = 0;
				var count = Math.Max(i, i - rnd.Next(10));
				var byteSegment = new ArraySegment<byte>(byteArray, offset, count);

				var b64url = byteSegment.ToB64Url();
				var b64 = byteSegment.ToB64();

				Assert.IsTrue(b64url + b64[b64.Length - 1] == b64);
				Assert.IsTrue(Enumerable.SequenceEqual(byteSegment, b64url.FromB64Url()));
			});
		}// Base64_ToB64Url_Test()
Beispiel #41
0
        /// <summary>
        /// new Base stat and automatically calculate all stats
        /// </summary>
        public Stats(int health, int attack, int defense, int specialattack, int specialdefense, int speed, int level, bool randomize = true)
        {
            BaseHealth = health;
            BaseAttack = attack;
            BaseDefense = defense;
            BaseSpecialAttack = specialattack;
            BaseSpecialDefense = specialdefense;
            BaseSpeed = speed;

            if (randomize) {
                var rand = new CryptoRandom();
                RandAttack = rand.Next(1, 31);
                RandDefense = rand.Next(1, 31);
                RandSpecialAttack = rand.Next(1, 31);
                RandSpecialDefense = rand.Next(1, 31);
                RandSpeed = rand.Next(1, 31);
            }
            CalculateStats(level);
        }
Beispiel #42
0
 /// <summary>
 /// Checks if the opponent has an ability that can trigger an ailment on hit
 /// </summary>
 /// <param name="user"></param>
 /// <param name="opponent"></param>
 /// <param name="move"></param>
 /// <returns></returns>
 public Ailment GetAilment(Monster user, Monster opponent, Move move)
 {
     //If user already has an ailment
     if (user.Ailment != Ailment.Normal) return user.Ailment;
     //If move does not make contact with the opponent
     if (move.Kind != Kind.Physical) return user.Ailment;
     var rand = new CryptoRandom();
     switch (opponent.Ability.Id) {
     case AbilityId.ToxicBody:
         if (rand.Next(0, 100) <= 10) {
             Drawer.AddMessage(new List<string> { $"{opponent.Name}s {opponent.Ability.Name} made {user.Name} poisoned!" });
             return Ailment.Poisoned;
         }
         break;
     case AbilityId.Warm:
         if (rand.Next(0, 100) <= 7.5) {
             Drawer.AddMessage(new List<string> { $"{opponent.Name}s {opponent.Ability.Name} made {user.Name} fall asleep!" });
             return Ailment.Sleep;
         }
         break;
     case AbilityId.OnFire:
         if (rand.Next(0, 100) <= 7.5) {
             Drawer.AddMessage(new List<string> { $"{opponent.Name}s {opponent.Ability.Name} made {user.Name} catch fire!" });
             return Ailment.Burned;
         }
         break;
     }
     return Ailment.Normal;
 }
Beispiel #43
0
 public bool SkipTurn(Monster user)
 {
     if (user.Ability.Id == AbilityId.Silly) {
         ChanceToSkipTurn = 10f;
         var rand = new CryptoRandom();
         int ran = rand.Next(0, 100);
         if (ran <= ChanceToSkipTurn) {
             Drawer.AddMessage(new List<string> { $"{user.Name}s {user.Ability.Name} made {user.Name} skip a turn!" });
             return true;
         }
     }
     return false;
 }
		public void EtM_CTR_Sanity()
		{
			var rnd = new CryptoRandom();
			const int plaintextOffset = 16;

			for (int i = 0; i < 2000; ++i)
			{
				var plaintext = new byte[rnd.Next(plaintextOffset + plaintextOffset, 50 * 1024)];
				var plaintextSegment = new ArraySegment<byte>(array: plaintext, offset: plaintextOffset /* some non-zero offset */, count: plaintext.Length - plaintextOffset - plaintextOffset);
				rnd.NextBytes(plaintext);
				var masterkey = new byte[rnd.Next(0, 64)];
				rnd.NextBytes(masterkey);

				var salt = new byte[rnd.Next(0, 64)];
				rnd.NextBytes(salt);
				var saltSegment = new ArraySegment<byte>(salt);

				var ciphertext = EtM_CTR.Encrypt(masterkey, plaintextSegment, saltSegment);
				var ciphertext_with_padding = new byte[ciphertext.Length + plaintextOffset + plaintextOffset];
				Utils.BlockCopy(ciphertext, 0, ciphertext_with_padding, plaintextOffset, ciphertext.Length);

				var ciphertextSegment = new ArraySegment<byte>(array: ciphertext_with_padding, offset: plaintextOffset, count: ciphertext.Length);

				var decryptedtext = EtM_CTR.Decrypt(masterkey, ciphertextSegment, saltSegment);
				Assert.IsTrue(Utils.ConstantTimeEqual(new ArraySegment<byte>(decryptedtext), plaintextSegment));

				Assert.IsTrue(EtM_CTR.Authenticate(masterkey, ciphertextSegment, saltSegment));
			}//for
		}//EtM_CTR_Sanity()
Beispiel #45
0
        public void ChangeSize()
        {
            //Create a random number gen and height gen
            CryptoRandom rnd = new CryptoRandom();
            HeightGen conv = new HeightGen();

            //set values on the first turn only.
            if (firstTurn == true)
            {
                VarStorage.Globals.player1Height = Convert.ToDouble(txtStartP1.Text);
                VarStorage.Globals.player2Height = Convert.ToDouble(txtStartP2.Text);
                firstTurn = false;
            }

            //Checks who's turn it is, then sets global variables.
            if (p1Turn == true)
            {
                VarStorage.Globals.mainName = txtP1Name.Text;
                VarStorage.Globals.otherName = txtP2Name.Text;
                VarStorage.Globals.mainSize = VarStorage.Globals.player1Height;
                VarStorage.Globals.otherSize = VarStorage.Globals.player2Height;
            }
            else
            {
                VarStorage.Globals.mainName = txtP2Name.Text;
                VarStorage.Globals.otherName = txtP1Name.Text;
                VarStorage.Globals.mainSize = VarStorage.Globals.player2Height;
                VarStorage.Globals.otherSize = VarStorage.Globals.player1Height;
            }

            //Rolls to see which change to make, then executes said change.
            int rNumber = rnd.Next(100) + 1;
                ChangeHandler theChange = new ChangeHandler();
            if (rNumber >= 1 && rNumber <= 10)
            {
                VarStorage.Globals.rollType = 1;
                theChange.Changing();
            }
            else if (rNumber >= 11 && rNumber <= 50)
            {
                VarStorage.Globals.rollType = 2;
                theChange.Changing();
            }
            else if (rNumber >=51 && rNumber <= 60)
            {
                VarStorage.Globals.rollType = 3;
                theChange.Changing();
            }
            else
            {
                VarStorage.Globals.rollType = 4;
                theChange.Changing();
            }

            //Checks the turn and then sets the main height variables.
            if (p1Turn == true)
            {
                VarStorage.Globals.player1Height = VarStorage.Globals.mainFinalSize;
                VarStorage.Globals.player2Height = VarStorage.Globals.otherFinalSize;
            }
            else
            {
                VarStorage.Globals.player1Height = VarStorage.Globals.otherFinalSize;
                VarStorage.Globals.player2Height = VarStorage.Globals.mainFinalSize;
            }

            //Creates the text that is displayed in the main textbox.
            txtDisplay.Text += VarStorage.Globals.textLine1;
            txtDisplay.Text += Environment.NewLine;
            txtDisplay.Text += Environment.NewLine;

            //Finds closest object sizes.
            List<int> objects = new List<int> { 304800, 762000, 1828800, 7493000};
            int relativeSize = Convert.ToInt32(VarStorage.Globals.mainFinalSize);
            string compObject = "";
              /*
            if (VarStorage.Globals.player1Height >= VarStorage.Globals.player2Height)
            { relativeSize = Convert.ToInt32(VarStorage.Globals.player1Height * 12); }
            else
            { relativeSize = Convert.ToInt32(VarStorage.Globals.player2Height * 12); }
               */
            double closest = objects.Aggregate((x, y) => Math.Abs(x - relativeSize) < Math.Abs(y - relativeSize) ? x : y);
            if (closest == 304800)
            { compObject = "Rabbit"; }
            else if (closest == 762000)
            { compObject = "Wolf"; }
            else if (closest == 1828800)
            { compObject = "SUV"; }

            //Creates text for the comparison textbox.
            VarStorage.Globals.textLine2 = VarStorage.Globals.mainName + " now appears " + conv.totalHeight(Convert.ToInt32(VarStorage.Globals.mainCompSize)) + " to the " + conv.totalHeight(Convert.ToInt32((VarStorage.Globals.otherFinalSize))) + " tall " + VarStorage.Globals.otherName;
            VarStorage.Globals.textLine3 = VarStorage.Globals.otherName + " looks to be " + conv.totalHeight(Convert.ToInt32(VarStorage.Globals.otherCompSize)) + " tall to " + VarStorage.Globals.mainName + ".";

            txtRecap.Text = VarStorage.Globals.textLine2;
            txtRecap.Text += Environment.NewLine;
            txtRecap.Text += VarStorage.Globals.textLine3;
            txtRecap.Text += Environment.NewLine;
            txtRecap.Text += "To " + VarStorage.Globals.mainName + ", the " + compObject + " looks to be " + conv.totalHeight(Convert.ToInt32((closest * 1828800) / Convert.ToInt32(VarStorage.Globals.mainFinalSize)));

            //Creates the VMS link.
            double p1in = VarStorage.Globals.player1Height;
            string p1HeightRounded = p1in.ToString("0");
            double p2in = VarStorage.Globals.player2Height;
            string p2HeightRounded = p2in.ToString("0");

            txtBFLink.Text = "http://vms.bigfurs.com/?chars=" + compObject + "+" + txtP1Name.Text + "[" + p1HeightRounded+ "um]+" + txtP2Name.Text + "[" + p2HeightRounded + "um]";

            txtDisplay.SelectionStart = txtDisplay.Text.Length; //Set the current caret position at the end
            txtDisplay.ScrollToCaret(); //Now scroll it automatically

            //Set the Height text fields.
            txtSize1.Text = conv.totalHeight(Convert.ToInt32(VarStorage.Globals.player1Height));
            txtSize2.Text = conv.totalHeight(Convert.ToInt32(VarStorage.Globals.player2Height));
        }
Beispiel #46
0
 public Monster GetRandomMonster()
 {
     CryptoRandom rand = new CryptoRandom();
     int index = rand.Next(0, Monsters.Count);
     Monsters[index].Stats.Health = Monsters[index].MaxHealth;
     Monsters[index].Ailment = Ailment.Normal;
     return Monsters[index];
 }
Beispiel #47
0
        public void Changing()
        {
            CryptoRandom rng = new CryptoRandom();
            DescrptHandler display = new DescrptHandler();

            double mainSize = VarStorage.Globals.mainSize;
            double otherSize = VarStorage.Globals.otherSize;
            double mainFinalSize = VarStorage.Globals.mainSize;
            double otherFinalSize = VarStorage.Globals.otherSize;
            string deltaSizeRounded = "";
            VarStorage.Globals.percentDelta = "";

            int changeType = rng.Next(5) + 1;
            if (VarStorage.Globals.rollType == 1)
            {
                if (changeType <= 5)
                {
                    double rAmount = rng.Next(110) + 11;
                    double deltaSize = (rAmount / 100) * mainSize;
                    deltaSizeRounded = deltaSize.ToString("0.00");
                    mainFinalSize = mainSize + Convert.ToDouble(deltaSizeRounded);
                    VarStorage.Globals.changeType = 1;
                    VarStorage.Globals.percentDelta = Convert.ToString(rAmount);
                }
                else
                {
                    double rAmount = rng.Next(Convert.ToInt32(mainSize));
                    double deltaSize = rAmount / 12;
                    deltaSizeRounded = deltaSize.ToString("0.00");
                    mainFinalSize = mainSize + Convert.ToDouble(deltaSizeRounded);
                    VarStorage.Globals.changeType = 2;
                }
            }
            else if (VarStorage.Globals.rollType == 2)
            {
                if (changeType <= 5)
                {
                    double rAmount = rng.Next(60) + 11;
                    double deltaSize = (rAmount / 100) * mainSize;
                    deltaSizeRounded = deltaSize.ToString("0.00");
                    mainFinalSize = mainSize - Convert.ToDouble(deltaSizeRounded);
                    VarStorage.Globals.changeType = 1;
                    VarStorage.Globals.percentDelta = Convert.ToString(rAmount);
                }
                else
                {
                    double rAmount = rng.Next(Convert.ToInt32(mainSize));
                    double deltaSize = rAmount / 12;
                    deltaSizeRounded = deltaSize.ToString("0.00");
                    mainFinalSize = mainSize - Convert.ToDouble(deltaSizeRounded);
                    VarStorage.Globals.changeType = 2;
                    VarStorage.Globals.percentDelta = "";
                }
            }
            else if (VarStorage.Globals.rollType == 3)
            {
                if (changeType <= 5)
                {
                    double rAmount = rng.Next(40) + 11;
                    double deltaSize = (rAmount / 100) * otherSize;
                    deltaSizeRounded = deltaSize.ToString("0.00");
                    mainFinalSize = mainSize + Convert.ToDouble(deltaSizeRounded);
                    otherFinalSize = otherSize - Convert.ToDouble(deltaSizeRounded);
                    VarStorage.Globals.changeType = 1;
                    VarStorage.Globals.percentDelta = Convert.ToString(rAmount);
                }
                else
                {
                    double rAmount = rng.Next((Convert.ToInt32(otherSize)) - 1);
                    double deltaSize = rAmount / 12;
                    deltaSizeRounded = deltaSize.ToString("0.00");
                    mainFinalSize = mainSize + Convert.ToDouble(deltaSizeRounded);
                    otherFinalSize = otherSize - Convert.ToDouble(deltaSizeRounded);
                    VarStorage.Globals.changeType = 2;
                    VarStorage.Globals.percentDelta = "";
                }
            }
            else if (VarStorage.Globals.rollType == 4)
            {
                if (changeType <= 5)
                {
                    double rAmount = rng.Next(60) + 11;
                    double deltaSize = (rAmount / 100) * otherSize;
                    deltaSizeRounded = deltaSize.ToString("0.00");
                    otherFinalSize = otherSize - Convert.ToDouble(deltaSizeRounded);
                    VarStorage.Globals.changeType = 1;
                    VarStorage.Globals.percentDelta = Convert.ToString(rAmount);
                }
                else
                {
                    double rAmount = rng.Next(Convert.ToInt32(mainSize));
                    double deltaSize = rAmount / 12;
                    deltaSizeRounded = deltaSize.ToString("0.00");
                    mainFinalSize = mainSize - Convert.ToDouble(deltaSizeRounded);
                    VarStorage.Globals.changeType = 2;
                    VarStorage.Globals.percentDelta = "";
                }
            }

            VarStorage.Globals.mainSize = mainSize;
            VarStorage.Globals.mainFinalSize = mainFinalSize;
            VarStorage.Globals.otherFinalSize = otherFinalSize;
            VarStorage.Globals.otherSize = otherSize;
            VarStorage.Globals.changeDelta = Convert.ToDouble(deltaSizeRounded);
            VarStorage.Globals.mainCompSize = ((mainFinalSize) * 1828800) / (otherFinalSize);
            VarStorage.Globals.otherCompSize = ((otherFinalSize) * 1828800) / (mainFinalSize);
            display.DescPath();
        }
    void CreateTurretsRandom()
    {
        Debug.Log("Creating Turrets for " + this.gameObject.name);

        // Make sure there are rig points on this ship from XML.
        if (attributes.rigPointType == null)
        {
            Debug.LogError("Points are Null");
            return;
        }
        if ( attributes.rigPointType.Length < 1)
        {
            Debug.LogError("Points are Empty");
            return;
        }

        // Make sure Rig Points and Rig Sizes array have proper amount of rigs.
        List<string> properAmount = new List<string>();
        for (int ndx = 0; ndx < attributes.rigPointType.Length; ++ndx)
        {
            if (!String.IsNullOrEmpty(attributes.rigPointType[ndx]))
                properAmount.Add(attributes.rigPointType[ndx]);
            else
                break;
        }

        attributes.rigPointType = properAmount.ToArray();
        properAmount.Clear();

        for (int ndx = 0; ndx < attributes.rigPointSize.Length; ++ndx)
        {
            if (!String.IsNullOrEmpty(attributes.rigPointSize[ndx]))
                properAmount.Add(attributes.rigPointSize[ndx]);
            else
                break;
        }
        attributes.rigPointSize = properAmount.ToArray();

        int rigPoints = attributes.rigPointType.Length;
        //Debug.Log("Start Position: " + transform.position);
        //PopulateRigPoints();

        if (rigPoints != RigPointsCount)
        {
            // Also add InGame to InXML amounts for debugging for modding.
            Debug.LogError(this.name + " Ship rig points != XML Rig points for ship. Please make sure you have the correct amount of rig point types in your XML file for this ship. Ship will stop being rigged for weapons now. " + rigPoints + " / " + RigPointsCount);
            return;
        }

        //Debug.Log("Starting Loop for Random turrets");
        int rpcount = 0;

        CryptoRandom rng = new CryptoRandom();

        foreach (Transform rp in RigPoints)
        {
            if (rpcount > 3)
                break;

            // Holds all the possible types for this rig point
            string possibleTypes = attributes.rigPointType[rpcount];
            List<string> typeArray = new List<string>(possibleTypes.Split('|'));
            int typesPossible = typeArray.Count;
        //
        //			string debugadd = "";
        //
        //			for (int ndx = 0; ndx <= typesPossible; ndx++)
        //			{
        //				debugadd += typeArray[ndx];
        //			}
        //
        //			// Possible Tpes
        //			Debug.LogWarning(debugadd);
        //			debugadd = "";

            // Holds all the possible Sizes for this rigpoint.
            string possibleSizes = attributes.rigPointSize[rpcount];
            string[] sizeArray = possibleSizes.Split('|');
            int sizesPossible = sizeArray.Length;
        //
        //			// PossibleSizes
        //			for (int ndx = 0; ndx <= sizesPossible; ndx++)
        //			{
        //				debugadd += sizeArray[ndx];
        //			}
        //			Debug.LogWarning(debugadd);

            //Debug.LogWarning(sizesPossible.ToString() + " " + typesPossible.ToString());

            bool selectingWeapon = true;
            string weaponSelection = "";
            WeaponAttributes weaponSelectionAttributes = null;

            Weapon.WeaponSize sze = Weapon.WeaponSize.NONE;
            Weapon.WeaponType tpe = Weapon.WeaponType.NONE;
            //Debug.LogWarning(typesPossible);

            int loopCount = 0;
            while (selectingWeapon)
            {
                // Select a random weapon size / type from possibilities.
                rng = new CryptoRandom();
                int	pickSize = rng.Next(sizesPossible);

                rng = new CryptoRandom();
                int pickType = 	pickType = rng.Next(typesPossible);

                //Debug.LogWarning(pickSize + " " + pickType);
                sze = (Weapon.WeaponSize) System.Enum.Parse(typeof(Weapon.WeaponSize), sizeArray[pickSize]);
                tpe = (Weapon.WeaponType) System.Enum.Parse(typeof(Weapon.WeaponType), typeArray[pickType]);

                //Debug.LogWarning((int)tpe);
                // Get all the corresponding weapon size dictionary.
                //Debug.LogWarning(sze.ToString() + " " + tpe.ToString());
                Weapon.WeaponTypeCache holder = Game.weaponDictionary[sze.ToString() + "|" + tpe.ToString()];

                // Make a list for all the possible weapons in that size.
                List<WeaponAttributes> weaponsPossible = new List<WeaponAttributes>();
                // Insert all weapons possible into that list.
                foreach (var pair in holder.weapons)
                {
                    weaponsPossible.Add(pair.Value);
                }

                // Select one of the weapons from that list.
                weaponSelectionAttributes = weaponsPossible[UnityEngine.Random.Range(0,weaponsPossible.Count - 1)];
                weaponSelection = weaponSelectionAttributes.path;
                //

                // If weapon is selected exit loop.
                if (weaponSelection.Length > 1)
                    break;

                // Try 50 times before saying f**k this shit.
                loopCount++;
                if (loopCount > 10)
                    return;
            }

            // Instantiate proper turret -- Offset it by space between two rig points. Attach.
            //Debug.Log("Current Position: " + transform.position);
            //Debug.Log("Weapons/" + sze.ToString() + "/" + tpe.ToString() + "/" + weaponSelection);
            GameObject tur = PhotonNetwork.Instantiate("Weapons/" + sze.ToString() + "/" + tpe.ToString() + "/" + weaponSelection, rp.position, rp.rotation, 0) as GameObject;

            Weapon wscript = tur.GetComponent<Weapon>();
            wscript.SetAttributes(weaponSelectionAttributes);
            wscript.owner = this;
            Weapons.Add(wscript);
            tur.transform.parent = rp;
            //tur.transform.position = wscript.owner.transform.position;
            //tur.transform.localScale = new Vector3(3,3,3);
            // rPoint or rp figure it out!

            if (wscript.rigpoint == null)
                wscript.SetRigPoint();

            Vector3 offset = rp.position - wscript.rigpoint.position;
            tur.transform.position += offset;
            tur.transform.parent = rp;
            tur.name = weaponSelection;

            ++rpcount;
        }
    }
Beispiel #49
0
 static void Main(string[] args)
 {
     CryptoRandom rng = new CryptoRandom();
     Console.WriteLine(rng.Next());
 }