Exemplo n.º 1
0
    /** Scan the map with a raycast */
    public void Scan()
    {
        TileNode[,] nodes = new TileNode[width, depth];

        // maybe not the proper way (use the MeshFilter component ?)
        Vector3 center = GetComponent<Renderer>().bounds.center;
        Vector3 size = GetComponent<Renderer>().bounds.size;

        // consider the mesh as a rectangle
        startPos = center - size / 2;
        cellWidth = size.x / width;
        cellDepth = size.z / depth;

        // raycast position
        Vector3 pos = new Vector3(0,0,0);
        pos.y = height;

        for (int x = 0; x < width; x++) {
            for (int z = 0; z < depth; z++) {
                pos = startPos + new Vector3(x * cellWidth, height, z * cellDepth);
                RaycastHit hit;
                if (Physics.Raycast(pos, -Vector3.up, out hit, Mathf.Infinity, layer)) {
                    nodes[x,z] = new TileNode(hit.point, x*width+z, x, z);

                    if (hit.transform.gameObject.layer == layerObstacles) {
                        nodes[x,z].Walkable = false;
                    }
                }

            }
        }

        tileGraph = new TileGraph(nodes, width, depth, cellWidth, cellDepth, startPos);
    }
Exemplo n.º 2
0
	public void LinkWith(TileNode node)
	{
		if (!links.Contains(node))
		{
			links.Add(node);
		}
	}
Exemplo n.º 3
0
    void Start()
    {
        //make nodes array the same size as placeholder array (x and y swapped for code readbility)
        nodes = new TileNode[level.GetLength(1), level.GetLength(0)];

        for (int y = 0; y < level.GetLength(0); y++)                    //This iteration code will be changed when placeholder array is removed
        {
            for (int x = 0; x < level.GetLength(1); x++)
            {
                //Convert array position to world position
                Vector2 position = Helper.GridToIso(new Vector2(x, y), worldTileOffset);

                if (level[y, x] == 0)
                    nodes[x, y] = new TileNode(TileNode.Type.Blank, new Vector2(x, y), position);
                else
                {
                    if (level[y, x] == 2)
                        nodes[x, y] = new TileNode(TileNode.Type.PlayerSpawn, new Vector2(x, y), position);
                    else if (level[y, x] == 3)
                        nodes[x, y] = new TileNode(TileNode.Type.EnemySpawn, new Vector2(x, y), position);
                    else
                        nodes[x, y] = new TileNode(TileNode.Type.Ground, new Vector2(x, y), position);

                    if (groundTile)
                    {
                        GameObject obj = Instantiate(groundTile, new Vector3(position.x, position.y, position.y), Quaternion.identity) as GameObject;
                        obj.name = groundTile.name + " (" + x + ", " + y + ")";
                        obj.transform.parent = transform;
                    }
                }
            }
        }
    }
Exemplo n.º 4
0
 /// <summary>returns 1 if on, else 0, and -1 if no link info exist with target node</summary>
 public int LinkIsOn(TileNode node)
 {
     foreach (LinkState l in linkStates)
     {
         if (l.neighbour == node) return (l.isOn?1:0);
     }
     return -1; // did not have link info
 }
Exemplo n.º 5
0
        public DFS(List<string> log)
        {
            openList = new List<TileNode>();
            closedList = new List<TileNode>();
            Current = new TileNode(0, 0, 0, 0);
            openList.Add(Current);

            //Player logs
            PlayerLog = log;
        }
Exemplo n.º 6
0
	private float delayTimer = 0f;			// used when unit isDelayed

	#endregion
	// ====================================================================================================================
	#region pub

	/// <summary>Instantiates a new unit on target node</summary>
	public static NaviUnit SpawnUnit(GameObject unitFab, MapNav mapnav, TileNode node)
	{
		GameObject go = (GameObject)GameObject.Instantiate(unitFab);
        go.transform.position = node.transform.position;
		NaviUnit unit = go.GetComponent<NaviUnit>();
		unit.mapnav = mapnav;
		unit._tr = go.transform;
		unit.LinkWith(node);
		return unit;
	}
	/// <summary>returns 1 if on, else 0, and -1 if no link info exist with target node</summary>
	public int LinkIsOn(TileNode node, TileNode.TileType forType)
	{
		if ((mask & forType) == 0)
		{
			Debug.Log("Mask does not include " + forType + " towards " + node);
			return -1; // this one does not control this tile type
		}

		foreach (LinkState l in linkStates)
		{
			if (l.neighbour == node) return (l.isOn?1:0);
		}

		return -1; // did not have link info
	}
Exemplo n.º 8
0
        public MapNode(model.Map map)
        {
            this.map = map;

            for ( int x = 0 ; x < map.tiles.Length ; x++)
            {
                for (int y = 0; y < map.tiles[x].Length; y++ )
                {
                    TileNode tn = new TileNode();
                    tn.tile = map.tiles[x][y];
                    tn.x = x;
                    tn.y = y;
                    children.Add(tn);
                }
            }
        }
Exemplo n.º 9
0
    public void SetLinkStateWith(TileNode node, bool on)
    {
        foreach (LinkState l in linkStates)
        {
            if (l.neighbour == node)
            {
                l.isOn = on;
                return;
            }
        }

        // not found? add
        LinkState ls = new LinkState();
        ls.neighbour = node;
        ls.isOn = on;
        linkStates.Add(ls);
    }
Exemplo n.º 10
0
    void Start()
    {
        //Get reference to level info from the game manager
        levelInfo = GameManager.instance.levelInfo;

        characterAction = GetComponent<CharacterAction>();
        characterAnimation = GetComponent<CharacterAnimation>();

        //Get spawn node if player, enemies are set when spawned
        if(isPlayer)
            spawnNode = levelInfo.GetSpawnTile(TileNode.Type.PlayerSpawn);

        //Start character at spawn node
        transform.position = spawnNode.worldPosition;
        //Set array position to spawn node
        MoveToNode(spawnNode.gridPosition);

        //set target position to current
        newPos = transform.position;
    }
Exemplo n.º 11
0
    //Searches the array for a spawn tile, and returns it
    public TileNode GetSpawnTile(TileNode.Type spawnType)
    {
        for (int x = 0; x < nodes.GetLength(0); x++)
        {
            for (int y = 0; y < nodes.GetLength(1); y++)
            {
                if (spawnType == TileNode.Type.PlayerSpawn && nodes[x, y].type == TileNode.Type.PlayerSpawn)
                {
                    return nodes[x, y];
                }
                else if (spawnType == TileNode.Type.EnemySpawn && nodes[x, y].type == TileNode.Type.EnemySpawn)
                {
                    return nodes[x, y];
                }
            }
        }

        //If no spawn tile is found, return null
        return null;
    }
Exemplo n.º 12
0
	/// <summary>
	/// Checks if the tergate node is in radius range from this node
	/// </summary>
	public bool IsInRange(TileNode targetNode, int radius)
	{
		radius--;
		if (radius < 0) return false;
		foreach (TileNode node in nodeLinks)
		{
			if (node != null)
			{
				if (node == targetNode) return true;
				if (node.IsInRange(targetNode, radius)) return true;
			}
		}
		return false;
	}
Exemplo n.º 13
0
        public static bool interruptionTasks(CustomTask v)
        {
            if (v.taskMetaData.bedTimePrerequisite.enoughTimeToDoTask() == false)
            {
                CustomTask task = WayPoints.pathToWayPointReturnTask("bed");
                if (task == null)
                {
                    ModCore.CoreMonitor.Log("SOMETHING WENT WRONG WHEN TRYING TO GO TO BED", LogLevel.Error);
                    return(false);
                }
                ModCore.CoreMonitor.Log("Not enough time remaining in day. Going home and removing tasks.", LogLevel.Alert);
                task.runTask();
                return(true);
            }

            if (v.taskMetaData.locationPrerequisite.isPlayerAtLocation() == false)
            {
                //Force player to move to that location, but also need the cost again....
                // ModCore.CoreMonitor.Log("PLAYERS LOCATION:"+Game1.player.currentLocation.name);
                Utilities.tileExceptionList.Clear();
                CustomTask task = WarpGoal.getWarpChainReturnTask(Game1.player.currentLocation, v.taskMetaData.locationPrerequisite.location.name);
                if (task == null)
                {
                    ModCore.CoreMonitor.Log("SOMETHING WENT WRONG WHEN TRYING TO GO TO" + v.taskMetaData.locationPrerequisite.location.name, LogLevel.Error);
                    return(false);
                }

                task.runTask();
                object[]        arr = (object[])v.objectParameterDataArray;
                List <TileNode> path;
                try
                {
                    List <List <TileNode> > okList    = (arr[0] as List <List <TileNode> >);
                    List <TileNode>         smallList = okList.ElementAt(okList.Count - 1);
                    TileNode tile = smallList.ElementAt(smallList.Count - 1);
                    //arr[0] = WarpGoal.pathToWorldTileReturnTask(Game1.player.currentLocation, v.taskMetaData.locationPrerequisite.location.name,(int) tile.tileLocation.X,(int) tile.tileLocation.Y);
                    TileNode s = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
                    s.fakePlacementAction(Game1.player.currentLocation, Game1.player.getTileX(), Game1.player.getTileY());

                    path = Utilities.getIdealPath(tile, s);
                }
                catch (Exception err)
                {
                    Utilities.tileExceptionList.Clear();
                    List <TileNode> smallList = (arr[1] as List <TileNode>);
                    TileNode        tile      = smallList.ElementAt(smallList.Count - 1);
                    //ModCore.CoreMonitor.Log("LOC:" + tile.thisLocation + tile.thisLocation);


                    Warp         lastWarp     = new Warp(-1, -1, "Grahm", -1, -1, false);
                    GameLocation fakeLocation = Game1.getLocationFromName(Game1.player.currentLocation.name);
                    foreach (var ok in fakeLocation.warps)
                    {
                        if (ok.X == Game1.player.getTileX() && ok.Y == Game1.player.getTileY() + 1)
                        {
                            lastWarp = ok;
                        }
                    }

                    //ModCore.CoreMonitor.Log("MYLOC:" + lastWarp.TargetName + lastWarp.TargetX +" "+lastWarp.TargetY);
                    //arr[0] = WarpGoal.pathToWorldTileReturnTask(Game1.player.currentLocation, v.taskMetaData.locationPrerequisite.location.name,(int) tile.tileLocation.X,(int) tile.tileLocation.Y);
                    TileNode s = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
                    s.fakePlacementAction(Game1.getLocationFromName(lastWarp.TargetName), lastWarp.TargetX, lastWarp.TargetY);

                    path = Utilities.getIdealPath(tile, s);
                    //arr[0] = s;
                }

                // ModCore.CoreMonitor.Log("PATHCOUNT:"+path.Count);

                //arr[1] = path;
                //v.objectParameterDataArray = arr;
                PathFindingLogic.calculateMovement(path);
                return(false);
            }

            if (v.taskMetaData.name == "Water Crop")
            {
                StardewValley.Tools.WateringCan w = new WateringCan();
                bool found = false;
                foreach (var item in Game1.player.items)
                {
                    if (item == null)
                    {
                        continue;
                    }
                    if (item.GetType() == typeof(StardewValley.Tools.WateringCan))
                    {
                        w     = (WateringCan)item;
                        found = true;
                    }
                }
                if (found == false)
                {
                    removalList.Add(v);
                    return(false);
                }
                if (w.WaterLeft == 0)
                {
                    CustomTask waterRefill = WaterLogic.getAllWaterTilesTask(Game1.player.currentLocation);
                    ModCore.CoreMonitor.Log("No water in can. Going to refil");
                    waterRefill.runTask();
                    return(true);
                }
                //
            }
            return(false);
        }
