Esempio n. 1
0
            internal static (Dto, Dto) CreatePair(PseudoRandom pr, IEnumerable <Pair> equals)
            {
                var equal     = equals.First();
                var equalTail = equals.Skip(1);
                var deeper    = equalTail.Any() ?
                                CreatePair(pr, equalTail).ToTuple() :
                                null;

                var dto = Randomise(pr);

                (Dto, Dto)pair;
                switch (equal)
                {
                case Pair.Equal:
                    pair = (dto, dto.CopyShallow());
                    break;

                case Pair.Differs:
                    pair = (dto, dto.CopyShallow().With(d => d.MyProperty += 1));
                    break;

                default:
                    throw new ArgumentException($"Parameter {nameof(equal)} is not a proper enum.");
                }
                pair.Item1.Deeper = deeper?.Item1;
                pair.Item2.Deeper = deeper?.Item2;

                return(pair);
            }
Esempio n. 2
0
    void    Start()
    {
        this.step.set_next(STEP.GAME);

        this.controlable = new bool[4];

        for (int i = 0; i < 4; i++)
        {
            this.controlable[i] = true;
        }

        //

        this.debug_flag.play_bgm = false;

        dbwin.root();

        if (dbwin.root().getWindow("game") == null)
        {
            this.create_debug_window();
        }
        if (dbwin.root().getWindow("player") == null)
        {
            this.create_debug_window_player();
        }
        #if false
        PseudoRandom.Plant plant = PseudoRandom.get().createPlant("test0");
        plant = PseudoRandom.get().createPlant("test1");

        for (int i = 0; i < 16; i++)
        {
            Debug.Log(plant.getRandom().ToString());
        }
        #endif
    }
Esempio n. 3
0
        public void OnHappen(MsgParam msg, WarServerNpcMgr npcMgr)
        {
            //TODO : do something
            WarAnimParam warParam = msg as WarAnimParam;

            if (warParam != null && warParam.described != null)
            {
                //杀死人,described只有一个元素
                SelfDescribed described = warParam.described;
                if (described.srcEnd != null)
                {
                    ///
                    /// 杀死别人,自己身上的Buff和Trigger消失
                    ///
                    int casterId = described.srcEnd.param1;
                    //int sufferId = described.srcEnd.param2;
                    if (casterId == HangUpNpcId)
                    {
                        ///
                        /// 概率上的检测
                        ///

                        bool happed = PseudoRandom.getInstance().happen(cfg.Prob);
                        if (happed)
                        {
                            OnEnd();
                        }
                    }
                }
            }
        }
Esempio n. 4
0
	public static string GetForestSpriteNameForTile(int x, int y, string[,] nsewMap, int[,] map, PseudoRandom prnd)
	{
		string spriteName = "";

		if (map [y, x] == 1) 
		{
			if (nsewMap [y, x].Contains("_")) 
			{
				string num = prnd.Next (1,2).ToString();
				spriteName = "Forest_TreeTopSide" + nsewMap [y, x] + "_" + num; 
			} 
			else 
			{
				string num = prnd.Next (1,4).ToString();
				spriteName = "Forest_TreeTop" + "_" + num; 
			}
		} 
		else 
		{
			if(y+1 < map.GetLength (0) && map [y+1, x] == 1)
			{
				string num = prnd.Next (1,6).ToString();
				spriteName = "Forest_TreeTrunk_" + num;
			}
			else
			{
				string num = prnd.Next (1,3).ToString();
				spriteName = "Forest_Floor_" + num;
			}
		}

		return spriteName; 
	}
        public unsafe void TestMinimumIntensityProjection()
        {
            const int pixels     = 512 * 512;
            const int subsamples = 11;

            var rng      = new PseudoRandom(0x2DB8498F);
            var slabData = new ushort[pixels * subsamples];

            for (var n = 0; n < slabData.Length; ++n)
            {
                slabData[n] = (ushort)rng.Next(ushort.MinValue, ushort.MaxValue);
            }

            var expectedResults = new ushort[pixels];

            for (var p = 0; p < pixels; ++p)
            {
                expectedResults[p] = Enumerable.Range(0, subsamples).Select(s => slabData[s * pixels + p]).Min();
            }

            var actualResults = new ushort[pixels];
            var projectedData = new byte[pixels * sizeof(ushort)];

            fixed(ushort *pSlabData = slabData)
            {
                SlabProjection.AggregateSlabMinimumIntensity((IntPtr)pSlabData, projectedData, subsamples, pixels, 2, false);
                Buffer.BlockCopy(projectedData, 0, actualResults, 0, projectedData.Length);
            }

            Assert.AreEqual(expectedResults, actualResults);
        }
Esempio n. 6
0
        public void ReachAllInnerClasses()
        {
            //  #   Arrange.
            var     pr  = new PseudoRandom(nameof(ReachAllInnerClasses));
            var     obj = new MyPublicClass();
            dynamic sut = new ReachIn(obj);
            int     res;
            int     val;

            //  #   Act and Assert.
            val = pr.Int();

            //  We don't support finding privates in inherited classes
            //  so here we look for a field overloaded in the child class
            //  just as a sanity check.
            sut._myInnerPrivateClass._myPrivateField = val;
            res = sut._myInnerPrivateClass._myPrivateField;
            res.Should().Be(val);

            //  Keep looking for a visible (e.g. internal) field that comes
            //  from the base class.
            sut._myInnerPrivateClass._myInternalField = val;
            res = sut._myInnerPrivateClass._myInternalField;
            res.Should().Be(val);
            sut._myInnerInternalClass._myInternalField = val;
            res = sut._myInnerInternalClass._myInternalField;
            res.Should().Be(val);
            sut._myInnerProtectedClass._myInternalField = val;
            res = sut._myInnerProtectedClass._myInternalField;
            res.Should().Be(val);
            sut._myInnerPublicClass._myInternalField = val;
            res = sut._myInnerPublicClass._myInternalField;
            res.Should().Be(val);
        }
