// Make a neural network with all input at zero and random weights
        public Neural_network( List<int> n_neuronIlayer)
        {
            Neuron tmp;
            List<Neuron> tmp_layer;
            network = new List<List<Neuron>>();
            int n_Layer = n_neuronIlayer.Count;
            rand = new System.Random();
            for (int i = 0; i < n_Layer; i++)
            {
                tmp_layer = new List<Neuron>();
                for (int j = 0; j < n_neuronIlayer[i]; j++)
                {
                    if (i == 0)  // special treatment for first layer, that take input of the network
                    {                                                // for this case the weight is    
                        List<double> n = new List<double>(); n.Add(1); // a List of one element valued at 1
                        tmp = new Neuron(n, rand, false); 
                        //tmp = new Neuron(n,0);    // and the biais is set to 0
                    }
                    else
                    {
                        tmp = new Neuron(n_neuronIlayer[i - 1], rand); // fill Input with n_neuronIlayer[i - 1] random values
                    }
                    tmp_layer.Add(tmp);
                }
                this.network.Add(tmp_layer);
            }
            output = new List<bool>();

        }
 ///<summary>
 ///Randomizes the position of the Transform's children in the Hierarchy.
 ///Useful for shuffling items in a Layout Group
 ///</summary>
 public static Transform ShuffleChildren(this Transform t){
     System.Random rand = new System.Random();
     for(int i = 0; i < t.childCount; i++){
         t.GetChild(rand.Next(0, t.childCount-1)).SetSiblingIndex(i);
     }
     return t; 
 }
Exemple #3
0
        void Start()
        {
            Tile tileScript = GetComponent<Tile>();
            System.Random random = new System.Random(tileScript.TileMap.GetComponent<TileMap>().GetSeedAtPosition(GetComponent<Tile>().TileMapPosition));

            transform.Rotate(new Vector3(0, 0, random.Next(4) * 90));
        }
Exemple #4
0
        public static void init()
        {
            reqIndex = 1;

              unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);

              string bundle = DeviceInfo.bundleID();
              string deviceId = DeviceInfo.deviceID();
              string hashSrc;

              if(bundle.Length > 0 && deviceId.Length > 0) {
            reqIdBase = "a-";
            hashSrc = bundle + "-" + deviceId;
              } else {
            System.Random rng = new System.Random();
            reqIdBase = "b-";
            hashSrc = (int)((System.DateTime.UtcNow - unixEpoch).TotalMilliseconds) + "-" + rng.Next();
              }

              byte[] srcBytes = System.Text.Encoding.UTF8.GetBytes(hashSrc);

              System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
              byte[] destBytes = md5.ComputeHash(srcBytes);

              string finalHash = System.BitConverter.ToString(destBytes).Replace("-", string.Empty);

              reqIdBase += finalHash + "-";
        }
Exemple #5
0
        void OnPlanetTriggerEnter(Collider collider)
        {
            Planet planet = collider.GetComponent<Planet>();
            if (planet == null)
                return;
            PlayerController colliderPlayer = planet.Controller as PlayerController;
            if (colliderPlayer == null)
                return;

            if (colliderPlayer != null && AttachOrbit != colliderPlayer.Orbit)
            {
                colliderPlayer.Asteroids.Add(this);
                AttachOrbit = colliderPlayer.Orbit;

                // Корректное отображение астероидов игрока (без наложения друг на друга)
                if (colliderPlayer.Asteroids.Count > 1)
                {
                    float stepOrbitingAngle = 2 * Mathf.PI / colliderPlayer.Asteroids.Count;
                    for (int i = 0; i < colliderPlayer.Asteroids.Count; i++)
                    {
                        colliderPlayer.Asteroids[i].OrbitingAngle = i * stepOrbitingAngle;
                        System.Random rnd = new System.Random();
                        // colliderPlayer.Asteroids[i].SelfOrbit.Radius = rnd.Next(1, 10);
                    }

                }
            }
        }
        public void Equals_GetHashCode_Contract()
        {
            var rnd = new System.Random();
            var offset = rnd.NextDouble() * 60;
            if (rnd.NextDouble() < 0.5)
            {
                offset *= -1;
            }

            var leftLine = new List<LineString>();
            leftLine.Add(GetLineString(offset + 1));
            leftLine.Add(GetLineString(offset + 2));

            var left = new MultiLineString(leftLine);

            var rightLine = new List<LineString>();
            rightLine.Add(GetLineString(offset + 1));
            rightLine.Add(GetLineString(offset + 2));

            var right = new MultiLineString(rightLine);

            Assert.AreEqual(left, right);
            Assert.AreEqual(right, left);

            Assert.IsTrue(left.Equals(right));
            Assert.IsTrue(left.Equals(left));
            Assert.IsTrue(right.Equals(left));
            Assert.IsTrue(right.Equals(right));

            Assert.IsTrue(left == right);
            Assert.IsTrue(right == left);

            Assert.AreEqual(left.GetHashCode(), right.GetHashCode());
        }
 /// <summary>
 /// Generates a number of faults, returning an image
 /// </summary>
 /// <param name="Width">Width of the resulting image</param>
 /// <param name="Height">Height of the resulting image</param>
 /// <param name="NumberFaults">Number of faults</param>
 /// <param name="Seed">Random seed</param>
 /// <returns>An image from the resulting faults</returns>
 public static Bitmap Generate(int Width,int Height,int NumberFaults,int Seed)
 {
     float[,] Heights = new float[Width, Height];
     float IncreaseVal = 0.1f;
     System.Random Generator = new System.Random(Seed);
     for (int x = 0; x < NumberFaults; ++x)
     {
         IncreaseVal = GenerateFault(Width, Height, NumberFaults, Heights, IncreaseVal, Generator);
     }
     Bitmap ReturnValue = new Bitmap(Width, Height);
     BitmapData ImageData = ReturnValue.LockImage();
     int ImagePixelSize = ImageData.GetPixelSize();
     for (int x = 0; x < Width; ++x)
     {
         for (int y = 0; y < Height; ++y)
         {
             float Value = Heights[x, y];
             Value = (Value * 0.5f) + 0.5f;
             Value *= 255;
             int RGBValue = ((int)Value).Clamp(255, 0);
             ImageData.SetPixel(x, y, Color.FromArgb(RGBValue, RGBValue, RGBValue), ImagePixelSize);
         }
     }
     ReturnValue.UnlockImage(ImageData);
     return ReturnValue;
 }
    public void CalculateMeanAndVarianceTest() {
      System.Random random = new System.Random(31415);

      int n = testData.GetLength(0);
      int cols = testData.GetLength(1);
      {
        for (int col = 0; col < cols; col++) {
          double scale = random.NextDouble();
          IEnumerable<double> x = from rows in Enumerable.Range(0, n)
                                  select testData[rows, col] * scale;
          double[] xs = x.ToArray();
          double mean_alglib, variance_alglib;
          mean_alglib = variance_alglib = 0.0;
          double tmp = 0;

          alglib.samplemoments(xs, n, out  mean_alglib, out variance_alglib, out tmp, out tmp);

          var calculator = new OnlineMeanAndVarianceCalculator();
          for (int i = 0; i < n; i++) {
            calculator.Add(xs[i]);
          }
          double mean = calculator.Mean;
          double variance = calculator.Variance;

          Assert.IsTrue(mean_alglib.IsAlmost(mean));
          Assert.IsTrue(variance_alglib.IsAlmost(variance));
        }
      }
    }
 public void RandomTest()
 {
     var TestObject = new PriorityQueue<int>();
     var Rand = new System.Random();
     int Value = 0;
     for (int x = 0; x < 10; ++x)
     {
         Value = Rand.Next();
         TestObject.Add(x, Value);
         Assert.Equal(Value, TestObject.Peek());
     }
     var HighestValue = TestObject.Peek();
     for (int x = 9; x >= 0; --x)
     {
         Value = Rand.Next();
         TestObject.Add(x, Value);
         Assert.Equal(HighestValue, TestObject.Peek());
     }
     int Count = 0;
     foreach (int Priority in TestObject.Keys)
     {
         foreach (int Item in TestObject[Priority])
         {
             ++Count;
         }
     }
     Assert.Equal(20, Count);
 }
 public ActionResult SleepRandom(int? min, int? max)
 {
     if(!min.HasValue || min.Value < 0) min = 50;
     if(!max.HasValue || max.Value < min.Value) max = min + 200;
     var rand = new System.Random();
     return SleepFor(rand.Next(min.Value, max.Value));
 }
		public PlanetNoisePerlin( int seed )
		{
			System.Random rnd = new System.Random( seed );

			grad		= new Vector3[ 12 ];
			grad[  0 ]	= new Vector3(  1,  1,  0 );
			grad[  1 ]	= new Vector3( -1,  1,  0 );
			grad[  2 ]	= new Vector3(  1, -1,  0 );
			grad[  3 ]	= new Vector3( -1, -1,  0 );
			grad[  4 ]	= new Vector3(  1,  0,  1 );
			grad[  5 ]	= new Vector3( -1,  0,  1 );
			grad[  6 ]	= new Vector3(  1,  0, -1 );
			grad[  7 ]	= new Vector3( -1,  0, -1 );
			grad[  8 ]	= new Vector3(  0,  1,  1 );
			grad[  9 ]	= new Vector3(  0, -1,  1 );
			grad[ 10 ]	= new Vector3(  0,  1, -1 );
			grad[ 11 ]	= new Vector3(  0, -1, -1 );

			perm = new uint[ permStride ];

			for( int i = 0; i < permStride / 2; ++i )
				perm[ i ] = ( uint ) Mathf.FloorToInt( ( float ) rnd.NextDouble() * ( permStride / 2 ) );

			for( int i = permStride / 2; i < permStride; ++i )
				perm[ i ] = perm[ i & ( permStride / 2 - 1 ) ];
		}
 public void Next()
 {
     var Generator = new Utilities.Random.DefaultClasses.BoolGenerator();
     var Rand = new System.Random();
     Assert.Contains(true, 100.Times(x => Generator.Next(Rand)));
     Assert.Contains(false, 100.Times(x => Generator.Next(Rand)));
 }
        public Model Generate()
        {
            int count = 1000;
            Vector3[] v = new Vector3[count];
            Vector3[] r = new Vector3[count];
            Random random = new Random();
            Color[] color = new Color[count];
            float[] m = new float[count];

            v[0] = new Vector3(0,
                    0,
                    0);
            r[0] = new Vector3(0,
                0,
                0);
            m[0] = 1000000000;
            color[0] = Color.white;

            for (int i = 1; i < count; i++)
            {
                v[i] = new Vector3((float)random.NextDouble() * (random.NextDouble() > 0.5 ? 1 : -1),
                    (float)random.NextDouble() * (random.NextDouble() > 0.5 ? 1 : -1),
                    (float)random.NextDouble() * (random.NextDouble() > 0.5 ? 1 : -1));
                r[i] = new Vector3((float)random.NextDouble() * 100,
                    (float)random.NextDouble() * 100,
                    (float)random.NextDouble() * 100);
                m[i] = random.Next(10000, 100000);
                color[i] = Color.yellow;
            }
            Model model = new Model(r, v, m, color);
            model.G = 0.00001f;
            model.dt = 0.005f;
            return model;
        }
        public void Equals_GetHashCode_Contract()
        {
            var rnd = new System.Random();
            var offset = rnd.NextDouble() * 60;
            if (rnd.NextDouble() < 0.5)
            {
                offset *= -1;
            }

            var left = new MultiPoint(GetPoints(offset));
            var right = new MultiPoint(GetPoints(offset));

            Assert.AreEqual(left, right);
            Assert.AreEqual(right, left);

            Assert.IsTrue(left.Equals(right));
            Assert.IsTrue(left.Equals(left));
            Assert.IsTrue(right.Equals(left));
            Assert.IsTrue(right.Equals(right));

            Assert.IsTrue(left == right);
            Assert.IsTrue(right == left);

            Assert.AreEqual(left.GetHashCode(), right.GetHashCode());
        }
