Example #1
0
 public static bool IsJumpableFrom(Game game, Coord src, Coord toJump)
 {
     Coord diff = new Coord() { Row = toJump.Row - src.Row, Col = toJump.Col - src.Col };
     Coord toLand = new Coord() { Row = src.Row + diff.Row * 2, Col = src.Col + diff.Col * 2 };
     // TODO add out of bounds checking
     return game.GetPieceAt(toLand) == BoardSpaceState.None && game.GetPieceAt(toJump) != BoardSpaceState.None;
 }
Example #2
0
        public Line(Coord ptA, Coord ptB)
        {
            pts = new List<Coord>();

            int x0 = ptA.X;
            int y0 = ptA.Y;
            int x1 = ptB.X;
            int y1 = ptB.Y;

            bool steep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);
            if (steep) { Utilities.Swap<int>(ref x0, ref y0); Utilities.Swap<int>(ref x1, ref y1); }
            if (x0 > x1) { Utilities.Swap<int>(ref x0, ref x1); Utilities.Swap<int>(ref y0, ref y1); }
            int dX = (x1 - x0), dY = Math.Abs(y1 - y0), err = (dX / 2), ystep = (y0 < y1 ? 1 : -1), y = y0;

            for (int x = x0; x <= x1; ++x)
            {
                pts.Add(steep ? new Coord(y, x) : new Coord(x, y));
                err = err - dY;
                if (err < 0) { y += ystep; err += dX; }
            }

            if (pts.Count > 0 && pts[0] != ptA)
            {
                pts.Reverse();
            }
        }
Example #3
0
        public static BoardSpace.ArrowDirection ArrowDirectionOfCoords(Coord from, Coord to)
        {
            Coord diff = to - from;

            if (diff.Row < 0 && diff.Col == 0)
            {
                return BoardSpace.ArrowDirection.NORTH;
            }
            if (diff.Row < 0 && diff.Col < 0)
            {
                return BoardSpace.ArrowDirection.NORTHWEST;
            }
            if (diff.Row == 0 && diff.Col < 0)
            {
                return BoardSpace.ArrowDirection.WEST;
            }
            if (diff.Row > 0 && diff.Col < 0)
            {
                return BoardSpace.ArrowDirection.SOUTHWEST;
            }
            if (diff.Row > 0 && diff.Col == 0)
            {
                return BoardSpace.ArrowDirection.SOUTH;
            }
            if (diff.Row > 0 && diff.Col > 0)
            {
                return BoardSpace.ArrowDirection.SOUTHEAST;
            }
            if (diff.Row == 0 && diff.Col > 0)
            {
                return BoardSpace.ArrowDirection.EAST;
            }

            return BoardSpace.ArrowDirection.NORTHEAST;
        }
Example #4
0
        static void Main(string[] args)
        {
            string delim = new string('-', 50);

            string st1 = "Niki";
            string st2 = "Niki";
            string st3 = st2;
            st3 = "Gosho";
            Console.WriteLine(Object.ReferenceEquals(st3, st2));  // returns false, because for strings assigning new value doesn`t change the value in heap, but creates  new instance, writes the new value there and changes the address of the string to point to the new address with the new value. st2 value is unchanged

            //st3 = Console.ReadLine();

            Console.WriteLine(st3.Equals(st2)); // if we entered "Niki" at the console this will return true, because Equals is overriden for string types to compare by value
            Console.WriteLine(Object.ReferenceEquals(st3, st2)); // this will return false because st3 has different address than st2, although its value is the same it was dynamically (at runtime) assigned, so it was stored in a new address in heap. If it was compile time aassigned, it was going to be at the same address as st2, so this would have returned true

            Console.WriteLine(delim);
            int i1 = 1;
            //int i2 = int.Parse(Console.ReadLine());
            int i2 = 1;
            Console.WriteLine(ReferenceEquals(i1, i2));
            Console.WriteLine(Equals(i1, i2));
            Console.WriteLine(i1 == i2);

            Console.WriteLine(delim);
            Coord c1 = new Coord(1, 2);
            Coord c2 = new Coord(1, 2);

            Console.WriteLine(ReferenceEquals(c1, c2)); // always gives false for value types
            Console.WriteLine(Equals(c1, c2)); // actually compares them
            //Console.WriteLine(c1 == c2); // must be overriden first
        }
Example #5
0
        public void Play(Player p, Coord start, Coord end)
        {
            if (CanSelectToPlay(p, start.x, start.y) && board.IsEmpty(end.x, end.y))
            {
                var distance = end - start;
                int travelLength = Math.Abs(distance.x) + Math.Abs(distance.y);

                //Move -> Remove original
                if (travelLength == 2)
                {
                    board[start.x, start.y] = null;
                }

                //Copy (or Move) -> Put token
                PutToken(p, end.x, end.y);
                var offsetCalc = new OffsetCalculator(end.x, end.y);
                for (int i = 0; i < 9; i++)
                {
                    offsetCalc.setDirection(i);
                    offsetCalc.MakeOffset(1);

                    if (board.CanOvertakeToken(p, offsetCalc.ResultX, offsetCalc.ResultY))
                    {
                        PutToken(p, offsetCalc.ResultX, offsetCalc.ResultY);
                    }
                }

                HandlePlayerChange();

                if (SnapshotContainer != null)
                {
                    SnapshotContainer.TakeSnapShot(new TwoPartTurn() { Start = start, End = end, PlayerThatPlayed = p, PlayerToPlay = CurrentPlayer, Board = board.Clone() });
                }
            }
        }