Esempio n. 7
0
    public void BSP_initLevel()
    {
        LevelEndUI.SetActive(false);
        // destroy previous level if there is one, and make a new one.
        if (currentLevel != 0)
        {
            GameObject.Destroy(tilesHolderInstance);
            GameObject.Destroy(enemyHolderInstance);
            GameObject.Destroy(potionsHolderInstance);
            print(generateStats());
        }
        tilesHolderInstance = Instantiate(holderTemplate);
        tilesHolderInstance.transform.name = "Tiles Holder";

        enemyHolderInstance = Instantiate(holderTemplate);
        enemyHolderInstance.transform.name = "Enemy Holder";

        potionsHolderInstance = Instantiate(holderTemplate);
        potionsHolderInstance.transform.name = "Potions Holder";

        currentLevel++;
        updateSeed();

        rand = GetComponent <PseudoRandom>();
        rand.randomInit(rand.hasher, seed, 2);
        levelMap = new bool[width, height];
        levelMap = mapInit(levelMap);
        levelMap = partition(levelMap, 1, height - 2, 1, width - 2);
        setSpawnCounts();
        // once logic'd out, draw it as a Unity level, put the player in, and let's dance.
        GenerateUnityMap();
        placeStartAndExit();
    }
Esempio n. 8
0
        /// <summary>
        /// 检测是否符合逻辑
        /// </summary>
        /// <param name="sk">技能</param>
        /// <param name="cfg">条件配置技能</param>
        /// <param name="caster">施法者忽略</param>
        /// <param name="targets">目标者们忽略</param>
        public bool check(RtSkData sk, ConditionConfigure cfg, ServerNPC caster, IEnumerable <ServerNPC> targets)
        {
                        #if DEBUG
            Utils.Assert(sk == null, "Skill is null in TimeoutCondition.");
            Utils.Assert(cfg == null, "ConditionConfigure is null in TimeoutCondition.");
                        #endif

            bool Condi = false;

            ///
            /// 1. 判定是否符合关心的BeHead类型
            ///
            var self           = this.GetType();
            var classAttribute = (ConditionAttribute)Attribute.GetCustomAttribute(self, typeof(ConditionAttribute));
            if (cfg.ConditionType == classAttribute.Con)
            {
                RtFakeSkData fakeSk = sk as RtFakeSkData;
                if (fakeSk != null)
                {
                    float TimeOut = cfg.Param1 * Consts.OneThousand;
                    ///
                    ///2.判定是否超时
                    ///
                    Condi = fakeSk.aliveDur >= TimeOut;

                    ///3.判定概率
                    if (Condi)
                    {
                        Condi = PseudoRandom.getInstance().happen(cfg.Prop);
                    }
                }
            }

            return(Condi);
        }
Esempio n. 9
0
        public void generateEnemy(PseudoRandom tRand, int regionID, double x, double y, Action <List <Projectile> > OnFire, Action OnDamage, Action OnDeath)
        {
            double val = tRand.RandomDouble();

            if (val > 0.2)
            {
                return;
            }
            else if (val > 0.05)
            {
                enemyShips.Add(new ShipBase(enemyShipGfx, Behavior.ShootConstantly, regionID / 3 + 2, 40, x, y, LineArt.PlayerShootPoints1)
                {
                    OnWeaponFire = OnFire
                });
            }
            else if (val > 0.005)
            {
                enemyShips.Add(new ShipBase(enemy2ShipGfx, Behavior.SpinShoot, regionID / 3 + 4, 5, x, y, LineArt.EnemyShip2_ShootPoints.Select(p => new PointF(p.X * 2f, p.Y * 2f)).ToList())
                {
                    OnWeaponFire = OnFire
                });
            }
            else
            {
                enemyShips.Add(new ShipBase(new UnitGraphics(Pens.Fuchsia, LineArt.BossShip), Behavior.Boss, regionID / 3 + 150, 6, x, y, LineArt.BossBulletPoints)
                {
                    facing = Math.PI / 2, collider = new DCollider(LineArt.BossColliders), OnWeaponFire = OnFire
                });
            }
        }
Esempio n. 10
0
 public static PseudoRandom getInstance()
 {
     if (_pseudoRandom == null)
     {
         _pseudoRandom = new PseudoRandom();
     }
     return(_pseudoRandom);
 }
Esempio n. 11
0
	public GraphGenCA(Graph grph, PseudoRandom _pRnd, double _r)
	{
		minCoord = new int[2]{ 0, 0 };
		maxCoord = new int[2]{ 0, 0 };
		CreateTranslateCoord (grph);
		pRnd = _pRnd; 
		r = _r; 
	}
Esempio n. 12
0
        public static Color GetRandomBrightColor()
        {
            var r = (byte)PseudoRandom.Get(128, 256);
            var g = (byte)PseudoRandom.Get(128, 256);
            var b = (byte)PseudoRandom.Get(128, 256);

            return(new Color(r, g, b));
        }
Esempio n. 13
0
    //================================================================//
	// CreateNSEWMap
	//================================================================//
	// Creates a maze in the form of a 2D string array that is populated 
	// with directions e.g. "NSEW". If a direction is in the string then 
	// there is as wall on that side of the point. For example if the 
	// point (3,4) is "SE" then there is a wall on the south and east 
	// side of the point (3,4).
	//================================================================//
	public string[,] CreateNSEWMap(int width, int length, int divRate, int[] startPoint) {
        int maximumX = width;
        int maximumY = length;
        bool mirrorEdges = false; 
        PseudoRandom rnd = new PseudoRandom(seedX, seedY, seedZ); 

		string[,] cellMap = CreateMapShape(maximumX, maximumY, rnd);  
        int[,]    cellMapNo = new int[maximumY, maximumX];  


        List<Point> cellList = new List<Point>(); 
		int[] start = startPoint; 
        cellList.Add(new Point(start[0], start[1])); 

        cellMap[cellList[0].Y, cellList[0].X] += "X"; 
        cellMapNo[cellList[0].Y, cellList[0].X] = 0;  
        while(cellList.Count != 0) {
            int cellNo = cellList.Count-1;; 
            
            if(rnd.Next(0,99) < divRate) {
                cellNo = cellList.Count-1;
            }
            else {
                cellNo = rnd.Next(0, cellList.Count-1); 
            }

            Point cell = cellList[cellNo]; 

            List<int> list = CreateRandomOrderDirectionList(rnd);

            bool visitedAllNeighours = true; 
            for(int c = 0; c < 4; c++) {
                int dir = list[c]; 
                int newX = NewXFromDir(dir, cell.X, cell.Y,maximumX, cellMap, mirrorEdges); 
                int newY = NewYFromDir(dir, cell.Y, cell.X,maximumY, cellMap, mirrorEdges); 
                if(cellMap[newY,newX] == "NSEW") {
                    visitedAllNeighours = false;
                    char carve = CharToIntConversion(dir); 
                    
                    cellMap[cell.Y, cell.X] = cellMap[cell.Y, cell.X].Replace(carve, ' '); 
                    cellMap[newY,newX] = cellMap[newY,newX].Replace(GetOppositeDirection(carve), ' ');

                    cellMapNo[newY, newX] = cellMapNo[cell.Y, cell.X] + 1; 
                    cellList.Add(new Point(newX,newY)); 
                    break; 
                }
            } 

            if(visitedAllNeighours) {
                cellList.RemoveAt(cellNo); 
            }
        }

        cellMap = FindEndPoint(cellMapNo, cellMap, maximumX, maximumY); 

        return cellMap; 
    }
