コード例 #1
0
        public void UniqueQueueDequeue()
        {
            UniqueQueue <int> queue = new UniqueQueue <int>();

            queue.Enqueue(10);
            Assert.That(queue.Dequeue(), Is.EqualTo(10));
            Assert.Throws <InvalidOperationException>(() => queue.Dequeue());
        }
コード例 #2
0
        public static Dfa ToDfa(this Nfa nfa)
        {
            var once  = new UniqueQueue <NfaClosure>();
            var start = new NfaClosure(nfa.Start, nfa.End);

            once.Enqueue(start);

            while (once.Count > 0)
            {
                var closure     = once.Dequeue();
                var transitions = closure.UnambiguateTransitions();

                foreach (var transition in transitions)
                {
                    var terminal      = transition.Key;
                    var targets       = transition.Value;
                    var targetClosure = new NfaClosure(targets, nfa.End);
                    once.Enqueue(targetClosure, out targetClosure);
                    var target = targetClosure.State;

                    closure.State.Add(Atom.From(terminal), target);
                }
            }

            //return new Dfa(start.State);
            return(new Dfa(start.State));
        }
コード例 #3
0
        private void OnServerTick100ms(float dt)
        {
            accum += dt;

            if (updateSnowLayerQueue.Count > 5 || (accum > 1 && updateSnowLayerQueue.Count > 0))
            {
                accum = 0;
                int cnt = 0;
                int max = 10;
                UpdateSnowLayerChunk[] q = new UpdateSnowLayerChunk[max];

                lock (updateSnowLayerQueueLock)
                {
                    while (updateSnowLayerQueue.Count > 0)
                    {
                        q[cnt] = updateSnowLayerQueue.Dequeue();
                        cnt++;
                        if (cnt >= max)
                        {
                            break;
                        }
                    }
                }

                for (int i = 0; i < cnt; i++)
                {
                    processBlockUpdates(q[i].Coords, q[i], ba);
                }

                ba.Commit();
            }
        }
コード例 #4
0
        private void onThreadTick()
        {
            while (!isShuttingDown)
            {
                Thread.Sleep(5);
                int i = 0;

                while (chunkColsstoCheckQueue.Count > 0 && i++ < 10)
                {
                    Vec2i chunkCoord;
                    lock (chunkstoCheckQueueLock)
                    {
                        chunkCoord = chunkColsstoCheckQueue.Dequeue();
                    }

                    int regionX = (chunkCoord.X * chunksize) / regionsize;
                    int regionZ = (chunkCoord.Y * chunksize) / regionsize;

                    WeatherSimulationRegion sim = ws.getOrCreateWeatherSimForRegion(regionX, regionZ);

                    IServerMapChunk mc = sapi.WorldManager.GetMapChunk(chunkCoord.X, chunkCoord.Y);

                    if (mc != null && sim != null)
                    {
                        UpdateSnowLayerOffThread(sim, mc, chunkCoord);
                    }
                }
            }
        }
コード例 #5
0
        public void Update(GameTime gameTime)
        {
            foreach (AbstractCreature creature in creatures)
            {
                creature.Update(gameTime);
            }

            // Remove dead creatures
            // iterate backwards to remove them from the array as we loop
            for (int i = creatures.Count - 1; i >= 0; i--)
            {
                if (!creatures[i].alive)
                {
                    creatures.RemoveAt(i);
                }
            }

            if (blockUpdateQueue.Count == 0)
            {
                blockUpdateQueue = new UniqueQueue <byte[]>(nextBlockUpdateQueue);
                nextBlockUpdateQueue.Clear();
            }

            for (int i = 0; i < 64000 && blockUpdateQueue.Count > 0; i++)
            {
                byte[] blockPosition = blockUpdateQueue.Dequeue();
                blocks[blockPosition[0], blockPosition[1], blockPosition[2]].Update(gameTime);
            }
        }
