Example #1
0
 public void CreateNewQueue(List <Unit> units)
 {
     unitsTurnQueue.Clear();
     foreach (var unit in units)
     {
         unitsTurnQueue.Enqueue(unit, -unit.speed);
     }
 }
Example #2
0
 /// <summary>
 /// Clear intermediate variables.
 /// </summary>
 public virtual void clear()
 {
     _determined_vertex_set.Clear();
     _vertex_candidate_queue.Clear();
     _start_vertex_distance_index.Clear();
     _predecessor_index.Clear();
 }
Example #3
0
        public int[] Resolve(int[] input)
        {
            _queue.Clear();
            _passedPositions.Clear();
            var initialMove = new Move(0, input);

            _queue.Enqueue(initialMove, initialMove.Heuristic());

            while (_queue.Count > 0)
            {
                var move = _queue.Dequeue();

                _passedPositions.Add(move);

                if (move.CurrentState.SequenceEqual(Rules.FinalState))
                {
                    return(move.GetBreadcrumbs());
                }

                var neigbours = move.Neigbors();

                foreach (var neighbor in neigbours)
                {
                    if (!_passedPositions.Contains(neighbor))
                    {
                        _queue.Enqueue(neighbor, neighbor.Heuristic());
                    }
                }
            }

            throw new SolutionNotFoundException(initialMove.CurrentState);
        }
Example #4
0
        public void QueueAddChunks(int loadDistance)
        {
            chunkLoadQueue.Clear();

            float      ld2       = loadDistance * loadDistance;
            ChunkIndex playerLoc = world.Player.ChunkID;

            for (int y = -loadDistance; y < loadDistance; y++)
            {
                for (int x = -loadDistance; x < loadDistance; x++)
                {
                    for (int z = -loadDistance; z < loadDistance; z++)
                    {
                        float d = x * x + y * y + z * z;
                        if (d < ld2)
                        {
                            ChunkIndex index = new ChunkIndex(playerLoc.X + x, playerLoc.Y + y, playerLoc.Z + z, world.Size);
                            lock (chunkLoadingList)
                            {
                                if (!Chunks.ContainsKey(index) && !chunkLoadingList.Contains(index))
                                {
                                    chunkLoadQueue.Enqueue(index, d);
                                }
                            }
                        }
                    }
                }
            }
        }
        private void HookManager_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == ClearListsKey)
            {
                BulkTradeQueue.Clear();
                TradesQueue.Clear();
                frmItemLists.ClearLists();
            }
            if (e.KeyCode == this.LiveSearchMsgKey)
            {
                Task t = this.SendMessage();
            }
            if (e.KeyCode == this.BulkSearchMsgKey)
            {
                if (BulkTradeQueue.Count > 0)
                {
                    BulkTradeInfo item;
                    bool          ok = BulkTradeQueue.TryDequeue(out item);
                    if (ok)
                    {
                        frmItemLists.RemoveItemFromGrid(item.Id, true);
                        if (item.dblStock >= item.AmountYouGetD)
                        {
                            string msgFormat = "@{0} Hi, I'd like to buy your {1} {2} for my {3} {4} in {5}.";
                            string msg1      = string.Format(msgFormat, item.IGN, item.TotalAmountYouCanBuy, item.ItemYouGet, item.BuyAllPrice, item.ItemYouPay, item.LeagueName);
                            bool   clipSet   = false;
                            int    i         = 0;
                            while (clipSet != true)
                            {
                                i++;
                                try
                                {
                                    if (i < 3)
                                    {
                                        System.Windows.Forms.Clipboard.SetText(msg1);
                                        clipSet = true;
                                    }
                                    else
                                    {
                                        clipSet = true;
                                    }
                                }
                                catch
                                { }
                            }

                            inputSim.Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.RETURN);
                            inputSim.Keyboard.KeyUp(WindowsInput.Native.VirtualKeyCode.RETURN);
                            inputSim.Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.CONTROL);
                            inputSim.Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.VK_V);
                            inputSim.Keyboard.KeyUp(WindowsInput.Native.VirtualKeyCode.VK_V);
                            inputSim.Keyboard.KeyUp(WindowsInput.Native.VirtualKeyCode.CONTROL);
                            inputSim.Keyboard.KeyDown(WindowsInput.Native.VirtualKeyCode.RETURN);
                            inputSim.Keyboard.KeyUp(WindowsInput.Native.VirtualKeyCode.RETURN);
                        }
                    }
                }
            }
        }