Esempio n. 14
0
        public Wallet(WalletOptions options = null)
        {
            options = options ?? new WalletOptions();

            this.version = options.Version ?? Wallet.DefaultVersion;

            switch (this.version)
            {
            case 2:
                this.scryptParams      = new ScryptParams();
                this.scryptParams.Salt = this.scryptParams.Salt ?? PseudoRandom.RandomBytesAsHexString(this.scryptParams.SaltLength);
                break;

            default:
                break;
            }

            string passwordKey = default;

            if (options.PasswordKeys != null && options.PasswordKeys.ContainsKey(this.version))
            {
                passwordKey = options.PasswordKeys[this.version];
            }
            else
            {
                passwordKey = Wallet.ComputePasswordKey(new WalletOptions
                {
                    Version  = this.version,
                    Password = options.Password,
                    Scrypt   = this.scryptParams
                });
            }

            var account = new Account(options.SeedHex);

            var ivHex        = options.Iv ?? PseudoRandom.RandomBytesAsHexString(16);
            var masterKeyHex = string.IsNullOrWhiteSpace(options.MasterKey)
                ? PseudoRandom.RandomBytesAsHexString(16)
                : options.MasterKey;

            this.Options     = options;
            this.account     = account;
            this.ivHex       = ivHex;
            this.Address     = this.account.Address;
            this.programHash = this.account.ProgramHash;

            this.masterKey     = Aes.Encrypt(masterKeyHex, passwordKey, ivHex.FromHexString());
            this.seedEncrypted = Aes.Encrypt(options.SeedHex, masterKeyHex, ivHex.FromHexString());

            this.Options.Iv          = null;
            this.Options.SeedHex     = null;
            this.Options.Password    = null;
            this.Options.MasterKey   = null;
            this.Options.PasswordKey = null;
            this.Options.PasswordKeys.Clear();
        }
Esempio n. 15
0
        public Dmg toTargetDmg(NPCData self, NPCData target, EffectConfigData cfg)
        {
            ///-------- 物理伤害强度------
            ///先计算自己的物理伤害,
            float bphyselfhit = Physical_Hit(self, cfg);

            ///-------- 魔法伤害强度 -------
            /// 先计算自己的魔法伤害,
            float bMagselfhit = Magical_Hit(self, cfg);

            ///-------- NPC的总攻击强度,是cfg.EffectClass 类型-------
            float hit = bphyselfhit + bMagselfhit;

            //---------- 开始计算伤害 ---------
            float dmg = 0f;

            switch (cfg.EffectClass)
            {
            case SkillTypeClass.Holly:
                //神圣伤害不减少伤害
                dmg = hit;
                break;

            case SkillTypeClass.Magical:
                float magenemyavoid = Magical_Avoid(target, self);
                dmg = hit * (1.0f - magenemyavoid);
                break;

            case SkillTypeClass.Physical:
                float avdenemyratio = Physical_Avoid(target, self);
                dmg = hit * (1.0f - avdenemyratio);
                break;
            }

            /// --------- 暴击伤害 ----------
            ///
            float critialRatio = CriticalRatio(self, target, cfg);
            bool  isCri        = PseudoRandom.getInstance().happen(critialRatio);

            if (isCri)
            {
                float addtion = AdditionRatio(self, cfg);
                dmg = dmg * addtion;
            }

            Dmg final = new Dmg()
            {
                dmgValue   = dmg,
                dmgType    = cfg.EffectClass,
                isCritical = isCri,
                hitCls     = HurtHitClass.None,
            };

            return(final);
        }
Esempio n. 16
0
 public Chunk(int gridSize, float blockSize, Color color)
     : base(
         new Rectangle(
             new Vector2D(blockSize * (int)(gridSize / 2.0f), blockSize * (int)(gridSize / 2.0f)),
             new Size(blockSize)), color)
 {
     this.gridSize  = gridSize;
     this.blockSize = blockSize;
     RenderLayer    = 2;
     random         = new PseudoRandom();
 }
 Vector Unit(Vector vector)
 {
     if (vector.Magnitude() == 0)
     {
         return(PseudoRandom.Vector(1).Unit());
     }
     else
     {
         return(vector.Unit());
     }
 }
Esempio n. 18
0
        /// <summary>
        /// 检测是否符合逻辑
        /// </summary>
        /// <param name="sk">技能忽略</param>
        /// <param name="cfg">条件配置技能忽略</param>
        /// <param name="caster">施法者忽略</param>
        /// <param name="targets">目标者们忽略</param>
        public bool check(RtSkData sk, ConditionConfigure cfg, ServerNPC caster, IEnumerable <ServerNPC> targets)
        {
                        #if DEBUG
            Utils.Assert(cfg == null, "ConditionConfigure is null in PropCondition.");
                        #endif

            ///1.判定概率
            bool Condi = PseudoRandom.getInstance().happen(cfg.Prop);

            return(Condi);
        }