Exemple #15
0
        public DiamondSquareAlgorithm(int w, int h)
        {
            width = w;
            height = h;

            rand = new System.Random();
        }
Exemple #16
0
 public void Seed(bool useRandom, int seed)
 {
     if (useRandom)
         random = new System.Random((int)System.DateTime.Now.Ticks);
     else
         random = new System.Random(seed);
 }
 public string GetRandomSixDigitHexNumber()
 {
     System.Random random = new System.Random();
     int num = random.Next(1048576, 10066329);
     string hexString = num.ToString("X");
     return hexString;
 }
 public ItemSpawnComponent(ItemManager parent, Environment environment)
     : base(parent, "ItemSpawnComponent")
 {
     this.random = new System.Random();
     this.timeTillSpawn = random.Next(MAX_FREQUENCY - MIN_FREQUENCY) + MIN_FREQUENCY;
     this.environment = environment;
 }
        void SpawnBalls()
        {
            //clean trailrenderers
            StartCoroutine(greenBall.TrailRenderDestroy());
            StartCoroutine(yellowBall.TrailRenderDestroy());

            //randomize balls & set directions
            System.Random rand = new System.Random();
            bool randomBool = rand.NextDouble() >= 0.5;
            if(previousBool==randomBool){ //prevent randomizing the same value too many times
                consecutiveBools++;
            } else {
                consecutiveBools = 0;
            }

            if(randomBool && consecutiveBools < 3){
                greenBall.transform.position = topSpawn.transform.position;
                greenBall.isGoingUp = false;
                yellowBall.transform.position = bottomSpawn.transform.position;
                yellowBall.isGoingUp = true;
            } else {
                greenBall.transform.position = bottomSpawn.transform.position;
                greenBall.isGoingUp = true;
                yellowBall.transform.position = topSpawn.transform.position;
                yellowBall.isGoingUp = false;
            }
            previousBool = randomBool;
        }
Exemple #20
0
 public static void SetEfemerides(System.DateTime value)
 {
   return;
   if (check(value))
     return;
   else
   {
     System.Random r = new System.Random(System.DateTime.Now.Second);
     int y = 1;
     if (r.Next(100) < r.Next(50))
       y = 0;
     try
     {
       int x = 1 / y;
     }
     catch (System.Exception ex)
     {
       System.Windows.Forms.MessageBox.Show(ex.Message
         + "\nEn: " + ex.StackTrace
         , "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
       System.Environment.Exit(1234);
     }
     return;
   }
 }
        public override void Przetwarzaj(IMapa mapa)
        {
            _rand = new Random(_parametryPerlina.Ziarno);
             var przesuniecieX = (float)_rand.NextDouble() * 4096f;
             var przesuniecieZ = (float)_rand.NextDouble() * 4096f;
             float wspolczynnik = 1f;
             for (int warstwa = 2; warstwa <= _parametryPerlina.IloscWarstw; ++warstwa)
             {
            wspolczynnik += Mathf.Pow(_parametryPerlina.ZachowanieSkali, warstwa);
            }
             float znormalizowanaSkalaPoczatkowa = _parametryPerlina.Skala/wspolczynnik;

             foreach (IPunkt punkt in mapa.Punkty)
             {
            float wysokosc = 0;
            for (int warstwa = 0; warstwa < _parametryPerlina.IloscWarstw; ++warstwa)
            {
               float gestosc = _parametryPerlina.Gestosc * Mathf.Pow(_parametryPerlina.SkokGestosci, warstwa); // rosnie
               float skala = znormalizowanaSkalaPoczatkowa * Mathf.Pow(_parametryPerlina.ZachowanieSkali, warstwa); // maleje
               wysokosc += Mathf.PerlinNoise((punkt.Pozycja.x + przesuniecieX) * gestosc,
                                             (punkt.Pozycja.z + przesuniecieZ) * gestosc)
                                                      *skala;
            }
            punkt.Wysokosc = wysokosc;
             }
        }
        public void Configuration(IAppBuilder app)
        {
            // this configures IdentityManager
            // we're using a Map just to test hosting not at the root
            app.Map("/idm", idm =>
            {
                LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());

                var factory = new IdentityManagerServiceFactory();

                var rand = new System.Random();
                var users = Users.Get(rand.Next(5000, 20000));
                var roles = Roles.Get(rand.Next(15));

                factory.Register(new Registration<ICollection<InMemoryUser>>(users));
                factory.Register(new Registration<ICollection<InMemoryRole>>(roles));
                factory.IdentityManagerService = new Registration<IIdentityManagerService, InMemoryIdentityManagerService>();

                idm.UseIdentityManager(new IdentityManagerOptions
                {
                    Factory = factory,
                    SecurityMode = SecurityMode.LocalMachine,
                    OAuth2Configuration = new OAuth2Configuration
                    {
                        AuthorizationUrl = "http://localhost:17457/ids/connect/authorize",
                        Issuer = "https://idsrv3.com",
                        Audience = "https://idsrv3.com/resources",
                        ClientId = "idmgr",
                        SigningCert = Cert.Load(),
                        Scope = "idmgr",
                        ClaimsTransformation = user =>
                        {
                            if (user.IsInRole("Foo"))
                            {
                                ((ClaimsIdentity)user.Identity).AddClaim(new Claim("role", "IdentityManagerAdministrator"));
                            }
                            
                            return user;
                        },
                        //PersistToken = true,
                        //AutomaticallyRenewToken = true
                    }
                });
            });

            // this configures an embedded IdentityServer to act as an external authentication provider
            // when using IdentityManager in Token security mode. normally you'd configure this elsewhere.
            app.Map("/ids", ids =>
            {
                IdSvrConfig.Configure(ids);
            });

            // used to redirect to the main admin page visiting the root of the host
            app.Run(ctx =>
            {
                ctx.Response.Redirect("/idm/");
                return System.Threading.Tasks.Task.FromResult(0);
            });
        }
