Exemple #1
0
    public static Monster CreateMonster(int level, Point location)
    {
        Pool <Monster> monsterPool = new Pool <Monster>();

        monsterPool.Add(Kobold.Create(level), 25);
        monsterPool.Add(Ooze.Create(level), 25);
        monsterPool.Add(Goblin.Create(level), 50);

        Monster monster = monsterPool.Get();

        monster.X = location.X;
        monster.Y = location.Y;

        return(monster);
    }
    public void ReturnRandomNeighborToPool()
    {
        int sizeActiveNeighbors = activeNeighbors.Count;

        if (sizeActiveNeighbors != 0)
        {
            int index = Random.Range(0, sizeActiveNeighbors);

            Neighbor neighbor = activeNeighbors[index];

            activeNeighbors.RemoveAt(index);
            neighbor.Deactivate();
            pool.Add(neighbor);
        }
    }
Exemple #3
0
        static void Main(string[] args)
        {
            Cage cage = new Cage("1", 2);
            Pool pool = new Pool("2", 3);

            // Base system
            Monkey monkey = new Monkey("Donkey Kong");

            cage.Add(monkey);

            // PolyMorphic system
            Turtle turtleL = new Turtle("Leonardo");
            Turtle turtleR = new Turtle("Raphael");
            Turtle turtleD = new Turtle("Donatello");
            Turtle turtleM = new Turtle("Michelangelo");

            pool.Add(turtleL);
            pool.Add(turtleR);
            pool.Add(turtleD);

            // Test Zone capacity limit
            try
            {
                pool.Add(turtleM);
            }
            catch (Exception ex) { Console.Out.WriteLine(ex.Message); }

            // No duplicate animal in many zone
            try
            {
                cage.Add(turtleL);
            }
            catch (Exception ex) { Console.Out.WriteLine(ex.Message); }

            // Test if mixed animal
            Lion lion = new Lion("Simba");

            try
            {
                cage.Add(lion);
            }
            catch (Exception ex) { Console.Out.WriteLine(ex.Message); }

            cage.Remove(monkey);
            cage.Add(lion);

            int i = +1;
        }
Exemple #4
0
        public void PooledObject_ReinitialiseOnTake_RasisesEvent_OnReinitialiseError()
        {
            var policy = new PoolPolicy <PooledObject <DisposableTestPoolItem> >()
            {
                Factory = (p) => new PooledObject <DisposableTestPoolItem>(p, new DisposableTestPoolItem()),
                InitializationPolicy = PooledItemInitialization.Take,
                MaximumPoolSize      = 1,
                ReinitializeObject   = (item) =>
                {
                    throw new OutOfMemoryException("Test");
                }
            };

            var eventRaised = false;

            using (var eventRaisedSignal = new System.Threading.ManualResetEvent(false))
            {
                var pool = new Pool <PooledObject <DisposableTestPoolItem> >(policy);
                pool.ReinitialiseError += (s, e) => { eventRaised = true; eventRaisedSignal.Set(); };

                var item = pool.Take();
                pool.Add(item);
                item = pool.Take();
                eventRaisedSignal.WaitOne(1000);
                Assert.IsTrue(eventRaised);
            }
        }
        /// <summary>
        ///     Handles the shifting of the object pool when the user scrolls up or down.
        /// </summary>
        /// <param name="direction"></param>
        private void HandlePoolShifting(Direction direction)
        {
            switch (direction)
            {
            case Direction.Forward:
                if (PoolStartingIndex > AvailableItems.Count - 1 || PoolStartingIndex + PoolSize > AvailableItems.Count - 1)
                {
                    return;
                }

                var firstDrawable = Pool.First();

                // Check if the object is in the rect of the ScrollContainer.
                // If it is, then there's no updating that needs to happen.
                if (!RectangleF.Intersect(firstDrawable.ScreenRectangle, ScreenRectangle).IsEmpty)
                {
                    return;
                }

                // Update the mapset's information and y position.
                firstDrawable.Y = (PoolStartingIndex + PoolSize) * DrawableHeight;

                firstDrawable.UpdateContent(AvailableItems[PoolStartingIndex + PoolSize], PoolStartingIndex + PoolSize);

                // Circularly shift the drawable in the list so it's at the end.
                Pool.Remove(firstDrawable);
                Pool.Add(firstDrawable);

                PoolStartingIndex++;
                break;

            case Direction.Backward:
                if (PoolStartingIndex - 1 > AvailableItems.Count - 1 || PoolStartingIndex - 1 < 0)
                {
                    return;
                }

                var lastDrawable = Pool.Last();

                // Check if the object is in the rect of the ScrollContainer.
                // If it is, then there's no updating that needs to happen.
                if (!RectangleF.Intersect(lastDrawable.ScreenRectangle, ScreenRectangle).IsEmpty)
                {
                    return;
                }

                lastDrawable.Y = (PoolStartingIndex - 1) * DrawableHeight;
                lastDrawable.UpdateContent(AvailableItems[PoolStartingIndex - 1], PoolStartingIndex - 1);

                // Circularly shift the drawable in the list so it's at the beginning
                Pool.Remove(lastDrawable);
                Pool.Insert(0, lastDrawable);

                PoolStartingIndex--;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
            }
        }
        public virtual TObject Pop(TInfo info)
        {
            if (Pool.Count < InitialPoolCount)
            {
                for (var i = 0; i < InitialPoolCount; i++)
                {
                    var newInitialPoolObject = CreateNewPoolObject();

                    Pool.Add(newInitialPoolObject);
                }
            }

            for (var i = 0; i < Pool.Count; i++)
            {
                if (Pool[i].InPool)
                {
                    Pool[i].InPool = false;
                    Pool[i].WakeUp(info);

                    return(Pool[i]);
                }
            }

            var newPoolObject = CreateNewPoolObject();

            Pool.Add(newPoolObject);

            newPoolObject.InPool = false;
            newPoolObject.WakeUp(info);

            return(newPoolObject);
        }
