Exemplo n.º 1
0
    void OnTriggerEnter2D(Collider2D other)
    {
        if (hitpointController.isDead)
        {
            return;
        }

        // Reverse moving if hit bullets
        if (other.CompareTag("Bullet"))
        {
            moveSpeed *= -1f;
        }

        // Get edge
        EdgeController edgeController = other.GetComponent <EdgeController> ();

        // If hit edge with edge controller
        if (other.CompareTag("Edge") && edgeController)
        {
            moveSpeed = edgeController.changeSpeed(moveSpeed);
        }

        // Collect if hit item
        if (other.tag == "Item")
        {
            // Item name
            Item item = other.GetComponent <Item> ();

            if (item.type == "Star")
            {
                stars += item.amount;
            }

            if (item.type == "Diamond")
            {
                diamonds += item.amount;
            }

            if (item.type == "Hitpoint")
            {
                hitpointController.heal(item.amount);
            }

            // Update UI
            updateResources();

            // Destroy item
            Destroy(other.gameObject);
        }
    }
Exemplo n.º 2
0
        public void TestDeserilaizeOperationException()
        {
            IStorage        storage         = new BinaryStorage();
            GraphController graphController = new GraphController(null);
            EdgeController  edgeController  = new EdgeController(graphController);
            IVisualEdge     edge            = new VisualEdge(edgeController, 0x30000001, 0x30000002, false);

            storage.WriteUnsignedInteger(FieldCode.EdgeSignature, 12);
            storage.Seek(0, SeekOrigin.Begin);

            Assert.Throws <InvalidOperationException>(() =>
            {
                edge.Deserialize(storage);
            });
        }
Exemplo n.º 3
0
        public void TestSerializeDeserialize()
        {
            IStorage        storage         = new BinaryStorage();
            GraphController graphController = new GraphController(null);
            EdgeController  edgeController  = new EdgeController(graphController);
            IVisualEdge     edge00          = new VisualEdge(edgeController, 0x30000001, 0x30000002, false);

            edge00.Serialize(storage);
            storage.Seek(0, SeekOrigin.Begin);
            IVisualEdge edge01 = VisualEdge.Create(edgeController, storage);

            Assert.AreEqual(edge00.EdgeId, edge01.EdgeId);
            Assert.AreEqual(edge00.StartSlotId, edge01.StartSlotId);
            Assert.AreEqual(edge00.EndSlotId, edge01.EndSlotId);
        }
Exemplo n.º 4
0
 bool isAlreadyUsed(NodeController node1, NodeController node2, int id)
 {
     //regarder chaque edge,
     foreach (Transform t in ListeEdges.transform)
     {
         //si un edge est égal à node1-node2 et que son id est le même alors on retourne true
         EdgeController actualEdge = t.GetComponent <EdgeController>();
         if ((actualEdge.Node1() == node1 || actualEdge.Node2() == node1) && (actualEdge.Node1() == node2 || actualEdge.Node2() == node2) && actualEdge.idMessage == id)
         {
             return(true);
         }
         //sinon, false
     }
     return(false);
 }
Exemplo n.º 5
0
        public void TestRecordEdgeCreationForUndo00()
        {
            GraphController  graphController = new GraphController(null);
            UndoRedoRecorder urr             = new UndoRedoRecorder(graphController);
            EdgeController   edgeController  = new EdgeController(graphController);

            List <IVisualEdge> edgeList = new List <IVisualEdge>();
            VisualEdge         edge     = new VisualEdge(edgeController, EdgeType.ExplicitConnection);

            edgeList.Add(edge);

            Assert.Throws <InvalidOperationException>(() =>
            {
                urr.RecordEdgeCreationForUndo(edgeList);
            });
        }
Exemplo n.º 6
0
 private void doJump()
 {
     if (grabbedEdge != null)
     {
         becomeHittable();
         grabbedEdge = null;
     }
     if (jumpType == Utilities.jumpType.Small)
     {
         smallJump();
     }
     else
     {
         normalJump();
     }
 }
    public static bool TriangleContainsEdge(NodeController[] triangle, EdgeController edge)
    {
        if (edge.ContainsBoth(triangle[0], triangle[1]))
        {
            return(true);
        }

        if (edge.ContainsBoth(triangle[0], triangle[2]))
        {
            return(true);
        }

        if (edge.ContainsBoth(triangle[1], triangle[2]))
        {
            return(true);
        }

        return(false);
    }
