Esempio n. 1
0
        public static DSAKeyPair GenerateNew(int bits, Rng random)
        {
            BigInteger one = new BigInteger(1);
            BigInteger[] pq = findRandomStrongPrime(bits, 160, random);
            BigInteger p = pq[0], q = pq[1];
            BigInteger g = findRandomGenerator(q, p, random);

            BigInteger x;
            do {
                x = BigInteger.GenerateRandom(q.BitCount());
            } while ((x < one) || (x > q));

            BigInteger y = g.ModPow(x, p);

            return new DSAKeyPair(p, g, q, y, x);
        }
        public static void Prefix([HarmonyArgument(0)] out Il2CppReferenceArray <GameData.PlayerInfo> playerInfos)
        {
            List <Role> assignedRoles = AssignedRoles.Values.ToList();

            foreach (Role r in assignedRoles)
            {
                r.ClearSettings();
            }

            var infected = new List <GameData.PlayerInfo>();
            var roles    = new List <Role>();

            List <Role> availableRoles = Main.Roles.ToList();

            List <RoleSlot>      roleSlots        = Main.GetRoleSlots().ToList();
            List <PlayerControl> availablePlayers = AllPlayers.ToList();

            for (var i = 0; i < roleSlots.Count && availablePlayers.Count > 0; i++)
            {
                RoleSlot           roleSlot         = roleSlots[i];
                var                spawnChance      = 0;
                IEnumerable <Role> possibleRoles    = roleSlot.GetFittingRoles(availableRoles);
                var                roleSpawnChances = new List <RoleSpawnChancePair>();
                foreach (Role possibleRole in possibleRoles)
                {
                    roleSpawnChances.Add(new RoleSpawnChancePair(possibleRole,
                                                                 spawnChance += (int)Main.GetRoleSpawnChance(possibleRole.GetType())));
                }

                // IEnumerable<RoleSpawnChancePair> roleSpawnChances = roleSlot.GetFittingRoles(availableRoles).Select(role => new RoleSpawnChancePair(role, spawnChance += (int) Main.GetRoleSpawnChance(role.GetType())));
                int spawnValue = Rng.Next(spawnChance);
                foreach (RoleSpawnChancePair roleSpawnChance in roleSpawnChances)
                {
                    if (roleSpawnChance.spawnChance > spawnValue)
                    {
                        roles.Add(roleSpawnChance.role);
                        PlayerControl player = availablePlayers[Rng.Next(availablePlayers.Count)];
                        Role.RpcSetRole(roleSpawnChance.role, player);

                        availableRoles.Remove(roleSpawnChance.role);
                        availablePlayers.Remove(player);
                        if (roleSlots[i].IsInfected)
                        {
                            infected.Add(player.Data);
                        }

                        break;
                    }
                }

                /*
                 * Role role = roleSlots[i].GetRole(ref availableRoles);
                 * PlayerControl player = availablePlayers[Rng.Next(availablePlayers.Count)];
                 * Role.SetRole(role, player);
                 *
                 * availableRoles.Remove(role);
                 * availablePlayers.Remove(player);
                 * if (roleSlots[i].IsInfected)
                 * {
                 *  infected.Add(player.Data);
                 * }
                 */
            }

            foreach (Role role in roles)
            {
                role.InitializeRole();
            }

            int killAbilitiesToAdd = (int)Main.OptionMafiaKillStart - roles.Count(role =>
                                                                                  role.Faction == Faction.Mafia && role.GetAbility <AbilityKill>() != null);

            // TODO: Randomize order of adding killAbilities, so you don't have an advantage if you log into lobby earlier than another one
            for (var i = 0; i < roles.Count && killAbilitiesToAdd > 0; i++)
            {
                Role role = roles[i];
                if (role.Faction != Faction.Mafia || role.GetAbility <AbilityKill>() != null)
                {
                    continue;
                }

                role.AddAbility <Mafioso, AbilityKill>(true);
                WriteRPC(RPC.AddKillAbility, role.Owner.PlayerId);
                killAbilitiesToAdd--;
            }

            playerInfos = new Il2CppReferenceArray <GameData.PlayerInfo>(infected.ToArray());
        }
Esempio n. 3
0
 public static PositionComponent Respawn(PositionComponent position)
 {
     position.Placement = new EntityPlacement(
         EntityPos.Origin + new EntityOffset((Rng.NextDouble() * 2 - 1) * 32, 0, (Rng.NextDouble() * 2 - 1) * 32),
         new EntityOrientation(0, Rng.NextDouble() * 2 * Math.PI));
     position.InternalPos = position.Placement.Pos;
     return(position);
 }
Esempio n. 4
0
   public static Option <Tpl <Rng, int> > randomIndexT <A>(this IList <A> list, Rng rng) =>
   list.Count == 0
 ? F.none <Tpl <Rng, int> >()
 : F.some(rng.nextIntInRangeT(new Range(0, list.Count - 1)));
Esempio n. 5
0
 public static A random <A>(this NonEmpty <ImmutableArray <A> > list, ref Rng rng) =>
 random <ImmutableArray <A>, A>(list, ref rng);
Esempio n. 6
0
    public virtual void Start()
    {
        transitions = new Dictionary <Focusswitch, estate>
        {
            { new Focusswitch(estate.wander, eaction.spot), estate.chase },
            { new Focusswitch(estate.wander, eaction.lose), estate.wander },
            { new Focusswitch(estate.wander, eaction.inrange), estate.attack },
            { new Focusswitch(estate.wander, eaction.earshot), estate.chase },

            { new Focusswitch(estate.chase, eaction.inrange), estate.attack },
            { new Focusswitch(estate.chase, eaction.lose), estate.wander },
            { new Focusswitch(estate.chase, eaction.spot), estate.chase },
            { new Focusswitch(estate.chase, eaction.earshot), estate.chase },

            { new Focusswitch(estate.attack, eaction.spot), estate.chase },
            { new Focusswitch(estate.attack, eaction.inrange), estate.attack },
            { new Focusswitch(estate.attack, eaction.lose), estate.wander },
            { new Focusswitch(estate.attack, eaction.earshot), estate.attack },
        };
        funcs = new Dictionary <estate, Action>
        {
            { estate.attack, new Action(attack) },
            { estate.chase, new Action(chase) },
            { estate.wander, new Action(wander) },
        };

        Transform playerwrap = GameObject.FindGameObjectWithTag("Player").transform;

        player                   = playerwrap.GetComponent <Thief> ();
        target                   = playerwrap.transform.FindChild("fpcontrol");
        fov                      = transform.GetComponent <Fov> ();
        fov.speed                = speed * 2;
        fov.enabled              = false;
        nmagent                  = GetComponent <NavMeshAgent> ();
        nmagent.speed            = speed;
        nmagent.stoppingDistance = stoprange;
        anim                     = transform.GetChild(0).GetComponent <Animator> ();
        gun                      = transform.FindChild("gun");
        gunpoint                 = gun.FindChild("point");
        //gunhold = transform.FindChild ("ghold");
        gun.parent        = gunhold;
        gun.localPosition = Vector3.zero;
        gun.localRotation = Quaternion.identity;
        gun.gameObject.SetActive(false);
        playerlayer = LayerMask.NameToLayer("player");
        //Transform activwrap = GameObject.Find ("activities").transform;
        stage = transform.parent.parent;
        Transform activwrap = stage.FindChild("activities");

        if (activwrap)
        {
            activities = new List <Activity> ();
            for (int i = 0; i < activwrap.childCount; i++)
            {
                activities.Add(activwrap.GetChild(i).GetComponent <Activity> ());
            }
            rng          = transform.GetComponent <Rng> ();
            rng.activlen = activities.Count;
            //pickactivity ();
        }

        /*rng = transform.GetComponent<Rng> ();
         * rng.activlen = activities.Count;*/
        viewbox    = transform.FindChild("viewbox").gameObject;
        viewboxlit = transform.FindChild("viewboxlit").gameObject;

        if (patrol)
        {
            //Transform routewrap = transform.FindChild ("patrol");
            routepoint = 0;
            route      = new List <Transform> ();
            //print ("rlen - "+routewrap.childCount);
            for (int i = 0; i < routewrap.childCount; i++)
            {
                route.Add(routewrap.GetChild(i));
            }
        }

        pickactivity();
        StartCoroutine("hunt", .1f);
    }
Esempio n. 7
0
        public static BigInteger PKCS1PadType2(BigInteger input, int pad_len, Rng rng) {
            int input_byte_length = (input.bitCount() + 7) / 8;
            //System.out.println(String.valueOf(pad_len) + ":" + input_byte_length);
            byte[] pad = new byte[pad_len - input_byte_length - 3];

            for (int i = 0; i < pad.Length; i++) {
                byte[] b = new byte[1];
                rng.GetBytes(b);
                while (b[0] == 0)
                    rng.GetBytes(b); //0ではだめだ
                pad[i] = b[0];
            }

            BigInteger pad_int = new BigInteger(pad);
            pad_int = pad_int << ((input_byte_length + 1) * 8);
            BigInteger result = new BigInteger(2);
            result = result << ((pad_len - 2) * 8);
            result = result | pad_int;
            result = result | input;

            return result;
        }