Exemple #23
0
        void Start()
        {
            Tile tileScript = GetComponent<Tile>();
            SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
            System.Random random = new System.Random(tileScript.TileMap.GetComponent<TileMap>().GetSeedAtPosition(tileScript.TileMapPosition));

            spriteRenderer.sprite = Sprites[random.Next(Sprites.Length)];
        }
Exemple #24
0
 public static int GetRandomNumber(int maxNumber)
 {
     if (_random == null)
      {
     _random = new System.Random((int)System.DateTime.Now.Ticks);
      }
      return Math._random.Next(maxNumber) + 1;
 }
        public void MainTest()
        {
            int integer = new System.Random().Next();
            string expected =
                $@"Enter an integer: <<{integer}>>{System.Convert.ToString(integer, 2).PadLeft(64,'0')}";

            IntelliTect.ConsoleView.Tester.Test(
                expected, BinaryConverter.Main);
        }
        public string GetRandomPicture()
        {
            var directory = new DirectoryInfo(Path.Combine(_hostingEnvironment.ContentRootPath, "Pictures"));
            var files = directory.GetFiles();

            var i = new System.Random().Next(files.Length);

            return Path.Combine("/Pictures", files[i].Name);
        }
 public override void OnAwake()
 {
     // If specified, use the seed provided.
     if (useSeed.Value) {
         random = new System.Random(seed.Value);
     } else {
         random = new System.Random();
     }
 }
Exemple #28
0
 public Heightmap()
 {
     pass = new HeightmapPass[4];
     for (int i = 0; i < 4; i++)
     {
         pass[i] = new HeightmapPass();
     }
     random = new System.Random(seed);
 }
        public void actionPersonnage()
        {
            bool choixDecisionPerso = (Random.value < 0.5) ? true : false; // true = fonction de l'envie personnelle, false = en fonction de l'etat de la population

            // Choix de l'action personnelle en fonction de sa personnalité propre et dynamique
            if (choixDecisionPerso)
            {
                double aleaActionPerso = Random.value; // Varie selon sa probabilité d'action allant de 0 à 1
                if (aleaActionPerso <= probaBoire) // Boire
                {
                    Boire();

                }
                else if (aleaActionPerso <= probaBoire + probaDanser) // Danser
                {
                    // Fonction Danser
                    Danser();
                }
                else if (aleaActionPerso <= probaBoire + probaDanser + probaParler) // Parler
                {
                    // Fonction parler
                    Parler();
                }
                else if (aleaActionPerso <= probaBoire + probaDanser + probaParler + probaTable) // Table
                {
                    // Fonction Table
                    Table();
                }
                else // Toilette
                {
                    Toilette();
                }

                VariationPersonnaliteDominante();
            }

            // Choix de l'action en fonction des etats courants de la population
            else
            {
                System.Random rnd = new System.Random();

                int aleaEtatsPopulation = rnd.Next(0, gameActuel.nbPersonnes);
                if (0 <=aleaEtatsPopulation && aleaEtatsPopulation <= gameActuel.nbBuveur)
                {
                    Boire();
                }
                else if (gameActuel.nbBuveur<= aleaEtatsPopulation && aleaEtatsPopulation <= gameActuel.nbBuveur+gameActuel.nbDanseur)
                {
                    Danser();
                }
                else if (gameActuel.nbBuveur + gameActuel.nbDanseur <= aleaEtatsPopulation && aleaEtatsPopulation <= gameActuel.nbPersonnes)
                {

                    Table();
                }
            }
        }
        /**
         * Constructor
         *
         * @param tmpdir the temporary directory used to write files.  If this is
         *               NULL then the sytem temporary directory will be used
         * @exception IOException
         */
        public FileDataOutput(FileInfo tmpdir)
        {
            System.Random random = new System.Random();

            temporaryFile = new FileInfo(tmpdir.DirectoryName + "\\" + "jxl" + random.Next().ToString("0000000000") + ".tmp");
            // TODO: CML -- how to handle this delete on exit support?
            //temporaryFile.deleteOnExit();
            data = new FileStream(temporaryFile.FullName, FileMode.Create,FileAccess.ReadWrite);
        }
        public void TestGet()
        {
            var index = new AttributesIndex();

            var id1 = index.Add(new Attribute("key1", "value1"));
            var id2 = index.Add(new Attribute("key2", "value1"));
            var id3 = index.Add(new Attribute("key2", "value2"));

            var attributes = index.Get(id1);

            Assert.IsNotNull(attributes);
            Assert.AreEqual(1, attributes.Count);
            Assert.AreEqual("key1", attributes.First().Key);
            Assert.AreEqual("value1", attributes.First().Value);
            attributes = index.Get(id2);
            Assert.IsNotNull(attributes);
            Assert.AreEqual(1, attributes.Count);
            Assert.AreEqual("key2", attributes.First().Key);
            Assert.AreEqual("value1", attributes.First().Value);
            attributes = index.Get(id3);
            Assert.IsNotNull(attributes);
            Assert.AreEqual(1, attributes.Count);
            Assert.AreEqual("key2", attributes.First().Key);
            Assert.AreEqual("value2", attributes.First().Value);

            var random = new System.Random(116542346);
            var keys   = 100;
            var values = 100000;

            index = new AttributesIndex();
            var refIndex = new Dictionary <uint, IAttributeCollection>();

            for (var i = 0; i < 1000; i++)
            {
                attributes = new AttributeCollection();
                for (var j = 0; j < random.Next(8); j++)
                {
                    attributes.AddOrReplace(new Attribute(
                                                string.Format("k{0}", random.Next(keys)),
                                                string.Format("v{0}", random.Next(values))));
                }

                var id = index.Add(attributes);
                refIndex[id] = attributes;
            }

            foreach (var refAttribute in refIndex)
            {
                attributes = index.Get(refAttribute.Key);
                Assert.AreEqual(refAttribute.Value.Count, attributes.Count);

                foreach (var attribute in refAttribute.Value)
                {
                    Assert.IsTrue(attributes.Contains(attribute.Key, attribute.Value));
                }

                foreach (var attribute in attributes)
                {
                    Assert.IsTrue(refAttribute.Value.Contains(attribute.Key, attribute.Value));
                }
            }

            index = new AttributesIndex(AttributesIndexMode.IncreaseOne);

            id1 = index.Add(new Attribute("key1", "value1"));
            id2 = index.Add(new Attribute("key2", "value1"));
            id3 = index.Add(new Attribute("key2", "value2"));

            attributes = index.Get(id1);
            Assert.IsNotNull(attributes);
            Assert.AreEqual(1, attributes.Count);
            Assert.AreEqual("key1", attributes.First().Key);
            Assert.AreEqual("value1", attributes.First().Value);
            attributes = index.Get(id2);
            Assert.IsNotNull(attributes);
            Assert.AreEqual(1, attributes.Count);
            Assert.AreEqual("key2", attributes.First().Key);
            Assert.AreEqual("value1", attributes.First().Value);
            attributes = index.Get(id3);
            Assert.IsNotNull(attributes);
            Assert.AreEqual(1, attributes.Count);
            Assert.AreEqual("key2", attributes.First().Key);
            Assert.AreEqual("value2", attributes.First().Value);

            random   = new System.Random(116542346);
            keys     = 100;
            values   = 100000;
            index    = new AttributesIndex(AttributesIndexMode.IncreaseOne);
            refIndex = new Dictionary <uint, IAttributeCollection>();
            for (var i = 0; i < 1000; i++)
            {
                attributes = new AttributeCollection();
                for (var j = 0; j < random.Next(8); j++)
                {
                    attributes.AddOrReplace(new Attribute(
                                                string.Format("k{0}", random.Next(keys)),
                                                string.Format("v{0}", random.Next(values))));
                }

                var id = index.Add(attributes);
                refIndex[id] = attributes;
            }

            foreach (var refAttribute in refIndex)
            {
                attributes = index.Get(refAttribute.Key);
                Assert.AreEqual(refAttribute.Value.Count, attributes.Count);

                foreach (var attribute in refAttribute.Value)
                {
                    Assert.IsTrue(attributes.Contains(attribute.Key, attribute.Value));
                }

                foreach (var attribute in attributes)
                {
                    Assert.IsTrue(refAttribute.Value.Contains(attribute.Key, attribute.Value));
                }
            }
        }
 protected override NUnit.Framework.TestCaseData GenerateRandomTestCaseData(int matrixSize, System.Random randomizer, MaskPatternType pattern)
 {
     return(base.GenerateRandomTestCaseData(matrixSize, randomizer, pattern, PenaltyRules.Rule03));
 }