Exemplo n.º 8
0
    /// <summary>
    /// Lets go to specified direction
    /// </summary>
    /// <param name="dir">The desired direction</param>
    protected void letGo(Utilities.direction dir)
    {
        rbd.gravityScale = gravityAmount;
        state            = Utilities.state.Air;
        grabbedEdge      = null;
        becomeHittable();

        if (dir == Utilities.direction.Down)
        {
            rbd.velocity = new Vector2(rbd.velocity.x, -1);
        }
        else if (dir == Utilities.direction.Right)
        {
            rbd.velocity = new Vector2(1, rbd.velocity.y);
        }
        else if (dir == Utilities.direction.Left)
        {
            rbd.velocity = new Vector2(-1, rbd.velocity.y);
        }
    }
    public bool AssessEdgeIntersection(EdgeController edge)
    {
        foreach (var tri in currentTriangles)
        {
            Vector3 centroid = (
                tri[0].transform.position +
                tri[1].transform.position +
                tri[2].transform.position) / 3f;

            // shift all points by an epsilon inwards, to make sure points aren't erronously said to
            // overlap due to floating point errors.

            Vector3 pos1 = Vector3.MoveTowards(
                tri[0].transform.position, centroid, .01f
                );

            Vector3 pos2 = Vector3.MoveTowards(
                tri[1].transform.position, centroid, .01f
                );

            Vector3 pos3 = Vector3.MoveTowards(
                tri[2].transform.position, centroid, .01f
                );

            Vector3?intersectionPoint = null;
            bool    intersects        = TriTriOverlap.TriEdgeIntersect(
                pos1,
                pos2,
                pos3,
                edge.startNode.transform.position,
                edge.endNode.transform.position,
                out intersectionPoint
                );

            if (intersects)
            {
                return(true);
            }
        }
        return(false);
    }
Exemplo n.º 10
0
        internal VisualEdge(EdgeController edgeController, uint startSlotId, uint endSlotId, bool isImplicit)
        {
            this.edgeController = edgeController;
            if (isImplicit)
            {
                this.EdgeType = EdgeType.ImplicitConnection;
            }
            else
            {
                this.EdgeType = EdgeType.ExplicitConnection;
            }
            this.version     = VisualEdge.Version.Current;
            this.StartSlotId = startSlotId;
            this.EndSlotId   = endSlotId;

            // Generate new ID for this visual edge.
            GraphController graphController = edgeController.GetGraphController();
            IdGenerator     idGenerator     = graphController.GetIdGenerator();

            this.EdgeId = idGenerator.GetNextId(ComponentType.Edge);

            controlPoints.Add(new Point());
            controlPoints.Add(new Point());
            controlPoints.Add(new Point());
            controlPoints.Add(new Point());

            GraphController controller = edgeController.GetGraphController();
            Slot            startSlot  = controller.GetSlot(this.StartSlotId) as Slot;
            Slot            endSlot    = controller.GetSlot(this.EndSlotId) as Slot;

            if (startSlot != null && endSlot != null)
            {
                Point startPoint = startSlot.GetPosition();
                Point endPoint   = endSlot.GetPosition();
                UpdateControlPoint(startPoint, endPoint, startSlot.SlotType != SlotType.Output);
            }
            else
            {
                throw new ArgumentNullException("startSlot or endSlot");
            }
        }
Exemplo n.º 11
0
    public void UpdateArrow()
    {
        EdgeController edgeController = GetComponent <EdgeController>();
        float          AdaptiveSize   = (float)(edgeController.Width * 2 / Vector3.Distance(ArrowOrigin, ArrowTarget));

        if (cachedLineRenderer == null)
        {
            cachedLineRenderer = this.GetComponent <LineRenderer>();
        }
        cachedLineRenderer.widthCurve = new AnimationCurve(
            new Keyframe(0, 0.4f)
            , new Keyframe(0.999f - AdaptiveSize, 0.4f) // neck of arrow
            , new Keyframe(1 - AdaptiveSize, 1f)        // max width of arrow head
            , new Keyframe(1, 0f));                     // tip of arrow
        cachedLineRenderer.SetPositions(new Vector3[] {
            ArrowOrigin
            , Vector3.Lerp(ArrowOrigin, ArrowTarget, 0.999f - AdaptiveSize)
            , Vector3.Lerp(ArrowOrigin, ArrowTarget, 1 - AdaptiveSize)
            , ArrowTarget
        });
    }