Esempio n. 8
0
        //***********************************************************************
        // Tests the correct implementation of the modulo exponential and
        // inverse modulo functions using RSA encryption and decryption.  The two
        // pseudoprimes p and q are fixed, but the two RSA keys are generated
        // for each round of testing.
        //***********************************************************************

        public static void RSATest2(int rounds, Rng rand) {
            byte[] val = new byte[64];

            byte[] pseudoPrime1 = {
                (byte)0x85, (byte)0x84, (byte)0x64, (byte)0xFD, (byte)0x70, (byte)0x6A,
                (byte)0x9F, (byte)0xF0, (byte)0x94, (byte)0x0C, (byte)0x3E, (byte)0x2C,
                (byte)0x74, (byte)0x34, (byte)0x05, (byte)0xC9, (byte)0x55, (byte)0xB3,
                (byte)0x85, (byte)0x32, (byte)0x98, (byte)0x71, (byte)0xF9, (byte)0x41,
                (byte)0x21, (byte)0x5F, (byte)0x02, (byte)0x9E, (byte)0xEA, (byte)0x56,
                (byte)0x8D, (byte)0x8C, (byte)0x44, (byte)0xCC, (byte)0xEE, (byte)0xEE,
                (byte)0x3D, (byte)0x2C, (byte)0x9D, (byte)0x2C, (byte)0x12, (byte)0x41,
                (byte)0x1E, (byte)0xF1, (byte)0xC5, (byte)0x32, (byte)0xC3, (byte)0xAA,
                (byte)0x31, (byte)0x4A, (byte)0x52, (byte)0xD8, (byte)0xE8, (byte)0xAF,
                (byte)0x42, (byte)0xF4, (byte)0x72, (byte)0xA1, (byte)0x2A, (byte)0x0D,
                (byte)0x97, (byte)0xB1, (byte)0x31, (byte)0xB3,
            };

            byte[] pseudoPrime2 = {
                (byte)0x99, (byte)0x98, (byte)0xCA, (byte)0xB8, (byte)0x5E, (byte)0xD7,
                (byte)0xE5, (byte)0xDC, (byte)0x28, (byte)0x5C, (byte)0x6F, (byte)0x0E,
                (byte)0x15, (byte)0x09, (byte)0x59, (byte)0x6E, (byte)0x84, (byte)0xF3,
                (byte)0x81, (byte)0xCD, (byte)0xDE, (byte)0x42, (byte)0xDC, (byte)0x93,
                (byte)0xC2, (byte)0x7A, (byte)0x62, (byte)0xAC, (byte)0x6C, (byte)0xAF,
                (byte)0xDE, (byte)0x74, (byte)0xE3, (byte)0xCB, (byte)0x60, (byte)0x20,
                (byte)0x38, (byte)0x9C, (byte)0x21, (byte)0xC3, (byte)0xDC, (byte)0xC8,
                (byte)0xA2, (byte)0x4D, (byte)0xC6, (byte)0x2A, (byte)0x35, (byte)0x7F,
                (byte)0xF3, (byte)0xA9, (byte)0xE8, (byte)0x1D, (byte)0x7B, (byte)0x2C,
                (byte)0x78, (byte)0xFA, (byte)0xB8, (byte)0x02, (byte)0x55, (byte)0x80,
                (byte)0x9B, (byte)0xC2, (byte)0xA5, (byte)0xCB,
            };


            BigInteger bi_p = new BigInteger(pseudoPrime1);
            BigInteger bi_q = new BigInteger(pseudoPrime2);
            BigInteger bi_pq = (bi_p - 1) * (bi_q - 1);
            BigInteger bi_n = bi_p * bi_q;

            for (int count = 0; count < rounds; count++) {
                // generate private and public key
                BigInteger bi_e = bi_pq.genCoPrime(512, rand);
                BigInteger bi_d = bi_e.modInverse(bi_pq);

                /*
                Console.WriteLine("\ne =\n" + bi_e.ToString(10));
                Console.WriteLine("\nd =\n" + bi_d.ToString(10));
                Console.WriteLine("\nn =\n" + bi_n.ToString(10) + "\n");*/

                // generate data of random length
                int t1 = 0;
                while (t1 == 0)
                    t1 = rand.GetInt(65);

                bool done = false;
                while (!done) {
                    for (int i = 0; i < 64; i++) {
                        if (i < t1)
                            val[i] = (byte)rand.GetInt(256);
                        else
                            val[i] = 0;

                        if (val[i] != 0)
                            done = true;
                    }
                }

                while (val[0] == 0)
                    val[0] = (byte)rand.GetInt(256);

                //Console.Write("Round = " + count);

                // encrypt and decrypt data
                BigInteger bi_data = new BigInteger(val, t1);
                BigInteger bi_encrypted = bi_data.modPow(bi_e, bi_n);
                BigInteger bi_decrypted = bi_encrypted.modPow(bi_d, bi_n);

                // compare
                if (bi_decrypted != bi_data) {
                    /*
                    Console.WriteLine("\nError at round " + count);
                    Console.WriteLine(bi_data + "\n");*/
                    return;
                }
                //Console.WriteLine(" <PASSED>.");
            }

        }