Esempio n. 19
0
        public void RandomFloatSanityTest()
        {
            var random = new PseudoRandom();
            const int Max = 10;
            var wasChosen = new bool[Max];
            const int Trials = Max * 1000;
            for (int i = 0; i < Trials; i++)
                wasChosen[(int)random.Get(0.0f, Max)] = true;

            for (int i = 0; i < Max; i++)
                Assert.IsTrue(wasChosen[i]);
        }
Esempio n. 20
0
	public static PseudoRandom	get()
	{
		if(PseudoRandom.instance == null) {

			GameObject	go = new GameObject("PseudoRandom");

			PseudoRandom.instance = go.AddComponent<PseudoRandom>();
			PseudoRandom.instance.create();
		}

		return(PseudoRandom.instance);
	}
Esempio n. 21
0
    public static PseudoRandom      get()
    {
        if (PseudoRandom.instance == null)
        {
            GameObject go = new GameObject("PseudoRandom");

            PseudoRandom.instance = go.AddComponent <PseudoRandom>();
            PseudoRandom.instance.create();
        }

        return(PseudoRandom.instance);
    }
Esempio n. 22
0
    // --- create salt ----
    private byte[] generateSalt()
    {
        PseudoRandom mRandom = PseudoRandom.getInstance();

        byte[] content = mRandom.generateRandom(SALT_LENGTH);
        // Create the file and write to it.
        // DANGER: System.IO.File.Create will overwrite the file if it already exists.
        using (FileStream fs = File.Create(saltPath)) {
            fs.Write(content, 0, content.Length);
        }
        return(content);
    }
Esempio n. 23
0
        /// 治疗值 = (p(1)*物理攻击系数+p(2)*法术攻击系数) /1000 + p(3) +p(4) * TargetAttr(MaxHP) / 1000
        ///
        /// 疗效 = TargetAttr(BeHeal)
        ///	治疗值 = 治疗值 * (1+疗效) * (1+p(5) / 1000)
        ///
        ///	是否可暴击按照p(6)处理
        ///	技能暴击率 = 暴击率 + p(7) / 1000
        ///	技能治疗暴击提升比=治疗暴击提升比+P(8) / 1000
        ///
        ///	if 暴击 then
        ///		真实治疗值 = 治疗值 * 技能治疗暴击提升比
        ///		end if
        public Treat toTargetTreat(NPCData self, NPCData target, EffectConfigData cfg)
        {
            ///-------- 物理伤害强度------
            ///先计算自己的物理伤害,
            float bphyselfhit = Physical_Hit(self, cfg);

            ///-------- 魔法伤害强度 -------
            /// 先计算自己的魔法伤害,
            float bMagselfhit = Magical_Hit(self, cfg);

            ///-------- NPC的总攻击强度,是cfg.EffectClass 类型-------
            float hit = bphyselfhit + bMagselfhit + cfg.Param3 + cfg.Param4 * self.rtData.totalHp * Consts.OneThousand;

            ///
            /// ------------ 分为不可暴击 和 不计算疗效 ------------
            ///
            TreatClass treatCls = (TreatClass)Enum.ToObject(typeof(TreatClass), cfg.Param6);

            bool forbid_critical = treatCls == TreatClass.Forbid_Critical;
            bool forbid_beheal   = treatCls == TreatClass.Forbid_BeHeal;

            /// 治疗值
            float treat = hit * (1 + cfg.Param7 * Consts.OneThousand);

            if (!forbid_beheal)
            {
                treat = treat * (1 + self.rtData.BeHeal);
            }

            /// --------- 暴击伤害 ----------
            ///
            bool isCri = false;

            if (!forbid_critical)
            {
                float critialRatio = CriticalRatio(self, target, cfg);
                isCri = PseudoRandom.getInstance().happen(critialRatio);
                if (isCri)
                {
                    float addtion = AdditionRatio(self, cfg);
                    treat = treat * addtion;
                }
            }

            Treat val = new Treat()
            {
                treatValue = (int)treat,
                treatType  = cfg.EffectClass,
                isCritical = isCri,
            };

            return(val);
        }
Esempio n. 24
0
        /// <summary>
        /// Generates nodes and edges endlessly for demonstration.
        /// </summary>
        public void StartGeneration()
        {
            lock (_nodeLock) {
                Color colour = Color.FromArgb(120, Color.White);

                // Add basis nodes.
                for (int i = 0; i < 100; i++)
                {
                    Add(new Node(PseudoRandom.UInt64().ToString(), colour));
                }

                // Connect some basis nodes.
                for (int i = 0; i < 80; i++)
                {
                    Node a, b;
                    do
                    {
                        a = _nodes[PseudoRandom.Int32(_nodes.Count - 1)];
                        b = _nodes[PseudoRandom.Int32(_nodes.Count - 1)];
                    } while (a == b || a.IsConnectedTo(b));
                    Connect(a, b);
                }

                // Add group nodes.
                for (int i = 0; i < 200; i++)
                {
                    Node node = new Node(PseudoRandom.UInt64().ToString(), colour);
                    Connect(node, _nodes[PseudoRandom.Int32(10)]);
                    Add(node);
                }

                // Add outlier nodes.
                for (int i = 0; i < 200; i++)
                {
                    Node node = new Node(PseudoRandom.UInt64().ToString(), colour);
                    Connect(node, _nodes[PseudoRandom.Int32(_nodes.Count - 1)]);
                    Add(node);
                }

                // Connect more nodes.
                for (int i = 0; i < 50; i++)
                {
                    Node a, b;
                    do
                    {
                        a = _nodes[PseudoRandom.Int32(_nodes.Count - 1)];
                        b = _nodes[PseudoRandom.Int32(_nodes.Count - 1)];
                    } while (a == b || a.IsConnectedTo(b));
                    Connect(a, b);
                }
            }
        }
Esempio n. 25
0
        public void PseudoRandom_DifferentSeed_ReturnDifferentResult()
        {
            //  #   Arrange.
            var sut1 = new PseudoRandom("Seed1");
            var sut2 = new PseudoRandom("Seed2");

            //  #   Act.
            var res1 = sut1.PositiveInt();
            var res2 = sut2.PositiveInt();

            //  #   Assert.
            Assert.AreNotEqual(res1, res2);
        }