Exemplo n.º 12
0
    public void AddNodeToTrajectory(NodeController node)
    {
        //vérifier que le node n'a jamais été ajouté, et qu'une trajectoire est en cours
        if (actualTrajectory.Count > 0 && /*!actualTrajectory.Contains(node)*/ !isAlreadyUsed(node, actualTrajectory[actualTrajectory.Count - 1], actualTrajectory[0].call.id)) //todo à changer
        {
            //vérifier si on respecte les edges
            if (node.IsConnectedTo(actualTrajectory[actualTrajectory.Count - 1]))
            {
                actualTrajectory.Add(node);
                soundManager.PlaySound(SoundManager.SoundList.LINK_NODE, false);
                Debug.Log("Add " + node.name);

                Call call = null;
                foreach (Call c in callsInTransmission)
                {
                    if (c.caller == actualTrajectory[0] || c.reciever == actualTrajectory[0])
                    {
                        call = c;
                    }
                }

                EdgeController actualEdge = node.edge(actualTrajectory[actualTrajectory.Count - 2]);

                if (actualEdge.IsTaken())
                {
                    alreadyUsedEdges.Add(actualEdge);
                    idUsedEdges.Add(actualEdge.idMessage);
                }
                //changer couleur du edge en question
                //node.edge(actualTrajectory[actualTrajectory.Count - 2]).ChangeColor(new Color(1,0,0));
                actualEdge.TakePath(call.id);

                //si c'est un node obligatoire, alors il devient "utilisé"
                if (call.node_obligatory == node)
                {
                    node.isUsed = true;
                }
            }
        }
    }
 /// <summary>
 /// Gets a connecting node of two edges. If none, returns null.
 /// </summary>
 /// <param name="v1"></param>
 /// <param name="v2"></param>
 public static NodeController GetConnection(EdgeController v1, EdgeController v2)
 {
     if (v1.startNode == v2.startNode)
     {
         return(v1.startNode);
     }
     else if (v1.startNode == v2.endNode)
     {
         return(v1.startNode);
     }
     else if (v1.endNode == v2.startNode)
     {
         return(v1.endNode);
     }
     else if (v1.endNode == v2.endNode)
     {
         return(v1.endNode);
     }
     else
     {
         return(null);
     }
 }
Exemplo n.º 14
0
    /// <summary>
    /// Spawn road using prefab, stretch it to match
    /// distances and set on the center, between two positions
    /// </summary>
    /// <param name="positionA"></param>
    /// <param name="positionB"></param>
    void SpawnRoad(Vector3 positionA, Vector3 positionB)
    {
        Vector3 targetDirection = positionB - positionA;

        targetDirection.y = 0;
        Quaternion rotation = Quaternion.LookRotation(targetDirection);
        Vector3    center   = (positionA + positionB) / 2;

        center.y = 0.02f;

        GameObject road = Instantiate(WhiteRoadObjectPrefab, center, rotation);

        Vector3 currentScale = road.transform.localScale;
        float   newScale     = Vector3.Distance(positionA, positionB);

        currentScale.z            = newScale / 10;
        road.transform.localScale = currentScale;

        EdgeController edgeController = road.GetComponent <EdgeController>();

        edgeController.StartPosition = positionA;
        edgeController.EndPosition   = positionB;
    }
