コード例 #1
0
        public void EnqueueDequeue()
        {
            var pq1 = new PriorityQueue <int>();
            var pq2 = new PriorityQueue <int>();

            for (int i = 10; i > 0; i--)
            {
                pq1.Enqueue(i);
                pq2.Enqueue(i);
            }
            var mt = MTRandom.Create();

            for (int i = -1; i < 20; i++)
            {
                EnqueueDequeue(i);
                EnqueueDequeue(mt.Next());
            }

            void EnqueueDequeue(int value)
            {
                pq2.Enqueue(value);
                pq1.EnqueueDequeue(value).Should().Be(pq2.Dequeue());
                pq1.Unorderd().ToArray().Should().BeEquivalentTo(pq2.Unorderd().ToArray());
            }
        }
コード例 #2
0
        public void DequeueEnqueueKV()
        {
            var pq1 = new PriorityQueueDictionary <int, string>();
            var pq2 = new PriorityQueueDictionary <int, string>();
            Func <int, string, (int, string)> func = (k, v) => (k * 2, (2 * k).ToString());

            for (int i = 10; i > 0; i--)
            {
                pq1.Enqueue(i, i.ToString());
                pq2.Enqueue(i, i.ToString());
            }
            var mt = MTRandom.Create();

            for (int i = -1; i < 20; i++)
            {
                EnqueueDequeue();
            }

            void EnqueueDequeue()
            {
                var(k, v)   = pq2.Dequeue();
                var(ek, ev) = func(k, v);
                pq2.Enqueue(KeyValuePair.Create(ek, ev));
                pq1.DequeueEnqueue(func);
                pq1.UnorderdKeys().ToArray().Should().BeEquivalentTo(pq2.UnorderdKeys().ToArray());
                pq1.UnorderdValues().ToArray().Should().BeEquivalentTo(pq2.UnorderdValues().ToArray());
            }
        }
コード例 #3
0
        public void EnqueueDequeueKV()
        {
            var pq1 = new PriorityQueueDictionary <int, string>();
            var pq2 = new PriorityQueueDictionary <int, string>();

            for (int i = 10; i > 0; i--)
            {
                pq1.Enqueue(i, i.ToString());
                pq2.Enqueue(i, i.ToString());
            }
            var mt = MTRandom.Create();

            for (int i = -1; i < 20; i++)
            {
                EnqueueDequeue(i);
                EnqueueDequeue(mt.Next());
            }

            void EnqueueDequeue(int value)
            {
                pq2.Enqueue(value, value.ToString());
                pq1.EnqueueDequeue(value, value.ToString()).Should().Be(pq2.Dequeue());
                pq1.UnorderdKeys().ToArray().Should().BeEquivalentTo(pq2.UnorderdKeys().ToArray());
                pq1.UnorderdValues().ToArray().Should().BeEquivalentTo(pq2.UnorderdValues().ToArray());
            }
        }
コード例 #4
0
        public void Sequence_MT()
        {
            var seed = Environment.TickCount;

            Test(MTRandom.Create(seed, MTEdition.Original_19937), MTRandom.Create(seed, MTEdition.Cok_19937));
            Test(MTRandom.Create(seed, MTEdition.Original_19937), MTRandom.Create(seed, MTEdition.CokOpt_19937));
        }
コード例 #5
0
ファイル: LuaLib.cs プロジェクト: LostTemple1990/BarrageDemo
    /// <summary>
    /// 随机返回-1或者1
    /// </summary>
    /// <param name="luaState"></param>
    /// <returns></returns>
    public static int GetRandomSign(ILuaState luaState)
    {
        int ret = MTRandom.GetNextInt(0, 1);

        luaState.PushNumber(ret == 0 ? -1 : 1);
        return(1);
    }
コード例 #6
0
        public Vector3[] GetTCoordsQuick(int index, Material mat, Vector3i coord)
        {
            // NOTE: This method is called very often by the client (when r_compute is off). Any optimization here will be very useful (For old clients)!
            Vector3[] set = BSSD.TCrds[index];
            int       len = set.Length;

            Vector3[] vecs = new Vector3[len];
            Vector3   temp;

            int[][] helper = MaterialHelpers.ALL_MATS[(int)mat].TID;
            int     choice = -1;

            for (int i = 0; i < len; i++)
            {
                temp = set[i];
                int[] opts = helper[DB_RLOK[(int)temp.Z]];
                if (opts.Length == 1)
                {
                    temp.Z = opts[0];
                }
                else
                {
                    if (choice == -1)
                    {
                        // TODO: 39 is probably pointlessly high here.
                        choice = new MTRandom(39, (ulong)(SimplexNoise.Generate(coord.X, coord.Y, coord.Z) * 1000 * 1000)).Next(10000);
                    }
                    temp.Z = opts[choice % opts.Length];
                }
                vecs[i] = temp;
            }
            return(vecs);
        }