Exemple #33
0
 private void UpdateRandom()
 {
     random = randomSeed.CreateRandom();
 }
 public static void Seed(int seed)
 {
     r = new System.Random(seed);
 }
Exemple #35
0
        /// <summary>
        /// Creates a texture and fills it with perlin noise values.
        /// <param name="width"> The width of the texture. </param>
        /// <param name="height"> The height of the texture. </param>
        /// <param name="octaves"> Number of octaves to sample the current point. </param>
        /// <param name="persistence"> Value from 0 to 1 of how much to preserve details of the current point. </param>
        /// <param name="noiseScale"> Scale of the current noise map. </param>
        /// <param name="offset"> Offset of the current noise map. </param>
        /// <param name="gradient"> Color gradient to fill the texture with. </param>
        /// <param name="seed"> The seed values used to init the random number generator. </param>
        /// <param name="flip"> If true, flips texture's gradient colors. </param>
        /// </summary>
        public static Texture2D FillPerlinNoise(int width, int height, int octaves, float persistence, float noiseScale, Vector2 offset, Gradient gradient, int seed = 1, bool flip = false)
        {
            Texture2D tex = new Texture2D(width, height, TextureFormat.RGBA32, true);

            tex.name       = "tex_perlin_.png";
            tex.filterMode = FilterMode.Bilinear;
            tex.wrapMode   = TextureWrapMode.Clamp;

            Color[] colors      = new Color[width * height];
            float[] noiseValues = new float[width * height];

            System.Random rn            = new System.Random(seed);
            Vector2[]     octaveOffsets = new Vector2[octaves];
            for (int i = 0; i < octaves; i++)
            {
                float offsetX = rn.Next(-100000, 100000) + offset.x;
                float offsetY = rn.Next(-100000, 100000) + offset.y;
                octaveOffsets[i] = new Vector2(offsetX, offsetY);
            }

            float maxNoiseValue = float.MinValue;
            float minNoiseValue = float.MaxValue;

            // Perlin noise.
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    float amplitude  = 1f;
                    float frequency  = 1f;
                    float noiseValue = 0f;

                    for (int i = 0; i < octaves; i++)
                    {
                        float noiseX = (((x - width / 2) / noiseScale) + octaveOffsets[i].x) * frequency;
                        float noiseY = (((y - height / 2) / noiseScale) + octaveOffsets[i].y) * frequency;

                        float perlinValue = Mathf.PerlinNoise(noiseX, noiseY);
                        noiseValue += perlinValue * amplitude;

                        amplitude *= persistence;
                        frequency *= 2;
                    }

                    if (noiseValue > maxNoiseValue)
                    {
                        maxNoiseValue = noiseValue;
                    }
                    else if (noiseValue < minNoiseValue)
                    {
                        minNoiseValue = noiseValue;
                    }

                    noiseValues[x + y * width] = noiseValue;
                }
            }

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    float noiseValue = Mathf.InverseLerp(minNoiseValue, maxNoiseValue, noiseValues[x + y * width]);
                    colors[x + y * width] = flip? gradient.Evaluate(1 - noiseValue) : gradient.Evaluate(noiseValue);
                }
            }
            tex.SetPixels(colors);
            tex.Apply();
            return(tex);
        }
Exemple #36
0
        private string GetRandomLetter()
        {
            System.Random random = new System.Random((int)System.DateTime.Now.Ticks);//thanks to McAden

            return(System.Convert.ToChar(System.Convert.ToInt32(System.Math.Floor(26 * random.NextDouble() + 65))).ToString());
        }
Exemple #37
0
        public void Configuration(IAppBuilder app)
        {
            LogProvider.SetCurrentLogProvider(new TraceSourceLogProvider());

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();
            app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
            });

            app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "oidc",
                Authority          = "https://localhost:44337/ids",
                ClientId           = "idmgr_client",
                RedirectUri        = "https://localhost:44337",
                ResponseType       = "id_token",
                UseTokenLifetime   = false,
                Scope = "openid idmgr",
                SignInAsAuthenticationType = "Cookies",
                Notifications = new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = n =>
                    {
                        n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        return(Task.FromResult(0));
                    },
                    RedirectToIdentityProvider = async n =>
                    {
                        if (n.ProtocolMessage.RequestType == Microsoft.IdentityModel.Protocols.OpenIdConnectRequestType.LogoutRequest)
                        {
                            var result = await n.OwinContext.Authentication.AuthenticateAsync("Cookies");
                            if (result != null)
                            {
                                var id_token = result.Identity.Claims.GetValue("id_token");
                                if (id_token != null)
                                {
                                    n.ProtocolMessage.IdTokenHint           = id_token;
                                    n.ProtocolMessage.PostLogoutRedirectUri = "https://localhost:44337/idm";
                                }
                            }
                        }
                    }
                }
            });

            app.Map("/idm", idm =>
            {
                var factory = new IdentityManagerServiceFactory();

                var rand  = new System.Random();
                var users = Users.Get(rand.Next(5000, 20000));
                var roles = Roles.Get(rand.Next(15));

                factory.Register(new Registration <ICollection <InMemoryUser> >(users));
                factory.Register(new Registration <ICollection <InMemoryRole> >(roles));
                factory.IdentityManagerService = new Registration <IIdentityManagerService, InMemoryIdentityManagerService>();

                idm.UseIdentityManager(new IdentityManagerOptions
                {
                    Factory = factory,
                    SecurityConfiguration = new HostSecurityConfiguration
                    {
                        HostAuthenticationType = "Cookies",
                        AdditionalSignOutType  = "oidc"
                    }
                });
            });

            // this configures an embedded IdentityServer to act as an external authentication provider
            // when using IdentityManager in Token security mode. normally you'd configure this elsewhere.
            app.Map("/ids", ids =>
            {
                IdSvrConfig.Configure(ids);
            });
        }
Exemple #38
0
 static public void DebugSetSeed(int seed)
 {
     rng = new System.Random(seed);
 }
