예제 #1
0
        public void Click(RadarForm form, MouseEventArgs e)
        {
            Point cursorPosition = form.PointToClient(Cursor.Position);
            var   cursorRect     = new Rectangle(cursorPosition.X, cursorPosition.Y, 5, 5);

            try
            {
                foreach (PGameObject node in ObjectManager.GetGameObject)
                {
                    if (FindNode.IsHerb(node) || FindNode.IsMine(node))
                    {
                        float x       = form.OffsetX(node.Location.X, ObjectManager.MyPlayer.Location.X);
                        float y       = form.OffsetY(node.Location.Y, ObjectManager.MyPlayer.Location.Y);
                        var   objRect = new Rectangle((int)y, (int)x, 5, 5);
                        if (Rectangle.Intersect(objRect, cursorRect) != Rectangle.Empty)
                        {
                            if (FlyingBlackList.IsBlacklisted(node))
                            {
                                FlyingBlackList.Unblacklist(node);
                            }
                            else
                            {
                                Logging.Write("Added the node to the permanent blacklist");
                                FlyingBlackList.AddBadNode(node);
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
예제 #2
0
    public void bestpath()
    {
        //this method will find the shortest path
        if(found == false)
        {
            //
            if(nodecheck.one != null)
                findnodecost(nodecheck, nodecheck.one);
            if(nodecheck.two != null)
                findnodecost(nodecheck, nodecheck.two);
            if(nodecheck.three != null)
                findnodecost(nodecheck, nodecheck.three);
            if(nodecheck.four != null)
                findnodecost(nodecheck, nodecheck.four);
            //moves the current node from open list to close list
            //as it already has been checked.
            Add2Close(nodecheck);
            RemoveOpen(nodecheck);

            nodecheck = minTotalcost();

            nodenum++;
            print ("Node number: #" + nodenum +"has been searched");
        }
    }
예제 #3
0
        private async Task SendFindNode(IEnumerable <Node> newNodes)
        {
            foreach (Node node in Node.CloserNodes(engine.LocalId, nodes, newNodes, Bucket.MaxCapacity))
            {
                FindNode request = new FindNode(engine.LocalId, engine.LocalId);
                activeRequests++;
                var args = await engine.SendQueryAsync(request, node);

                activeRequests--;

                if (!args.TimedOut)
                {
                    FindNodeResponse response = (FindNodeResponse)args.Response;
                    await SendFindNode(Node.FromCompactNode(response.Nodes));
                }

                if (activeRequests == 0)
                {
                    if (initialNodes.Count > 0 && engine.RoutingTable.CountNodes() < 10)
                    {
                        await new InitialiseTask(engine).ExecuteAsync();
                    }
                }
            }
        }
예제 #4
0
        private void SendFindNode(Node node)
        {
            FindNode msg = new FindNode(GetNeighborId(node.Id), NodeId.Create());

            //FindNode msg = new FindNode(LocalId, NodeId.Create());
            Send(msg, node.EndPoint);
        }
예제 #5
0
    public void findHeuristics(FindNode first)
    {
        //will calculate cost values nodes
        //will start by going row by row
        FindNode rstart = startnode;
        FindNode nextnode = rstart;

        int x1, x2, z1 , z2;
        float cost;

        while (rstart != null)
        {
            while(nextnode != null)
            {
                //will use the manhattan distance as heuristic
                x1 = Mathf.FloorToInt(nextnode.transform.position.x);
                x2 = Mathf.FloorToInt(endnode.transform.position.x);
                z1 = Mathf.FloorToInt(nextnode.transform.position.z);
                z2 = Mathf.FloorToInt(endnode.transform.position.z);
                cost = Mathf.Abs(x1 - x2) + Mathf.Abs(z1 - z2);
                nextnode.hvalue = (int)cost;
            }
            rstart = rstart.three;	//goes down to next node row by row
            nextnode = rstart;
        }
    }
예제 #6
0
 private void QueryNode(Node node)
 {
     _node            = node;
     _message         = new FindNode(_engine.LocalId, node.Id);
     _task            = new SendQueryTask(_engine, _message, node);
     _task.Completed += TaskComplete;
     _task.Execute();
 }
예제 #7
0
        public void FindNodeEncode()
        {
            FindNode m = new FindNode(id, infohash);
            m.TransactionId = transactionId;

            Compare(m, "d1:ad2:id20:abcdefghij01234567896:target20:mnopqrstuvwxyz123456e1:q9:find_node1:t2:aa1:y1:qe");
            message = m;
        }
예제 #8
0
 private void QueryNode(Node node)
 {
     this.node = node;
     message = new FindNode(engine.LocalId, node.Id);
     task = new SendQueryTask(engine, message, node);
     task.Completed += TaskComplete;
     task.Execute();
 }
예제 #9
0
 private void QueryNode(Node node)
 {
     this.node       = node;
     message         = new FindNode(engine.LocalId, node.Id);
     task            = new SendQueryTask(engine, message, node);
     task.Completed += TaskComplete;
     task.Execute();
 }
예제 #10
0
        public void FindNodeEncode()
        {
            FindNode m = new FindNode(id, infohash);

            m.TransactionId = transactionId;

            Compare(m, "d1:ad2:id20:abcdefghij01234567896:target20:mnopqrstuvwxyz123456e1:q9:find_node1:t2:aa1:y1:qe");
            message = m;
        }
예제 #11
0
        public void FindNodeDecode()
        {
            string   text = "d1:ad2:id20:abcdefghij01234567896:target20:mnopqrstuvwxyz123456e1:q9:find_node1:t2:aa1:y1:qe";
            FindNode m    = (FindNode)Decode(text);

            Assert.AreEqual(id, m.Id, "#1");
            Assert.AreEqual(infohash, m.Target, "#1");
            Compare(m, text);
        }
예제 #12
0
 internal static bool DismountAndHarvest(PGameObject harvest, Ticker timeOut)
 {
     if (!LazySettings.BackgroundMode && !harvest.Location.IsFacing())
     {
         harvest.Location.Face();
     }
     if (Mount.IsMounted() && !ObjectManager.MyPlayer.IsInFlightForm)
     {
         Mount.Dismount();
         timeOut.Reset();
         while (ObjectManager.MyPlayer.IsMoving && !timeOut.IsReady)
         {
             Thread.Sleep(100);
         }
         Thread.Sleep(500);
     }
     Logging.Debug("Going to do harvest now");
     harvest.Interact(true);
     Latency.Sleep(ObjectManager.MyPlayer.UnitRace != "Tauren" ? 750 : 500);
     if (!ObjectManager.MyPlayer.IsCasting && ObjectManager.MyPlayer.UnitRace != "Tauren")
     {
         harvest.Interact(true);
         Latency.Sleep(750);
     }
     if (CheckFight(harvest))
     {
         ToldAboutNode.TellAbout("正在战斗状态", harvest);
         return(false);
     }
     timeOut.Reset();
     while (ObjectManager.MyPlayer.IsCasting && !timeOut.IsReady)
     {
         if (CheckFight(harvest))
         {
             ToldAboutNode.TellAbout("正在战斗状态", harvest);
             return(false);
         }
         Thread.Sleep(100);
     }
     if (CheckFight(harvest))
     {
         ToldAboutNode.TellAbout("正在战斗状态", harvest);
         return(false);
     }
     if (Langs.SkillToLow(ObjectManager.MyPlayer.RedMessage))
     {
         Logging.Write("技能太低");
         HelperFunctions.ResetRedMessage();
         if (FindNode.IsMine(harvest) || FindNode.IsHerb(harvest))
         {
             SkillToLow.Blacklist(harvest.Name, 240);
         }
         return(false);
     }
     return(true);
 }
예제 #13
0
        public void FindNodeEncode()
        {
            var message = new FindNode(_id, _infohash)
            {
                TransactionId = _transactionId
            };

            Compare(message, "d1:ad2:id20:abcdefghij01234567896:target20:mnopqrstuvwxyz123456e1:q9:find_node1:t2:aa1:y1:qe");
            _message = message;
        }
예제 #14
0
 private void SendFindNode(IEnumerable <Node> newNodes)
 {
     foreach (Node node in Node.CloserNodes(engine.LocalId, nodes, newNodes, Bucket.MaxCapacity))
     {
         activeRequests++;
         FindNode      request = new FindNode(engine.LocalId, engine.LocalId);
         SendQueryTask task    = new SendQueryTask(engine, request, node);
         task.Completed += FindNodeComplete;
         task.Execute();
     }
 }
예제 #15
0
 private static void SendFindNode(IEnumerable <Node> knonwn, NodeId nodeId)
 {
     foreach (Node node in knonwn)
     {
         FindNode      request = new FindNode(engine.LocalId, nodeId);
         SendQueryTask task    = new SendQueryTask(engine, request, node);
         task.Completed += FindNodeComplete;
         task.Execute();
         lock (engine)
             activities++;
     }
 }
예제 #16
0
        public void SelectByNodeFullPath(string nodetext)
        {
            FindNode f = new FindNode(treeView1);
            bool     b = f.SelectByNodeFullPath(nodetext);

            if (!b)
            {
                if (computerNode != null)
                {
                    treeView1.SelectedNode = computerNode;
                }
            }
        }
예제 #17
0
        private void BtnsClick(string s)
        {
            if (s.EndsWith("\\"))
            {
                s = s.Remove(s.Length - 1, 1);//移除  字符 /
            }
            FindNode fd = new FindNode(treeView1);

            fd.SelectByNodeFullPath(s);

            DisposeButtons();
            CreateButtons(s);
        }
예제 #18
0
        private void SendFindNodeRequest(IPEndPoint address, NodeId nodeid = null)
        {
            var nid = nodeid == null ? LocalId : GetNeighborId(nodeid);

            try
            {
                var msg = new FindNode(nid, NodeId.Create());
                Send(msg, address);
            }
            catch (Exception ex)
            {
                Logger.Trace($"SendFindNodeRequest nid:{nid} {address} {ex.ToString()}");
            }
        }
        public Tuple <string, FindNode> BuildFindNodePacket(string name)
        {
            FindNode obj = new FindNode()
            {
                id   = "scene/node/find",
                data = new Data13()
                {
                    name = name
                }
            };
            string json = JsonConvert.SerializeObject(obj);

            return(new Tuple <string, FindNode>(json, obj));
        }
예제 #20
0
 internal static bool PlayerToClose(int distance, PGameObject gameObject)
 {
     if (!FlyingSettings.AvoidPlayers)
     {
         return(false);
     }
     if (
         ObjectManager.GetPlayers.Where(obj => !obj.Name.Equals(ObjectManager.MyPlayer.Name))
         .Any(obj => FindNode.GetLocation(gameObject).GetDistanceTo(obj.Location) < distance))
     {
         Logging.Write("Player to close to node");
         FlyingBlackList.Blacklist(gameObject, 300, false);
         return(true);
     }
     return(false);
 }
예제 #21
0
 public static bool GatherNode(PGameObject harvest)
 {
     if (FindNode.IsSchool(harvest))
     {
         return(GatherFishNode(harvest));
     }
     if (ApprochNode(harvest))
     {
         Logging.Write("靠近[矿/草]点");
         HitTheNode(harvest);
         if (!CheckMobs(harvest))
         {
             return(false);
         }
         if (FlyingBlackList.IsBlacklisted(harvest))
         {
             ToldAboutNode.TellAbout("is blacklisted", harvest);
             return(false);
         }
         if (MoveHelper.NegativeValue(ObjectManager.MyPlayer.Location.Z - FindNode.GetLocation(harvest).Z) > 1)
         {
             Logging.Write("下降中......");
             DescentToNode(harvest);
         }
         if (FlyingBlackList.IsBlacklisted(harvest))
         {
             ToldAboutNode.TellAbout("is blacklisted", harvest);
             return(false);
         }
         if (FindNode.GetLocation(harvest).DistanceToSelf2D > 5)
         {
             ApproachPosFlying.Approach(harvest.Location, 4);
         }
         if (FindNode.GetLocation(harvest).DistanceToSelf > 10)
         {
             Logging.Write("距离矿/草太远,放弃");
             return(false);
         }
         if (!DismountAndHarvest(harvest, TimeOut))
         {
             return(false);
         }
         return(true);
     }
     ToldAboutNode.TellAbout("过不去啊!!!", harvest);
     return(false);
 }
예제 #22
0
        async Task SendFindNode(IEnumerable <Node> newNodes)
        {
            var activeRequests = new List <Task <SendQueryEventArgs> > ();
            var nodes          = new ClosestNodesCollection(engine.LocalId);

            foreach (Node node in newNodes)
            {
                var request = new FindNode(engine.LocalId, engine.LocalId);
                activeRequests.Add(engine.SendQueryAsync(request, node));
                nodes.Add(node);
            }

            while (activeRequests.Count > 0)
            {
                var completed = await Task.WhenAny(activeRequests);

                activeRequests.Remove(completed);

                SendQueryEventArgs args = await completed;
                if (args.Response != null)
                {
                    if (engine.RoutingTable.CountNodes() >= MinHealthyNodes)
                    {
                        initializationComplete.TrySetResult(null);
                    }

                    var response = (FindNodeResponse)args.Response;
                    foreach (Node node in Node.FromCompactNode(response.Nodes))
                    {
                        if (nodes.Add(node))
                        {
                            var request = new FindNode(engine.LocalId, engine.LocalId);
                            activeRequests.Add(engine.SendQueryAsync(request, node));
                        }
                    }
                }
            }

            if (initialNodes.Count > 0 && engine.RoutingTable.NeedsBootstrap)
            {
                await new InitialiseTask(engine).ExecuteAsync();
            }
        }
예제 #23
0
        public async Task Execute()
        {
            if (bucket.Nodes.Count == 0)
            {
                return;
            }

            bucket.SortBySeen();

            foreach (var node in bucket.Nodes.ToArray())
            {
                var message = new FindNode(engine.LocalId, node.Id);

                var args = await engine.SendQueryAsync(message, node);

                if (!args.TimedOut)
                {
                    return;
                }
            }
        }
예제 #24
0
 internal static void HitTheNode(PGameObject nodeToHarvest)
 {
     Face.Reset();
     ToLongRun.Reset();
     _oldDis = FindNode.GetLocation(nodeToHarvest).DistanceToSelf;
     while (!ToLongRun.IsReady)
     {
         MoveHelper.Forwards(true);
         _distanceX =
             Math.Round(Math.Abs(FindNode.GetLocation(nodeToHarvest).Y - ObjectManager.MyPlayer.Location.Y));
         _distanceY =
             Math.Round(Math.Abs(FindNode.GetLocation(nodeToHarvest).X - ObjectManager.MyPlayer.Location.X));
         if (_distanceX <= 3 && _distanceY <= 3)
         {
             break;
         }
         if (Face.IsReady)
         {
             FindNode.GetLocation(nodeToHarvest).Face();
             Face.Reset();
         }
         Thread.Sleep(2);
         if (_oldDis < FindNode.GetLocation(nodeToHarvest).DistanceToSelf)
         {
             break;
         }
     }
     if (nodeToHarvest.Location.DistanceToSelf2D > 2.9)
     {
         if (nodeToHarvest.Location.DistanceToSelf2D > 2)
         {
             Thread.Sleep(150);
         }
         else if (nodeToHarvest.Location.DistanceToSelf2D > 1)
         {
             Thread.Sleep(100);
         }
     }
     MoveHelper.ReleaseKeys();
 }
예제 #25
0
 public void Draw(RadarForm form)
 {
     foreach (PGameObject selectNode in ObjectManager.GetGameObject)
     {
         if (FindNode.IsHerb(selectNode) || FindNode.IsMine(selectNode))
         {
             if (FlyingBlackList.IsBlacklisted(selectNode))
             {
                 form.PrintCircle(_colorBadNodes,
                                  form.OffsetY(selectNode.Location.Y, ObjectManager.MyPlayer.Location.Y),
                                  form.OffsetX(selectNode.Location.X, ObjectManager.MyPlayer.Location.X),
                                  selectNode.Name);
             }
             else
             {
                 form.PrintCircle(_colorObjects,
                                  form.OffsetY(selectNode.Location.Y, ObjectManager.MyPlayer.Location.Y),
                                  form.OffsetX(selectNode.Location.X, ObjectManager.MyPlayer.Location.X),
                                  selectNode.Name);
             }
         }
     }
 }
예제 #26
0
 public void RemoveOpen(FindNode node)
 {
     openlist.Remove(node);
 }
예제 #27
0
        public bool EngineStart()
        {
            FindNode.LoadHarvest();
            FlyingSettings.LoadSettings();
            KeyHelper.AddKey("FMount", "None", FlyingSettings.FlyingMountBar, FlyingSettings.FlyingMountKey);
            KeyHelper.AddKey("Lure", "None", FlyingSettings.LureBar, FlyingSettings.LureKey);
            KeyHelper.AddKey("Waterwalk", "None", FlyingSettings.WaterwalkBar, FlyingSettings.WaterwalkKey);
            KeyHelper.AddKey("CombatStart", "None", FlyingSettings.ExtraBar, FlyingSettings.ExtraKey);
            if (!ObjectManager.InGame)
            {
                Logging.Write(LogType.Info, "Enter game before starting the bot");
                return(false);
            }
            if (ObjectManager.MyPlayer.IsGhost)
            {
                Logging.Write(LogType.Info, "Please ress before starting the bot");
                return(false);
            }
            if (CurrentProfile == null)
            {
                Logging.Write(LogType.Info, "Please load a profile");
                return(false);
            }
            if (CurrentProfile.WaypointsNormal.Count < 2)
            {
                Logging.Write(LogType.Info, "Profile should have more than 2 waypoints");
                return(false);
            }
            Navigation = new FlyingNavigation(CurrentProfile.WaypointsNormal, true, FlyingWaypointsType.Normal);
            Navigator  = new FlyingNavigator();
            ToTown.SetToTown(false);
            switch (CurrentMode)
            {
            case Mode.Normal:
                FlyingStates = new List <MainState>
                {
                    new StateMount(),
                    new StateMoving(),
                    new StateGather(),
                    new StateCombat(),
                    new StateRess(),
                    new StateResting(),
                    new StateMailbox(),
                    new StateToTown(),
                    new StateVendor(),
                    new StateFullBags(),
                };
                break;

            case Mode.TestNormal:
                Logging.Write(LogType.Warning,
                              "Starting flying engine in TestNormal mode, next start will be in normal mode");
                FlyingStates = new List <MainState>
                {
                    new StateMount(),
                    new StateMoving(),
                    new StateFullBags(),
                };
                break;

            case Mode.TestToTown:
                Logging.Write(LogType.Warning,
                              "Starting flying engine in TestToTown mode, next start will be in normal mode");
                FlyingStates = new List <MainState>
                {
                    new StateMount(),
                    new StateMoving(),
                    new StateCombat(),
                    new StateMailbox(),
                    new StateToTown(),
                    new StateVendor(),
                    new StateFullBags(),
                };
                ToTown.SetToTown(true);     //Set town mode to true
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            Stuck.Run();
            FlyingBlackList.Load();
            CloseWindows();
            CurrentMode = Mode.Normal;
            _harvest    = 0;
            _kills      = 0;
            _death      = 0;
            _startTime  = DateTime.Now;
            UpdateStats(0, 0, 0);
            return(true);
        }
예제 #28
0
 public void Add2Open(FindNode node)
 {
     openlist.Add(node);
 }
예제 #29
0
    void OnGUI()
    {
        GUI.UnfocusWindow();
        //绘制标题
        GUILayout.Space(10);
        GUI.skin.label.fontSize  = 24;
        GUI.skin.label.alignment = TextAnchor.MiddleCenter;
        GUILayout.Label("地图设置");


        strWidth = EditorGUILayout.TextField("横向格子个数 :", strWidth);
        if (strWidth != "" && strWidth != null)
        {
            bool isSettingWidth = !Int32.TryParse(strWidth, out _width);
            if (isSettingWidth)
            {
                Debug.LogErrorFormat("宽度没有设置");
            }
        }

        strHeight = EditorGUILayout.TextField("纵向格子个数 :", strHeight);
        if (strHeight != "" && strHeight != null)
        {
            bool isSettingHeight = !Int32.TryParse(strHeight, out _height);
            if (isSettingHeight)
            {
                Debug.LogErrorFormat("高度没有设置");
            }
        }


        if (GUILayout.Button("生成地图", GUILayout.Width(80), GUILayout.Height(20)))
        {
            if (EditorApplication.isPlaying == false)
            {
                EditorApplication.isPlaying = true;
            }
            if (EditorApplication.isPlaying)
            {
                initAllGrid();
            }
        }

        if (GUILayout.Button("设置Wall", GUILayout.Width(80), GUILayout.Height(20)))
        {
            Transform[] transforms = Selection.transforms;
            foreach (var node in transforms)
            {
                Node curNode = findAllGridNode(node.transform.gameObject);
                if (!wallList.Contains(curNode))
                {
                    curNode.transform.GetComponent <Renderer>().material.color = Color.black;
                    wallList.Add(curNode);
                }
            }
        }

        if (GUILayout.Button("清理Wall", GUILayout.Width(80), GUILayout.Height(20)))
        {
            Transform[] transforms = Selection.transforms;
            foreach (var node in transforms)
            {
                for (int i = 0; i < wallList.Count; i++)
                {
                    if (object.ReferenceEquals(node, wallList[i].transform))
                    {
                        node.transform.GetComponent <Renderer>().material.color = Color.white;
                        wallList.RemoveAt(i);
                    }
                }
            }
        }

        if (GUILayout.Button("设置开始点", GUILayout.Width(80), GUILayout.Height(20)))
        {
            Transform[] transforms = Selection.transforms;
            if (transforms.Length > 0)
            {
                startNode = findAllGridNode(transforms[0].transform.gameObject);
                startNode.transform.GetComponent <Renderer>().material.color = Color.red;
            }
        }

        if (GUILayout.Button("设置结束点", GUILayout.Width(80), GUILayout.Height(20)))
        {
            Transform[] transforms = Selection.transforms;
            if (transforms.Length > 0)
            {
                endNode = findAllGridNode(transforms[0].transform.gameObject);
                endNode.transform.GetComponent <Renderer>().material.color = Color.yellow;
            }
        }


        GUILayout.Space(10);
        findNode = (FindNode)EditorGUILayout.ObjectField("Find Node", findNode, typeof(FindNode), true);

        if (findNode != null)
        {
            if (GUILayout.Button("清理", GUILayout.Width(80), GUILayout.Height(20)))
            {
                if (findNode != null)
                {
                    findNode.clear();
                    clearAllGridNode();
                }
            }
            if (GUILayout.Button("测试寻路", GUILayout.Width(80), GUILayout.Height(20)))
            {
                if (findNode != null)
                {
                    if (findNode.openList.Count != 0)
                    {
                        Debug.LogErrorFormat("需要清理才能寻路");
                    }
                    else
                    {
                        findNode.settingData();
                        findNode.handleFindNode();
                    }
                }
            }
        }
    }
예제 #30
0
    public void findnodecost(FindNode node, FindNode nextnode)
    {
        //
        int newMoveCost;

        if(nextnode == null)
            return;

        if(nextnode == endnode)
        {
            endnode.Init = node;
            found = true;
            return;
        }

        if(nextnode.gameObject.tag == "Wall")
            return;
        //making sure node wasn't already checked
        if(closelist.Contains(nextnode) == false)
        {
            //making sure if the node is currently in the list of nodes not yet checked
            //
            if(openlist.Contains(nextnode) == true)
            {
                //getting new cost for movement
                newMoveCost = node.movCost + basemovcost;

                if(newMoveCost < nextnode.movecost)
                {
                    //if new move cost is lower, then we found a new
                    //node to use search from
                    nextnode.Init = node;
                    nextnode.movCost = newMoveCost;
                    nextnode.findTotalcost();
                }
            }
            //otherwise calcuate the move cost and add it to open list
            else
            {
                //
                nextnode.Init = node;
                nextnode.movCost = node.movCost + basemovcost;
                nextnode.findTotalcost();
                Add2Open(nextnode);
            }
        }
    }
예제 #31
0
 /// <summary>
 /// Constructor of the class. It calls the base constructor and store contacts into the message.
 /// </summary>
 /// <param name="nodeID">Identificator of the sender</param>
 /// <param name="request">FindNode request that orginates this response</param>
 /// <param name="recommended">List of contact that could match the request</param>
 /// <param name="nodeEndpoint">Address of the sender</param>
 public FindNodeResponse(ID nodeID, FindNode request, List<Contact> recommended, Uri nodeEndpoint)
     : base(nodeID, request, nodeEndpoint)
 {
     contacts = recommended;
 }
예제 #32
0
    public void FindAdjacentNode()
    {
        //going to use raycast to 'hit' adjacent nodes
        //don't care for efficient at this point
        RaycastHit hit;

        if(Physics.Raycast(this.transform.position, this.transform.forward, out hit) == true)
        {
            one = hit.collider.GetComponent<FindNode>();
        }

        if(Physics.Raycast(this.transform.position, this.transform.right, out hit) == true)
        {
            two = hit.collider.GetComponent<FindNode>();
        }

        if(Physics.Raycast(this.transform.position, this.transform.forward, out hit) == true)
        {
            three = hit.collider.GetComponent<FindNode>();
        }

        if(Physics.Raycast(this.transform.position, this.transform.right, out hit) == true)
        {
            four = hit.collider.GetComponent<FindNode>();
        }
    }
예제 #33
0
        public void FindNodeEncode()
        {
            var m = new FindNode(_id, _infohash) {TransactionId = _transactionId};

            Compare(m, "d1:ad2:id20:abcdefghij01234567896:target20:mnopqrstuvwxyz123456e1:q9:find_node1:t2:aa1:y1:qe");
            _message = m;
        }
예제 #34
0
 private void SendFindNode(IEnumerable<Node> newNodes)
 {
     foreach (Node node in Node.CloserNodes(engine.LocalId, nodes, newNodes, Bucket.MaxCapacity))
     {
         activeRequests++;
         FindNode request = new FindNode(engine.LocalId, engine.LocalId);
         SendQueryTask task = new SendQueryTask(engine, request, node);
         task.Completed += FindNodeComplete;
         task.Execute();
     }
 }
예제 #35
0
        ///----------------------------------------------------------------------------------------------

        ///Graph events AFTER nodes
        static void HandlePostNodesGraphEvents(Graph graph, Vector2 canvasMousePos)
        {
            //Shortcuts
            if (GUIUtility.keyboardControl == 0)
            {
                //Copy/Cut/Paste
                if (e.type == EventType.ValidateCommand || e.type == EventType.Used)
                {
                    if (e.commandName == "Copy" || e.commandName == "Cut")
                    {
                        List <Node> selection = null;
                        if (GraphEditorUtility.activeNode != null)
                        {
                            selection = new List <Node> {
                                GraphEditorUtility.activeNode
                            };
                        }
                        if (GraphEditorUtility.activeElements != null && GraphEditorUtility.activeElements.Count > 0)
                        {
                            selection = GraphEditorUtility.activeElements.Cast <Node>().ToList();
                        }
                        if (selection != null)
                        {
                            CopyBuffer.Set <Node[]>(Graph.CloneNodes(selection).ToArray());
                            if (e.commandName == "Cut")
                            {
                                foreach (Node node in selection)
                                {
                                    graph.RemoveNode(node);
                                }
                            }
                        }
                        e.Use();
                    }
                    if (e.commandName == "Paste")
                    {
                        if (CopyBuffer.Has <Node[]>())
                        {
                            TryPasteNodesInGraph(graph, CopyBuffer.Get <Node[]>(), canvasMousePos + new Vector2(500, 500) / graph.zoomFactor);
                        }
                        e.Use();
                    }
                }

                if (e.type == EventType.KeyUp)
                {
                    //Delete
                    if (e.keyCode == KeyCode.Delete || e.keyCode == KeyCode.Backspace)
                    {
                        if (GraphEditorUtility.activeElements != null && GraphEditorUtility.activeElements.Count > 0)
                        {
                            foreach (var obj in GraphEditorUtility.activeElements.ToArray())
                            {
                                if (obj is Node)
                                {
                                    graph.RemoveNode(obj as Node);
                                }
                                if (obj is Connection)
                                {
                                    graph.RemoveConnection(obj as Connection);
                                }
                            }
                            GraphEditorUtility.activeElements = null;
                        }

                        if (GraphEditorUtility.activeNode != null)
                        {
                            graph.RemoveNode(GraphEditorUtility.activeNode);
                            GraphEditorUtility.activeElement = null;
                        }

                        if (GraphEditorUtility.activeConnection != null)
                        {
                            graph.RemoveConnection(GraphEditorUtility.activeConnection);
                            GraphEditorUtility.activeElement = null;
                        }
                        e.Use();
                    }

                    //Duplicate
                    if (e.keyCode == KeyCode.D && e.control && !e.alt)
                    {
                        if (GraphEditorUtility.activeElements != null && GraphEditorUtility.activeElements.Count > 0)
                        {
                            TryPasteNodesInGraph(graph, GraphEditorUtility.activeElements.OfType <Node>().ToArray(), default(Vector2));
                        }
                        if (GraphEditorUtility.activeNode != null)
                        {
                            GraphEditorUtility.activeElement = GraphEditorUtility.activeNode.Duplicate(graph);
                        }
                        //Connections can't be duplicated by themselves. They do so as part of multiple node duplication.
                        e.Use();
                    }
                }
            }

            //No panel is obscuring
            if (GraphEditorUtility.allowClick)
            {
                #region 自定义快捷键

                if ((currentGraph.GetType() == typeof(FlowGraph) || currentGraph.GetType().IsSubclassOf(typeof(FlowGraph))) && GUIUtility.keyboardControl == 0)
                {
                    if (e.keyCode == KeyCode.F && e.control && !e.alt)
                    {
                        //Debug.Log("ctrl +f ");

                        FindNode toolNode = currentGraph.GetAllNodesOfType <FindNode>().FirstOrDefault();
                        if (toolNode != null)
                        {
                            NodeCanvas.Editor.GraphEditorUtility.activeElement = toolNode;
                        }
                        else
                        {
                            FindNode newNode = currentGraph.AddNode <FindNode>(ViewToCanvas(e.mousePosition));

                            NodeCanvas.Editor.GraphEditorUtility.activeElement = newNode;
                            //Debug.Log("There is no Find Node,Create a new node!");
                        }
                        //e.Use();
                    }


                    if (e.keyCode == KeyCode.A && e.control && !e.alt && !e.shift)
                    {
                        NodeCanvas.Editor.GraphEditorUtility.activeElements = null;
                        NodeCanvas.Editor.GraphEditorUtility.activeElement  = null;

                        if (currentGraph.allNodes == null)
                        {
                            return;
                        }

                        if (currentGraph.allNodes.Count > 1)
                        {
                            NodeCanvas.Editor.GraphEditorUtility.activeElements = currentGraph.allNodes.Cast <object>().ToList();
                            //e.Use();
                            return;
                        }
                        else
                        {
                            NodeCanvas.Editor.GraphEditorUtility.activeElement = currentGraph.allNodes[0];
                            //e.Use();
                        }
                    }
                    if (e.keyCode == KeyCode.C && e.type == EventType.KeyUp && !e.control && !e.alt && !e.shift && GUIUtility.keyboardControl == 0)
                    {
                        if (GraphEditorUtility.activeElement != null ||
                            GraphEditorUtility.activeElements != null && GraphEditorUtility.activeElements.Count > 0)
                        {
                            List <Node> node = new List <Node>();
                            if (GraphEditorUtility.activeElement != null)
                            {
                                node.Add((Node)GraphEditorUtility.activeElement);
                            }
                            else
                            {
                                node = GraphEditorUtility.activeElements.Cast <Node>().ToList();
                            }

                            Undo.RegisterCompleteObjectUndo(currentGraph, "Create Group");
                            if (currentGraph.canvasGroups == null)
                            {
                                currentGraph.canvasGroups = new List <Framework.CanvasGroup>();
                            }
                            Framework.CanvasGroup group = new Framework.CanvasGroup(GetNodeBounds(node).ExpandBy(100f), "New Canvas Group");
                            currentGraph.canvasGroups.Add(group);
                            group.isRenaming = true;
                        }
                    }
                    if (e.keyCode == KeyCode.G && !e.control && !e.alt && e.shift && GUIUtility.keyboardControl == 0)
                    {
                        if (NodeCanvas.Editor.GraphEditorUtility.activeElements == null ||
                            NodeCanvas.Editor.GraphEditorUtility.activeElements.Count < 2 && NodeCanvas.Editor.GraphEditorUtility.activeElement != null &&
                            NodeCanvas.Editor.GraphEditorUtility.activeElement.GetType() == typeof(MacroNodeWrapper))
                        {
                            //Debug.Log("current select is group node");
                            MacroNodeWrapper n = (MacroNodeWrapper)NodeCanvas.Editor.GraphEditorUtility.activeElement;

                            if (n.macro.allNodes.Count <= 2)
                            {
                                return;
                            }
                            List <Node> childNode = new List <Node>();

                            foreach (var c in n.macro.allNodes)
                            {
                                if (c.GetType() != typeof(MacroInputNode) && c.GetType() != typeof(MacroOutputNode))
                                {
                                    childNode.Add(c);
                                }
                            }

                            var newNodes = Graph.CopyNodesToGraph(childNode, currentGraph);

                            currentGraph.RemoveNode(n);
                            NodeCanvas.Editor.GraphEditorUtility.activeElement = null;

                            if (NodeCanvas.Editor.GraphEditorUtility.activeElements != null)
                            {
                                NodeCanvas.Editor.GraphEditorUtility.activeElements = newNodes.Cast <object>().ToList();
                            }
                        }
                    }

                    if (e.keyCode == KeyCode.G && e.control && !e.alt && !e.shift && GUIUtility.keyboardControl == 0)
                    {
                        //Debug.Log("ctrl +g ");
                        if (NodeCanvas.Editor.GraphEditorUtility.activeElements == null || NodeCanvas.Editor.GraphEditorUtility.activeElements.Count < 1)
                        {
                            //e.Use();
                            return;
                        }

                        List <Node> ns            = NodeCanvas.Editor.GraphEditorUtility.activeElements.Cast <Node>().ToList();
                        Rect        groupNodeRect = GetNodeBounds(ns, viewRect, false);
                        var         wrapper       = currentGraph.AddNode <MacroNodeWrapper>(groupNodeRect.center);
                        wrapper.macro              = NestedUtility.CreateBoundNested <GroupMacro>(wrapper, currentGraph);
                        wrapper.macro.name         = "NewGroup";
                        wrapper.macro.CategoryPath = (currentGraph.agent != null ? currentGraph.agent.name : currentGraph.name) + "/";
                        wrapper.macro.agent        = currentGraph.agent;

                        wrapper.macro.entry.position = new Vector2(groupNodeRect.x - 200f,
                                                                   groupNodeRect.y + 0.5f * groupNodeRect.height);
                        wrapper.macro.exit.position = new Vector2(groupNodeRect.x + groupNodeRect.width + 100f,
                                                                  groupNodeRect.y + 0.5f * groupNodeRect.height);

                        wrapper.macro.translation = -groupNodeRect.center + new Vector2(500f, 500f);

                        Graph.CopyNodesToGraph(NodeCanvas.Editor.GraphEditorUtility.activeElements.OfType <Node>().ToList(), wrapper.macro);

                        foreach (var c in ns)
                        {
                            currentGraph.RemoveNode(c);
                        }
                        NodeCanvas.Editor.GraphEditorUtility.activeElements.Clear();
                        NodeCanvas.Editor.GraphEditorUtility.activeElement = wrapper;
                    }
                    if (e.type == EventType.KeyDown && e.keyCode == KeyCode.I && GUIUtility.keyboardControl == 0)
                    {
                        List <Node> allNodes = currentGraph.GetAllNodesOfType <Node>();
                        if (allNodes != null && allNodes.Count < 2)
                        {
                            return;
                        }

                        if (NodeCanvas.Editor.GraphEditorUtility.activeElement != null)
                        {
                            if (allNodes.Contains((Node)NodeCanvas.Editor.GraphEditorUtility.activeElement))
                            {
                                allNodes.Remove((Node)NodeCanvas.Editor.GraphEditorUtility.activeElement);
                                NodeCanvas.Editor.GraphEditorUtility.activeElement = null;
                                NodeCanvas.Editor.GraphEditorUtility.activeElements.Clear();
                                NodeCanvas.Editor.GraphEditorUtility.activeElements = allNodes.Cast <object>().ToList();
                            }
                            return;
                        }

                        if (NodeCanvas.Editor.GraphEditorUtility.activeElements != null && NodeCanvas.Editor.GraphEditorUtility.activeElements.Count > 1)
                        {
                            List <object> invertNodeList = NodeCanvas.Editor.GraphEditorUtility.activeElements;
                            invertNodeList.ForEach(x =>
                            {
                                if (allNodes.Contains((Node)x))
                                {
                                    allNodes.Remove((Node)x);
                                }
                            });
                            NodeCanvas.Editor.GraphEditorUtility.activeElements.Clear();
                            if (allNodes.Count == 0)
                            {
                                NodeCanvas.Editor.GraphEditorUtility.activeElement = null;
                            }
                            else if (allNodes.Count == 1)
                            {
                                NodeCanvas.Editor.GraphEditorUtility.activeElement = allNodes[0];
                            }
                            else
                            {
                                NodeCanvas.Editor.GraphEditorUtility.activeElements = allNodes.Cast <object>().ToList();
                            }

                            return;
                        }
                        e.Use();
                    }
                    if (e.type == EventType.KeyUp && e.alt && e.control)
                    {
                        //Type genericType;

                        UnityEditor.GenericMenu.MenuFunction2 S = (obj) =>
                        {
                            NodeCanvas.Editor.GraphEditorUtility.activeElement = GraphEditor.currentGraph.AddNode(obj.GetType(),
                                                                                                                  ViewToCanvas(e.mousePosition));
                        };

                        UnityEditor.GenericMenu.MenuFunction2 D = (obj) =>
                        {
                            var genericT = typeof(SimplexNodeWrapper <>).MakeGenericType(obj.GetType());
                            NodeCanvas.Editor.GraphEditorUtility.activeElement = GraphEditor.currentGraph.AddNode(genericT, ViewToCanvas(e.mousePosition));
                        };


                        if (e.keyCode == KeyCode.S)
                        {
                            var menu = new UnityEditor.GenericMenu();

                            menu.AddItem(new GUIContent("Split"), false, S, new Split());
                            menu.AddItem(new GUIContent("Sequence"), false, S, new Sequence());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("SetActive"), false, D, new S_Active());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("SendEvent"), false, D, new SendEvent());
                            menu.AddItem(new GUIContent("SendEvent<T>"), false, D, new SendEvent <object>());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("Self"), false, S, new OwnerVariable());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("SwitchByIndex"), false, S, new Switch <object>());
                            menu.AddItem(new GUIContent("Switch Value"), false, D, new SwitchValue <object>());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("SwitchFlow/Switch Bool"), false, S, new SwitchBool());
                            menu.AddItem(new GUIContent("SwitchFlow/Switch String"), false, S, new SwitchString());
                            menu.AddItem(new GUIContent("SwitchFlow/Switch Int"), false, S, new SwitchInt());
                            menu.AddItem(new GUIContent("SwitchFlow/Switch Enum"), false, S, new SwitchEnum());
                            menu.AddItem(new GUIContent("SwitchFlow/Switch Tag"), false, S, new SwitchTag());
                            menu.AddItem(new GUIContent("SwitchFlow/Switch Comparison"), false, S, new SwitchComparison());

                            menu.ShowAsContext();
                            //e.Use();
                            return;
                        }

                        if (e.keyCode == KeyCode.A)
                        {
                            var menu = new UnityEditor.GenericMenu();

                            menu.AddItem(new GUIContent("Awake"), false, S, new ConstructionEvent());
                            menu.AddItem(new GUIContent("OnEnable"), false, S, new EnableEvent());
                            menu.AddItem(new GUIContent("Start"), false, S, new StartEvent());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("Update"), false, S, new UpdateEvent());
                            menu.AddItem(new GUIContent("FixedUpdate"), false, S, new FixedUpdateEvent());
                            menu.AddItem(new GUIContent("LateUpdate"), false, S, new LateUpdateEvent());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("OnDisable"), false, S, new DisableEvent());
                            menu.ShowAsContext();
                            return;
                        }
                        if (e.keyCode == KeyCode.C)
                        {
                            var menu = new UnityEditor.GenericMenu();
                            menu.AddItem(new GUIContent("Cache"), false, D, new Cache <object>());

                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("Coroutine"), false, S, new CoroutineState());
                            menu.AddItem(new GUIContent("Cooldown"), false, S, new Cooldown());
                            menu.AddItem(new GUIContent("Chance"), false, S, new Chance());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("CustomEvent"), false, S, new CustomEvent());
                            menu.AddItem(new GUIContent("CustomEvent<T>"), false, S, new CustomEvent <object>());

                            menu.ShowAsContext();
                            return;
                        }

                        if (e.keyCode == KeyCode.E)
                        {
                            var menu = new UnityEditor.GenericMenu();
                            menu.AddItem(new GUIContent("KeyBoard"), false, S, new KeyboardEvents());
                            menu.AddItem(new GUIContent("UnityEventAutoCallbackEvent"), false, S, new UnityEventAutoCallbackEvent());
                            menu.AddItem(new GUIContent("CSharpAutoCallbackEvent"), false, S, new CSharpAutoCallbackEvent());
                            menu.AddItem(new GUIContent("DelegateCallbackEvent"), false, S, new DelegateCallbackEvent());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("UnityEventCallbackEvent"), false, S, new UnityEventCallbackEvent());
                            menu.AddItem(new GUIContent("CSharpEventCallback"), false, S, new CSharpEventCallback());
                            menu.ShowAsContext();
                            return;
                        }
                        if (e.keyCode == KeyCode.D)
                        {
                            var menu = new UnityEditor.GenericMenu();

                            menu.AddItem(new GUIContent("Debug log OnScreen"), false, S, new G_LogOnScreen());
                            menu.AddItem(new GUIContent("Debug log"), false, D, new LogText());
                            menu.AddItem(new GUIContent("Debug Event"), false, D, new DebugEvent());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("DummyFlow"), false, S, new Dummy());
                            menu.AddItem(new GUIContent("DummyValue"), false, D, new Identity <object>());

                            menu.AddItem(new GUIContent("DoOnce"), false, S, new DoOnce());
                            menu.ShowAsContext();
                            e.Use();
                        }

                        if (e.keyCode == KeyCode.R)
                        {
                            var menu = new UnityEditor.GenericMenu();

                            menu.AddItem(new GUIContent("RelayFlowInput"), false, S, new RelayFlowInput());
                            menu.AddItem(new GUIContent("RelayFlowOutput"), false, S, new RelayFlowOutput());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("RelayValueInput"), false, S, new RelayValueInput <object>());
                            menu.AddItem(new GUIContent("RelayValueOutput"), false, S, new RelayValueOutput <object>());

                            menu.ShowAsContext();
                            e.Use();
                        }

                        if (e.keyCode == KeyCode.W)
                        {
                            var menu = new UnityEditor.GenericMenu();

                            menu.AddItem(new GUIContent("Wait"), false, D, new Wait());
                            menu.AddItem(new GUIContent("While"), false, S, new While());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("WaitForOneFrame"), false, D, new WaitForOneFrame());
                            menu.AddItem(new GUIContent("WaitForEndOfFrame"), false, D, new FlowCanvas.Nodes.WaitForEndOfFrame());
                            menu.AddItem(new GUIContent("WaitForFixedUpdate"), false, D, new WaitForFixedUpdate());
                            menu.AddItem(new GUIContent("WaitForPhysicsFrame"), false, D, new WaitForPhysicsFrame());
                            menu.ShowAsContext();
                            e.Use();
                        }

                        if (e.keyCode == KeyCode.F)
                        {
                            Selection.activeGameObject = null;  //防止快捷键冲突
                            var menu = new UnityEditor.GenericMenu();
                            menu.AddItem(new GUIContent("Find"), false, D, new G_FindGameObject());
                            menu.AddItem(new GUIContent("FindChild"), false, D, new G_FindChild());
                            menu.AddItem(new GUIContent("FindGameObjectWithTag"), false, D, new G_FindGameObjectWithTag());
                            menu.AddItem(new GUIContent("FindGameObjectsWithTag"), false, D, new G_FindGameObjectsWithTag());
                            menu.AddItem(new GUIContent("FindObjectOfType"), false, D, new FindObjectOfType());
                            menu.AddItem(new GUIContent("FindObjectsOfType"), false, D, new FindObjectsOfType());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("Finish"), false, S, new Finish());
                            menu.AddItem(new GUIContent("CustomFunction"), false, S, new CustomFunctionEvent());
                            menu.AddItem(new GUIContent("CallCustomFunction"), false, S, new CustomFunctionCall());
                            menu.AddItem(new GUIContent("CallCustomFunction(CustomPort)"), false, S, new FunctionCall());
                            menu.AddItem(new GUIContent("FunctionCustomReturn"), false, S, new Return());

                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("ForLoop"), false, S, new ForLoop());
                            menu.AddItem(new GUIContent("ForEach"), false, S, new ForEach <float>());
                            menu.AddItem(new GUIContent("FlipFlop"), false, S, new FlipFlop());

                            menu.ShowAsContext();
                            e.Use();
                        }

                        if (e.keyCode == KeyCode.G)
                        {
                            var menu = new UnityEditor.GenericMenu();
                            menu.AddItem(new GUIContent("GetName"), false, D, new G_Name());
                            menu.AddItem(new GUIContent("GetAcive"), false, D, new G_Active());
                            menu.AddItem(new GUIContent("GetPosition"), false, D, new G_Position());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("GetChildByIndex"), false, D, new G_Child());
                            menu.AddItem(new GUIContent("GetChildCount"), false, D, new G_ChildCount());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("GetComponentByType"), false, D, new G_Component());
                            menu.AddItem(new GUIContent("GetComponentsByType"), false, D, new G_Components());
                            menu.AddItem(new GUIContent("GetComponentByName"), false, D, new G_ComponentByTypeName());
                            menu.AddItem(new GUIContent("GetComponentsInChildren"), false, D, new G_ComponentsInChildren());
                            menu.AddItem(new GUIContent("GetComponentInChildren"), false, D, new G_ComponentInChildren());
                            menu.AddItem(new GUIContent("GetComponentInParent"), false, D, new G_ComponentInParent());

                            menu.ShowAsContext();
                            e.Use();
                        }
                    }

                    if (e.type == EventType.KeyUp && e.alt)
                    {
                        Type genericType;

                        switch (e.keyCode)
                        {
                        case KeyCode.Alpha1:
                            genericType = typeof(GetVariable <>).MakeGenericType(typeof(float));
                            break;

                        case KeyCode.Alpha2:
                            genericType = typeof(GetVariable <>).MakeGenericType(typeof(Vector2));
                            break;

                        case KeyCode.Alpha3:
                            genericType = typeof(GetVariable <>).MakeGenericType(typeof(Vector3));
                            break;

                        case KeyCode.Alpha4:
                            genericType = typeof(GetVariable <>).MakeGenericType(typeof(Quaternion));
                            break;

                        case KeyCode.Alpha5:
                            genericType = typeof(GetVariable <>).MakeGenericType(typeof(Color));
                            break;

                        default:
                            //genericType = typeof(GetVariable<>).MakeGenericType(typeof(float));
                            return;
                            //break;
                        }

                        var varN = (FlowNode)GraphEditor.currentGraph.AddNode(genericType);
                        varN.position = ViewToCanvas(e.mousePosition - varN.rect.center * 0.5f);

                        NodeCanvas.Editor.GraphEditorUtility.activeElement = varN;

                        e.Use();
                    }
                }
                if (e.type == EventType.KeyDown && e.keyCode == KeyCode.F && GUIUtility.keyboardControl == 0)
                {
                    FocusSelection();
                }

                #endregion


                //'Tilt' or 'Space' keys, opens up the complete context menu browser
                if (e.type == EventType.KeyDown && !e.shift && (e.keyCode == KeyCode.BackQuote || e.keyCode == KeyCode.Space))
                {
                    GenericMenuBrowser.Show(GetAddNodeMenu(graph, canvasMousePos), e.mousePosition, string.Format("Add {0} Node", graph.GetType().FriendlyName()), graph.baseNodeType);
                    e.Use();
                }

                //Right click canvas context menu. Basicaly for adding new nodes.
                if (e.type == EventType.ContextClick)
                {
                    var menu = GetAddNodeMenu(graph, canvasMousePos);
                    if (CopyBuffer.Has <Node[]>() && CopyBuffer.Peek <Node[]>()[0].GetType().IsSubclassOf(graph.baseNodeType))
                    {
                        menu.AddSeparator("/");
                        var copiedNodes = CopyBuffer.Get <Node[]>();
                        if (copiedNodes.Length == 1)
                        {
                            menu.AddItem(new GUIContent(string.Format("Paste Node ({0})", copiedNodes[0].GetType().FriendlyName())), false, () => { TryPasteNodesInGraph(graph, copiedNodes, canvasMousePos); });
                        }
                        else if (copiedNodes.Length > 1)
                        {
                            menu.AddItem(new GUIContent(string.Format("Paste Nodes ({0})", copiedNodes.Length.ToString())), false, () => { TryPasteNodesInGraph(graph, copiedNodes, canvasMousePos); });
                        }
                    }

                    if (NCPrefs.useBrowser)
                    {
                        menu.ShowAsBrowser(e.mousePosition, string.Format("Add {0} Node", graph.GetType().FriendlyName()), graph.baseNodeType);
                    }
                    else
                    {
                        menu.ShowAsContext();
                    }
                    e.Use();
                }
            }
        }
