public void TickOuterHealth()
 {
     if (--outerEntity.GetDamageable().health.amount <= 0)
     {
         // this also removes this modifier, so we're done
         outerEntity.Die();
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// Attacks the entity looking in the specified direction. Otherwise,
        /// moves in the specified direction, after which tries to attack whatever is
        /// at the same cell as the projectile at that point. Would not attack if provided direction of zero.
        /// Would start watching the cell's <c>EnterEvent</c> and attack entities that enter the cell
        /// until the end of loop. Attacking is only done on entities at the <c>targetLayer</c>.
        /// </summary>
        /// <returns>Always returns true.</returns>
        /// <remarks>
        /// In the future, should add a `Do` chain that should be traversed instead of attacking entities directly.
        /// </remarks>
        public bool Activate(Entity actor, IntVector2 direction)
        {
            // Assert.AreNotEqual(IntVector2.Zero, direction, "Must be moving somewhere");
            var transform = actor.GetTransform();
            var stats     = actor.GetStats();

            stats.GetLazy(Attack.Index, out var attack);

            // If the projectile is not floating at one spot
            if (direction != IntVector2.Zero)
            {
                Assert.That(!actor.GetDisplaceable().blockLayer.HasFlag(Layers.WALL),
                            "We should be able to move INTO walls");

                // First, attack entities, that are looking at us, standing at the same cell as us.
                // Ignore any directed entities.

                foreach (var targetTransform in transform.GetAllUndirectedButSelfFromLayer(targetedLayer))
                {
                    if (targetTransform.orientation != -direction)
                    {
                        continue;
                    }

                    if (targetTransform.entity.TryBeAttacked(actor, attack, transform.orientation))
                    {
                        actor.Die();
                        return(true);
                    }
                }

                stats.GetLazy(Move.Index, out var move);
                actor.TryDisplace(direction, move, out bool _);
            }

            if (!actor.IsDead())
            {
                // Attack the entity (entities) from the same cell, but not oneself.
                foreach (var targetTransform in transform.GetAllButSelfFromLayer(targetedLayer))
                {
                    if (targetTransform.entity.TryBeAttacked(actor, attack, transform.orientation))
                    {
                        actor.Die();
                        return(true);
                    }
                }

                // Attack anything that enters the spot.
                transform.SubsribeToEnterEvent(context => HitEntered(actor, context));
            }

            return(true);
        }
Exemplo n.º 3
0
    public void Tick()
    {
        // Entity action
        foreach (Entity e in entities)
        {
            e.Act();
        }

        // Entity creation
        entities.AddRange(newEntities);
        newEntities.Clear();

        // Entity destruction
        for (int i = entities.Count - 1; i >= 0; i--)
        {
            Entity e = entities[i];
            if (e.health <= 0)
            {
                e.Die();
                entities.RemoveAt(i);
                entityMap[e.position.y, e.position.x].Remove(e);
                e.onPositionChanged -= UpdateEntityMap;
            }
        }
    }
Exemplo n.º 4
0
 public void RemoveEntity(Entity e)
 {
     e.Die();
     entities.Remove(e);
     entityMap[e.position.y, e.position.x].Remove(e);
     e.onPositionChanged -= UpdateEntityMap;
 }
Exemplo n.º 5
0
    private void ProcessExplode(bool fly)
    {
        //  伤害处理(溅射范围为0则针对单个目标,否则根据溅射范围计算。)
        if (Entity.model.splashRange > 0)
        {
            //  飞天陷阱根据body计算位置、普通陷阱获取自身位置。
            Vector2 p;
            if (fly)
            {
                var currPosition = Entity.view.body.position;
                p = new Vector2(currPosition.x, currPosition.z);
            }
            else
            {
                p = Entity.GetCurrentPositionCenter();
            }
            GameDamageManager.ProcessDamageMultiTargeters(FindTargetersInSplash(p.x, p.y), Entity.model, Entity);
        }
        else
        {
            GameDamageManager.ProcessDamageOneTargeter(m_currTraceTargeter, Entity.model, Entity);
        }

        //  爆炸显示效果
        GameEffectManager.Instance.AddEffect(Entity.model.hitEffectName, fly ? Entity.view.body.position : Entity.view.transform.position);

        //  自身死亡
        Entity.Die();

        //  改变数据
        Entity.buildingVO.trapBuildingVO.broken = true;
    }
Exemplo n.º 6
0
        public void IsDeadReturnsTrueIfHealthIsPositive()
        {
            var e = new Entity("Slime", 's', Color.Blue, 0, 0, 17, 3, 1);

            Assert.That(e.IsDead, Is.False);

            e.Die();
            Assert.That(e.IsDead, Is.True);
        }
 public void HandleEntityDeath(string entityId)
 {
     if (entities.ContainsKey(entityId))
     {
         Entity entity = entities[entityId];
         StartCoroutine(entity.Die(true, 1f));
         RemoveEntity(entity.uniqueId);
     }
 }
Exemplo n.º 8
0
    void OnTriggerEnter2D(Collider2D other)
    {
        Entity entity = other.GetComponent <Entity> ();

        if (entity)
        {
            entity.Die();
        }
    }
Exemplo n.º 9
0
        public void DieSetsEntityHealthCharacterAndColor()
        {
            var e = new Entity("Fodder", 'f', Color.Green, 0, 0, 17, 3, 1);

            e.Die();

            Assert.That(e.CurrentHealth, Is.Zero);
            Assert.That(e.Character, Is.EqualTo('%'));
            Assert.That(e.Color, Is.EqualTo(Palette.DarkBurgandyPurple));
        }
Exemplo n.º 10
0
    void Start()
    {
        MainMenu.victory = true;
        GameObject playerObject = GameObject.FindWithTag("Player");
        Entity     playerEntity = playerObject.GetComponent <Entity>();

        playerEntity.Die();

        Instantiate(rewardPrefab, transform);
    }
Exemplo n.º 11
0
        private void Tick(CallReason callReason)
        {
            DoDamage();

            if (callReason == CallReason.LastTick)
            {
                m_DamageTicker.ContinueEvent -= Tick;
                Entity.Die();
            }
        }
Exemplo n.º 12
0
        public static bool HandleMove(Entity entity, Moves move)
        {
            int x = entity.X;
            int y = entity.Y;

            switch (move)
            {
            case (Moves.Up):
                x += entity.Size;
                break;

            case (Moves.Down):
                x -= entity.Size;
                break;

            case (Moves.Left):
                y -= entity.Size;
                break;

            case (Moves.Right):
                y += entity.Size;
                break;
            }

            Entity TileEntity = GetOccupiedTileEntity(x, y);

            if (TileEntity != null && TileEntity.ID == entity.ID)
            {
                return(false);
            }

            bool ValidMove = IsFreeTile(x, y);

            if (ValidMove)
            {
                SetNewPostion(entity, x, y);
                return(true);
            }

            if (!ValidMove && TileEntity != null)
            {
                if (entity.Strength > TileEntity.Strength + 0.5 * TileEntity.Defense)
                {
                    TileEntity.Die();
                    SetNewPostion(entity, x, y);
                    return(true);
                }
                else
                {
                    entity.Die();
                    return(false);
                }
            }
            return(false);
        }
Exemplo n.º 13
0
        // Returns true if the entity died
        public bool Attack(Entity victim)
        {
            victim.Health -= attackDamage;
            if (victim.Health >= 0)
            {
                victim.Die();
                return(true);
            }

            return(false);
        }
Exemplo n.º 14
0
 public void Die()
 {
     if (healthBar)
     {
         DestroyHealthBar();
     }
     if (entity)
     {
         entity.Die();
     }
     Destroy(gameObject);
 }
Exemplo n.º 15
0
        private static void HitEntered(Entity projectile, CellMovementContext context)
        {
            if (!projectile.IsDead() &&
                !context.actor.IsDead() &&
                context.transform.layer.HasEitherFlag(projectile.GetProjectileComponent().targetedLayer))
            {
                projectile.GetStats().Get(Attack.Index, out var attack);

                if (context.actor.TryBeAttacked(projectile, attack, projectile.GetTransform().orientation))
                {
                    projectile.Die(); // For now, just die. Add a do chain later.
                }
            }
        }
Exemplo n.º 16
0
    public void LoseHP(int amt = 1)
    {
        if (amt > 0 && cur_hp > 0)
        {
            cur_hp -= amt;
        }

        if (cur_hp <= 0)
        {
            m_entity.Die();
        }

        //Debug.Log("lost " + amt + " hp, " + cur_hp + " left.");
    }
Exemplo n.º 17
0
    /// <summary>
    /// [覆盖] 处理攻击过程(不沿用父类的流程)
    /// </summary>
    /// <param name="dt"></param>
    protected override void UpdateAttacking(float dt)
    {
        m_timePassed += dt;
        if (m_timePassed >= Entity.model.rate)
        {
            //  伤害处理
            ProcessDamagePoint(Entity.GetCurrentPositionCenter());

            //  爆炸显示效果
            GameEffectManager.Instance.AddEffect(Entity.model.hitEffectName, Entity.view.transform.position);

            //  自身死亡
            Entity.Die();
        }
    }
Exemplo n.º 18
0
    public void TakeDamage(int amount)
    {
        currentHealth -= amount;

        UpdateHealthGFX();

        if (currentHealth <= 0)
        {
            entity.Die();
        }
        else if (entity.ActivePhalanx != null && settings.rotateOnDamage)
        {
            entity.ActivePhalanx.RotateColumn(entity);
        }
    }
Exemplo n.º 19
0
 private void resolveAttack(Entity other)
 {
     // TODO: Add a timer-thing, so this method is not called every frame. Maybe use Coroutines.
     bool kill = other.TakeDamage(_entity.Stats.Attack);
     if (kill) // Prevent the enemy from hurting the player, if the player kills it first.
     {
         disengageAttack(other);
         other.Die();
         _entity.Stats.ScoreValue += other.Stats.ScoreValue;
         _entity.Stats.Experience += other.Stats.Experience;
         return;
     }
     bool died = _entity.TakeDamage(other.Stats.Attack);
     if (died) _entity.Die();
 }
Exemplo n.º 20
0
    private void UpdateHealth()
    {
        float currentHealthFrac = (float)_meEntity.CurrentHealth / _meEntity.MaxHealth;

        HealthBar.material.SetFloat(Charge, currentHealthFrac);
        _text.text = _meEntity.CurrentHealth + " / " + _meEntity.MaxHealth;

        if (_meEntity.CurrentHealth <= 0)
        {
            _meEntity.Die();
            if (_hurtTime <= 0)
            {
                Destroy(gameObject);
            }
        }
    }
Exemplo n.º 21
0
 /// <summary>
 /// Kills a character.
 /// </summary>
 /// <param name="entity">Character to kill.</param>
 public static void KillCharacter(Entity entity)
 {
     if (entity && instance.charactersOnLevel.Contains(entity))
     {
         instance.charactersOnLevel.Remove(entity);
         if (instance.infectedCharacters.Contains(entity))
         {
             instance.infectedCharacters.Remove(entity);
         }
         entity.Die();
         if (instance.infectedCharacters.Count <= 0)
         {
             instance.StopCoroutine(instance.InfectionTimer());
         }
         SetCurrentCharacter();
     }
 }
Exemplo n.º 22
0
    void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.tag == "Enemy" && !invincible)
        {
            Debug.Log("collided with enemy");
            damaged    = true;
            invincible = true;
            animator.SetBool("Hit", true);
            entity.TakeDamage(1);
            timeDamaged = Time.time;
        }

        if (collider.tag == "Death")
        {
            entity.Die();
        }
    }