Esempio n. 26
0
    public static void InitializeHashGrid(int seed)
    {
        _hashGrid = new PseudoRandom[HashGridSize * HashGridSize];
        var currentState = Random.state;

        Random.InitState(seed);
        for (var i = 0; i < _hashGrid.Length; i++)
        {
            _hashGrid[i] = PseudoRandom.Create();
        }

        Random.state = currentState;
    }
Esempio n. 27
0
    public int[,] Generate(Vector2 mapSize, Vector2 startCell, int seed)
    {
        this.mapSize = mapSize;
        this.startCell = startCell;

        array = new int[(int)mapSize.x, (int)mapSize.y];

        pseudoRand = new PseudoRandom(seed);

        setCell(startCell);

        return array;
    }
Esempio n. 28
0
        public GameScreen()
        {
            currentLevelIndex = -1;
            randomizer        = new PseudoRandom();
            SetViewportBackground("GameBackground");
            var font = ContentLoader.Load <Font>("Tahoma30");

            currentLevelFontText = new FontText(font, "", Rectangle.FromCenter(new Vector2D(0.5f, DrawArea.Top + 0.079f), new Size(0.6f, 0.3f)));
            nextLevel            = new NextLevelScreen();
            CreateImageContainersForRiddle();
            CreateDisplayCharacterButtons();
            CreateLevels();
        }
Esempio n. 29
0
 public PseudoRandom this[Player target]
 {
     get
     {
         PseudoRandom random = null;
         map.TryGetValue(target, out random);
         if (random == null)
         {
             random = new PseudoRandom();
             map.Add(target, random);
         }
         return(random);
     }
 }
Esempio n. 30
0
        public void PseudoRandom_SameSeed_ReturnSameResult()
        {
            //  #   Arrange.
            const string Seed = "MySeed";
            var          sut1 = new PseudoRandom(Seed);
            var          sut2 = new PseudoRandom(Seed);

            //  #   Act.
            var res1 = new[] { sut1.PositiveInt(), sut1.PositiveInt(), sut1.PositiveInt() };
            var res2 = new[] { sut2.PositiveInt(), sut2.PositiveInt(), sut2.PositiveInt() };

            //  #   Assert.
            CollectionAssert.AreEqual(res1, res2);
        }
Esempio n. 31
0
        public void PseudoRandom_HashCodeFunc_CustomMethod_UseIt()
        {
            //  #   Arrange.
            // Create a hashing function that always returns the same hash code.
            var hashingFunction = new Func <string, int>(s => 0);

            //  #   Act.
            var res1 = new PseudoRandom(hashingFunction, "a seed").PositiveInt();
            var res2 = new PseudoRandom(hashingFunction, "another seed").PositiveInt();

            //  #   Assert.
            Assert.AreEqual(res1, res2);
            Assert.AreEqual(1559595546, res1);
        }
Esempio n. 32
0
 /// <summary>
 /// Intializes new instance to default values
 /// </summary>
 /// <param name="position"></param>
 public ParticleEmitter(Vector2 position)
 {
     particles  = new List <Particle>();
     generators = new List <PropertyGenerator>();
     modifiers  = new List <ParticleModifier>();
     textures   = new List <Texture2D>();
     random     = new PseudoRandom();
     // by default, emitter is relative to the effect position
     Position = position;
     Quantity = 1;
     fraction = 0.0f;
     Flags    = EmitterModes.PositionRelative | EmitterModes.RotationRelative;
     name     = "AbstractEmitter";
 }
Esempio n. 33
0
        public void ThrowExceptionIfStaticFieldOrPropetyNotFound()
        {
            //  #   Arrange.
            var     pr  = new PseudoRandom(nameof(ThrowExceptionIfStaticFieldOrPropetyNotFound));
            dynamic sut = new ReachIn(typeof(MyBaseClass));

            //  #   Act and Assert.
            //  A setter does not exist.
            Assert.Throws <Exception>(
                () => { sut.ThisPropertyOrFieldIsNotFound = pr.Int(); });

            //  A getter does not exist.
            Assert.Throws <Exception>(
                () => { var res = sut.ThisPropertyOrFieldIsNotFound; });
        }
Esempio n. 34
0
    public void AddBuildings(Vector3 position, Cell cell, PseudoRandom hash)
    {
        var prefab = PickHousePrefab(cell.UrbanizationLevel, hash.existingChance, hash.housePick);

        if (!prefab)
        {
            return;
        }
        var house = Instantiate(prefab);

        position.y += house.transform.localScale.y * 0.5f;
        house.transform.localPosition = Metrics.Perturb(position);
        house.transform.localRotation = Quaternion.Euler(0f, 360f * hash.rotation, 0f);
        house.transform.SetParent(_objectContainer, false);
    }
Esempio n. 35
0
        public void RandomIntSanityTest()
        {
            const int Max       = 10;
            var       wasChosen = new bool[Max];
            const int Trials    = Max * 1000;

            for (int i = 0; i < Trials; i++)
            {
                wasChosen[PseudoRandom.Get(0, Max)] = true;
            }

            for (int i = 0; i < Max; i++)
            {
                Assert.IsTrue(wasChosen[i]);
            }
        }
Esempio n. 36
0
        public void ThrowExceptionIfMethodNotFound()
        {
            //  #   Arrange.
            var     pr  = new PseudoRandom(nameof(ThrowExceptionIfMethodNotFound));
            var     obj = new MyBaseClass();
            dynamic sut = new ReachIn(obj);

            //  #   Act and Assert.
            //  The method does not exist.
            Assert.Throws <Exception>(
                () => { sut.ThisMethodIsNotFound(pr.Int()); });

            //  There is a property by the same name.
            Assert.Throws <RuntimeBinderException>(
                () => { sut.MyPrivateProperty(pr.Int()); });
        }