Example #6
0
 public void DeviceRect(Coord x0, Coord y0, Coord x1, Coord y1)
 {
     int x = (int) Math.Round(Math.Min((double) x0.Value, (double) x1.Value));
     int y = (int) Math.Round(Math.Min((double) x0.Value, (double) x1.Value));
     int w = (int) Math.Round(Math.Min((double) x0.Value, (double) x1.Value));
     int h = (int) Math.Round(Math.Min((double) x0.Value, (double) x1.Value));
 }
Example #7
0
 /// <summary>
 /// 拷贝源本到新元素
 /// </summary>
 /// <param name="desPos">目标坐标</param>
 public void CopyTo(Coord desPos)
 {
     if (SouVersion != null)
     {
         MotaWorld.GetInstance().MapManager.CopyNode(SouVersion, desPos);
     }
 }
Example #8
0
        public void TwoHopTrajectory()
        {
            this.walker = new Walker(new Board(5, 5));

            Coord from = new Coord(0, 3), to = new Coord(2, 1);
            this.AssertBestProbToArrive(from, to, 0.25f);
        }
	// Use this for initialization
	void Start () {

		supportive = GetComponent<AudioSource>();

		// This is some instantiation.
		// We want it so that if the player is within a + direction from the particle, they will get hurt.
		GameObject player = GameObject.FindGameObjectWithTag("Player");
		int playerX = (int)player.transform.position.x;
		int playerY = (int)player.transform.position.y;

		Coord myPlace = new Coord((int)this.transform.position.x, (int)this.transform.position.y);
		Coord playerCoord = new Coord(playerX, playerY);
		Coord n, w, s, e;
		n = playerCoord.nextCoord (Direction.North);
		w = playerCoord.nextCoord (Direction.West);
		s = playerCoord.nextCoord (Direction.South);
		e = playerCoord.nextCoord (Direction.East);

		if( myPlace.isEqual (playerCoord) ||
		    myPlace.isEqual (n) ||
		    myPlace.isEqual (w) ||
		    myPlace.isEqual (s) ||
		    myPlace.isEqual (e) ) {
			PlayerMovement hitPlayer = player.GetComponent<PlayerMovement>();
			supportive.PlayOneShot(haha,1f);
			hitPlayer.LoseHealth(750); }

		Destroy (this.gameObject, 3);

	}
Example #10
0
        private Question travelRange()
        {
            Coord start, destination;
            int distance;

            Question travel = new Question("Where do you go?:", new string[] { });

            foreach (KeyValuePair<string, Coord> pair in Reference.Directory.Instance.Catalog) {

                start = Reference.Directory.Instance.Catalog[this.alias];

                destination = new Coord(pair.Value.coordX, pair.Value.coordY);

                distance = Utility.MathHelper.distance(start, destination);

                if (distance <= 10 && distance != 0) {

                    travel.addAnswer(pair.Key);

                }

            }

            travel.addAnswer("Exit");

            return travel;
        }
Example #11
0
        public void ImpossibleTrajectory()
        {
            this.walker = new Walker(new Board(5, 9));

            Coord from = new Coord(0, 7), to = new Coord(4, 1);
            this.AssertBestProbToArrive(from, to, 0);
        }
Example #12
0
        public User OnUserJoinedMessage(EMMServerMessage message)
        {
            // make sure user exists in database
            using (EMMDataContext db = Manager.GetContext)
            {
                User user = db.Users.SingleOrDefault(i => i.Username == message.Data["username"]);
                if (user == null)
                {
                    user = CreateDefaultUser(message.Data["username"]);
                }

                // parse their current location from the join message
                Coord position = new Coord(message);
                user.LocX = position.X;
                user.LocY = position.Y;
                user.LocZ = position.Z;
                user.LastSeen = DateTime.Now;
                db.SubmitChanges();

                // save the current location to the tracking table
                TrackUserPosition(user);

                return user;
            }
        }
 public Tree(Coord root)
 {
     this.rootNode = new TreeNode();
     this.rootNode.SetRoot(root,new List<Coord>());
     this.nodes = new List<TreeNode>();
     this.nodes.Add(rootNode);
 }
    public int Distance(Coord start, Coord end)
    {
        //		Debug.Log ("Chain Start: " + start.ToString());
        //		Debug.Log ("Chain End: " + end.ToString());

        return GetChain(start,end).Count;
    }
Example #15
0
 public Router_Flit(Coord myCoord)
     : base(myCoord)
 {
     m_injectSlot  = null;
     m_injectSlot2 = null;
     rBuf = new ResubBuffer();
 }
	// Generate a line from one coordinate to another
	// You can ask for it to be totaly walls or totally floor, based on the bool
	// False: Walls
	// True: Floor
	public static void makeLine(Tile[,] map, Coord begin, Coord end, bool applyFloor) {

		// Assert in range
		if( begin.isOOB (map.GetLength(0), map.GetLength (1), Direction.Stop) ||
		    end.isOOB (map.GetLength(0), map.GetLength (1), Direction.Stop) )
			return;
		
		int startX = begin.x;
		int endX = end.x;
		int startY = begin.y;
		int endY = end.y;


		// Find the linear spacing appropriate from point
		// including the endpoint
		int lengthX = Math.Abs( endX - startX );

		var linspace = new List<Double>();
			linspace = LinSpace (startY, endY, lengthX, true).ToList ();

		// Now it's time to actually put our money where our mouth is
		for(int i = startX; i < endX; i++) {
			int j = (int) linspace[i] ;
			map[i,j].property = applyFloor ? TileType.Floor1 : TileType.OuterWall1;
		}

		// Phew! Thought this one was so easy, didn't cha!?

		return;
	}
Example #17
0
 public Apple(Renderer renderer, PlayField playField)
 {
     _renderer = renderer;
     AppleCoordinate = new Coord();
     _playFieldHeight = playField.Height;
     _playFieldWidth = playField.Width;
 }