Exemplo n.º 15
0
    private void actualizePositionEdges(GameObject liste_edges)
    {
        foreach (Transform edgeTransform in liste_edges.transform)
        {
            EdgeController edge = edgeTransform.GetComponent <EdgeController>();
            if (edge.gameObject.activeSelf)
            {
                //pour chaque edge, on récupère les positions des deux bouts
                //et on détermine où le edges doit aller
                Vector3 pos1 = edge.Node1().GetTransform().position;
                Vector3 pos2 = edge.Node2().GetTransform().position;

                Vector3 n = pos2 - pos1;

                float distance = (n).magnitude;
                float alpha    = angle(n.x, n.y);

                edge.transform.position         = (pos1 + pos2) / 2.0f;
                edge.transform.localScale       = new Vector3(distance * 1 / 8.5f, edge.epaisseur, 1);
                edge.transform.localEulerAngles = new Vector3(0, 0, alpha);
            }
        }
    }
Exemplo n.º 16
0
 public void AddEdge(EdgeController edge)
 {
     neighborhoodList.Add(edge);
 }
Exemplo n.º 17
0
    /// <summary>
    /// Modified the graph, creates or removes edge if valid.
    /// </summary>
    /// <param name="joinNode">New node we are using to modify</param>
    public Outcome AttemptModification(NodeController joinNode, out object outcomeData)
    {
        outcomeData = null;
        if (!creating)
        {
            return(Outcome.None);
        }

        EdgeController foundEdge;

        if (graphLogicManager.EdgeExists(startNode, joinNode, out foundEdge))
        {
            Debug.LogFormat("Removing edge between {0} and {1}", startNode.name, joinNode.name);
            List <NodeController[]> removedFaces;
            graphLogicManager.RemoveEdge(foundEdge, out removedFaces);
            counter.EdgeCountChange(-1);
            if (removedFaces.Count > 0)
            {
                outcomeData = new object[] { foundEdge, removedFaces };
                return(Outcome.RemovedEdgeAndFaces);
            }
            else
            {
                return(Outcome.RemovedEdge);
            }
        }

        if (counter.remaining <= 0)
        {
            counter.OnCreateWithNoneRemaining();
            return(Outcome.NoEdgesRemaining);
        }

        if (graphLogicManager.IsValidEdge(startNode, joinNode))
        {
            Debug.LogFormat("Creating edge between {0} and {1}", startNode.name, joinNode.name);

            EdgeController newEdge = Create(startNode, joinNode);

            // first check if this edge intersects a face directly
            bool edgeCreatesEdgeIntersection;
            edgeCreatesEdgeIntersection = graphLogicManager.AssessEdgeIntersection(newEdge);

            if (edgeCreatesEdgeIntersection)
            {
                Debug.Log("Edge invalid! Creates edge intersection.");
                Destroy(newEdge.gameObject);
                return(Outcome.IntersectingEdge);
            }

            // if it doesnt, check if it creates a face which creates an intersection
            bool edgeCreatesFaceIntersection;
            var  newFaces = graphLogicManager.CheckForNewFaces(newEdge, out edgeCreatesFaceIntersection);

            if (edgeCreatesFaceIntersection)
            {
                Debug.Log("Edge invalid! Creates face intersection.");
                Destroy(newEdge.gameObject);
                return(Outcome.IntersectingFace);
            }
            else
            {
                Debug.Log("Adding edge to graph");
                graphLogicManager.AddEdge(newEdge);
                counter.EdgeCountChange(1);
                if (newFaces.Count > 0)
                {
                    outcomeData = new object[] { newEdge, newFaces };
                    return(Outcome.CreatedEdgeAndFaces);
                }
                else
                {
                    outcomeData = newEdge;
                    return(Outcome.CreatedEdge);
                }
            }
        }
        else
        {
            return(Outcome.InvalidNodePair);
        }
    }
    public void RegisterJoin(NodeController joinNode)
    {
        if (joinNode != previouslySelectedNode && joinNode != null)
        {
            object  outcomeData;
            Outcome outcome = edgeCreator.AttemptModification(joinNode, out outcomeData);
            switch (outcome)
            {
            case Outcome.CreatedEdgeAndFaces:

                object[] edgeAndFaces = (object[])outcomeData;

                EdgeController          createdEdge  = (EdgeController)edgeAndFaces[0];
                List <NodeController[]> createdFaces = (List <NodeController[]>)edgeAndFaces[1];

                createdEdge.nodes
                .ForEach(n => n.OnCreateEdge());

                createdFaces
                .SelectMany(face => face)
                .ToList()
                .ForEach(node => node.OnCreateFace());

                var distinctEdges = graphLogicManager.DistinctEdgesInTriangles(createdFaces).ToList();
                distinctEdges.ForEach(e => e.SetEdgeState(EdgeState.Face));

                break;

            case Outcome.CreatedEdge:
                EdgeController newEdge = (EdgeController)outcomeData;
                joinNode.OnCreateEdge();
                previouslySelectedNode.OnCreateEdge();
                newEdge.SetEdgeState(EdgeState.NoFace);
                break;

            case Outcome.RemovedEdgeAndFaces:

                object[] removedEdgesAndFaces = (object[])outcomeData;

                EdgeController          removedEdge  = (EdgeController)removedEdgesAndFaces[0];
                List <NodeController[]> removedFaces = (List <NodeController[]>)removedEdgesAndFaces[1];

                removedFaces
                .SelectMany(face => face)
                .ToList()
                .ForEach(node => node.OnRemoveFace());

                removedEdge.nodes
                .ForEach(n => n.OnRemoveEdge());

                IEnumerable <EdgeController> edgesToUpdate = graphLogicManager.DistinctEdgesInTriangles(removedFaces);

                graphLogicManager.UpdateEdgeStates(edgesToUpdate);

                break;

            case Outcome.RemovedEdge:
                joinNode.OnRemoveEdge();
                previouslySelectedNode.OnRemoveEdge();
                break;

            case Outcome.IntersectingFace:
            case Outcome.IntersectingEdge:
                feedback.FeedbackIntersectingFace();
                break;

            case Outcome.InvalidNodePair:
                feedback.FeedbackInvalidPair();
                break;
            }
        }
        RegisterDeSelect();
        edgeCreator.DePointNode();
    }