Esempio n. 37
0
		public List<Quadrant> QuarterQuadrant(PseudoRandom rnd, double roomChance)
        {   
            List<Quadrant> newQuadrants = new List<Quadrant>(); 

            int newHeight = height/2; 
            int newWidth  = width/2; 
            
            if( newHeight != 0 && newWidth != 0 && (newHeight*newWidth/4) >= 1)
            {
                newQuadrants.Add(new Quadrant(X, Y, newHeight, newWidth, depth+1, SelectRoom(rnd, roomChance) ) ); // Top Left
                newQuadrants.Add(new Quadrant(X+newWidth, Y, newHeight, (width-newWidth), depth+1, SelectRoom(rnd, roomChance) ) ); // Top Right 
                
                newQuadrants.Add(new Quadrant(X, Y+newHeight, (height-newHeight), newWidth, depth+1, SelectRoom(rnd, roomChance) ) ); // Bottom Left
                newQuadrants.Add(new Quadrant(X+newWidth, Y+newHeight, (height-newHeight), (width-newWidth), depth+1, SelectRoom(rnd, roomChance) ) );  // Bottom Right
            }

            return newQuadrants; 
        }
Esempio n. 38
0
	public static int[,] CreateAgentBasedMap(int _mapSize, int seedX, int seedY, int seedZ)
	{
		int mapSize = _mapSize;  
        
		PseudoRandom rnd = new PseudoRandom(seedX, seedY, seedZ); 
        int[,] map = InitialiseMap(mapSize);

        int[] startPoint = ChooseRandomPoint( (int)Math.Round(mapSize/3f), (int)Math.Round(2f*mapSize/3f), rnd);
        AgentBased agent = new AgentBased(0.05, 0.05, startPoint, rnd.Next(0,4));

		while(agent.CanContinue(map, rnd) && (!CheckFilled(map, 0.5f)) )
        {
            map = agent.PlaceRoom(map, rnd);
            map = agent.MoveInDirection(map, rnd);
        }

        return map;
    }
Esempio n. 39
0
	public int[,] CreateCellularAutomataFromMap(int[,] startMap, PseudoRandom rnd)
	{
		int n = 4; //The number of iterations of the cellular automata generation, n.
		int M = 1; //Size/scale of the neighbourhood being used, M.
		int T = 5; //Rock threshold, T.

		int[,] map = startMap;

		for(int h = 0; h < n; h++)
		{
			map = ApplyCellularAutomata(map, M, T, true); 
		}

		for(int h = 0; h < 3; h++)
		{
			map = ApplyCellularAutomata(map, M, T, false); 
		}
		return map; 
	}
Esempio n. 40
0
	Enemy CreateEnemy(PseudoRandom rnd){//, Player target){

		int[] coords = envr.layout.FindRandomPoint (rnd); 

		// Standard Set enemy up code. 
		Enemy anEnemy = (Enemy) Instantiate (Resources.Load<Enemy> ("Prefabs/Enemy"), (Vector3) envr.grid.GetCoords(coords[0], coords[1]), Quaternion.identity);
		anEnemy.coords[0] = coords[0];
		anEnemy.coords[1] = coords[1];
		anEnemy.envr = envr; 

		List<int[]> waypoints = new List<int[]>();
		waypoints.Add (coords);
		waypoints.Add (envr.layout.FindRandomPoint (rnd));
		waypoints.Add (envr.layout.FindRandomPoint (rnd));
		AIBase patrolAI = new AIPatrol (anEnemy, waypoints);
		//AIBase newAI = new AIFollowAndAttack (currentEnemy, target); 
		AIBase newAI = new AIAndAttack(anEnemy, patrolAI); 
		//AIBase newAI = new AISearchArea (currentEnemy, target.coords); 
		//anEnemy.workingAI = newAI;
		return anEnemy;
	}
Esempio n. 41
0
	public void CreateEnemiesForTile()
	{
		if (envr.currentMapInfo.enemyList.Count > 0) {

			foreach (Enemy dude in envr.currentMapInfo.enemyList) 
			{
				if (!dude.IsDead ()) {
					dude.gameObject.SetActive (true);
				}
			}
			enemyList = envr.currentMapInfo.enemyList; 
			envr.currentMapInfo.enemyList = new List<Enemy> ();

		} else {
			PseudoRandom rnd = new PseudoRandom (envr.currentMapInfo.seedX + 1, envr.currentMapInfo.seedY + 1, envr.currentMapInfo.seedZ + 1);

			for (int i = 0; i < 10; i++) {
				enemyList.Add (CreateEnemy (rnd));
			}
		}
	}
Esempio n. 42
0
	public int[,] InitialiseMap(double r, int mapSize, PseudoRandom rnd)
    {
        int[,] map = new int[mapSize, mapSize];

        for(int y = 0; y < mapSize; y++)
        {
            for(int x = 0; x < mapSize; x++)
            {   
                double number = Math.Round(rnd.Next(), 3); 
                if(number < r)
                {
                    map[y,x] = stateRock;
                }
                else
                {
                    map[y,x] = stateEmpty;
                }
            }
        }   
    
        return map;
    }
Esempio n. 43
0
	int[,] PlaceRoom(int[,] map, PseudoRandom rnd)
    {
        if(rnd.Next(0,99) < roomChance*100)
        {
            bool canPlace = CanPlaceRoom(map, rnd);
            Console.Write("Place Room: " + canPlace + "\n");
            if(canPlace)
            {
                int[] firstStep  = MoveDirection(currentPosition[0], currentPosition[1], currentDirection);
                int[] roomCenter = MoveDirection(firstStep[0], firstStep[1], currentDirection);
                int[] newPosition = MoveDirection(roomCenter[0], roomCenter[1], currentDirection);
                
                for(int y = roomCenter[1]-1; y <= roomCenter[1]+1; y++)
                {
                    for(int x = roomCenter[0]-1; x <= roomCenter[0]+1; x++)
                    {
                        map = ChangeToRoom(x, y, map);
                    }
                }
                currentPosition[0] = newPosition[0];
                currentPosition[1] = newPosition[1];

                for(int i = 0; i < 4; i++)
                {
                    int[] newStart = MoveDirection(roomCenter[0], roomCenter[1], i);
                    positions.Add(newStart[0]);
                    positions.Add(newStart[1]);
                }

                roomChance = 0.05; 
            }
            else
            {
                roomChance += roomRate; 
            }
        }
        roomChance += roomRate; 
        return map; 
    }