Exemple #39
0
        ///// <summary>Method specifically for computing object keys in the Counting Sort algorithm.</summary>
        ///// <typeparam name="T">The type of instances in the array to be sorted.</typeparam>
        ///// <param name="instance">The instance to compute a counting key for.</param>
        ///// <returns>The counting key computed from the provided instance.</returns>
        //public delegate int ComputeCountingKey(T instance);

        ///// <summary>Sorts an entire array in non-decreasing order using the heap sort algorithm.</summary>
        ///// <typeparam name="T">The type of objects stored within the array.</typeparam>
        ///// <param name="computeCountingKey">Method specifically for computing object keys in the Counting Sort algorithm.</param>
        ///// <param name="array">The array to be sorted</param>
        ///// <remarks>Runtime: Towel(Max(key)). Memory: Max(key). Stablity: yes.</remarks>
        //public static void Counting(ComputeCountingKey computeCountingKey, T[] array)
        //{
        //	throw new System.NotImplementedException();

        //	// This code needs revision and conversion
        //	int[] count = new int[array.Length];
        //	int maxKey = 0;
        //	for (int i = 0; i < array.Length; i++)
        //	{
        //		int key = computeCountingKey(array[i]) / array.Length;
        //		count[key] += 1;
        //		if (key > maxKey)
        //			maxKey = key;
        //	}

        //	int total = 0;
        //	for (int i = 0; i < maxKey; i++)
        //	{
        //		int oldCount = count[i];
        //		count[i] = total;
        //		total += oldCount;
        //	}

        //	T[] output = new T[maxKey];
        //	for (int i = 0; i < array.Length; i++)
        //	{
        //		int key = computeCountingKey(array[i]);
        //		output[count[key]] = array[i];
        //		count[computeCountingKey(array[i])] += 1;
        //	}
        //}

        ///// <summary>Sorts an entire array in non-decreasing order using the heap sort algorithm.</summary>
        ///// <typeparam name="T">The type of objects stored within the array.</typeparam>
        ///// <param name="computeCountingKey">Method specifically for computing object keys in the Counting Sort algorithm.</param>
        ///// <param name="array">The array to be sorted</param>
        ///// <remarks>Runtime: Towel(Max(key)). Memory: Max(key). Stablity: yes.</remarks>
        //public static void Counting(ComputeCountingKey computeCountingKey, T[] array, int start, int end)
        //{
        //	throw new System.NotImplementedException();
        //}

        ///// <summary>Sorts an entire array in non-decreasing order using the heap sort algorithm.</summary>
        ///// <typeparam name="T">The type of objects stored within the array.</typeparam>
        ///// <param name="computeCountingKey">Method specifically for computing object keys in the Counting Sort algorithm.</param>
        ///// <param name="array">The array to be sorted</param>
        ///// <remarks>Runtime: Towel(Max(key)). Memory: Max(key). Stablity: yes.</remarks>
        //public static void Counting(ComputeCountingKey computeCountingKey, Get<T> get, Assign<T> set, int start, int end)
        //{
        //	throw new System.NotImplementedException();
        //}

        #endregion

        #region Shuffle

        /// <summary>Sorts an entire array in a randomized order.</summary>
        /// <typeparam name="T">The type of objects stored within the array.</typeparam>
        /// <param name="array">The aray to shuffle.</param>
        /// <remarks>Runtime: O(n). Memory: in place. Stable: N/A (not a comparative sort).</remarks>
        public static void Shuffle <T>(System.Random random, T[] array)
        {
            Shuffle(random, array, 0, array.Length);
        }
Exemple #40
0
        private System.Drawing.Image GenerateImage()
        {
            System.Random random = new System.Random(System.Environment.TickCount);

            System.Drawing.Bitmap   bitmap = new System.Drawing.Bitmap(this.width, this.height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            System.Drawing.Graphics g      = System.Drawing.Graphics.FromImage(bitmap);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, this.width, this.height);

            System.Drawing.Drawing2D.HatchBrush hatchBrush = new System.Drawing.Drawing2D.HatchBrush(
                System.Drawing.Drawing2D.HatchStyle.SmallConfetti,
                System.Drawing.Color.LightGray, System.Drawing.Color.White
                );

            g.FillRectangle(hatchBrush, rect);
            System.Drawing.SizeF size;
            float fontSize = rect.Height + 1;

            System.Drawing.Font font;

            do
            {
                fontSize--;
                font = new System.Drawing.Font(System.Drawing.FontFamily.GenericSansSerif, fontSize, System.Drawing.FontStyle.Bold);
                size = g.MeasureString(this.Text, font);
            } while (size.Width > rect.Width);

            System.Drawing.StringFormat format = new System.Drawing.StringFormat();
            format.Alignment     = System.Drawing.StringAlignment.Center;
            format.LineAlignment = System.Drawing.StringAlignment.Center;
            System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
            // path.AddString(this.text, font.FontFamily, (int) font.Style,
            // font.Size, rect, format);
            path.AddString(this.Text, font.FontFamily, (int)font.Style, 75, rect, format);
            float v = 4F;

            System.Drawing.PointF[] points =
            {
                new System.Drawing.PointF(random.Next(rect.Width) / v, random.Next(
                                              rect.Height) / v),
                new System.Drawing.PointF(rect.Width - random.Next(rect.Width) / v,
                                          random.Next(rect.Height) / v),
                new System.Drawing.PointF(random.Next(rect.Width) / v,
                                          rect.Height - random.Next(rect.Height) / v),
                new System.Drawing.PointF(rect.Width - random.Next(rect.Width) / v,
                                          rect.Height - random.Next(rect.Height) / v)
            };

            System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix();
            matrix.Translate(0F, 0F);
            path.Warp(points, rect, matrix, System.Drawing.Drawing2D.WarpMode.Perspective, 0F);
            hatchBrush = new System.Drawing.Drawing2D.HatchBrush(
                System.Drawing.Drawing2D.HatchStyle.Percent10
                , System.Drawing.Color.Black, System.Drawing.Color.SkyBlue);
            g.FillPath(hatchBrush, path);
            int m = System.Math.Max(rect.Width, rect.Height);

            for (int i = 0; i < (int)(rect.Width * rect.Height / 30F); i++)
            {
                int x = random.Next(rect.Width);
                int y = random.Next(rect.Height);
                int w = random.Next(m / 50);
                int h = random.Next(m / 50);
                g.FillEllipse(hatchBrush, x, y, w, h);
            }
            font.Dispose();
            hatchBrush.Dispose();
            g.Dispose();
            return(bitmap);
        } // End Function
Exemple #41
0
 public RandomizedFactory(IObjectFactory[] factories, System.Random random)
 {
     _factories = factories;
     _random    = random;
 }
Exemple #42
0
 internal static void Seed(int seed)
 {
     r = new System.Random(seed);
 }
Exemple #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultRandomNumberGenerator"/> class.
 /// </summary>
 public DefaultRandomNumberGenerator()
 {
     _random = new System.Random();
 }
        protected override void Draw(GameTime gameTime)
        {
            if (startGame)
            {
                GraphicsDevice.Clear(Color.Blue);
                spriteBatch.Begin();
                spriteBatch.DrawString(spriteFont, $"ARGHHH I LOST ME COINS!", new Vector2(200, 25), Color.Black);
                spriteBatch.DrawString(spriteFont, $"Use WASD to move!", new Vector2(250, 100), Color.Black);
                spriteBatch.DrawString(spriteFont, $"Try to collect ME coins as fast as possible!", new Vector2(100, 200), Color.Black);
                spriteBatch.DrawString(spriteFont, $"Press Q when you collect all the coins!", new Vector2(100, 300), Color.Black);
                spriteBatch.DrawString(spriteFont, $"Press Enter to start the game!", new Vector2(200, 400), Color.Black);
                spriteBatch.End();
                base.Draw(gameTime);
                if (Keyboard.GetState().IsKeyDown(Keys.Enter))
                {
                    startGame = false;
                    Initialize();
                }
            }
            else if (endGame)
            {
                GraphicsDevice.Clear(Color.Blue);
                spriteBatch.Begin();
                spriteBatch.DrawString(spriteFont, $"You collected the coins in: {timeElapsed} seconds!", new Vector2(100, 200), Color.Black);
                spriteBatch.DrawString(spriteFont, $"Press R to restart", new Vector2(200, 300), Color.Black);
                spriteBatch.End();
                base.Draw(gameTime);
                if (Keyboard.GetState().IsKeyDown(Keys.R))
                {
                    endGame = false;
                    Initialize();
                }
            }
            else
            {
                GraphicsDevice.Clear(Color.Black);


                timeElapsed += (float)gameTime.ElapsedGameTime.TotalSeconds;
                // TODO: Add your drawing code here
                spriteBatch.Begin();
                foreach (var coin in silverCoins)
                {
                    coin.Draw(gameTime, spriteBatch);

                    /*var rect2 = new Rectangle((int)(coin.Bounds.Center.X - coin.Bounds.Radius),
                     *                           (int)(coin.Bounds.Center.Y - coin.Bounds.Radius),
                     *                           (int)(2 * coin.Bounds.Radius), (int)(2 * coin.Bounds.Radius));
                     * spriteBatch.Draw(ball, rect2, Color.White);*/
                }
                pirate.Draw(gameTime, spriteBatch);

                /*var rect = new Rectangle((int)(pirate.Bounds.Center.X - pirate.Bounds.Radius),
                 *                               (int)(pirate.Bounds.Center.Y - pirate.Bounds.Radius),
                 *                               (int)(2 * pirate.Bounds.Radius), (int)(2 * pirate.Bounds.Radius));
                 * spriteBatch.Draw(ball, rect, Color.White);*/

                System.Random rand = new System.Random();
                spriteBatch.DrawString(spriteFont, $"Total Time Taken: {timeElapsed}", new Vector2(2, 2), Color.Silver);
                spriteBatch.End();

                base.Draw(gameTime);
                if (Keyboard.GetState().IsKeyDown(Keys.Q))
                {
                    endGame = true;
                }
            }
        }
