NextDouble() public method

public NextDouble ( ) : double
return double
Ejemplo n.º 1
1
        public Pigeon(ContentManager con)
        {
            boundingBox = new Vector3(6, 3, 6);

            distance = 0;
            rand = new Random();

            dx = (0.5-rand.NextDouble())*0.8 + 0.2;
            dy = rand.NextDouble()*1.5 + 0.7;
            dz = 0.8;

            x = 5.8;
            y = -2;
            z = 83.5;

            sx = 5.8;
            sy = -2;
            sz = 83.5;

            this.world = Matrix.CreateTranslation(new Vector3((float)x, (float)y, (float)z));

            model = con.Load<Model>(@"models/pigeon");

            isDone = false;
        }
Ejemplo n.º 2
0
        public Particle(Texture2D texture, Vector2 position, Random random)
        {
            int whichColor = random.Next(3);

            Texture = texture;
            Position = position;
            Velocity = new Vector2(0,0);
            Angle = 0;
            AngularVelocity = 0.05f * (float)(random.NextDouble() * 2 - 1);
            Size = (float)random.NextDouble() / 2;
            TTL = 1000;

            switch (whichColor)
            {
                case 0:
                    Color = new Color(20, 20, 20);
                    break;
                case 1:
                    Color = new Color(40, 40, 40);
                    break;
                case 2:
                    Color = new Color(60, 60, 60);
                    break;
                default:
                    Color = Color.Black;
                    break;
            }

            sizeOverride = true;
            Randomness = new Vector2((float)(random.NextDouble() * 2 - 1), (float)(random.NextDouble() * 2 - 1));
        }
Ejemplo n.º 3
0
        public override void Update(GameTime gameTime, TeeEngine engine)
        {
            Hero player = (Hero) engine.GetEntity("Player");
            KeyboardState keyboardState = Keyboard.GetState();

            if (KeyboardExtensions.GetKeyDownState(keyboardState, Keys.S, this, true)
                && Entity.IntersectsWith(this, "interaction", player, "Shadow", gameTime))
            {
                if (CurrentDrawableState != "Open")
                {
                    Random random = new Random();

                    _openSfx[random.Next(1)].Play();

                    CurrentDrawableState = "Open";
                    Drawables.ResetState("Open", gameTime);

                    for (int i = 0; i < 10; i++)
                    {
                        Coin coin = new Coin(this.Pos.X, this.Pos.Y, 100, (CoinType)random.Next(3));
                        coin.Pos.X += (float) ((random.NextDouble() - 0.5) * 100);
                        coin.Pos.Y += (float) ((random.NextDouble() - 0.5) * 100);
                        coin.TerrainCollisionEnabled = false;       // Prevent from getting stuck in sorrounding walls.

                        engine.AddEntity(coin);
                    }
                }
            }

            base.Update(gameTime, engine);
        }
Ejemplo n.º 4
0
        private static PlotModel RangeColorAxis(AxisPosition position)
        {
            int n = 1000;
            var model = new PlotModel
            {
                Title = string.Format("ScatterSeries and RangeColorAxis (n={0})", n),
                Background = OxyColors.LightGray
            };

            model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom });
            model.Axes.Add(new LinearAxis { Position = AxisPosition.Left });

            var rca = new RangeColorAxis { Position = position, Maximum = 2, Minimum = -2 };
            rca.AddRange(0, 0.5, OxyColors.Blue);
            rca.AddRange(-0.2, -0.1, OxyColors.Red);
            model.Axes.Add(rca);

            var s1 = new ScatterSeries { MarkerType = MarkerType.Square, MarkerSize = 6, };

            var random = new Random(13);
            for (int i = 0; i < n; i++)
            {
                double x = (random.NextDouble() * 2.2) - 1.1;
                s1.Points.Add(new ScatterPoint(x, random.NextDouble()) { Value = x });
            }

            model.Series.Add(s1);
            return model;
        }
Ejemplo n.º 5
0
 public void WriteCoordinatesToCsvFile()
 {
     Random rnd = new Random();
     double[] coords = new double[200];
     double[] z = new double[100];
     for (int i = 0; i < 100; i++)
     {
         coords[i * 2] = rnd.NextDouble() * 6 - 126;
         coords[i * 2 + 1] = rnd.NextDouble() * 90;
     }
     double[] projected = new double[200];
     Array.Copy(coords, projected, 200);
     ProjectionInfo dest = KnownCoordinateSystems.Projected.UtmWgs1984.WGS1984UTMZone10N;
     Reproject.ReprojectPoints(projected, z, KnownCoordinateSystems.Geographic.World.WGS1984, dest, 0, 100);
     StringBuilder sb = new StringBuilder();
     for (int i = 0; i < 100; i++)
     {
         sb.Append(coords[2 * i] + ",");
         sb.Append(coords[2 * i + 1] + ",");
         sb.Append(projected[2 * i] + ",");
         sb.AppendLine(projected[2 * i + 1].ToString());
     }
     Directory.CreateDirectory(@"C:\Data\");
     File.WriteAllText(@"C:\Data\projectionTest.csv", sb.ToString());
 }
        private void UpdateParticlesData(ParticleEmitterComponent smokeParticleEmitterComponent)
        {
            bool isUptoDate = true;
            if (ParticleData == null || ParticleData.Length != Count)
            {
                ParticleData = new ScriptParticleSmoke.ParticleData[Count];
                isUptoDate = false;
            }

            if (isUptoDate)
                return;

            var description = Description;
            var random = new Random();
            var particlesBuffer = (ScriptParticleSmoke.ParticleData[])ParticleData;

            for (int i = 0; i < particlesBuffer.Length; i++)
            {
                particlesBuffer[i] = new ScriptParticleSmoke.ParticleData
                    {
                        Position = description.Position,
                        Velocity = (Half3)(description.Velocity + Vector3.Modulate(new Vector3((float)(random.NextDouble() * 2 - 1), (float)(random.NextDouble() * 2 - 1), (float)(random.NextDouble())), description.Scatter)),
                        Size = (Half)description.InitialSize,
                        Time = (float)random.NextDouble() * description.MaxTime,
                        Opacity = (Half)description.Opacity,
                        Factors = new Half4((Half)random.NextDouble(), (Half)0, (Half)description.Opacity, (Half)0),
                        TimeStep = (Half)10.0f,
                    };
                particlesBuffer[i].Position += ((Vector3)particlesBuffer[i].Velocity) * particlesBuffer[i].Time * 100.0f / 1000.0f;
            }
        }
Ejemplo n.º 7
0
        public override Scene OnLoadScene()
        {
            this.mEngine.RegisterUpdateHandler(new FPSLogger());

            Scene scene = new Scene(1);
            scene.Background = new ColorBackground(0.09804f, 0.6274f, 0.8784f);

            Random random = new Random(RANDOM_SEED);

            for (int i = 0; i < LINE_COUNT; i++)
            {
                float x1 = (float)(random.NextDouble() * CAMERA_WIDTH);
                float x2 = (float)(random.NextDouble() * CAMERA_WIDTH);
                float y1 = (float)(random.NextDouble() * CAMERA_HEIGHT);
                float y2 = (float)(random.NextDouble() * CAMERA_HEIGHT);
                float lineWidth = (float)(random.NextDouble() * 5);

                Line line = new Line(x1, y1, x2, y2, lineWidth);

                line.SetColor((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble());

                scene.getLastChild().attachChild(line);
            }

            return scene;
        }
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            plotter.Visible = new DataRect(0, 0, 1, 1);

            int count = (int)1e4;
            Point[] pts = new Point[count];

            Random rnd = new Random();
            for (int i = 0; i < count; i++)
            {
                pts[i] = new Point(rnd.NextDouble(), rnd.NextDouble());
            }

            markerChart.AddPropertyBinding<Point>(Shape.ToolTipProperty, p =>
            {
                return String.Format("X: {0:F2}   Y: {1:F2}", p.X, p.Y);
            });

            HSBPalette palette = new HSBPalette();
            markerChart.AddPropertyBinding<Point>(Shape.FillProperty, p =>
            {
                double length = Math.Sqrt(p.X * p.X + p.Y * p.Y) / Math.Sqrt(2);

                return new SolidColorBrush(palette.GetColor(length));
            });

            //markerChart.Filters.Add(new BoundsFilter());
            //markerChart.Filters.Add(new ParallelUnitingPointGroupFilter());
            //markerChart.Filters.Add(new ParallelClusteringFilter { MarkerSize = 8 });
            markerChart.Filters.Add(new UnitingPointGroupFilter { MarkerSize = 6 });
            //markerChart.GetDataAsyncronously = true;
            //markerChart.ShowMarkersConsequently = false;

            markerChart.ItemsSource = pts;
        }
        /// <summary>
        /// Den privata statiska metoden RandomizeShapes() ska slumpa mellan 
        /// 5 och 20 figurer vars längder och bredder slumpas till värden av typen 
        /// double i det halvöppna intervallet mellan 5,0 och 100,0 ([5, 100[).
        /// 
        /// Typ av figur ska också slumpas och då måste en ”switch”-sats användas 
        /// tillsammans med uppräkningsbara typen ShapeType, som ska användas för att 
        /// typomvandla heltalet 0 till ShapeType.Ellips och heltalet 1 till 
        /// ShapeType.Rectangle.
        /// 
        /// Referenserna till figurerna ska sparas i en array som metoden returnerar 
        /// en referens till.
        /// </summary>
        /// <returns></returns>
        private static Shape[] RandomizeShapes()
        {
            Random randomNumber = new Random();
            int numberOfShapes = randomNumber.Next(5, 20);
            Shape[] shapes = new Shape[numberOfShapes];
            int maximum = 99;
            int minimum = 5;

            for (int i = 0; i < numberOfShapes; i++)
            {
                double lenght = randomNumber.NextDouble() * (maximum - minimum) + minimum;
                double width = randomNumber.NextDouble() * (maximum - minimum) + minimum;
                int typeOfShape = randomNumber.Next(0, 2);

                switch ((ShapeType)typeOfShape)
                {
                    case ShapeType.Ellipse:
                        shapes[i] = new Ellipse(lenght, width);
                        break;
                    case ShapeType.Rectangle:
                        shapes[i] = new Rectangle(lenght, width);
                        break;
                }
            }
            return shapes;
        }
Ejemplo n.º 10
0
Archivo: Task4.cs Proyecto: annhv/parp
        public static void Start(Random rnd)
        {
            int length = 4096;
            var masComplex1 = new Complex[length];
            var masSimdComplex1 = new Vector2[length];
            var masComplex2 = new Complex[length];
            var masSimdComplex2 = new Vector2[length];
            for (int i = 0; i < length; i++)
            {
                float v1 = (float) rnd.NextDouble()*1000;
                float v2 = (float) rnd.NextDouble()*1000;
                masComplex1[i] = new Complex(v1, v2);
                masSimdComplex1[i] = new Vector2(v1,v2);

                v1 = (float)rnd.NextDouble() * 1000;
                v2 = (float)rnd.NextDouble() * 1000;
                masComplex2[i] = new Complex(v1, v2);
                masSimdComplex2[i] = new Vector2(v1, v2);
            }

            Extensions.TestTime(() =>
                TestWithoutSimd(masComplex1, masComplex2),
                "Время для complex       ");

            Extensions.TestTime(() =>
                TestWithSimd(masSimdComplex1, masSimdComplex2),
                "Время для complex(simd) ");
        }
Ejemplo n.º 11
0
 public Network(List<int> _sizes)
 {
     r = new Random(DateTime.Now.Millisecond);
     sizes = _sizes;
     biases = new List<List<double>>();
     weights = new List<List<double>>();
     for (int j = 0; j < sizes.Count; j++ )
     {
         var t = new List<double>();
         for (int i = 0; i < sizes[j]; i++)
         {
             t.Add(r.NextDouble());
         }
         biases.Add(t);
         if(j+1 != sizes.Count)
         {
             int x = sizes[j];
             int y = sizes[j + 1];
             for (int xi = 0; xi < x; xi++)
             {
                 var temp = new List<double>();
                 for (int yi = 0; yi < y; yi++)
                 {
                     temp.Add(r.NextDouble());
                 }
                 weights.Add(temp);
             }
         }
     }
 }
        public Model3D 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];

            for (int i = 0; i < count; i++)
            {
                v[i] = new Vector3(0,
                    0,
                    0);
                /* r[i] = new Vector3((float)random.NextDouble() * 1,
                     (float)random.NextDouble() * 1,
                     (float)random.NextDouble() * 1);*/
                r[i] = new Vector3((float)random.NextDouble() ,
                                    (float)random.NextDouble() ,
                                    (float)random.NextDouble() );

                m[i] = random.Next(10, 100);
                color[i] = Color.FromArgb(random.Next(100, 200), random.Next(100, 200), random.Next(100, 200));
            }
            Model3D model3D = new Model3D(r, v, m, color);
            model3D.G = 0.1f;
            return model3D;
        }