コード例 #6
0
        public override void OnOffThreadTick()
        {
            int quantityToGen = chunksToGen.Count;

            while (quantityToGen > 0)
            {
                quantityToGen--;
                Vec2i cord;

                lock (chunksToGenLock)
                {
                    if (chunksToGen.Count == 0)
                    {
                        break;
                    }
                    cord = chunksToGen.Dequeue();
                }

                if (!api.World.BlockAccessor.IsValidPos(cord.X * chunksize, 1, cord.Y * chunksize))
                {
                    continue;
                }

                IMapChunk mc = api.World.BlockAccessor.GetMapChunk(cord);
                if (mc == null)
                {
                    lock (chunksToGenLock)
                    {
                        chunksToGen.Enqueue(cord);
                    }

                    continue;
                }

                int[] pixels = (int[])GenerateChunkImage(cord, mc)?.Clone();

                if (pixels == null)
                {
                    lock (chunksToGenLock)
                    {
                        chunksToGen.Enqueue(cord);
                    }
                    continue;
                }

                api.Event.EnqueueMainThreadTask(() =>
                {
                    if (loadedMapData.ContainsKey(cord))
                    {
                        UpdateMapData(loadedMapData[cord] as ChunkMapComponent, pixels);
                    }
                    else
                    {
                        mapSink.AddMapData(loadedMapData[cord] = LoadMapData(cord, pixels));
                    }
                }, "chunkmaplayerready");
            }
        }
コード例 #7
0
        public void Dequeue_QueuedString_Dequeued()
        {
            UniqueQueue <string> queue = new UniqueQueue <string>();

            queue.Enqueue("abc");

            Assert.Equal("abc", queue.Dequeue());
            Assert.Equal(0, queue.Count);
        }
コード例 #8
0
        public void Dequeue_WhileEmpty_InvalidOperationException()
        {
            UniqueQueue <string> queue = new UniqueQueue <string>();

            Assert.Throws <InvalidOperationException>(() =>
            {
                queue.Dequeue();
            });
        }
コード例 #9
0
        public void Enqueue_QueueAnotherOfSameStringAfterDequeue_BothQueuesSuccess()
        {
            UniqueQueue <string> queue = new UniqueQueue <string>();

            queue.Enqueue("abc");
            queue.Dequeue();
            queue.Enqueue("abc");

            Assert.Equal(1, queue.Count);
        }
コード例 #10
0
        public static void TestSimple()
        {
            UniqueQueue <int> queue = new UniqueQueue <int>();

            Assert.IsTrue(queue.Enqueue(0));
            Assert.IsFalse(queue.Enqueue(0));
            Assert.IsTrue(queue.Contains(0));
            Assert.AreEqual(queue.Peek(), 0);
            Assert.AreEqual(queue.Dequeue(), 0);
        }
コード例 #11
0
        public override void OnOffThreadTick()
        {
            int quantityToGen = chunksToGen.Count;

            while (quantityToGen > 0)
            {
                quantityToGen--;
                Vec2i cord;

                lock (chunksToGenLock)
                {
                    if (chunksToGen.Count == 0)
                    {
                        break;
                    }
                    cord = chunksToGen.Dequeue();
                }

                IMapChunk mc = api.World.BlockAccessor.GetMapChunk(cord);
                if (mc == null)
                {
                    lock (chunksToGenLock)
                    {
                        chunksToGen.Enqueue(cord);
                    }
                    continue;
                }

                int[] pixels = (int[])GenerateChunkImage(cord, mc)?.Clone();

                if (pixels == null)
                {
                    lock (chunksToGenLock)
                    {
                        chunksToGen.Enqueue(cord);
                    }
                    continue;
                }

                api.Event.EnqueueMainThreadTask(() =>
                {
                    if (loadedMapData.ContainsKey(cord))
                    {
                        loadedMapData[cord].Dispose();
                        mapSink.RemoveMapData(loadedMapData[cord]);
                    }

                    mapSink.AddMapData(loadedMapData[cord] = LoadMapData(cord, pixels));
                }, "chunkmaplayerready");
            }
        }