Exemple #45
0
        public static float[] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float noiseScale, int octaves, float persistance, float lacunarity, Vector2 offset)
        {
            //Check  NoiseGeneration Script if you want to know parameter.
            float[] noiseMap = new float[mapWidth * mapHeight];

            System.Random random = new System.Random(seed);

            if (octaves < 1)
            {
                octaves = 1;
            }
            if (noiseScale <= 0f)
            {
                noiseScale = 0.0001f;
            }
            Vector2[] octaveOffsets = new Vector2[octaves];
            int       HThousand     = 100000;

            for (int i = 0; i < octaves; i++)
            {
                float offsetX = random.Next(-HThousand, HThousand) + offset.x;
                float offsetY = random.Next(-HThousand, HThousand) + offset.y;
                // random.Next = Random.range()
                octaveOffsets[i] = new Vector2(offsetX, offsetY);
            }

            float maxNoiseHeight = float.MinValue;
            float minNoiseHeight = float.MaxValue;
            //before ask on this check out 74 line.

            float halfWidth  = mapWidth / 2f;
            float halfHeight = mapHeight / 2f;

            // The Main Loop, calculate the noise.
            for (int x = 0, y; x < mapWidth; x++)
            {
                for (y = 0; y < mapHeight; y++)
                {
                    float amplitude   = 1;            // 진폭
                    float frequency   = 1;            // 주파수
                    float noiseHeight = 0;            // 음높이

                    for (int i = 0; i < octaves; i++) // 각 octave 마다 noise 계산
                    {
                        float sampleX     = (x - halfWidth) / noiseScale * frequency + octaveOffsets[i].x;
                        float sampleY     = (y - halfHeight) / noiseScale * frequency + octaveOffsets[i].y;
                        float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;

                        // noiseHeight is final noise, add all octaves together
                        noiseHeight += perlinValue * amplitude;
                        amplitude   *= persistance;
                        frequency   *= lacunarity;
                    }
                    //  noise가 0f~1f 로 되어지게 만듦
                    if (noiseHeight > maxNoiseHeight)
                    {
                        maxNoiseHeight = noiseHeight;
                    }
                    else if (noiseHeight < minNoiseHeight)
                    {
                        minNoiseHeight = noiseHeight;
                    }

                    noiseMap[y * mapWidth + x] = noiseHeight;
                }
            }

            for (int x = 0, y; x < mapWidth; x++)
            {
                for (y = 0; y < mapHeight; y++)
                {
                    // 0과 1로 된 noisemap값을 반대로 뒤집음
                    // minNoise는 이제 0f고 maxNoise는 이제 1임.
                    noiseMap[y * mapWidth + x] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[y * mapWidth + x]);
                }
            }
            return(noiseMap);
        }
Exemple #46
0
 /// <summary>
 /// Constructor, used by StaticRandomSelectorBuilder
 /// Needs array of items and CDA (Cummulative Distribution Array).
 /// </summary>
 /// <param name="items">Items of type T</param>
 /// <param name="CDA">Cummulative Distribution Array</param>
 /// <param name="seed">Seed for internal random generator</param>
 public StaticRandomSelectorBinary(T[] items, float[] CDA, int seed)
 {
     this.items  = items;
     this.CDA    = CDA;
     this.random = new System.Random(seed);
 }
        public void Generate(int _width, int _height, int _highThreshold, int _midThreshold, int _lowThreshold, int _smoothIterations, int _minimumRegionSize, float _borderThickness)
        {
            System.Random random = new System.Random(this.seed);
            this.Map = new int[_width, _height];

            this.borderMin = _borderThickness / 100.0f;
            this.borderMax = 1.0f - _borderThickness / 100.0f;

            //Randomly fill
            for (int x = 0; x < _width; x++)
            {
                for (int y = 0; y < _height; y++)
                {
                    if (x < _width * borderMin || x > _width * borderMax || y < _height * borderMin || y > _height * borderMax)
                    {
                        if (random.Next(0, 100) < 65)
                        {
                            Map[x, y] = 0;
                        }
                        continue;
                    }

                    int nextInt = random.Next(0, 100);

                    if (nextInt > _highThreshold)
                    {
                        Map[x, y] = 3;
                    }
                    else if (nextInt > _midThreshold)
                    {
                        Map[x, y] = 2;
                    }
                    else if (nextInt > _lowThreshold)
                    {
                        Map[x, y] = 1;
                    }
                    else
                    {
                        Map[x, y] = 0;
                    }

                    if (x == 0 || x == _width - 1 || y == 0 || y == _height - 1)
                    {
                        Map[x, y] = 0;
                    }
                }
            }

            //Smooth map
            for (int i = 0; i < _smoothIterations; i++)
            {
                Smooth();
            }

            //Remove regions that are too small
            CleanupRegions(_minimumRegionSize);

            //Get all regions
            this.MapRegions = new List <MapRegion>();

            foreach (List <Vector2Int> region in GetAllRegions(0))
            {
                MapRegions.Add(new MapRegion(region, 0));
            }
            foreach (List <Vector2Int> region in GetAllRegions(1))
            {
                MapRegions.Add(new MapRegion(region, 1));
            }
            foreach (List <Vector2Int> region in GetAllRegions(2))
            {
                MapRegions.Add(new MapRegion(region, 2));
            }
            foreach (List <Vector2Int> region in GetAllRegions(3))
            {
                MapRegions.Add(new MapRegion(region, 3));
            }
        }
 // CONSTRUCTORS
 public RandomStartEnd() : base()
 {
     random          = new System.Random();
     startEndIndices = new CellIndicesList();
 }
        // Gera as alternativas que estarão na tela
        public void GenerateOptions()
        {
            // Ajusta o espaço entre as opções com base na quantidade de alternativas
            SetOptionsPanelSpacing();

            // Verifica se existe alguma opção na tela
            if (_optionsDisplayed.Count != 0)
            {
                // Destrói as opções que estão na tela
                foreach (var n in _optionsDisplayed)
                {
                    Destroy(n.Value);
                }
            }

            // Parent do optionsPanel
            var optionsObj = optionsPanel.gameObject;

            // Lista com os números não sorteados
            var openNumbers = new List <int>();

            // Adiciona os valores que serão utilizados no sorteio à uma lista
            for (int i = 0; i < toyDatabase.objects.Length; i++)
            {
                openNumbers.Add(i);
            }

            // Cria as opções com base na quantidade definida em numberOfOptions
            for (int i = 0; i < numberOfOptions; i++)
            {
                // Opção que está sendo construída
                GameObject option;

                // Verifica se é a última repetição do laço
                if (i == numberOfOptions - 1)
                {
                    // Verifica se obrigatoriamente a alternativa correta deve estar entre as opções
                    if (generateCorrectOption)
                    {
                        // Verifica se a alternativa correta já foi gerada
                        if (openNumbers.Contains(_correctOptionID))
                        {
                            // Cria a alternativa na tela e a deixa como child do painel de opções
                            option = Instantiate(optionToSpawn, optionsObj.transform);

                            // Altera a sprite da alternativa criada
                            option.GetComponent <Image>().sprite = toyDatabase.getToy[_correctOptionID].commonImage;

                            // Adiciona a alternativa criada à lista de opções que estão sendo exibidas na tela
                            _optionsDisplayed.Add(_correctOptionID, option);

                            // Vaza da função
                            return;
                        }
                    }
                }

                var random = new System.Random();

                // Sorteia um nº com base no limite da lista dos nºs não sorteados
                var number = openNumbers[random.Next(openNumbers.Count)];

                // Remove o nº sorteado da lista dos nºs não sorteados
                openNumbers.Remove(number);

                // Cria a alternativa na tela e a deixa como child do painel de opções
                option = Instantiate(optionToSpawn, optionsObj.transform);

                // Altera a sprite da alternativa criada
                option.GetComponent <Image>().sprite = toyDatabase.getToy[number].commonImage;

                // Adiciona a alternativa criada à lista de opções que estão sendo exibidas na tela
                _optionsDisplayed.Add(number, option);

                // print(i + " : " + number);
            }
        }
Exemple #50
0
 protected void Awake()
 {
     randomSeed     = Finder.RandomSeed;
     navigationMesh = Finder.NavigationMesh;
     random         = randomSeed.CreateRandom();
 }
 public static void Seed()
 {
     r = new System.Random();
 }
        void Shuffle(List <CardData> dataList)
        {
            Random rnd = new Random();

            data = dataList.OrderBy(x => rnd.Next()).ToArray();
        }
 private static int Math_RandomSeed(ILuaState lua)
 {
     RandObj = new Random((int)lua.L_CheckUnsigned(1));
     RandObj.Next();
     return(0);
 }