Esempio n. 9
0
        public void Randomize(Blob seed, Flags flags, Preferences preferences)
        {
            MT19337 rng;

            using (SHA256 hasher = SHA256.Create())
            {
                Blob FlagsBlob    = Encoding.UTF8.GetBytes(Flags.EncodeFlagsText(flags));
                Blob SeedAndFlags = Blob.Concat(new Blob[] { FlagsBlob, seed });
                Blob hash         = hasher.ComputeHash(SeedAndFlags);
                rng = new MT19337(BitConverter.ToUInt32(hash, 0));
            }
            if (flags.TournamentSafe)
            {
                AssureSafe();
            }

            UpgradeToMMC3();
            MakeSpace();
            Bank1E();
            Bank1B();
            EasterEggs();
            DynamicWindowColor(preferences.MenuColor);
            PermanentCaravan();
            ShiftEarthOrbDown();
            CastableItemTargeting();
            FixEnemyPalettes();       // fixes a bug in the original game's programming that causes third enemy slot's palette to render incorrectly
            FixWarpBug();             // The warp bug must be fixed for magic level shuffle and spellcrafter
            SeparateUnrunnables();
            var talkroutines = new TalkRoutines();
            var npcdata      = new NPCdata(this);

            UpdateDialogs(npcdata);

            if (flags.TournamentSafe)
            {
                Put(0x3FFE3, Blob.FromHex("66696E616C2066616E74617379"));
            }

            flags = Flags.ConvertAllTriState(flags, rng);

            TeleportShuffle teleporters      = new TeleportShuffle();
            var             palettes         = OverworldMap.GeneratePalettes(Get(OverworldMap.MapPaletteOffset, MapCount * OverworldMap.MapPaletteSize).Chunk(OverworldMap.MapPaletteSize));
            var             overworldMap     = new OverworldMap(this, flags, palettes, teleporters);
            var             maps             = ReadMaps();
            var             shopItemLocation = ItemLocations.CaravanItemShop1;
            var             oldItemNames     = ReadText(ItemTextPointerOffset, ItemTextPointerBase, ItemTextPointerCount);

            if (flags.EFGWaterfall || flags.EFGEarth1 || flags.EFGEarth2)
            {
                MapRequirements      reqs;
                MapGeneratorStrategy strategy;
                MapGenerator         generator = new MapGenerator();
                if (flags.EFGWaterfall)
                {
                    reqs = new MapRequirements
                    {
                        MapId = MapId.Waterfall,
                        Rom   = this,
                    };
                    strategy = MapGeneratorStrategy.WaterfallClone;
                    CompleteMap waterfall = generator.Generate(rng, strategy, reqs);

                    // Should add more into the reqs so that this can be done inside the generator.
                    teleporters.Waterfall.SetEntrance(waterfall.Entrance);
                    overworldMap.PutOverworldTeleport(OverworldTeleportIndex.Waterfall, teleporters.Waterfall);
                    maps[(int)MapId.Waterfall] = waterfall.Map;
                }

                if (flags.EFGEarth1)
                {
                    reqs = new MapRequirements
                    {
                        MapId = MapId.EarthCaveB1,
                        Rom   = this,
                    };

                    strategy = MapGeneratorStrategy.Square;
                    var earthB1 = generator.Generate(rng, strategy, reqs);

                    // Should add more into the reqs so that this can be done inside the generator.
                    teleporters.EarthCave1.SetEntrance(earthB1.Entrance);
                    overworldMap.PutOverworldTeleport(OverworldTeleportIndex.EarthCave1, teleporters.EarthCave1);
                    maps[(int)MapId.EarthCaveB1] = earthB1.Map;
                }
                if (flags.EFGEarth2)
                {
                    reqs = new MapRequirements
                    {
                        MapId = MapId.EarthCaveB2,
                        Rom   = this,
                    };

                    strategy = MapGeneratorStrategy.Square;
                    var earthB2 = generator.Generate(rng, strategy, reqs);

                    // Should add more into the reqs so that this can be done inside the generator.
                    teleporters.EarthCave2.SetEntrance(earthB2.Entrance);
                    overworldMap.PutStandardTeleport(TeleportIndex.EarthCave2, teleporters.EarthCave2, OverworldTeleportIndex.EarthCave1);
                    maps[(int)MapId.EarthCaveB2] = earthB2.Map;
                }
            }

            var flippedMaps = new List <MapId>();

            if ((bool)flags.FlipDungeons)
            {
                flippedMaps = HorizontalFlipDungeons(rng, maps, teleporters, overworldMap);
            }

            if ((bool)flags.RandomizeFormationEnemizer)
            {
                DoEnemizer(rng, (bool)flags.RandomizeEnemizer, (bool)flags.RandomizeFormationEnemizer, flags.EnemizerDontMakeNewScripts);
            }

            if (preferences.ModernBattlefield)
            {
                EnableModernBattlefield();
            }

            if ((bool)flags.TitansTrove)
            {
                EnableTitansTrove(maps);
            }

            if ((bool)flags.LefeinShops)
            {
                EnableLefeinShops(maps);
            }

            // This has to be done before we shuffle spell levels.
            if (flags.SpellBugs)
            {
                FixSpellBugs();
            }

            //must be done before spells get shuffled around otherwise we'd be changing a spell that isnt lock
            if (flags.LockMode != LockHitMode.Vanilla)
            {
                ChangeLockMode(flags.LockMode);
            }

            if (flags.EnemySpellsTargetingAllies)
            {
                FixEnemyAOESpells();
            }

            if (flags.AllSpellLevelsForKnightNinja)
            {
                KnightNinjaChargesForAllLevels();
            }

            if (flags.BuffHealingSpells)
            {
                BuffHealingSpells();
            }

            UpdateMagicAutohitThreshold(rng, flags.MagicAutohitThreshold);

            if ((bool)flags.GenerateNewSpellbook)
            {
                CraftNewSpellbook(rng, (bool)flags.SpellcrafterMixSpells, flags.LockMode, (bool)flags.MagicLevels, (bool)flags.SpellcrafterRetainPermissions);
            }

            if ((bool)flags.MagisizeWeapons)
            {
                MagisizeWeapons(rng, (bool)flags.MagisizeWeaponsBalanced);
            }

            if ((bool)flags.ItemMagic)
            {
                ShuffleItemMagic(rng, (bool)flags.BalancedItemMagicShuffle);
            }

            if ((bool)flags.GuaranteedRuseItem)
            {
                CraftRuseItem();
            }

            if ((bool)flags.ShortToFR)
            {
                ShortenToFR(maps, (bool)flags.PreserveFiendRefights, (bool)flags.PreserveAllFiendRefights, rng);
            }

            if (((bool)flags.Treasures) && flags.ShardHunt && !flags.FreeOrbs)
            {
                EnableShardHunt(rng, talkroutines, flags.ShardCount);
            }

            if ((bool)flags.TransformFinalFormation && !flags.SpookyFlag)
            {
                TransformFinalFormation((FinalFormation)rng.Between(0, Enum.GetValues(typeof(FinalFormation)).Length - 1), flags.EvadeCap);
            }

            var maxRetries = 8;

            for (var i = 0; i < maxRetries; i++)
            {
                try
                {
                    overworldMap = new OverworldMap(this, flags, palettes, teleporters);
                    if (((bool)flags.Entrances || (bool)flags.Floors || (bool)flags.Towns) && ((bool)flags.Treasures) && ((bool)flags.NPCItems))
                    {
                        overworldMap.ShuffleEntrancesAndFloors(rng, flags);

                        // Disable the Princess Warp back to Castle Coneria
                        if ((bool)flags.Entrances || (bool)flags.Floors)
                        {
                            talkroutines.ReplaceChunk(newTalkRoutines.Talk_Princess1, Blob.FromHex("20CC90"), Blob.FromHex("EAEAEA"));
                        }
                    }

                    if ((bool)flags.Treasures && (bool)flags.ShuffleObjectiveNPCs)
                    {
                        overworldMap.ShuffleObjectiveNPCs(rng);
                    }

                    IncentiveData incentivesData = new IncentiveData(rng, flags, overworldMap, shopItemLocation);

                    if (((bool)flags.Shops))
                    {
                        var excludeItemsFromRandomShops = new List <Item>();
                        if ((bool)flags.Treasures)
                        {
                            excludeItemsFromRandomShops = incentivesData.ForcedItemPlacements.Select(x => x.Item).Concat(incentivesData.IncentiveItems).ToList();
                        }

                        if (!((bool)flags.RandomWaresIncludesSpecialGear))
                        {
                            excludeItemsFromRandomShops.AddRange(ItemLists.SpecialGear);
                            if ((bool)flags.GuaranteedRuseItem)
                            {
                                excludeItemsFromRandomShops.Add(Item.PowerRod);
                            }
                        }

                        if ((bool)flags.NoMasamune)
                        {
                            excludeItemsFromRandomShops.Add(Item.Masamune);
                        }

                        shopItemLocation = ShuffleShops(rng, (bool)flags.ImmediatePureAndSoftRequired, ((bool)flags.RandomWares), excludeItemsFromRandomShops, flags.WorldWealth);
                        incentivesData   = new IncentiveData(rng, flags, overworldMap, shopItemLocation);
                    }

                    if ((bool)flags.Treasures)
                    {
                        generatedPlacement = ShuffleTreasures(rng, flags, incentivesData, shopItemLocation, overworldMap, teleporters);
                    }
                    break;
                }
                catch (InsaneException e)
                {
                    Console.WriteLine(e.Message);
                    if (maxRetries > (i + 1))
                    {
                        continue;
                    }
                    throw new InvalidOperationException(e.Message);
                }
            }

            // Change Astos routine so item isn't lost in wall of text
            if ((bool)flags.NPCItems || (bool)flags.NPCFetchItems || (bool)flags.ShuffleAstos)
            {
                talkroutines.Replace(newTalkRoutines.Talk_Astos, Blob.FromHex("A674F005BD2060F027A5738561202096B020A572203D96A575200096A476207F90207392A5611820109F201896A9F060A57060"));
            }

            npcdata.UpdateItemPlacement(generatedPlacement);

            if ((bool)flags.MagicShopLocs)
            {
                ShuffleMagicLocations(rng);
            }

            if (((bool)flags.MagicShops))
            {
                ShuffleMagicShops(rng);
            }

            if (((bool)flags.MagicLevels))
            {
                ShuffleMagicLevels(rng, ((bool)flags.MagicPermissions), (bool)flags.MagicLevelsTiered, (bool)flags.MagicLevelsMixed, (bool)!flags.GenerateNewSpellbook);
            }

            new StartingInventory(rng, flags, this).SetStartingInventory();

            /*
             * if (flags.WeaponPermissions)
             * {
             *      ShuffleWeaponPermissions(rng);
             * }
             *
             * if (flags.ArmorPermissions)
             * {
             *      ShuffleArmorPermissions(rng);
             * }
             */

            if (flags.SaveGameWhenGameOver)
            {
                EnableSaveOnDeath(flags);
            }

            // Ordered before RNG shuffle. In the event that both flags are on, RNG shuffle depends on this.
            if (((bool)flags.FixMissingBattleRngEntry))
            {
                FixMissingBattleRngEntry();
            }

            if (((bool)flags.Rng))
            {
                ShuffleRng(rng);
            }

            if (((bool)flags.EnemyScripts))
            {
                ShuffleEnemyScripts(rng, (bool)flags.AllowUnsafePirates, (bool)!flags.BossScriptsOnly, ((bool)flags.EnemySkillsSpellsTiered || (bool)flags.ScaryImps), (bool)flags.ScaryImps);
            }

            if (((bool)flags.EnemySkillsSpells))
            {
                if ((bool)flags.EnemySkillsSpellsTiered && (bool)!flags.BossSkillsOnly)
                {
                    GenerateBalancedEnemyScripts(rng, (bool)flags.SwolePirates);
                    ShuffleEnemySkillsSpells(rng, false);
                }
                else
                {
                    ShuffleEnemySkillsSpells(rng, (bool)!flags.BossSkillsOnly);
                }
            }

            if (((bool)flags.EnemyStatusAttacks))
            {
                if (((bool)flags.RandomStatusAttacks))
                {
                    RandomEnemyStatusAttacks(rng, (bool)flags.AllowUnsafePirates, (bool)flags.DisableStunTouch);
                }
                else
                {
                    ShuffleEnemyStatusAttacks(rng, (bool)flags.AllowUnsafePirates);
                }
            }

            if (flags.Runnability == Runnability.Random)
            {
                flags.Runnability = (Runnability)Rng.Between(rng, 0, 3);
            }

            if (flags.Runnability == Runnability.AllRunnable)
            {
                CompletelyRunnable();
            }
            else if (flags.Runnability == Runnability.AllUnrunnable)
            {
                CompletelyUnrunnable();
            }
            else if (flags.Runnability == Runnability.Shuffle)
            {
                ShuffleUnrunnable(rng);
            }

            // Always on to supply the correct changes for WaitWhenUnrunnable
            AllowStrikeFirstAndSurprise(flags.WaitWhenUnrunnable, (bool)flags.UnrunnablesStrikeFirstAndSurprise);

            if (((bool)flags.EnemyFormationsSurprise))
            {
                ShuffleSurpriseBonus(rng);
            }

            // Put this before other encounter / trap tile edits.
            if ((bool)flags.AllowUnsafeMelmond)
            {
                EnableMelmondGhetto(flags.EnemizerEnabled);
            }

            // After unrunnable shuffle and before formation shuffle. Perfect!
            if (flags.WarMECHMode != WarMECHMode.Vanilla)
            {
                WarMECHNpc(flags.WarMECHMode, npcdata, rng, maps);
            }

            if (flags.WarMECHMode == WarMECHMode.Unleashed)
            {
                UnleashWarMECH();
            }

            if ((bool)flags.ClassAsNpcFiends || (bool)flags.ClassAsNpcKeyNPC)
            {
                ClassAsNPC(flags, talkroutines, npcdata, flippedMaps, rng);
            }

            if ((bool)flags.FiendShuffle)
            {
                FiendShuffle(rng);
            }

            if (flags.FormationShuffleMode != FormationShuffleMode.None && !flags.EnemizerEnabled)
            {
                ShuffleEnemyFormations(rng, flags.FormationShuffleMode);
            }

            if ((bool)flags.RemoveTrapTiles)
            {
                RemoveTrapTiles(flags.EnemizerEnabled);
            }

            if (((bool)flags.EnemyTrapTiles) && !flags.EnemizerEnabled)
            {
                ShuffleTrapTiles(rng, ((bool)flags.RandomTrapFormations));
            }

            if ((bool)flags.OrdealsPillars)
            {
                ShuffleOrdeals(rng, maps);
            }

            if (flags.SkyCastle4FMazeMode == SkyCastle4FMazeMode.Maze)
            {
                DoSkyCastle4FMaze(rng, maps);
            }
            else if (flags.SkyCastle4FMazeMode == SkyCastle4FMazeMode.Teleporters)
            {
                ShuffleSkyCastle4F(rng, maps);
            }

            if ((bool)flags.ConfusedOldMen)
            {
                EnableConfusedOldMen(rng);
            }

            if ((bool)flags.EarlyOrdeals)
            {
                EnableEarlyOrdeals();
            }

            if (flags.ChaosRush)
            {
                EnableChaosRush();
            }
            if ((bool)flags.EarlyKing)
            {
                EnableEarlyKing(npcdata);
            }

            if ((bool)flags.EarlySarda)
            {
                EnableEarlySarda(npcdata);
            }

            if ((bool)flags.EarlySage)
            {
                EnableEarlySage(npcdata);
            }

            if ((bool)flags.FreeBridge)
            {
                EnableFreeBridge();
            }

            if ((bool)flags.FreeAirship)
            {
                EnableFreeAirship();
            }

            if ((bool)flags.FreeShip)
            {
                EnableFreeShip();
            }

            if (flags.FreeOrbs)
            {
                EnableFreeOrbs();
            }

            if ((bool)flags.FreeCanal)
            {
                EnableFreeCanal((bool)flags.NPCItems, npcdata);
            }

            if ((bool)flags.FreeCanoe)
            {
                EnableFreeCanoe();
            }

            if ((bool)flags.FreeLute)
            {
                EnableFreeLute();
            }

            if ((bool)flags.FreeTail && !(bool)flags.NoTail)
            {
                EnableFreeTail();
            }

            if (flags.NoPartyShuffle)
            {
                DisablePartyShuffle();
            }

            if (flags.SpeedHacks)
            {
                EnableSpeedHacks();
            }

            if (flags.IdentifyTreasures)
            {
                EnableIdentifyTreasures();
            }

            if (flags.Dash)
            {
                EnableDash();
            }

            if (flags.BuyTen)
            {
                EnableBuyQuantity();
            }

            if (flags.WaitWhenUnrunnable)
            {
                ChangeUnrunnableRunToWait();
            }

            if (flags.SpeedHacks && flags.EnableCritNumberDisplay)
            {
                EnableCritNumberDisplay();
            }

            if (flags.BattleMagicMenuWrapAround)
            {
                BattleMagicMenuWrapAround();
            }

            if (flags.NPCSwatter)
            {
                EnableNPCSwatter(npcdata);
            }

            if (flags.EasyMode)
            {
                EnableEasyMode();
            }

            if ((bool)flags.TrappedChests || (bool)flags.TCMasaGuardian || (bool)flags.TrappedShards)
            {
                MonsterInABox(rng, flags);
            }

            if (flags.HouseMPRestoration || flags.HousesFillHp)
            {
                FixHouse(flags.HouseMPRestoration, flags.HousesFillHp);
            }

            if (flags.BBCritRate)
            {
                DontDoubleBBCritRates();
            }

            if (flags.WeaponCritRate)
            {
                DoubleWeaponCritRates();
            }

            //needs to go after item magic, moved after double weapon crit to have more control over the actual number of crit gained.
            if ((bool)flags.RandomWeaponBonus)
            {
                RandomWeaponBonus(rng, flags.RandomWeaponBonusLow, flags.RandomWeaponBonusHigh, (bool)flags.RandomWeaponBonusExcludeMasa);
            }

            if ((bool)flags.RandomArmorBonus)
            {
                RandomArmorBonus(rng, flags.RandomArmorBonusLow, flags.RandomArmorBonusHigh);
            }

            if (flags.WeaponBonuses)
            {
                IncreaseWeaponBonus(flags.WeaponTypeBonusValue);
            }

            if (flags.WeaponStats)
            {
                FixWeaponStats();
            }

            if (flags.ChanceToRun)
            {
                FixChanceToRun();
            }

            if (flags.EnemyStatusAttackBug)
            {
                FixEnemyStatusAttackBug();
            }

            if (flags.BlackBeltAbsorb)
            {
                FixBBAbsorbBug();
            }

            if (flags.MDefMode != MDEFGrowthMode.None)
            {
                MDefChanges(flags.MDefMode);
            }

            if (flags.ThiefHitRate)
            {
                ThiefHitRate();
            }

            if (flags.ImproveTurnOrderRandomization)
            {
                ImproveTurnOrderRandomization(rng);
            }

            if (flags.FixHitChanceCap)
            {
                FixHitChanceCap();
            }

            if (flags.EnemyElementalResistancesBug)
            {
                FixEnemyElementalResistances();
            }

            if (preferences.FunEnemyNames && !flags.EnemizerEnabled)
            {
                FunEnemyNames(preferences.TeamSteak);
            }

            var itemText = ReadText(ItemTextPointerOffset, ItemTextPointerBase, ItemTextPointerCount);

            itemText[(int)Item.Ribbon] = itemText[(int)Item.Ribbon].Remove(7);

            if ((bool)flags.HintsVillage || (bool)flags.HintsDungeon)
            {
                if ((bool)flags.HintsDungeon)
                {
                    SetDungeonNPC(flippedMaps, rng);
                }

                NPCHints(rng, npcdata, flags, overworldMap);
            }

            ExpGoldBoost(flags.ExpBonus, flags.ExpMultiplier);
            ScalePrices(flags, itemText, rng, ((bool)flags.ClampMinimumPriceScale), shopItemLocation);
            ScaleEncounterRate(flags.EncounterRate / 30.0, flags.DungeonEncounterRate / 30.0);

            overworldMap.ApplyMapEdits();
            WriteMaps(maps);

            WriteText(itemText, ItemTextPointerOffset, ItemTextPointerBase, ItemTextOffset, UnusedGoldItems);

            if ((bool)flags.SwolePirates)
            {
                EnableSwolePirates();
            }

            if (flags.EnemyScaleStatsHigh != 100 || flags.EnemyScaleStatsLow != 100 || ((bool)flags.SeparateEnemyHPScaling && (flags.EnemyScaleHpLow != 100 || flags.EnemyScaleHpHigh != 100)))
            {
                ScaleEnemyStats(rng, flags);
            }

            if (flags.BossScaleStatsHigh != 100 || flags.BossScaleStatsLow != 100 || ((bool)flags.SeparateBossHPScaling && (flags.BossScaleHpLow != 100 || flags.BossScaleHpHigh != 100)))
            {
                ScaleBossStats(rng, flags);
            }

            PartyComposition(rng, flags, preferences);

            if (((bool)flags.RecruitmentMode))
            {
                PubReplaceClinic(rng, flags);
            }

            if ((bool)flags.ChangeMaxMP)
            {
                SetMPMax(flags.RedMageMaxMP, flags.WhiteMageMaxMP, flags.BlackMageMaxMP, flags.KnightMaxMP, flags.NinjaMaxMP);
            }

            if ((bool)flags.ShuffleAstos)
            {
                ShuffleAstos(flags, npcdata, talkroutines, rng);
            }

            if ((bool)flags.EnablePoolParty)
            {
                EnablePoolParty(flags, rng);
            }

            if ((bool)flags.MapCanalBridge)
            {
                EnableCanalBridge();
            }

            if (flags.NoDanMode)
            {
                NoDanMode();
            }

            SetProgressiveScaleMode(flags);

            if ((bool)flags.RandomizeClass)
            {
                RandomizeClass(rng, flags, oldItemNames);
            }

            if ((bool)flags.EnableRandomPromotions)
            {
                EnableRandomPromotions(flags, rng);
            }

            if (flags.DisableTentSaving)
            {
                CannotSaveOnOverworld();
            }

            if (flags.DisableInnSaving)
            {
                CannotSaveAtInns();
            }

            if (flags.PacifistMode && !flags.SpookyFlag)
            {
                PacifistEnd(talkroutines, npcdata, (bool)flags.EnemyTrapTiles || flags.EnemizerEnabled);
            }

            if (flags.ShopInfo)
            {
                ShopUpgrade();
            }

            if (flags.SpookyFlag)
            {
                Spooky(talkroutines, npcdata, rng, flags);
            }

            if (flags.InventoryAutosort && !(preferences.RenounceAutosort))
            {
                EnableInventoryAutosort();
            }

            // We have to do "fun" stuff last because it alters the RNG state.
            // Back up Rng so that fun flags are uniform when different ones are selected
            uint funRngSeed = rng.Next();

            RollCredits(rng);

            if (preferences.DisableDamageTileFlicker)
            {
                DisableDamageTileFlicker();
            }

            if (preferences.ThirdBattlePalette)
            {
                UseVariablePaletteForCursorAndStone();
            }

            if (preferences.PaletteSwap && !flags.EnemizerEnabled)
            {
                rng = new MT19337(funRngSeed);
                PaletteSwap(rng);
            }

            if (preferences.TeamSteak && !(bool)flags.RandomizeEnemizer)
            {
                TeamSteak();
            }

            if (preferences.ChangeLute)
            {
                rng = new MT19337(funRngSeed);
                ChangeLute(rng);
            }

            rng = new MT19337(funRngSeed);

            HurrayDwarfFate(preferences.HurrayDwarfFate, npcdata, rng);

            if (preferences.Music != MusicShuffle.None)
            {
                rng = new MT19337(funRngSeed);
                ShuffleMusic(preferences.Music, rng);
            }

            if (preferences.DisableSpellCastFlash)
            {
                DisableSpellCastScreenFlash();
            }

            npcdata.WriteNPCdata(this);
            talkroutines.WriteRoutines(this);
            talkroutines.UpdateNPCRoutines(this, npcdata);

            WriteSeedAndFlags(seed.ToHex(), Flags.EncodeFlagsText(flags));
            ExtraTrackingAndInitCode(flags);
        }