Exemplo n.º 19
0
 private VisualEdge(EdgeController edgeController)
 {
     this.edgeController = edgeController;
 }
 public bool AssessEdgeIntersection(EdgeController newEdge)
 {
     return(faceCreator.AssessEdgeIntersection(newEdge));
 }
Exemplo n.º 21
0
    private void InsertOneObstacle(int buttonId, bool onPlayerPath)
    {
        while (true)
        {
            //Calculates the shortest distance before adding the obstacle.
            GameObject algorithmObject = Instantiate(modifiedDijkstraAlgorithmPrefab);
            if (MainScript.CurrentLevelCount != -1)
            {
                MainScript.GarbageCollectorGameObjects.Add(algorithmObject);
            }
            ModifiedDijkstraAlgorithm algorithm = algorithmObject.GetComponent <ModifiedDijkstraAlgorithm>();
            if (onPlayerPath)
            {
                //path between start and target node
                algorithm.Initialize(MainScript.AllNodes[playerStartPosition], MainScript.AllNodes[MainScript.NumberOfNodes - 1]);
            }
            else
            {
                //path between the node in the upper right corner and the node in the lower left corner
                algorithm.Initialize(MainScript.AllNodes[opponentStartPosition], MainScript.AllNodes[MainScript.Height - 1]);
            }
            algorithm.CalculateModifiedDijkstraAlgorithm();
            List <NodeController> shortestPath = algorithm.ShortestPath;

            //Gets randomly a node of the shortest path as obstacle.
            int            randomNumber = Random.Range((int)Math.Floor((double)shortestPath.Count / 4), (int)(shortestPath.Count - Math.Floor((double)shortestPath.Count / 10)));
            NodeController startNode    = shortestPath[randomNumber];
            NodeController targetNode   = shortestPath[randomNumber + 1];

            //Sets the new values of the obstacle
            EdgeController edge = startNode.GetEdgeToNode(targetNode);
            if (edge.Obstacle != -1)
            {
                continue;
            }
            TransformEdge(edge, buttonId);

            //Calculates the shortest distance after adding the obstacle.
            GameObject algorithmObject1 = Instantiate(modifiedDijkstraAlgorithmPrefab);
            if (MainScript.CurrentLevelCount != -1)
            {
                MainScript.GarbageCollectorGameObjects.Add(algorithmObject1);
            }
            ModifiedDijkstraAlgorithm algorithm1 = algorithmObject1.GetComponent <ModifiedDijkstraAlgorithm>();
            if (onPlayerPath)
            {
                algorithm1.Initialize(MainScript.AllNodes[playerStartPosition], MainScript.AllNodes[MainScript.NumberOfNodes - 1]);
            }
            else
            {
                algorithm1.Initialize(MainScript.AllNodes[opponentStartPosition], MainScript.AllNodes[MainScript.Height - 1]);
            }
            algorithm1.CalculateModifiedDijkstraAlgorithm();
            int shortestDistanceWithObstacle = algorithm1.ShortestDistance;

            //Tries to insert a valid button
            if (InsertButton(shortestDistanceWithObstacle, startNode, shortestPath, buttonId, onPlayerPath, edge))
            {
                Destroy(algorithmObject);
                Destroy(algorithmObject1);
                //Changes the color of the obstacle to its initial value.
                edge.ChangeColorOfObstacle(0);
                break;
            }
            else
            {
                //Resets the edge and tries to find another location for the obstacle.
                Destroy(algorithmObject);
                Destroy(algorithmObject1);
                ResetEdge(edge);
            }
        }
    }
 public void RemoveEdge(EdgeController edgeToRemove, out List <NodeController[]> removedFaces)
 {
     removedFaces = faceCreator.RemoveFacesByEdge(edgeToRemove);
     Destroy(edgeToRemove.gameObject);
     edges.Remove(edgeToRemove);
 }