Ejemplo n.º 13
0
        public Star(GameplayScreen game, Model model, Matrix view, Matrix projection, Random random)
            : base(game.ScreenManager.Game)
        {
            this.random = random;
            this.x = random.Next(-340, 200) / 100f;
            this.speed = random.Next(2, 8) / 1000f;

            float scale = random.Next(100, 1000)/100000f;

            if(speed > 0.0004)
                this.y = random.Next(5, 10);
            else
                this.y = random.Next(2, 5);

            xRotation = (float) random.Next(-360, 360);
            yRotation = (float)random.Next(-360, 360);
            zRotation = (float)random.Next(-360, 360);

            color = new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble());

            this.DrawOrder = 900;
            this.view = view;
            this.projection = projection;
            this.model = model;
            this.game = game;
            this.world = Matrix.Identity * Matrix.CreateScale(scale) * Matrix.CreateTranslation(x, y, 13f);
            transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);
        }
Ejemplo n.º 14
0
        public void Multipg()
        {
            Random rnd = new Random();
            Polygon[] pg = new Polygon[50];
            GeoAPI.Geometries.IPolygon[] pgcheck = new GeoAPI.Geometries.IPolygon[50];
            GisSharpBlog.NetTopologySuite.Geometries.GeometryFactory gf = new GisSharpBlog.NetTopologySuite.Geometries.GeometryFactory();
            for (int i = 0; i < 50; i++)
            {
                Coordinate center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
                Coordinate[] coord = new Coordinate[36];
                GeoAPI.Geometries.ICoordinate[] coordscheck = new GeoAPI.Geometries.ICoordinate[36];
                for (int ii = 0; ii < 36; ii++)
                {
                    coord[ii] = new Coordinate(center.X + Math.Cos((ii * 10) * Math.PI / 10), center.Y + (ii * 10) * Math.PI / 10);
                    double x = coord[ii].X;
                    double y = coord[ii].Y;
                    GisSharpBlog.NetTopologySuite.Geometries.Coordinate c = new GisSharpBlog.NetTopologySuite.Geometries.Coordinate(x, y);
                    coordscheck[ii] = c;
                }
                coord[35] = new Coordinate(coord[0].X, coord[0].Y);
                coordscheck[35] = new GisSharpBlog.NetTopologySuite.Geometries.Coordinate(coordscheck[0].X, coordscheck[0].Y);
                GeoAPI.Geometries.ILinearRing ring = gf.CreateLinearRing(coordscheck);
                pgcheck[i] = gf.CreatePolygon(ring, null);
                pg[i] = new Polygon(coord);

            }
            MultiPolygon mpg = new MultiPolygon(pg);
            GeoAPI.Geometries.IMultiPolygon mpgcheck = gf.CreateMultiPolygon(pgcheck);
            for (int ii = 0; ii < mpg.Coordinates.Count; ii++)
            {
                Assert.AreEqual(mpg.Coordinates[ii].X, mpgcheck.Coordinates[ii].X);
                Assert.AreEqual(mpg.Coordinates[ii].Y, mpgcheck.Coordinates[ii].Y);
            }
        }