コード例 #7
0
    /// <summary>
    /// 根据ChangeValue的值获取对应的值并返回
    /// </summary>
    /// <param name="changeValue"></param>
    /// <returns></returns>
    private float GetValueByChangeValue(ParaChangeValue changeValue)
    {
        float value = 0;

        if (changeValue.argType == 0)
        {
            value = changeValue.arg0;
        }
        else if (changeValue.argType == 1)
        {
            Vector2 playerPos = new Vector2(Global.PlayerPos.x, Global.PlayerPos.y);
            Vector2 bulletPos = _bullet.GetPosition();
            float   angle     = MathUtil.GetAngleBetweenXAxis(playerPos - bulletPos);
            value = angle;
        }
        else if (changeValue.argType == 2)
        {
            Vector2 targetPos = new Vector2(changeValue.arg0, changeValue.arg1);
            Vector2 bulletPos = _bullet.GetPosition();
            float   angle     = MathUtil.GetAngleBetweenXAxis(targetPos - bulletPos);
            value = angle;
        }
        if (changeValue.offset != 0)
        {
            value += MTRandom.GetNextFloat(-changeValue.offset, changeValue.offset);
        }
        return(value);
    }
コード例 #8
0
        public void UtilReverseTest()
        {
            var mt = MTRandom.Create();

            for (int n = 0; n < 200; n++)
            {
                var arr = new int[n];
                for (int i = 0; i < n; i++)
                {
                    arr[i] = mt.Next();
                }
                var cpp = arr.ToArray();
                Array.Sort(arr);
                Array.Reverse(arr);
                Array.Sort(cpp, ComparerUtil.ReverseComparerInt);
                cpp.Should().Equal(cpp);
            }
            for (int n = 0; n < 200; n++)
            {
                var arr = new long[n];
                for (int i = 0; i < n; i++)
                {
                    arr[i] = mt.Next();
                }
                var cpp = arr.ToArray();
                Array.Sort(arr);
                Array.Reverse(arr);
                Array.Sort(cpp, ComparerUtil.ReverseComparerLong);
                cpp.Should().Equal(cpp);
            }
        }
コード例 #9
0
 /// <summary>
 /// Performs a simulation of the Ising system with given parameters.
 /// </summary>
 /// <param name="MagMean">Mean magnetization.</param>
 /// <param name="Susceptibility">Magnetic susceptibility of the system.</param>
 public void PerformSimulation(out double MagMean, out double Susceptibility)
 {
     Generator = MTRandom.Create(MTEdition.Original_19937);
     State     = new sbyte[ProblemSize];
     MagSamp   = new double[SamplingCount];
     for (int i = 0; i < ProblemSize; i++)
     {
         State[i] = 1;
     }
     for (int i = 0; i < WarmupFactor; i++)
     {
         UpdateStateN();
     }
     MagMean = 0;
     for (int i = 0; i < SamplingCount; i++)
     {
         for (int j = 0; j < SamplingTime; j++)
         {
             UpdateStateN();
         }
         MagSamp[i] = ComputeMagSample();
         MagMean   += MagSamp[i];
     }
     MagMean       /= SamplingCount;
     Susceptibility = 0;
     for (int i = 0; i < SamplingCount; i++)
     {
         Susceptibility += (MagSamp[i] - MagMean) * (MagSamp[i] - MagMean);
     }
     Susceptibility *= ((double)ProblemSize) / SamplingCount;
 }
コード例 #10
0
        /// <summary>
        /// 创建Besize曲线的Action
        /// </summary>
        /// <param name="targetTF">Target T.</param>
        /// <param name="startPos">Start position.</param>
        /// <param name="endPos">End position.</param>
        /// <param name="showTime">Show time.</param>
        /// <param name="config">Config.</param>
        public static MTBezierTo CreateBesizeAction(Transform targetTF, Vector3 startPos, Vector3 endPos, float showTime, BesizeControlConfig config, BesizeControlConfig config2)
        {
            bool left = MTRandom.GetRandomInt(1, 2) > 1;

            Vector3 controller1;

            EffectUtil.BesizeControlPos(startPos, endPos, config, out controller1, out controller1, left);
            controller1.z = 0;

            Vector3 controller2;

            EffectUtil.BesizeControlPos(startPos, endPos, config2, out controller2, out controller2, left);
            controller2.z = 0;

            startPos      = targetTF.InverseTransformPoint(startPos);
            startPos.z    = 0;
            endPos        = targetTF.InverseTransformPoint(endPos);
            endPos.z      = 0;
            controller1   = targetTF.InverseTransformPoint(controller1);
            controller1.z = 0;
            controller2   = targetTF.InverseTransformPoint(controller2);
            controller2.z = 0;

            MTBezierConfig bconfig = new MTBezierConfig();

            bconfig.ControlPoint1 = controller1;
            bconfig.ControlPoint2 = controller2;
            bconfig.EndPosition   = endPos;

            return(new MTBezierTo(showTime, bconfig));
        }
コード例 #11
0
 private static void Fill(ulong[] array, MTRandom random)
 {
     for (int i = 0; i < array.Length; i++)
     {
         array[i] = random.genrand_int64();
     }
 }