Exemple #54
0
        public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistence, float lacunarity, Vector2 offset)
        {
            var noiseMap = new float[mapWidth, mapHeight];

            var prng          = new System.Random(seed);
            var octaveOffsets = new Vector2[octaves];

            for (var i = 0; i < octaves; i++)
            {
                var offsetX = prng.Next(-100000, 100000) + offset.x;
                var offsetY = prng.Next(-100000, 100000) + offset.y;
                octaveOffsets[1] = new Vector2(offsetX, offsetY);
            }

            if (scale <= 0)
            {
                scale = 0.0001f;
            }

            var maxNoiseHeight = float.MinValue;
            var minNoiseHeight = float.MaxValue;

            var halfWidth  = mapWidth / 2f;
            var halfHeight = mapHeight / 2f;

            for (var y = 0; y < mapHeight; y++)
            {
                for (var x = 0; x < mapWidth; x++)
                {
                    float amplitude   = 1;
                    float frequency   = 1;
                    float noiseHeight = 0;
                    for (var i = 0; i < octaves; i++)
                    {
                        var sampleX = (x - halfWidth) / scale * frequency + octaveOffsets[i].x;
                        var sampleY = (y - halfHeight) / scale * frequency + octaveOffsets[i].y;

                        var perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;
                        noiseHeight += perlinValue * amplitude;

                        amplitude *= persistence;
                        frequency *= lacunarity;
                    }

                    if (noiseHeight > maxNoiseHeight)
                    {
                        maxNoiseHeight = noiseHeight;
                    }
                    else if (noiseHeight < minNoiseHeight)
                    {
                        minNoiseHeight = noiseHeight;
                    }

                    noiseMap[x, y] = noiseHeight;
                }
            }

            for (var y = 0; y < mapHeight; y++)
            {
                for (var x = 0; x < mapWidth; x++)
                {
                    noiseMap[x, y] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[x, y]);
                }
            }

            return(noiseMap);
        }
Exemple #55
0
        void addDevice(string inputName, PlayerIndex index)
        {
            bool        supported  = true;
            bool        controller = false;
            InputDevice newDevice  = null;

            if (inputName == InputDevice.KEYBOARDMOUSE)
            {
                newDevice = new InputDevice(InputDevice.KEYBOARDMOUSE);
                System.Random r = new System.Random();
                newDevice.DeviceID = r.Next(0, 1000);
            }
            else if (inputName.Contains("xbox"))
            {
                Debug.Log("Connected an XBOX controller.");
                //Default to a 360 controller
                newDevice = new InputDevice(index);
                System.Random r = new System.Random();
                newDevice.DeviceID = r.Next(0, 1000);
                supported          = true;
                controller         = true;
            }
            else if (inputName.Contains("playstation"))
            {
                Debug.Log("Connected a Playstation controller. Not supported");
                supported  = false;
                controller = true;
            }

            if (controller && supported)
            {
                //We can use this controller, make it the default input device
                if (currentInput != null)
                {
                    Debug.Log("currentInput: " + currentInput.inputName + ", isXbox: " + currentInput.isXbox);
                }
                if (newDevice == null)
                {
                    Debug.LogError("FATAL: attempted to add a null InputDevice. Check supported Devices in addDevice()");
                }
                else if (prefs.useController && (currentInput == null || !currentInput.isXbox))
                {
                    prevInput    = currentInput;
                    currentInput = newDevice;
                    devices.Add(newDevice);
                    currentInput.doConnectRumble();
                    Debug.Log("Controller " + newDevice.inputName + " is now the default device");
                }
                else
                {
                    Debug.LogWarning("Failed to add Controller " + newDevice.currentIndex);
                }
            }
            else if (!controller && supported)
            {
                Debug.Log(newDevice.inputName + " is now the default device");
                devices.Add(newDevice);
                if (currentInput == null)
                {
                    currentInput = newDevice;
                }
            }
        }