Example #6
0
 private void Clear()
 {
     mPaths.Clear();
     mVisited.Clear();
     mPathRecord.Clear();
     mWeights.Clear();
     mTargetReached = false;
 }
Example #7
0
    public static Queue <Entity> FindPath(Entity start, Entity end, float D, float D2)
    {
        frontier.Clear();
        start.moveCost.cost = 0f;
        frontier.Enqueue(start, 0);
        exploredNodes.Clear();
        exploredNodes.Add(start);

        Entity current;
        float  cost;

        while (frontier.Count > 0)
        {
            current = frontier.Dequeue();

            if (current == end)
            {
                return(ReconstructPath(ref end, ref start));
            }

            neighbors = current.neighbors.neighbors;
            for (int i = 0; i < neighbors.Count; i++)
            {
                var next = neighbors [i];

                if (next.node.isBlocked || next.hasLastBlocked || next.isTemporaryBlocked)
                {
                    continue;
                }

                if ((next.position.x + next.position.z) - (current.position.x + current.position.z) == 1)
                {
                    cost = D;
                }
                else
                {
                    cost = D2;
                }

                var newCost = current.moveCost.cost + cost;
                if (!exploredNodes.Contains(next) || next.moveCost.cost > newCost)
                {
                    next.moveCost.cost   = newCost;
                    next.cameFrom.origin = current;
                    if (!exploredNodes.Contains(next))
                    {
                        exploredNodes.Add(next);
                    }

                    var priority = newCost + GetHScore(next.position, end.position, D, D2) * 1.5f;
                    frontier.Enqueue(next, priority);                      //smaller priority go first
                }
            }
        }

        return(null);
    }
Example #8
0
 /// <summary>
 /// clears prev search data for next search
 /// </summary>
 public void clearSearch()
 {
     priorityQueue.Clear();
     currentNode  = null;
     currentState = new State();
     exploredStack.Clear();
     finalNode             = null;
     replayActionText.text = "Action";
 }
Example #9
0
        public void QueueChunkUpdates(int loadDistance)
        {
            chunkUpdateQueue.Clear();

            foreach (ChunkIndex i in Chunks.Keys)
            {
                float d = i.X * i.X + i.Y * i.Y + i.Z * i.Z;
                chunkUpdateQueue.Enqueue(i, d);
            }
        }
Example #10
0
    private void ClearOpen()
    {
        foreach (var s in m_open)
        {
            s.Opened = s.Closed = false;
            s.SetSearchType(SearchType.None, true);
        }

        m_open.Clear();
    }
Example #11
0
        public static List <Operation> GeneratePlan(World world, State initialState, Goal goal, Heuristic heuristic)
        {
            heuristic.InitialiseGoal(goal);

            //Open 1 pour avoir le min en O(logn)
            //Open 2 pour faire un check O(1)
            //si le state est deja dans open et doit etre updated
            SimplePriorityQueue <State> open  = new SimplePriorityQueue <State>();
            HashSet <State>             open2 = new HashSet <State>();
            HashSet <State>             close = new HashSet <State>();

            State currentState = initialState;

            open.Enqueue(currentState, 0);
            open2.Add(currentState);

            bool foundSolution = false;

            while (open.Count > 0)
            {
                currentState = open.Dequeue();
                open2.Remove(currentState);

                if (showDetails)
                {
                    Console.WriteLine(currentState.ToString());
                }

                close.Add(currentState);

                if (goal.GoalSatisfied(currentState))
                {
                    foundSolution = true;
                    open.Clear();
                    break;
                }

                List <Operation> nextOperations = world.GetActions(currentState);
                List <State>     nextStates     = GenerateNextStates(world, currentState, nextOperations);

                VisitNextStates(heuristic, open, open2, close, currentState, nextStates, nextOperations);
            }

            if (foundSolution)
            {
                return(GetActionsFromParent(currentState));
            }
            else
            {
                return(null);
            }
        }
    private IEnumerator UpdatePath()
    {
        yield return(new WaitForSeconds(timeBetweenSearches));


        if (isSearching &&
            !path.Contains(graph.playerLastNodeID) &&
            graph.playerLastNodeID != -1 &&
            mostRecentNode != graph.playerLastNodeID &&
            groundedEntity.IsTouchingFloor())
        {
            path = graph.GetPathIDs(mostRecentNode, graph.playerLastNodeID);

            pathMessageLookup = graph.GetPathMessages(path);

            messagePriorityQueue.Clear();
            messagePriorityQueue.Enqueue(pathMessageLookup[mostRecentNode], -1000);
            //isSearching = true;
        }

        StartCoroutine(UpdatePath());
    }