Ejemplo n.º 15
0
 public void Multils()
 {
     Random rnd = new Random();
     LineString[] ls = new LineString[40];
     GeoAPI.Geometries.ILineString[] lscheck = new GeoAPI.Geometries.ILineString[40];
     GisSharpBlog.NetTopologySuite.Geometries.GeometryFactory gf = new GisSharpBlog.NetTopologySuite.Geometries.GeometryFactory();
     for (int ii = 0; ii < 40; ii++)
     {
         Coordinate[] coord = new Coordinate[36];
         GeoAPI.Geometries.ICoordinate[] coordcheck = new GeoAPI.Geometries.ICoordinate[36];
         for (int i = 0; i < 36; i++)
         {
             coord[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
             double x = coord[i].X;
             double y = coord[i].Y;
             GisSharpBlog.NetTopologySuite.Geometries.Coordinate c = new GisSharpBlog.NetTopologySuite.Geometries.Coordinate(x, y);
             coordcheck[i] = c;
         }
         ls[ii] = new LineString(coord);
         lscheck[ii] = gf.CreateLineString(coordcheck);
     }
     MultiLineString mls = new MultiLineString(ls);
     GeoAPI.Geometries.IMultiLineString mlscheck = gf.CreateMultiLineString(lscheck);
     for (int ii = 0; ii < mls.Coordinates.Count; ii++)
     {
         Assert.AreEqual(mls.Coordinates[ii].X, mlscheck.Coordinates[ii].X);
         Assert.AreEqual(mls.Coordinates[ii].Y, mlscheck.Coordinates[ii].Y);
     }
     Assert.AreEqual(mls.NumGeometries, mlscheck.NumGeometries);
 }
Ejemplo n.º 16
0
 public ElmansNetwork(int numberOfEntryNeurons,int numberOfHiddenNeurons, int numberOfExitNeurons, bool useTechnicalAnalysis)
 {
     realNumberOfEntryNeurons = numberOfEntryNeurons + 1;
     if (useTechnicalAnalysis)
         realNumberOfEntryNeurons += 2;
     this.useTechnicalAnalysis = useTechnicalAnalysis;
     entryValues = new double[realNumberOfEntryNeurons];
     contextValues = new double[numberOfHiddenNeurons];
     hiddenValues = new double[numberOfHiddenNeurons + 1];
     exitValues = new double[numberOfExitNeurons];
     errorValues = new double[numberOfExitNeurons];
     this.numberOfExitNeurons = numberOfExitNeurons;
     this.numberOfHiddenNeurons = numberOfHiddenNeurons;
     this.numberOfEntryNeurons = numberOfEntryNeurons;
     this.numberOfContextNeurons = numberOfHiddenNeurons;
     Random rand = new Random();
     entryHiddenWeights = new double[this.realNumberOfEntryNeurons, this.numberOfHiddenNeurons];
     contextHiddenWeights = new double[this.numberOfContextNeurons, this.numberOfHiddenNeurons];
     hiddenExitWeights = new double[this.numberOfHiddenNeurons + 1, this.numberOfExitNeurons];
     entryValues[entryValues.Length - 1] = 1;
     hiddenValues[hiddenValues.Length - 1] = 1;
     for (int i = 0; i < realNumberOfEntryNeurons; i++)
         for (int j = 0; j < numberOfHiddenNeurons; j++)
             entryHiddenWeights[i, j] = rand.NextDouble();
     for (int i = 0; i < numberOfContextNeurons; i++)
         for (int j = 0; j < numberOfHiddenNeurons; j++)
             contextHiddenWeights[i, j] = rand.NextDouble();
     for (int i = 0; i < numberOfHiddenNeurons + 1; i++)
         for (int j = 0; j < numberOfExitNeurons; j++)
             hiddenExitWeights[i, j] = rand.NextDouble();
 }
Ejemplo n.º 17
0
 public void RTreeQuery_PointIntersectionTest()
 {
     for (int seed = 0; seed < 1; ++seed)
     {
         int n = 100000;
         var points = new Point[n];
         var rand = new Random(seed);
         double scale = 1000;
         for (int i = 0; i < n; ++i)
         {
             points[i] = new Point(rand.NextDouble() * scale, rand.NextDouble() * scale);
         }
         var bsptree = new RTree<Point>(
             from p in points
             select new KeyValuePair<Rectangle, Point>(new Rectangle(p), p));
         Assert.AreEqual(bsptree.GetAllLeaves().Count(), n);
         Assert.AreEqual(bsptree.GetAllIntersecting(new Rectangle(-2, -2, -1, -1)).Count(), 0);
         Assert.AreEqual(bsptree.GetAllIntersecting(new Rectangle(0, 0, scale, scale)).Count(), n);
         int intersecting = 0;
         for (int i = 0; i < 10000; ++i)
         {
             double s = scale / 100;
             var query = new Rectangle(rand.NextDouble() * s, rand.NextDouble() * s, rand.NextDouble() * s, rand.NextDouble() * s);
             if (bsptree.IsIntersecting(query))
             {
                 ++intersecting;
             }
         }
         System.Console.WriteLine(intersecting);
     }
 }
        /// <summary>
        /// Constructs a new demo.
        /// </summary>
        /// <param name="game">Game owning this demo.</param>
        public RayCastTestDemo(DemosGame game)
            : base(game)
        {
            Space.Add(new Box(new Vector3(0, -0.5f, 0), 50, 1, 50));

            //Put whatever you'd like to ray cast here.
            var capsule = new Capsule(new Vector3(0, 1.2f, 0), 1, 0.6f);
            capsule.AngularVelocity = new Vector3(1, 1, 1);
            Space.Add(capsule);

            var cylinder = new Cylinder(new Vector3(0, 5, 0), 2, .5f);
            cylinder.AngularVelocity = new Vector3(1, -1, 1);
            Space.Add(cylinder);

            var points = new List<Vector3>();

            var random = new Random(0);
            for (int k = 0; k < 40; k++)
            {
                points.Add(new Vector3(1 * (float)random.NextDouble(), 3 * (float)random.NextDouble(), 2 * (float)random.NextDouble()));
            }
            var convexHull = new ConvexHull(new Vector3(0, 10, 0), points);
            convexHull.AngularVelocity = new Vector3(-1, 1, 1);
            Space.Add(convexHull);


            game.Camera.Position = new Vector3(-10, 5, 10);
            game.Camera.Yaw((float)Math.PI / -4f);
            game.Camera.Pitch(-(float)Math.PI / 9f);

            //Starter ray.
            origin = new Vector3(10, 5, 0);
            direction = new Vector3(-3, -1, 0);

        }
Ejemplo n.º 19
0
        protected override void DoInitialize()
        {
            base.DoInitialize();

            {
                // velocity
                var buffer = VertexBuffer.Create(typeof(vec4), ParticleModel.particleCount, VBOConfig.Vec4, "empty", BufferUsage.DynamicCopy);
                unsafe
                {
                    var random = new Random();
                    var array = (vec4*)buffer.MapBuffer(MapBufferAccess.WriteOnly);
                    for (int i = 0; i < ParticleModel.particleCount; i++)
                    {
                        array[i] = new vec4(
                            (float)(random.NextDouble() - 0.5) * 0.2f,
                            (float)(random.NextDouble() - 0.5) * 0.2f,
                            (float)(random.NextDouble() - 0.5) * 0.2f,
                            0);
                    }
                    buffer.UnmapBuffer();
                }
                this.VelocityBuffer = buffer;
            }

            this.PositionBuffer = this.DataSource.GetVertexAttributeBuffer(ParticleModel.strPosition, null);
        }
Ejemplo n.º 20
0
        private static uint[] Generate(int width, int height, double tileSize, double cameraZ, double cameraAngleOfView, uint iteration)
        {
            var random = new Random();
            var result = new uint[width * height];

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            for (uint i = 1; i <= iteration; ++i)
            {
                for (int y = 0; y < height; ++y)
                {
                    for (int x = 0; x < width; ++x)
                    {
                        var intersection = GetIntersection(cameraZ, cameraAngleOfView, width, height, x + random.NextDouble(), y + random.NextDouble());

                        result[width * y + x] += GetColor(tileSize, intersection.Item1, intersection.Item2);
                    }
                }

                Console.WriteLine($"Iteration {i} / {iteration}, Remaining time: {TimeSpan.FromMilliseconds(stopwatch.ElapsedMilliseconds * ((iteration - i) / (double)i))}");
            }

            return result;
        }
Ejemplo n.º 21
0
 List<List<NeighborInfo>> PrepareNeighbors()
 {
     Random random = new Random(0);
     List<List<NeighborInfo>> allSplits = new List<List<NeighborInfo>>();
     for (int i = 0; i < NeighborListSplit; ++i)
     {
         List<NeighborInfo> neighbors = new List<NeighborInfo>();
         for (int j = 0; j < NeighborsChecked; ++j)
         {
             NeighborInfo neighbor = new NeighborInfo();
             do
             {
                 float angle = Angle.FromFraction((float)random.NextDouble() * 0.5f);
                 float distance = Calc.InterpolateExponential(MinHalfDistance, MaxHalfDistance, (float)random.NextDouble());
                 neighbor.Position = Calc.Round(Calc.Multiply(distance, Angle.ToVector(angle)));
             } while (neighbor.Position == new Point() || neighbor.Position.Y < 0);
             neighbor.Orientation = Angle.ToVector(Angle.Add(Angle.ToOrientation(Angle.Atan(neighbor.Position)), Angle.PI));
             if (!neighbors.Any(info => info.Position == neighbor.Position))
                 neighbors.Add(neighbor);
         }
         neighbors.Sort((left, right) => Calc.CompareYX(left.Position, right.Position));
         allSplits.Add(neighbors);
     }
     return allSplits;
 }
Ejemplo n.º 22
0
        private void btnMakePoints_Click(object sender, RoutedEventArgs e)
        {
            drawingCanvas.Children.Clear();
            var sizeX = drawingCanvas.ActualWidth;
            var sizeY = drawingCanvas.ActualHeight;
            vertices = new List<Vertex>();
            var r = new Random();

            /****** Random Vertices ******/
            for (var i = 0; i < NumberOfVertices; i++)
            {
                var vi = new Vertex(sizeX * r.NextDouble(), sizeY * r.NextDouble());
                vertices.Add(vi);
            }
            
            ShowVertices();

            var now = DateTime.Now;
            voronoiMesh = VoronoiMesh.Create<Vertex, Cell>(vertices);
            var interval = DateTime.Now - now;
            txtBlkTimer.Text = string.Format("{0:0.000}s ({1} faces)", interval.TotalSeconds, voronoiMesh.Vertices.Count());

            btnFindDelaunay.IsEnabled = true;
            btnFindVoronoi.IsEnabled = true;
        }
Ejemplo n.º 23
0
 public TargetTrackingImpl(double sigma_f, double dT, string screenSize, string cameraType)
 {
     this.screenSize = screenSize;
     this.sigma_f = sigma_f;
     this.cameraType = cameraType;
     SPOI.Zero();
     Sx2.Zero();
     for (int i = 0; i < 7; i++)
     {
         if (i < 3)
             SPOI[i, i] = 0.5;
         else
             SPOI[i, i] = 0.001;
     }
     for (int i = 0; i < 9; i++)
     {
         if (i < 6)
             Sx2[i, i] = 0.1;
         else
             Sx2[i, i] = 0.01;
     }
     Random r = new Random();
     SSCR[2, 2] = 0.01; // laser covariance
     scr_noise[0, 0] = r.NextDouble() * 10; scr_noise[1, 0] = r.NextDouble() * 10;
     algorithm = new TargetTrackingAlgorithm(dT);
 }
Ejemplo n.º 24
0
 public MarchingCubes( DatasetManager datasetManager )
 {
     Random rand = new Random();
     aa = rand.NextDouble();
     bb = rand.NextDouble();
     cc = rand.NextDouble();
 }
Ejemplo n.º 25
0
        public void AsyncPipelineWaitTest()
        {
            Random rand = new Random(222);
            int started = 0;
            int finished1 = 0;
            int finished2 = 0;
            int numActions = 1000;
            Action action1 = (() => 
                {
                    lock (this) started++;
                    Thread.Sleep((int)(rand.NextDouble() * 100));
                    lock (this) finished1++;
                });
            Action action2 = (() =>
            {
                Thread.Sleep((int)(rand.NextDouble() * 100));
                lock (this) finished2++;
            });

            var pipeline = new AsyncPipeline(10);
            for (int i = 0; i < numActions; i++)
            {
                var async1 = Task.Run(action1);
                pipeline.Add(async1);
                var async2 = async1.ContinueWith(_ => action2());
                pipeline.Add(async2);
            }
            pipeline.Wait();
            Assert.AreEqual(numActions, started);
            Assert.AreEqual(numActions, finished1);
            Assert.AreEqual(numActions, finished2);
        }
Ejemplo n.º 26
0
 public MainViewModel()
 {
     this.Measurements = new Collection<Measurement>();
     var r = new Random(31);
     double p1 = 0;
     double p2 = 5;
     double v1 = 0;
     double v2 = 0;
     for (int i = 0; i < 100; i++)
     {
         v1 += (r.NextDouble() - 0.5) * 0.7;
         v2 += (r.NextDouble() - 0.5) * 0.1;
         double y1 = p1 + v1;
         double y2 = p2 + v2;
         p1 = y1;
         p2 = y2;
         this.Measurements.Add(new Measurement
                              {
                                  Time = i * 2.5,
                                  Value = y1,
                                  Maximum = y1 + y2,
                                  Minimum = y1 - y2
                              });
     }
 }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            Random myR = new Random();
            double[,] A, B;
            Console.Write("Enter no rows in A: ");
            int n = int.Parse(Console.ReadLine());
            Console.Write("Enter no cols in A: ");
            int p = int.Parse(Console.ReadLine());
            Console.Write("Enter no cols in B: ");
            int m = int.Parse(Console.ReadLine());

            int i, j;

            for (i = 0; i <= n; i++)
            {
                for (j = 0; j < p; j++)
                    A[i, j] = myR.NextDouble() * 10;

            }

                for (i = 0; i < p; i++)
                {
                    for (j = 0; j < m; j++)
                        B[i, j] = myR.NextDouble() * 10;
                }

                double[,] C = MultMat(A,B);
        }
        /// <summary>
        /// Setup constructor
        /// </summary>
        private SimpleNoise2d( Random rnd )
        {
            m_Perm = new int[ 64 ];
            for ( int permIndex = 0; permIndex < m_Perm.Length; ++permIndex )
            {
                m_Perm[ permIndex ] = permIndex;
            }
            for ( int permIndex = 0; permIndex < m_Perm.Length; ++permIndex )
            {
                int swapIndex0 = rnd.Next( m_Perm.Length );
                int swapIndex1 = rnd.Next( m_Perm.Length );
                int tmpValue = m_Perm[ swapIndex0 ];
                m_Perm[ swapIndex0 ] = m_Perm[ swapIndex1 ];
                m_Perm[ swapIndex1 ] = tmpValue;
            }
            m_GradX = new float[ 64 ];
            m_GradY = new float[ 64 ];
            for ( int gradIndex = 0; gradIndex < m_GradX.Length; ++gradIndex )
            {
                float m;

                //	Generate a random, non-zero length vector within the unit circle
                do
                {
                    m_GradX[ gradIndex ] = ( ( float )rnd.NextDouble( ) * 2.0f ) - 1.0f;
                    m_GradY[ gradIndex ] = ( ( float )rnd.NextDouble( ) * 2.0f ) - 1.0f;
                    m = m_GradX[ gradIndex ] * m_GradX[ gradIndex ] + m_GradY[ gradIndex ] * m_GradY[ gradIndex ];
                } while ( ( m == 0.0f ) && ( m > 1.0f ) );

                //	Normalize the vector
                m = 1.0f / ( float )Math.Sqrt( m );
                m_GradX[ gradIndex ] *= m;
                m_GradY[ gradIndex ] *= m;
            }
        }
Ejemplo n.º 29
0
        private void MoveLine(object sender, EventArgs e)
        {
            Random rnd = new Random();


            foreach (IFeature feature in _myLines.Features)
            {
                // Coordinates can be updated geographically like
                // feature.Coordinates[0].X += (rnd.NextDouble() - .5);
                // feature.Coordinates[0].Y += (rnd.NextDouble() - .5);

                //for (int i = 0; i < 10; i++)
                //{
                    // Or controled in pixels with the help of the map
                    System.Drawing.Point pixelLocation =App.Map.ProjToPixel(feature.Coordinates[0]);

                    // Control movement in terms of pixels
                    int dx = Convert.ToInt32((rnd.NextDouble() - .5) * 50); // shift left or right 5 pixels
                    int dy = Convert.ToInt32((rnd.NextDouble() - .5) * 50); // shift up or down 5 pixels
                    pixelLocation.X = pixelLocation.X + dx;
                    pixelLocation.Y = pixelLocation.Y + dy;

                    // Convert the pixel motions back to geographic motions.
                    //feature.Coordinates[i] = App.Map.PixelToProj(pixelLocation);
                    feature.Coordinates[0] = App.Map.PixelToProj(pixelLocation);
                //}
            }

            // Refresh the cached representation because we moved points around.
            App.Map.MapFrame.Invalidate();
            App.Map.Invalidate();
        }
        public double[] gradiente(double alpha, double[] x, double[] y, double ep = 0.0001, double max_iter = 10000)
        {
            bool converge = false;
            int i = 0,
                m = x.Count();
            Random rnd = new Random();
            double t0 = rnd.NextDouble()* x[0],
                t1 = rnd.NextDouble() * x[0];

            var J = x.Zip(y, (a, b) => Math.Pow(t0 + t1 * a - b, 2)).Sum();

            while( i<max_iter && !converge)
            {
                double g0 = 1.0 / m * x.Zip(y, (a, b) => (t0 + t1 * a - b)).Sum(),
                    g1 = x.Zip(y, (a, b) => (t0 + t1 * a - b)*a).Sum();

                t0 = t0 - alpha * g0;
                t1 = t1 - alpha * g1;
                double e = x.Zip(y, (a, b) => Math.Pow(t0 + t1 * a - b, 2)).Sum();

                converge = (Math.Abs(J - e) <= ep);
                J = e;
                i++;
            }

            return new double[] { t0, t1 };
        }
Ejemplo n.º 31
0
 public static float Noise()
 {
     return((float)rnd.NextDouble());
 }
Ejemplo n.º 32
0
 public static float Next(float min, float max)
 {
     return((float)(min + (_random.NextDouble() * (max - min))));
 }