Exemplo n.º 14
0
        public void StartSearch()
        {
            if (startNode == null || destinationNode == null)
            {
                return;
            }

            interactive = false;

            // Check if won

            if (openSet.Count == 0)
            {
                unsolvable = true;
                return;
            }

            //Console.WriteLine("\n\nSearching...-----------");

            //printNodeList(openSet);

            TileNode current = getSmallNext(openSet);

            //Console.WriteLine("Extracted smallest: " + current);

            closedSet.Add(current);
            openSet.Remove(current);

            List <TileNode> neighbors = current.getNeighbors();


            foreach (TileNode i in neighbors)
            {
                if (!openSet.Contains(i))
                {
                    i.updateStats(current);
                    i.parent = current;
                    openSet.Add(i);
                }
                else
                {
                    //Console.Write("" + i + "Already in openlist ");
                    //Console.WriteLine("previous g() = " + i.g + " current g() = " + i.getManhattanDistance(current));
                    if (i.getManhattanDistance(current) < i.g)
                    {
                        i.updateStats(current);
                        i.parent = current;
                    }
                    //Console.WriteLine("Updated, now g() = " + i.g);
                }
            }

            //Console.WriteLine("Removed currentnode, added neighbors");

            //printNodeList(openSet);
            //printNodeList(closedSet);

            // only try to find a path the first time around
            // Need to be done manually every time after that
            if (closedSet.Contains(destinationNode))
            {
                pathFound = true;
                winSet    = buildPath();
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// Get a path from - to node
 /// </summary>
 public TileNode[] GetPath(TileNode fromNode, TileNode toNode)
 {
     return(GetPath(fromNode, toNode, 0));
 }
Exemplo n.º 16
0
    static void RenderTileNodeGizmo(TileNode node, GizmoType gizmoType) 
	{
		if (node.mapnav == null) return;
        Vector3 position = node.transform.position;
		Vector3 gizmoSize = TileNode.GizmoSize * (node.mapnav.tileSpacing / TileNode.GizmoSizeDiv);

		// draw cube(s) for node
		if (node.mapnav.gizmoDrawNodes || ((gizmoType & GizmoType.Selected) != 0))
		{
			if ((gizmoType & GizmoType.Selected) != 0)
			{
				Gizmos.color = Color.red;
				Gizmos.DrawCube(position, gizmoSize);
			}

			else if (node.mapnav.gizmoColorCoding)
			{
				bool drawn = false;
				Vector3 offs = Vector3.zero;
				for (int i = 0; i < TileNode.GizmoColourCoding.Length; i++)
				{
					int t = (int)Mathf.Pow(2, i);
					if ( ((int)node.tileTypeMask & t) == t)
					{
						Gizmos.color = TileNode.GizmoColourCoding[i];
						Gizmos.DrawCube(position + offs, gizmoSize);
						offs.y += gizmoSize.y;
						drawn = true;
					}
				}

				if (!drawn)
				{
					Gizmos.color = Color.black;
					Gizmos.DrawCube(position, gizmoSize);
				}
			}

			else
			{
				Gizmos.color = Color.black;
				Gizmos.DrawCube(position, gizmoSize);
			}
		}

		// draw the node links
		if (node.nodeLinks != null && (node.mapnav.gizmoDrawLinks || (gizmoType & GizmoType.Selected) != 0))
		{			
			TNELinksOnOffSwitch linkSwitch = node.gameObject.GetComponent<TNELinksOnOffSwitch>();
			foreach (TileNode n in node.nodeLinks)
		    {				
		        if (n != null)
		        {
					Gizmos.color = Color.blue;

					if (linkSwitch != null)
					{	// check if link is on with neighbour
						if (linkSwitch.LinkIsOn(n, (TileType)(-1))==0) Gizmos.color = Color.red;
					}

					//TNELinksOnOffSwitch nls = n.gameObject.GetComponent<TNELinksOnOffSwitch>();
					//if (nls != null)
					//{	// check if neighbour's link with me is on
					//	if (nls.LinkIsOn(node)==0) Gizmos.color = Color.red;
					//}

					Gizmos.DrawLine(position, n.transform.position);
		        }
		    }

			// look for forced links
			TNEForcedLink fl = node.gameObject.GetComponent<TNEForcedLink>();
			if (fl != null)
			{
				foreach (TileNode link in fl.links)
				{
					if (link == null) continue;
					Gizmos.DrawLine(position, link.transform.position);
				}
			}
		}
	}
Exemplo n.º 17
0
	/// <summary>
	/// Returns a list of Nodes in Range (in radius) that include a certain layer in their masks.
	/// </summary>
	/// <param name="radius">Up to how far from this node to check</param>
	/// <param name="validNodesLayer">Layer of valid nodes</param>
	/// <param name="checkIfUnitInWay">If true, check if there would be a unit in the way, else ignore this check</param>
	/// <param name="inclMoveMod">Include the move mod check to see if a unit would spend more moves to move over node to reach another?</param>
	/// <param name="incLinkCheck">Include the check to see if a node is actually linked and if that link is on or off?</param>
	/// <returns></returns>
	public List<TileNode> GetAllInRange(int radius, TileNode.TileType validNodesLayer, bool checkIfUnitInWay, bool inclMoveMod, bool incLinkCheck)
	{
		List<TileNode> ret = new List<TileNode>();
		List<TileNode> helper = new List<TileNode>();
		_GetAllInRangeRecursive(radius, validNodesLayer, checkIfUnitInWay, inclMoveMod, incLinkCheck, ref helper, ref ret);
		return ret;
	}
Exemplo n.º 18
0
 public static void harvestSingleCrop(TileNode v)
 {
     object[] obj = new object[1];
     obj[0] = v;
     harvestSingleCrop(obj);
 }
Exemplo n.º 19
0
 public TileNode(int X, int Y, TileNode Parent)
 {
     this.X      = X;
     this.Y      = Y;
     this.Parent = Parent;
 }
Exemplo n.º 20
0
        public virtual int getNextPathDirection(int currentTileX, int currentTileY, int desiredTileX, int desiredTileY)
        {
            if (currentTileX == desiredTileX && currentTileY == desiredTileY)
            {
                return(-1);
            }

            if (tileIsOccupied(desiredTileX, desiredTileY))
            {
                //this.x = (x / 32)*32;
                // this.y = (y / 32) * 32;
                return(-1);
            }
            int yTiles = Game1.wallArray.GetLength(0);
            int xTiles = Game1.wallArray.GetLength(1);


            bool[,] visited = new bool[yTiles, xTiles];
            Queue <TileNode> q = new Queue <TileNode>();

            TileNode start = new TileNode(currentTileX, currentTileY);
            TileNode end   = new TileNode(desiredTileX, desiredTileY);

            q.Enqueue(start);
            visited[start.Y, start.X] = true;



            while (q.Count != 0)
            {
                TileNode next = q.Dequeue();
                if (next.X != end.X || next.Y != end.Y)
                {
                    if (next.X + 1 < xTiles && !visited[next.Y, next.X + 1] && !Game1.wallArray[next.Y, next.X + 1] && !tileIsOccupied(next.X + 1, next.Y))
                    {
                        TileNode temp = new TileNode(next.X + 1, next.Y, next);
                        visited[next.Y, next.X + 1] = true;
                        q.Enqueue(temp);
                    }
                    if (next.X - 1 >= 0 && !visited[next.Y, next.X - 1] && !Game1.wallArray[next.Y, next.X - 1] && !tileIsOccupied(next.X - 1, next.Y))
                    {
                        TileNode temp = new TileNode(next.X - 1, next.Y, next);
                        visited[next.Y, next.X - 1] = true;
                        q.Enqueue(temp);
                    }
                    if (next.Y + 1 < yTiles && !visited[next.Y + 1, next.X] && !Game1.wallArray[next.Y + 1, next.X] && !tileIsOccupied(next.X, next.Y + 1))
                    {
                        TileNode temp = new TileNode(next.X, next.Y + 1, next);
                        visited[next.Y + 1, next.X] = true;
                        q.Enqueue(temp);
                    }
                    if (next.Y - 1 >= 0 && !visited[next.Y - 1, next.X] && !Game1.wallArray[next.Y - 1, next.X] && !tileIsOccupied(next.X, next.Y - 1))
                    {
                        TileNode temp = new TileNode(next.X, next.Y - 1, next);
                        visited[next.Y - 1, next.X] = true;
                        q.Enqueue(temp);
                    }
                }
                else
                {
                    while (!next.Parent.Equals(start))
                    {
                        next = (TileNode)next.Parent;
                    }
                    if (next.X < start.X)
                    {
                        return(0);
                    }
                    if (next.X > start.X)
                    {
                        return(2);
                    }
                    if (next.Y < start.Y)
                    {
                        return(1);
                    }
                    if (next.Y > start.Y)
                    {
                        return(3);
                    }
                }
            }
            return(-1);
        }
Exemplo n.º 21
0
        public override VariableFlag.Strategy Think(TileNode currentNode, VariableFlag.Strategy currentStrategy)
        {
            strategy = ChooseMoveStrategy(currentNode, _strategyList, _fallbackStrategy);

            return(strategy);
        }
Exemplo n.º 22
0
 public virtual List <TileNode> FinalTargetTiles(Actor source, TileNode center)
 {
     return(TargetTiles(source, center));
 }
Exemplo n.º 23
0
 public abstract List <TileNode> TargetTiles(Actor source, TileNode center);
Exemplo n.º 24
0
	/// <summary>
	/// Unlink with specified node
	/// </summary>
	public void UnlinkWithNode(TileNode node)
	{
		if (nodeLinks != null && node != null)
		{
			for (int i=0; i<nodeLinks.Length; i++)
			{
				if (nodeLinks[i] == node)
				{
					nodeLinks[i] = null;
					break;
				}
			}
		}

	}
Exemplo n.º 25
0
	/// <summary>
	/// Checks if link with the target node is on or off. See TNELinksOnOffSwitch
	/// </summary>
	public bool LinkIsOnWith(TileNode withNode, TileType forType)
	{
		// first check if provided link is actually a neighbour of this one
		if (!IsDirectNeighbour(withNode)) return false;

		int state = -1;

		// linkOnOffSwitch might not be inited this function is called from editor
		if (linkOnOffSwitch == null)
		{
			linkOnOffSwitch = gameObject.GetComponent<TNELinksOnOffSwitch>();
		}

		// check if the link with the target is on or off
		if (linkOnOffSwitch != null)
		{	// check if link is on with neighbour
			state = linkOnOffSwitch.LinkIsOn(withNode, forType);
		}

		// not found? check if the neighbour is on carrying the link info
		if (state == -1)
		{
			if (withNode.linkOnOffSwitch != null)
			{	// check if link is on from neighbour's side
				state = withNode.linkOnOffSwitch.LinkIsOn(this, forType);
			}
		}

		// default is true, only return false if specifically told that link is off 
		return (state == 0 ? false : true);
	}
Exemplo n.º 26
0
 public static void waterSingleCrop(TileNode v)
 {
     object[] obj = new object[1];
     obj[0] = v;
     waterSingleCrop(obj);
 }
Exemplo n.º 27
0
	public void _ShowNeighboursRecursive(int radius, bool show, TileNode.TileType validNodesLayer, bool inclMoveMod, bool incLinkCheck, ref List<TileNode> closeList)
	{
		this._ShowNeighboursRecursive_Helper = radius;
		closeList.Add(this);
		
		radius--; if (radius < 0) return;
		int r = radius;

		foreach (TileNode node in this.nodeLinks)
		{
			if (node == null) continue;
			if (closeList.Contains(node))
			{
				if (node._ShowNeighboursRecursive_Helper >= radius) continue;
			}

			r = radius;

			if (show == true)
			{
				if (validNodesLayer > 0)
				{
					// only allow one unit per tile?
					if (node.mapnav.oneUnitPerTileOnly && node.units.Count > 0) continue;

					// if validNodesLayer given, then check if this is a valid node according to it mask
					if ((node.tileTypeMask & validNodesLayer) != validNodesLayer) continue;

					// also check if another unit is occupying the same layer, which makes this node invalid
					if (node.GetUnitInLevel(validNodesLayer)) continue;
				}

				// check if movement mod applies
				if (inclMoveMod && node.movesMod != null)
				{
					foreach (TNEMovementModifier.MovementInfo m in node.movesMod.moveInfos)
					{
						if (m.tileType == validNodesLayer) r -= m.movesModifier;
					}
					if (r < 0) continue;
				}

				// check if link possibly off
				if (incLinkCheck)
				{
					if (!this.LinkIsOnWith(node, validNodesLayer)) continue;
				}
			}

			node.Show(show);

			if (r > 0)
			{
				node._ShowNeighboursRecursive(r, show, validNodesLayer, inclMoveMod, incLinkCheck, ref closeList);
			}
		}
	}
Exemplo n.º 28
0
        public static void waterSingleCrop(object obj)
        {
            object[] objArr = (object[])obj;
            TileNode v      = (TileNode)objArr[0];
            bool     moveOn = false;

            foreach (var q in Utilities.tileExceptionList)
            {
                if (q.tile == v && q.actionType == "Water")
                {
                    moveOn = true;
                }
            }
            if (moveOn == false)
            {
                return;
            }

            WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.VK_C);
            int                     xMin      = -1;
            int                     yMin      = -1;
            int                     xMax      = 1;
            int                     yMax      = 1;
            List <TileNode>         miniGoals = new List <TileNode>();
            List <List <TileNode> > paths     = new List <List <TileNode> >();

            //try to set children to tiles where children haven't been before
            for (int x = xMin; x <= xMax; x++)
            {
                for (int y = yMin; y <= yMax; y++)
                {
                    if (x == 0 && y == 0)
                    {
                        continue;
                    }

                    //Include these 4 checks for just left right up down movement. Remove them to enable 8 direction path finding
                    if (x == -1 && y == -1)
                    {
                        continue;                         //upper left
                    }
                    if (x == -1 && y == 1)
                    {
                        continue;                        //bottom left
                    }
                    if (x == 1 && y == -1)
                    {
                        continue;                        //upper right
                    }
                    if (x == 1 && y == 1)
                    {
                        continue;                       //bottom right
                    }
                    Vector2 pos = new Vector2(v.tileLocation.X + x, v.tileLocation.Y + y);
                    //ModCore.CoreMonitor.Log("AHHHHHHH POSITION: " + pos.ToString(), LogLevel.Alert);
                    bool f = PathFindingCore.TileNode.checkIfICanPlaceHere(v, pos * Game1.tileSize, v.thisLocation, true);
                    // ModCore.CoreMonitor.Log("OK THIS IS THE RESULT F: " + f, LogLevel.Alert);
                    if (f == true)
                    {
                        TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.RosyBrown));
                        t.placementAction(Game1.currentLocation, (int)pos.X * Game1.tileSize, (int)pos.Y * Game1.tileSize);
                        //StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode( t, Game1.currentLocation, (int)pos.X * Game1.tileSize, (int)pos.Y * Game1.tileSize));
                        miniGoals.Add(t);
                        Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "CropNavigation"));
                    }
                }
            }
            List <TileNode> removalList = new List <TileNode>();

            foreach (var nav in miniGoals)
            {
                TileNode tempSource = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.RosyBrown));
                tempSource.placementAction(Game1.player.currentLocation, Game1.player.getTileX() * Game1.tileSize, Game1.player.getTileY() * Game1.tileSize);
                //StaardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(tempSource, Game1.currentLocation, Game1.player.getTileX() * Game1.tileSize, Game1.player.getTileY() * Game1.tileSize));
                List <TileNode> path = PathFindingCore.PathFindingLogic.pathFindToSingleGoalReturnPath(tempSource, nav, new List <TileNode>(), true);

                if (path.Count != 0)
                {
                    //ModCore.CoreMonitor.Log("PATH WAS NOT NULL", LogLevel.Warn);
                    paths.Add(path);
                    foreach (var someTile in path)
                    {
                        if (someTile == nav)
                        {
                            removalList.Add(someTile);
                        }
                        StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(someTile);
                        someTile.thisLocation.objects.Remove(someTile.tileLocation);
                        //someTile.performRemoveAction(someTile.tileLocation, someTile.thisLocation);
                        //StardustCore.Utilities.masterRemovalList.Add(someTile);
                        //ModCore.CoreMonitor.Log("CAUGHT MY CULPERATE", LogLevel.Warn);
                    }
                }
            }
            Console.WriteLine("GOALS COUNT:" + miniGoals.Count);
            foreach (var q in removalList)
            {
                StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(q);
                q.thisLocation.objects.Remove(q.tileLocation);
            }
            removalList.Clear();
            int             pathCost    = 999999999;
            List <TileNode> correctPath = new List <TileNode>();

            foreach (var potentialPath in paths)
            {
                if (potentialPath.Count == 0)
                {
                    continue;
                }
                if (potentialPath.Count < pathCost)
                {
                    pathCost    = potentialPath.Count;
                    correctPath = potentialPath;
                }
            }

            foreach (var goodTile in correctPath)
            {
                StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
                //StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(goodTile, Game1.currentLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize));
                goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
            }
            PathFindingLogic.calculateMovement(correctPath);



            if (v.tileLocation.X < Game1.player.getTileX())
            {
                Game1.player.faceDirection(3);
            }
            else if (v.tileLocation.X > Game1.player.getTileX())
            {
                Game1.player.faceDirection(1);
            }
            else if (v.tileLocation.Y < Game1.player.getTileY())
            {
                Game1.player.faceDirection(0);
            }
            else if (v.tileLocation.Y > Game1.player.getTileY())
            {
                Game1.player.faceDirection(2);
            }
            foreach (var item in Game1.player.items)
            {
                if (item is StardewValley.Tools.WateringCan)
                {
                    Game1.player.CurrentToolIndex = Game1.player.getIndexOfInventoryItem(item);
                }
            }
            bool move = false;

            while ((v.thisLocation.terrainFeatures[v.tileLocation] as StardewValley.TerrainFeatures.HoeDirt).state == 0)
            {
                if (WindowsInput.InputSimulator.IsKeyDown(WindowsInput.VirtualKeyCode.VK_C) == false)
                {
                    WindowsInput.InputSimulator.SimulateKeyDown(WindowsInput.VirtualKeyCode.VK_C);
                }

                Vector2 center = new Vector2();
                if (Game1.player.facingDirection == 2)
                {
                    center = Utilities.parseCenterFromTile((int)v.tileLocation.X + 1, (int)v.tileLocation.Y);
                    continue;
                }
                if (Game1.player.facingDirection == 1)
                {
                    center = Utilities.parseCenterFromTile((int)v.tileLocation.X - 1, (int)v.tileLocation.Y);
                    continue;
                }
                if (Game1.player.facingDirection == 0)
                {
                    center = Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y + 1);
                    continue;
                }
                if (Game1.player.facingDirection == 3)
                {
                    center = Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y - 1);
                    continue;
                }
                Game1.player.position = center;


                //Game1.setMousePosition((int)v.tileLocation.X*Game1.tileSize/2,(int)v.tileLocation.Y*Game1.tileSize/2);
                ModCore.CoreMonitor.Log("DOESNT WATER LIKE YOU THINK IT SHOULD");
                ModCore.CoreMonitor.Log("player pos: " + Game1.player.position.ToString(), LogLevel.Warn);
                ModCore.CoreMonitor.Log("TilePos: " + v.position.ToString(), LogLevel.Error);
            }
            Utilities.cleanExceptionList(v);
            StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
            // StardustCore.Utilities.masterRemovalList.Add(v);
            //v.performRemoveAction(v.tileLocation, v.thisLocation);
            v.thisLocation.objects.Remove(v.tileLocation);
            foreach (var goodTile in correctPath)
            {
                StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(goodTile);
                //StardustCore.Utilities.masterRemovalList.Add(v);
                goodTile.performRemoveAction(goodTile.tileLocation, goodTile.thisLocation);
                //goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
            }
            WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.VK_C);
        }