コード例 #12
0
            public void GenerateTrees(SimpleGeneratorCore sgc, Vector3i chunkPos, int Seed, int seed, int seed3, int seed4, int seed5)
            {
                Trees         = new List <KeyValuePair <Vector2i, int> >();
                ChunkPosition = chunkPos;
                CPos          = chunkPos.ToLocation() * Chunk.CHUNK_SIZE;
                MTRandom random = new MTRandom((ulong)chunkPos.GetHashCode());
                // TODO: Biome basis!
                int c = 0;

                if (random.Next(1, 5) == 1)
                {
                    if (random.Next(1, 5) == 1)
                    {
                        if (random.Next(1, 5) == 1)
                        {
                            c = random.Next(1, 3);
                        }
                        else
                        {
                            c = random.Next(1, 2);
                        }
                    }
                    else
                    {
                        c = 1;
                    }
                }
                for (int i = 0; i < c; i++)
                {
                    Trees.Add(new KeyValuePair <Vector2i, int>(new Vector2i(random.Next(Chunk.CHUNK_SIZE), random.Next(Chunk.CHUNK_SIZE)), random.Next()));
                }
            }
コード例 #13
0
        public void DequeueEnqueue()
        {
            var             pq1  = new PriorityQueue <int>();
            var             pq2  = new PriorityQueue <int>();
            Func <int, int> func = k => k * 2;

            for (int i = 10; i > 0; i--)
            {
                pq1.Enqueue(i);
                pq2.Enqueue(i);
            }
            var mt = MTRandom.Create();

            for (int i = -1; i < 20; i++)
            {
                EnqueueDequeue();
            }

            void EnqueueDequeue()
            {
                pq2.Enqueue(func(pq2.Dequeue()));
                pq1.DequeueEnqueue(func);
                pq1.Unorderd().ToArray().Should().BeEquivalentTo(pq2.Unorderd().ToArray());
            }
        }
コード例 #14
0
ファイル: RandomSphere.cs プロジェクト: Dracir/semicolon
        private static Vector3 PickCubePoints(ref UMT.MersenneTwister _rand)
        {
            float x = MTRandom.ScaleFloatToRange(_rand.NextSingle(true), -1, 1, 0, 1);
            float y = MTRandom.ScaleFloatToRange(_rand.NextSingle(true), -1, 1, 0, 1);
            float z = MTRandom.ScaleFloatToRange(_rand.NextSingle(true), -1, 1, 0, 1);

            return(new Vector3(x, y, z));
        }
コード例 #15
0
ファイル: LuaLib.cs プロジェクト: LostTemple1990/BarrageDemo
    public static int GetRandomFloat(ILuaState luaState)
    {
        float begin = (float)luaState.ToNumber(-2);
        float end   = (float)luaState.ToNumber(-1);

        luaState.PushNumber(MTRandom.GetNextFloat(begin, end));
        return(1);
    }
コード例 #16
0
ファイル: RandomDisk.cs プロジェクト: Dracir/semicolon
        // CIRCLE with R=1
        public static Vector2 Circle(ref UMT.MersenneTwister _rand)
        {
            float t    = (float)_rand.Next();
            float _2pi = (float)Math.PI * 2;
            float a    = MTRandom.ScaleFloatToRange(t, 0, _2pi, 0, Int32.MaxValue);

            return(new Vector2((float)Math.Cos(a), (float)Math.Sin(a)));
        }
コード例 #17
0
ファイル: LuaLib.cs プロジェクト: LostTemple1990/BarrageDemo
    public static int GetRandomInt(ILuaState luaState)
    {
        int begin = luaState.ToInteger(-2);
        int end   = luaState.ToInteger(-1);

        luaState.PushInteger(MTRandom.GetNextInt(begin, end));
        return(1);
    }
コード例 #18
0
	private void ExampleOnSphere()
	{
		DebugStreamer.AddMessage("MTRandom mrand = new MTRandom(seed)");
		DebugStreamer.AddMessage("mrand.PointOnASphere()");
		mrand = new MTRandom(user_seed);
		CleanUp();		
		MakeObjects();
	}
コード例 #19
0
        public void StressOK()
        {
            var mt = MTRandom.Create();

            for (int phase = 0; phase < 10000; phase++)
            {
                int n      = mt.Next(1, 21);
                int m      = mt.Next(1, 101);
                var expect = new bool[n];
                for (int i = 0; i < n; i++)
                {
                    expect[i] = mt.NextBool();
                }
                var ts    = new TwoSat(n);
                var xs    = new int[m];
                var ys    = new int[m];
                var types = new int[m];
                for (int i = 0; i < m; i++)
                {
                    int x    = mt.Next(0, n);
                    int y    = mt.Next(0, n);
                    int type = mt.Next(0, 3);
                    xs[i]    = x;
                    ys[i]    = y;
                    types[i] = type;
                    if (type == 0)
                    {
                        ts.AddClause(x, expect[x], y, expect[y]);
                    }
                    else if (type == 1)
                    {
                        ts.AddClause(x, !expect[x], y, expect[y]);
                    }
                    else
                    {
                        ts.AddClause(x, expect[x], y, !expect[y]);
                    }
                }
                ts.Satisfiable().Should().BeTrue();
                var actual = ts.Answer();
                for (int i = 0; i < m; i++)
                {
                    int x = xs[i], y = ys[i], type = types[i];
                    if (type == 0)
                    {
                        (actual[x] == expect[x] || actual[y] == expect[y]).Should().BeTrue();
                    }
                    else if (type == 1)
                    {
                        (actual[x] != expect[x] || actual[y] == expect[y]).Should().BeTrue();
                    }
                    else
                    {
                        (actual[x] == expect[x] || actual[y] != expect[y]).Should().BeTrue();
                    }
                }
            }
        }