예제 #36
0
 // Use this for initialization
 void Start()
 {
     findHeuristics(firstnode);
     nodecheck = firstnode;
 }
예제 #37
0
        public ActionResult Index()
        {
            //instantiate classes
            Random     rand                   = new Random();
            CreateTree createTree             = new CreateTree();
            FindNode   node                   = new FindNode();
            FindingCallNumbersModel     model = new FindingCallNumbersModel();
            FindingCallNumbersViewModel vm    = new FindingCallNumbersViewModel();

            model.TopLevel    = new List <string>();
            model.SecondLevel = new List <string>();
            model.ThirdLevel  = new List <string>();
            //set question amount
            model.QuestionAmt = 4;

            //call method from Helper class to assign to Tree
            var tree = createTree.GetTree();

            //call method to assign model with values from tree
            tree.Nodes.ForEach(x => node.GetNode(x, 0, model));

            //instantiate view model
            vm.TopLevelQ       = new List <string>();
            vm.SecondLevelQ    = new List <string>();
            vm.ThirdLevelQ     = new List <string>();
            vm.TimeRunningList = new List <TimeSpan>();

            //TOP LEVEL QUESTIONS
            //get 4 top-level questions
            List <int> randIndexes = new List <int>();

            //get list of random indexes that are unique
            randIndexes = rg.randomNumberList(0, 10, randIndexes, rand);
            //call method that returns random list of unique values
            vm.TopLevelQ = rg.RandomizeList(model.TopLevel, randIndexes);
            //shuffle list again to ensure randomization
            vm.TopLevelQ = vm.TopLevelQ.OrderBy(x => rand.Next()).Take(model.QuestionAmt).ToList();
            //get answer randomly
            vm.topLevelAns = vm.TopLevelQ[rand.Next(0, model.QuestionAmt)];
            //gets first char to get relevant children
            string identifier = vm.topLevelAns[0].ToString();

            //create random index to be the correct answer
            int randNum2 = rand.Next(0, model.QuestionAmt);
            int randNum3 = rand.Next(0, model.QuestionAmt);


            //SECOND LEVEL QUESTIONS
            //second level child questions
            vm.SecondLevelQ = model.SecondLevel.FindAll(x => x.StartsWith(identifier)).Take(model.QuestionAmt).ToList();
            //clear random number list
            randIndexes.Clear();
            //generate new random number list
            randIndexes = rg.randomNumberList(0, model.QuestionAmt, randIndexes, rand);
            //randomize list
            vm.SecondLevelQ = rg.RandomizeList(vm.SecondLevelQ, randIndexes);
            //shuffle list again to ensure randomization
            vm.SecondLevelQ = vm.SecondLevelQ.OrderBy(x => rand.Next()).Take(model.QuestionAmt).ToList();
            //second level child random answer
            vm.secondLevelAns = vm.SecondLevelQ[randNum2].ToString();
            //get first two characters to get children of third level
            string secondLvlIdentifier = vm.secondLevelAns.Substring(0, 2);

            //THIRD LEVEL QUESTIONS
            //third level child questions
            vm.ThirdLevelQ = model.ThirdLevel.FindAll(x => x.StartsWith(secondLvlIdentifier)).Take(model.QuestionAmt).ToList();
            //clear random number list
            randIndexes.Clear();
            //generate new random number list
            randIndexes = rg.randomNumberList(0, model.QuestionAmt, randIndexes, rand);
            //randomize list
            vm.ThirdLevelQ = rg.RandomizeList(vm.ThirdLevelQ, randIndexes);
            //shuffle questions for randomization
            vm.ThirdLevelQ = vm.ThirdLevelQ.OrderBy(x => rand.Next()).Take(model.QuestionAmt).ToList();
            //third level child random answer
            vm.thirdLevelAns = vm.ThirdLevelQ[randNum3].ToString();

            //now need to get only description part of call number to display as question
            vm.question = vm.thirdLevelAns.Substring(vm.thirdLevelAns.IndexOf(' ') + 1);

            //assign the current questions as top level questions
            vm.questionsList = vm.TopLevelQ;
            vm.currentLevel  = 1;
            //assign total marks for test from leaderboard
            //get length of test from leaderboards
            var leaderboards = db.Leaderboards.Where(p => p.Name.Contains("Finding")).FirstOrDefault();

            vm.TotalMarks = leaderboards.TotalMarks;

            //assign tempdata to be accessed in other methods
            TempData["FindingCallNumbersModel"] = vm;

            return(View(vm));
        }
예제 #38
0
    public FindNode startnode = null; //starting point

    #endregion Fields

    #region Methods

    public void Add2Close(FindNode node)
    {
        closelist.Add(node);
    }