Exemplo n.º 29
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            font      = Content.Load <SpriteFont>(@"sprites\gamefont");
            bigFont   = Content.Load <SpriteFont>(@"sprites\bigfont");
            smallFont = Content.Load <SpriteFont>(@"sprites\smallfont");

            tileSprite = Content.Load <Texture2D>(@"sprites\tile");

            interfaceArea = new Rectangle(
                0 + DISPLAYPADDING,
                0 + DISPLAYPADDING,
                GraphicsDevice.Viewport.Width - (DISPLAYPADDING * 2),
                INTERFACEHEIGHT - (DISPLAYPADDING * 2));

            playArea = new Rectangle(
                0 + DISPLAYPADDING,
                INTERFACEHEIGHT + DISPLAYPADDING,
                GraphicsDevice.Viewport.Width - (DISPLAYPADDING * 2),
                GraphicsDevice.Viewport.Height - (interfaceArea.Height) - (DISPLAYPADDING * 4)
                );


            // Create our clickable tile board
            int tileWidth  = playArea.Width / BOARDWIDTH;
            int tileHeight = playArea.Height / BOARDHEIGHT;

            tileNodes   = new TileNode[BOARDWIDTH, BOARDHEIGHT];
            tileButtons = new TileButton[BOARDWIDTH, BOARDHEIGHT];

            for (int yi = 0; yi < tileButtons.GetLength(1); yi++)
            {
                for (int xi = 0; xi < tileButtons.GetLength(0); xi++)
                {
                    // Create our tilenodes
                    tileNodes[xi, yi] = new TileNode(xi, yi);

                    // And create TileButtons
                    tileButtons[xi, yi] = new TileButton(
                        new Rectangle(
                            (xi * tileWidth) + playArea.Left + BUTTONMARGIN,
                            (yi * tileHeight) + playArea.Top + BUTTONMARGIN,
                            tileWidth - BUTTONMARGIN,
                            tileHeight - BUTTONMARGIN
                            ),
                        tileSprite,
                        tileNodes[xi, yi]
                        );
                }
            }

            // Now connect all of our tileNodes to each other
            for (int yi = 0; yi < tileNodes.GetLength(1); yi++)
            {
                for (int xi = 0; xi < tileNodes.GetLength(0); xi++)
                {
                    if (yi > 0)
                    {
                        tileNodes[xi, yi].Up = tileNodes[xi, yi - 1];
                    }
                    if (yi < tileNodes.GetLength(1) - 1)
                    {
                        tileNodes[xi, yi].Down = tileNodes[xi, yi + 1];
                    }
                    if (xi > 0)
                    {
                        tileNodes[xi, yi].Left = tileNodes[xi - 1, yi];
                    }
                    if (xi < tileNodes.GetLength(0) - 1)
                    {
                        tileNodes[xi, yi].Right = tileNodes[xi + 1, yi];
                    }
                }
            }
            Console.WriteLine();
        }