Exemple #7
0
        public Identifier RegisterSubPool(SubPool subpool)
        {
            var id = new Identifier(Registry.Global._currentMod, _assigner.Next());

            pool.Add(id, subpool);
            return(id);
        }
        private Particle GenerateNewParticle(Texture2D texture, Vector2 position, Vector2 velocity,
                                             float angle, float angularVelocity, Vector4 color, float size, int ttl, float sizeVel, float alphaVel) // генерация новой частички
        {
            var particle = particles.TryGet(typeof(Particle));

            if (particle == null)
            {
                particle = new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl, sizeVel, alphaVel);
                particles.Add(particle);
            }
            else
            {
                particle.Texture         = texture;
                particle.Position        = position;
                particle.Velocity        = velocity;
                particle.AngularVelocity = angularVelocity;
                particle.Angle           = angle;
                particle.Color           = color;
                particle.Size            = size;
                particle.TTL             = ttl;
                particle.SizeVel         = sizeVel;
                particle.AlphaVel        = alphaVel;
                particle.Free            = false;
            }
            return(particle);
        }
 public void Return(byte[] array)
 {
     lock (Pool)
     {
         Pool.Add(new WeakReference <byte[]>(array));
     }
 }
Exemple #10
0
 private void OnDisable()
 {
     _elapsedTime       = 0;
     transform.position = Vector3.zero;
     ActivePool.RemoveAt(Index);
     Pool.Add(gameObject);
 }
Exemple #11
0
 /// <summary>
 /// Client connection accepted event
 /// </summary>
 /// <param name="serverConnection">Server connection</param>
 private void ClientConnectionAcceptedEvent(ServerConnection serverConnection)
 {
     lock (users)
     {
         int user_id = users.NextAvailableID;
         if (user_id == users.InvalidID)
         {
             serverListener.Disconnect(serverConnection);
         }
         else
         {
             ServerUser user = new ServerUser(user_id, "Unknown", serverConnection);
             users.Add(user);
             serverConnection.SendPlayerNumberMessageAsync(user);
         }
     }
 }
Exemple #12
0
        public override void ReturnGOToPool(GameObject go)
        {
            CheckIfNull(go);

            Pool.Add(go);

            go.SetActive(false);
        }
Exemple #13
0
    public Pool <T> Copy()
    {
        Pool <T> result = new Pool <T>();

        pList.ForEach(p => {
            result.Add(p.item, p.weight);
        });
        return(result);
    }
Exemple #14
0
        public async Task <bool> Append(Transaction tx)
        {
            if (!await Contains(tx))
            {
                return(await Pool.Add(tx));
            }

            return(false);
        }
Exemple #15
0
        public async Task <bool> Append(OfferCancel of)
        {
            if (!await Contains(of))
            {
                return(await Pool.Add(of));
            }

            return(false);
        }
Exemple #16
0
        public async Task <bool> Append(Deposit dp)
        {
            if (!await Contains(dp))
            {
                return(await Pool.Add(dp));
            }

            return(false);
        }