Exemplo n.º 23
0
    /**
     * Tries to insert a button for the corresponding obstacle.
     * <param name="shortestDistance">The shortest distance of the path after adding the obstacle.</param>
     * <param name="nodeAtObstacle">The node in front of the obstacle.</param>
     * <param name="optimalPathWithoutObstacle">The optimal path before adding the obstacle.</param>
     * <param name="buttonId">The id of the button.</param>
     * <param name="onPlayerPath">The location flag of the obstacle.</param>
     * <param name="obstacle">The corresponding obstacle.</param>
     * <returns>Whether the operation was successful.</returns>
     */
    private bool InsertButton(int shortestDistance, NodeController nodeAtObstacle, List <NodeController> optimalPathWithoutObstacle, int buttonId, bool onPlayerPath, EdgeController obstacle)
    {
        //Counts the number of tested nodes.
        int counter = 0;

        while (true)
        {
            //Breaks if it checked too much nodes. Chooses after that another obstacle.
            if (counter == MainScript.NumberOfNodes)
            {
                return(false);
            }

            //Gets a random node as button.
            NodeController node = GetRandomNode();
            //Checks the conditions of the node.
            if (optimalPathWithoutObstacle.Contains(node) || node.Button != -1)
            {
                continue;
            }
            //Sets the values of the new button.
            node.Button = buttonId;
            node.States = SetStates(buttonId);

            //Calculates the shortest distance after adding the button.
            GameObject algorithmObject = Instantiate(modifiedDijkstraAlgorithmPrefab);
            if (MainScript.CurrentLevelCount != -1)
            {
                MainScript.GarbageCollectorGameObjects.Add(algorithmObject);
            }
            ModifiedDijkstraAlgorithm algorithm = algorithmObject.GetComponent <ModifiedDijkstraAlgorithm>();
            if (onPlayerPath)
            {
                algorithm.Initialize(MainScript.AllNodes[playerStartPosition], MainScript.AllNodes[MainScript.NumberOfNodes - 1]);
            }
            else
            {
                algorithm.Initialize(MainScript.AllNodes[opponentStartPosition], MainScript.AllNodes[MainScript.Height - 1]);
            }
            algorithm.CalculateModifiedDijkstraAlgorithm();
            int newShortestDistance = algorithm.ShortestDistance;

            //Calculates the distance between button and obstacle.
            GameObject algorithmObject1 = Instantiate(modifiedDijkstraAlgorithmPrefab);
            if (MainScript.CurrentLevelCount != -1)
            {
                MainScript.GarbageCollectorGameObjects.Add(algorithmObject1);
            }
            ModifiedDijkstraAlgorithm algorithm1 = algorithmObject1.GetComponent <ModifiedDijkstraAlgorithm>();
            algorithm1.Initialize(node, nodeAtObstacle);
            algorithm1.CalculateModifiedDijkstraAlgorithm();
            int distanceBetweenButtonAndObstacle = algorithm1.ShortestDistance;

            //Checks the conditions.
            if (newShortestDistance < shortestDistance && distanceBetweenButtonAndObstacle > (shortestDistance / 10))
            {
                Destroy(algorithmObject);
                Destroy(algorithmObject1);
                //Adds the button at the choosen node.
                GameObject       gameObject = Instantiate(buttonPrefab, node.transform.position, Quaternion.identity);
                ButtonController button     = gameObject.GetComponent <ButtonController>();
                button.Initialize(obstacle, node, buttonId);
                MainScript.AllButtons.Add(button);
                button.gameObject.transform.localScale = new Vector3(0.25f * MainScript.ScaleMazeSize, 0.25f * MainScript.ScaleMazeSize);
                if (MainScript.CurrentLevelCount != -1)
                {
                    MainScript.GarbageCollectorGameObjects.Add(gameObject);
                }
                break;
            }
            //Resets the values and checks another node.
            Destroy(algorithmObject);
            Destroy(algorithmObject1);
            node.Button = -1;
            node.States = null;
            counter++;
        }
        return(true);
    }
 public void AddEdge(EdgeController newEdge)
 {
     edges.Add(newEdge);
 }