Esempio n. 10
0
 /// <summary>
 /// Generates a random initialization vector to be used for the algorithm.
 /// </summary>
 public override void GenerateIV()
 {
     this.IVValue = new byte[this.FeedbackSizeValue / 8];
     Rng.GetBytes(this.IVValue);
 }
Esempio n. 11
0
 /// <summary>
 /// Generates a random key to be used for the algorithm.
 /// </summary>
 public override void GenerateKey()
 {
     this.KeyValue = new byte[this.KeySizeValue / 8];
     Rng.GetBytes(this.KeyValue);
 }
Esempio n. 12
0
        private void SvcGetInfo(AThreadState ThreadState)
        {
            long StackPtr = (long)ThreadState.X0;
            int  InfoType = (int)ThreadState.X1;
            long Handle   = (long)ThreadState.X2;
            int  InfoId   = (int)ThreadState.X3;

            //Fail for info not available on older Kernel versions.
            if (InfoType == 18 ||
                InfoType == 19 ||
                InfoType == 20)
            {
                ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidInfo);

                return;
            }

            switch (InfoType)
            {
            case 0:
                ThreadState.X1 = AllowedCpuIdBitmask;
                break;

            case 2:
                ThreadState.X1 = MemoryRegions.MapRegionAddress;
                break;

            case 3:
                ThreadState.X1 = MemoryRegions.MapRegionSize;
                break;

            case 4:
                ThreadState.X1 = MemoryRegions.HeapRegionAddress;
                break;

            case 5:
                ThreadState.X1 = MemoryRegions.HeapRegionSize;
                break;

            case 6:
                ThreadState.X1 = MemoryRegions.TotalMemoryAvailable;
                break;

            case 7:
                ThreadState.X1 = MemoryRegions.TotalMemoryUsed + CurrentHeapSize;
                break;

            case 8:
                ThreadState.X1 = EnableProcessDebugging ? 1 : 0;
                break;

            case 11:
                ThreadState.X1 = (ulong)Rng.Next() + ((ulong)Rng.Next() << 32);
                break;

            case 12:
                ThreadState.X1 = MemoryRegions.AddrSpaceStart;
                break;

            case 13:
                ThreadState.X1 = MemoryRegions.AddrSpaceSize;
                break;

            case 14:
                ThreadState.X1 = MemoryRegions.MapRegionAddress;
                break;

            case 15:
                ThreadState.X1 = MemoryRegions.MapRegionSize;
                break;

            default:
                Process.PrintStackTrace(ThreadState);

                throw new NotImplementedException($"SvcGetInfo: {InfoType} {Handle:x8} {InfoId}");
            }

            ThreadState.X0 = 0;
        }