Exemple #17
0
        public async Task <bool> Append(Withdrawal wd)
        {
            if (!await Contains(wd))
            {
                return(await Pool.Add(wd));
            }

            return(false);
        }
Exemple #18
0
 /// <summary>
 /// Adds a new particle
 /// </summary>
 /// <param name="position">The initial position of the particle</param>
 /// <param name="parameters1">The initial configuration of this particle</param>
 /// <param name="parameters2">The configuration this particle will take in its "second life"</param>
 private void AddParticle(DoubleVector3 position, CpuParticleParametersStruct parameters1, CpuParticleParametersStruct parameters2)
 {
     if (_deadParticles.Count > 0)
     {
         CpuParticle particle = _deadParticles.Pop();
         particle.Alive       = true;
         particle.Position    = position;
         particle.Velocity    = default(Vector3);
         particle.Parameters1 = parameters1;
         particle.Parameters2 = parameters2;
         particle.Color       = parameters1.Color;
         particle.SecondLife  = false;
         _firstLifeParticles.Add(particle);
     }
     else
     {
         _firstLifeParticles.Add(new CpuParticle(position, parameters1, parameters2));
     }
 }
Exemple #19
0
        public void Add <T>(T item)
            where T : IRng
        {
            if (item == null)
            {
                throw new ArgumentNullException();
            }

            Pool.Add(item);
        }
Exemple #20
0
        private Entry Insert(string str, IntPtr?address = null)
        {
            var entry = address != null ? new Entry(str, address.Value) : new Entry(str);

            Pool.Add(str, entry);

            ReverseLookup.Add(entry.Unmanaged, entry);

            return(entry);
        }
        private Dictionary <string, ServiceItem> OpenOrCreateSubDictionary <T>()
        {
            Type type = typeof(T);

            if (!Pool.TryGetValue(type, out Dictionary <string, ServiceItem>?list))
            {
                list = new Dictionary <string, ServiceItem>();
                Pool.Add(type, list);
            }
            return(list);
        }
Exemple #22
0
        public void Process(JobContext context)
        {
            JobDataService jobService = new JobDataService(JobManager.Settings);
            Job            job        = new Job();

            job.Id        = context.JobId;
            job.StartedOn = DateTime.UtcNow;
            job.Status    = JobStatus.Running;

            try
            {
                jobService.UpdateJob(job);
                Pool.Add(context);

                var      assemblies = AppDomain.CurrentDomain.GetAssemblies();
                Assembly assembly   = assemblies.FirstOrDefault(a => a.GetName().Name == context.Type.Assembly);

                if (assembly == null)
                {
                    //log error
                    throw new Exception("Assembly can not be found!");
                }

                Type type = assembly.GetType(context.Type.CompleteClassName);
                if (type == null)
                {
                    throw new Exception($"Type with name '{context.Type.CompleteClassName}' does not exist in assembly {assembly.FullName}");
                }

                var method = type.GetMethod(context.Type.MethodName);
                if (method == null)
                {
                    throw new Exception($"Method with name '{context.Type.MethodName}' does not exist in assembly {assembly.FullName}");
                }

                //execute job method
                method.Invoke(new DynamicObjectCreater(type).CreateInstance(), new object[] { context });

                job.FinishedOn = DateTime.UtcNow;
                job.Status     = JobStatus.Finished;
                jobService.UpdateJob(job);
            }
            catch (Exception ex)
            {
                job.FinishedOn   = DateTime.UtcNow;
                job.Status       = JobStatus.Failed;
                job.ErrorMessage = ex.Message;
                jobService.UpdateJob(job);
            }
            finally
            {
                Pool.Remove(context);
            }
        }
    public void WhenAddObject_PoolIncreasesSize()
    {
        Pool <Transform> pool = poolFactory.CreatePool <Transform>(prefabTransform.gameObject);

        int       expectedSize = pool.GetPoolSize() + 1;
        Transform newTransform = Object.Instantiate(prefabTransform);

        pool.Add(newTransform);

        Assert.AreEqual(expectedSize, pool.GetPoolSize(),
                        $"The pool dont increase size, expected {expectedSize}, get {pool.GetPoolSize()}");
    }
 /// <summary>
 /// Socket远程终结点异步通讯
 /// </summary>
 /// <param name="server"></param>
 private void AsyncCommunicating(Socket socket)
 {
     Task.Factory.StartNew(() =>
     {
         SocketEventArgs arg = new SocketEventArgs()
         {
             SocketUserToken = new SocketUserToken(socket),
             Buffer          = null,
             Message         = null
         };
         try
         {
             if (ConnectedToRemoteEndPoint != null)
             {
                 ConnectedToRemoteEndPoint(this, arg);
             }
             Pool.Add(arg.SocketUserToken);
             while (true)
             {
                 byte[] bytes = new byte[BufSize];
                 //获取信息
                 int len = socket.Receive(bytes);
                 //转换
                 string msg = Encoding.UTF8.GetString(bytes, 0, len);
                 if (ReceivedFromRemoteEndPoint != null)
                 {
                     arg.Buffer  = Encoding.UTF8.GetBytes(msg.ToCharArray(), 0, len);
                     arg.Message = null;
                     ReceivedFromRemoteEndPoint(this, arg);
                 }
             }
         }
         catch (Exception ex)
         {
             Dispose((new List <dynamic>()
             {
                 socket
             }));
             //该异常不是由监听Socket的关闭操作引起时
             if (_Alive)
             {
                 if (ExceptionOccuredOfRemoteEndPoint != null)
                 {
                     arg.Buffer  = null;
                     arg.Message = ex.Message;
                     ExceptionOccuredOfRemoteEndPoint(this, arg);
                 }
             }
             //从Socket管理池中移除失效的Socket远程终结点句柄
             Pool.Remove(arg.SocketUserToken);
         }
     });
 }