Example #18
0
        /// <summary>
        /// 以待编辑的元素坐标创建窗口
        /// </summary>
        public FrmEdit(Coord editPos)
        {
            InitializeComponent();

            this.CurPosation = editPos;
            this.content.Text = MotaWorld.GetInstance().MapManager.GetNodeString(editPos);
        }
Example #19
0
        public void StraightTrajectory()
        {
            this.board.RemovePinAt(1, 1);

            Coord from = new Coord(0, 1), to = new Coord(2, 1);
            this.AssertBestProbToArrive(from, to, 1);
        }
Example #20
0
		public DemoCardContents() : base(Orientation.Vertical)
		{
			var label = new Label(Name);
			AddChild(label);
			
			UserSize = new Coord(320, 480);
		}
Example #21
0
        /// <summary>
        /// 以一定的移动速度创建可移动元素对象
        /// </summary>
        /// <param name="fileName">移动对象的图像文件</param>
        /// <param name="pos">可移动对象的初始位置</param>
        /// <param name="name">移动对象名称</param>
        /// <param name="unitSize">图像分割的单位尺寸</param>
        public MoveElement(string fileName, Coord pos, string name, Size unitSize)
            :base(fileName, pos, TouchMethod.ImmediatelyTouch, true, name, unitSize)
        {
            this.Speed = GameIni.IniHeroSpeed;

            MoveDirection = Direction.No;
        }