Esempio n. 44
0
	public int[,] CreateCellularAutomata(int _mapSize, int seedX, int seedY, int seedZ)
	{
		int mapSize = _mapSize;  

		double r = 0.45; //Probability of square being rock in ititial state.
		int n = 4; //The number of iterations of the cellular automata generation, n.
		int M = 1; //Size/scale of the neighbourhood being used, M.
		int T = 5; //Rock threshold, T.

		PseudoRandom rnd = new PseudoRandom(seedX, seedY, seedZ); 
		int[,] map = InitialiseMap(r, mapSize, rnd);

		for(int h = 0; h < n; h++)
		{
			map = ApplyCellularAutomata(map, M, T, true); 
		}

		for(int h = 0; h < 3; h++)
		{
			map = ApplyCellularAutomata(map, M, T, false); 
		}
		return map; 
	}
Esempio n. 45
0
	public static int[,] CreateSpacialPartitionMap(int _mapSize, int _x, int _y, int _z)
	{
		int mapSize = _mapSize;  
        double splitChance = 1; 
        double roomChance = 0.375; 

		PseudoRandom rnd = new PseudoRandom(_x, _y, _z); 
        int[,] map = InitialiseMap(mapSize, rnd);
        List<Quadrant> final = SpacialPartition(mapSize, splitChance, roomChance, rnd);
        List<Quadrant> rooms = RemoveEmptyQuadrants(final);
        
        map = SetMapFromPartition(map, rooms);        

        for(int i = 1; i < rooms.Count; i++)
        {
            if(!rooms[i-1].NextToQuadrant(rooms[i]))
            {   
                int firstX = rooms[i-1].PickRandomX(rnd);
                int firstY = rooms[i-1].PickRandomY(rnd);

                int secondX = rooms[i].PickRandomX(rnd);
                int secondY = rooms[i].PickRandomY(rnd);
                map = ConnectPoints(map, firstX, firstY, secondX, secondY);
            }
        }

        return map;
    }
Esempio n. 46
0
	void ChangeDirection(PseudoRandom rnd)
    {
        if(rnd.Next(0,99) < directionChance*100)
        {
            Console.Write("Direction Change From: " + currentDirection + "\n");
            
            currentDirection = NewDirection(currentDirection, rnd);

            Console.Write("Direction Change To: " + currentDirection + "\n");
            directionChance = 0.05; 
        }
        directionChance += directionRate; 
    }
Esempio n. 47
0
	int[,] MoveInDirection(int[,] map, PseudoRandom rnd)
    {
        int[] moveTo = MoveDirection(currentPosition[0], currentPosition[1], currentDirection);
        
        if(IsValidRoute(moveTo, map) )
        {
            currentPosition = moveTo; 
            map = ChangeToRoom(currentPosition[0], currentPosition[1], map);
            ChangeDirection(rnd);
        }

        return map; 
    }
Esempio n. 48
0
	int NewDirection(int dir, PseudoRandom rnd)
    {
        int newDir = dir; 
        if(rnd.Next(0,2) == 0)
        {
            newDir = (dir + 1)%4;
        }
        else
        {
            newDir = (dir - 1)%4; 
        }

        if(newDir < 0)
        {
            newDir = 4 + newDir; 
        }
        return newDir; 
    }
Esempio n. 49
0
	bool CanContinue(int[,] map, PseudoRandom rnd)
    {
        bool returnable = false; 
        int[] newPoint = MoveDirection(currentPosition[0], currentPosition[1], currentDirection );
        if(IsValidRoute(newPoint, map))
        {
            returnable = true; 
        }
        else
        {
            int startDir = rnd.Next(0,4);
            for(int i = 0; i < 4; i++)
            {   
                newPoint = MoveDirection(currentPosition[0], currentPosition[1], (startDir+i)%4 );
               
                if(IsValidRoute(newPoint, map))
                {
                    returnable = true; 
                    Console.Write("CC Direction Change From: " + currentDirection + "\n");
                
                    currentDirection = NewDirection(currentDirection, rnd);
                    
                    Console.Write("CC Direction Change To: " + currentDirection + "\n");
                    directionChance = 0.05;  
                    break;
                }
            }
        }

        if(returnable == false && positions.Count > 0)
        {
            currentPosition[0] = positions[0];
            currentPosition[1] = positions[1];
            positions.RemoveAt(1);
            positions.RemoveAt(0);
            returnable = true; 
        }
        return returnable;
    }
Esempio n. 50
0
	//================================================================//
	// StartNewGame
	//================================================================//
	// Create a new game with a different seed and reset appropriate 
	// information. 
	//================================================================//
	public void StartNewGame()
	{
		startSize = 5; 
		currentSquareSize = 5;
		currentDiversion = 100;
		ChangeSeed ();

		currentScore = 0;
		scoreDisplay.color = Color.white;
		highScoreMessage.enabled = false;
		currentScore +=currentSquareSize*(currentSquareSize-1)*10;

		MazeGenerator maze = new MazeGenerator(seedX, seedY, seedZ);
		PseudoRandom rnd = new PseudoRandom(seedX, seedY, seedZ);
		currentStart = maze.CreateRandomPoint(rnd, currentSquareSize, currentSquareSize);
		CreateNewLevel (currentStart);

		int[] startPoint = FindStart (currentMap);

		if (currentPlayer == null) {
			currentPlayer = (Player) Instantiate (player, gridMaster.GetCoordVect2(startPoint[0], startPoint[1]), Quaternion.identity);
		}
		inGame = true;
		currentPlayer.SetGridMaster (gridMaster);
		currentPlayer.SetLayout (this);
		//print (startPoint[0] + " - "+ startPoint[1]);
		currentPlayer.transform.position = gridMaster.GetCoordVect2 (startPoint [0], startPoint [1]);
		currentPlayer.currentCoord = startPoint;
	}
Esempio n. 51
0
	static int[] ChooseRandomPoint(int lowerLimit, int upperLimit, PseudoRandom rnd)
    {
        int[] coords = new int[2];
        coords[0] = rnd.Next(lowerLimit, upperLimit);
        coords[1] = rnd.Next(lowerLimit, upperLimit);

        return coords;
    }