Exemplo n.º 23
0
    void Eat(GameObject meal)
    {
        if (pathfindTarget == null)
        {
            return;
        }

        Entity targetEntity = pathfindTarget.GetComponent <Entity>();
        float  targetEnergy = targetEntity.energy;

        float totalNewEnergy = targetEnergy * ((maxAge - currentAge) / maxAge);

        energy += totalNewEnergy;
        targetEntity.Die();

        AddWait(eatDuration);
    }
Exemplo n.º 24
0
    /*
     * void OnCollisionEnter2D(Collision2D collision)
     * {
     *  Debug.Log("Collision");
     *  if (collision.gameObject.GetComponent<Entity>().entityName.CompareTo(sourceEntity.entityName) != 0)
     *  {
     *      //if (collision.gameObject.tag.CompareTo("Enemy") == 0)
     *      //{
     *          Debug.Log("Hit Enemy");
     *          // Debug.Log(collision.gameObject.GetComponent<EnemyStats>().currentHP);
     *          collision.gameObject.GetComponent<Entity>().recieveDamage(damage);
     *
     *          GameObject text = Instantiate(textPrefab, transform.position, Quaternion.identity);
     *          text.GetComponent<FloatingTextScript>().setText("" + damage);
     *
     *     // }
     *
     *      Destroy(gameObject);
     *  }
     *  else
     *  {
     *      Debug.Log("Poggers hit self");
     *  }
     *
     * }
     */

    void OnTriggerEnter2D(Collider2D collision)
    {
        //CHECKS IF HITTING FRIENDLY
        if (collision.gameObject.tag.CompareTo(sourceEntity.gameObject.tag) == 0)
        {
        }
        //CHECKS IF HITTING ANYTHING BUT SELF
        else if (!GameObject.ReferenceEquals(collision.gameObject, sourceEntity.gameObject))
        {
            //CHECKS IF HIT WAS AN ENTITY
            if (collision.gameObject.GetComponent <Entity>() != null)
            {
                //CHECKS IF BULLET HASN'T COLLIDED WITH ANYTHING
                if (!registered)
                {
                    registered = true;
                    // Debug.Log("Hit Enemy");
                    Entity entityScript     = collision.gameObject.GetComponent <Entity>();
                    float  calculatedDamage = entityScript.CalculateDamage(damage, damageType);

                    if (entityScript.WillKill(calculatedDamage))
                    {
                        Debug.Log("Gain Exp");
                        entityScript.Die();
                        sourceEntity.GainExperience(200f);
                    }
                    else
                    {
                        entityScript.TakeDamage(calculatedDamage);
                    }



                    GameObject         text       = Instantiate(textPrefab, transform.position, Quaternion.identity);
                    FloatingTextScript textScript = text.GetComponent <FloatingTextScript>();
                    textScript.SetText("" + calculatedDamage);
                    textScript.SetColor(GetColor(damageType));
                    textScript.StartFloatText();
                }

                Destroy(gameObject);
            }
        }
    }