コード例 #12
0
 public void goToFloor(int floor)
 {
     if (currentFloor != floor)
     {
         transform.position = new Vector2(transform.position.x, Mathf.MoveTowards(transform.position.y, FloorSpaceManager.convertFloorToPosition(floor), speed));
         if (Mathf.Approximately(transform.position.y, Mathf.Round(transform.position.y)))
         {
             currentFloor = FloorSpaceManager.convertPositionToFloor(transform.position.y);
         }
     }
     else
     {
         floorQueue.Dequeue();
     }
 }
コード例 #13
0
        private void ReadCommand(object state)
        {
            if (commandsList.Count != 0)
            {
                var command = commandsList.Dequeue();
                var message = command.Value <JObject>("message");

                var messageID = message.Value <int>("message_id");
                var userID    = message.Value <JObject>("chat").Value <int>("id");
                var text      = message.Value <string>("text");

                string answerUrl = commandProcessor.Process(messageID, userID, text);
                string response  = Synchronizer.RunSync(new Func <Task <string> >
                                                            (async() => await VisitAsync(answerUrl)));
            }
        }
コード例 #14
0
        public IEnumerable <State> Closure()
        {
            var once = new UniqueQueue <State>();

            once.Enqueue(this);

            while (once.Count > 0)
            {
                var state = once.Dequeue();
                foreach (var transition in state.EpsilonTransitions)
                {
                    once.Enqueue(transition.Target);
                }
            }

            return(once.Seen);
        }