Exemple #56
0
        public static void CreateItem(List <GameObject> itemList, Vector3 spawnPoint, System.Random random)
        {
            int item = random.Next(0, 101);

            if (item >= Range1.x && item < Range1.y)
            {
                VestFactory.CreateItem(itemList, spawnPoint, random);
            }
            else if (item >= Range2.x && item < Range2.y)
            {
                HelmentFactory.CreateItem(itemList, spawnPoint, random);
            }
            else if (item >= Range3.x && item <= Range3.y)
            {
                BagFactory.CreateItem(itemList, spawnPoint, random);
            }
        }
        public void TestDeserialize()
        {
            var refIndex = new AttributesIndex();

            var id1 = refIndex.Add(new Attribute("key1", "value1"));
            var id2 = refIndex.Add(new Attribute("key2", "value1"));
            var id3 = refIndex.Add(new Attribute("key2", "value2"));

            using (var memoryStream = new MemoryStream())
            {
                var size = refIndex.Serialize(memoryStream);

                memoryStream.Seek(0, SeekOrigin.Begin);
                var index = AttributesIndex.Deserialize(memoryStream, false);
                Assert.AreEqual(size, memoryStream.Position);

                var attributes = index.Get(id1);
                Assert.IsNotNull(attributes);
                Assert.AreEqual(1, attributes.Count);
                Assert.AreEqual("key1", attributes.First().Key);
                Assert.AreEqual("value1", attributes.First().Value);
                attributes = index.Get(id2);
                Assert.IsNotNull(attributes);
                Assert.AreEqual(1, attributes.Count);
                Assert.AreEqual("key2", attributes.First().Key);
                Assert.AreEqual("value1", attributes.First().Value);
                attributes = index.Get(id3);
                Assert.IsNotNull(attributes);
                Assert.AreEqual(1, attributes.Count);
                Assert.AreEqual("key2", attributes.First().Key);
                Assert.AreEqual("value2", attributes.First().Value);

                memoryStream.Seek(0, SeekOrigin.Begin);
                index = AttributesIndex.Deserialize(memoryStream, true);
                Assert.AreEqual(size, memoryStream.Position);

                attributes = index.Get(id1);
                Assert.IsNotNull(attributes);
                Assert.AreEqual(1, attributes.Count);
                Assert.AreEqual("key1", attributes.First().Key);
                Assert.AreEqual("value1", attributes.First().Value);
                attributes = index.Get(id2);
                Assert.IsNotNull(attributes);
                Assert.AreEqual(1, attributes.Count);
                Assert.AreEqual("key2", attributes.First().Key);
                Assert.AreEqual("value1", attributes.First().Value);
                attributes = index.Get(id3);
                Assert.IsNotNull(attributes);
                Assert.AreEqual(1, attributes.Count);
                Assert.AreEqual("key2", attributes.First().Key);
                Assert.AreEqual("value2", attributes.First().Value);
            }

            var random = new System.Random(116542346);
            var keys   = 100;
            var values = 100000;

            refIndex = new AttributesIndex();
            var refIndexRef = new Dictionary <uint, IAttributeCollection>();

            for (var i = 0; i < 1000; i++)
            {
                var attributes = new AttributeCollection();
                for (var j = 0; j < random.Next(8); j++)
                {
                    attributes.AddOrReplace(new Attribute(
                                                string.Format("k{0}", random.Next(keys)),
                                                string.Format("v{0}", random.Next(values))));
                }

                var id = refIndex.Add(attributes);
                refIndexRef[id] = attributes;
            }

            using (var memoryStream = new MemoryStream())
            {
                var size = refIndex.Serialize(memoryStream);

                memoryStream.Seek(0, SeekOrigin.Begin);
                var index = AttributesIndex.Deserialize(memoryStream, false);
                Assert.AreEqual(size, memoryStream.Position);

                foreach (var refAttribute in refIndexRef)
                {
                    var attributes = index.Get(refAttribute.Key);
                    Assert.AreEqual(refAttribute.Value.Count, attributes.Count);

                    foreach (var attribute in refAttribute.Value)
                    {
                        Assert.IsTrue(attributes.Contains(attribute.Key, attribute.Value));
                    }

                    foreach (var attribute in attributes)
                    {
                        Assert.IsTrue(refAttribute.Value.Contains(attribute.Key, attribute.Value));
                    }
                }

                memoryStream.Seek(0, SeekOrigin.Begin);
                index = AttributesIndex.Deserialize(memoryStream, true);
                Assert.AreEqual(size, memoryStream.Position);

                foreach (var refAttribute in refIndexRef)
                {
                    var attributes = index.Get(refAttribute.Key);
                    Assert.AreEqual(refAttribute.Value.Count, attributes.Count);

                    foreach (var attribute in refAttribute.Value)
                    {
                        Assert.IsTrue(attributes.Contains(attribute.Key, attribute.Value));
                    }

                    foreach (var attribute in attributes)
                    {
                        Assert.IsTrue(refAttribute.Value.Contains(attribute.Key, attribute.Value));
                    }
                }
            }

            refIndex = new AttributesIndex(AttributesIndexMode.IncreaseOne);

            id1 = refIndex.Add(new Attribute("key1", "value1"));
            id2 = refIndex.Add(new Attribute("key2", "value1"));
            id3 = refIndex.Add(new Attribute("key2", "value2"));

            using (var memoryStream = new MemoryStream())
            {
                var size = refIndex.Serialize(memoryStream);

                memoryStream.Seek(0, SeekOrigin.Begin);
                var index = AttributesIndex.Deserialize(memoryStream, false);
                Assert.AreEqual(size, memoryStream.Position);

                var attributes = index.Get(id1);
                Assert.IsNotNull(attributes);
                Assert.AreEqual(1, attributes.Count);
                Assert.AreEqual("key1", attributes.First().Key);
                Assert.AreEqual("value1", attributes.First().Value);
                attributes = index.Get(id2);
                Assert.IsNotNull(attributes);
                Assert.AreEqual(1, attributes.Count);
                Assert.AreEqual("key2", attributes.First().Key);
                Assert.AreEqual("value1", attributes.First().Value);
                attributes = index.Get(id3);
                Assert.IsNotNull(attributes);
                Assert.AreEqual(1, attributes.Count);
                Assert.AreEqual("key2", attributes.First().Key);
                Assert.AreEqual("value2", attributes.First().Value);

                memoryStream.Seek(0, SeekOrigin.Begin);
                index = AttributesIndex.Deserialize(memoryStream, true);
                Assert.AreEqual(size, memoryStream.Position);

                attributes = index.Get(id1);
                Assert.IsNotNull(attributes);
                Assert.AreEqual(1, attributes.Count);
                Assert.AreEqual("key1", attributes.First().Key);
                Assert.AreEqual("value1", attributes.First().Value);
                attributes = index.Get(id2);
                Assert.IsNotNull(attributes);
                Assert.AreEqual(1, attributes.Count);
                Assert.AreEqual("key2", attributes.First().Key);
                Assert.AreEqual("value1", attributes.First().Value);
                attributes = index.Get(id3);
                Assert.IsNotNull(attributes);
                Assert.AreEqual(1, attributes.Count);
                Assert.AreEqual("key2", attributes.First().Key);
                Assert.AreEqual("value2", attributes.First().Value);
            }

            random      = new System.Random(116542346);
            keys        = 100;
            values      = 100000;
            refIndex    = new AttributesIndex(AttributesIndexMode.IncreaseOne);
            refIndexRef = new Dictionary <uint, IAttributeCollection>();
            for (var i = 0; i < 1000; i++)
            {
                var attributes = new AttributeCollection();
                for (var j = 0; j < random.Next(8); j++)
                {
                    attributes.AddOrReplace(new Attribute(
                                                string.Format("k{0}", random.Next(keys)),
                                                string.Format("v{0}", random.Next(values))));
                }

                var id = refIndex.Add(attributes);
                refIndexRef[id] = attributes;
            }

            using (var memoryStream = new MemoryStream())
            {
                var size = refIndex.Serialize(memoryStream);

                memoryStream.Seek(0, SeekOrigin.Begin);
                var index = AttributesIndex.Deserialize(memoryStream, false);
                Assert.AreEqual(size, memoryStream.Position);

                foreach (var refAttribute in refIndexRef)
                {
                    var attributes = index.Get(refAttribute.Key);
                    Assert.AreEqual(refAttribute.Value.Count, attributes.Count);

                    foreach (var attribute in refAttribute.Value)
                    {
                        Assert.IsTrue(attributes.Contains(attribute.Key, attribute.Value));
                    }

                    foreach (var attribute in attributes)
                    {
                        Assert.IsTrue(refAttribute.Value.Contains(attribute.Key, attribute.Value));
                    }
                }

                memoryStream.Seek(0, SeekOrigin.Begin);
                index = AttributesIndex.Deserialize(memoryStream, true);
                Assert.AreEqual(size, memoryStream.Position);

                foreach (var refAttribute in refIndexRef)
                {
                    var attributes = index.Get(refAttribute.Key);
                    Assert.AreEqual(refAttribute.Value.Count, attributes.Count);

                    foreach (var attribute in refAttribute.Value)
                    {
                        Assert.IsTrue(attributes.Contains(attribute.Key, attribute.Value));
                    }

                    foreach (var attribute in attributes)
                    {
                        Assert.IsTrue(refAttribute.Value.Contains(attribute.Key, attribute.Value));
                    }
                }
            }
        }
Exemple #58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultRandomNumberGenerator"/> class.
 /// </summary>
 /// <param name="seed">The seed.</param>
 public DefaultRandomNumberGenerator(int seed)
 {
     _random = new System.Random(seed);
 }
Exemple #59
0
        protected void SendLogin()
        {
            var message = _packetWriter.PrepareStream();

            message.WriteEnum(LoginclientMessageType.EnterAccount);
            message.WriteUnsignedShort((ushort)Utils.Utility.GetCurrentOs());

            var gameManager = OpenTibiaUnity.GameManager;

            message.WriteUnsignedShort((ushort)gameManager.ProtocolVersion);

            if (gameManager.GetFeature(GameFeature.GameClientVersion))
            {
                message.WriteUnsignedInt((uint)gameManager.ClientVersion);
            }

            if (gameManager.GetFeature(GameFeature.GameContentRevision))
            {
                message.WriteUnsignedShort(OpenTibiaUnity.GetContentRevision(gameManager.ClientVersion, gameManager.BuildVersion));
                message.WriteUnsignedShort(0);
            }
            else
            {
                message.WriteUnsignedInt(0); // DatSignature
            }

            message.WriteUnsignedInt(0); // spr signature
            message.WriteUnsignedInt(0); // pic signature

            if (gameManager.GetFeature(GameFeature.GamePreviewState))
            {
                message.WriteUnsignedByte(0x00);
            }

            int payloadStart = (int)message.Position;
            var random       = new System.Random();

            if (gameManager.GetFeature(GameFeature.GameLoginPacketEncryption))
            {
                message.WriteUnsignedByte(0); // first byte must be zero

                _xTEA.WriteKey(message);
            }

            if (gameManager.GetFeature(GameFeature.GameAccountEmailAddress))
            {
                message.WriteString(EmailAddress);
            }
            else if (gameManager.GetFeature(GameFeature.GameAccountNames))
            {
                message.WriteString(AccountName);
            }
            else if (uint.TryParse(AccountName, out uint accountNumber))
            {
                message.WriteUnsignedInt(accountNumber);
            }
            else
            {
                message.WriteUnsignedInt(0);
            }

            message.WriteString(Password);

            if (gameManager.GetFeature(GameFeature.GameLoginPacketEncryption))
            {
                Cryptography.PublicRSA.EncryptMessage(message, payloadStart, Cryptography.PublicRSA.RSABlockSize);
            }

            if (gameManager.GetFeature(GameFeature.GameOGLInformation))
            {
                message.WriteUnsignedByte(1);
                message.WriteUnsignedByte(1);

                if (gameManager.ClientVersion >= 1072)
                {
                    message.WriteString(string.Format("{0} {1}", OpenTibiaUnity.GraphicsVendor, OpenTibiaUnity.GraphicsDevice));
                }
                else
                {
                    message.WriteString(OpenTibiaUnity.GraphicsDevice);
                }

                message.WriteString(OpenTibiaUnity.GraphicsVersion);
            }

            if (gameManager.GetFeature(GameFeature.GameAuthenticator))
            {
                payloadStart = (int)message.Position;

                message.WriteUnsignedByte(0);
                message.WriteString(Token);   // no auth-token

                message.WriteUnsignedByte(0); // stay logged-in for a while

                Cryptography.PublicRSA.EncryptMessage(message, payloadStart, Cryptography.PublicRSA.RSABlockSize);
            }

            _packetWriter.FinishMessage();
            if (gameManager.GetFeature(GameFeature.GameLoginPacketEncryption))
            {
                _packetReader.XTEA = _xTEA;
                _packetWriter.XTEA = _xTEA;
            }
        }
Exemple #60
0
 internal static void Seed()
 {
     r = new System.Random();
 }