Example #13
0
    protected virtual void Initialize()
    {
        m_openQueue.Clear();

        ForeachNode((node) =>
        {
            node.G = c_large;
            node.SetRhs(c_large, null);
        });

        BeginNode().SetRhs(0, null);
        BeginNode().LPAKey = CalculateKey(BeginNode());
        AddOrUpdateOpenQueue(BeginNode());
    }
Example #14
0
        public void QueueRemoveChunks(int loadDistance)
        {
            chunkUnloadQueue.Clear();

            ChunkIndex playerLoc = world.Player.ChunkID;

            foreach (Chunk c in Chunks.Values.ToList())
            {
                float d = playerLoc.Distance(world.Size, c.ChunkID);
                if (d > loadDistance)
                {
                    chunkUnloadQueue.Enqueue(c.ChunkID, 64 / (d + 1));
                }
            }
        }
 /* Method: reset
  * -------------
  * Resets to compute a new diagram.
  */
 public void reset()
 {
     // Leftover beach sections to the used list
     if (beachLine.Root)
     {
         BeachArc arc = beachLine.GetFirst(beachLine.Root);
         while (arc)
         {
             usedBeachArcs.Add(arc);
             arc = arc.Next;
         }
     }
     beachLine.Root = null;
     // Reset sweep line (should be empty)
     sweepLine.Clear();
 }
Example #16
0
    private void ClearOpen(bool clearShow)
    {
        m_open.Clear();

        ForeachNode((n) =>
        {
            n.Opened = false;

            if (!n.IsObstacle() && n.SearchType == SearchType.Open)
            {
                n.SetSearchType(SearchType.None, true, true);
            }

            if (clearShow && !n.IsObstacle() && n.SearchType == SearchType.Expanded)
            {
                n.SetSearchType(SearchType.None, true, true);
            }
        });
    }
        private bool FindPath(Cell start, Cell goal)
        {
            frontier.Clear();

            cameFrom.Clear();

            costSoFar.Clear();

            frontier.Enqueue(start, 0);

            cameFrom[start] = start;

            costSoFar[start] = 0;

            while (frontier.Count > 0)
            {
                var current = frontier.Dequeue();

                if (current == goal)
                {
                    return(true);
                }

                foreach (var next in GetNeighbors(current, goal))
                {
                    int newCost = costSoFar[current] + 1;

                    if (!costSoFar.ContainsKey(next) || newCost < costSoFar[next])
                    {
                        costSoFar[next] = newCost;

                        int priority = newCost + Heuristic(next, goal);

                        frontier.Enqueue(next, priority);

                        cameFrom[next] = current;
                    }
                }
            }

            return(false);
        }
Example #18
0
    /// <summary>
    /// Performs whatever actions in the queue it can.
    /// </summary>
    public void performActions(Ecosystem eco)
    {
        // the queue for the next turn
        SimplePriorityQueue <Action> nextQueue = new SimplePriorityQueue <Action>();

        while (actionQueue.Count > 0)
        {
            Action nextAction = actionQueue.Dequeue();

            // if action is not possible, then ignore it (don't add it to the queue)
            if (nextAction.isPossible(this))
            {
                // ignore actions that the creature doesn't have enough resources to perform
                if (nextAction.enoughResources(this))
                {
                    // if there is time left for an action, perform it
                    if (nextAction.timeCost <= remainingTurnTime)
                    {
                        //Debug.Log("performing " + nextAction.name);
                        nextAction.performWrapper(this, eco);
                    }
                    else
                    {
                        // put actions that take too long on the next turn's queue
                        nextQueue.Enqueue(nextAction, nextAction.priority);
                    }
                }
            }
        }
        // actionQueue is now the queue for next turn
        actionQueue = nextQueue;

        // keep action queue a manageable size by clearing it every few steps, and clearing it if its size gets too big
        if (actionClearCount > actionClearInterval || actionQueue.Count >= actionClearSize)
        {
            actionClearCount = 0;
            actionQueue.Clear();
        }
        actionClearCount++;
        //Debug.Log("Queue size: " + actionQueue.Count);
    }
Example #19
0
        public void Reset()
        {
            stopwatch.Reset();

            Start = null;
            Goal  = null;

            startNode   = null;
            goalNode    = null;
            currentNode = null;

            nodesThisCall = 0;

            closedSet.Clear();
            openSet.Clear();
            cameFrom.Clear();
            g_score.Clear();
            f_score.Clear();
            IsInitialized = false;
            IsReady       = false;
        }