Exemplo n.º 30
0
    /// <summary>
    /// Returns a set of tile nodes that this tower can legally move to
    /// </summary>
    /// <returns></returns>
    public MoveSet GetMoves()
    {
        MoveSet moves = new MoveSet();

        foreach (PieceData curPiece in pieces)
        {
            // hook alone does not make a move
            if (curPiece.type == PieceData.Type.Hook)
            {
                continue;
            }

            // start from tower's position
            TileNode cur = node;

            #region moving off way check
            // must move to new way or off current way if on way (standard way)
            if (node.type == TileNode.Type.Way)
            {
                if (cur.adjacent[curPiece.direction] == null)
                {
                    continue;
                }

                // same line
                if (node.adjacent[curPiece.direction].wayLine == node.wayLine || node.adjacent[curPiece.direction].type == TileNode.Type.WayCross)
                {
                    continue;
                }
            }

            // must move to new way or off current way if on way (intersection)
            if (node.type == TileNode.Type.WayCross)
            {
                if (cur.adjacent[curPiece.direction] == null)
                {
                    continue;
                }

                // same line
                if (node.adjacent[curPiece.direction].type == TileNode.Type.Way)
                {
                    continue;
                }
            }
            #endregion

            #region normal move with range
            // extend out by the range and search for more.
            SearchNormalMoves(curPiece, moves);

            // reverse hook
            if (hook != null && pieces.Count == 6)
            {
                SearchReverseHookMoves(curPiece, moves);
            }
            #endregion
        }

        return(moves);
    }
Exemplo n.º 31
0
 /// <summary>
 /// Returns the piece to be moved and the destination
 /// </summary>
 /// <param name="piece">Piece.</param>
 /// <param name="dest">Destination.</param>
 public WeightedMove Move(PieceTower piece, TileNode dest)
 {
     return(new WeightedMove(piece, dest, 1));
 }
Exemplo n.º 32
0
    void Update()
    {
        if (isMovingUnit)
        {
            moveTime += Time.deltaTime * 2.6f;

            if (moveTime >= 1f)
            {
                movingUnit.body.transform.position                  = moveDest.GetPos();
                movingUnit.body.transform.GetChild(0).rotation      = movingUnit.GetFaceRotation();
                movingUnit.body.transform.GetChild(0).localPosition = 0.8f * Vector3.up;
                movingUnit.SetPosKey(moveDest.GetKey());

                if (movingPath.Count == 0)
                {
                    isMovingUnit = false;
                }
                else
                {
                    moveSrc  = moveDest;
                    moveDest = movingPath[0];
                    movingPath.RemoveAt(0);
                    moveTime = 0f;

                    Vector3    moveDir = (moveDest.GetPos() - moveSrc.GetPos()).normalized;
                    Vector2Int faceDir = new Vector2Int(Mathf.RoundToInt(moveDir.x), Mathf.RoundToInt(moveDir.z));
                    movingUnit.SetFaceDirection(faceDir);
                }
            }
            else
            {
                // Vector3 pos = moveSrc.GetPos() * (1 - moveTime) + moveDest.GetPos() * moveTime;
                // movingUnit.body.transform.position = pos;

                Vector3 moveDir = (moveDest.GetPos() - moveSrc.GetPos()).normalized;

                float stepSize = 1f / 4f;

                float stepTime = Mathf.FloorToInt(moveTime / stepSize) * stepSize;
                // stepTime = moveTime;
                float   rotAngle = stepTime * 360;
                Vector3 rotVec   = Vector3.Cross(Vector3.up, Vector3.forward);
                Vector3 pos      = moveSrc.GetPos() * (1 - stepTime) + moveDest.GetPos() * stepTime;
                movingUnit.body.transform.position                  = pos;
                movingUnit.body.transform.GetChild(0).rotation      = movingUnit.GetFaceRotation() * Quaternion.AngleAxis(rotAngle, rotVec);
                movingUnit.body.transform.GetChild(0).localPosition = (Mathf.Abs(Mathf.Cos(rotAngle * Mathf.Deg2Rad)) * 0.4f + 0.4f) * Vector3.up;

                // movingUnit.SetPosKey(moveDest.GetKey());
            }
        }

        if (isControllingUnit)
        {
            controlTime += Time.deltaTime;

            if (currentUnit.unit.apCur == 2 && controlTime >= 1f)
            {
                HashSet <TileNode> targets = GetMoveTiles(currentUnit);
                TileNode           end     = targets.ToArray()[UnityEngine.Random.Range(0, targets.Count)];
                List <TileNode>    path    = GetMovePath(currentUnit, end);
                MoveUnit(currentUnit, path);
                controlTime -= 1f;
            }

            if (currentUnit.unit.apCur == 1 && !isMovingUnit && controlTime >= 1f)
            {
                List <Action> actions = currentUnit.unit.actions;
                Action        action  = actions[UnityEngine.Random.Range(0, actions.Count)];

                HashSet <TileNode> targets = action.GetSelectionTiles(currentUnit, this);

                if (action.GetActionType() == ActionType.Targeted)
                {
                    TileNode target = targets.ToArray()[UnityEngine.Random.Range(0, targets.Count)];
                    ActUnit(currentUnit, action, target);
                }

                if (action.GetActionType() == ActionType.Fixed)
                {
                    List <TileNode> target = new List <TileNode>(targets.ToArray());
                    ActUnit(currentUnit, action, target);
                }

                controlTime -= 1f;
            }

            if (currentUnit.unit.apCur == 0 && !isActingUnit && controlTime >= 1f)
            {
                isControllingUnit = false;
                controlTime      -= 1f;
            }
        }
    }