Exemple #25
0
        private RNG(uint seed)
        {
            Seed = seed;
            var first = new XorWow(seed);

            Pool.Add(first);

            for (int i = 1; i < 4; i++)
            {
                Pool.Add(new XorWow(first.UInt32));
            }
        }
Exemple #26
0
        public Entity CreateEntity()
        {
            var entity = new Entity();

            Pool.Add(entity);

            AttachAdderMethodsToNewEntity(entity);
            AttachRemoverMethodsToNewEntity(entity);
            AttachModifierMethodsToNewEntity(entity);

            return(entity);
        }
        /// <summary>
        ///     Adds a drawable to the pool and returns it
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        private PoolableSprite <T> AddObject(int index)
        {
            var drawable = CreateObject(AvailableItems[index], index);

            drawable.DestroyIfParentIsNull = false;
            drawable.Y = (PoolStartingIndex + index) * drawable.HEIGHT;

            drawable.UpdateContent(AvailableItems[index], index);
            Pool.Add(drawable);

            return(drawable);
        }
Exemple #28
0
 public ObjectPool(int startingCapacity = 128) : base(startingCapacity)
 {
     for (int i = 0; i < startingCapacity; i++)
     {
         T obj = new T();
         if (obj is IPoolable pooled)
         {
             pooled.PoolInitialize();
         }
         Pool.Add(obj);
     }
 }
Exemple #29
0
 public void initializeEnvironmentVar(int taskNumber)
 {
     taskNum        = taskNumber;
     emptyQueue     = false;
     population     = new Pool();
     tempPopulation = new Pool();
     for (int i = 0; i < pmPopSize; i++)
     {
         Genotype <GeneType> genotype = new Genotype <GeneType>(pmGenotypeLen);
         tempPopulation.Add(genotype, -10.0);
         population.Add(genotype, -10.0);
     }
 }
Exemple #30
0
        public void TestReleaseOfPoolable()
        {
            Pool <PooledInstance> anotherPool = new Pool <PooledInstance>();

            anotherPool.size = 4;
            anotherPool.Add(new PooledInstance());
            PooledInstance instance = anotherPool.GetInstance();

            instance.someValue = 42;
            Assert.AreEqual(42, instance.someValue);
            anotherPool.ReturnInstance(instance);
            Assert.AreEqual(0, instance.someValue);
        }
        public static EllipsoidPrimitiveRenderable CreateInstance(Pool<EllipsoidPrimitiveRenderable> pool,
            int verticesCount, int indicesWFCount, int indicesCount, VertexBuffer vertexBuffer, IndexBuffer indicesWFBuffer,
            IndexBuffer indicesBuffer, Matrix world, Matrix view, Matrix projection, Color color, bool isOpaque)
        {
            EllipsoidPrimitiveRenderable result = null;

            if (!pool.TryGetInstance(out result))
            {
                result = new EllipsoidPrimitiveRenderable();
                pool.Add(result);
            }

            result.Initialize(verticesCount, indicesWFCount, indicesCount, vertexBuffer, indicesWFBuffer, indicesBuffer, ref world, ref view, ref projection, ref color, isOpaque);

            return result;
        }