Esempio n. 52
0
		int SelectRoom(PseudoRandom rnd, double roomChance)
        {
            double room = Math.Round(rnd.Next(), 2);
            
            //Console.Write("Chance: " + roomChance + " - " + room + "\n");
            int num = 0;
            if(room < roomChance)
            {
                num = stateRoom; 
            }
            return num;
        }
Esempio n. 53
0
	//================================================================//
	// CreateNewLevel
	//================================================================//
	// Destroy all previous parts of the level, then load a level using 
	// MazeGenerator and the current level seed. 
	//================================================================//
	public void CreateNewLevel(int[] newStart)
	{
		while(levelParts.Count != 0) {
			Destroy(levelParts[0]);
			levelParts.RemoveAt (0);
		}

		MazeGenerator maze = new MazeGenerator(seedX, seedY, seedZ);
		PseudoRandom rnd = new PseudoRandom(seedX, seedY, seedZ);
		currentStart = newStart;
		currentMap = maze.CreateNSEWMap(currentSquareSize, currentSquareSize, currentDiversion, currentStart);
		currentFinish = FindEnd (currentMap); 
		mainCamera.GetComponent<CameraFollow> ().SetSpotlightSettings (currentSquareSize);

		MapToLevel (currentMap);
		CreateBoundries (currentMap);

		gridMaster = new GridMaster (0.5f, 0.5f, currentMap.GetLength(1), currentMap.GetLength(0), 1f, 1f);
		GameObject fin = (GameObject)Instantiate (finish, gridMaster.GetCoordVect2(currentFinish[0], currentFinish[1]), Quaternion.identity);
		levelParts.Add (fin);

		if (currentSquareSize > startSize) {
			currentScore +=currentSquareSize*(currentSquareSize-1)*10;
			currentPlayer.SetGridMaster (gridMaster);
			currentPlayer.SetLayout (this);
		}
		SaveCurrentGame ();
	}
Esempio n. 54
0
		public int PickRandomY(PseudoRandom rnd)
        {
            return rnd.Next(Y, Y+height);
        }
Esempio n. 55
0
		public int PickRandomX(PseudoRandom rnd)
        {
            return rnd.Next(X, X+width);
        }
Esempio n. 56
0
	//================================================================//
	// ContinueGame
	//================================================================//
	// Load in the game settings from a previous game, and create 
	// the level.  
	//================================================================//
	public void ContinueGame(Game game)
	{
		CreateLevelFromGame (game); 
		MazeGenerator maze = new MazeGenerator(seedX, seedY, seedZ);
		PseudoRandom rnd = new PseudoRandom(seedX, seedY, seedZ);
		CreateNewLevel (currentStart);

		int[] startPoint = currentStart;

		if (currentPlayer == null) {
			currentPlayer = (Player) Instantiate (player, gridMaster.GetCoordVect2(startPoint[0], startPoint[1]), Quaternion.identity);
		}
		inGame = true; 
		currentPlayer.SetGridMaster (gridMaster);
		currentPlayer.SetLayout (this);
		//print (startPoint[0] + " - "+ startPoint[1]);
		currentPlayer.transform.position = gridMaster.GetCoordVect2 (startPoint [0], startPoint [1]);
		currentPlayer.currentCoord = startPoint;
	}
Esempio n. 57
0
	static List<Quadrant> SpacialPartition(int mapSize, double splitChance, double roomChance, PseudoRandom rnd)
    {
        Quadrant first = new Quadrant(0,0, mapSize, mapSize, 0, 0);
        List<Quadrant> next = first.QuarterQuadrant(rnd, roomChance); 
        
        List<Quadrant> final = new List<Quadrant>();

        while(next.Count != 0)
        {
            int index = 0;

			double split = Math.Round(rnd.Next(), 2);
            if(split < splitChance)
            {
                List<Quadrant> subs = next[index].QuarterQuadrant(rnd, roomChance);
                if(subs.Count == 0) 
                {
                    final.Add(next[index]); 
                }
                else
                {
                    next.AddRange(subs);    
                }
            } 
            else
            {
                final.Add(next[index]); 
            }
            
            next.RemoveAt(index); 
        }

        return final; 
    }
Esempio n. 58
0
	static int[,] InitialiseMap(int mapSize, PseudoRandom rnd)
    {
        int[,] map = new int[mapSize, mapSize];

        for(int y = 0; y < mapSize; y++)
        {
            for(int x = 0; x < mapSize; x++)
            {   
				map[y,x] = stateEmpty;
            }
        }   
    
        return map;
    }
Esempio n. 59
0
	bool CanPlaceRoom(int[,] map, PseudoRandom rnd)
    {
        bool returnable = true; 
        int[] firstStep  = MoveDirection(currentPosition[0], currentPosition[1], currentDirection);
        int[] roomCenter = MoveDirection(firstStep[0], firstStep[1], currentDirection);

        for(int y = roomCenter[1]-1; y <= roomCenter[1]+1; y++)
        {
            for(int x = roomCenter[0]-1; x <= roomCenter[0]+1; x++)
            {
                if(x >= 0 && x < map.GetLength(1) && y >= 0 && y < map.GetLength(0))
                {
                    if(map[y, x] == stateRoom && y != currentPosition[1] && x != currentPosition[0])
                    {
                        returnable = false; 
                    }
                }
                else
                {
                    returnable = false; 
                }
            }
        }
        return returnable; 
    }
Esempio n. 60
0
	void CreateGraphCAMap()
	{
		Graph grph = Graph.CreateGraphMaxSize(1000, 40);
		DisplayGraph (grph);


		PseudoRandom rnd = new PseudoRandom(seedX, seedY, seedZ); 
		CellularAutomata ca = new CellularAutomata();
		GraphGenCA grCa = new GraphGenCA (grph, rnd, 0.385f);
		int[,] start = grCa.CreateInitalMapFromGraph (grph, 16, 4);
		map = ca.CreateBasicCellularAutomataFromMap (start, rnd);


		mainCam.transform.position = new Vector3 ((map.GetLength(1)+3)/2, (map.GetLength(0)+3)/2, -10 );
		mainCam.orthographicSize = 90f;
		CreateMap (map);
		toggle = true; 
	}