Example #20
0
 public static void FFBProcessingThread()
 {
     try {
         logger.Info("Starting FFBProcThread");
         while (true)
         {
             while (packets.Count > 0)
             {
                 VirtualFFBPacket packet = packets.Dequeue();
                 handlers[packet.ID]?.Invoke(packet);
                 //FFBDataReceived?.Invoke(packets.Dequeue());
                 //Thread.Sleep(1);
             }
             Thread.Sleep(100);
             //newDataEvent.WaitOne();
         }
     } catch (ThreadAbortException) {
         logger.Info("Stopping FFBProcThread");
     } catch (Exception ex) {
         logger.Warn($"FFBProcThread WTF {ex}");
     } finally {
         packets.Clear();
     }
 }
 public void clear()
 {
     simplePriorityQueue.Clear();
 }
Example #22
0
 /// <summary>
 /// Cleans this instance.
 /// </summary>
 public override void clean()
 {
     base.clean();
     pQueue.Clear();
 }
Example #23
0
        public static bool RequestPathFromTile(CaveStateNode startTile, CaveStateNode targetTile, List <CaveStateNode> bestPath, out int totalCost)
        {
            // Clear our initial state
            _costs.Clear();
            _frontier.Clear();
            _pathInProgress.Clear();
            _scratch.Clear();
            bestPath.Clear();

            totalCost = Int32.MaxValue;
            _frontier.Enqueue(startTile, 0);
            _costs[startTile]          = 0;
            _pathInProgress[startTile] = null;

            do
            {
                /*
                 * _frontier.Sort(delegate(CaveStateNode tA, CaveStateNode tB)
                 * {
                 *
                 *
                 *  return (_costs[tA] + Distance(tA, targetTile)).CompareTo(_costs[tB] + Distance(tB, targetTile));
                 * });*/

                CaveStateNode currentTile = _frontier.Dequeue();
                if (currentTile == targetTile)
                {
                    break;
                }
                //_frontier.RemoveAt(0);

                Dictionary <CaveStateNode, int> transitions = currentTile.Transitions;
                foreach (var kvp in transitions)
                {
                    var neighbor        = kvp.Key;
                    int incrementalCost = kvp.Value;
                    int navCost         = 0;
                    _costs.TryGetValue(currentTile, out navCost);
                    navCost += incrementalCost;
                    int knownCost = 0;
                    if (!_costs.TryGetValue(neighbor, out knownCost))
                    {
                        knownCost = Int32.MaxValue;
                    }

                    if (navCost < knownCost)
                    {
                        _costs[neighbor]          = navCost;
                        _pathInProgress[neighbor] = currentTile;
                        _frontier.Enqueue(neighbor, navCost + Distance(neighbor, targetTile));
                    }
                }
            } while (_frontier.Count > 0);

            if (_pathInProgress.ContainsKey(targetTile))
            {
                var next = targetTile;
                while (next != startTile)
                {
                    bestPath.Add(next);
                    next = _pathInProgress[next];
                }
                bestPath.Reverse();
                totalCost = _costs[targetTile];
                return(true);
            }


            return(false);
        }
 private void ClearQueue()
 {
     m_Queue.Clear();
 }
Example #25
0
 public override void Clear()
 {
     _queue.Clear();
 }
Example #26
0
        public Path FindPath(Waypoint start, Waypoint end)
        {
            bool found = false;

            _distances.Clear();
            _distancesSorted.Clear();
            _visited.Clear();
            _predecessors.Clear();

            // init with d(start)=0
            _distances.Add(start, 0);

            Waypoint current = start;

            _visited.Add(start);

            Steps          = 0;
            VisitedNodes   = 0;
            InspectedNodes = 0;

            while (true)
            {
                Steps++;
                var unvisitedNeighbours = current.Connections.Where(c => !_visited.Contains(c));
                UpdateDistances(current, unvisitedNeighbours);


                current = _distancesSorted.Count > 0 ? _distancesSorted.Dequeue() : null;

                if (current == null)
                {
                    break;
                }
                else if (current == end)
                {
                    found = true;
                    break;
                }

                _visited.Add(current);
            }

            VisitedNodes   = _visited.Count;
            InspectedNodes = _distances.Count;

            if (found)
            {
                Path p = new Path();

                current = end;

                while (current != start)
                {
                    var next = _predecessors[current];
                    p.Waypoints.Insert(0, _predecessors[current]);
                    current = next;
                }

                return(p);
            }

            return(null);
        }
Example #27
0
 public void Clear()
 {
     _queue.Clear();
 }