コード例 #15
0
        static void Main(string[] args)
        {
            string seed                   = "http://web.archive.org/web/20100101163446/http://www.fool.com/";
            int    downloadCounter        = 0;
            UniqueQueue <string> urlQueue = new UniqueQueue <string>();
            WebClient            client   = new WebClient();

            if (!Directory.Exists(DOWNLOADS_FOLDER))
            {
                Directory.CreateDirectory(DOWNLOADS_FOLDER);
            }

            urlQueue.Enqueue(seed);
            while (urlQueue.Count > 0 && downloadCounter < DOWNLOAD_LIMIT)
            {
                string url = urlQueue.Dequeue();
                Console.WriteLine("Downloading from {0}", url);
                try
                {
                    string html     = client.DownloadString(url);
                    string filename = (url.Split('/').Last().Length > 0 ? url.Split('/').Last() : DateTime.Now.Ticks.ToString() + ".html");
                    using (StreamWriter outfile = new StreamWriter(Path.Combine(DOWNLOADS_FOLDER, filename)))
                    {
                        outfile.Write(html);
                    }

                    IEnumerable <string> links = GetLinks(html);
                    foreach (var link in links)
                    {
                        urlQueue.Enqueue(link);
                    }
                    seen[url] = true;
                    downloadCounter++;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            Console.WriteLine("{0} URLs downloaded, {1} URLs remaining in queue", downloadCounter, urlQueue.Count);
            Console.ReadLine();
        }
コード例 #16
0
        /// <summary>
        /// Get or create a new instance
        /// </summary>
        /// <returns>A valid instance of type <see cref="T"/></returns>
        public T Get()
        {
            T result;

            if (m_items.Count == 0)
            {
                result = new T();
            }
            else
            {
                result = m_items.Dequeue();
                if (result == null)
                {
                    throw new NullReferenceException("A null item has been found in the pool. " +
                                                     "That means the item has been modified or destroyed after recycle operation." +
                                                     "Be sure, after having recycled an item, to not access it anymore since its ownership" +
                                                     "can be assigned to any other object that requires it.");
                }
            }

            return(result);
        }
コード例 #17
0
        private void OnServerTick100ms(float dt)
        {
            accum += dt;

            if (updateSnowLayerQueue.Count > 5 || (accum > 1 && updateSnowLayerQueue.Count > 0))
            {
                accum = 0;
                int cnt = 0;
                int max = 10;
                UpdateSnowLayerChunk[] q = new UpdateSnowLayerChunk[max];

                lock (updateSnowLayerQueue)
                {
                    while (updateSnowLayerQueue.Count > 0)
                    {
                        q[cnt] = updateSnowLayerQueue.Dequeue();
                        cnt++;
                        if (cnt >= max)
                        {
                            break;
                        }
                    }
                }

                for (int i = 0; i < cnt; i++)
                {
                    IMapChunk mc = sapi.WorldManager.GetMapChunk(q[i].Coords.X, q[i].Coords.Y);
                    if (mc == null)
                    {
                        continue;             // No longer loaded, we can just ditch it and re-do the thing again next time it gets loaded again
                    }
                    processBlockUpdates(mc, q[i], ba);
                }

                ba.Commit();
            }
        }
コード例 #18
0
            public static FA ToDfa(FA nfa)
            {
                if (nfa.Final == null)
                {
                    EnsureDfa(nfa);
                    return(nfa);
                }

                var once  = new UniqueQueue <Closure>();
                var start = new Closure(nfa.Start, nfa.Final);

                once.Enqueue(start);

                while (once.Count > 0)
                {
                    var closure     = once.Dequeue();
                    var transitions = closure.UnambiguateTransitions();

                    foreach (var transition in transitions)
                    {
                        var terminal      = transition.Key;
                        var targets       = transition.Value;
                        var targetClosure = new Closure(targets, nfa.Final);
                        once.Enqueue(targetClosure, out targetClosure);
                        var target = targetClosure.DfaState;

                        closure.DfaState.Add(Integers.From(terminal), target);
                    }
                }

                var dfa = From(start.DfaState);

                EnsureDfa(dfa);

                return(dfa);
            }
コード例 #19
0
        public List <MatchPlayer> GetCurrentPlayers(LeagueType RANK = LeagueType.NONE)
        {
            lock (m_queue)
            {
                List <MatchPlayer> pl = new List <MatchPlayer>();
                if (RANK == LeagueType.NONE || !Settings.USE_RANKING_QUEUES)
                {
                    while (m_queue.Count > 0)
                    {
                        if (pl.Count < Settings.MAX_PLAYERS)
                        {
                            pl.Add(m_queue.Dequeue());
                        }
                        else
                        {
                            break;
                        }
                    }
                    return(pl);
                }
            }

            return(null);
        }
コード例 #20
0
ファイル: Chip.cs プロジェクト: polklabs/Project-Bit
        protected virtual void GetOutput(bool forceUpdate)
        {
            int loops = 0;
            UniqueQueue <Guid> queue       = new UniqueQueue <Guid>();
            UniqueQueue <Guid> outputQueue = new UniqueQueue <Guid>();

            // This is a new update loops so make sure gates and chips are not dirty
            foreach (Chip chip in Chips)
            {
                chip.Dirty.SetAll(false);
            }
            foreach (Gate gate in Gates)
            {
                gate.SetClean();
            }

            // Update input wires
            foreach (Wire wire in WireDict[ID])
            {
                if (forceUpdate || FirstRun || (OldInput[wire.FromIndex] != Input[wire.FromIndex]))
                {
                    if (wire.IsChip)
                    {
                        Chip chip = Chips[wire.CircuitIndex];
                        chip.SetInputBit(wire.ToIndex, Input[wire.FromIndex] ^ wire.InvertValue);
                        chip.Update(forceUpdate);

                        if (forceUpdate || FirstRun || chip.IsDirty())
                        {
                            queue.Enqueue(chip.ID);
                        }
                    }
                    else
                    {
                        Gate gate = Gates[wire.CircuitIndex];
                        gate.SetInputBit(wire.ToIndex, Input[wire.FromIndex] ^ wire.InvertValue);
                        gate.Update(ScrubOutput);

                        if (forceUpdate || FirstRun || gate.IsDirty())
                        {
                            queue.Enqueue(gate.ID);
                        }
                    }
                }
            }

            //Update internal components
            while (queue.Count > 0)
            {
                //Stop infinite loops from continuing
                loops++;
                if (loops >= 100)
                {
                    Debug.Log("Infinite loop, breaking");
                    return;
                }

                Guid guid = queue.Dequeue();

                BitArray FromValues;
                BitArray FromDirty;

                // The output of the previous gate
                Gate previousGate = FindGate(guid);
                if (previousGate != null)
                {
                    FromValues = new BitArray(1, previousGate.Output);
                    FromDirty  = new BitArray(1, previousGate.IsDirty());
                }
                else
                {
                    Chip c = FindChip(guid);
                    FromValues = c.Output;
                    FromDirty  = c.Dirty;
                }

                foreach (Wire wire in WireDict[guid])
                {
                    if (wire.IsChip)
                    {
                        if (wire.CircuitIndex == -1)
                        {
                            outputQueue.Enqueue(guid);
                            Output[wire.ToIndex] = FromValues[wire.FromIndex] ^ wire.InvertValue;
                            //Debug.Log("Updated output: " + wire.ToIndex);
                        }
                        else if (FromDirty[wire.FromIndex])
                        {
                            Chip chip = Chips[wire.CircuitIndex];
                            chip.SetInputBit(wire.ToIndex, FromValues[wire.FromIndex] ^ wire.InvertValue);
                            chip.Update(false);
                            //Debug.Log("Updated chip: " + (char)(Chips.FindIndex(x => x.ID == guid) + 65) + "->" + (char)(wire.CircuitIndex + 65));

                            if (chip.IsDirty())
                            {
                                queue.Enqueue(chip.ID);
                            }
                        }
                    }
                    else if (FromDirty[wire.FromIndex])
                    {
                        Gate gate = Gates[wire.CircuitIndex];
                        gate.SetInputBit(wire.ToIndex, FromValues[wire.FromIndex] ^ wire.InvertValue);
                        gate.Update(ScrubOutput);
                        //Debug.Log("Updated gate: " + (char)(wire.CircuitIndex + 65));

                        if (forceUpdate || FirstRun || gate.IsDirty())
                        {
                            queue.Enqueue(gate.ID);
                        }
                    }
                }
            }

            //Update output wires
            while (outputQueue.Count > 0)
            {
                Guid guid = outputQueue.Dequeue();

                BitArray FromValues;

                Gate gate = FindGate(guid);
                if (gate != null)
                {
                    FromValues = new BitArray(1, gate.Output);
                }
                else
                {
                    FromValues = FindChip(guid).Output;
                }

                foreach (Wire wire in WireDict[guid])
                {
                    if (wire.IsChip && wire.CircuitIndex == -1)
                    {
                        Output[wire.ToIndex] = FromValues[wire.FromIndex] ^ wire.InvertValue;
                    }
                }
            }
        }
コード例 #21
0
        public override void OnOffThreadTick(float dt)
        {
            genAccum += dt;
            if (genAccum < 0.1)
            {
                return;
            }
            genAccum = 0;

            int quantityToGen = chunksToGen.Count;

            while (quantityToGen > 0)
            {
                if (mapSink.IsShuttingDown)
                {
                    break;
                }

                quantityToGen--;
                Vec2i cord;

                lock (chunksToGenLock)
                {
                    if (chunksToGen.Count == 0)
                    {
                        break;
                    }
                    cord = chunksToGen.Dequeue();
                }

                if (!api.World.BlockAccessor.IsValidPos(cord.X * chunksize, 1, cord.Y * chunksize))
                {
                    continue;
                }

                IMapChunk mc = api.World.BlockAccessor.GetMapChunk(cord);
                if (mc == null)
                {
                    //api.Logger.Notification("From DB @{0}/{1}", cord.X, cord.Y);
                    MapPieceDB piece = mapdb.GetMapPiece(cord);
                    if (piece?.Pixels != null)
                    {
                        loadFromChunkPixels(cord, piece.Pixels);
                    }

                    continue;
                }

                //api.Logger.Notification("Genpixels @{0}/{1}", cord.X, cord.Y);

                int[] pixels = (int[])GenerateChunkImage(cord, mc)?.Clone();

                if (pixels == null)
                {
                    lock (chunksToGenLock)
                    {
                        chunksToGen.Enqueue(cord);
                    }

                    continue;
                }

                toSaveList[cord.Copy()] = new MapPieceDB()
                {
                    Pixels = pixels
                };


                /// North: Negative Z
                /// East: Positive X
                /// South: Positive Z
                /// West: Negative X

                /*bool north = !api.World.LoadedMapChunkIndices.Contains(MapUtil.Index2dL(cord.X, cord.Y - 1, chunkmapSizeX));
                 * bool east = !api.World.LoadedMapChunkIndices.Contains(MapUtil.Index2dL(cord.X + 1, cord.Y, chunkmapSizeX));
                 * bool south = !api.World.LoadedMapChunkIndices.Contains(MapUtil.Index2dL(cord.X, cord.Y + 1, chunkmapSizeX));
                 * bool west = !api.World.LoadedMapChunkIndices.Contains(MapUtil.Index2dL(cord.X - 1, cord.Y, chunkmapSizeX));*/

                loadFromChunkPixels(cord, pixels /*, (north ? 1 : 0 ) | (east ? 2 : 0) | (south ? 4 : 0) | (west ? 8 : 0)*/);
            }

            if (toSaveList.Count > 100 || diskSaveAccum > 4f)
            {
                diskSaveAccum = 0;
                mapdb.SetMapPieces(toSaveList);
                toSaveList.Clear();
            }
        }
コード例 #22
0
        public static bool FindPath(int size, int iEnd, int jEnd,
                                    Dictionary <string, Path> paths,
                                    HashSet <string> visited,
                                    UniqueQueue <string> notVisited
                                    )
        {
            while (notVisited.Any())
            {
                var currentNode = notVisited.Dequeue();
                var ijCurrent   = currentNode.Split('-').Select(x => int.Parse(x)).ToList();
                var iStart      = ijCurrent[0];
                var jStart      = ijCurrent[1];

                if (iStart == iEnd && jStart == jEnd)
                {
                    return(true);
                }

                //if (visited.Count >= size)
                //{
                //    ifImpossible = true;
                //    return false;
                //}

                //if (iStart >= size || iStart < 0
                //                   || jStart >= size || jStart < 0
                //)
                //{
                //    return false;
                //}

                //var currentNode = $"{iStart}-{jStart}";

                visited.Add(currentNode);


                if (!paths.ContainsKey(currentNode))
                {
                    paths.Add(currentNode, new Path());
                }

                foreach (var move in _movesMap)
                {
                    var newIStart = move.Value.Item1 + iStart;
                    var newJStart = move.Value.Item2 + jStart;
                    var newNode   = $"{newIStart}-{newJStart}";

                    if (newIStart >= size || newIStart < 0 ||
                        newJStart >= size || newJStart < 0 ||
                        visited.Contains(newNode))
                    {
                        continue;
                    }

                    if (!paths.ContainsKey(newNode))
                    {
                        paths.Add(newNode, new Path());
                    }

                    notVisited.Enqueue(newNode);
                    var newCost = paths[currentNode].cost == int.MaxValue ? int.MaxValue : paths[currentNode].cost + 1;
                    var cost    = paths[newNode].cost;
                    if (newCost < cost)
                    {
                        paths[newNode].cost         = newCost;
                        paths[newNode].PreviousNode = currentNode;
                        paths[newNode].Move         = move.Key;
                    }
                }

                //foreach (var neighborNode in notVisited)
                //{
                //    var ij = neighborNode.Split('-').Select(x => int.Parse(x)).ToList();
                //    var isFound = FindPath(size, ij[0], ij[1], iEnd, jEnd, paths, visited, out ifImpossible);
                //    if (isFound)
                //    {
                //        return true;
                //    }

                //    if (ifImpossible)
                //    {
                //        ifImpossible = true;
                //        return false;
                //    }
                //}
            }

            return(false);
        }