Exemplo n.º 25
0
    private void resolveAttack(Entity other)
    {
        // TODO: Add a timer-thing, so this method is not called every frame. Maybe use Coroutines.
        bool kill = other.TakeDamage(_entity.Stats.Attack);

        if (kill) // Prevent the enemy from hurting the player, if the player kills it first.
        {
            disengageAttack(other);
            other.Die();
            _entity.Stats.ScoreValue += other.Stats.ScoreValue;
            _entity.Stats.Experience += other.Stats.Experience;
            return;
        }
        bool died = _entity.TakeDamage(other.Stats.Attack);

        if (died)
        {
            _entity.Die();
        }
    }
Exemplo n.º 26
0
    //计算伤害
    public static void CalcBlood(Entity caster, Entity target, CSVSkill skillInfo)
    {
        if (target == null)
        {
            return;
        }
        if (skillInfo.attackBuff != 0)
        {
            target.Buff.AddBuff((int)skillInfo.attackBuff);
        }
        bool isCrit = false;
        int  damage = GetDamage(caster, target, skillInfo, out isCrit);

        if (damage != 0)
        {
            target.Property.HP -= damage;
            if (target.IsDead)
            {
                target.Die();
            }
        }
    }
Exemplo n.º 27
0
    void Eat(Entity entity)
    {
        switch (Manager.eatMode)
        {
        case EntityManager.EatMechanics.RestorePreyMaxEnergyPercentage:
            energy += entity.energy * Manager.eatValue;
            break;

        case EntityManager.EatMechanics.RestorePreyCurrentEnergyPercentage:
            energy += entity.maxEnergy * Manager.eatValue;
            break;

        case EntityManager.EatMechanics.FixedByPrey:
            foreach (GameObjectWithRate prey in canEatEntities)
            {
                if (entity.name == prey.prefab.name)
                {
                    energy += prey.rate;
                }
            }
            break;

        case EntityManager.EatMechanics.FixedAmount:
            energy += Manager.eatValue;
            break;

        case EntityManager.EatMechanics.RestoreMaxEnergyPercentage:
            energy += maxEnergy * Manager.eatValue;
            break;
        }
        if (!Manager.canOutnumberMaxEnergy)
        {
            Mathf.Clamp(energy, 0f, maxEnergy);
        }
        entity.Die();
        hungry = false;
        status = Status.idle;
    }
        public virtual bool OnFoundCollectible(Entity foundEntity)
        {
            ItemStack itemstack = foundEntity.OnCollected(this.entity);
            bool      collected = false;

            if (itemstack != null && itemstack.StackSize > 0)
            {
                collected = entity.TryGiveItemStack(itemstack);
            }

            if (itemstack != null && itemstack.StackSize <= 0)
            {
                foundEntity.Die(EnumDespawnReason.PickedUp);
            }

            if (collected)
            {
                entity.World.PlaySoundAt(new AssetLocation("sounds/player/collect"), entity);
                return(true);
            }

            return(false);
        }