Exemplo n.º 33
0
 // Update our g() value, since it may change during the run
 public void updateStats(TileNode src)
 {
     DisplayStats = true;
     _g           = getManhattanDistance(src);
 }
 public ChangeTileEffectCombatNode(string newTileType, Actor source, TileNode targetedTile) : base(source, targetedTile)
 {
     this.newTileType = newTileType;
 }
Exemplo n.º 35
0
    private void GenerateGraphFromGameObject()
    {
        tileDict  = new Dictionary <Vector2Int, TileNode>();
        spawnDict = new Dictionary <Vector2Int, int>();

        // Add nodes from gameObject children
        foreach (Transform child in transform)
        {
            BattleGridMarker marker = child.gameObject.GetComponent <BattleGridMarker>();
            Vector3          v      = child.position;

            // If marker, add as special
            if (marker)
            {
                switch (marker.type)
                {
                case MarkerType.Spawn:
                    spawnDict.Add(Vector3ToKey(v), marker.val);
                    break;

                default:
                    Debug.Log("Should not reach here");
                    break;
                }

                child.gameObject.SetActive(false);
                continue;
            }

            // Else, add as tile
            TileNode node = new TileNode(v);
            tileDict.Add(node.GetKey(), node);

            // Update boundaries
            xMin = Mathf.Min(xMin, v.x - 0.45f);
            xMax = Mathf.Max(xMax, v.x + 0.45f);
            zMin = Mathf.Min(zMin, v.z - 0.45f);
            zMax = Mathf.Max(zMax, v.z + 0.45f);
        }

        // Add edges for all adjacent nodes
        foreach (KeyValuePair <Vector2Int, TileNode> entry in tileDict)
        {
            Vector2Int k = entry.Key;
            TileNode   n = entry.Value;

            for (int i = k.x - 1; i <= k.x + 1; i++)
            {
                for (int j = k.y - 1; j <= k.y + 1; j++)
                {
                    if (i == k.x && j == k.y)
                    {
                        continue;
                    }

                    Vector2Int t = new Vector2Int(i, j);

                    if (!tileDict.ContainsKey(t))
                    {
                        continue;
                    }

                    float w = (n.GetPos() - tileDict[t].GetPos()).magnitude;
                    w = Mathf.RoundToInt(w * 10) / 10f;
                    n.AddNeighbor(tileDict[t], w);
                }
            }
        }

        // Debug printing

        /*
         * foreach (KeyValuePair<Vector2Int, TileNode> entry in tileDict) {
         * Debug.Log(entry.Value);
         * }
         * foreach (KeyValuePair<Vector2Int, int> entry in spawnDict) {
         * Debug.Log(entry.Value);
         * }
         */
    }
Exemplo n.º 36
0
        public static void recalculateTask(ref CustomTask v)
        {
            object[] oArray = (object[])v.objectParameterDataArray;
            //  ModCore.CoreMonitor.Log("RECALCULATING: "+ v.taskMetaData.name);

            if (v.taskMetaData.name.Contains("Path to "))
            {
                Utilities.tileExceptionList.Clear();
                // ModCore.CoreMonitor.Log("POKE DEW VALLEY: " + v.taskMetaData.name);
                string[] s = v.taskMetaData.name.Split(' ');
                ModCore.CoreMonitor.Log(s.ElementAt(s.Length - 1));
                List <List <TileNode> > newPaths = new List <List <TileNode> >();
                newPaths            = TaskCore.MapTransitionLogic.WarpGoal.getWarpChainReturn(Game1.player.currentLocation, s.ElementAt(s.Length - 1));
                v.taskMetaData.cost = 0;
                int value = 0;
                foreach (var path in newPaths)
                {
                    value += (path.Count * TaskMetaDataHeuristics.pathCostMultiplier);
                }
                object[] arr = (object[])v.objectParameterDataArray;
                arr[3] = newPaths;
                v.taskMetaData.cost        = value;
                v.taskMetaData.pathsToTake = newPaths;
                //ModCore.CoreMonitor.Log("IDK ANY MORE: " + v.taskMetaData.cost);
                return;
            }
            Utilities.tileExceptionList.Clear();
            try
            {
                Utilities.tileExceptionList.Clear();
                TileNode t = (TileNode)oArray[0];
                Utilities.tileExceptionList.Clear();
                //ModCore.CoreMonitor.Log("Premtive calculate 1");
                //ModCore.CoreMonitor.Log("Valaue before???:" + v.taskMetaData.pathsToTake[0].Count);
                v.taskMetaData.calculateTaskCost(t, false);
                //v.taskMetaData.pathsToTake = new List<List<TileNode>>();
                //v.taskMetaData.pathsToTake.Add(StarAI.PathFindingCore.Utilities.getIdealPath(v));


                object[] objArr = new object[10];
                objArr[0] = (object)t;
                objArr[1] = (object)v.taskMetaData.pathsToTake[0];
                //ModCore.CoreMonitor.Log("HMM SO WHAT'S HAPPENING???:" + v.taskMetaData.pathsToTake[0].Count);
                int malcolm = 0;
                objArr[2] = (object)v.taskMetaData.pathsToTake[0].ElementAt(malcolm); //source of whatever is hit.
                try
                {
                    objArr[3] = oArray[3];
                }
                catch (Exception err2)
                {
                }
                try
                {
                    objArr[4] = oArray[4];
                }
                catch (Exception err2)
                {
                }
                try
                {
                    objArr[5] = oArray[5];
                }
                catch (Exception err2)
                {
                }
                v.objectParameterDataArray = objArr;
                return;
            }
            catch (Exception err)
            {
            }

            try
            {
                Utilities.tileExceptionList.Clear();
                List <TileNode> t = (List <TileNode>)oArray[0];
                // ModCore.CoreMonitor.Log("Premtive calculate 2");
                foreach (var s in Utilities.tileExceptionList)
                {
                    ModCore.CoreMonitor.Log(s.actionType);
                }
                v.taskMetaData.calculateTaskCost(t, false);
                object[] objArr = new object[10];
                objArr[0] = (object)t;                             //List of trees to use for path calculations
                objArr[1] = (object)v.taskMetaData.pathsToTake[0]; //The path itself.
                int malcolm = 0;
                // ModCore.CoreMonitor.Log("THIS IS MALCOLM:" + malcolm);
                objArr[2] = (object)v.taskMetaData.pathsToTake[0].ElementAt(malcolm); //source of whatever is hit.
                try
                {
                    objArr[3] = oArray[3];
                }
                catch (Exception err2)
                {
                }
                try
                {
                    objArr[4] = oArray[4];
                }
                catch (Exception err2)
                {
                }
                try
                {
                    objArr[5] = oArray[5];
                }
                catch (Exception err2)
                {
                }
                v.objectParameterDataArray = objArr;
                Utilities.tileExceptionList.Clear();
                return;
            }
            catch (Exception err)
            {
            }

            try
            {
                Utilities.tileExceptionList.Clear();
                List <List <TileNode> > t = (List <List <TileNode> >)oArray[3];
                // ModCore.CoreMonitor.Log("Premtive calculate 3");
                foreach (var s in Utilities.tileExceptionList)
                {
                    ModCore.CoreMonitor.Log(s.actionType);
                }
                v.taskMetaData.calculateTaskCost(t, false);
                object[] objArr = new object[10];
                objArr[0] = (object)t;                          //List of trees to use for path calculations
                objArr[1] = (object)v.taskMetaData.pathsToTake; //The path itself.
                int malcolm = 0;
                // ModCore.CoreMonitor.Log("THIS IS MALCOLM:" + malcolm);
                objArr[2] = (object)v.taskMetaData.pathsToTake[0].ElementAt(malcolm); //source of whatever is hit.
                try
                {
                    objArr[3] = oArray[3];
                }
                catch (Exception err2)
                {
                }
                try
                {
                    objArr[4] = oArray[4];
                }
                catch (Exception err2)
                {
                }
                try
                {
                    objArr[5] = oArray[5];
                }
                catch (Exception err2)
                {
                }
                v.objectParameterDataArray = objArr;
                Utilities.tileExceptionList.Clear();
                return;
            }
            catch (Exception err)
            {
            }
        }