コード例 #20
0
ファイル: MissionMode.cs プロジェクト: ramius86/Barotrauma
        public MissionMode(GameModePreset preset, object param)
            : base(preset, param)
        {
            Location[] locations = { GameMain.GameSession.StartLocation, GameMain.GameSession.EndLocation };

            MTRandom rand = new MTRandom(ToolBox.StringToInt(GameMain.NetLobbyScreen.LevelSeed));

            mission = Mission.LoadRandom(locations, rand, param as string);
        }
コード例 #21
0
ファイル: RandomSphere.cs プロジェクト: Dracir/semicolon
        /// <summary>
        /// Returns a point on the unit sphere that is within a cone along the z-axis
        /// </summary>
        /// <param name="spotAngle">[0..180] specifies the angle of the cone. </param>
        /// <remarks>
        /// FROM: http://unifycommunity.com/wiki/index.php?title=UnitSphere
        /// </remarks>
        public static Vector3 GetPointOnCap(float spotAngle, ref UMT.MersenneTwister _rand)
        {
            float   angle1 = MTRandom.ScaleFloatToRange(_rand.NextSingle(true), 0.0f, Mathf.PI * 2, 0, 1);
            float   angle2 = MTRandom.ScaleFloatToRange(_rand.NextSingle(true), 0.0f, spotAngle * Mathf.Deg2Rad, 0, 1);
            Vector3 V      = new Vector3(Mathf.Sin(angle1), Mathf.Cos(angle1), 0);

            V  *= Mathf.Sin(angle2);
            V.z = Mathf.Cos(angle2);
            return(V);
        }
コード例 #22
0
        void RunTo(Vector3 startPos, Vector3 endPos, float delayTime, float showTime, TrailConfig config)
        {
            StartCoroutine(CurveAction(startPos, endPos, Vector3.up, delayTime, showTime));
            Destroy(gameObject, delayTime + showTime);
            return;             //----------------------curve---------------

            int   minAngle = config.MinAngle;
            int   maxAngle = config.MaxAngle;
            float minDist  = config.MinDistRatio;
            float maxDist  = config.MaxDistRatio;

            int angle = UnityEngine.Random.Range(minAngle, maxAngle);

            if (MTRandom.GetRandomInt(1, 2) > 1)
            {
                angle = -angle;
            }

            Vector3 dis = new Vector3(endPos.x - startPos.x, endPos.y - startPos.y, 0);
            float   r   = Mathf.Atan2(dis.y, dis.x) * 180 / Mathf.PI;

            angle += (int)r;

            //计算两点之间随机值
            float   dist      = UnityEngine.Random.Range(minDist, maxDist);
            Vector3 middlePos = Vector3.Lerp(startPos, endPos, dist);

            dist = Vector3.Distance(startPos, middlePos);

//		middlePos = Vector3.RotateTowards

            float distx = Mathf.Cos(angle) * dist;
            float disty = Mathf.Sin(angle) * dist;

            Vector3 c1 = new Vector3(distx + startPos.x, disty + startPos.y, 0);

//		c1 = new Vector3 (c1.x / 100, c1.y / 100, 0);
//		endPos = new Vector3 (endPos.x / 100, endPos.y / 100, 0);

            MTBezierConfig bconfig = new MTBezierConfig();

            bconfig.ControlPoint1 = c1;
            bconfig.ControlPoint2 = c1;
            bconfig.EndPosition   = endPos;

            MTBezierTo action = new MTBezierTo(showTime, bconfig);

//		trail.gameObject.RunAction (action);
            trail.gameObject.RunActions(new MTDelayTime(delayTime), action, new MTDestroy());



//		MTMoveTo action = new MTMoveTo (showTime, endPos);
//		trail.gameObject.RunAction (action);
        }
コード例 #23
0
        /// <summary>
        /// Section of teh floor, contain Puzzles.
        /// </summary>
        /// <param name="startRoom">Start room of this section.</param>
        /// <param name="path">Critical path for this section.</param>
        /// <param name="haveBossRoom">Should we place a boss door in this section.</param>
        /// <param name="rng">Randrom generator for this dungeon.</param>
        public DungeonFloorSection(RoomTrait startRoom, List <MazeMove> path, bool haveBossRoom, MTRandom rng)
        {
            _lockColorProvider    = new LockColorProvider();
            _lockedDoorCandidates = new LinkedList <LockedDoorCandidateNode>();
            this.Places           = new List <PlaceNode>();
            this.Puzzles          = new List <Puzzle>();

            _placeBossDoor = haveBossRoom;
            _rng           = rng;

            this.InitLists(startRoom, path);
        }
コード例 #24
0
    public void DestoryAndGenCoin()
    {
        int m = MTRandom.GetRandomInt(0, 2);

        if (m == 0)
        {
            var coin = Instantiate <GameObject>(ResMgr.Current.CoinPrefab);
            coin.transform.position = transform.position;
            SoundMgr.Current.PlayCoinCameOut();
        }
        DestroyCell();
    }
コード例 #25
0
        static ZobristHashing()
        {
            var random = new MTRandom(0);

            PieceHashes = new ulong[2 * (int)PieceType.Count * 64];
            Fill(PieceHashes, random);
            EnPassantHashes = new ulong[64];
            Fill(EnPassantHashes, random);
            CastlingHashes = new ulong[64];
            Fill(CastlingHashes, random);
            WhiteSideHash = random.genrand_int64();
        }