Exemplo n.º 29
0
        static void Demo()
        {
            var ____ = Spider.Factory;
            var _____ = TestTinkerStuff.tinker;
            var ______ = TestStatusStuff.status;

            System.Console.WriteLine("\n ------ Definition + Instantiation Demo ------ \n");

            World world = new World(5, 5);
            System.Console.WriteLine("Created world");

            // Statused.RegisterStatus(TestStatusTinkerStuff.status, 1);
            var packed = Registry.Default.Tinker.PackModMap();
            Registry.Default.Tinker.SetServerMap(packed);

            var player.Factory = new EntityFactory<Player>();
            player.Factory.AddBehavior(Attackable.DefaultPreset);
            player.Factory.AddBehavior(Attacking.Preset);
            player.Factory.AddBehavior(Displaceable.DefaultPreset);
            player.Factory.AddBehavior(Moving.Preset);
            player.Factory.AddBehavior(Pushable.Preset);
            player.Factory.AddBehavior(Statused.Preset);
            System.Console.WriteLine("Set up player.Factory");

            Acting.Config playerActingConf = new Acting.Config(Algos.SimpleAlgo, null);

            player.Factory.AddBehavior(Acting.Preset(playerActingConf));
            player.Factory.Retouch(Hopper.Core.Retouchers.Skip.EmptyAttack);

            // this one's for the equip demo
            player.Factory.Retouch(Hopper.Core.Retouchers.Equip.OnDisplace);


            var enemy.Factory = new EntityFactory<Entity>();
            enemy.Factory.AddBehavior(Attackable.DefaultPreset);
            enemy.Factory.AddBehavior(Attacking.Preset);
            enemy.Factory.AddBehavior(Displaceable.DefaultPreset);
            enemy.Factory.AddBehavior(Moving.Preset);
            enemy.Factory.AddBehavior(Pushable.Preset);


            Acting.Config enemyActingConf = new Acting.Config(Algos.EnemyAlgo);

            enemy.Factory.AddBehavior(Acting.Preset(enemyActingConf));


            var attackAction = Action.CreateBehavioral<Attacking>();
            var moveAction = Action.CreateBehavioral<Moving>();
            CompositeAction attackMoveAction = new CompositeAction(
                new Action[] { attackAction, moveAction }
            );

            Step[] stepData =
            {
                new Step { action = null },
                new Step { action = attackMoveAction, movs = Movs.Basic }
            };

            var sequenceConfig = new Sequential.Config(stepData);

            enemy.Factory.AddBehavior(Sequential.Preset(sequenceConfig));
            System.Console.WriteLine("Set up enemy.Factory");

            Entity player = player.Factory.Instantiate();
            System.Console.WriteLine("Instantiated Player");

            Entity enemy = enemy.Factory.Instantiate();
            System.Console.WriteLine("Instantiated Enemy");

            enemy.Init(new IntVector2(1, 2), world);
            world.State.AddEntity(enemy);
            world.Grid.Reset(enemy, enemy.Pos);
            System.Console.WriteLine("Enemy set in world");

            player.Init(new IntVector2(1, 1), world);
            world.State.AddPlayer(player);
            world.Grid.Reset(player, player.Pos);
            System.Console.WriteLine("Player set in world");

            var playerNextAction = attackMoveAction.Copy();
            playerNextAction.direction = new IntVector2(0, 1);
            player.Behaviors.Get<Acting>().NextAction = playerNextAction;
            System.Console.WriteLine("Set player action");
            System.Console.WriteLine("\n ------ Modifier Demo ------ \n");

            var mod = Modifier.Create(Attack.Path, new Attack { damage = 1 });//new StatModifier(Attack.Path, new Attack { damage = 1 });
            var attack = player.Stats.Get(Attack.Path);
            System.Console.WriteLine("Attack damage:{0}", attack.damage);
            System.Console.WriteLine("Attack pierce:{0}", attack.pierce);
            System.Console.WriteLine("Adding modifier");
            mod.AddSelf(player.Stats);
            attack = player.Stats.Get(Attack.Path);
            System.Console.WriteLine("Attack damage:{0}", attack.damage);
            System.Console.WriteLine("Attack pierce:{0}", attack.pierce);
            System.Console.WriteLine("Removing modifier");
            mod.RemoveSelf(player.Stats);
            attack = player.Stats.Get(Attack.Path);
            System.Console.WriteLine("Attack damage:{0}", attack.damage);
            System.Console.WriteLine("Attack pierce:{0}", attack.pierce);

            var mod2 = Modifier.Create(Attack.Path, new EvHandler<StatEvent<Attack>>(
                (StatEvent<Attack> eve) =>
                {
                    System.Console.WriteLine("Called handler");
                    eve.file.damage *= 3;
                })
            );
            System.Console.WriteLine("Adding modifier");
            mod2.AddSelf(player.Stats);
            attack = player.Stats.Get(Attack.Path);
            System.Console.WriteLine("Attack damage:{0}", attack.damage);
            System.Console.WriteLine("Attack pierce:{0}", attack.pierce);
            System.Console.WriteLine("Removing modifier");
            player.Stats.RemoveChainModifier(mod2);
            attack = player.Stats.Get(Attack.Path);
            System.Console.WriteLine("Attack damage:{0}", attack.damage);
            System.Console.WriteLine("Attack pierce:{0}", attack.pierce);

            System.Console.WriteLine("\n ------ Pools Demo ------ \n");

            PoolItem[] items = new[]
            {
                new PoolItem(0, 1),
                new PoolItem(1, 1),
                new PoolItem(2, 1),
                new PoolItem(3, 1),
                new PoolItem(4, 10)
            };

            var pool = Pool.CreateNormal<Hopper.Core.Items.IItem>();

            pool.AddRange("zone1/weapons", items.Take(2));
            pool.AddRange("zone1/trinkets", items.Skip(2).Take(2));
            pool.Add("zone1/trinkets", items[4]);

            var poolCopy = pool.Copy();

            var it1 = pool.GetNextItem("zone1/weapons");
            System.Console.WriteLine($"Item Id = {it1.id}, q = {it1.quantity}");
            // var it2 = pool.GetNextItem("zone1/weapons");
            // System.Console.WriteLine($"Item Id = {it2.id}, q = {it2.quantity}");
            var it3 = poolCopy.GetNextItem("zone1/weapons");
            System.Console.WriteLine($"Item Id = {it3.id}, q = {it3.quantity}");
            var it4 = poolCopy.GetNextItem("zone1/weapons");
            System.Console.WriteLine($"Item Id = {it4.id}, q = {it4.quantity}");


            System.Console.WriteLine("\n ------ TargetProvider Demo ------ \n");
            var pattern = new Pattern
            (
                new Piece
                {
                    pos = new IntVector2(1, 0),
                    dir = new IntVector2(1, 0),
                    reach = null
                },
                new Piece
                {
                    pos = new IntVector2(2, 0),
                    dir = new IntVector2(1, 0),
                    reach = new List<int>()
                }
            );
            var weapon = TargetProvider.CreateAtk(pattern, Handlers.GeneralChain);
            System.Console.WriteLine($"Enemy is at {enemy.Pos}");
            var atk = player.Stats.Get(Attack.Path);
            var targets = weapon.GetTargets(player, playerNextAction.direction, atk);
            foreach (var t in targets)
            {
                System.Console.WriteLine($"Entity at {t.targetEntity.Pos} has been considered a potential target");
            }

            System.Console.WriteLine("\n ------ Inventory Demo ------ \n");
            var inventory = (Inventory)player.Inventory;

            var slot = new SizedSlot<CircularItemContainer, Hopper.Core.Items.IItem>("stuff2", 1);

            inventory.AddContainer(slot);

            var tinker = Tinker<TinkerData>.SingleHandlered<Attacking.Event>(
                Attacking.Check,
                e => System.Console.WriteLine("Hello from tinker applied by item")
            );
            var item = new TinkerItem(new ItemMetadata("Test_Tinker_Item"), tinker, slot);

            // inventory.Equip(item) ->         // the starting point
            // item.BeEquipped(entity) ->       // it's interface method
            // tinker.Tink(entity)  ->          // adds the handlers
            // entity.Tinkers.SetStore()        // creates the tinker data
            inventory.Equip(item);

            world.Loop();
            System.Console.WriteLine("Looped");

            // creates excess as the size is 1
            inventory.Equip(item);
            // inventory.DropExcess() ->
            // item.BeUnequipped()    ->
            // tinker.Untink() -> entity.Tinkers.RemoveStore()
            // + world.CreateDroppedItem(id, pos)
            inventory.DropExcess();

            var entities = world.Grid.GetCellAt(player.Pos).m_entities;
            System.Console.WriteLine($"There's {entities.Count} entities in the cell where the player is standing");

            System.Console.WriteLine("\n ------ History Demo ------ \n");
            var enemyUpdates = enemy.History.Updates;
            var playerUpdates = player.History.Updates;
            foreach (var updateInfo in enemyUpdates)
            {
                System.Console.WriteLine($"Enemy did {System.Enum.GetName(typeof(UpdateCode), updateInfo.updateCode)}. Position after: {updateInfo.stateAfter.pos}");
            }
            foreach (var updateInfo in playerUpdates)
            {
                System.Console.WriteLine($"Player did {System.Enum.GetName(typeof(UpdateCode), updateInfo.updateCode)}. Position after: {updateInfo.stateAfter.pos}");
            }

            System.Console.WriteLine("\n ------ Equip on Displace Demo ------ \n");
            // we don't need the entity for the next test
            enemy.Die();

            var playerMoveAction = moveAction.Copy();
            playerMoveAction.direction = IntVector2.Down;
            player.Behaviors.Get<Acting>().NextAction = playerMoveAction;

            var slot2 = new SizedSlot<CircularItemContainer, Hopper.Core.Items.IItem>("stuff3", 1);
            inventory.AddContainer(slot2);

            var chainDefs2 = new IChainDef[0];
            var tinker2 = new Tinker<TinkerData>(chainDefs2);
            var item2 = new TinkerItem(new ItemMetadata("Test_Tinker_Item_2"), tinker2, slot2);

            var droppedItem2 = world.SpawnDroppedItem(item2, player.Pos + IntVector2.Down);

            /*
            this only works because we did
            `player.Factory.AddRetoucher(Core.Retouchers.Equip.OnDisplace);`
            up top.
            */

            System.Console.WriteLine($"Player's position before moving: {player.Pos}");
            world.Loop();
            System.Console.WriteLine($"Player's new position: {player.Pos}");
            System.Console.WriteLine($"There's {world.Grid.GetCellAt(player.Pos).m_entities.Count} entities in the cell where the player is standing");


            System.Console.WriteLine("\n ------ Tinker static reference Demo ------ \n");

            var tinker3 = TestTinkerStuff.tinker; // see the definition below
            tinker3.Tink(player);
            player.Behaviors.Get<Acting>().NextAction = playerMoveAction;
            world.Loop();
            tinker3.Untink(player);


            System.Console.WriteLine("\n ------ Status Demo ------ \n");

            // this has to be rethought for sure
            var status = TestStatusStuff.status;
            status.TryApply(
                player,
                new StatusData(),
                new StatusFile { power = 1, amount = 2 }
            );
            player.Behaviors.Get<Acting>().NextAction = playerMoveAction;
            world.Loop();
            player.Behaviors.Get<Acting>().NextAction = playerMoveAction;
            world.Loop();
            player.Behaviors.Get<Acting>().NextAction = playerMoveAction;
            world.Loop();

            System.Console.WriteLine("\n ------ Spider Demo ------ \n");
            player.ResetPosInGrid(new IntVector2(4, 4));
            var spider = world.SpawnEntity(Spider.Factory, new IntVector2(3, 3));
            world.Loop();
            System.Console.WriteLine($"Tinker is applied? {BindStatuses.NoMove.IsApplied(player)}");
            System.Console.WriteLine("Looped");
            System.Console.WriteLine($"Player's new position: {player.Pos}");
            System.Console.WriteLine($"Spider's new position: {spider.Pos}");

            player.Behaviors.Get<Acting>().NextAction = attackAction;
            world.Loop();
            System.Console.WriteLine("Looped");
            System.Console.WriteLine($"Player's new position: {player.Pos}");
            System.Console.WriteLine($"Spider's new position: {spider.Pos}");

            player.Behaviors.Get<Displaceable>().Activate(new IntVector2(-1, -1), new Move());
            world.Loop();
            System.Console.WriteLine("Looped");
            System.Console.WriteLine($"Player's new position: {player.Pos}");
            System.Console.WriteLine($"Spider's new position: {spider.Pos}");

            System.Console.WriteLine("Killing spider");
            spider.Die();
            world.Loop();
            System.Console.WriteLine($"Tinker is applied? {BindStatuses.NoMove.IsApplied(player)}");

            System.Console.WriteLine("\n ------ Input Demo ------ \n");
            // we also have the possibilty to add behaviors dynamically.
            var Input.Factory = new BehaviorFactory<Controllable>();
            var input = (Controllable)Input.Factory.Instantiate(player,
                new Controllable.Config { defaultAction = attackMoveAction });
            player.Behaviors.Add(typeof(Controllable), input);

            var outputAction0 = input.ConvertVectorToAction(IntVector2.Up);
            System.Console.WriteLine($"Fed Up. Output: {outputAction0.direction}");
            var outputAction1 = input.ConvertInputToAction(InputMapping.Special_0);
            System.Console.WriteLine($"Fed Special_0. Output is null?: {outputAction1 == null}");
        }