Exemplo n.º 37
0
        public static void pathToSingleChest(object obj)
        {
            object[] objArray = (object[])obj;

            TileNode v = (TileNode)objArray[0];
            //List<TileNode> correctPath = Utilities.pathStuff(v);//(List<TileNode>)objArray[1];
            List <TileNode> correctPath = (List <TileNode>)objArray[1];

            foreach (var goodTile in correctPath)
            {
                StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
                //StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(goodTile, Game1.currentLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize));
                goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
            }
            PathFindingLogic.calculateMovement(correctPath);
            if (v.tileLocation.X < Game1.player.getTileX())
            {
                Game1.player.faceDirection(3);
            }
            else if (v.tileLocation.X > Game1.player.getTileX())
            {
                Game1.player.faceDirection(1);
            }
            else if (v.tileLocation.Y < Game1.player.getTileY())
            {
                Game1.player.faceDirection(0);
            }
            else if (v.tileLocation.Y > Game1.player.getTileY())
            {
                Game1.player.faceDirection(2);
            }

            bool        move             = false;
            Chest       chest            = (Chest)v.thisLocation.objects[v.tileLocation];
            List <Item> removalListSeeds = new List <Item>();

            //Try to grab all the seeds I can from the chest.
            while (Game1.player.isInventoryFull() == false && chest.items.Count > 0)
            {
                if (chest.giftbox)
                {
                    ModCore.CoreMonitor.Log("GIFT BOX", LogLevel.Warn);
                    v.thisLocation.objects.Remove(v.tileLocation);
                }
                foreach (var item in chest.items)
                {
                    if (item.getCategoryName() == "Seed")
                    {
                        int seedIndex = item.parentSheetIndex;

                        if (seedIndex == 770)
                        {
                            seedIndex = Crop.getRandomLowGradeCropForThisSeason(Game1.currentSeason);
                            if (seedIndex == 473)
                            {
                                --seedIndex;
                            }
                        }

                        StardewValley.Crop c = new Crop(seedIndex, 0, 0);

                        if (c.seasonsToGrowIn.Contains(Game1.currentSeason))
                        {
                            Game1.player.addItemByMenuIfNecessary(item);
                            removalListSeeds.Add(item);
                            break;
                        }
                    }
                }


                foreach (var remove in removalListSeeds)
                {
                    chest.items.Remove(remove);
                }
                // if (WindowsInput.InputSimulator.IsKeyDown(WindowsInput.VirtualKeyCode.VK_C) == false) WindowsInput.InputSimulator.SimulateKeyDown(WindowsInput.VirtualKeyCode.VK_C);



                Vector2 center = new Vector2();
                if (Game1.player.facingDirection == 2)
                {
                    center = Utilities.parseCenterFromTile((int)v.tileLocation.X + 1, (int)v.tileLocation.Y);
                    continue;
                }
                if (Game1.player.facingDirection == 1)
                {
                    center = Utilities.parseCenterFromTile((int)v.tileLocation.X - 1, (int)v.tileLocation.Y);
                    continue;
                }
                if (Game1.player.facingDirection == 0)
                {
                    center = Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y + 1);
                    continue;
                }
                if (Game1.player.facingDirection == 3)
                {
                    center = Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y - 1);
                    continue;
                }
                Game1.player.position = center;
            }
            Utilities.cleanExceptionList(v);
            StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
            // StardustCore.Utilities.masterRemovalList.Add(v);
            //v.performRemoveAction(v.tileLocation, v.thisLocation);
            // v.thisLocation.objects.Remove(v.tileLocation);
            foreach (var goodTile in correctPath)
            {
                StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(goodTile);
                //StardustCore.Utilities.masterRemovalList.Add(v);
                goodTile.performRemoveAction(goodTile.tileLocation, goodTile.thisLocation);
                //goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
            }
            //WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.VK_C);
        }
Exemplo n.º 38
0
    public HashSet <TileNode> GetMoveTiles(BattleUnit bu)
    {
        // Use Dijkstra's alg to get tiles in range
        float move = bu.unit.move;
        float jump = bu.unit.jump;

        // Return set
        HashSet <TileNode> visited = new HashSet <TileNode>();

        // Initial collection values
        List <TileNode> queue = new List <TileNode>();
        Dictionary <TileNode, TileNode> previous  = new Dictionary <TileNode, TileNode>();
        Dictionary <TileNode, float>    distances = new Dictionary <TileNode, float>();

        foreach (TileNode node in tileDict.Values)
        {
            distances.Add(node, float.MaxValue);
        }

        distances[tileDict[bu.GetPosKey()]] = 0f;
        queue.Add(tileDict[bu.GetPosKey()]);

        // Start search
        while (queue.Count != 0)
        {
            queue = queue.OrderBy(node => distances[node]).ToList();
            TileNode current = queue[0];
            queue.RemoveAt(0);
            visited.Add(current);

            float baseDist   = distances[current];
            float baseHeight = current.GetPos().y;

            foreach (TileEdge edge in current.edges)
            {
                float    edgeDist = baseDist + edge.GetWeight();
                TileNode node     = edge.GetNode();
                float    height   = Mathf.Abs(node.GetPos().y - baseHeight);

                // Unit blocking
                BattleUnit blockingUnit = GetUnit(node.GetPos());
                bool       blocked      = (blockingUnit != null && blockingUnit.team != bu.team);

                if (edgeDist <= move && edgeDist <= distances[node] && height <= jump && !blocked)
                {
                    if (!previous.ContainsKey(node))
                    {
                        queue.Add(node);
                    }

                    previous[node]  = current;
                    distances[node] = edgeDist;
                }
            }
        }

        // Remove units and return
        foreach (BattleUnit unit in units)
        {
            visited.Remove(tileDict[unit.GetPosKey()]);
        }

        return(visited);
    }
Exemplo n.º 39
0
    public List <TileNode> GetMovePath(BattleUnit bu, TileNode end)
    {
        // Use Dijkstra's alg to get tiles in range
        float move = bu.unit.move;
        float jump = bu.unit.jump;

        // Initial collection values
        List <TileNode> queue = new List <TileNode>();
        Dictionary <TileNode, TileNode> previous  = new Dictionary <TileNode, TileNode>();
        Dictionary <TileNode, float>    distances = new Dictionary <TileNode, float>();

        foreach (TileNode node in tileDict.Values)
        {
            distances.Add(node, float.MaxValue);
        }

        distances[tileDict[bu.GetPosKey()]] = 0f;
        queue.Add(tileDict[bu.GetPosKey()]);

        // Start search
        while (queue.Count != 0)
        {
            queue = queue.OrderBy(node => distances[node]).ToList();
            TileNode current = queue[0];
            queue.RemoveAt(0);

            // Exit search when hit end
            if (current == end)
            {
                break;
            }

            float baseDist   = distances[current];
            float baseHeight = current.GetPos().y;

            foreach (TileEdge edge in current.edges)
            {
                float    edgeDist = baseDist + edge.GetWeight();
                TileNode node     = edge.GetNode();
                float    height   = Mathf.Abs(node.GetPos().y - baseHeight);

                // Unit blocking
                BattleUnit blockingUnit = GetUnit(node.GetPos());
                bool       blocked      = (blockingUnit != null && blockingUnit.team != bu.team);

                if (edgeDist <= move && edgeDist <= distances[node] && height <= jump && !blocked)
                {
                    if (!previous.ContainsKey(node))
                    {
                        queue.Add(node);
                    }

                    previous[node]  = current;
                    distances[node] = edgeDist;
                }
            }
        }

        // Remove initial and return
        List <TileNode> path  = new List <TileNode>();
        TileNode        start = tileDict[bu.GetPosKey()];
        TileNode        prev  = end;

        while (prev != start)
        {
            path.Insert(0, prev);
            prev = previous[prev];
        }

        path.Insert(0, start);
        return(path);
    }
Exemplo n.º 40
0
 public HashSet <TileNode> GetRangeTiles(TileNode center, float range)
 {
     return(GetRangeTiles(center, range, false, true));
 }
Exemplo n.º 41
0
	/// <summary>
	/// Counts the distance from this node to the target node, using the layout linking as guideline on how to count.
	/// Similar to calculating the path to the target, ignoring obstacles, and taking that distance. Returns 0 on error.
	/// </summary>
	public int TileCountTo(TileNode targetNode)
	{
		TileNode[] path = mapnav.GetPath(this, targetNode);
		if (path == null) return 0;
		return path.Length;
	}
Exemplo n.º 42
0
        public static void goToAdjacentWarpGoal(object obj)
        {
            object[] objArray = (object[])obj;

            TileNode        v            = (TileNode)objArray[2];
            string          locationName = (string)objArray[3];
            List <TileNode> correctPath  = (List <TileNode>)objArray[1];

            foreach (var goodTile in correctPath)
            {
                StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
                goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
            }
            PathFindingLogic.calculateMovement(correctPath);
            Vector2 tileLocation = v.tileLocation;

            for (int i = -1; i <= 1; i++)
            {
                for (int j = -1; j <= 1; j++)
                {
                    foreach (var warp in v.thisLocation.warps)
                    {
                        if (warp.X == Game1.player.getTileX() + i && warp.Y == Game1.player.getTileY() + j)
                        {
                            Game1.warpFarmer(warp.TargetName, warp.TargetX, warp.TargetY, false);
                        }
                    }
                }
            }

            /*
             * if (Game1.player.facingDirection == 2)
             * {
             *  if (InputSimulator.IsKeyDown(VirtualKeyCode.VK_S) == false) InputSimulator.SimulateKeyDown(VirtualKeyCode.VK_S);
             * }
             * if (Game1.player.facingDirection == 1)
             * {
             *  if (InputSimulator.IsKeyDown(VirtualKeyCode.VK_D) == false) InputSimulator.SimulateKeyDown(VirtualKeyCode.VK_D);
             * }
             * if (Game1.player.facingDirection == 0)
             * {
             *  if (InputSimulator.IsKeyDown(VirtualKeyCode.VK_W) == false) InputSimulator.SimulateKeyDown(VirtualKeyCode.VK_W);
             *
             * }
             * if (Game1.player.facingDirection == 3)
             * {
             *  if (InputSimulator.IsKeyDown(VirtualKeyCode.VK_A) == false) InputSimulator.SimulateKeyDown(VirtualKeyCode.VK_A);
             * }
             *
             *
             * InputSimulator.SimulateKeyUp(VirtualKeyCode.VK_W);
             * InputSimulator.SimulateKeyUp(VirtualKeyCode.VK_A);
             * InputSimulator.SimulateKeyUp(VirtualKeyCode.VK_S);
             * InputSimulator.SimulateKeyUp(VirtualKeyCode.VK_D);
             */
            //ModCore.CoreMonitor.Log(tileLocation.ToString());
            //if(v.thisLocation.isTerrainFeatureAt)

            Utilities.cleanExceptionList(v);
            StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
            foreach (var goodTile in correctPath)
            {
                StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(goodTile);
                goodTile.performRemoveAction(goodTile.tileLocation, goodTile.thisLocation);
            }
        }