Exemplo n.º 25
0
 /**
  * Transforms the edge to a obstacle.
  * <param name="edge">The edge which should be transformed.</param>
  * <param name="buttonId">The id of the corresponding button.</param>
  */
 private void TransformEdge(EdgeController edge, int buttonId)
 {
     edge.Obstacle = buttonId;
     edge.Costs    = SetCosts(buttonId, GetLengthOfObstacle());
 }
    public List <NodeController[]> CheckForNewFaces(EdgeController newEdge, out bool edgeCreatesIntersection)
    {
        // Get all edges that contain either the start or end node from newEdge,
        // and is not this edge
        var connectedEdges = edges.Where(
            e => ((e != this) && (GetConnection(e, newEdge) != null))
            ).ToList();

        int n = connectedEdges.Count;

        // now check all pairings with the new edges

        edgeCreatesIntersection = false;

        List <NodeController[]> facesToCreate = new List <NodeController[]>();

        for (int i = 0; i < n - 1; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                List <EdgeController> potentialTriangle = new List <EdgeController>()
                {
                    newEdge,
                    connectedEdges[i],
                    connectedEdges[j]
                };

                // if they share exactly 3 nodes, the three edges form a triangle.
                List <NodeController> distinctNodes = DistinctNodesInSubGraph(potentialTriangle).ToList();
                Debug.LogFormat("Asessing triangle: {0}-{1}-{2}", distinctNodes.Select(node => node.name).ToArray());
                if (distinctNodes.Count() == 3)
                {
                    Debug.Log("Assessing triangle intersection");
                    // now we know the new edge created a new triangle, we must test if the new triangle would intersect with other existing triangles.
                    edgeCreatesIntersection = faceCreator.AssessFaceIntersection(
                        distinctNodes[0],
                        distinctNodes[1],
                        distinctNodes[2]
                        );

                    if (edgeCreatesIntersection)
                    {
                        // one intersection invalidates the edge
                        facesToCreate.Clear();
                        return(facesToCreate);
                    }
                    else
                    {
                        facesToCreate.Add(
                            new NodeController[] {
                            distinctNodes[0],
                            distinctNodes[1],
                            distinctNodes[2]
                        }
                            );

                        Debug.Log("Successful triangle");

                        // continue to assess, since a single node can form multiple triangles
                    }
                }
            }
        }

        if (facesToCreate.Count > 0)
        {
            foreach (var newFace in facesToCreate)
            {
                faceCreator.CreateFace(
                    newFace[0],
                    newFace[1],
                    newFace[2]
                    );
            }
        }

        return(facesToCreate);
    }
Exemplo n.º 27
0
 /**
  * Resets an obstacle to a normal edge.
  * <param name="edge">The edge which should be reseted.</param>
  */
 private void ResetEdge(EdgeController edge)
 {
     edge.Obstacle = -1;
     edge.Costs    = null;
 }