Example #28
0
        Dictionary <int, int> costSoFarDict = new Dictionary <int, int>();                  // 储存所有格子的到起点的最少花费

        void DoBFS()
        {
            if (mapWidth == 0 || mapHeight == 0)
            {
                return;
            }
            if (view.player.Index >= gridCount)
            {
                return;
            }

            // 储存边界的优先队列
            frontierPriorityQueue.Clear();
            frontierPriorityQueue.Enqueue(view.player.Index, 0);

            cameFromDict.Clear();

            costSoFarDict.Clear();
            costSoFarDict[view.player.Index] = 0;

            int curStep = 0;
            int next    = 0;
            int newCost = 0;

            while (!ShowStep || curStep < Step)
            {
                if (frontierPriorityQueue.Count > 0)
                {
                    int curIndex = frontierPriorityQueue.Dequeue();

                    // 边界到达目标点,提前结束
                    if (EarlyExit && curIndex == view.target.Index)
                    {
                        break;
                    }

                    CalcNeighborIndexs(ref neighborArray, curIndex);
                    for (int i = 0; i < neighborArray.Length; i++)
                    {
                        next = neighborArray[i];
                        if (next == -1)
                        {
                            continue;                           // 四周
                        }
                        if (curMapData.IsBlock(next))
                        {
                            continue;                           // 墙
                        }
                        int toNextCost = HasMovementCost ? (curMapData[next] == PathFindingGridView.NORMAL ? 1 : 5) : 1;
                        newCost = costSoFarDict[curIndex] + toNextCost;
                        if (!costSoFarDict.ContainsKey(next) || newCost < costSoFarDict[next])  // 没被探索
                        {
                            costSoFarDict[next] = newCost;
                            frontierPriorityQueue.Enqueue(next, newCost);       // 步数少的优先探索
                            cameFromDict[next] = curIndex;
                        }
                    }
                }
                else
                {
                    break;
                }
                if (ShowStep)
                {
                    curStep++;
                }
            }

            // 通过cameFromArray,找出路径
            pathList.Clear();
            int current = view.target.Index;

            if (cameFromDict.ContainsKey(current))   // 说明已探索到target
            {
                while (current != view.player.Index)
                {
                    pathList.Add(current);
                    current = cameFromDict[current];
                }
            }

            curMapData.ClearShowArray();
            if (HasMovementCost)
            {
                for (int i = 0; i < curMapData.showArray.Length; i++)
                {
                    curMapData.showArray[i] = curMapData[i];
                }
            }
            else
            {
                // 标记已探索
                for (int i = 0; i < curMapData.showArray.Length; i++)
                {
                    curMapData.showArray[i] = cameFromDict.ContainsKey(i) ? PathFindingGridView.REACHED : curMapData.showArray[i];
                }
                // 标记边界
                while (frontierPriorityQueue.Count > 0)
                {
                    int index = frontierPriorityQueue.Dequeue();
                    curMapData.showArray[index] = PathFindingGridView.FRONTIER;
                }
            }
        }
    public List <Vector2Int> FindPath(Vector2Int start, Vector2Int end, Func <Node, Node, PathCost> costFunction)
    {
        ResetNodes();
        queue.Clear();
        closed.Clear();

        queue  = new SimplePriorityQueue <Node, float>();
        closed = new HashSet <Node>();

        grid[start].Cost = 0;
        queue.Enqueue(grid[start], 0);

        while (queue.Count > 0)
        {
            Node node = queue.Dequeue();
            closed.Add(node);

            if (node.Position == end)
            {
                return(ReconstructPath(node));
            }

            foreach (var offset in neighbors)
            {
                if (!grid.InBounds(node.Position + offset))
                {
                    continue;
                }
                var neighbor = grid[node.Position + offset];
                if (closed.Contains(neighbor))
                {
                    continue;
                }

                var pathCost = costFunction(node, neighbor);
                if (!pathCost.traversable)
                {
                    continue;
                }

                float newCost = node.Cost + pathCost.cost;

                if (newCost < neighbor.Cost)
                {
                    neighbor.Previous = node;
                    neighbor.Cost     = newCost;

                    if (queue.TryGetPriority(node, out float existingPriority))
                    {
                        queue.UpdatePriority(node, newCost);
                    }
                    else
                    {
                        queue.Enqueue(neighbor, neighbor.Cost);
                    }
                }
            }
        }

        return(null);
    }
Example #30
0
 public static void DisposeAllTimers()
 {
     _queue.Clear();
 }