Ejemplo n.º 33
0
    public override void Update()
    {
        Debug.Log("hit yet: " + hitYet + ", mode: " + mode + ", state: " + currentState);
        base.Update();
        moving = !GamePause.paused;
        if (!moving)
        {
            return;
        }

        //handle movement and merging
        if (currentState == state.DECIDING)
        {
            goingRight   = !ShouldWeGoLeft(mergepoints[mergeIdx]);           //pick a direction to move in
            currentState = state.MOVING;
        }
        else if (currentState == state.MOVING)
        {
            Arrive();
        }
        else if (currentState == state.BOUNCING)
        {
            if (bounceLeft)
            {
                if (thetas.y < 0)
                {
                    thetas.y     = 0;
                    currentState = state.DECIDING;
                }
            }
            else
            {
                //Debug.Log("thetas: " + thetas.x + "," + thetas.y + "," + thetas.z);
                if (thetas.y > 0)
                {
                    thetas.y     = 0;
                    currentState = state.DECIDING;
                }
            }
        }
        else if (currentState == state.SPAWNING)
        {
            System.Random rand    = new System.Random();
            List <Enemy>  enemies = Dial.GetAllEnemiesInZone(SpawnIndexToZoneID(mergeIdx));
            bool          hasBlob = false;
            bool          hasMega = false;
            foreach (Enemy e in enemies)
            {
                if (e.GetSrcFileName().Equals("blob"))
                {
                    hasBlob = true;
                }
                if (e.GetSrcFileName().Equals("megasplit") || e.GetSrcFileName().Equals("minisplit"))
                {
                    hasMega = true;
                }
            }
            //decide whether to drop an enemy, and which one
            if (hasBlob)
            {
                if (hasMega)
                {
                    BeginMerge();
                    return;                     //short circuit this update so the next frame is in the MERGING state
                }
                else
                {
                    DropMegasplit();
                }
            }
            else
            {
                if (hasMega)
                {
                    DropBlob();
                }
                else
                {
                    if (rand.NextDouble() < 0.5)
                    {
                        DropMegasplit();
                    }
                    else
                    {
                        DropBlob();
                    }
                }
            }
            //end spawn state
            PickTargetZone();
            hitYet       = false;
            currentState = state.DECIDING;
        }
        else if (currentState == state.MERGING)
        {
            //update enemy facsimiles if necessary

            //check if it's time to move on, then move on
            if (mergeTimer.TimeElapsedSecs() >= mergeDelay || mode == 0)
            {
                FinishMerge();
                PickTargetZone();
                hitYet       = false;
                currentState = state.DECIDING;
            }
        }
    }
Ejemplo n.º 34
0
    public void GenerateTrack()
    {
        difficulty = Mathf.Clamp01(difficulty);
        length     = Mathf.Clamp(length, MIN_LENGTH, MAX_LENGTH);

        HashSet <TrackNode> nodes = new HashSet <TrackNode>();

        // Start one block forward
        IntVector3 cursor = new IntVector3();

        cursor.z = 1;

        float heightChangeProb = HEIGHT_CHANGE_PROB * difficulty;
        int   remainingChunks  = length;
        int   currentRotation  = 0;
        bool  done             = false;

        int firstStretchLen = 0;
        int countdown       = INITIAL_GENERATION_TIMEOUT * length;

        while (!done)
        {
            if (countdown-- < 0)
            {
                throw new InvalidTrackException("Initial track generation timed out.");
            }

            int heightDiff = 0;
            TrackChunk.ChunkType direction = TrackChunk.ChunkType.STRAIGHT;

            if (firstStretchLen > FIRST_STRETCH_LEN)
            {
                if (rand.NextDouble() < heightChangeProb)
                {
                    heightDiff = (rand.NextDouble() < 0.5 ? 1 : -1);
                }

                // Decide Direction
                if (heightDiff == 0 && rand.NextDouble() < DIRECTION_TURN_PROB * difficulty)
                {
                    if (rand.NextDouble() < 0.5)
                    {
                        direction = TrackChunk.ChunkType.CURVE_LEFT;
                    }
                    else
                    {
                        direction = TrackChunk.ChunkType.CURVE_RIGHT;
                    }
                }
            }

            firstStretchLen++;

            int nextRotation = currentRotation;

            // Update rotation
            if (direction == TrackChunk.ChunkType.CURVE_RIGHT)
            {
                nextRotation += 90;
            }
            else if (direction == TrackChunk.ChunkType.CURVE_LEFT)
            {
                nextRotation -= 90;
            }

            nextRotation = ClampRotation(nextRotation);

            IntVector3 nextPos = GetNextPoint(cursor, nextRotation, 0);

            if (HasNodeAt(nodes, nextPos))
            {
                continue;
            }

            if (heightDiff == 0)
            {
                IntVector3 nextPosUp   = GetNextPoint(cursor, nextRotation, 1);
                IntVector3 nextPosDown = GetNextPoint(cursor, nextRotation, -1);

                if (HasNodeAt(nodes, nextPosUp) || HasNodeAt(nodes, nextPosDown))
                {
                    continue;
                }
            }
            else
            {
                IntVector3 nextPosHDiff = GetNextPoint(cursor, nextRotation, heightDiff);
                if (HasNodeAt(nodes, nextPosHDiff))
                {
                    continue;
                }
            }

            nextPos.y += heightDiff;

            TrackNode node = new TrackNode(cursor, currentRotation);
            node.chunkType  = direction;
            node.heightDiff = heightDiff;
            nodes.Add(node);
            trackOrderedChunks.Add(node);

            currentRotation = nextRotation;
            cursor          = nextPos;

            if (firstStretchLen > FIRST_STRETCH_LEN)
            {
                remainingChunks--;
            }

            if (remainingChunks == 0)
            {
                done = true;
            }
        }

        // Now, close the circuit

        bool ok = CloseCircuit(nodes, cursor, currentRotation);

        // Instance prefabs
        List <TrackChunk> instancedChunks = InstanceChunkClones(trackOrderedChunks);

        if (!ok)
        {
            throw new InvalidTrackException("A* pathfinding timed out.");
        }
        else
        {
            RacingTrack rt = trackBase.AddComponent <RacingTrack>();
            rt.trackChunks = instancedChunks;
            rt.startChunk  = instancedChunks[0];
            rt.endChunk    = instancedChunks[instancedChunks.Count - 1];
        }
    }
Ejemplo n.º 35
0
    public IEnumerator LoadConfig()
    {
        string[] config_urls = this.config_urls;

        string config_urls_json_str = PlayerPrefs.GetString("config_urls", "");

        if (!string.IsNullOrEmpty(config_urls_json_str))        //从config 文件中保存了config_urls 到 PlayerPrefs 中//如果
        {
            JSONObject    json       = new JSONObject(config_urls_json_str);
            List <string> configList = new List <string>();
            //config_urls = new string[json.list.Count + this.config_urls.Length];

            foreach (var item in json.list)
            {
                //UnityEngine.Debug.Log("CK : ------------------------------ name = " + item.str );

                if (!configList.Contains(item.ToString()))
                {
                    configList.Add(item.str);
                }
            }

            foreach (var item in this.config_urls)
            {
                if (!configList.Contains(item.ToString()))
                {
                    configList.Add(item);
                }
            }

            config_urls = configList.ToArray();
        }

        JSONObject configObj = null;

        if (config_urls != null && config_urls.Length > 0)
        {
            _ResultInfo += "------------所有的Configs------------------\r\n";
            foreach (var item in config_urls)
            {
                _ResultInfo += item + "\r\n";
            }

            System.Random ro      = new System.Random();
            string        tempStr = string.Empty;
            foreach (var item in config_urls)
            {
                tempStr = item + "?" + ro.NextDouble();

                WWW www = new WWW(tempStr);
                yield return(www);

                if (www.error == null)
                {
                    HttpResult result = BaseResult(www);
                    if (result.resultType == HttpResult.ResultType.Sucess)
                    {
                        _ResultInfo += "\r\n当前用的Config:\r\n" + tempStr;
                        _ResultInfo += "\r\nConfig text = " + www.text;
                        configObj    = (JSONObject)result.resultObject;
                        break;
                    }
                    else
                    {
                        _ResultInfo += "\r\nurl: " + tempStr + " 出错了, error = " + result.resultObject;
                    }
                }
                else
                {
                    _ResultInfo += "\r\nurl: " + tempStr + " 出错了, error = " + www.error;
                }
            }
        }

        if (configObj == null)
        {
            _ResultInfo += "\r\n无有效url";
        }

        yield return(StartCoroutine(UpdateConfig(configObj)));       //更新配置文件信息
    }