Esempio n. 13
0
        private void RollDice()
        {
            if (!CanRoll)
            {
                MessageBox.Show("You can't roll right now");
                return;
            }

            if (GameOver)
            {
                MessageBox.Show("It's game over, please start a new game!");
                return;
            }

            if (Round % 3 == 1)
            {
                CanRoll = false;
            }
            else
            {
                CanRoll = true;
            }

            if (ScoringPossible)
            {
                Round++;
            }
            ScoringPossible = true;

            Message1();
            Message2();

            for (int i = 0; i < 5; i++)
            {
                if (Round % 3 == 0 || DiceCheckboxes[i].IsChecked != true)
                {
                    DiceValues[i] = Rng.Next(1, 7);
                    var uri = new Uri(@"/7Yahtzee;component/Resources/Dice/" + DiceValues[i] + ".png", UriKind.Relative);
                    Dice[i].Source = new BitmapImage(uri);
                }
            }

            int[] DiceCounts = new int[6];
            //count the types of dice
            for (int i = 0; i < 5; i++)
            {
                DiceCounts[DiceValues[i] - 1]++;
            }

            //calculate scoreable points
            int count          = 1;
            int PointsSum      = 0;
            int StraightLength = 0;

            ScoreablePoints = new int[13];
            foreach (int i in DiceCounts)
            {
                if (i > 0)
                {
                    StraightLength++;
                }
                else
                {
                    StraightLength = 0;
                }

                //small straight
                if (StraightLength > 3)
                {
                    ScoreablePoints[9] = 30;
                }
                //large straight
                if (StraightLength > 4)
                {
                    ScoreablePoints[10] = 40;
                }

                ScoreablePoints[count - 1] = count * i;
                PointsSum += count * i;

                count++;
            }
            ScoreablePoints[11] = PointsSum;

            foreach (int i in DiceCounts)
            {
                if (i > 2)
                {
                    //three of a kind
                    ScoreablePoints[6] = PointsSum;


                    foreach (int j in DiceCounts)
                    {
                        if (j == 2)
                        {
                            //full house
                            ScoreablePoints[8] = 25;
                        }
                    }
                }

                if (i > 3)
                {
                    //four of a kind
                    ScoreablePoints[7] = PointsSum;
                }
                if (i > 4)
                {
                    //Yahtzee
                    ScoreablePoints[12] = 50;
                    bool b = false;
                    if (Round < 3 && Scores[12] != null)
                    {
                        b                      = true;
                        Scores[12]            += 100;
                        YahtzeeP1Label.Content = Scores[12].ToString();
                    }
                    else if (Round > 2 && Scores[25] != null)
                    {
                        b                      = true;
                        Scores[25]            += 100;
                        YahtzeeP1Label.Content = Scores[25].ToString();
                    }
                    if (!b)
                    {
                        break;
                    }
                    for (int j = 0; j < 13; j++)
                    {
                        if (j < 6)
                        {
                            ScoreablePoints[j] = (j + 1) * 5;
                        }
                        else if (j == 6 || j == 7 || j == 11)
                        {
                            ScoreablePoints[j] = PointsSum;
                        }
                        else if (j == 8)
                        {
                            ScoreablePoints[j] = 25;
                        }
                        else if (j == 9)
                        {
                            ScoreablePoints[j] = 30;
                        }
                        else if (j == 10)
                        {
                            ScoreablePoints[j] = 40;
                        }
                    }
                }
            }

            //chance
            ScoreablePoints[11] = PointsSum;

            count = 0;
            //display possible scores
            for (int i = 0; i < 26; i++)
            {
                if (Scores[i] == null)
                {
                    ScoreableLabels[i].Content = "";
                }
                ScoreableLabels[i].Opacity = 1;
            }

            //this value determines which side displays the possible scores.
            int coefficient;

            if (Round < 3)
            {
                coefficient = 0;
            }
            else
            {
                coefficient = 13;
            }

            for (int i = coefficient; i < 13 + coefficient; i++)
            {
                if (Scores[i] == null && ScoreablePoints[i % 13] > 0)
                {
                    ScoreableLabels[i].Content = ScoreablePoints[i % 13].ToString();
                    ScoreableLabels[i].Opacity = 0.5;
                }
                count++;
            }
        }
Esempio n. 14
0
 private void ResolveRandomDirection()
 {
     _direction = new Physics().GetDirectionTowards(Vector2.Zero, new Vector2(Rng.Int(-100, 100), Rng.Int(-100, 100)));
 }
Esempio n. 15
0
        private static BigInteger[] findRandomStrongPrime(uint primeBits, int orderBits, Rng random)
        {
            BigInteger one = new BigInteger(1);
            BigInteger u, aux, aux2;
            long[] table_q, table_u, prime_table;
            PrimeSieve sieve = new PrimeSieve(16000);
            uint table_count = sieve.AvailablePrimes() - 1;
            int i, j;
            bool flag;
            BigInteger prime = null, order = null;

            order = BigInteger.genPseudoPrime(orderBits, 20, random);

            prime_table = new long[table_count];
            table_q = new long[table_count];
            table_u = new long[table_count];

            i = 0;
            for (int pN = 2; pN != 0; pN = sieve.getNextPrime(pN), i++) {
                prime_table[i] = (long)pN;
            }

            for (i = 0; i < table_count; i++) {
                table_q[i] =
                    (((order % new BigInteger(prime_table[i])).LongValue()) *
                    (long)2) % prime_table[i];
            }

            while (true) {
                u = new BigInteger();
                u.genRandomBits((int)primeBits, random);
                u.setBit(primeBits - 1);
                aux = order << 1;
                aux2 = u % aux;
                u = u - aux2;
                u = u + one;

                if (u.bitCount() <= (primeBits - 1))
                    continue;

                for (j = 0; j < table_count; j++) {
                    table_u[j] =
                        (u % new BigInteger(prime_table[j])).LongValue();
                }

                aux2 = order << 1;

                for (i = 0; i < (1 << 24); i++) {
                    long cur_p;
                    long value;

                    flag = true;
                    for (j = 1; j < table_count; j++) {
                        cur_p = prime_table[j];
                        value = table_u[j];
                        if (value >= cur_p)
                            value -= cur_p;
                        if (value == 0)
                            flag = false;
                        table_u[j] = value + table_q[j];
                    }
                    if (!flag)
                        continue;

                    aux = aux2 * new BigInteger(i);
                    prime = u + aux;

                    if (prime.bitCount() > primeBits)
                        continue;

                    if (prime.isProbablePrime(20))
                        break;
                }

                if (i < (1 << 24))
                    break;
            }

            return new BigInteger[] { prime, order };
        }