Example #22
0
		public override void RenderOverlay(Scene scene)
		{
			// compute the current frame rate
			if (_stopwatch.IsRunning)
			{
				var fps = 1.0 / _stopwatch.Elapsed.TotalSeconds;
				_stopwatch.Reset();
				_fpsAverager.Add(fps);
			}
			else
			{
				_stopwatch.Start();
			}

			// get the last mouse position
			Coord pos;
			if (_lastMouseEvent != null)
				pos = _lastMouseEvent.Pos;
			else
				pos = new Coord();
					
			_label.Body = String.Format("{0:###.#} fps -- {1} ({2} x {3})", 
				_fpsAverager.Compute(), pos, Scene.Width, Scene.Height);
			OnSceneResized(Scene);

			base.RenderOverlay(scene);
		}
		public void AddCoordToAppropriateSequence(Coord coord)
		{
			bool flag = false;
			foreach (Sequence current in this.Sequences)
			{
				if (current.LastCoord.I + 1 == coord.I && current.LastCoord.J + 1 == coord.J)
				{
					current.LastCoord = coord;
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				this.Sequences.Add(new Sequence
				{
					FirstCoord = new Coord
					{
						I = coord.I - coord.Size + 1,
						J = coord.J - coord.Size + 1,
						Size = 1
					},
					LastCoord = coord
				});
			}
		}
Example #24
0
        /// <summary>
        /// 以一定的移动速度创建可移动元素对象
        /// </summary>
        /// <param name="faceIndex">移动对象的图像索引</param>
        /// <param name="pos">可移动对象的初始位置</param>
        /// <param name="name">移动对象名称</param>
        public MoveElement(MotaElement faceIndex, Coord pos, string name)
            : base(faceIndex, pos, TouchMethod.ImmediatelyTouch, true, name)
        {
            this.Speed = GameIni.IniHeroSpeed;

            MoveDirection = Direction.No;
        }
Example #25
0
 public void ShouldConvertToVector3()
 {
     Coord coord = new Coord(2, 2);
     Vector2 vector = coord.ToVector2();
     Assert.AreEqual(2f, vector.x, 0.001f);
     Assert.AreEqual(2f, vector.y, 0.001f);
 }
Example #26
0
 public void DeviceRect(Coord x0, Coord y0, Coord x1, Coord y1)
 {
     Coord left = Math.Min(x0.Value, x1.Value);
     Coord right = Math.Max(x0.Value, x1.Value);
     Coord botom = Math.Min(y0.Value, y1.Value);
     Coord top = Math.Max(y0.Value, y1.Value);
 }
	public override void boardSetup() {
		
		boardHolder = new GameObject ("Board").transform;
		
		// Generate a map from Cellular Automata.
		// CellularAutomata foo = new CellularAutomata(rows, columns);
		//PureRandom foo = new PureRandom(rows, columns);
		GameObject playerChar = GameObject.FindGameObjectWithTag("Player");
		selectedRule.initializeMap ();
		selectedRule.generateMap ();
		Tile[,] mapConvert = selectedRule.map;

		MapValidationFunctions mvf = new MapValidationFunctions();

		Coord startPoint = new Coord(floodStartX,floodStartY); 
		Coord endPoint = new Coord(floodGoalX, floodGoalY);
		
		mvf.FloodFillCheck(selectedRule.map, startPoint, endPoint);

		// This is the autotiler phase.
		//
		// Let's try this method of instantiating the prefab of our choice...
		GameObject tileInstance = Instantiate(tilesetToUse, new Vector3(0,0,0), Quaternion.identity) as GameObject;
		
		selectedTileset = tileInstance.GetComponent<Tileset>();
		selectedTileset.autoTiler( mapConvert ); 

		if(MapValidationFunctions.clearable) Debug.Log ("The goal has been found!");
		else Debug.Log ("I can't find the goal.");
		
		//convertTiles( mapConvert );
		
	}
Example #28
0
        /// <summary>
        /// 根据自定义的图像设置事件元素实例
        /// </summary>
        /// <param name="fileName">图像文件名</param>
        /// <param name="showPosation">事件在地图上的坐标</param>
        /// <param name="method">触发方式</param
        /// <param name="repeated">是否是触发触发的事件</param>>
        /// <param name="eventName">事件名</param>
        /// <param name="unitSize">图像分隔的单位尺寸</param>
        protected MapEvent(string fileName, Coord showPosation, TouchMethod method, bool repeated, string eventName, Size unitSize)
            : base(fileName, showPosation, unitSize)
        {
            SetAttr(method, repeated, eventName);

            this.FaceUnit = unitSize;
        }
Example #29
0
        public SimpleCircle(Coord center, int radius)
            : base(center, radius)
        {
            pts = new List<Coord>();

            int x0 = center.X;
            int y0 = center.Y;
            int x = radius;
            int y = 0;
            int decisionOver2 = 1 - x;   // Decision criterion divided by 2 evaluated at x=r, y=0

            while (y <= x)
            {
                pts.Add(new Coord(x + x0, y + y0)); // Octant 1
                pts.Add(new Coord(y + x0, x + y0)); // Octant 2
                pts.Add(new Coord(-x + x0, y + y0)); // Octant 4
                pts.Add(new Coord(-y + x0, x + y0)); // Octant 3
                pts.Add(new Coord(-x + x0, -y + y0)); // Octant 5
                pts.Add(new Coord(-y + x0, -x + y0)); // Octant 6
                pts.Add(new Coord(x + x0, -y + y0)); // Octant 7
                pts.Add(new Coord(y + x0, -x + y0)); // Octant 8
                y++;
                if (decisionOver2 <= 0)
                {
                    decisionOver2 += 2 * y + 1;   // Change in decision criterion for y -> y+1
                }
                else
                {
                    x--;
                    decisionOver2 += 2 * (y - x) + 1;   // Change for y -> y+1, x -> x-1
                }
            }
        }        
Example #30
0
        public Node(NodeMapping mapping, Coord c)
        {
            m_coord = c;
            m_mapping = mapping;

            if (mapping.hasCPU(c.ID))
            {
                m_cpu = new CPU(this);
            }
            if (mapping.hasMem(c.ID))
            {
				Console.WriteLine("Proc/Node.cs : MC locations:{0}", c.ID);
                m_mem = new MemCtlr(this);
            }

            m_inj_pool = Simulator.controller.newPrioPktPool(m_coord.ID);
            Simulator.controller.setInjPool(m_coord.ID, m_inj_pool);
            m_injQueue_flit = new Queue<Flit>();
            m_injQueue_evict = new Queue<Flit>();
            m_local = new Queue<Packet>();

            m_rxbuf_naive = new RxBufNaive(this,
                    delegate(Flit f) { m_injQueue_evict.Enqueue(f); },
                    delegate(Packet p) { receivePacket(p); });
        }
Example #31
0
 protected static bool CoordsMatch(Coord a, Coord b) => a.X == b.X && a.Y == b.Y;
Example #32
0
 public static GameObject Floor(Coord position) => new GameObject(position, layer: 0, parentObject: null, isStatic: true, isWalkable: true, isTransparent: true);
Example #33
0
 public IUnit TryGetUnit(Coord coord)
 {
     units.TryGetValue(coord, out var unit);
     return(unit);
 }
Example #34
0
 public bool ContainsUnit(Coord coord) => units.ContainsKey(coord);
Example #35
0
 public void RemoveUnit(Coord coord) => units.Remove(coord);
Example #36
0
 public void AddUnit(Coord coord, IUnit unit) => units[coord] = unit;
Example #37
0
    public void GenerateMap()
    {
        //Map info
        currentMap = maps[mapIndex];
        System.Random prng = new System.Random(currentMap.seed);
        //tile map
        tileMap = new Transform[currentMap.mapSize.x, currentMap.mapSize.y];

        //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));
        //HOLDERS
        //object name
        string holderName   = "Generated Map";
        string tileName     = "Tiles";
        string obstacleName = "Obstacles";

        if (transform.Find(holderName))
        {
            if (transform.Find(holderName).Find(tileName))
            {
                DestroyImmediate(transform.Find(holderName).Find(tileName).gameObject);
            }
            if (transform.Find(holderName).Find(obstacleName))
            {
                DestroyImmediate(transform.Find(holderName).Find(obstacleName).gameObject);
            }
            //immediate cause it is called from the editor
            DestroyImmediate(transform.Find(holderName).gameObject);
        }
        //map group
        Transform mapHolder = new GameObject(holderName).transform;

        mapHolder.parent = transform;
        //tiles group

        Transform tileHolder = new GameObject(tileName).transform;

        tileHolder.parent = mapHolder;
        //obstacles group

        Transform obstacleHolder = new GameObject(obstacleName).transform;

        obstacleHolder.parent = mapHolder;
        //CREATE TILES
        for (int x = 0; x < currentMap.mapSize.x; x++)
        {
            for (int y = 0; y < currentMap.mapSize.y; y++)
            {
                //left edge. +.5f to put edge of the tile on that pos, not center
                Vector3 tilePos = CoordToPos(x, y);
                //translate ar Euler angle. Vector.right - X Axis
                Transform newTile = Instantiate(tilePrefab, tilePos, Quaternion.Euler(Vector3.right * 90)) as Transform;
                //scale. creates distance between tiles
                newTile.localScale = Vector3.one * (1 - outlinePercent) * tileSize;
                newTile.parent     = tileHolder;
                tileMap[x, y]      = newTile;
            }
        }
        //CREATE OBSTACLES
        bool[,] obstacleMap = new bool[currentMap.mapSize.x, currentMap.mapSize.y];
        int obstacleCount   = (int)(currentMap.mapSize.x * currentMap.mapSize.y * currentMap.obstaclePercent);
        int currentObsCount = 0;
        //copy
        List <Coord> allOpenCoords = new List <Coord>(allTileCoords);

        for (int i = 0; i < obstacleCount; i++)
        {
            Coord randomCoord = GetRandomCoord();
            obstacleMap[randomCoord.x, randomCoord.y] = true;
            currentObsCount++;
            //no obs in center. center - player spawn
            if (randomCoord != currentMap.mapCenter && MapIsFullyAccessible(obstacleMap, currentObsCount))
            {
                //random height
                float     obsHeight   = Mathf.Lerp(currentMap.minObsHeight, currentMap.maxObsHeight, (float)prng.NextDouble());
                Vector3   obstaclePos = CoordToPos(randomCoord.x, randomCoord.y);
                Transform newObs      = Instantiate(obstaclePrefab, obstaclePos + Vector3.up * obsHeight / 2,
                                                    Quaternion.identity) as Transform;
                newObs.parent     = obstacleHolder;
                newObs.localScale = new Vector3((1 - outlinePercent) * tileSize,
                                                obsHeight,
                                                (1 - outlinePercent) * tileSize);
                //MAKE GRADIENT COLOR
                Renderer obsRenderer = newObs.GetComponent <Renderer>();
                Material obsMat      = new Material(obsRenderer.sharedMaterial);
                //see how forward randCoord is
                float colorPercent = randomCoord.y / (float)currentMap.mapSize.y;
                obsMat.color = Color.Lerp(currentMap.fgColor, currentMap.bgColor, colorPercent);
                obsRenderer.sharedMaterial = obsMat;
                //remove obstacle coord
                allOpenCoords.Remove(randomCoord);
            }
            else
            {
                obstacleMap[randomCoord.x, randomCoord.y] = false;
                currentObsCount--;
            }
        }
        //Shuffle all open coords
        shuffledOpenTileCoords = new Queue <Coord>(Utility.ShuffleArray(allOpenCoords.ToArray(), currentMap.seed));
        //NAV MESH
        //LEFT MASK
        Transform maskLeft = Instantiate(navmeshMaskPrefab,
                                         Vector3.left * (currentMap.mapSize.x + maxMapSize.x) / 4f * tileSize,
                                         Quaternion.identity) as Transform;

        maskLeft.parent = mapHolder;
        //x scale = distance between edges of  map and maxMap
        maskLeft.localScale = new Vector3((maxMapSize.x - currentMap.mapSize.x) / 2f, 1, currentMap.mapSize.y) * tileSize;

        //RIGHT MASK
        Transform maskRight = Instantiate(navmeshMaskPrefab,
                                          Vector3.right * (currentMap.mapSize.x + maxMapSize.x) / 4f * tileSize,
                                          Quaternion.identity) as Transform;

        maskRight.parent = mapHolder;
        //x scale = distance between edges of  map and maxMap
        maskRight.localScale = new Vector3((maxMapSize.x - currentMap.mapSize.x) / 2f, 1, currentMap.mapSize.y) * tileSize;
        //MASK TOP
        //forward - z
        Transform maskTop = Instantiate(navmeshMaskPrefab,
                                        Vector3.forward * (currentMap.mapSize.y + maxMapSize.y) / 4f * tileSize,
                                        Quaternion.identity) as Transform;

        maskTop.parent = mapHolder;
        //x scale = distance between edges of  map and maxMap
        maskTop.localScale = new Vector3(maxMapSize.x, 1, (maxMapSize.y - currentMap.mapSize.y) / 2f) * tileSize;
        //MASK BOTTOM
        Transform maskBottom = Instantiate(navmeshMaskPrefab,
                                           Vector3.back * (currentMap.mapSize.y + maxMapSize.y) / 4f * tileSize,
                                           Quaternion.identity) as Transform;

        maskBottom.parent = mapHolder;
        //x scale = distance between edges of  map and maxMap
        maskBottom.localScale = new Vector3(maxMapSize.x,
                                            1,
                                            (maxMapSize.y - currentMap.mapSize.y) / 2f) * tileSize;

        //x,y,0 because its rotated 90*
        navmeshFloor.localScale = new Vector3(maxMapSize.x, maxMapSize.y) * tileSize;
        //floor collider
        mapFloor.localScale = new Vector3(currentMap.mapSize.x * tileSize, currentMap.mapSize.y * tileSize);
    }
Example #38
0
    public void GenerateRoom()
    {
        tileCoordinates = new List <Coord> ();
        obsticleCorrd   = new List <Coord> ();

        for (int x = 0; x < mapSize.x; x++)
        {
            for (int y = 0; y < mapSize.y; y++)
            {
                tileCoordinates.Add(new Coord(x, y));
            }
        }

        shuffledTileCoordinates = new Queue <Coord> (Utility.RandomlyShuffledArray(tileCoordinates.ToArray(), seed));

        string holder = "Generated";

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

        Transform obsticalHolder = new GameObject(holder).transform;

        obsticalHolder.parent = transform;


        Transform North = wallPrefab;

        if (north == 0)
        {
            North = passPrefab;
        }
        if (north == -1)
        {
            North = exitPrefab;
        }
        Vector3   nv        = new Vector3(0 + mapLocation.x * tileSize, 1f, (tileSize / 2 - 0.5f) * tileSize + mapLocation.y * tileSize);
        Transform northWall = Instantiate(North, nv, Quaternion.identity) as Transform;

        northWall.parent     = obsticalHolder;
        northWall.localScale = Vector3.one * tileSize;

        Transform East = wallPrefab;

        if (east == 0)
        {
            East = passPrefab;
        }
        if (east == -1)
        {
            East = exitPrefab;
        }
        Vector3   ev       = new Vector3((tileSize / 2 - 0.5f) * tileSize + mapLocation.x * tileSize, 1f, 0 + mapLocation.y * tileSize);
        Transform eastWall = Instantiate(East, ev, Quaternion.Euler(Vector3.up * 90)) as Transform;

        eastWall.parent     = obsticalHolder;
        eastWall.localScale = Vector3.one * tileSize;

        Transform South = wallPrefab;

        if (south == 0)
        {
            South = passPrefab;
        }
        if (south == -1)
        {
            North = exitPrefab;
        }
        Vector3   sv        = new Vector3(0 + mapLocation.x * tileSize, 1f, -(tileSize / 2 - 0.5f) * tileSize + mapLocation.y * tileSize);
        Transform southWall = Instantiate(South, sv, Quaternion.identity) as Transform;

        southWall.parent     = obsticalHolder;
        southWall.localScale = Vector3.one * tileSize;


        Transform West = wallPrefab;

        if (west == 0)
        {
            West = passPrefab;
        }
        if (west == -1)
        {
            West = exitPrefab;
        }
        Vector3   wv       = new Vector3(-(tileSize / 2 - 0.5f) * tileSize + mapLocation.x * tileSize, 1f, 0 + mapLocation.y * tileSize);
        Transform westWall = Instantiate(West, wv, Quaternion.Euler(Vector3.up * 90)) as Transform;

        westWall.parent     = obsticalHolder;
        westWall.localScale = Vector3.one * tileSize;

        Vector3   fl    = new Vector3(mapLocation.x * tileSize, 1f, mapLocation.y * tileSize);
        Transform floor = Instantiate(floorPrefab, fl, Quaternion.identity) as Transform;

        floor.parent     = obsticalHolder;
        floor.localScale = Vector3.one * tileSize;

        for (int x = 0; x < mapSize.x; x++)
        {
            for (int y = 0; y < mapSize.y; y++)
            {
                Vector3   tilePosition = CoordinateToPosition(x, y);
                Transform newTile      = Instantiate(tilePrefab, tilePosition, Quaternion.Euler(Vector3.right * 90)) as Transform;
                newTile.localScale = Vector3.one * (1 - tileOutlinePercent) * tileSize;
                newTile.parent     = obsticalHolder;
            }
        }

        for (int i = 0; i < obsticleCount; i++)
        {
            Coord randomCoordinate = GetRandomCoordinate();
            obsticleCorrd.Add(randomCoordinate);
            Vector3   obsticlePosition = CoordinateToPosition(randomCoordinate.x, randomCoordinate.y);
            Transform newObsticle      = Instantiate(obsticalPrefab, obsticlePosition + Vector3.up * 0.5f, Quaternion.identity) as Transform;
            newObsticle.parent     = obsticalHolder;
            newObsticle.localScale = Vector3.one * tileSize;
        }


        //generate enemies
        EnemyGeneration();
    }
Example #39
0
 protected static int GetManhattenDistance(Coord origin, Coord destination)
 {
     return(Math.Abs(origin.X - destination.X) + Math.Abs(origin.Y - destination.Y));
 }
Example #40
0
 public override string ToString()
 {
     return("Site " + _siteIndex.ToString() + ": " + Coord.ToString());
 }
Example #41
0
 public bool SetCursorPosition(Coord position)
 {
     return(SetConsoleCursorPosition(ScreenBuffer, position));
 }
Example #42
0
 static extern bool SetConsoleCursorPosition(IntPtr hConsoleOutput, Coord dwCursorPosition);
Example #43
0
 public bool isSurround(Coord c)
 {
     return(obsticleCorrd.Contains(new Coord(c.x - 1, c.y)) && obsticleCorrd.Contains(new Coord(c.x, c.y - 1)) && obsticleCorrd.Contains(new Coord(c.x + 1, c.y)) && obsticleCorrd.Contains(new Coord(c.x, c.y + 1)));
 }
Example #44
0
 public Queen(Coord coord)
 {
     coordinate = coord;
 }
Example #45
0
    public void EnemyGeneration()
    {
        nextStepGen();
        int   x, y;
        Coord c;

        enemyrespwaned = new List <Coord> ();
        System.Random prng   = new System.Random(seed);
        string        holder = "Enemies";

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

        Transform enemyHolder = new GameObject(holder).transform;

        enemyHolder.parent = transform;


        for (int i = 0; i < enemyCount; i++)
        {
            int r = prng.Next(0, obsticleCorrd.Count);
            x = obsticleCorrd.ToArray() [r].x - 1 + prng.Next(0, 3);
            y = obsticleCorrd.ToArray() [r].y - 1 + prng.Next(0, 3);
            c = new Coord(x, y);
            if (isObstical(c) || enemyrespwaned.Contains(c))
            {
                i--;
                continue;
            }
            enemyrespwaned.Add(c);
            Vector3 pos = CoordinateToPositionEnemy(x, y);
            //obsticleCorrd.Add (new Coord (x, y));
            Transform enemy = Instantiate(enemyPrefab, pos, Quaternion.identity) as Transform;
            enemy.parent = enemyHolder;

            if (prng.Next(0, 2) == 0)
            {
                EnemyPathGeneration(x, y, enemy, obsticleCorrd.ToArray() [r], true);
            }
            else
            {
                EnemyPathGeneration(x, y, enemy, obsticleCorrd.ToArray() [r], false);
            }
        }

        for (int i = 0; i < enemySPCount; i++)
        {
            int r = prng.Next(0, obsticleCorrd.Count);
            x = obsticleCorrd.ToArray() [r].x - 1 + prng.Next(0, 3);
            y = obsticleCorrd.ToArray() [r].y - 1 + prng.Next(0, 3);
            c = new Coord(x, y);
            if (isObstical(c) || enemyrespwaned.Contains(c))
            {
                i--;
                continue;
            }
            enemyrespwaned.Add(c);
            Vector3 pos = CoordinateToPositionEnemy(x, y);
            //obsticleCorrd.Add (new Coord (x, y));
            Transform enemy = Instantiate(enemySPPrefab, pos, Quaternion.identity) as Transform;
            enemy.parent = enemyHolder;

            if (prng.Next(0, 2) == 0)
            {
                EnemyPathGeneration(x, y, enemy, obsticleCorrd.ToArray() [r], true);
            }
            else
            {
                EnemyPathGeneration(x, y, enemy, obsticleCorrd.ToArray() [r], false);
            }
        }
    }
Example #46
0
 public bool isObstical(Coord c)
 {
     return(obsticleCorrd.Contains(c));
 }
Example #47
0
 public Repulser(Coord coord, Coord targetCoord)
     : this(coord)
 {
     this.TargetCoord = targetCoord;
 }
Example #48
0
 public IPieceAgent At(Coord coord)
 {
     return(_pieces.FirstOrDefault(p => p.Coord.Value == coord));
 }
Example #49
0
 public Repulser(Coord coord)
     : base(coord)
 {
 }
Example #50
0
    // connect rooms closest to each other
    void ConnectClosestRooms(List <Room> allRooms, bool forceAccessFromMain = false)
    {
        List <Room> roomListA = new List <Room>();
        List <Room> roomListB = new List <Room>();

        if (forceAccessFromMain)
        {
            foreach (Room room in allRooms)
            {
                if (room.isAccessibleFromMain)
                {
                    roomListB.Add(room);
                }
                else
                {
                    roomListA.Add(room);
                }
            }
        }
        else
        {
            roomListA = allRooms;
            roomListB = allRooms;
        }

        int   bestDistance       = 0;
        Coord bestTileA          = new Coord();
        Coord bestTileB          = new Coord();
        Room  bestRoomA          = new Room();
        Room  bestRoomB          = new Room();
        bool  possibleConnection = false;

        foreach (Room roomA in roomListA)
        {
            if (!forceAccessFromMain)
            {
                possibleConnection = false;                 // watch ep 7(~9:00) to understand this logic
                if (roomA.connectedRooms.Count > 0)
                {
                    continue;
                }
            }

            foreach (Room roomB in roomListB)
            {
                if (roomA == roomB || roomA.IsConnected(roomB))
                {
                    continue;                     // goes to next roomB
                }
                foreach (Coord tileA in roomA.edgeTiles)
                {
                    foreach (Coord tileB in roomB.edgeTiles)
                    {
                        int distanceBetweenRooms = (int)(Mathf.Pow(tileA.tileX - tileB.tileX, 2) + Mathf.Pow(tileA.tileY - tileB.tileY, 2));

                        if (distanceBetweenRooms < bestDistance || !possibleConnection)
                        {
                            bestDistance       = distanceBetweenRooms;
                            possibleConnection = true;
                            bestTileA          = tileA;
                            bestTileB          = tileB;
                            bestRoomA          = roomA;
                            bestRoomB          = roomB;
                        }
                    }
                }
            }
            if (possibleConnection && !forceAccessFromMain)
            {
                CreatePassage(bestRoomA, bestRoomB, bestTileA, bestTileB);
            }
        }
        if (possibleConnection && forceAccessFromMain)
        {
            CreatePassage(bestRoomA, bestRoomB, bestTileA, bestTileB);
            ConnectClosestRooms(allRooms, true);
        }

        if (!forceAccessFromMain)
        {
            ConnectClosestRooms(allRooms, true);
        }
    }
Example #51
0
 static extern int SetConsoleCursorPosition(IntPtr buffer, Coord position);
Example #52
0
 static extern int FillConsoleOutputCharacter(IntPtr buffer, char character, int length, Coord position, out int written);
Example #53
0
 public void GenerateWorkerAt(Coord spot)
 {
     // For now just make the game object.
     Instantiate(workerPrefab, spot.GetWorldCoords() + WorldGenerator.RandomCirclePos() + (Vector3.back * 2), Quaternion.identity);
 }
Example #54
0
        override public List <GameObject> SetValueOfGameObjects()
        {
            List <GameObject> gameObjects = new List <GameObject>();

            countOfMeteors = 350;


            centerPlanet = new Planet();
            gameObjects.Add(centerPlanet);
            centerPlanet.phisObj.angulVel = -2 * Math.PI / 500;

            centerPlanet.image = MainWindow.window.CenterStar;



            planets = new List <Planet>();
            for (int i = 0; i < countOfPlanets; i++)
            {
                planets.Add(new Planet());
                gameObjects.Add(planets[i]);

                planets[i].image = MainWindow.Clone(MainWindow.window.SmallPlanet);
                MainWindow.window.PlayingCanvas.Children.Add(planets[i].image);

                planets[i].phisObj.mass  = centerPlanet.phisObj.mass / 100;
                planets[i].phisObj.coord = centerPlanet.phisObj.coord + Coord.FromPolar(500 + 400, 2 * Math.PI / countOfPlanets * i);
                planets[i].phisObj.speed = Gravitation.CosmicSpeeds(planets[i].phisObj, centerPlanet.phisObj, 1);
            }



            rocket = new Rocket();
            gameObjects.Add(rocket);

            rocket.image = MainWindow.window.Rocket;

            rocket.Y     = -400;
            rocket.Angle = 0;

            rocket.phisObj.speed = Gravitation.CosmicSpeeds(rocket.phisObj, centerPlanet.phisObj, 1);


            fire = new ReactiveGases(rocket);

            fire.image = MainWindow.window.Fire;

            gameObjects.Add(fire);


            playingBorder = new PlayingBorder(centerPlanet, rocket);

            playingBorder.image = MainWindow.window.Border;

            gameObjects.Add(playingBorder);



            meteors = SetValueOfMeteors();

            gameObjects = gameObjects.Concat(meteors).ToList();



            return(gameObjects);
        }
Example #55
0
    void ConnectClosestRooms(List <Room> allRooms, bool forceAccessibilityFromMainRoom = false)
    {
        List <Room> roomListA = new List <Room>();
        List <Room> roomListB = new List <Room>();

        if (forceAccessibilityFromMainRoom)
        {
            foreach (Room room in allRooms)
            {
                if (room.isAccessibleFromMainRoom)
                {
                    roomListB.Add(room);
                }
                else
                {
                    roomListA.Add(room);
                }
            }
        }
        else
        {
            roomListA = allRooms;
            roomListB = allRooms;
        }

        int   bestDistance            = 0;
        Coord bestTileA               = new Coord();
        Coord bestTileB               = new Coord();
        Room  bestRoomA               = new Room();
        Room  bestRoomB               = new Room();
        bool  possibleConnectionFound = false;

        foreach (Room roomA in roomListA)
        {
            if (!forceAccessibilityFromMainRoom)
            {
                possibleConnectionFound = false;
                if (roomA.connectedRooms.Count > 0)
                {
                    continue;
                }
            }

            foreach (Room roomB in roomListB)
            {
                if (roomA == roomB || roomA.IsConnected(roomB))
                {
                    continue;
                }

                for (int tileIndexA = 0; tileIndexA < roomA.edgeTiles.Count; tileIndexA++)
                {
                    for (int tileIndexB = 0; tileIndexB < roomB.edgeTiles.Count; tileIndexB++)
                    {
                        Coord tileA = roomA.edgeTiles[tileIndexA];
                        Coord tileB = roomB.edgeTiles[tileIndexB];
                        int   distanceBetweenRooms = (int)(Mathf.Pow(tileA.tileX - tileB.tileX, 2) + Mathf.Pow(tileA.tileY - tileB.tileY, 2));

                        if (distanceBetweenRooms < bestDistance || !possibleConnectionFound)
                        {
                            bestDistance            = distanceBetweenRooms;
                            possibleConnectionFound = true;
                            bestTileA = tileA;
                            bestTileB = tileB;
                            bestRoomA = roomA;
                            bestRoomB = roomB;
                        }
                    }
                }
            }
            if (possibleConnectionFound && !forceAccessibilityFromMainRoom)
            {
                CreatePassage(bestRoomA, bestRoomB, bestTileA, bestTileB);
            }
        }

        if (possibleConnectionFound && forceAccessibilityFromMainRoom)
        {
            CreatePassage(bestRoomA, bestRoomB, bestTileA, bestTileB);
            ConnectClosestRooms(allRooms, true);
        }

        if (!forceAccessibilityFromMainRoom)
        {
            ConnectClosestRooms(allRooms, true);
        }
    }
Example #56
0
 public IResponse Move(IPieceAgent agent, Coord coord)
 {
     return(Model.Move(agent.Model, coord));
 }
Example #57
0
 Vector3 CoordToWorldPoint(Coord tile)
 {
     return(new Vector3(-width / 2 + .5f + tile.tileX, 2, -height / 2 + .5f + tile.tileY));
 }
Example #58
0
 static extern bool WriteConsoleOutput(
     SafeFileHandle hConsoleOutput,
     Pixel[] lpBuffer,
     Coord dwBufferSize,
     Coord dwBufferCoord,
     ref ScreenSize lpWriteRegion);
Example #59
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));

        // Create map holder object
        string holderName = "Generated Map";

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

        Transform mapHolder = new GameObject(holderName).transform;

        mapHolder.parent = transform;

        // Spawning 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;
            }
        }

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

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

        for (int i = 0; i < obstacleCount; i++)
        {
            Coord randomCoord = GetRandomCoord();
            obstacleMap[randomCoord.x, randomCoord.y] = true;
            currentObstacleCount++;
            if (randomCoord != currentMap.mapCentre && 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 obstacleMaterial = new Material(obstacleRenderer.sharedMaterial);
                float    colorPercent     = randomCoord.y / (float)currentMap.mapSize.y;
                obstacleMaterial.color          = Color.Lerp(currentMap.foregroundColor, currentMap.backgroundColor, colorPercent);
                obstacleRenderer.sharedMaterial = obstacleMaterial;

                allOpenCoords.Remove(randomCoord);
            }
            else
            {
                obstacleMap[randomCoord.x, randomCoord.y] = false;
                currentObstacleCount--;
            }
        }

        shuffledOpenTileCoords = new Queue <Coord>(Utility.ShuffleArray(allOpenCoords.ToArray(), currentMap.seed));

        // Creating navmesh mask
        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) / 2, 1, currentMap.mapSize.y) * tileSize;

        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) / 2, 1, currentMap.mapSize.y) * tileSize;

        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) / 2) * tileSize;

        Transform maskBottom = Instantiate(navmeshMaskPrefab, Vector3.back * (currentMap.mapSize.y + maxMapSize.y) / 4f * tileSize, Quaternion.identity) as Transform;

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


        navmeshFloor.localScale = new Vector3(maxMapSize.x, maxMapSize.y) * tileSize;
        mapFloor.localScale     = new Vector3(currentMap.mapSize.x * tileSize, currentMap.mapSize.y * tileSize);
    }
Example #60
0
 public int DistanceTo(Coord other)
 {
     return(Mathf.RoundToInt((this.ToVector2() - other.ToVector2()).magnitude / Constantes.INNER_RADIUS / 2));
 }