Ejemplo n.º 36
0
 // Update is called once per frame
 void Update()
 {
     if (!gameOver)
     {
         //This is for bullet reload, player can shoot a bullet every .1 sec
         if (bulletReload <= 0)
         {
             bulletReload = 0.1f;
             canShoot     = true;
         }
         //This is to create an enemy after .5 seconds have passed
         if (enemyCreation <= 0)
         {
             //If 10 enemies have not been created yet make a normal enemy
             if (level != 10)
             {
                 //Create enemy object
                 GameObject EnemyClone = GameObject.Instantiate(Enemy);
                 EnemyClone.name = "Enemy";
                 //Sets the enemy position 3 scales away from player
                 float x = 0;
                 float y = 0;
                 do
                 {
                     x = (float)(random.Next(-25, 40));
                     y = (float)(random.Next(-15, 6));
                 } while (Mathf.Abs(x - this.transform.position.x) > 3 && Mathf.Abs(y - this.transform.position.y) > 3);
                 EnemyClone.transform.Translate(x, y, 0f);
                 //Make rigidbody and set gravity scale to 0
                 EnemyClone.GetComponent <SpriteRenderer>().color = new Color((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble());
                 Enemy.AddComponent <Rigidbody2D>();
                 Enemy.GetComponent <Rigidbody2D>().gravityScale = 0;
                 enemyCreation = .5f;
                 level++;
             }
             //if 10 enemies have been createde make aqn A star enemy
             else
             {
                 //Instantiate the A star enemy
                 GameObject EnemyClone = GameObject.Instantiate(AStarEnemy);
                 EnemyClone.name = "AStarEnemy";
                 //Sets the enemy position 3 scales away from player
                 float x = 0;
                 float y = 0;
                 do
                 {
                     x = (float)(random.Next(-25, 40));
                     y = (float)(random.Next(-15, 6));
                 } while (Mathf.Abs(x - this.transform.position.x) > 3 && Mathf.Abs(y - this.transform.position.y) > 3);
                 enemyCreation = .5f;
                 EnemyClone.transform.Translate(x, y, 0f);
                 level = 0;
             }
         }
         //This is to move the player and save the direction they moved
         if (Input.GetKey(KeyCode.UpArrow))
         {
             //
             transform.Translate(0f, .3f, 0f);
             updateQueue(Direction.up);
         }
         else if (Input.GetKey(KeyCode.DownArrow))
         {
             //
             transform.Translate(0f, -.3f, 0f);
             updateQueue(Direction.down);
         }
         else if (Input.GetKey(KeyCode.RightArrow))
         {
             // createBullet(100, 0, 0, 90);
             transform.Translate(.3f, 0f, 0f);
             updateQueue(Direction.right);
         }
         else if (Input.GetKey(KeyCode.LeftArrow))
         {
             //createBullet(-100, 0, 0, 270);
             transform.Translate(-.3f, 0f, 0f);
             updateQueue(Direction.left);
         }
         //This is to shoot the bullet in a certain direction (Diagnol Shooting is possible)
         if (Input.GetKey(KeyCode.W) && canShoot)
         {
             if (Input.GetKey(KeyCode.A))
             {
                 createBullet(-1200, 1200, 0, 0);
             }
             else if (Input.GetKey(KeyCode.D))
             {
                 createBullet(1200, 1200, 0, 0);
             }
             else
             {
                 createBullet(0, 1200, 0, 0);
             }
         }
         else if (Input.GetKey(KeyCode.S) && canShoot)
         {
             if (Input.GetKey(KeyCode.A))
             {
                 createBullet(-1200, -1200, 0, 0);
             }
             else if (Input.GetKey(KeyCode.D))
             {
                 createBullet(1200, -1200, 0, 0);
             }
             else
             {
                 createBullet(0, -1200, 0, 180);
             }
         }
         else if (Input.GetKey(KeyCode.D) && canShoot)
         {
             createBullet(1200, 0, 0, 90);
         }
         else if (Input.GetKey(KeyCode.A) && canShoot)
         {
             createBullet(-1200, 0, 0, 270);
         }
         //countdown timer for enemy creation
         enemyCreation -= Time.deltaTime;
         //countdown timer for bullet reload
         bulletReload -= Time.deltaTime;
         //ensure no rotation of the player
         this.gameObject.transform.rotation = Quaternion.Euler(0f, 0f, 0f);
     }
 }
Ejemplo n.º 37
0
    public void GenerateMap()
    {
        currentMap = maps[mapIndex];
        tileMap    = new Transform[currentMap.mapSize.x, currentMap.mapSize.y];
        System.Random prng = new System.Random(currentMap.seed);

        //Generating coords
        allTileCoords = new List <Coord> ();
        for (int x = 0; x < currentMap.mapSize.x; x++)
        {
            for (int y = 0; y < currentMap.mapSize.y; y++)
            {
                allTileCoords.Add(new Coord(x, y));
            }
        }
        shuffledTileCoords = new Queue <Coord> (Utility.ShuffleArray(allTileCoords.ToArray(), currentMap.seed));

        //Put under Generated map holder
        string holderName = "Generated Map";

        if (transform.Find(holderName))
        {
            DestroyImmediate(transform.Find(holderName).gameObject);
        }
        Transform mapHolder = new GameObject(holderName).transform;

        mapHolder.parent = transform;

        //Instantiate Tiles
        for (int x = 0; x < currentMap.mapSize.x; x++)
        {
            for (int y = 0; y < currentMap.mapSize.y; y++)
            {
                Vector3   tilePosition = CoordToPosition(x, y);
                Transform newTile      = Instantiate(tilePrefab, tilePosition, Quaternion.Euler(Vector3.right * 90)) as Transform;
                newTile.localScale = Vector3.one * (1 - outlinePercent) * tileSize;
                newTile.parent     = mapHolder;
                tileMap[x, y]      = newTile;
            }
        }

        bool[,] obstacleMap = new bool[(int)currentMap.mapSize.x, (int)currentMap.mapSize.y];

        //Instantiate Obstacles
        int          obstacleCount        = (int)(currentMap.mapSize.x * currentMap.mapSize.y * currentMap.obstaclePercent);
        int          currentObstacleCount = 0;
        List <Coord> allOpenCoords        = new List <Coord> (allTileCoords); //Copies allTileCoords

        for (int i = 0; i < obstacleCount; i++)
        {
            Coord randomCoord = GetRandomCoord();
            obstacleMap[randomCoord.x, randomCoord.y] = true;
            currentObstacleCount++;

            if (randomCoord != currentMap.mapCenter && MapIsFullyAccessible(obstacleMap, currentObstacleCount))
            {
                float obstacleHeight = Mathf.Lerp(currentMap.minObstacleHeight, currentMap.maxObstacleHeight, (float)prng.NextDouble());

                Vector3   obstaclePosition = CoordToPosition(randomCoord.x, randomCoord.y);
                Transform newObstacle      = Instantiate(obstaclePrefab, obstaclePosition + Vector3.up * (obstacleHeight / 2), Quaternion.identity) as Transform;
                newObstacle.parent     = mapHolder;
                newObstacle.localScale = new Vector3((1 - outlinePercent) * tileSize, obstacleHeight, (1 - outlinePercent) * tileSize);

                Renderer obstacleRenderer = newObstacle.GetComponent <Renderer> ();
                Material obstaceMaterial  = new Material(obstacleRenderer.sharedMaterial);
                float    colorPercent     = randomCoord.y / (float)currentMap.mapSize.y;
                obstaceMaterial.color           = Color.Lerp(currentMap.foregroundColour, currentMap.backgroundColour, colorPercent);
                obstacleRenderer.sharedMaterial = obstaceMaterial;

                //Remove the coordinate from the allOpenCoord if there is an obstacle on it.
                allOpenCoords.Remove(randomCoord);
            }
            else
            {
                obstacleMap[randomCoord.x, randomCoord.y] = false;
                currentObstacleCount--;
            }
        }

        //Shuffle open tile coords
        shuffledOpenTileCoords = new Queue <Coord> (Utility.ShuffleArray(allOpenCoords.ToArray(), currentMap.seed));


        //Place navmash blocker around the mep, so tha agents wont go around the map
        //Left
        Transform maskLeft = Instantiate(navmeshMaskPrefab, Vector3.left * ((currentMap.mapSize.x + maxMapSize.x) / 4f) * tileSize, Quaternion.identity) as Transform;

        maskLeft.parent     = mapHolder;
        maskLeft.localScale = new Vector3((maxMapSize.x - currentMap.mapSize.x) / 2f, 1, currentMap.mapSize.y) * tileSize;
        //Right
        Transform maskRight = Instantiate(navmeshMaskPrefab, Vector3.right * ((currentMap.mapSize.x + maxMapSize.x) / 4f) * tileSize, Quaternion.identity) as Transform;

        maskRight.parent     = mapHolder;
        maskRight.localScale = new Vector3((maxMapSize.x - currentMap.mapSize.x) / 2f, 1, currentMap.mapSize.y) * tileSize;
        //Top
        Transform maskTop = Instantiate(navmeshMaskPrefab, Vector3.forward * ((currentMap.mapSize.y + maxMapSize.y) / 4f) * tileSize, Quaternion.identity) as Transform;

        maskTop.parent     = mapHolder;
        maskTop.localScale = new Vector3(maxMapSize.x, 1, (maxMapSize.y - currentMap.mapSize.y) / 2f) * tileSize;
        //Bottom
        Transform maskBot = Instantiate(navmeshMaskPrefab, Vector3.back * ((currentMap.mapSize.y + maxMapSize.y) / 4f) * tileSize, Quaternion.identity) as Transform;

        maskBot.parent     = mapHolder;
        maskBot.localScale = new Vector3(maxMapSize.x, 1, (maxMapSize.y - currentMap.mapSize.y) / 2f) * tileSize;

        navmeshFloor.localScale = new Vector3(maxMapSize.x, maxMapSize.y) * tileSize;
        mapFloor.localScale     = new Vector3(currentMap.mapSize.x * tileSize, currentMap.mapSize.y * tileSize);
    }
Ejemplo n.º 38
0
    //rand//Method used to generate the base events
    protected override void generateEvents()
    {
        System.Random     rand = new System.Random();
        bool              good = false;
        List <EventStats> eS;

        do
        {
            eS = new List <EventStats>();

            int[] nums = new int[12] {
                3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
            };

            for (int i = 1; i < 13; i++)
            {
                List <int> stim = new List <int>()
                {
                    getMatchingNum(i)
                };

                int min = 0;
                int max = 6;
                if (stim[0] > 6)
                {
                    min = 6;
                    max = 12;
                }

                int total = 0;

                for (int j = min; j < max; j++)
                {
                    if (!stim.Contains(j + 1) && i != j + 1)
                    {
                        total += nums[j];
                    }
                }

                double threshold = rand.NextDouble();

                float sum = 0;

                for (int j = min; j < max; j++)
                {
                    if (!stim.Contains(j + 1) && i != j + 1)
                    {
                        sum += ((float)nums[j]) / ((float)total);

                        if (sum > threshold)
                        {
                            stim.Add(j + 1);
                            nums[j]--;
                            break;
                        }
                    }
                }

                if (stim[0] > 6)
                {
                    min = 0;
                    max = 6;
                }
                else
                {
                    min = 6;
                    max = 12;
                }

                int count = 0;

                do
                {
                    total = 0;

                    for (int j = min; j < max; j++)
                    {
                        if (!stim.Contains(j + 1) && i != j + 1)
                        {
                            total += nums[j];
                        }
                    }

                    threshold = rand.NextDouble();
                    sum       = 0;

                    for (int j = min; j < max; j++)
                    {
                        if (!stim.Contains(j + 1) && i != j + 1)
                        {
                            sum += ((float)nums[j]) / ((float)total);

                            if (sum > threshold)
                            {
                                stim.Add(j + 1);
                                nums[j] = nums[j] - 1;
                                break;
                            }
                        }
                    }
                    count++;
                }while(count < 2);

                eS.Add(new AssociateEvent(i, stim));
            }

            good = true;

            foreach (int m in nums)
            {
                if (m != 0)
                {
                    Debug.Log("RETRY");
                    good = false;
                    break;
                }
            }
        }while(!good);

        events = eS;
    }
    public static ChromosomeComposition Mutate(ChromosomeComposition currentCreatureComposition, double mutationRate, float mutationFactor)
    {
        // Mutate colour
        var newColour     = new float[3];                           // new 3 bit colour, r, g, and b
        var currentColour = currentCreatureComposition.GetColour(); // get the current colour of the creature

        // map current colours rgb values to the new colour
        newColour[0] = currentColour.r;
        newColour[1] = currentColour.g;
        newColour[2] = currentColour.b;

        for (var i = 0; i < 3; i++)
        {
            _rand = Rnd.NextDouble();
            if (_rand < mutationRate)
            {
                newColour[i] += RandomiseThisGene(mutationFactor);
            }
        }

        // Assign new colour to this creature
        currentCreatureComposition.SetColour(newColour[0], newColour[1], newColour[2]);

        // Mutate root scale
        var currentRootScale = currentCreatureComposition.GetRootScale();

        // Check that the current scale (of x, y and z) is currently greater than 1
        if (currentRootScale.x > 1F && currentRootScale.y > 1F && currentRootScale.z > 1F)
        {// Create new 3 bit root scale (x,y, and z)
            var newRootScale = new float[3];
            newRootScale[0] = currentRootScale.x;
            newRootScale[1] = currentRootScale.y;
            newRootScale[2] = currentRootScale.z;

            for (var i = 0; i < 3; i++)
            {
                _rand = Rnd.NextDouble();
                if (_rand < mutationRate)
                {
                    // Randomise scale
                    newRootScale[i] += RandomiseThisGene(mutationFactor);
                }
            }

            // Assign new root scale to creature
            var rootScale = new Vector3(newRootScale[0], newRootScale[1], newRootScale[2]);
            currentCreatureComposition.SetRootScale(rootScale);
        }

        // Mutate limbs colour
        currentColour = currentCreatureComposition.GetLimbColour();
        newColour[0]  = currentColour.r;
        newColour[1]  = currentColour.g;
        newColour[2]  = currentColour.b;
        for (var i = 0; i < 3; i++)
        {
            _rand = Rnd.NextDouble();
            if (_rand < mutationRate)
            {
                newColour[i] += RandomiseThisGene(mutationFactor);
            }
        }

        // Assign new colour to creature
        currentCreatureComposition.SetLimbColour(newColour[0], newColour[1], newColour[2]);

        var currentBranches = currentCreatureComposition.Branches;

        foreach (var branch in currentBranches)
        {// get a list of limbs
            var currentLimbs = (ArrayList)branch;
            foreach (var limb in currentLimbs)
            {
                var limbs = (ArrayList)limb;
                var v     = (Vector3)limbs[1];
                for (var k = 0; k < 3; k++)
                {
                    _rand = Rnd.NextDouble();
                    if (_rand < mutationRate)
                    {
                        v[k] += RandomiseThisGene(mutationFactor);
                    }
                }
            }
        }

        // mutate base frequency and amplitude
        _rand = Rnd.NextDouble();
        if (_rand < mutationRate)
        {
            currentCreatureComposition.JointAmplitude += RandomiseThisGene(mutationFactor);
        }

        _rand = Rnd.NextDouble();
        if (_rand < mutationRate)
        {
            currentCreatureComposition.JointFrequency += RandomiseThisGene(mutationFactor);
        }

        _rand = Rnd.NextDouble();
        if (_rand < mutationRate)
        {
            currentCreatureComposition.JointPhase += RandomiseThisGene(mutationFactor);
        }

        _rand = Rnd.NextDouble();
        if (_rand < mutationRate)
        {
            currentCreatureComposition.HungerPoint += RandomiseThisGene(mutationFactor);
        }

        currentCreatureComposition.SetBranches(currentBranches);
        return(currentCreatureComposition);
    }
Ejemplo n.º 40
0
    internal override void Update()
    {
        base.Update();

        if (Session.Status != SessionStatus.Tracking)
        {
            return;
        }

        if ((mListCloudAnchorPanelGO.activeInHierarchy == false) && (mAddCloudAnchorPanelGO.activeInHierarchy == false))
        {
            Touch lastTouched;
            if (LastTouch(out lastTouched))
            {
                if (lastTouched.phase == TouchPhase.Ended)
                {
                    TrackableHit hit;
                    if (Frame.Raycast(lastTouched.position.x, lastTouched.position.y, TrackableHitFlags.PlaneWithinPolygon | TrackableHitFlags.FeaturePointWithSurfaceNormal, out hit))
                    {
                        // Anchorを生成
                        Anchor anchor = Session.CreateAnchor(hit.Pose, hit.Trackable);

                        GameObject anchorGO = Instantiate(mAnchorPrefab, anchor.transform.position, anchor.transform.rotation);
                        anchorGO.SetActive(true);
                        anchorGO.transform.parent = anchor.transform;

                        // CloudAnchorを生成
                        XPSession.CreateCloudAnchor(anchor).ThenAction(delegate(CloudAnchorResult result)
                        {
                            XPAnchor xpAnchor = result.Anchor;

                            if (xpAnchor != null)
                            {
                                AddAnchorGO(xpAnchor, anchorGO, anchor);
                            }
                        });
                    }
                }
            }
        }

        // アニメーション
        bool enableAnimation = false;

        if (mLeftAnimationInterval > 0)
        {
            mLeftAnimationInterval    -= Time.deltaTime;
            mLeftOneAnimationInterval -= Time.deltaTime;

            if (mLeftOneAnimationInterval <= 0)
            {
                enableAnimation           = true;
                mLeftOneAnimationInterval = MinimumAnimationInterval;
            }
        }

        // 表示位置の更新
        if (mCloudAnchorDic.Count > 0)
        {
            foreach (string cloudAnchorId in mAnchorDic.Keys)
            {
                Anchor     anchor        = mAnchorDic[cloudAnchorId];
                GameObject cloudAnchorGO = null;

                if (enableAnimation)
                {
                    int    direction      = (mRandom.Next() * mRandom.Next()) % 3;
                    double distanceSource = mRandom.NextDouble() * mRandom.NextDouble();
                    float  distance       = ((float)(distanceSource - System.Math.Floor(distanceSource)) / 1);
                    if (direction == 0)
                    {
                        anchor.transform.position = new Vector3(anchor.transform.position.x + distance, anchor.transform.position.y, anchor.transform.position.z);
                    }
                    else if (direction == 1)
                    {
                        anchor.transform.position = new Vector3(anchor.transform.position.x, anchor.transform.position.y + distance, anchor.transform.position.z);
                    }
                    else
                    {
                        anchor.transform.position = new Vector3(anchor.transform.position.x, anchor.transform.position.y, anchor.transform.position.z + distance);
                    }
                }

                if ((enableAnimation || mUpdateAnchorsPosition) && mCloudAnchorGODic.TryGetValue(cloudAnchorId, out cloudAnchorGO))
                {
                    cloudAnchorGO.transform.SetPositionAndRotation(anchor.transform.position, anchor.transform.rotation);

                    mUpdateAnchorsPosition = false;
                }
            }
        }
    }
Ejemplo n.º 41
0
 float NextFloat(float range)
 {
     System.Random random = new System.Random();
     return((float)(random.NextDouble() * range));
 }
Ejemplo n.º 42
0
 private float MagSyncedRandomFloat(float min, float max)
 {
     return((float)(magSyncedRNG.NextDouble() * (max - min) + min));
 }
Ejemplo n.º 43
0
 public static float rand(float start, float stop)
 {
     return((float)(random.NextDouble() * (stop - start) + start));
 }
Ejemplo n.º 44
0
    IEnumerator DoDownload(Dictionary <string, long> m_RelativeUrlSizeMap_temp = null)
    {
        string error = string.Empty;

        System.Random ro    = new System.Random();
        byte[]        bytes = null;
        if (m_RelativeUrlSizeMap_temp == null)
        {
            m_RelativeUrlSizeMap_temp = m_RelativeUrlSizeMap;
        }
        //Dictionary<string, long> m_RelativeUrlSizeMap_pending = new Dictionary<string, long>();// 这个用来把正在下载的文件(以保持在本地的位置为准, 避免本地文件被多个地方修改) 先挂起来, 下下载其他文件, 都下载好了 再重新回来检查下载情况//目前还没在用

        foreach (var item in m_RelativeUrlSizeMap_temp)
        {
            m_CurrentRelativeUrl = item.Key;

            string resUrl = m_BaseSrcUrl_raw + m_RelativeUrlVersionCodeMap[m_CurrentRelativeUrl] + Constants.DirName + m_CurrentRelativeUrl;//热更新升级后 会有 热更新版本号
            //UnityEngine.Debug.Log("ck debug : -------------------------------- resUrl = " + resUrl);

            string savePath = m_BaseDesUrl + m_CurrentRelativeUrl;
            string saveDir  = Path.GetDirectoryName(savePath);
            if (!Directory.Exists(saveDir))
            {
                Directory.CreateDirectory(saveDir);                            //创建文件夹
            }
            //热更新升级, 添加在下载文件前检查文件是否已经下载完成
            if (File.Exists(savePath))
            {
                bytes = File.ReadAllBytes(savePath);
                if (bytes.Length > 0)
                {
                    CheckMD5(bytes);

                    while (fileMD5 == null)
                    {
                        yield return(0);
                    }

                    if (fileMD5 == m_FileMD5Map[item.Key])
                    {
                        OnFileUpdated(); //把已经完成的下载配置 记录到 配置文件中

                        continue;        //文件已经下载完成了
                    }
                }
            }


            using (WWW www = new WWW(resUrl + "?" + ro.NextDouble()))
            {//这段代码可以抽取下
                while (!www.isDone)
                {
                    //while(Application.internetReachability != NetworkReachability.ReachableViaLocalAreaNetwork)
                    //{//只在wifi环境下下载资源
                    //    yield return new WaitForSeconds(10);
                    //}

                    error = CheckTimeOut(www);

                    if (www.error != null)
                    {
                        error = " @ " + www.error;
                    }
                    else
                    {
                        if (_OnDownloadProgressChanged != null)
                        {
                            _OnDownloadProgressChanged(m_CurrentRelativeUrl, System.Convert.ToInt64(m_DownloadedFilesBytes + www.progress * item.Value), m_TotalDownloadBytes);
                        }
                    }

                    if (string.IsNullOrEmpty(error))
                    {
                        yield return(0);
                    }
                    else
                    {
                        OnComplete(error);
                        //www.Dispose();
                        //www = null;
                        yield break;
                    }
                }

                //启用线程,避免MD5计算时间过程导致卡顿//同时使用while循环阻塞该协程,直到md5计算完后才继续后面的计算

                bytes = StaticUtils.Crypt(www.bytes);
                CheckMD5(bytes);

                while (fileMD5 == null)
                {
                    yield return(0);
                }

                if (fileMD5 != m_FileMD5Map[item.Key])
                {
                    if (Constants.isEditor)
                    {
                        UnityEngine.Debug.LogError("ck debug : -------------------------------- <color=red>下载出错 = " + m_CurrentRelativeUrl + " @ 文件md5出错了</color>" + ", error = " + error + ", www.bytes.length = " + (www.bytes != null ? www.bytes.Length : 0) + ", resUrl = " + resUrl);
                    }

                    OnComplete(" @ 文件md5出错了");
                    yield break;
                }

                //UnityEngine.Debug.Log("CK : ------------------------------ www config updater fileMD5 = " + fileMD5 + ", savePath = " + savePath);

                m_DownloadedFilesCount++;
                m_DownloadedFilesBytes += item.Value;
                if (File.Exists(savePath))
                {
                    File.Delete(savePath);
                }
                File.WriteAllBytes(savePath, bytes);
                SetNoBackupFlag(savePath);

                //UnityEngine.Debug.Log("CK : ------------------------------ www config updater = " + www.assetBundle + ", savePath = " + savePath);

                OnFileUpdated();
                //UnityEngine.Debug.Log("CK : ------------------------------ www config updater = " + 1);
                if (www.assetBundle)
                {
                    www.assetBundle.Unload(false);                 //释放assetbundle资源
                }
                //www.Dispose();
                //www = null;
            }
        }

        //UnityEngine.Debug.Log("CK : ------------------------------ download complete = "  );

        OnComplete(null);
    }
Ejemplo n.º 45
0
 public static float NextFloat(this System.Random random)
 {
     return((float)random.NextDouble());
 }
Ejemplo n.º 46
0
    float GenerateWave(double phase, float lfoFreq, float lfoAmpSlider)
    {
        float data             = 0;
        int   activeOscCounter = 0;

        // Calculated sin (with LFO modulation if lfoFreq and lfoAmpSlider are not zeros)
        float calculatedSin = Mathf.Sin((float)phase + lfoAmpSlider * (float)frequency * Mathf.Sin(lfoFreq * time));

        if (sinGain > 0.0f)
        {
            data += sinGain * calculatedSin;
            activeOscCounter++;
        }
        if (squareGain > 0.0f)
        {
            if (calculatedSin > 0)
            {
                data += squareGain;
            }
            else
            {
                data += -squareGain;
            }
            activeOscCounter++;
        }
        if (triangleGain > 0.0f)
        {
            data += triangleGain * Mathf.Asin(calculatedSin) * 2.0f / Mathf.PI;
            activeOscCounter++;
        }
        if (sawtoothGain > 0.0f)
        {
            //data += gain * (2.0f / Mathf.PI) * ((float)phase * Mathf.PI * ((float)deltaTime * 7.5f % (1.0f / (float)phase)) - (Mathf.PI / 2.0f));
            //data += gain * ((float)phase - Mathf.Floor((float)phase));
            //data += gain * ((float)phase % 1.0f);
            float d = 0;
            for (int n = 1; n < 20; n++)
            {
                d += (Mathf.Sin(n * (float)phase + lfoAmpSlider * (float)frequency * Mathf.Sin(lfoFreq * time))) / n;
            }
            data += d * sawtoothGain * (2.0f / Mathf.PI);
            activeOscCounter++;
        }
        if (whiteNoiseGain > 0.0f)
        {
            if (lfoAmpSlider == 0)
            {
                data += whiteNoiseGain * (float)(rand.NextDouble() * 2.0 - 1.0);
            }
            else
            {
                data += whiteNoiseGain * Mathf.Sin((float)(rand.NextDouble() * 2.0 - 1.0) + lfoAmpSlider * (float)frequency * Mathf.Sin(lfoFreq * time));
            }

            activeOscCounter++;
        }
        if (redNoiseGain > 0.0f)
        {
            float d = 0;
            if (redNoiseSampleCounter < skippedSamples)
            {
                // Interpolation
                d = redNoiseFirstSample * (1.0f - ((redNoiseSampleCounter - 1.0f) / (skippedSamples - 1.0f))) + redNoiseLastSample * ((redNoiseSampleCounter - 1.0f) / (skippedSamples - 1.0f));
                redNoiseSampleCounter++;
            }
            else
            {
                redNoiseFirstSample = redNoiseLastSample;
                if (lfoAmpSlider == 0)
                {
                    redNoiseLastSample = (float)(rand.NextDouble() * 2.0 - 1.0);
                }
                else
                {
                    redNoiseLastSample = Mathf.Sin((float)(rand.NextDouble() * 2.0 - 1.0) + lfoAmpSlider * (float)frequency * Mathf.Sin(lfoFreq * time));
                }

                redNoiseSampleCounter = 2;

                d = redNoiseFirstSample;
            }

            data += redNoiseGain * d;
            activeOscCounter++;
        }

        return((float)envelope.GetAmplitude(time / samplingFrequency) * data / activeOscCounter);
    }
Ejemplo n.º 47
0
 public bool RandomBool(float trueProbability)
 {
     return(_random.NextDouble() < trueProbability);
 }
Ejemplo n.º 48
0
 public static float RandFloat()
 {
     return((float)ms_Random.NextDouble());
 }
Ejemplo n.º 49
0
    public void GenerateMap()
    {
        System.Random random = new System.Random(seed);

        ground.localScale         = new Vector3(maxMapSize.x, maxMapSize.y, 1f);
        groundCollider.localScale = new Vector3(maxMapSize.x, 0.1f, maxMapSize.y);

        map = new bool[mapSize.x, mapSize.y];
        tileBack.localScale = new Vector3(mapSize.x, mapSize.y, 1f);
        tileBack.GetComponent <Renderer>().sharedMaterial.color = tileBackColor;

        mapCoords = new List <Coord>();
        for (int i = 0; i < mapSize.x; i++)
        {
            for (int j = 0; j < mapSize.y; j++)
            {
                mapCoords.Add(new Coord(i, j));
            }
        }
        List <Coord> walkableCoordList = new List <Coord>(mapCoords);

        shuffledMapCoordQueue = ShuffleListToQueue(mapCoords);

        // clean original tiles
        string tileHolderName = "Map Holder";

        if (transform.FindChild(tileHolderName))
        {
            DestroyImmediate(transform.FindChild(tileHolderName).gameObject);
        }

        Transform tileHolder = new GameObject(tileHolderName).transform;

        tileHolder.parent = transform;

        // generate tiles
        for (int i = 0; i < mapSize.x; i++)
        {
            for (int j = 0; j < mapSize.y; j++)
            {
                Transform tile = Instantiate(tilePrefab, new Vector3(i - mapSize.x / 2f + 0.5f, 0f, j - mapSize.y / 2f + 0.5f), Quaternion.Euler(90f, 0f, 0f)) as Transform;
                tile.localScale = Vector3.one * (1 - tileMargin);
                tile.parent     = tileHolder;
            }
        }

        // generate obstacles
        int totalObstacles  = (int)(mapSize.x * mapSize.y * obstacleCoverage);
        int placedObstacles = 0;

        for (int i = 0; i < totalObstacles; i++)
        {
            Coord obstacleCoord = GetNextFromQueue(shuffledMapCoordQueue);
            if (obstacleCoord == mapCenter)
            {
                continue;
            }

            map[obstacleCoord.x, obstacleCoord.y] = true;
            placedObstacles++;
            if (IsPathFullyAccessible(map, placedObstacles))
            {
                float     obstacleHeight = Mathf.Lerp(obstacleMinHeight, obstacleMaxHeight, (float)random.NextDouble());
                Transform obstacle       = Instantiate(obstaclePrefab, CoordToPosition(obstacleCoord) + new Vector3(0, obstacleHeight / 2f, 0), Quaternion.identity) as Transform;
                obstacle.parent = tileHolder;
                Renderer renderer = obstacle.GetComponent <Renderer>();
                Material material = new Material(renderer.sharedMaterial);
                material.color          = Color.Lerp(frontObstacleColor, backObstacleColor, obstacleCoord.y / (float)mapSize.y);
                renderer.sharedMaterial = material;
                obstacle.localScale     = new Vector3(1f, obstacleHeight, 1f);
                walkableCoordList.Remove(obstacleCoord);
            }
            else
            {
                map[obstacleCoord.x, obstacleCoord.y] = false;
                placedObstacles--;
            }
        }

        shuffledWalkableCoordQueue = ShuffleListToQueue(walkableCoordList);
    }
Ejemplo n.º 50
0
    void Update()
    {
        // エンター押下時:バッファ文字を出現
        if (Input.GetKeyDown(KeyCode.Return))
        {
            System.Random random  = new System.Random();
            TextMeshPro   aText   = new TextMeshPro();
            Vector3       lkeyPos = new Vector3(0, 0, 0);

            aText = createTextInstance(aText, textMeshPro, lkeyPos, this.transform.localRotation, bufferStr);
            aText.GetComponent <KeyTextController>().isEnter = true;
            aText.fontSize *= 1.5f;
            bufferStr       = "";

            // 押下音再生
            audioSource.PlayOneShot(SoundEnter);
        }
        // スペース押下時:スペース独自エフェクト
        else if (Input.GetKeyDown(KeyCode.Space))
        {
            Vector3    pos  = new Vector3(0, 0, 0) * convertMilitoUnitWeight;
            GameObject gObj = new GameObject();
            Vector3    gObjSize;

            // 値設定
            Vector3 lkeyPos = new Vector3(-1 * KeyboardLayout.body.sizeX / 2, 0, KeyboardLayout.body.sizeZ / 2) * convertMilitoUnitWeight;
            lkeyPos   += (Vector3)KeyboardLayout.layout["space"][0] * convertMilitoUnitWeight;
            gObjSize   = (Vector3)KeyboardLayout.layout["space"][1] * convertMilitoUnitWeight;
            bufferStr += " ";

            // 作成
            gObj = createObjectInstance(gObj, spaceEffect, lkeyPos, this.transform.localRotation, gObjSize);

            // 押下音再生
            audioSource.PlayOneShot(soundKeydown_01);
        }
        // デリート押下時:バッファ削除
        else if ((Input.GetKeyDown(KeyCode.Backspace)) || (Input.GetKeyDown(KeyCode.Delete)))
        {
            if (bufferStr.Length > 0)
            {
                Vector3    pos  = new Vector3(0, 0, 0) * convertMilitoUnitWeight;
                GameObject gObj = new GameObject();

                Vector3 lkeyPos = new Vector3(1 * KeyboardLayout.body.sizeX / 2, 0.02f, 0) * convertMilitoUnitWeight;
                gObj      = createObjectInstance(gObj, deleteEffect, lkeyPos, this.transform.localRotation, Vector3.zero);
                bufferStr = "";
                // 押下音再生
                audioSource.PlayOneShot(soundDelete);
            }
        }
        // エスケープキー押下時:全部出現
        else if (Input.GetKeyDown(KeyCode.Escape))
        {
            foreach (KeyValuePair <string, ArrayList> kvp in KeyboardLayout.layout)
            {
                System.Random random = new System.Random();
                TextMeshPro   aText  = new TextMeshPro();

                Vector3 lkeyPos = new Vector3(-1 * KeyboardLayout.body.sizeX / 2, 0, KeyboardLayout.body.sizeZ / 2) * convertMilitoUnitWeight;
                lkeyPos += ((Vector3)kvp.Value[0]) * convertMilitoUnitWeight;

                aText       = createTextInstance(aText, textMeshPro, lkeyPos, this.transform.localRotation, kvp.Key.ToString());
                aText.color = new Color((float)random.NextDouble() * 0.9f + 0.1f, (float)random.NextDouble() * 0.9f + 0.1f, (float)random.NextDouble() * 0.9f + 0.1f, (float)random.NextDouble() * 0.1f + 0.9f);
            }
            // 押下音再生
            audioSource.PlayOneShot(soundSpace);
        }
        // その他通常キー押下時:出現+バッファ
        else
        {
            foreach (char c in Input.inputString)
            {
                ArrayList   arKey = new ArrayList();
                string      tmpStr;
                TextMeshPro aText = new TextMeshPro();

                Vector3 lkeyPos = new Vector3(-1 * KeyboardLayout.body.sizeX / 2, 0, KeyboardLayout.body.sizeZ / 2) * convertMilitoUnitWeight;

                // 押下キーが設定から取得できた場合
                if (KeyboardLayout.layout.TryGetValue(c.ToString(), out arKey))
                {
                    lkeyPos   += (Vector3)arKey[0] * convertMilitoUnitWeight;
                    tmpStr     = c.ToString();
                    bufferStr += c;
                }
                else
                {
                    lkeyPos += new Vector3(KeyboardLayout.body.sizeX / 2, 0, -1 * KeyboardLayout.body.sizeZ / 2) * convertMilitoUnitWeight;
                    tmpStr   = "><";
                }
                aText = createTextInstance(aText, textMeshPro, lkeyPos, this.transform.localRotation, tmpStr);

                // 押下音再生
                if (Random.value > 0.5f)
                {
                    audioSource.PlayOneShot(soundKeydown_01);
                }
                else
                {
                    audioSource.PlayOneShot(soundKeydown_02);
                }
            }
        }

        // GameObjectを作成+設定
        GameObject createObjectInstance(GameObject gObj, GameObject instance, Vector3 pos, Quaternion rot, Vector3 scale)
        {
            gObj = Instantiate(instance, pos, Quaternion.identity, this.transform);
            gObj.transform.localPosition = pos;
            gObj.transform.localRotation = rot;
            gObj.transform.localScale    = scale;
            return(gObj);
        }

        // TextMeshProを作成+設定
        TextMeshPro createTextInstance(TextMeshPro txtObj, TextMeshPro instance, Vector3 pos, Quaternion rot, string text)
        {
            txtObj = Instantiate(instance, pos, Quaternion.identity, this.transform);
            txtObj.transform.localPosition = pos;
            txtObj.transform.localRotation = rot;
            txtObj.text = text;
            return(txtObj);
        }
    }
    //Creates Tile Map
    public void GenerateMap()
    {
        m_CurrentMap = maps[mapIndex];
        tileMap      = new Transform[m_CurrentMap.mapSize.x, m_CurrentMap.mapSize.y];
        System.Random prng = new System.Random(m_CurrentMap.m_Seed);
        m_Collection = new List <Coords>();

        //Generating Coords
        for (int x = 0; x < m_CurrentMap.mapSize.x; x++)
        {
            for (int y = 0; y < m_CurrentMap.mapSize.y; y++)
            {
                m_Collection.Add(new Coords(x, y));
            }
        }

        //Shuffle Collection of Coords
        m_ShuffledCollection = new Queue <Coords>(Utility.ShuffleArray(m_Collection.ToArray(), m_CurrentMap.m_Seed));

        //Clear list on function call
        string name = "Generated Map";

        if (transform.Find(name))
        {
            DestroyImmediate(transform.Find(name).gameObject);
        }

        Transform mapHolder = new GameObject(name).transform;

        mapHolder.parent = transform;

        bool[,] obstacleMap = new bool[m_CurrentMap.mapSize.x, m_CurrentMap.mapSize.y];
        List <Coords> openCollection = new List <Coords>(m_Collection);

        //Set Obstacle positions
        int currObstCount = 0;
        int numObstacles  = (int)((m_CurrentMap.mapSize.x * m_CurrentMap.mapSize.y) * m_CurrentMap.m_ObstaclePercent);

        for (int i = 0; i < numObstacles; i++)
        {
            Coords randCoord = GetRandCoord();
            obstacleMap[randCoord.x, randCoord.y] = true;
            currObstCount++;

            if (randCoord != m_CurrentMap.mapCentre && !isEdge(randCoord.x, randCoord.y) && MapIsFullyAccessible(obstacleMap, currObstCount))
            {
                float   obstacleHeight   = Mathf.Lerp(m_CurrentMap.minObstacleHeight, m_CurrentMap.maxObstacleHeight, (float)prng.NextDouble());
                Vector3 obstaclePosition = CoordToPosition(randCoord.x, randCoord.y);

                Transform obstacle = Instantiate(obstaclePrefab, obstaclePosition + Vector3.up * (obstacleHeight * 0.5f), Quaternion.identity) as Transform;
                obstacle.localScale = new Vector3((1 - outlinePercent) * tileSize, obstacleHeight, (1 - outlinePercent) * tileSize);
                obstacle.parent     = mapHolder;

                openCollection.Remove(randCoord);
            }
            else
            {
                obstacleMap[randCoord.x, randCoord.y] = false;
                currObstCount--;
            }
        }

        m_ShuffledOpenCollection = new Queue <Coords>(Utility.ShuffleArray(openCollection.ToArray(), m_CurrentMap.m_Seed));

        //Spawn Tiles
        for (int x = 0; x < m_CurrentMap.mapSize.x; x++)
        {
            for (int y = 0; y < m_CurrentMap.mapSize.y; y++)
            {
                Vector3 tilePosition = CoordToPosition(x, y);
                //Only Spawn Tile if obstacle doesn't exist in current position
                if (obstacleMap[x, y] == true)
                {
                    continue;
                }
                else if (isEdge(x, y))
                {
                    float     obstacleHeight = Mathf.Lerp(m_CurrentMap.minObstacleHeight, m_CurrentMap.maxObstacleHeight, (float)prng.NextDouble());
                    Transform obstacle       = Instantiate(obstaclePrefab, tilePosition + Vector3.up * (obstacleHeight * 0.5f), Quaternion.identity) as Transform;
                    obstacle.localScale = Vector3.one * (1 - outlinePercent) * tileSize;
                    obstacle.parent     = mapHolder;

                    obstacleMap[x, y] = true;
                }
                else
                {
                    Transform tileinstance = Instantiate(tilePrefab, tilePosition, Quaternion.Euler(Vector3.right * 90)) as Transform;
                    tileinstance.localScale = Vector3.one * (1 - outlinePercent) * tileSize;
                    tileinstance.parent     = mapHolder;

                    tileMap[x, y] = tileinstance;
                }
            }
        }
    }
Ejemplo n.º 52
0
    public double GetDoubleInRange(double minValue, double maxValue)
    {
        double result = rnd.NextDouble() * (maxValue - minValue) + minValue;

        return(result);
    }
Ejemplo n.º 53
0
 public static double NextDoubleRanged(this System.Random rand, double min, double max)
 {
     return(min + rand.NextDouble() * (max - min));
 }
Ejemplo n.º 54
0
    public void GenerateMap()
    {
        // If empty parent transforms exist, then create them.
        if (mapParent == null)
        {
            mapParent = new GameObject("Generated SquareTileMap").transform;

            if (tilesParent == null)
            {
                tilesParent        = new GameObject("Square Tiles").transform;
                tilesParent.parent = mapParent;
            }

            if (obstaclesParent == null)
            {
                obstaclesParent        = new GameObject("Obstacles").transform;
                obstaclesParent.parent = mapParent;
            }

            if (navmeshMasksParent == null)
            {
                navmeshMasksParent        = new GameObject("Navmesh Floor Masks").transform;
                navmeshMasksParent.parent = mapParent;
            }
        }

        // Set floor box collider size.
        navmeshFloor.GetComponent <BoxCollider>().size = new Vector3(minMapSize.x * tileSize, 0.05f, minMapSize.y * tileSize);

        // Random number seed for placing obstacles and modifying obstacle height.
        System.Random pRNG = new System.Random(obstaclePlaceSeed);

        // List of points in the map.
        points = new List <Point>();
        for (int x = 0; x < minMapSize.x; x++)
        {
            for (int y = 0; y < minMapSize.y; y++)
            {
                // Add the associated point to the points array.
                points.Add(new Point(x, y));
            }
        }

        // List of unoccupied points in the map. We remove points from this list during obstacle generation.
        List <Point> unoccupiedPoints = new List <Point>(points);

        shuffledTilePoints = new Queue <Point>(SquareTileMapUtility.ShuffleArray(points.ToArray(), obstaclePlaceSeed));

        // Destroy previous tiles.
        if (tiles != null)
        {
            for (int i = tilesParent.childCount - 1; i >= 0; --i)
            {
                DestroyImmediate(tilesParent.GetChild(i).gameObject);
            }
            tiles.Clear();
        }

        // Destroy previous obstacles.
        for (int i = obstaclesParent.childCount - 1; i >= 0; --i)
        {
            DestroyImmediate(obstaclesParent.GetChild(i).gameObject);
        }

        // Loop through axes to generate map.
        for (int x = 0; x < minMapSize.x; x++)
        {
            for (int y = 0; y < minMapSize.y; y++)
            {
                Vector3   tilePosition = PointToPosition(x, y);
                Transform newTile      = Instantiate(tilePrefab, tilePosition, Quaternion.Euler(Vector3.right * 90)) as Transform;
                newTile.localScale       = Vector3.one * (1 - tileOutlinePercent) * tileSize;
                newTile.transform.parent = tilesParent;

                if (newTile.GetComponent <SquareTile>() == null)
                {
                    newTile.gameObject.AddComponent <SquareTile>();
                }

                SquareTile newSquareTile = newTile.gameObject.GetComponent <SquareTile>();
                newSquareTile.SetPos(x, y);
                newSquareTile.Height = 0;
                // Add to tiles dictionary.
                tiles.Add(new Point(x, y), newSquareTile);
                // Since we haven't generated obstacles yet, add this squaretile to the obstacles dictionary with a null obstacle.
                obstacles.Add(newSquareTile, null);
            }
        }

        // Used in ensuring map connectivity.
        bool[,] obstacleMap = new bool[(int)minMapSize.x, (int)minMapSize.y];
        int obstacleFillAmount = (int)(minMapSize.x * minMapSize.y * obstaclePercent);
        int obstacleCount      = 0;

        // Generate obstacles.
        for (int i = 0; i < obstacleFillAmount; i++)
        {
            Point randomPoint = GetRandomPoint();

            // We presume we are instantiating an obstacle at the point before we can check if the obstacle closes anything off.
            obstacleMap[randomPoint.x, randomPoint.y] = true;
            obstacleCount++;

            // We never want to spawn an obstacle in the center of the map or in a place that would cut off a path.
            if (randomPoint != mapCenter && MapIsFullyAccessible(obstacleMap, obstacleCount))
            {
                float     obstacleHeight   = Mathf.Lerp(minObstacleHeight, maxObstacleHeight, (float)pRNG.NextDouble());
                Vector3   obstaclePosition = PointToPosition(randomPoint.x, randomPoint.y);
                Transform newObstacle      = Instantiate(obstaclePrefab, obstaclePosition + (Vector3.up * obstacleHeight / 2f), Quaternion.identity) as Transform;
                newObstacle.localScale = new Vector3((1 - tileOutlinePercent) * tileSize, obstacleHeight, (1 - tileOutlinePercent) * tileSize);
                newObstacle.parent     = obstaclesParent;

                // Remove this point from our unoccupied points list.
                unoccupiedPoints.Remove(randomPoint);

                // Add to obstacles dictionary.
                // Get the tile at our random point.
                SquareTile ourTile = tiles[randomPoint];
                // Add obstacle transform to obstacles dictionary.
                obstacles[ourTile] = newObstacle;

                // Color settings based on foreground/background colors.
                Renderer obstacleRenderer = newObstacle.GetComponent <Renderer>();
                Material obstacleMaterial = new Material(obstacleRenderer.sharedMaterial);

                // Determine how far 'forward' this obstacle is.
                float colorPercent = randomPoint.y / (float)minMapSize.y;

                obstacleMaterial.color          = Color.Lerp(foregroundColor, backgroundColor, colorPercent);
                obstacleRenderer.sharedMaterial = obstacleMaterial;
            }
            else
            {
                // If the check fails, then we remove the obstacle location from the obstacle map.
                obstacleMap[randomPoint.x, randomPoint.y] = false;
                obstacleCount--;
            }
        }

        unOccupiedTilePoints = new Queue <Point>(SquareTileMapUtility.ShuffleArray(unoccupiedPoints.ToArray(), obstaclePlaceSeed));

        // Destroy previous navmesh floor masks.
        for (int i = navmeshMasksParent.childCount - 1; i >= 0; --i)
        {
            DestroyImmediate(navmeshMasksParent.GetChild(i).gameObject);
        }

        // Destroy previous navmesh floor.
        for (int i = 0; i < mapParent.childCount; i++)
        {
            if (mapParent.GetChild(i).GetComponent <NavmeshFloor>())
            {
                DestroyImmediate(mapParent.GetChild(i).gameObject);
                break;
            }
        }

        // Generate navmesh floor.
        Transform ourFloor = Instantiate(navmeshFloor);

        ourFloor.localRotation = Quaternion.Euler(90f, 0f, 0f);
        ourFloor.localScale    = new Vector3(maxMapSize.x, maxMapSize.y) * tileSize;
        ourFloor.GetComponent <BoxCollider>().size = new Vector3(1f, 1f, 0);
        ourFloor.parent = mapParent;

        // Generate navmesh floor masks.
        Transform maskLeft = Instantiate(navmeshMaskPrefab, Vector3.left * (minMapSize.x + maxMapSize.x) / 4f * tileSize, Quaternion.identity) as Transform;

        maskLeft.gameObject.AddComponent <BoxCollider>();
        maskLeft.parent = navmeshMasksParent;
        Transform maskRight = Instantiate(navmeshMaskPrefab, Vector3.right * (minMapSize.x + maxMapSize.x) / 4f * tileSize, Quaternion.identity) as Transform;

        maskRight.gameObject.AddComponent <BoxCollider>();
        maskRight.parent = navmeshMasksParent;
        Transform maskTop = Instantiate(navmeshMaskPrefab, Vector3.forward * (minMapSize.y + maxMapSize.y) / 4f * tileSize, Quaternion.identity) as Transform;

        maskTop.gameObject.AddComponent <BoxCollider>();
        maskTop.parent = navmeshMasksParent;
        Transform maskBottom = Instantiate(navmeshMaskPrefab, Vector3.back * (minMapSize.y + maxMapSize.y) / 4f * tileSize, Quaternion.identity) as Transform;

        maskBottom.gameObject.AddComponent <BoxCollider>();
        maskBottom.parent = navmeshMasksParent;

        maskLeft.localScale   = new Vector3((maxMapSize.x - minMapSize.x) / 2f, 1, minMapSize.y) * tileSize;
        maskRight.localScale  = new Vector3((maxMapSize.x - minMapSize.x) / 2f, 1, minMapSize.y) * tileSize;
        maskTop.localScale    = new Vector3(maxMapSize.x, 1, (maxMapSize.y - minMapSize.y) / 2f) * tileSize;
        maskBottom.localScale = new Vector3(maxMapSize.x, 1, (maxMapSize.y - minMapSize.y) / 2f) * tileSize;

        // Save to map parent.
        if (mapParent.GetComponent <SquareTileMap>() == null)
        {
            mapParent.gameObject.AddComponent <SquareTileMap>();
        }

        mapParent.GetComponent <SquareTileMap>().Setup(minMapSize, obstaclePercent, obstaclePlaceSeed, minObstacleHeight, maxObstacleHeight, foregroundColor, backgroundColor);
    }