コード例 #26
0
        public void SimpleKV()
        {
            var mt = MTRandom.Create();

            for (int n = 0; n < 200; n++)
            {
                var list = new List <int>();
                var pq   = new PriorityQueueDictionary <long, int>();
                for (int i = 0; i < n; i++)
                {
                    var x = mt.Next(0, int.MaxValue);
                    pq.Enqueue(x, -x);
                    list.Add(x);
                    pq.Count.Should().Be(list.Count).And.Be(i + 1);
                }
                pq.UnorderdKeys().ToArray().Should().HaveCount(n);
                pq.UnorderdValues().ToArray().Should().HaveCount(n);
                list.Sort();
                foreach (var lx in list)
                {
                    pq.Dequeue().Should().Be(KeyValuePair.Create((long)lx, -lx));
                }
                pq.Count.Should().Be(0);


                list.Reverse();
                foreach (var lx in list)
                {
                    pq.Enqueue(-lx, lx);
                }
                foreach (var lx in list)
                {
                    pq.TryDequeue(out var res).Should().BeTrue();
                    res.Should().Be(KeyValuePair.Create(-(long)lx, lx));
                }
                pq.TryDequeue(out _).Should().BeFalse();
                pq.Count.Should().Be(0);

                foreach (var lx in list)
                {
                    pq.Enqueue(-lx, lx);
                }
                foreach (var lx in list)
                {
                    pq.TryDequeue(out var key, out var val).Should().BeTrue();
                    key.Should().Be(-lx);
                    val.Should().Be(lx);
                }
                pq.TryDequeue(out _, out _).Should().BeFalse();
                pq.Count.Should().Be(0);
            }
        }
コード例 #27
0
        public void GenMountainPositionsForGridCell(List <MountainData> locs, Vector2i mountainPos, Vector2i chunkPos, int seed)
        {
            Vector2i mtChunk     = new Vector2i((int)(mountainPos.X * MountainGridSize), (int)(mountainPos.Y * MountainGridSize));
            Location chunkCenter = chunkPos.ToLocation() * Constants.CHUNK_WIDTH;
            MTRandom random      = new MTRandom(39, (ulong)(mountainPos.X * 39 + mountainPos.Y + seed));
            int      count       = random.Next(1, 3);

            for (int i = 0; i < count; i++)
            {
                int rangeSize;
                if (random.Next(10) > 5)
                {
                    rangeSize = random.Next(5, 13);
                }
                else
                {
                    rangeSize = random.Next(3, 8);
                }
                double       ca       = random.NextDouble();
                double       cb       = random.NextDouble();
                Vector2i     centerMt = new Vector2i(mtChunk.X * Constants.CHUNK_WIDTH + (int)(ca * MountainGridSize * Constants.CHUNK_WIDTH), mtChunk.Y * Constants.CHUNK_WIDTH + (int)(cb * MountainGridSize * Constants.CHUNK_WIDTH));
                double       ch       = random.NextDouble() * 512 + 512;
                double       cradius  = random.NextDouble() * ch * 0.25 + ch * 0.75;
                MountainData cmt      = new MountainData()
                {
                    Center = centerMt, Height = ch, Radius = cradius
                };
                if (centerMt.ToLocation().DistanceSquared(chunkCenter) < (MountainMaxSizeBlocks * MountainMaxSizeBlocks))
                {
                    locs.Add(cmt);
                }
                double ph = ch;
                for (int r = 1; r < rangeSize; r++)
                {
                    double ra = random.NextDouble() * 2.0 - 1.0;
                    double rb = random.NextDouble() * 2.0 - 1.0;
                    ra = ra > 0 ? Math.Max(r / (double)rangeSize, ra) : Math.Min(-r / (double)rangeSize, ra);
                    rb = rb > 0 ? Math.Max(r / (double)rangeSize, rb) : Math.Min(-r / (double)rangeSize, rb);
                    Vector2i     rngMt   = new Vector2i(centerMt.X + (int)(ra * MountainRangeRadius), centerMt.Y + (int)(rb * MountainRangeRadius));
                    double       rh      = random.NextDouble() * (ph * 0.5) + (ph * 0.5);
                    double       rradius = random.NextDouble() * rh * 0.25 + rh * 0.75;
                    MountainData rmt     = new MountainData()
                    {
                        Center = rngMt, Height = rh, Radius = rradius
                    };
                    if (rngMt.ToLocation().DistanceSquared(chunkCenter) < (MountainMaxSizeBlocks * MountainMaxSizeBlocks))
                    {
                        locs.Add(rmt);
                    }
                }
            }
        }
コード例 #28
0
	private void ExampleOnCap()
	{
		DebugStreamer.AddMessage("MTRandom mrand = new MTRandom(seed)");
		DebugStreamer.AddMessage("mrand.PointOnCap(30.0f)");
		mrand = new MTRandom(user_seed);
		CleanUp();
		MakeObjects();
		GameObject[] objs = GameObject.FindGameObjectsWithTag("Player");
		foreach (GameObject item in objs) 
		{
			item.transform.position = ScalePosition(mrand.PointOnCap(30.0f));
		}
	}