Exemplo n.º 30
0
 public void RemoveUnit(Entity unit)
 {
     units.Remove(unit);
     unit.Die();
 }
Exemplo n.º 31
0
 public void Die()
 {
     owner.Die();
 }
Exemplo n.º 32
0
    // Update is called once per frame
    void Update()
    {
        //  Update the locations of the players.
        g_Fighter.transform.position = new Vector3(20 + 8 * Fighter.position, 0, 0);
        g_Thief.transform.position = new Vector3(20 + 8 * Thief.position, 0, 0);
        g_Wizard.transform.position = new Vector3(20 + 8 * Wizard.position, 0, 0);

        // Count down any delays.
        if (delay > 0.0) {
            delay -= Time.deltaTime;
            delaying = true;
            return;
        }

        delaying = false;

        // TODO: Remove
        {
            Fighter.position = (Fighter.position + 1) % 3;
            Thief.position = (Thief.position + 1) % 3;
            Wizard.position = (Wizard.position + 1) % 3;
            Log("Printing: " + ++count);
            delay = 2f;
            delaying = true;
            return;
        }

        while (toremove.Contains(waiting.Peek()))
            waiting.Dequeue();

        switch (state) {
            case State.Playing:
                target = null;
                if (waiting.Peek().type == Entity.Type.Enemy) {
                    acting = waiting.Dequeue();
                    delay = EnemyDecideDelay;
                    delaying = true;
                    state = State.EnemyThinking;
                }
                else if (waiting.Peek().type == Entity.Type.Fighter) {
                    acting = waiting.Dequeue();
                    delay = EnemyDecideDelay;
                    delaying = true;
                    state = State.FighterThinking;
                }
                else if (waiting.Peek().type == Entity.Type.Thief) {
                    acting = waiting.Dequeue();
                    delay = EnemyDecideDelay;
                    delaying = true;
                    state = State.ThiefThinking;
                }
                else if (waiting.Peek().type == Entity.Type.Wizard) {
                    acting = waiting.Dequeue();
                    delay = EnemyDecideDelay;
                    delaying = true;
                    state = State.WizardThinking;
                }
                break;
            case State.EnemyThinking:
                // Choose target.
                if (FighterIntercept) {
                    target = Fighter;
                }
                else {
                    var chance = (int)(Random.value * 100);
                    if (chance < 66) {
                        target = GetPlayer(0);
                    }
                    else if (chance < 90) {
                        target = GetPlayer(1);
                    }
                    else {
                        target = GetPlayer(2);
                    }
                }

                // Attack target.
                delay = ActionResultDelay;
                delaying = true;
                state = State.Acting;
                break;
            case State.FighterThinking :
                target = null;
                break;
            case State.ThiefThinking :
                target = null;
                break;
            case State.WizardThinking :
                target = null;
                break;
            case State.Acting :
                if (target != null) {
                    int damage = acting.Attack(0, target);

                    Log(string.Format(S_DAMAGED, acting.name, target.name, damage));

                    if (target.HP < 0) {
                        var drop = target.Die();
                        GameObject.Destroy(target.parent);

                        // TODO: Add drop to player inv.
                    }
                }
                break;
            case State.Won :
                target = null;
                break;
            case State.Lost :
                target = null;
                break;
        }
    }