Exemplo n.º 43
0
	/// <summary>
	/// returns true if withNode is a direct neighbour of this node (linked in nodeLinks)
	/// </summary>
	public bool IsDirectNeighbour(TileNode withNode)
	{
		foreach (TileNode n in nodeLinks)
		{
			if (n == withNode) return true;
		}
		return false;
	}
Exemplo n.º 44
0
 public int getManhattanDistance(TileNode dest)
 {
     return(getManhattanDistance(dest, this));
 }
Exemplo n.º 45
0
	/// <summary>
	/// Set the link withNode on or off. Returns false if operation could not be completed, 
	/// for example withNode was not a neighbour of this node
	/// </summary>
	public bool SetLinkState(TileNode withNode, bool on)
	{
		if (!IsDirectNeighbour(withNode)) return false;

		bool needToAdd = false;
		if (linkOnOffSwitch != null)
		{
			linkOnOffSwitch.SetLinkStateWith(withNode, on);
			needToAdd = false;
		}
		
		// check if neighbour might carry a link back to this node, and update
		if (withNode.linkOnOffSwitch != null)
		{
			withNode.linkOnOffSwitch.SetLinkStateWith(this, on);
			needToAdd = false;
		}

		// if none had link info, then add it now
		if (needToAdd)
		{
			linkOnOffSwitch = gameObject.AddComponent<TNELinksOnOffSwitch>();
			linkOnOffSwitch.SetLinkStateWith(withNode, on);
		}

		return true;
	}
Exemplo n.º 46
0
 /// <summary>return a list if nodes that can be used to reach the target node.</summary>
 public TileNode[] GetPathTo(TileNode targetNode)
 {
     return mapnav.GetPath(this.node, targetNode, this.tileLevel);
 }
Exemplo n.º 47
0
	private void _GetAllInRangeRecursive(int radius, TileNode.TileType validNodesLayer, bool checkIfUnitInWay, bool inclMoveMod, bool incLinkCheck, ref List<TileNode> helper, ref List<TileNode> retNodes)
	{
		this._ShowNeighboursRecursive_Helper = radius;
		helper.Add(this);

		radius--; if (radius < 0) return;
		int r = radius;

		foreach (TileNode node in this.nodeLinks)
		{
			if (node == null) continue;
			if (helper.Contains(node))
			{
				if (node._ShowNeighboursRecursive_Helper >= radius) continue;
			}

			r = radius;

			if (validNodesLayer > 0)
			{
				// check if this is a valid node according to its mask
				if ((node.tileTypeMask & validNodesLayer) != validNodesLayer) continue;

				if (checkIfUnitInWay)
				{
					// only allow one unit per tile?
					if (node.mapnav.oneUnitPerTileOnly && node.units.Count > 0) continue;

					// also check if another unit is occupying the same layer, which makes this node invalid
					if (node.GetUnitInLevel(validNodesLayer)) continue;
				}
			}

			// check if movement mod applies
			if (inclMoveMod && node.movesMod != null)
			{
				foreach (TNEMovementModifier.MovementInfo m in node.movesMod.moveInfos)
				{
					if (m.tileType == validNodesLayer) r -= m.movesModifier;
				}
				if (r < 0) continue;
			}

			// check if link possibly off
			if (incLinkCheck)
			{
				if (!this.LinkIsOnWith(node, validNodesLayer)) continue;
			}

			// this node seems fine, incl in return list
			retNodes.Add(node);

			// on to the next
			if (r > 0)
			{
				node._GetAllInRangeRecursive(r, validNodesLayer, checkIfUnitInWay, inclMoveMod, incLinkCheck, ref helper, ref retNodes);
			}
		}
	}
Exemplo n.º 48
0
    /// <summary>
    /// Move the unit to the specified target node. Will make a callback with 
    /// eventCode=1 when done moving if a callback was set in Init()
    /// iTween (free on Unity Asset Store) is used to move the Unit
    /// </summary>
    /// <param name="map">NavMap to use</param>
    /// <param name="targetNode">Node to reach</param>
    /// <param name="moves">
    /// Number of moves that can be use to reach target. Pass (-1) to ignore move limits. 
    /// The unit will move as close as possible if not enough moves given.
    /// ref moves = (moves - actual_moves_use) on return (thus moves left); or if moves = -1 passed, it will be set to number of moves that will be taken.
    /// </param>
    /// <returns>True if the unit started moving towards the target</returns>
    public bool MoveTo(TileNode targetNode, ref int moves)
    {
        if (isMoving) StopMoving();		// first stop current movement
        if (moves == 0) return false;	// could not move

        followPath = mapnav.GetPath(this.node, targetNode, this.tileLevel);
        if (followPath == null) { if (moves == -1)moves = 0; return false; }
        if (followPath.Length == 0) { if (moves == -1)moves = 0; return false; }

        // check if enough moves to reach destination
        followMaxMoves = followPath.Length;
        if (moves == -1)
        {
            moves = followMaxMoves;
        }
        else
        {
            if (moves >= 0)
            {
                if (moves <= followMaxMoves) { followMaxMoves = moves; moves = 0; }
                else moves -= followMaxMoves;
            }
            else moves = followPath.Length;
        }

        _StartMoving();

        return true;
    }
Exemplo n.º 49
0
	public void SetPathParent(TileNode parent, int g, int h)
	{
		pathParent = parent;
		PathG = g;
		PathH = h;
		PathF = g + h;
	}
Exemplo n.º 50
0
    private void _GotoNextNode()
    {
        if (followIdx < followMaxMoves)
        {
            // first check if nothing in way of moving to the next node
            bool isFine = true;
            if (followPath[followIdx].units.Count > 0)
            {
                // allow only one unit per tile?
                if (mapnav.oneUnitPerTileOnly)
                {
                    if (!mapnav.oneUnitExceptionAllowMoveOver) isFine = false;
                }

                if (isFine)
                {
                    // now check if another unit is occupying the same layer/level on the node
                    if (followPath[followIdx].GetUnitInLevel(tileLevel) != null) isFine = false;
                }
            }

            if (!isFine)
            {
                // will wait a bit and then try to move again
                isDelayed = true;
                delayTimer = 0.1f;
                OnMovementDelayed();
                return;
            }

            // unlink with current node and link with destination node
            node.units.Remove(this);
            node = followPath[followIdx];
            node.units.Add(this);

            this.mapnav = node.mapnav; // make sure this unit uses same mapnav as new node, just incase it moved onto new map

            // move unit with iTween
            if (jumpMovement)
            {
                endPointToReach = followPath[followIdx].transform.position;
                float dist = Vector3.Distance(_tr.position, endPointToReach);
                Vector3[] points = new Vector3[3];
                points[0] = _tr.position;
                points[1] = Vector3.MoveTowards(points[0], endPointToReach, dist / 2f);
                float h = Mathf.Abs(points[0].y - endPointToReach.y) * 2f;
                if (h <= 0.01f) h = dist / 2f;
                points[1].y += h;
                points[2] = endPointToReach;

                iTweenOpt["path"] = points;
                iTween.MoveTo(this.gameObject, iTweenOpt);
            }
            else
            {
                iTweenOpt["position"] = followPath[followIdx].transform.position;
                iTween.MoveTo(this.gameObject, iTweenOpt);
            }

            // set next node that will be moved to
            followIdx++;
        }
        else
        {	// done
            StopMoving();
            if (onUnitEvent != null) onUnitEvent(this, 1);
        }
    }
Exemplo n.º 51
0
 public static void RemoveUnit(GameObject unitFab, TileNode targetNode)
 {
     if (targetNode != null)
         targetNode.units.RemoveAt(0);
     Destroy(GameObject.Find(unitFab.name));
 }
Exemplo n.º 52
0
 public TileButton(Rectangle _screenLocation, Texture2D _tile, TileNode _tileNode)
 {
     this._screenLocation = _screenLocation;
     this._tile           = _tile;
     this._tileNode       = _tileNode;
 }
Exemplo n.º 53
0
    /// <summary>
    /// checks if unit can stand on the target node
    /// </summary>
    /// <param name="andLevelIsOpen">also check if there is a unit in the way?</param>
    public bool CanStandOn(TileNode targetNode, bool andLevelIsOpen)
    {
        if (targetNode == null) return false;

        // can this unit move onto a lvel on this tile?
        if ((targetNode.tileTypeMask & this.tileLevel) == this.tileLevel)
        {
            // check if there might be unit in the way on target tile?
            if (andLevelIsOpen)
            {
                // success if there is not a unit standing in same level on target tilenode
                if (targetNode.GetUnitInLevel(this.tileLevel) == null) return true;
            }
            else
            {
                return true;
            }
        }

        // fail
        return false;
    }