コード例 #29
0
        public EntityBackgroundSpawner(Engine engine, Camera camera)
            : base(CVars.Get <float>("entity_background_spawner_min"))
        {
            Engine  = engine;
            Camera  = camera;
            _random = new MTRandom();

            _entityCreationFunctions = new Func <Engine, Entity>[] {
                ChasingEnemyEntity.CreateSpriteOnly,
                LaserEnemyEntity.CreateSpriteOnly,
                ShootingEnemyEntity.CreateSpriteOnly
            };
        }
コード例 #30
0
    public override void Start()
    {
        SCEffect effect;
        float    angle = MTRandom.GetNextFloat(0, 360);

        for (int i = 0; i < MaxEffectCount; i++)
        {
            effect = new SCEffect();
            effect.Init(angle + i * 45, i);
            _effectList.Add(effect);
        }
        // 音效
        SoundManager.GetInstance().Play("se_masterspark", 0.1f, false, true);
    }
コード例 #31
0
ファイル: RandomDirection.cs プロジェクト: tkiapril/aura
		public int GetDirection(MTRandom rnd)
		{
			var visited = true;
			var direction = 0;

			while (visited)
			{
				direction = (int)rnd.GetUInt32() & 3;
				visited = this.Directions[direction] != 0;
			}

			this.Directions[direction] = 1;

			return direction;
		}
コード例 #32
0
ファイル: Item.cs プロジェクト: tkiapril/aura
		/// <summary>
		/// Changes item colors, using MTRandom and hash.
		/// </summary>
		/// <remarks>
		/// The hash is converted to an int, which is used as the seed for
		/// MTRandom, the RNG Mabi is using. That RNG is used to get specific
		/// "random" colors from the color map db.
		/// 
		/// Used to generate "random" colors on the equipment of
		/// new characters and partners.
		/// </remarks>
		public static void GenerateItemColors(ref List<Item> items, string hash)
		{
			var ihash = hash.Aggregate(5381, (current, ch) => current * 33 + (int)ch);

			var rnd = new MTRandom(ihash);
			foreach (var item in items.Where(a => a.Info.Pocket != Pocket.Face && a.Info.Pocket != Pocket.Hair))
			{
				var dataInfo = AuraData.ItemDb.Find(item.Info.Id);
				if (dataInfo == null)
					continue;

				item.Info.Color1 = (item.Info.Color1 != 0 ? item.Info.Color1 : AuraData.ColorMapDb.GetRandom(dataInfo.ColorMap1, rnd));
				item.Info.Color2 = (item.Info.Color2 != 0 ? item.Info.Color2 : AuraData.ColorMapDb.GetRandom(dataInfo.ColorMap2, rnd));
				item.Info.Color3 = (item.Info.Color3 != 0 ? item.Info.Color3 : AuraData.ColorMapDb.GetRandom(dataInfo.ColorMap3, rnd));
			}
		}
コード例 #33
0
 public static Vector2 Circle( ref UMT.MersenneTwister _rand, MTRandom.Normalization n, float t )
 {
     float r;
     switch (n) {
     case MTRandom.Normalization.STDNORMAL:
         r = MTRandom.ScaleFloatToRange( (float) NormalDistribution.Normalize(_rand.NextSingle(true), t), 0, Int32.MaxValue, 0, 1);
     break;
     case MTRandom.Normalization.POWERLAW:
         r = (float) PowerLaw.Normalize(_rand.NextSingle(true), t, 0, Int32.MaxValue);
     break;
     default:
         r = (float) _rand.Next();
     break;
     }
     float _2pi = (float) Math.PI * 2;
     float a = MTRandom.ScaleFloatToRange(r, 0, _2pi, 0, Int32.MaxValue);
     return new Vector2( (float) Math.Cos(a) , (float) Math.Sin(a));
 }
コード例 #34
0
ファイル: MazeGenerator.cs プロジェクト: tkiapril/aura
		public bool GenerateCriticalPath(MTRandom rnd, int critPathMin, int critPathMax)
		{
			if (this.isCriticalPathGenerated)
				return true;

			if (critPathMin > critPathMax)
			{
				var min = critPathMin;
				critPathMin = critPathMax;
				critPathMax = min;
			}

			//this._critPathMinResult = 0;
			this._critPathMaxResult = 0;
			this.isCriticalPathGenerated = this.GenerateCriticalPathRecursive(0, critPathMin, critPathMax, -1, rnd);

			return this.isCriticalPathGenerated;
		}
コード例 #35
0
        public static Vector2 Disk( ref UMT.MersenneTwister _rand, MTRandom.Normalization n, float temp )
        {
            double t, theta;

            switch (n) {
            case MTRandom.Normalization.STDNORMAL:
                t = NormalDistribution.Normalize(_rand.NextSingle(true), temp);
                theta = NormalDistribution.Normalize(_rand.NextSingle(true), temp) * 2 * Math.PI;
            break;
            case MTRandom.Normalization.POWERLAW:
                t = PowerLaw.Normalize(_rand.NextSingle(true), temp, 0, 1);
                theta = PowerLaw.Normalize(_rand.NextSingle(true), temp, 0, 1) * 2 * Math.PI;
            break;
            default:
                t = (float)  _rand.NextSingle(true);
                theta = _rand.NextSingle(false) * 2 * Math.PI;
            break;
            }

            return new Vector2( (float) (Math.Sqrt(t) * Math.Cos(theta)), (float) (Math.Sqrt(t) * Math.Sin(theta)) );
        }