Esempio n. 16
0
        //***********************************************************************
        // Generates a positive BigInteger that is probably prime.
        //***********************************************************************

        public static BigInteger genPseudoPrime(int bits, int confidence, Rng rand) {
            BigInteger result = new BigInteger();
            bool done = false;

            while (!done) {
                result.genRandomBits(bits, rand);
                result.data[0] |= 0x01;		// make it odd

                // prime test
                done = result.isProbablePrime(confidence);
            }
            return result;
        }
Esempio n. 17
0
        // builds a set of 4 weapons that won't include more than 1 bow or shield, nor any lack of ammo
        internal static Equipment BuildViableEquipmentSet()
        {
            //T.Restart();
            var gear       = new Equipment();
            var haveShield = false;
            var haveBow    = false;

            try
            {
                for (var slot = 0; slot < 4; slot++)
                {
                    EquipmentElement randomElement = default;
                    switch (slot)
                    {
                    case 0:
                    case 1:
                        randomElement = EquipmentItems.GetRandomElement();
                        break;

                    case 2 when !gear[3].IsEmpty:
                        randomElement = EquipmentItems.Where(x =>
                                                             x.Item.ItemType != ItemObject.ItemTypeEnum.Bow &&
                                                             x.Item.ItemType != ItemObject.ItemTypeEnum.Crossbow).ToList().GetRandomElement();
                        break;

                    case 2:
                    case 3:
                        randomElement = EquipmentItems.GetRandomElement();
                        break;
                    }

                    // matches here by obtaining a bow, which then stuffed ammo into [3]
                    if (slot == 3 && !gear[3].IsEmpty)
                    {
                        break;
                    }

                    if (randomElement.Item.ItemType == ItemObject.ItemTypeEnum.Bow ||
                        randomElement.Item.ItemType == ItemObject.ItemTypeEnum.Crossbow)
                    {
                        if (slot < 3)
                        {
                            // try again, try harder
                            if (haveBow)
                            {
                                slot--;
                                continue;
                            }

                            haveBow    = true;
                            gear[slot] = randomElement;
                            if (randomElement.Item.ItemType == ItemObject.ItemTypeEnum.Bow)
                            {
                                gear[3] = new EquipmentElement(Arrows.ToList()[Rng.Next(0, Arrows.Count)]);
                            }
                            else if (randomElement.Item.ItemType == ItemObject.ItemTypeEnum.Crossbow)
                            {
                                gear[3] = new EquipmentElement(Bolts.ToList()[Rng.Next(0, Bolts.Count)]);
                            }

                            continue;
                        }

                        randomElement = EquipmentItems.Where(x =>
                                                             x.Item.ItemType != ItemObject.ItemTypeEnum.Bow &&
                                                             x.Item.ItemType != ItemObject.ItemTypeEnum.Crossbow).ToList().GetRandomElement();
                    }

                    if (randomElement.Item.ItemType == ItemObject.ItemTypeEnum.Shield)
                    {
                        // try again, try harder
                        if (haveShield)
                        {
                            slot--;
                            continue;
                        }

                        haveShield = true;
                    }

                    gear[slot] = randomElement;
                }

                gear[5] = new EquipmentElement(ItemTypes[ItemObject.ItemTypeEnum.HeadArmor].GetRandomElement());
                gear[6] = new EquipmentElement(ItemTypes[ItemObject.ItemTypeEnum.BodyArmor].GetRandomElement());
                gear[7] = new EquipmentElement(ItemTypes[ItemObject.ItemTypeEnum.LegArmor].GetRandomElement());
                gear[8] = new EquipmentElement(ItemTypes[ItemObject.ItemTypeEnum.HandArmor].GetRandomElement());
                gear[9] = new EquipmentElement(ItemTypes[ItemObject.ItemTypeEnum.Cape].GetRandomElement());
                //Mod.Log("-----");
                //for (var i = 0; i < 10; i++)
                //{
                //    Mod.Log(gear[i].Item?.Name);
                //}
            }
            catch (Exception ex)
            {
                Mod.Log(ex);
            }

            //Mod.Log($"GEAR ==> {T.ElapsedTicks / 10000F:F3}ms");
            return(gear.Clone());
        }
Esempio n. 18
0
        /// <summary>
        /// Make encoded message (EM) as described in PKCS#1
        /// </summary>
        /// <param name="input">input bytes</param>
        /// <param name="len">total byte length of the result</param>
        /// <param name="rng">random number generator</param>
        /// <returns>new bits</returns>
        public static BigInteger PKCS1PadType2(byte[] input, int len, Rng rng)
        {
            // |00|02|<----- PS ----->|00|<-------- input -------->|
            // |<---------------------- len ---------------------->|

            int padLen = len - input.Length - 3;
            if (padLen < 8) {
                throw new ArgumentException("message too long");
            }

            byte[] pad = new byte[padLen];
            rng.GetBytes(pad);
            for (int i = 0; i < pad.Length; i++) {
                if (pad[i] == 0) {
                    pad[i] = (byte)(1 + rng.GetInt(255));
                }
            }

            byte[] buf = new byte[len];
            buf[1] = 2;
            Buffer.BlockCopy(pad, 0, buf, 2, pad.Length);
            Buffer.BlockCopy(input, 0, buf, padLen + 3, input.Length);

            return new BigInteger(buf);
        }
Esempio n. 19
0
    public void Action(int roll, string player)
    {
        Rng rng = new Rng();

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

        for (int i = 0; i < 6; i++)
        {
            if (Player.names[i] != null && i != Player.turn)
            {
                players.Add(Player.names[i]);
            }
        }
        string rndPlayer = players[rng.Range(0, players.Count)];

        if (roll >= 12 && roll <= 19)
        {
            actions.Add(player + "\nTake " + rng.Range(1, 4) + " sips. Everyone else takes double as many");
            actions.Add(player + "\nTake 1 sip. The next player takes 2 sips. The next again takes 3, etc.");
            actions.Add(player + "\nGive " + rng.Range(2, 5) + " sips to two players each");
            actions.Add(player + "\nGive " + rng.Range(1, 4) + " sips to as many players you want to");
            actions.Add(player + "\nGive out " + rng.Range(4, 8) + " sips");
            actions.Add(player + "\nGive a shot to another player");
            actions.Add(player + "\nGive out sips equal to the current weekday\n(Monday = 1-day, Tuesday = 2s-day etc.)");
            actions.Add(player + "\nGive " + rng.Range(2, 5) + " sips to both your neighbors");

            //actions.Add("");
            //actions.Add("");
            //actions.Add("");
            //actions.Add("");
            //actions.Add("");
            //actions.Add("");
            //actions.Add("");
            //actions.Add("");
        }

        else if (roll >= 6 && roll <= 11)
        {
            actions.Add(rndPlayer + " thinks all girls should drink.\nTake " + rng.Range(2, 5) + " sips each.\nCheers, ladies!");
            actions.Add(rndPlayer + " thinks all girls should drink.\nTake " + rng.Range(2, 5) + " sips each.\nCheers, ladies!");
            actions.Add(rndPlayer + " thinks all girls should take 1 shot. Better do it");

            actions.Add(rndPlayer + " thinks all boys should drink.\nTake " + rng.Range(2, 5) + " sips each.\nCheers, guys!");
            actions.Add(rndPlayer + " thinks all boys should drink.\nTake " + rng.Range(2, 5) + " sips each.\nCheers, guys!");
            actions.Add(rndPlayer + " thinks all boys should take 1 shot. Better do it");

            actions.Add(rndPlayer + " yelled CHEERS!\nEveryone takes " + rng.Range(2, 5) + " sips");
            actions.Add(rndPlayer + " called out for SHOOOOTS!\nEveryone takes 1 shot");
        }

        else if (roll >= 2 && roll <= 5)
        {
            actions.Add(player + "\nAll other players take " + rng.Range(1, 4) + " sips. You take double as many");
            actions.Add(player + "\nTake sips equal to the number of players. The next player takes 1 less. The next again takes 2 less, etc.");
            actions.Add(player + "\nAll other players give you 1 sip each");
            actions.Add(player + "\nTake a shot");
        }

        else if (roll == 1)
        {
            actions.Add(player + "\nDown your drink or take " + rng.Range(2, 4) + " shots");

            Misc.info.GetComponentInChildren <Text>().color = Color.HSVToRGB((1f / 360) * 0, 1, 0.5f);
        }

        else if (roll == 20)
        {
            actions.Add(player + "\nChoose another player.\nThey will choose to down their drink or take " + rng.Range(2, 4) + " shots");

            Misc.info.GetComponentInChildren <Text>().color = Color.HSVToRGB((1f / 360) * 120, 1, 0.5f);
        }

        Misc.info.GetComponentInChildren <Text>().text = actions[rng.Range(0, actions.Count)];
    }