Exemplo n.º 54
0
    public override List <TileNode> TargetTiles(Actor source, TileNode center)
    {
        int tempX, tempY, x, y;

        int StartX = source.GetPosX() - center.data.posX;
        int StartY = source.GetPosY() - center.data.posY;

        x = center.data.posX;
        y = center.data.posY;



        List <TileNode>    nodes   = new List <TileNode>();
        BoardManager       bm      = Globals.GetBoardManager();
        HashSet <TileNode> visited = new HashSet <TileNode>();

        Queue <TileNode> nodeQueue = new Queue <TileNode>();

        nodeQueue.Enqueue(center);


        while (nodeQueue.Count > 0)
        {
            TileNode currNode = nodeQueue.Dequeue();

            if (((Mathf.Abs(currNode.data.posX - x) > raidus) || (Mathf.Abs(currNode.data.posY - y)) > raidus) == false)
            {
                if (IsTileValid(currNode))
                {
                    nodes.Add(currNode);

                    tempX = currNode.data.posX;
                    tempY = currNode.data.posY;


                    if (
                        Mathf.Abs(Mathf.Abs(Mathf.Abs(x) - Mathf.Abs(source.GetPosX()))) ==
                        Mathf.Abs(Mathf.Abs(Mathf.Abs(y) - Mathf.Abs(source.GetPosY())))
                        )
                    {
                        if (ValidTile(x, y, tempX, tempY))
                        {
                            if (StartX < 0 && StartY < 0)
                            {
                                //top right
                                AddToQueue(nodeQueue, visited, tempX + 0, tempY + 1);
                                AddToQueue(nodeQueue, visited, tempX + 1, tempY + 0);
                            }
                            else if (StartX > 0 && StartY < 0)
                            {
                                AddToQueue(nodeQueue, visited, tempX + 0, tempY + 1);
                                AddToQueue(nodeQueue, visited, tempX - 1, tempY + 0);
                            }
                            else if (StartX > 0 && StartY > 0)
                            {
                                AddToQueue(nodeQueue, visited, tempX + 0, tempY - 1);
                                AddToQueue(nodeQueue, visited, tempX - 1, tempY + 0);
                            }
                            else if (StartX < 0 && StartY > 0)
                            {
                                AddToQueue(nodeQueue, visited, tempX + 0, tempY - 1);
                                AddToQueue(nodeQueue, visited, tempX + 1, tempY + 0);
                            }
                        }
                    }
                    else
                    {
                        int magx = Mathf.Abs(StartX);
                        int magY = Mathf.Abs(StartY);

                        if (magx > magY || magY == 0)
                        {
                            if (StartX < 0) // move right on the x position [x+1, y-1,y-0y+1]
                            {
                                AddToQueue(nodeQueue, visited, tempX + 1, tempY + 1);
                                AddToQueue(nodeQueue, visited, tempX + 1, tempY + 0);
                                AddToQueue(nodeQueue, visited, tempX + 1, tempY - 1);
                            }
                            else if (StartX > 0) // move left
                            {
                                AddToQueue(nodeQueue, visited, tempX - 1, tempY + 1);
                                AddToQueue(nodeQueue, visited, tempX - 1, tempY + 0);
                                AddToQueue(nodeQueue, visited, tempX - 1, tempY - 1);
                            }
                        }
                        else
                        {
                            if (StartY < 0)
                            {
                                //up
                                AddToQueue(nodeQueue, visited, tempX + 1, tempY + 1);
                                AddToQueue(nodeQueue, visited, tempX + 0, tempY + 1);
                                AddToQueue(nodeQueue, visited, tempX - 1, tempY + 1);
                            }
                            else if (StartY > 0)
                            {
                                //down
                                AddToQueue(nodeQueue, visited, tempX + 1, tempY - 1);
                                AddToQueue(nodeQueue, visited, tempX + 0, tempY - 1);
                                AddToQueue(nodeQueue, visited, tempX - 1, tempY - 1);
                            }
                        }
                    }
                }
            }
        }


        return(nodes);
    }
Exemplo n.º 55
0
    // ====================================================================================================================
    /// <summary>
    /// Link with target node and unlink with any currently linked node. aka, set NaviUnit.node variable.
    /// Note that this does not check if targetNode is a valid node that this Unit could stand on.
    /// Use CanStandOn to check for that.
    /// </summary>
    public void LinkWith(TileNode targetNode)
    {
        // first unlink with previous node if standing on any
        if (this.node != null)
        {
            this.node.units.Remove(this);
        }

        // link with new node
        this.node = targetNode;
        if (this.node != null)
        {
            this.node.units.Add(this);
        }
    }
Exemplo n.º 56
0
    public List <TileNode> GetAiPath(TileNode start)
    {
        start.parent = start;
        var openList   = new List <TileNode>();
        var closedList = new List <TileNode>();

        openList.Add(start);

        while (openList.Count > 0)
        {
            var      lowest  = openList.Min(l => l.totalCost);
            TileNode current = openList.First(l => l.totalCost == lowest);

            closedList.Add(current);
            openList.Remove(current);

            if (closedList.FirstOrDefault(l => tileOracle.BelowMap(l)) != null)
            {
                break;
            }

            var accessibleTile = tileOracle.GetAccessibleTiles(current);

            foreach (var adjacentTile in accessibleTile)
            {
                if (closedList.FirstOrDefault(l => l.Equals(adjacentTile)) != null)
                {
                    continue;
                }

                var newCost = current.totalCost + tileOracle.Cost(adjacentTile);

                var inOpenList = openList.FirstOrDefault(l => l.Equals(adjacentTile)) != null;

                if (!inOpenList || newCost < adjacentTile.totalCost)
                {
                    adjacentTile.totalCost = newCost;
                    adjacentTile.parent    = current;
                }

                if (!inOpenList)
                {
                    openList.Insert(0, adjacentTile);
                }
            }
        }

        List <TileNode> path = new List <TileNode>();
        var             last = closedList.FirstOrDefault(l => tileOracle.BelowMap(l));

        if (last != null)
        {
            path.Add(last);
            while (path.First().parent != start)
            {
                path.Insert(0, path.First().parent);
            }
        }

        return(path);
    }
Exemplo n.º 57
0
    public bool MoveTo(TileNode targetNode)
    {
        if (isMoving) StopMoving();		// first stop current movement

        followPath = mapnav.GetPath(this.node, targetNode, this.tileLevel);
        if (followPath == null) return false;
        if (followPath.Length == 0) return false;

        followMaxMoves = followPath.Length;
        isMoving = true;
        _StartMoving();
        return true;
    }
Exemplo n.º 58
0
 public bool Equals(TileNode other)
 {
     return(x == other.x && y == other.y);
 }
Exemplo n.º 59
0
    private void _StartMoving()
    {
        // If using same time moving, then a unit will have to mvoe from tile to tile and
        // 1st check ifallowed to mvoe further before going to its next tile since
        // another unit might have entered the target tile

        if (usingSameTimeMovement)
        {
            // setup iTween options to be used with this move
            if (jumpMovement)
            {
                iTweenOpt = iTween.Hash(
                            "path", null,
                            "speed", moveSpeed,
                            "orienttopath", true,
                            "easetype", "easeInOutExpo",
                            "axis", "y",
                            "oncomplete", "_OnCompleteMoveTo",
                            "oncompletetarget", gameObject);

            }
            else
            {
                endPointToReach = followPath[followMaxMoves - 1].transform.position;
                iTweenOpt = iTween.Hash(
                            "position", Vector3.zero,
                            "speed", ((moveSpeedMulti * followMaxMoves) + 1f) * moveSpeed,
                            "orienttopath", true,
                            "easetype", "linear",
                            "oncomplete", "_OnCompleteMoveTo",
                            "oncompletetarget", gameObject);

                if (!tiltToPath || adjustNormals) iTweenOpt.Add("axis", "y");

            }

            if ((adjustNormals || adjustToCollider) && adjustmentLayerMask != 0)
            {
                iTweenOpt.Add("onupdate", "_OnMoveToUpdate");
                iTweenOpt.Add("onupdatetarget", gameObject);
            }

            // start moving
            followIdx = 0;
            _GotoNextNode();
        }

        // *** not usingSameTimeMovement
        else
        {
            // setup iTween options to be used with this move
            if (jumpMovement)
            {
                iTweenOpt = iTween.Hash(
                            "path", null,
                            "speed", moveSpeed,
                            "orienttopath", true,
                            "easetype", "easeInOutExpo",
                            "axis", "y",
                            "oncomplete", "_OnCompleteMoveTo",
                            "oncompletetarget", gameObject);

                if ((adjustNormals || adjustToCollider) && adjustmentLayerMask != 0)
                {
                    iTweenOpt.Add("onupdate", "_OnMoveToUpdate");
                    iTweenOpt.Add("onupdatetarget", gameObject);
                }

                // start moving
                followIdx = 0;
                _GotoNextNode();
            }
            else
            {

                iTweenOpt = iTween.Hash(
                                    "speed", ((moveSpeedMulti * followMaxMoves) + 1f) * moveSpeed,
                                    "orienttopath", true,
                                    "easetype", "linear",
                                    "oncomplete", "_OnCompleteMoveTo",
                                    "oncompletetarget", gameObject);

                if (!tiltToPath || adjustNormals) iTweenOpt.Add("axis", "y");

                if ((adjustNormals || adjustToCollider) && adjustmentLayerMask != 0)
                {
                    iTweenOpt.Add("onupdate", "_OnMoveToUpdate");
                    iTweenOpt.Add("onupdatetarget", gameObject);
                }

                if (followMaxMoves > 1)
                {
                    Vector3[] points = new Vector3[followMaxMoves];
                    for (int i = 0; i < followMaxMoves; i++) points[i] = followPath[i].transform.position;
                    endPointToReach = points[points.Length - 1];
                    iTweenOpt.Add("path", points);
                }
                else
                {
                    endPointToReach = followPath[0].transform.position;
                    iTweenOpt.Add("position", endPointToReach);
                }

                // unlink with current node and link with destination node
                node.units.Remove(this);
                node = followPath[followMaxMoves-1];
                node.units.Add(this);

                // start movement
                iTween.MoveTo(this.gameObject, iTweenOpt);
            }
        }
    }
Exemplo n.º 60
0
 public bool BelowMap(TileNode node)
 {
     return(node.y > tileGenerator.GetSize().y);
 }