コード例 #36
0
        public static Vector2 Area( ref UMT.MersenneTwister _rand, MTRandom.Normalization n, float t )
        {
            float x,y;
            x = y = 0;
            switch (n) {
            case MTRandom.Normalization.STDNORMAL:
                x = (float) NormalDistribution.Normalize(_rand.NextSingle(true), t);
                y = (float) NormalDistribution.Normalize(_rand.NextSingle(true), t);
            break;
            case MTRandom.Normalization.POWERLAW:
                x = (float) PowerLaw.Normalize(_rand.NextSingle(true), t, 0, 1);
                y = (float) PowerLaw.Normalize(_rand.NextSingle(true), t, 0, 1);
            break;
            default:
                x = _rand.NextSingle(true);
                y = _rand.NextSingle(true);
            break;
            }

            // Move to -1, 1 space as for CIRCLE and SPHERE
            return new Vector2((2*x - 1), (2*y - 1));
        }
コード例 #37
0
 public void init()
 {
     int i;
     BattleGlobal.Core = this;
     this._random = new MTRandom();
     // test 设置固定随机种子
     this.initRandomSeed();
     this._playerList = new List<Player>();
     for (i=0;i<2;i++)
     {
         this._playerList.Add(new Player());
         this._playerList[i].init();
     }
     if (this._info == null)
     {
         this._info = new BattleInfo();
     }
     this._info.reset();
     this._isGameStarted = false;
     // 初始化战场区域
     Chessboard.init();
 }
コード例 #38
0
        public static Vector3 Surface(ref UMT.MersenneTwister _rand, MTRandom.Normalization n, float t)
        {
            Vector3 pos = new Vector3();
            switch (n) {
            case MTRandom.Normalization.STDNORMAL:
                pos = GetPointOnCubeSurface(
                    (float) NormalDistribution.Normalize(_rand.NextSingle(true), t),
                    (float) NormalDistribution.Normalize(_rand.NextSingle(true), t),
                    _rand.Next(5));
            break;
            case MTRandom.Normalization.POWERLAW:
                pos = GetPointOnCubeSurface(
                    (float) PowerLaw.Normalize(_rand.NextSingle(true), t, 0, 1),
                    (float) PowerLaw.Normalize(_rand.NextSingle(true), t, 0, 1),
                    _rand.Next(5));
            break;
            default:
                pos = GetPointOnCubeSurface(_rand.NextSingle(true),_rand.NextSingle(true),_rand.Next(6));
            break;
            }

            // Move to -1, 1 space as for CIRCLE and SPHERE
            return new Vector3((2*pos.x)-1, (2*pos.y)-1, (2*pos.z)-1);
        }
コード例 #39
0
ファイル: PoissonRandom.cs プロジェクト: umebayashi/CLR
 public PoissonRandom(int[] init_key, double lambda)
 {
     this.random = new MTRandom(init_key);
     this.lambda = lambda;
 }
コード例 #40
0
ファイル: DungeonFloorSection.cs プロジェクト: tkiapril/aura
		/// <summary>
		/// Section of teh floor, contain Puzzles.
		/// </summary>
		/// <param name="startRoom">Start room of this section.</param>
		/// <param name="path">Critical path for this section.</param>
		/// <param name="haveBossRoom">Should we place a boss door in this section.</param>
		/// <param name="rng">Randrom generator for this dungeon.</param>
		public DungeonFloorSection(RoomTrait startRoom, List<MazeMove> path, bool haveBossRoom, MTRandom rng)
		{
			_lockColorProvider = new LockColorProvider();
			_lockedDoorCandidates = new LinkedList<LockedDoorCandidateNode>();
			this.Places = new List<PlaceNode>();
			this.Puzzles = new List<Puzzle>();

			_placeBossDoor = haveBossRoom;
			_rng = rng;

			this.InitLists(startRoom, path);
		}
コード例 #41
0
ファイル: PoissonRandom.cs プロジェクト: umebayashi/CLR
 public PoissonRandom(double lambda)
 {
     this.random = new MTRandom();
     this.lambda = lambda;
 }
コード例 #42
0
ファイル: MazeGenerator.cs プロジェクト: tkiapril/aura
		private int GenerateSubPathRandomDir(MTRandom rnd, int[] directions)
		{
			for (int i = 0; i < 4; i++)
			{
				if (directions[i] == 0)
				{
					while (true)
					{
						int random_dir = (int)(rnd.GetUInt32() & 3);
						if (directions[random_dir] == 0)
						{
							directions[random_dir] = 1;
							return random_dir;
						}
					}
				}
			}

			return -1;
		}