Esempio n. 20
0
        private static BigInteger[] findRandomStrongPrime(int primeBits, int orderBits, Rng random)
        {
            BigInteger one = new BigInteger(1);
            ulong[] table_q, table_u, prime_table;
            PrimeSieve sieve = new PrimeSieve(16000);
            uint table_count = sieve.AvailablePrimes() - 1;
            int i, j;
            bool flag;
            BigInteger prime = null, order = null;

            order = BigInteger.GeneratePseudoPrime(orderBits);

            prime_table = new ulong[table_count];
            table_q = new ulong[table_count];
            table_u = new ulong[table_count];

            i = 0;
            for (uint pN = 2; pN != 0; pN = sieve.getNextPrime(pN), i++) {
                prime_table[i] = pN;
            }

            for (i = 0; i < table_count; i++) {
                table_q[i] =
                    ((AsUInt64(order % new BigInteger(prime_table[i]))) *
                    2UL) % prime_table[i];
            }

            while (true) {
                BigInteger u = BigInteger.GenerateRandom(primeBits);
                BigInteger aux = order << 1;
                BigInteger aux2 = u % aux;
                u = u - aux2;
                u = u + one;

                if (u.BitCount() <= (primeBits - 1))
                    continue;

                for (j = 0; j < table_count; j++) {
                    table_u[j] =
                        AsUInt64(u % new BigInteger(prime_table[j]));
                }

                aux2 = order << 1;

                for (i = 0; i < (1 << 24); i++) {
                    ulong cur_p;
                    ulong value;

                    flag = true;
                    for (j = 1; j < table_count; j++) {
                        cur_p = prime_table[j];
                        value = table_u[j];
                        if (value >= cur_p)
                            value -= cur_p;
                        if (value == 0)
                            flag = false;
                        table_u[j] = value + table_q[j];
                    }
                    if (!flag)
                        continue;

                    aux = aux2 * new BigInteger(i);
                    prime = u + aux;

                    if (prime.BitCount() > primeBits)
                        continue;

                    if (prime.IsProbablePrime())
                        break;
                }

                if (i < (1 << 24))
                    break;
            }

            return new BigInteger[] { prime, order };
        }
Esempio n. 21
0
 protected override void OneTimeSetup()
 {
     factory     = new GunFactory();
     always3     = new Rng(3);
     combatStats = new CombatStats(new Modifier(3), new Modifier(2), 20);
 }
Esempio n. 22
0
 public static A random <C, A>(this NonEmpty <C> list, ref Rng rng)
     where C : IReadOnlyList <A>
 =>
 list.a[rng.nextIntInRange(new Range(0, list.a.Count - 1), out rng)];
Esempio n. 23
0
 public Color Next()
 {
     return(new Color(Rng.Int(255), Rng.Int(255), Rng.Int(255)));
 }
Esempio n. 24
0
   public static Option <int> randomIndex <A>(this IList <A> list, ref Rng rng) =>
   list.Count == 0
 ? F.none <int>()
 : F.some(rng.nextIntInRange(new Range(0, list.Count - 1), out rng));
Esempio n. 25
0
        public const double TileLengthInMeter = 1f;     // length of 1 square tile

        public static double SkillRoll()
        {
            return(Rng.GaussianDouble(Mean, 5 * StandardDeviation, StandardDeviation));
        }
Esempio n. 26
0
        public static IEnumerable <A> shuffleRepeatedly <A>(this ICollection <A> collection, Rng rng)
        {
            var copy = collection.ToList();

            while (true)
            {
                copy.shuffle(ref rng);
                foreach (var item in copy)
                {
                    yield return(item);
                }
            }
        }
Esempio n. 27
0
 public static float Random(float n)
 {
     return((float)Rng.NextDouble() * n);
 }
Esempio n. 28
0
    void Awake()
    {
        //ui = GameObject.Find ("termui");
        int codelen;

        if (diff == difficulty.easy)
        {
            codelen = 3;
        }
        else if (diff == difficulty.medium)
        {
            codelen = 4;
        }
        else
        {
            codelen = 5;
        }

        code      = new int[codelen];
        screennum = new Text[codelen];
        inpnum    = new int[codelen];

        rng = transform.GetComponent <Rng> ();
        rng.getchance();         //first was always same;
        int chance = 50;

        hackwrap = transform.FindChild("hack");
        float      xoff = -1f;
        GameObject temp;
        Vector3    pos;

        for (int i = 0; i < code.Length; i++)
        {
            if (rng.getchance() < chance)
            {
                code [i] = 0;
            }
            else
            {
                code [i] = 1;
            }
            temp   = Instantiate(numslot, hackwrap);
            pos    = temp.transform.localPosition;
            pos.x += xoff;
            xoff  -= 0.4f;
            temp.transform.localPosition = pos;

            screennum [i] = temp.transform.GetChild(0).GetChild(0).GetComponent <Text> ();
            inpnum [i]    = 0;
        }

        up      = KeyCode.W;
        down    = KeyCode.S;
        left    = KeyCode.A;
        right   = KeyCode.D;
        setcode = KeyCode.E;

        trywrap          = transform.FindChild("tries");
        screentries      = trywrap.GetChild(0).GetChild(0).GetComponent <Text> ();
        screentries.text = "" + tries;

        rightwrap   = transform.FindChild("correct");
        screenright = rightwrap.GetChild(0).GetChild(0).GetComponent <Text> ();
        //screentries.text = ""+tries;
    }
Esempio n. 29
0
 public static float RandomRange(float min, float max)
 {
     return((float)Rng.NextDouble() * (max - min) + min);
 }
Esempio n. 30
0
        private static BigInteger findRandomGenerator(BigInteger order, BigInteger modulo, Rng random)
        {
            BigInteger one = new BigInteger(1);
            BigInteger aux = modulo - new BigInteger(1);
            BigInteger t = aux % order;
            BigInteger generator;

            if (t.LongValue() != 0) {
                return null;
            }

            t = aux / order;

            while (true) {
                generator = new BigInteger();
                generator.genRandomBits(modulo.bitCount(), random);
                generator = generator % modulo;
                generator = generator.modPow(t, modulo);
                if (generator != one)
                    break;
            }

            aux = generator.modPow(order, modulo);

            if (aux != one) {
                return null;
            }

            return generator;
        }
        public void MagisizeWeaponsBalanced(MT19337 rng)
        {
            var Spells = GetSpells();

            var tieredSpells = new List <List <MagicSpell> > {
                Spells.GetRange(0, 16), Spells.GetRange(16, 16), Spells.GetRange(32, 16), Spells.GetRange(48, 16)
            };

            var commonOdds = new List <int> {
                0, 0, 0, 0, 1, 1, 1, 1, 2, 2
            };
            var rareOdds = new List <int> {
                0, 1, 1, 1, 2, 2, 2, 3, 3, 3
            };
            var legendaryOdds = new List <int> {
                1, 2, 2, 2, 3, 3, 3, 3, 3, 3
            };

            for (int i = 0; i < 4; i++)
            {
                tieredSpells[i].RemoveAll(spell => spell.Data[4] == 0);
            }

            foreach (Item weapon in ItemLists.CommonWeaponTier)
            {
                var selectedTier = commonOdds.PickRandom(rng);
                while (tieredSpells[selectedTier].Count == 0)
                {
                    selectedTier = commonOdds.PickRandom(rng);
                }

                WriteItemSpellData(tieredSpells[selectedTier].SpliceRandom(rng), weapon);
            }

            foreach (Item weapon in ItemLists.RareWeaponTier.Except(ItemLists.AllMagicItem).ToList())
            {
                var selectedTier = rareOdds.PickRandom(rng);
                while (tieredSpells[selectedTier].Count == 0)
                {
                    selectedTier = rareOdds.PickRandom(rng);
                }

                WriteItemSpellData(tieredSpells[selectedTier].SpliceRandom(rng), weapon);
            }

            foreach (Item weapon in ItemLists.LegendaryWeaponTier)
            {
                var selectedTier = legendaryOdds.PickRandom(rng);
                while (tieredSpells[selectedTier].Count == 0)
                {
                    selectedTier = legendaryOdds.PickRandom(rng);
                }

                WriteItemSpellData(tieredSpells[selectedTier].SpliceRandom(rng), weapon);
            }

            foreach (Item weapon in ItemLists.UberTier)
            {
                var selectedTier = Rng.Between(rng, 0, 3);
                while (tieredSpells[selectedTier].Count == 0)
                {
                    selectedTier = Rng.Between(rng, 0, 3);
                }

                WriteItemSpellData(tieredSpells[selectedTier].SpliceRandom(rng), weapon);
            }
        }