コード例 #43
0
ファイル: MazeGenerator.cs プロジェクト: tkiapril/aura
		private bool GenerateCriticalPathRecursive(int critPathPos, int critPathMin, int critPathMax, int direction, MTRandom rnd)
		{
			var directions = new int[4];
			_critPathMaxResult += 1;

			if (_critPathMaxResult <= 10 * critPathMax)
			{
				if (critPathMin <= critPathPos && critPathPos <= critPathMax && this.IsRoomInDirectionFree(_currentPos, StartDirection))
				{
					this.StartPos = _currentPos;

					foreach (var move in this.CriticalPath)
					{
						int temp = move.PosFrom.X;
						move.PosFrom.X = move.PosTo.X;
						move.PosTo.X = temp;

						temp = move.PosFrom.Y;
						move.PosFrom.Y = move.PosTo.Y;
						move.PosTo.Y = temp;

						move.Direction = Direction.GetOppositeDirection(move.Direction);
					}

					this.CriticalPath.Reverse();

					return true;
				}
				else
				{
					critPathPos += 1;
					var count = 0;

					if (critPathPos <= critPathMax)
					{
						if (direction != -1)
							direction = Direction.GetOppositeDirection(direction);

						for (int i = 0; i < 4; i++)
						{
							if (i == direction)
								directions[i] = 0;
							else
							{
								var next_pos = _currentPos.GetBiasedPosition(i);
								directions[i] = Sub(next_pos);
								count += directions[i];
							}
						}

						while (count > 0)
						{
							var rndNum = rnd.GetUInt32() % count + 1;
							int cnt2 = 0;

							var iDir = 0;
							while (iDir < 4)
							{
								cnt2 += directions[iDir];
								if (cnt2 >= rndNum)
									break;

								iDir++;
							}

							count -= directions[iDir];
							directions[iDir] = 0;

							if (this.MakeMove(iDir))
							{
								if (this.GenerateCriticalPathRecursive(critPathPos, critPathMin, critPathMax, iDir, rnd))
									return true;

								this.UndoMove();
							}
						}
					}
				}
			}

			return false;
		}
コード例 #44
0
ファイル: MazeGenerator.cs プロジェクト: tkiapril/aura
		public bool GenerateSubPath(MTRandom rnd, int coverageFactor, int branchProbability)
		{
			if (!this.isCriticalPathGenerated)
				return false;

			if (this.isSubPathGenerated)
				return true;

			if (coverageFactor > 100)
				coverageFactor = 100;

			if (branchProbability > 100)
				branchProbability = 100;

			var freeRooms = 0;
			for (int y = 0; y < this.Height; ++y)
			{
				for (var x = 0; x < this.Width; ++x)
				{
					if (!this.Rooms[x][y].Occupied)
						freeRooms += 1;
				}
			}

			var coverage = (int)(freeRooms * coverageFactor / 100);
			var toVector = new List<Position>();

			if (this.CriticalPath.Count > 0)
			{
				foreach (var move in this.CriticalPath)
					toVector.Add(move.PosTo);

				toVector.RemoveAt(toVector.Count - 1);
			}

			toVector = this.GenerateSubPathSub1(toVector);

			if (coverage <= 0)
				return true;

			var tempVector = new List<Position>();
			for (int i = 0; i < coverage; ++i)
			{
				var vect = toVector;
				var flag = false;

				if (tempVector.Count == 0)
				{
					if (toVector.Count == 0)
						break;

					flag = true;
				}
				else
				{
					if (toVector.Count == 0)
					{
						flag = false;
						vect = tempVector;
					}
					else
					{
						var rndNum = rnd.GetUInt32() % 100;
						flag = branchProbability >= rndNum;
						if (!flag)
							vect = tempVector;
					}
				}

				int rndIndex = (int)(rnd.GetUInt32() % (uint)vect.Count());
				var pos = vect[rndIndex];
				var room = this.GetRoom(pos);
				var directions = new int[] { 0, 0, 0, 0 };
				var rndDirection = -1;
				var direction = 0;

				while (true)
				{
					rndDirection = this.GenerateSubPathRandomDir(rnd, directions);
					if (room.GetPassageType(rndDirection) == 0)
					{
						if (this.IsRoomInDirectionFree(pos, rndDirection))
							break;
					}

					direction += 1;

					if (direction >= 4)
						break;
				}

				if (direction >= 4)
				{
					tempVector = this.GenerateSubPathSub3(tempVector, toVector);
					toVector = this.GenerateSubPathSub1(toVector);
					continue;
				}

				var biasedPos = pos.GetBiasedPosition(rndDirection);
				var room2 = this.GetRoom(biasedPos);

				room.Directions[rndDirection] = 2;
				room2.Directions[Direction.GetOppositeDirection(rndDirection)] = 1;

				_counter += 1;

				room2.VisitedCount = _counter;
				tempVector.Add(biasedPos);

				if (!flag)
				{
					tempVector.RemoveAt(rndIndex);
					toVector.Add(pos);
				}

				tempVector = this.GenerateSubPathSub3(tempVector, toVector);
				toVector = this.GenerateSubPathSub1(toVector);
			}

			this.isSubPathGenerated = true;

			return true;
		}
コード例 #45
0
ファイル: NpcScript.cs プロジェクト: aura-project/aura
		/// <summary>
		/// Opens guild robe creation interface.
		/// </summary>
		public void OpenGuildRobeCreation()
		{
			var entityId = this.Player.EntityId;
			var guildName = "?";
			var color = 0x000000u;

			var guild = this.Player.Guild;
			if (guild != null)
				guildName = guild.Name;

			var rnd = new MTRandom(ErinnTime.Now.DateTimeStamp);
			color = AuraData.ColorMapDb.GetRandom(1, rnd);

			this.Player.Vars.Temp["GuildRobeColor"] = color;

			Send.GuildOpenGuildCreation(this.Player, entityId, guildName, color);
		}