Esempio n. 32
0
        //***********************************************************************
        // Populates "this" with the specified amount of random bits
        //***********************************************************************

        public void genRandomBits(int bits, Rng rand) {
            int dwords = bits >> 5;
            int remBits = bits & 0x1F;

            if (remBits != 0)
                dwords++;

            if (dwords > maxLength)
                throw (new ArithmeticException("Number of required bits > maxLength."));

            byte[] uintBits = new byte[4];
            for (int i = 0; i < dwords; i++) {
                rand.GetBytes(uintBits);
                data[i] = BitConverter.ToUInt32(uintBits, 0);
            }

            for (int i = dwords; i < maxLength; i++)
                data[i] = 0;

            if (remBits != 0) {
                uint mask = (uint)(0x01 << (remBits - 1));
                data[dwords - 1] |= mask;

                mask = (uint)(0xFFFFFFFF >> (32 - remBits));
                data[dwords - 1] &= mask;
            }
            else
                data[dwords - 1] |= 0x80000000;

            dataLength = dwords;

            if (dataLength == 0)
                dataLength = 1;
        }
        public override void OnInspectorGUI()
        {
            var obj = (TextureToGameObjectImporter)target;

            base.OnInspectorGUI();
            EditorGUILayout.Space();
            if (GUILayout.Button("Generate"))
            {
                if (!obj.texture)
                {
                    EditorUtils.userInfo(
                        "Texture not set!", "Please set the texture before generating.", Log.Level.ERROR
                        );
                    return;
                }

                var        width              = obj.texture.width;
                var        height             = obj.texture.height;
                var        unknownColorsFound = new HashSet <Color32>();
                const byte maxAlpha           = byte.MaxValue;
                var        ignoredColors      = obj.ignoredColors.Select(_ => _.with32Alpha(maxAlpha)).toHashSet();
                var        dictV              = obj.pallete
                                                .GroupBy(_ => _.color.with32Alpha(maxAlpha))
                                                .Select(group => {
                    var count = group.Count();
                    return((
                               count == 1
              ? Either <string, KeyValuePair <Color32, GameObject[]> > .Right(F.kv(
                                                                                  group.Key, group.SelectMany(_ => _.gameObjects).ToArray()
                                                                                  ))
              : Either <string, KeyValuePair <Color32, GameObject[]> > .Left(
                                   $"#{group.Key.toHex()} should have 1 entry: {count} entries found."
                                   )
                               ).asValidation());
                })
                                                .sequenceValidations();
                if (dictV.isLeft)
                {
                    EditorUtils.userInfo(
                        "Invalid pallete!",
                        dictV.__unsafeGetLeft.mkString("\n"),
                        Log.Level.ERROR
                        );
                    return;
                }
                var dict = dictV.__unsafeGetRight.toDict();

                using (var progress = new EditorProgress("Generating objects")) {
                    var pixels = progress.execute("Getting pixels", obj.texture.GetPixels32);
                    var parent = new GameObject(obj.holderGameObjectName).transform;

                    progress.execute("Reading pixels", () => {
                        var rng = new Rng(new Rng.Seed(obj.randomSeed));
                        for (var y = 0; y < height; y++)
                        {
                            for (var x = 0; x < width; x++)
                            {
                                var idx = y * width + x;
                                // ReSharper disable once AccessToDisposedClosure
                                progress.progress(idx, pixels.Length);
                                var pixel = pixels[idx].with32Alpha(maxAlpha);
                                if (dict.TryGetValue(pixel, out var gameObjects))
                                {
                                    var position          = obj.startPoint + new Vector3(x * obj.spacing.x, y * obj.spacing.y);
                                    var go                = gameObjects.random(ref rng).getOrThrow($"No objects for #{pixel.toHex()} found!");
                                    var instantiated      = ((GameObject)PrefabUtility.InstantiatePrefab(go)).transform;
                                    instantiated.parent   = parent;
                                    instantiated.position = position;
                                }
                                else if (!ignoredColors.Contains(pixel))
                                {
                                    unknownColorsFound.Add(pixel);
                                }
                            }
                        }
                    });
                }

                if (unknownColorsFound.nonEmpty())
                {
                    EditorUtils.userInfo(
                        "Found unknown colors!", level: Log.Level.ERROR,
                        body:
                        "These colors were not defined:\n" +
                        unknownColorsFound.Select(_ => $"#{_.toHex()}").OrderBySafe(_ => _).mkString("\n")
                        );
                }
            }
        }
Esempio n. 34
0
        //***********************************************************************
        // Generates a random number with the specified number of bits such
        // that gcd(number, this) = 1
        //***********************************************************************

        public BigInteger genCoPrime(int bits, Rng rand) {
            bool done = false;
            BigInteger result = new BigInteger();

            while (!done) {
                result.genRandomBits(bits, rand);
                //Console.WriteLine(result.ToString(16));

                // gcd test
                BigInteger g = result.gcd(this);
                if (g.dataLength == 1 && g.data[0] == 1)
                    done = true;
            }

            return result;
        }
Esempio n. 35
0
 /// <summary>
 /// create a whole bunch of birds across the map rooms
 /// </summary>
 public void spawnBirds()
 {
     int spawnedBirds  = 0;
     var birdSpawnRng  = new Rng(Random.NextInt(int.MaxValue));
     var birdClassDist = new DiscreteProbabilityDistribution <Wing.WingClass>(birdSpawnRng, new[] {
Esempio n. 36
0
        //***********************************************************************
        // Tests the correct implementation of sqrt() method.
        //***********************************************************************

        public static void SqrtTest(int rounds, Rng rand) {
            for (int count = 0; count < rounds; count++) {
                // generate data of random length
                int t1 = 0;
                while (t1 == 0)
                    t1 = rand.GetInt(1024);

                //Console.Write("Round = " + count);

                BigInteger a = new BigInteger();
                a.genRandomBits(t1, rand);

                BigInteger b = a.sqrt();
                BigInteger c = (b + 1) * (b + 1);

                // check that b is the largest integer such that b*b <= a
                if (c <= a) {
                    //Console.WriteLine("\nError at round " + count);
                    //Console.WriteLine(a + "\n");
                    return;
                }
                //Console.WriteLine(" <PASSED>.");
            }
        }
Esempio n. 37
0
 public override bool Condition()
 {
     return(Rng.Dbl() <= _chance);
 }
Esempio n. 38
0
        public static RSAKeyPair GenerateNew(int bits, Rng rnd) {
            BigInteger one = new BigInteger(1);
            BigInteger p = null;
            BigInteger q = null;
            BigInteger t = null;
            BigInteger p_1 = null;
            BigInteger q_1 = null;
            BigInteger phi = null;
            BigInteger G = null;
            BigInteger F = null;
            BigInteger e = null;
            BigInteger d = null;
            BigInteger u = null;
            BigInteger n = null;

            bool finished = false;

            while (!finished) {
                p = BigInteger.genPseudoPrime(bits / 2, 64, rnd);
                q = BigInteger.genPseudoPrime(bits - (bits / 2), 64, rnd);

                if (p == 0) {
                    continue;
                }
                else if (q < p) {
                    t = q;
                    q = p;
                    p = t;
                }

                t = p.gcd(q);
                if (t != one) {
                    continue;
                }

                p_1 = p - one;
                q_1 = q - one;
                phi = p_1 * q_1;
                G = p_1.gcd(q_1);
                F = phi / G;

                e = one << 5;
                e = e - one;
                do {
                    e = e + (one + one);
                    t = e.gcd(phi);
                } while (t != one);

                // !!! d = e.modInverse(F);
                d = e.modInverse(phi);
                n = p * q;
                u = p.modInverse(q);

                finished = true;
            }

            return new RSAKeyPair(e, d, n, u, p, q);
        }
Esempio n. 39
0
        public static RSAKeyPair GenerateNew(int bits, Rng rnd)
        {
            BigInteger one = new BigInteger(1);
            BigInteger p   = null;
            BigInteger q   = null;
            BigInteger t   = null;
            BigInteger p_1 = null;
            BigInteger q_1 = null;
            BigInteger phi = null;
            BigInteger G   = null;
            BigInteger F   = null;
            BigInteger e   = null;
            BigInteger d   = null;
            BigInteger u   = null;
            BigInteger n   = null;

            bool finished = false;

            while (!finished)
            {
                p = BigInteger.GeneratePseudoPrime(bits / 2);
                q = BigInteger.GeneratePseudoPrime(bits - (bits / 2));

                if (p == 0)
                {
                    continue;
                }
                else if (q < p)
                {
                    t = q;
                    q = p;
                    p = t;
                }

                t = p.GCD(q);
                if (t != one)
                {
                    continue;
                }

                p_1 = p - one;
                q_1 = q - one;
                phi = p_1 * q_1;
                G   = p_1.GCD(q_1);
                F   = phi / G;

                e = one << 5;
                e = e - one;
                do
                {
                    e = e + (one + one);
                    t = e.GCD(phi);
                } while (t != one);

                // !!! d = e.modInverse(F);
                d = e.ModInverse(phi);
                n = p * q;
                u = p.ModInverse(q);

                finished = true;
            }

            return(new RSAKeyPair(e, d, n, u, p, q));
        }
Esempio n. 40
0
        private static BigInteger findRandomGenerator(BigInteger order, BigInteger modulo, Rng random)
        {
            BigInteger one = new BigInteger(1);
            BigInteger aux = modulo - new BigInteger(1);
            BigInteger t = aux % order;
            BigInteger generator;

            if (AsUInt64(t) != 0) {
                return null;
            }

            t = aux / order;

            while (true) {
                generator = BigInteger.GenerateRandom(modulo.BitCount());
                generator = generator % modulo;
                generator = generator.ModPow(t, modulo);
                if (generator != one)
                    break;
            }

            aux = generator.ModPow(order, modulo);

            if (aux != one) {
                return null;
            }

            return generator;
        }
Esempio n. 41
0
 public static Option <A> random <A>(this IList <A> list, ref Rng rng) =>
 list.randomIndex(ref rng).map(idx => list[idx]);
Esempio n. 42
0
 public static Option <Tpl <Rng, A> > randomT <A>(this IList <A> list, Rng rng) =>
 list.randomIndexT(rng).map(t => t.map2(idx => list[idx]));
Esempio n. 43
0
 private ulong GetRnd64()
 {
     return((ulong)Rng.Next() + ((ulong)Rng.Next() << 32));
 }