Ejemplo n.º 1
0
 // addInventoryItem
 public void addInventoryItem(InventoryComponent inventoryComponent, ItemComponent item)
 {
     for (int i = 0; i < inventoryComponent.slots; i++)
     {
         if (!inventoryComponent.inventory.ContainsKey(i))
         {
             inventoryComponent.inventory.Add(i, item);
             return;
         }
     }
 }
Ejemplo n.º 2
0
 // assignItemToToolbar
 public void assignItemToToolbar(string levelUid, ItemComponent itemComponent, ToolbarComponent toolbarComponent, int toolbarSlot)
 {
     toolbarComponent.inventory[toolbarSlot] = itemComponent;
     selectToolbarSlot(levelUid, toolbarComponent, toolbarComponent.selectedIndex);
 }
Ejemplo n.º 3
0
        // removeInventoryItem
        public void removeInventoryItem(InventoryComponent inventoryComponent, ItemComponent item)
        {
            int index = -1;
            foreach (KeyValuePair<int, ItemComponent> pair in inventoryComponent.inventory)
            {
                if (pair.Value == item)
                {
                    index = pair.Key;
                    break;
                }
            }

            if (index != -1)
            {
                inventoryComponent.inventory.Remove(index);
            }
        }
Ejemplo n.º 4
0
 public static string generateArmorCode(ItemComponent.tAttributeType att, tOreType ore, ItemArmor.tArmorPart part)
 {
     return "" + (int)att + (int)ore + (int)part;
 }
Ejemplo n.º 5
0
 private bool TryFindController(ItemComponent targetComponent, out Controller controller)
 {
     controller = FindController(targetComponent);
     return(controller != null);
 }
Ejemplo n.º 6
0
 private Item FindWeapon(out ItemComponent weaponComponent) => GetWeapon(FindWeaponsFromInventory(), out weaponComponent);
        private void DeleteUndelete(bool redo)
        {
            bool wasDeleted = WasDeleted;

            // We are redoing instead of undoing, flip the behavior
            if (redo)
            {
                wasDeleted = !wasDeleted;
            }

            if (wasDeleted)
            {
                Debug.Assert(Receivers.All(entity => entity.GetReplacementOrThis().Removed), "Tried to redo a deletion but some items were not deleted");

                List <MapEntity> clones = MapEntity.Clone(CloneList);
                int length = Math.Min(Receivers.Count, clones.Count);
                for (int i = 0; i < length; i++)
                {
                    MapEntity clone = clones[i], receiver = Receivers[i];

                    if (receiver.GetReplacementOrThis() is Item item && clone is Item cloneItem)
                    {
                        foreach (ItemComponent ic in item.Components)
                        {
                            int           index     = item.GetComponentIndex(ic);
                            ItemComponent component = cloneItem.Components.ElementAtOrDefault(index);
                            switch (component)
                            {
                            case null:
                                continue;

                            case ItemContainer newContainer when newContainer.Inventory != null && ic is ItemContainer itemContainer && itemContainer.Inventory != null:
                                itemContainer.Inventory.GetReplacementOrThiS().ReplacedBy = newContainer.Inventory;
                                goto default;

                            default:
                                ic.GetReplacementOrThis().ReplacedBy = component;
                                break;
                            }
                        }
                    }

                    receiver.GetReplacementOrThis().ReplacedBy = clone;
                }

                for (int i = 0; i < length; i++)
                {
                    MapEntity clone = clones[i], receiver = Receivers[i];

                    if (clone is Item it)
                    {
                        foreach (var(slotRef, inventory) in PreviousInventories)
                        {
                            if (slotRef.Item == receiver)
                            {
                                inventory.GetReplacementOrThiS().TryPutItem(it, slotRef.Slot, false, false, null, createNetworkEvent: false);
                            }
                        }
                    }
                }

                foreach (MapEntity clone in clones)
                {
                    clone.Submarine = Submarine.MainSub;
                }
            }
            else
            {
                foreach (MapEntity t in Receivers)
                {
                    MapEntity receiver = t.GetReplacementOrThis();
                    if (!receiver.Removed)
                    {
                        receiver.Remove();
                    }
                }
            }
        }
Ejemplo n.º 8
0
 public static void LoadContent(Game1 game, ItemComponent item)
 {
     SpriteProcessor.LoadContent(game, item.spriteComponent);
 }
Ejemplo n.º 9
0
 private void OnEnable()
 {
     targetObject = (ItemComponent)target;
 }
Ejemplo n.º 10
0
        public void Update(GameTime gameTime)
        {
            ComponentManager cm = ComponentManager.GetInstance();

            foreach (var entity in cm.GetComponentsOfType <PlayerControlComponent>())
            {
                PlayerControlComponent playerComp = (PlayerControlComponent)entity.Value;

                if (cm.HasEntityComponent <InventoryComponent>(entity.Key))
                {
                    InventoryComponent invenComp = cm.GetComponentForEntity <InventoryComponent>(entity.Key);

                    if (invenComp.ItemsToAdd.Count > 0)
                    {
                        foreach (int item in invenComp.ItemsToAdd)
                        {
                            AddItemToInventory(entity.Key, item);
                        }
                        invenComp.ItemsToAdd.Clear();
                    }
                    if (invenComp.ItemsToRemove.Count > 0)
                    {
                        foreach (int item in invenComp.ItemsToRemove)
                        {
                            ItemComponent itemComp = cm.GetComponentForEntity <ItemComponent>(item);
                            invenComp.Items[itemComp.InventoryPosition] = 0;
                            invenComp.AmountOfItems--;
                        }
                        invenComp.ItemsToRemove.Clear();
                    }
                    if (playerComp.Inventory.IsButtonDown())
                    {
                        if (cm.HasEntityComponent <MoveComponent>(entity.Key) && cm.HasEntityComponent <AttackComponent>(entity.Key))
                        {
                            MoveComponent   moveComp   = cm.GetComponentForEntity <MoveComponent>(entity.Key);
                            AttackComponent attackComp = cm.GetComponentForEntity <AttackComponent>(entity.Key);
                            if (invenComp.IsOpen)
                            {
                                attackComp.CanAttack = true;
                                moveComp.CanMove     = true;
                                invenComp.HeldItem   = 0;
                                invenComp.IsOpen     = false;
                            }
                            else
                            {
                                attackComp.CanAttack = false;
                                moveComp.Velocity    = new Vector2(0.0f, 0.0f);
                                moveComp.CanMove     = false;
                                invenComp.IsOpen     = true;
                            }
                        }
                    }
                    if (invenComp.IsOpen)
                    {
                        if (invenComp.selectSlotCurCooldown <= 0.0f)
                        {
                            Vector2 stickDir = playerComp.Movement.GetDirection();

                            invenComp.selectSlotCurCooldown = invenComp.SelectSlotDelay;
                            if (Math.Abs(stickDir.X) > 0.5f || Math.Abs(stickDir.Y) > 0.5f)
                            {
                                //if the stick has been pushed in a direction
                                Point direction = MoveSystem.CalcDirection(stickDir.Y, stickDir.X);
                                Point nextSlot  = invenComp.SelectedSlot + direction;

                                UpdateNextSelectedPos(ref nextSlot, invenComp.SelectedSlot);

                                if (UpdateInventoryFocus(invenComp, nextSlot))
                                {
                                    invenComp.SelectedSlot          = nextSlot;
                                    invenComp.selectSlotCurCooldown = invenComp.SelectSlotDelay;
                                }
                            }
                            //Selecting slot
                            else if (playerComp.Interact.IsButtonDown())
                            {
                                //calculate the location of the selected slot in the items array
                                int selectedArraySlot = invenComp.SelectedSlot.Y + (invenComp.ColumnsRows.X) * invenComp.SelectedSlot.X;
                                //if no item is held
                                if (invenComp.HeldItem == 0)
                                {
                                    if (invenComp.LocationInInventory == LocationInInventory.Equipment)
                                    {
                                        //Unequip equipment
                                        int equipPos = Math.Abs(invenComp.SelectedSlot.X) - 1;
                                        if (AddItemToInventory(entity.Key, invenComp.WeaponBodyHead[equipPos]))
                                        {
                                            UnEquipItemVisually(invenComp.WeaponBodyHead[equipPos], cm);
                                            invenComp.WeaponBodyHead[equipPos] = 0;
                                        }
                                    }
                                    else if (invenComp.LocationInInventory == LocationInInventory.Bagspace)
                                    {
                                        //Picked an item to hold
                                        invenComp.HeldItem = invenComp.Items[selectedArraySlot];
                                    }
                                    else if (invenComp.LocationInInventory == LocationInInventory.Stats)
                                    {
                                        StatsComponent statComp = cm.GetComponentForEntity <StatsComponent>(entity.Key);
                                        if (statComp.SpendableStats > 0)
                                        {
                                            //Increase the selected stat
                                            if (invenComp.SelectedSlot.X == -1)
                                            {
                                                //increase int
                                                statComp.AddInt += 1;
                                            }
                                            else if (invenComp.SelectedSlot.X == -2)
                                            {
                                                //increase stamina
                                                statComp.AddSta += 1;
                                            }
                                            else if (invenComp.SelectedSlot.X == -3)
                                            {
                                                //increase agility
                                                statComp.AddAgi += 1;
                                            }
                                            else if (invenComp.SelectedSlot.X == -4)
                                            {
                                                //increase strength
                                                statComp.AddStr += 1;
                                            }
                                            statComp.SpendableStats--;
                                        }
                                    }
                                    else if (invenComp.LocationInInventory == LocationInInventory.Skills)
                                    {
                                        StatsComponent statComp = cm.GetComponentForEntity <StatsComponent>(entity.Key);
                                        //Choose the skill selected if it has not already been picked and prerequisite requirements have been met
                                        if (ChooseAvailableSkill(ref invenComp, GetSelectedSkillSlot(invenComp.SelectedSlot.X, invenComp.SelectedSlot.Y)) &&
                                            statComp.SpendableStats >= 5)
                                        {
                                            statComp.SpendableStats -= 5;
                                        }
                                    }
                                }
                                else
                                {
                                    //if we do have a held item
                                    ItemComponent heldItemComp = cm.GetComponentForEntity <ItemComponent>(invenComp.HeldItem);
                                    if (invenComp.LocationInInventory == LocationInInventory.Equipment)
                                    {
                                        //if our currently selected slot is in one of the equipment slots
                                        int equipPos = Math.Abs(invenComp.SelectedSlot.X) - 1;
                                        if ((int)heldItemComp.Type == equipPos)
                                        {
                                            int equipToSwap = 0;
                                            if (invenComp.WeaponBodyHead[equipPos] != 0)
                                            {
                                                //if there is an item in the selected slot. Swap locations of the items
                                                equipToSwap = invenComp.WeaponBodyHead[equipPos];
                                                cm.GetComponentForEntity <ItemComponent>(equipToSwap).InventoryPosition = heldItemComp.InventoryPosition;
                                                UnEquipItemVisually(equipToSwap, cm);
                                                invenComp.AmountOfItems++;
                                            }
                                            invenComp.WeaponBodyHead[equipPos] = invenComp.HeldItem;
                                            invenComp.Items[heldItemComp.InventoryPosition] = equipToSwap;
                                            heldItemComp.InventoryPosition = -equipPos;
                                            invenComp.AmountOfItems--;
                                        }
                                    }
                                    else if (invenComp.LocationInInventory == LocationInInventory.Bagspace)
                                    {
                                        int itemToSwap = 0;
                                        if (invenComp.Items[selectedArraySlot] != 0)
                                        {
                                            //Swap item locations
                                            itemToSwap = invenComp.Items[selectedArraySlot];
                                            invenComp.Items[heldItemComp.InventoryPosition] = itemToSwap;
                                            cm.GetComponentForEntity <ItemComponent>(itemToSwap).InventoryPosition = heldItemComp.InventoryPosition;
                                        }
                                        invenComp.Items[selectedArraySlot] = invenComp.HeldItem;
                                        invenComp.Items[heldItemComp.InventoryPosition] = itemToSwap;
                                        heldItemComp.InventoryPosition = selectedArraySlot;
                                    }
                                    invenComp.HeldItem = 0; // no matter what action was taken, the held item should be deselected so we can choose a new one in the future
                                }
                                UpdateActualEquippedItems(ref invenComp, ref cm, entity.Key);
                            }
                            //Quick equip
                            else if (playerComp.Attack.IsButtonDown())
                            {
                                if (invenComp.LocationInInventory == LocationInInventory.Bagspace)
                                {
                                    int           selectedArraySlot = invenComp.SelectedSlot.Y + (invenComp.ColumnsRows.X) * invenComp.SelectedSlot.X;
                                    ItemComponent selectedItemComp  = cm.GetComponentForEntity <ItemComponent>(invenComp.Items[selectedArraySlot]);

                                    if (selectedItemComp != null)
                                    {
                                        if ((int)selectedItemComp.Type <= 2)
                                        {
                                            if (invenComp.HeldItem != 0)
                                            {
                                                invenComp.HeldItem = 0;
                                            }
                                            if (invenComp.WeaponBodyHead[(int)selectedItemComp.Type] == 0)
                                            {
                                                //Equip the item
                                                invenComp.WeaponBodyHead[(int)selectedItemComp.Type] = invenComp.Items[selectedArraySlot];
                                                selectedItemComp.InventoryPosition = -(int)selectedItemComp.Type - 1;
                                                invenComp.Items[selectedArraySlot] = 0;
                                                invenComp.AmountOfItems--;
                                            }
                                            else
                                            {
                                                //The spot is occupied and will be swapped
                                                int itemToMove = invenComp.WeaponBodyHead[(int)selectedItemComp.Type];
                                                invenComp.WeaponBodyHead[(int)selectedItemComp.Type] = invenComp.Items[selectedArraySlot];
                                                invenComp.Items[selectedArraySlot] = itemToMove;

                                                cm.GetComponentForEntity <ItemComponent>(itemToMove).InventoryPosition = selectedItemComp.InventoryPosition;
                                                selectedItemComp.InventoryPosition = -(int)selectedItemComp.Type - 1;
                                                UnEquipItemVisually(itemToMove, cm);
                                            }
                                        }
                                        else if (selectedItemComp.Type == ItemType.Consumable)
                                        {
                                            selectedItemComp.Use(entity.Key, selectedItemComp.InventoryPosition);
                                            invenComp.AmountOfItems--;
                                        }
                                    }
                                }
                                UpdateActualEquippedItems(ref invenComp, ref cm, entity.Key);
                            }
                            //drop selected item
                            else if (playerComp.Back.IsButtonDown())
                            {
                                if (invenComp.LocationInInventory == LocationInInventory.Bagspace)
                                {
                                    int           selectedArraySlot = invenComp.SelectedSlot.Y + (invenComp.ColumnsRows.X) * invenComp.SelectedSlot.X;
                                    ItemComponent selectedItemComp  = cm.GetComponentForEntity <ItemComponent>(invenComp.Items[selectedArraySlot]);

                                    if (selectedItemComp != null)
                                    {
                                        PositionComponent playerPosComp = cm.GetComponentForEntity <PositionComponent>(entity.Key);
                                        cm.AddComponentsToEntity(invenComp.Items[selectedArraySlot], new IComponent[] {
                                            new PositionComponent(playerPosComp.Position),
                                            new InteractComponent(InteractType.Loot)
                                        });
                                        invenComp.Items[selectedArraySlot] = 0;
                                        invenComp.AmountOfItems--;
                                    }
                                }
                            }
                            else if (cm.HasEntityComponent <ActionBarComponent>(entity.Key))
                            {
                                ActionBarComponent actionBComp = cm.GetComponentForEntity <ActionBarComponent>(entity.Key);
                                if (playerComp.ActionBar1.IsButtonDown())
                                {
                                    BindToActionBar(ref invenComp, ref actionBComp, ref cm, 0);
                                }
                                else if (playerComp.ActionBar2.IsButtonDown())
                                {
                                    BindToActionBar(ref invenComp, ref actionBComp, ref cm, 1);
                                }
                                else if (playerComp.ActionBar3.IsButtonDown())
                                {
                                    BindToActionBar(ref invenComp, ref actionBComp, ref cm, 2);
                                }
                                else if (playerComp.ActionBar4.IsButtonDown())
                                {
                                    BindToActionBar(ref invenComp, ref actionBComp, ref cm, 3);
                                }
                                else
                                {
                                    invenComp.selectSlotCurCooldown = 0.0f;
                                }
                            }
                            else
                            {
                                invenComp.selectSlotCurCooldown = 0.0f;
                            }
                        }
                        else
                        {
                            invenComp.selectSlotCurCooldown -= (float)gameTime.ElapsedGameTime.TotalSeconds;
                        }
                    }
                }
            }
        }
Ejemplo n.º 11
0
 private bool IsLoaded(ItemComponent weapon, bool checkContainedItems = true) =>
 weapon.HasRequiredContainedItems(character, addMessage: false) &&
 (!checkContainedItems || weapon.Item.OwnInventory == null || weapon.Item.OwnInventory.AllItems.Any(i => i.Condition > 0));
Ejemplo n.º 12
0
        public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
        {
            string errorMsg = "";

            if (extraData == null || extraData.Length == 0 || !(extraData[0] is NetEntityEvent.Type))
            {
                if (extraData == null)
                {
                    errorMsg = "Failed to write a network event for the item \"" + Name + "\" - event data was null.";
                }
                else if (extraData.Length == 0)
                {
                    errorMsg = "Failed to write a network event for the item \"" + Name + "\" - event data was empty.";
                }
                else
                {
                    errorMsg = "Failed to write a network event for the item \"" + Name + "\" - event type not set.";
                }
                msg.WriteRangedInteger((int)NetEntityEvent.Type.Invalid, 0, Enum.GetValues(typeof(NetEntityEvent.Type)).Length - 1);
                DebugConsole.Log(errorMsg);
                GameAnalyticsManager.AddErrorEventOnce("Item.ServerWrite:InvalidData" + Name, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                return;
            }

            int initialWritePos = msg.LengthBits;

            NetEntityEvent.Type eventType = (NetEntityEvent.Type)extraData[0];
            msg.WriteRangedInteger((int)eventType, 0, Enum.GetValues(typeof(NetEntityEvent.Type)).Length - 1);
            switch (eventType)
            {
            case NetEntityEvent.Type.ComponentState:
                if (extraData.Length < 2 || !(extraData[1] is int))
                {
                    errorMsg = "Failed to write a component state event for the item \"" + Name + "\" - component index not given.";
                    break;
                }
                int componentIndex = (int)extraData[1];
                if (componentIndex < 0 || componentIndex >= components.Count)
                {
                    errorMsg = "Failed to write a component state event for the item \"" + Name + "\" - component index out of range (" + componentIndex + ").";
                    break;
                }
                else if (!(components[componentIndex] is IServerSerializable))
                {
                    errorMsg = "Failed to write a component state event for the item \"" + Name + "\" - component \"" + components[componentIndex] + "\" is not server serializable.";
                    break;
                }
                msg.WriteRangedInteger(componentIndex, 0, components.Count - 1);
                (components[componentIndex] as IServerSerializable).ServerWrite(msg, c, extraData);
                break;

            case NetEntityEvent.Type.InventoryState:
                if (extraData.Length < 2 || !(extraData[1] is int))
                {
                    errorMsg = "Failed to write an inventory state event for the item \"" + Name + "\" - component index not given.";
                    break;
                }
                int containerIndex = (int)extraData[1];
                if (containerIndex < 0 || containerIndex >= components.Count)
                {
                    errorMsg = "Failed to write an inventory state event for the item \"" + Name + "\" - container index out of range (" + containerIndex + ").";
                    break;
                }
                else if (!(components[containerIndex] is ItemContainer))
                {
                    errorMsg = "Failed to write an inventory state event for the item \"" + Name + "\" - component \"" + components[containerIndex] + "\" is not server serializable.";
                    break;
                }
                msg.WriteRangedInteger(containerIndex, 0, components.Count - 1);
                msg.Write(GameMain.Server.EntityEventManager.Events.Last()?.ID ?? (ushort)0);
                (components[containerIndex] as ItemContainer).Inventory.ServerWrite(msg, c);
                break;

            case NetEntityEvent.Type.Status:
                msg.Write(condition);
                break;

            case NetEntityEvent.Type.AssignCampaignInteraction:
                msg.Write((byte)CampaignInteractionType);
                break;

            case NetEntityEvent.Type.Treatment:
            {
                ItemComponent targetComponent = (ItemComponent)extraData[1];
                ActionType    actionType      = (ActionType)extraData[2];
                ushort        targetID        = (ushort)extraData[3];
                Limb          targetLimb      = (Limb)extraData[4];

                Character targetCharacter = FindEntityByID(targetID) as Character;
                byte      targetLimbIndex = targetLimb != null && targetCharacter != null ? (byte)Array.IndexOf(targetCharacter.AnimController.Limbs, targetLimb) : (byte)255;

                msg.Write((byte)components.IndexOf(targetComponent));
                msg.WriteRangedInteger((int)actionType, 0, Enum.GetValues(typeof(ActionType)).Length - 1);
                msg.Write(targetID);
                msg.Write(targetLimbIndex);
            }
            break;

            case NetEntityEvent.Type.ApplyStatusEffect:
            {
                ActionType    actionType      = (ActionType)extraData[1];
                ItemComponent targetComponent = extraData.Length > 2 ? (ItemComponent)extraData[2] : null;
                ushort        characterID     = extraData.Length > 3 ? (ushort)extraData[3] : (ushort)0;
                Limb          targetLimb      = extraData.Length > 4 ? (Limb)extraData[4] : null;
                ushort        useTargetID     = extraData.Length > 5 ? (ushort)extraData[5] : (ushort)0;
                Vector2?      worldPosition   = null;
                if (extraData.Length > 6)
                {
                    worldPosition = (Vector2)extraData[6];
                }

                Character targetCharacter = FindEntityByID(characterID) as Character;
                byte      targetLimbIndex = targetLimb != null && targetCharacter != null ? (byte)Array.IndexOf(targetCharacter.AnimController.Limbs, targetLimb) : (byte)255;

                msg.WriteRangedInteger((int)actionType, 0, Enum.GetValues(typeof(ActionType)).Length - 1);
                msg.Write((byte)(targetComponent == null ? 255 : components.IndexOf(targetComponent)));
                msg.Write(characterID);
                msg.Write(targetLimbIndex);
                msg.Write(useTargetID);
                msg.Write(worldPosition.HasValue);
                if (worldPosition.HasValue)
                {
                    msg.Write(worldPosition.Value.X);
                    msg.Write(worldPosition.Value.Y);
                }
            }
            break;

            case NetEntityEvent.Type.ChangeProperty:
                try
                {
                    WritePropertyChange(msg, extraData, inGameEditableOnly: !GameMain.NetworkMember.IsServer);
                }
                catch (Exception e)
                {
                    errorMsg = "Failed to write a ChangeProperty network event for the item \"" + Name + "\" (" + e.Message + ")";
                }
                break;

            case NetEntityEvent.Type.Upgrade:
                if (extraData.Length > 0 && extraData[1] is Upgrade upgrade)
                {
                    var upgradeTargets = upgrade.TargetComponents;
                    msg.Write(upgrade.Identifier);
                    msg.Write((byte)upgrade.Level);
                    msg.Write((byte)upgradeTargets.Count);
                    foreach (var(_, value) in upgrade.TargetComponents)
                    {
                        msg.Write((byte)value.Length);
                        foreach (var propertyReference in value)
                        {
                            object originalValue = propertyReference.OriginalValue;
                            msg.Write((float)(originalValue ?? -1));
                        }
                    }
                }
                else
                {
                    errorMsg = extraData.Length > 0
                            ? $"Failed to write a network event for the item \"{Name}\" - \"{extraData[1].GetType()}\" is not a valid upgrade."
                            : $"Failed to write a network event for the item \"{Name}\". No upgrade specified.";
                }
                break;

            default:
                errorMsg = "Failed to write a network event for the item \"" + Name + "\" - \"" + eventType + "\" is not a valid entity event type for items.";
                break;
            }

            if (!string.IsNullOrEmpty(errorMsg))
            {
                //something went wrong - rewind the write position and write invalid event type to prevent creating an unreadable event
                msg.BitPosition = initialWritePos;
                msg.LengthBits  = initialWritePos;
                msg.WriteRangedInteger((int)NetEntityEvent.Type.Invalid, 0, Enum.GetValues(typeof(NetEntityEvent.Type)).Length - 1);
                DebugConsole.Log(errorMsg);
                GameAnalyticsManager.AddErrorEventOnce("Item.ServerWrite:" + errorMsg, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
            }
        }
Ejemplo n.º 13
0
        private Item GetWeapon(IEnumerable <ItemComponent> weaponList, out ItemComponent weaponComponent)
        {
            weaponComponent = null;
            float bestPriority = 0;
            float lethalDmg    = -1;

            foreach (var weapon in weaponList)
            {
                // By default, the bots won't go offensive with bad weapons, unless they are close to the enemy or ordered to fight enemies.
                // NPC characters ignore this check.
                if ((initialMode == CombatMode.Offensive || initialMode == CombatMode.Arrest) && character.TeamID != Character.TeamType.FriendlyNPC)
                {
                    if (!objectiveManager.IsCurrentOrder <AIObjectiveFightIntruders>() && !EnemyIsClose())
                    {
                        if (weapon.CombatPriority < goodWeaponPriority)
                        {
                            continue;
                        }
                    }
                }

                float priority = weapon.CombatPriority;
                if (!IsLoaded(weapon))
                {
                    if (weapon is RangedWeapon && EnemyIsClose())
                    {
                        // Close to the enemy. Ignore weapons that don't have any ammunition (-> Don't seek ammo).
                        continue;
                    }
                    else
                    {
                        // Halve the priority for weapons that don't have proper ammunition loaded.
                        priority /= 2;
                    }
                }
                if (Enemy.Stun > 1)
                {
                    // Enemy is stunned, reduce the priority of stunner weapons.
                    Attack attack = GetAttackDefinition(weapon);
                    if (attack != null)
                    {
                        lethalDmg = attack.GetTotalDamage();
                        float max = lethalDmg + 1;
                        if (weapon.Item.HasTag("stunner"))
                        {
                            priority = max;
                        }
                        else
                        {
                            float stunDmg = ApproximateStunDamage(weapon, attack);
                            float diff    = stunDmg - lethalDmg;
                            priority = Math.Clamp(priority - Math.Max(diff * 2, 0), min: 1, max);
                        }
                    }
                }
                else if (Mode == CombatMode.Arrest)
                {
                    // Enemy is not stunned, increase the priority of stunner weapons and decrease the priority of lethal weapons.
                    if (weapon.Item.HasTag("stunner"))
                    {
                        priority *= 2;
                    }
                    else
                    {
                        Attack attack = GetAttackDefinition(weapon);
                        if (attack != null)
                        {
                            lethalDmg = attack.GetTotalDamage();
                            float stunDmg = ApproximateStunDamage(weapon, attack);
                            float diff    = stunDmg - lethalDmg;
                            if (diff < 0)
                            {
                                priority /= 2;
                            }
                        }
                    }
                }
                if (priority > bestPriority)
                {
                    weaponComponent = weapon;
                    bestPriority    = priority;
                }
            }
            if (weaponComponent == null)
            {
                return(null);
            }
            if (bestPriority < 1)
            {
                return(null);
            }
            if (Mode == CombatMode.Arrest)
            {
                if (weaponComponent.Item.HasTag("stunner"))
                {
                    isLethalWeapon = false;
                }
                else
                {
                    if (lethalDmg < 0)
                    {
                        lethalDmg = GetLethalDamage(weaponComponent);
                    }
                    isLethalWeapon = lethalDmg > 1;
                }
                if (allowHoldFire && !hasAimed && holdFireTimer <= 0)
                {
                    holdFireTimer = arrestHoldFireTime * Rand.Range(0.75f, 1.25f);
                }
            }
            return(weaponComponent.Item);

            bool EnemyIsClose() => character.CurrentHull == Enemy.CurrentHull || Vector2.DistanceSquared(character.Position, Enemy.Position) < 500;

            Attack GetAttackDefinition(ItemComponent weapon)
            {
                Attack attack = null;

                if (weapon is MeleeWeapon meleeWeapon)
                {
                    attack = meleeWeapon.Attack;
                }
                else if (weapon is RangedWeapon rangedWeapon)
                {
                    attack = rangedWeapon.FindProjectile(triggerOnUseOnContainers: false)?.Attack;
                }
                return(attack);
            }

            float GetLethalDamage(ItemComponent weapon)
            {
                float  lethalDmg = 0;
                Attack attack    = GetAttackDefinition(weapon);

                if (attack != null)
                {
                    lethalDmg = attack.GetTotalDamage();
                }
                return(lethalDmg);
            }

            float ApproximateStunDamage(ItemComponent weapon, Attack attack)
            {
                // Try to reduce the priority using the actual damage values and status effects.
                // This is an approximation, because we can't check the status effect conditions here.
                // The result might be incorrect if there is a high stun effect that's only applied in certain conditions.
                var statusEffects = attack.StatusEffects.Where(se => !se.HasConditions && se.type == ActionType.OnUse && se.HasRequiredItems(character));

                if (weapon.statusEffectLists != null && weapon.statusEffectLists.TryGetValue(ActionType.OnUse, out List <StatusEffect> hitEffects))
                {
                    statusEffects = statusEffects.Concat(hitEffects);
                }
                float afflictionsStun = attack.Afflictions.Keys.Sum(a => a.Identifier == "stun" ? a.Strength : 0);
                float effectsStun     = statusEffects.None() ? 0 : statusEffects.Max(se =>
                {
                    float stunAmount   = 0;
                    var stunAffliction = se.Afflictions.Find(a => a.Identifier == "stun");
                    if (stunAffliction != null)
                    {
                        stunAmount = stunAffliction.Strength;
                    }
                    return(stunAmount);
                });

                return(attack.Stun + afflictionsStun + effectsStun);
            }
        }
Ejemplo n.º 14
0
 private Item GetWeapon(out ItemComponent weaponComponent) => GetWeapon(GetAllWeapons(), out weaponComponent);
Ejemplo n.º 15
0
        private bool RecalculateWeaponAbilities(GameEntity actorEntity, bool melee, GameManager manager)
        {
            var canUseWeapons = CanUseWeapons(actorEntity);

            var           being           = actorEntity.Being;
            ItemComponent twoHandedWeapon = null;
            ItemComponent primaryWeapon   = null;
            ItemComponent secondaryWeapon = null;

            if (canUseWeapons)
            {
                if (melee)
                {
                    if (being.PrimaryNaturalWeaponId.HasValue)
                    {
                        primaryWeapon = manager.FindEntity(being.PrimaryNaturalWeaponId.Value).Item;
                    }
                    else
                    {
                        var primaryWeaponReference = TryCreateNaturalWeapon(being.UpperExtremities, melee, manager);
                        if (primaryWeaponReference != null)
                        {
                            primaryWeapon = primaryWeaponReference.Referenced.Item;
                            primaryWeapon.EquippedSlot   = EquipmentSlot.GraspPrimaryMelee;
                            being.PrimaryNaturalWeaponId = primaryWeapon.EntityId;
                            primaryWeaponReference.Dispose();
                        }
                    }

                    if (being.SecondaryNaturalWeaponId.HasValue)
                    {
                        secondaryWeapon = manager.FindEntity(being.SecondaryNaturalWeaponId.Value).Item;
                    }
                    else
                    {
                        var secondaryWeaponReference = TryCreateNaturalWeapon(being.UpperExtremities, melee, manager);
                        if (secondaryWeaponReference != null)
                        {
                            secondaryWeapon = secondaryWeaponReference.Referenced.Item;
                            secondaryWeapon.EquippedSlot   = EquipmentSlot.GraspSecondaryMelee;
                            being.SecondaryNaturalWeaponId = secondaryWeapon.EntityId;
                            secondaryWeaponReference.Dispose();
                        }
                    }
                }

                foreach (var itemEntity in manager.EntityItemsToContainerRelationship[actorEntity.Id])
                {
                    var item = itemEntity.Item;

                    if (melee)
                    {
                        switch (item.EquippedSlot)
                        {
                        case EquipmentSlot.GraspBothMelee:
                            twoHandedWeapon = item;
                            primaryWeapon   = null;
                            secondaryWeapon = null;
                            break;

                        case EquipmentSlot.GraspPrimaryMelee:
                            primaryWeapon = item;
                            break;

                        case EquipmentSlot.GraspSecondaryMelee:
                            secondaryWeapon = item;
                            break;
                        }
                    }
                    else
                    {
                        switch (item.EquippedSlot)
                        {
                        case EquipmentSlot.GraspBothRanged:
                            twoHandedWeapon = item;
                            primaryWeapon   = null;
                            secondaryWeapon = null;
                            break;

                        case EquipmentSlot.GraspPrimaryRanged:
                            primaryWeapon = item;
                            break;

                        case EquipmentSlot.GraspSecondaryRanged:
                            secondaryWeapon = item;
                            break;
                        }
                    }
                }
            }

            var activation            = melee ? ActivationType.OnMeleeAttack : ActivationType.OnRangedAttack;
            var twoHandedWeaponAttack = ResetWeaponAbility(
                melee ? TwoHandedMeleeWeaponAttackName : TwoHandedRangedWeaponAttackName,
                actorEntity, twoHandedWeapon, activation, manager);

            var primaryWeaponAttack = ResetWeaponAbility(
                melee ? PrimaryMeleeWeaponAttackName : PrimaryRangedWeaponAttackName,
                actorEntity, primaryWeapon, activation, manager);

            var secondaryWeaponAttack = ResetWeaponAbility(
                melee ? SecondaryMeleeWeaponAttackName : SecondaryRangedWeaponAttackName,
                actorEntity, secondaryWeapon, activation, manager);

            foreach (WieldingAbility defaultAttackTemplate in Ability.Loader.GetAllValues(AbilityType.DefaultAttack))
            {
                if ((melee && (defaultAttackTemplate.ItemType & ItemType.WeaponMelee) != 0) ||
                    (!melee && (defaultAttackTemplate.ItemType & ItemType.WeaponRanged) != 0))
                {
                    EnsureAbility(defaultAttackTemplate, actorEntity, manager);
                }
            }

            AbilityComponent defaultAttackAbility = null;
            var expectedItemType = melee ? ItemType.WeaponMelee : ItemType.WeaponRanged;

            foreach (var abilityEntity in manager.AbilitiesToAffectableRelationship[actorEntity.Id])
            {
                var ability = abilityEntity.Ability;
                if (ability.Template == null ||
                    !(ability.Template is WieldingAbility wieldingAbility) ||
                    (wieldingAbility.ItemType & expectedItemType) == 0)
                {
                    continue;
                }

                switch (wieldingAbility.WieldingStyle)
                {
                case WieldingStyle.OneHanded:
                    var primaryUsable = IsCompatible(
                        primaryWeapon, activation, wieldingAbility.ItemType, wieldingAbility.DamageType, manager);
                    var secondaryUsable = IsCompatible(
                        secondaryWeapon, activation, wieldingAbility.ItemType, wieldingAbility.DamageType, manager);

                    ResetWieldingAbility(ability, wieldingAbility,
                                         primaryUsable == secondaryUsable ? null :
                                         primaryUsable?primaryWeaponAttack: secondaryWeaponAttack,
                                         null, activation, actorEntity);
                    break;

                case WieldingStyle.TwoHanded:
                    var twoHandedUsable = IsCompatible(
                        twoHandedWeapon, activation, wieldingAbility.ItemType, wieldingAbility.DamageType, manager);

                    ResetWieldingAbility(ability, wieldingAbility,
                                         twoHandedUsable ? twoHandedWeaponAttack : null, null, activation, actorEntity);
                    break;

                case WieldingStyle.Dual:
                    var bothUsable = IsCompatible(
                        primaryWeapon, activation, wieldingAbility.ItemType,
                        wieldingAbility.DamageType, manager) &&
                                     IsCompatible(
                        secondaryWeapon, activation, wieldingAbility.ItemType,
                        wieldingAbility.DamageType, manager);

                    ResetWieldingAbility(ability, wieldingAbility,
                                         bothUsable ? primaryWeaponAttack : null, bothUsable ? secondaryWeaponAttack : null,
                                         activation, actorEntity);
                    break;

                default:
                    var primaryWeaponUsable = IsCompatible(
                        primaryWeapon, activation, wieldingAbility.ItemType, wieldingAbility.DamageType, manager);
                    var secondaryWeaponUsable = IsCompatible(
                        secondaryWeapon, activation, wieldingAbility.ItemType, wieldingAbility.DamageType, manager);
                    var twoHandedWeaponUsable = IsCompatible(
                        twoHandedWeapon, activation, wieldingAbility.ItemType, wieldingAbility.DamageType, manager);

                    ResetWieldingAbility(ability, wieldingAbility,
                                         primaryWeaponUsable ? primaryWeaponAttack :
                                         twoHandedWeaponUsable?twoHandedWeaponAttack: null,
                                         secondaryWeaponUsable ? secondaryWeaponAttack : null, activation, actorEntity);
                    break;
                }

                if (wieldingAbility.Type == AbilityType.DefaultAttack &&
                    ability.IsUsable)
                {
                    Debug.Assert(defaultAttackAbility == null);
                    defaultAttackAbility = ability;
                }
            }

            var setSlotMessage = manager.AbilitySlottingSystem.CreateSetAbilitySlotMessage(manager);

            setSlotMessage.Slot = melee
                ? AbilitySlottingSystem.DefaultMeleeAttackSlot
                : AbilitySlottingSystem.DefaultRangedAttackSlot;
            setSlotMessage.AbilityEntity = defaultAttackAbility?.Entity;
            setSlotMessage.OwnerEntity   = actorEntity;
            manager.Enqueue(setSlotMessage);

            return(canUseWeapons);
        }
Ejemplo n.º 16
0
        public void SetChickenWayPoint()
        {
            if (this._farmKind != FarmPoint.FarmKind.ChickenCoop)
            {
                return;
            }
            this.AreaIDOnHousingArea = this.GetHousingAreaID();
            if (!Singleton <Resources> .IsInstance())
            {
                return;
            }
            ItemComponent componentInParent = (ItemComponent)((Component)this).GetComponentInParent <ItemComponent>();

            Collider[] componentsInChildren = (Collider[])((Component)componentInParent)?.GetComponentsInChildren <Collider>();
            if (componentsInChildren.IsNullOrEmpty <Collider>())
            {
                return;
            }
            AnimalDefinePack.ChickenCoopWaypointSettings coopWaypointSetting = Singleton <Resources> .Instance.AnimalDefinePack.ChickenCoopWaypointSetting;
            Collider  collider1 = (Collider)null;
            LayerMask layer     = coopWaypointSetting.Layer;
            string    tagName   = coopWaypointSetting.TagName;

            foreach (Collider collider2 in componentsInChildren)
            {
                if (!Object.op_Equality((Object)collider2, (Object)null) && !Object.op_Equality((Object)((Component)collider2).get_gameObject(), (Object)null) && ((1 << ((Component)collider2).get_gameObject().get_layer() & LayerMask.op_Implicit(layer)) != 0 && ((Component)collider2).get_gameObject().get_tag() == tagName))
                {
                    collider1 = collider2;
                    break;
                }
            }
            if (Object.op_Equality((Object)collider1, (Object)null))
            {
                return;
            }
            Transform  transform = ((Component)componentInParent).get_transform();
            Vector3    position  = ((Component)collider1).get_transform().get_position();
            Quaternion rotation  = ((Component)collider1).get_transform().get_rotation();

            if (this._chickenWaypointPositionList == null)
            {
                this._chickenWaypointPositionList = new List <Vector3>();
            }
            else
            {
                this._chickenWaypointPositionList.Clear();
            }
            if (Object.op_Equality((Object)this._chickenWaypointRoot, (Object)null))
            {
                this._chickenWaypointRoot = new GameObject("Chicken Waypoint Root").get_transform();
                this._chickenWaypointRoot.SetParent(transform, false);
                Transform chickenWaypointRoot = this._chickenWaypointRoot;
                Vector3   zero = Vector3.get_zero();
                this._chickenWaypointRoot.set_localEulerAngles(zero);
                Vector3 vector3 = zero;
                chickenWaypointRoot.set_localPosition(vector3);
            }
            Vector3 installation = coopWaypointSetting.Installation;
            int     num1         = 0;
            int     num2         = 0;
            int     num3         = 0;

            while (++num3 <= 999999)
            {
                int num4 = 0;
                int num5 = 0;
                while (true)
                {
                    Vector3 vector3_1;
                    ((Vector3) ref vector3_1).\u002Ector((float)this.ReversiNumber(num2), 0.0f, (float)this.ReversiNumber(num5));
                    Vector3 vector3_2 = Vector3.Scale(vector3_1, installation);
                    vector3_1 = Vector3.op_Addition(position, Quaternion.op_Multiply(rotation, vector3_2));
                    int  num6 = Physics.RaycastNonAlloc(Vector3.op_Addition(vector3_1, Vector3.get_up()), Vector3.get_down(), FarmPoint._chickenWaypointRaycastHits, 2f, LayerMask.op_Implicit(layer));
                    int  num7 = Mathf.Min(FarmPoint._chickenWaypointRaycastHits.Length, num6);
                    bool flag = 0 < num7;
                    if (flag)
                    {
                        flag = false;
                        for (int index = 0; index < num7; ++index)
                        {
                            RaycastHit waypointRaycastHit = FarmPoint._chickenWaypointRaycastHits[index];
                            if (Object.op_Equality((Object)collider1, (Object)((RaycastHit) ref waypointRaycastHit).get_collider()))
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                    if (!flag)
                    {
                        ++num4;
                        if (num5 == 0)
                        {
                            break;
                        }
                    }
                    else
                    {
                        num1 = 0;
                        num4 = 0;
                        this._chickenWaypointPositionList.Add(vector3_1);
                    }
                    if (2 > num4)
                    {
                        ++num5;
                    }
                    else
                    {
                        goto label_32;
                    }
                }
                ++num1;
label_32:
                ++num2;
                if (2 <= num1)
                {
                    break;
                }
            }
            foreach (Waypoint chickenWaypoint in this._chickenWaypointList)
            {
                this.ReturnChickenWaypoint(chickenWaypoint);
            }
            this._chickenWaypointList.Clear();
            if (this._chickenWaypointPositionList.IsNullOrEmpty <Vector3>())
            {
                return;
            }
            float closestEdgeDistance = coopWaypointSetting.ClosestEdgeDistance;
            float sampleDistance      = coopWaypointSetting.SampleDistance;
            int   agentAreaMask       = coopWaypointSetting.AgentAreaMask;

            for (int id = 0; id < this._chickenWaypointPositionList.Count; ++id)
            {
                Vector3    vector3 = this._chickenWaypointPositionList[id];
                NavMeshHit navMeshHit;
                bool       flag = true & NavMesh.SamplePosition(vector3, ref navMeshHit, sampleDistance, agentAreaMask);
                if (flag)
                {
                    vector3 = ((NavMeshHit) ref navMeshHit).get_position();
                }
                if (flag)
                {
                    flag &= NavMesh.FindClosestEdge(vector3, ref navMeshHit, agentAreaMask);
                }
                if (flag)
                {
                    flag &= (double)closestEdgeDistance <= (double)((NavMeshHit) ref navMeshHit).get_distance();
                }
                if (flag)
                {
                    int num4 = Physics.RaycastNonAlloc(Vector3.op_Addition(vector3, Vector3.get_up()), Vector3.get_down(), FarmPoint._chickenWaypointRaycastHits, sampleDistance * 2f, LayerMask.op_Implicit(layer));
                    flag = 0 < num4;
                    if (flag)
                    {
                        int num5 = Mathf.Min(num4, FarmPoint._chickenWaypointRaycastHits.Length);
                        for (int index = 0; index < num5; ++index)
                        {
                            RaycastHit waypointRaycastHit = FarmPoint._chickenWaypointRaycastHits[index];
                            if (flag = Object.op_Equality((Object)collider1, (Object)((RaycastHit) ref waypointRaycastHit).get_collider()))
                            {
                                break;
                            }
                        }
                    }
                }
                if (flag)
                {
                    Waypoint chickenWaypoint = this.GetOrCreateChickenWaypoint(id);
                    ((Component)chickenWaypoint).get_transform().set_position(vector3);
                    if (!((Component)chickenWaypoint).get_gameObject().get_activeSelf())
                    {
                        ((Component)chickenWaypoint).get_gameObject().SetActive(true);
                    }
                    this._chickenWaypointList.Add(chickenWaypoint);
                }
            }
        }
Ejemplo n.º 17
0
 public bool TryGetTargetItemComponent(Item item, out ItemComponent firstMatchingComponent)
 {
     firstMatchingComponent = GetTargetItemComponent(item);
     return(firstMatchingComponent != null);
 }
Ejemplo n.º 18
0
        public virtual void GetItemDescriptionWithComparison(EntityManager entityManager, ItemComponent itemComponent, ItemsStoreComponent.Item item, out string header, out StringBuilder sb)
        {
            header = item.Name;
            sb     = new StringBuilder();
            sb.Append($"Item Level: {itemComponent.Level}");
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            if (item.ItemType == ItemType.Gear)
            {
                var equipped = UIManager.Instance.PlayerInfoMenuUIComponent.GearGroup.GearSlots
                               .Where(slot => slot.GearType == item.GearType).First();
                var equippedEntity = equipped.ItemEntity;
                var eqAttackValue  = 0;
                var eqDefenceValue = 0;
                var eqHealthValue  = 0;
                var eqMagicValue   = 0;

                if (equipped.HasItem)
                {
                    var eqItemComponent = entityManager.GetComponentData <ItemComponent>(equippedEntity);
                    if (entityManager.HasComponent <AttackStatModifierComponent>(equippedEntity))
                    {
                        var eqStatComponent = entityManager.GetComponentData <AttackStatModifierComponent>(equippedEntity);
                        eqAttackValue = eqStatComponent.Value * eqItemComponent.Level;
                    }
                    if (entityManager.HasComponent <DefenceStatModifierComponent>(equippedEntity))
                    {
                        var eqStatComponent = entityManager.GetComponentData <DefenceStatModifierComponent>(equippedEntity);
                        eqDefenceValue = eqStatComponent.Value * eqItemComponent.Level;
                    }
                    if (entityManager.HasComponent <HealthStatModifierComponent>(equippedEntity))
                    {
                        var eqStatComponent = entityManager.GetComponentData <HealthStatModifierComponent>(equippedEntity);
                        eqHealthValue = eqStatComponent.Value * eqItemComponent.Level;
                    }
                    if (entityManager.HasComponent <MagicStatModifierComponent>(equippedEntity))
                    {
                        var eqStatComponent = entityManager.GetComponentData <MagicStatModifierComponent>(equippedEntity);
                        eqMagicValue = eqStatComponent.Value * eqItemComponent.Level;
                    }
                }

                if (entityManager.HasComponent <AttackStatModifierComponent>(this.ItemEntity))
                {
                    var statComponent = entityManager.GetComponentData <AttackStatModifierComponent>(this.ItemEntity);
                    var totalValue    = statComponent.Value * itemComponent.Level;
                    sb.Append($"Attack: {totalValue}");

                    var difference = totalValue - eqAttackValue;
                    this.AddDifferenceText(sb, difference);

                    sb.Append(Environment.NewLine);
                }
                else
                {
                    if (eqAttackValue > 0)
                    {
                        sb.Append($"Attack: 0 (-{eqAttackValue})");
                        sb.Append(Environment.NewLine);
                    }
                }

                if (entityManager.HasComponent <DefenceStatModifierComponent>(this.ItemEntity))
                {
                    var statComponent = entityManager.GetComponentData <DefenceStatModifierComponent>(this.ItemEntity);
                    var totalValue    = statComponent.Value * itemComponent.Level;
                    sb.Append($"Defence: {totalValue}");

                    var difference = totalValue - eqDefenceValue;
                    this.AddDifferenceText(sb, difference);

                    sb.Append(Environment.NewLine);
                }
                else
                {
                    if (eqDefenceValue > 0)
                    {
                        sb.Append($"Defence: 0 (-{eqDefenceValue})");
                        sb.Append(Environment.NewLine);
                    }
                }

                if (entityManager.HasComponent <HealthStatModifierComponent>(this.ItemEntity))
                {
                    var statComponent = entityManager.GetComponentData <HealthStatModifierComponent>(this.ItemEntity);
                    var totalValue    = statComponent.Value * itemComponent.Level;
                    sb.Append($"Health: {totalValue}");

                    var difference = totalValue - eqHealthValue;
                    this.AddDifferenceText(sb, difference);

                    sb.Append(Environment.NewLine);
                }
                else
                {
                    if (eqHealthValue > 0)
                    {
                        sb.Append($"Health: 0 (-{eqHealthValue})");
                        sb.Append(Environment.NewLine);
                    }
                }

                if (entityManager.HasComponent <MagicStatModifierComponent>(this.ItemEntity))
                {
                    var statComponent = entityManager.GetComponentData <MagicStatModifierComponent>(this.ItemEntity);
                    var totalValue    = statComponent.Value * itemComponent.Level;
                    sb.Append($"Magic: {totalValue}");

                    var difference = totalValue - eqMagicValue;
                    this.AddDifferenceText(sb, difference);

                    sb.Append(Environment.NewLine);
                }
                else
                {
                    if (eqMagicValue > 0)
                    {
                        sb.Append($"Magic: 0 (-{eqMagicValue})");
                        sb.Append(Environment.NewLine);
                    }
                }
            }
            sb.Append(Environment.NewLine);
            sb.Append(item.Description.Replace("{value}", item.ModifierValue.ToString()));
        }
Ejemplo n.º 19
0
        static IList <data.ItemLink> MapItems(tftItems items)
        {
            IList <data.ItemLink>      links          = new List <data.ItemLink>();
            IList <data.ItemComponent> itemComponents = new List <data.ItemComponent>();

            foreach (PropertyInfo prop in items.GetType().GetProperties())
            {
                object value = prop.GetValue(items);
                Type   t     = value.GetType();

                if (t == typeof(ItemComponent))
                {
                    ItemComponent      temp          = (ItemComponent)value;
                    data.ItemComponent itemComponent = new data.ItemComponent
                    {
                        Name  = temp.name,
                        Type  = temp.type,
                        Bonus = temp.bonus,
                        Tier  = temp.tier,
                        Depth = temp.depth,
                        Kind  = temp.kind
                    };
                    foreach (ItemStat stat in temp.stats)
                    {
                        data.ItemComponentStat val = new data.ItemComponentStat
                        {
                            Name   = stat.name,
                            Title  = stat.title,
                            Amount = stat.amount
                        };
                        itemComponent.ItemComponentStat.Add(val);
                    }
                    itemComponents.Add(itemComponent);
                }
                else if (t == typeof(ItemFull))
                {
                    ItemFull      temp = (ItemFull)value;
                    data.ItemFull item = new data.ItemFull
                    {
                        Name  = temp.name,
                        Type  = temp.type,
                        Bonus = temp.bonus,
                        Tier  = temp.tier,
                        Depth = temp.depth,
                        Kind  = temp.kind
                    };
                    temp.buildsFrom = temp.buildsFrom.Distinct().ToList();
                    foreach (string buildComponent in temp.buildsFrom)
                    {
                        Regex pattern = new Regex("[.,' ]");

                        data.ItemComponent comp = itemComponents.First(x => pattern.Replace(x.Name.ToLower(), "") == buildComponent);
                        data.ItemLink      link = new data.ItemLink
                        {
                            ItemComponent = comp,
                            ItemFull      = item
                        };
                        links.Add(link);
                    }
                }
            }

            return(links);
        }
Ejemplo n.º 20
0
        public AIObjectiveOperateItem(ItemComponent item, Character character, AIObjectiveManager objectiveManager, string option, bool requireEquip,
                                      Entity operateTarget = null, bool useController = false, ItemComponent controller = null, float priorityModifier = 1)
            : base(character, objectiveManager, priorityModifier, option)
        {
            component          = item ?? throw new ArgumentNullException("item", "Attempted to create an AIObjectiveOperateItem with a null target.");
            this.requireEquip  = requireEquip;
            this.operateTarget = operateTarget;
            this.useController = useController;
            if (useController)
            {
                this.controller = controller ?? component?.Item?.FindController();
            }
            var target = GetTarget();

            if (target == null)
            {
                Abandon = true;
#if DEBUG
                throw new Exception("target null");
#endif
            }
            else if (target.Item.NonInteractable)
            {
                Abandon = true;
            }
        }
Ejemplo n.º 21
0
 private bool IsLoaded(ItemComponent weapon) => weapon.HasRequiredContainedItems(character, addMessage: false);
Ejemplo n.º 22
0
        protected override void Act(float deltaTime)
        {
            if (character.LockHands)
            {
                Abandon = true;
                return;
            }
            ItemComponent target = GetTarget();

            if (useController && controller == null)
            {
                character.Speak(TextManager.GetWithVariable("DialogCantFindController", "[item]", component.Item.Name, true), null, 2.0f, "cantfindcontroller", 30.0f);
                Abandon = true;
                return;
            }
            // Don't allow to operate an item that someone with a better skills already operates, unless this is an order
            if (objectiveManager.CurrentOrder != this && HumanAIController.IsItemOperatedByAnother(target, out _))
            {
                // Don't abandon
                return;
            }
            if (operateTarget != null)
            {
                if (HumanAIController.IsTrueForAnyCrewMember(other => other != HumanAIController && other.ObjectiveManager.GetActiveObjective() is AIObjectiveOperateItem operateObjective && operateObjective.operateTarget == operateTarget))
                {
                    // Another crew member is already targeting this entity.
                    Abandon = true;
                    return;
                }
            }
            if (target.CanBeSelected)
            {
                if (character.CanInteractWith(target.Item, out _, checkLinked: false))
                {
                    HumanAIController.FaceTarget(target.Item);
                    if (character.SelectedConstruction != target.Item)
                    {
                        target.Item.TryInteract(character, false, true);
                    }
                    if (component.AIOperate(deltaTime, character, this))
                    {
                        isDoneOperating = completionCondition == null || completionCondition();
                    }
                }
                else
                {
                    TryAddSubObjective(ref goToObjective, () => new AIObjectiveGoTo(target.Item, character, objectiveManager, closeEnough: 50)
                    {
                        DialogueIdentifier = "dialogcannotreachtarget",
                        TargetName         = target.Item.Name
                    },
                                       onAbandon: () => Abandon = true,
                                       onCompleted: () => RemoveSubObjective(ref goToObjective));
                }
            }
            else
            {
                if (component.Item.GetComponent <Pickable>() == null)
                {
                    //controller/target can't be selected and the item cannot be picked -> objective can't be completed
                    Abandon = true;
                    return;
                }
                else if (!character.Inventory.Items.Contains(component.Item))
                {
                    TryAddSubObjective(ref getItemObjective, () => new AIObjectiveGetItem(character, component.Item, objectiveManager, equip: true),
                                       onAbandon: () => Abandon = true,
                                       onCompleted: () => RemoveSubObjective(ref getItemObjective));
                }
                else
                {
                    if (requireEquip && !character.HasEquippedItem(component.Item))
                    {
                        //the item has to be equipped before using it if it's holdable
                        var holdable = component.Item.GetComponent <Holdable>();
                        if (holdable == null)
                        {
#if DEBUG
                            DebugConsole.ThrowError($"{character.Name}: AIObjectiveOperateItem failed - equipping item " + component.Item + " is required but the item has no Holdable component");
#endif
                            return;
                        }
                        for (int i = 0; i < character.Inventory.Capacity; i++)
                        {
                            if (character.Inventory.SlotTypes[i] == InvSlotType.Any || !holdable.AllowedSlots.Any(s => s.HasFlag(character.Inventory.SlotTypes[i])))
                            {
                                continue;
                            }
                            //equip slot already taken
                            if (character.Inventory.Items[i] != null)
                            {
                                //try to put the item in an Any slot, and drop it if that fails
                                if (!character.Inventory.Items[i].AllowedSlots.Contains(InvSlotType.Any) ||
                                    !character.Inventory.TryPutItem(character.Inventory.Items[i], character, new List <InvSlotType>()
                                {
                                    InvSlotType.Any
                                }))
                                {
                                    character.Inventory.Items[i].Drop(character);
                                }
                            }
                            if (character.Inventory.TryPutItem(component.Item, i, true, false, character))
                            {
                                component.Item.Equip(character);
                                break;
                            }
                        }
                        return;
                    }
                    if (component.AIOperate(deltaTime, character, this))
                    {
                        isDoneOperating = completionCondition == null || completionCondition();
                    }
                }
            }
        }
Ejemplo n.º 23
0
        private Item GetWeapon(IEnumerable <ItemComponent> weaponList, out ItemComponent weaponComponent)
        {
            weaponComponent = null;
            float bestPriority = 0;
            float lethalDmg    = -1;
            bool  enemyIsClose = EnemyIsClose();

            foreach (var weapon in weaponList)
            {
                float priority = weapon.CombatPriority;
                if (!IsLoaded(weapon))
                {
                    if (weapon is RangedWeapon && enemyIsClose)
                    {
                        // Close to the enemy. Ignore weapons that don't have any ammunition (-> Don't seek ammo).
                        continue;
                    }
                    else
                    {
                        // Halve the priority for weapons that don't have proper ammunition loaded.
                        priority /= 2;
                    }
                }
                if (Enemy.Stun > 1)
                {
                    // Enemy is stunned, reduce the priority of stunner weapons.
                    Attack attack = GetAttackDefinition(weapon);
                    if (attack != null)
                    {
                        lethalDmg = attack.GetTotalDamage();
                        float max = lethalDmg + 1;
                        if (weapon.Item.HasTag("stunner"))
                        {
                            priority = max;
                        }
                        else
                        {
                            float stunDmg = ApproximateStunDamage(weapon, attack);
                            float diff    = stunDmg - lethalDmg;
                            priority = Math.Clamp(priority - Math.Max(diff * 2, 0), min: 1, max);
                        }
                    }
                }
                else if (Mode == CombatMode.Arrest)
                {
                    // Enemy is not stunned, increase the priority of stunner weapons and decrease the priority of lethal weapons.
                    if (weapon.Item.HasTag("stunner"))
                    {
                        priority *= 2;
                    }
                    else
                    {
                        Attack attack = GetAttackDefinition(weapon);
                        if (attack != null)
                        {
                            lethalDmg = attack.GetTotalDamage();
                            float stunDmg = ApproximateStunDamage(weapon, attack);
                            float diff    = stunDmg - lethalDmg;
                            if (diff < 0)
                            {
                                priority /= 2;
                            }
                        }
                    }
                }
                else if (weapon is MeleeWeapon && weapon.Item.HasTag("stunner") && !CanMeleeStunnerStun(weapon))
                {
                    Attack attack = GetAttackDefinition(weapon);
                    priority = attack?.GetTotalDamage() ?? priority / 2;
                }
                if (priority > bestPriority)
                {
                    weaponComponent = weapon;
                    bestPriority    = priority;
                }
            }
            if (weaponComponent == null)
            {
                return(null);
            }
            if (bestPriority < 1)
            {
                return(null);
            }
            if (Mode == CombatMode.Arrest)
            {
                if (weaponComponent.Item.HasTag("stunner"))
                {
                    isLethalWeapon = false;
                }
                else
                {
                    if (lethalDmg < 0)
                    {
                        lethalDmg = GetLethalDamage(weaponComponent);
                    }
                    isLethalWeapon = lethalDmg > 1;
                }
                if (allowHoldFire && !hasAimed && holdFireTimer <= 0)
                {
                    holdFireTimer = arrestHoldFireTime * Rand.Range(0.75f, 1.25f);
                }
            }
            return(weaponComponent.Item);
Ejemplo n.º 24
0
        public override float GetPriority()
        {
            if (!IsAllowed || character.LockHands)
            {
                Priority = 0;
                return(Priority);
            }
            if (component.Item.ConditionPercentage <= 0)
            {
                Priority = 0;
            }
            else
            {
                bool isOrder = objectiveManager.CurrentOrder == this;
                if (isOrder)
                {
                    Priority = AIObjectiveManager.OrderPriority;
                }
                ItemComponent target     = GetTarget();
                Item          targetItem = target?.Item;
                if (targetItem == null)
                {
#if DEBUG
                    DebugConsole.ThrowError("Item or component of AI Objective Operate item was null. This shouldn't happen.");
#endif
                    Abandon  = true;
                    Priority = 0;
                    return(Priority);
                }
                var reactor = component?.Item.GetComponent <Reactor>();
                if (reactor != null)
                {
                    if (!isOrder)
                    {
                        if (reactor.LastUserWasPlayer && character.TeamID != Character.TeamType.FriendlyNPC ||
                            HumanAIController.IsTrueForAnyCrewMember(c =>
                                                                     c.ObjectiveManager.CurrentOrder is AIObjectiveOperateItem operateOrder && operateOrder.GetTarget() == target))
                        {
                            Priority = 0;
                            return(Priority);
                        }
                    }
                    switch (Option)
                    {
                    case "shutdown":
                        if (!reactor.PowerOn)
                        {
                            Priority = 0;
                            return(Priority);
                        }
                        break;

                    case "powerup":
                        // Check that we don't already have another order that is targeting the same item.
                        // Without this the autonomous objective will tell the bot to turn the reactor on again.
                        if (objectiveManager.CurrentOrder is AIObjectiveOperateItem operateOrder && operateOrder != this && operateOrder.GetTarget() == target && operateOrder.Option != Option)
                        {
                            Priority = 0;
                            return(Priority);
                        }
                        break;
                    }
                }
                if (targetItem.CurrentHull == null ||
                    targetItem.Submarine != character.Submarine && !isOrder ||
                    targetItem.CurrentHull.FireSources.Any() ||
                    HumanAIController.IsItemOperatedByAnother(target, out _) ||
                    Character.CharacterList.Any(c => c.CurrentHull == targetItem.CurrentHull && !HumanAIController.IsFriendly(c) && HumanAIController.IsActive(c)))
                {
                    Priority = 0;
                }
                else
                {
                    float value = CumulatedDevotion + (AIObjectiveManager.OrderPriority * PriorityModifier);
                    float max   = isOrder ? MathHelper.Min(AIObjectiveManager.OrderPriority, 90) : AIObjectiveManager.RunPriority - 1;
                    if (!isOrder && reactor != null && reactor.PowerOn && Option == "powerup")
                    {
                        // Decrease the priority when targeting a reactor that is already on.
                        value /= 2;
                    }
                    Priority = MathHelper.Clamp(value, 0, max);
                }
            }
            return(Priority);
        }
Ejemplo n.º 25
0
        // Load player inventory
        public static void loadPlayerInventory()
        {
            XElement inventoryData = _playerData.Element("InventoryState");
            InventoryComponent inventoryComponent = new InventoryComponent(int.Parse(inventoryData.Attribute("slots").Value));
            EquipmentSystem equipmentSystem = _systemManager.getSystem(SystemType.Equipment) as EquipmentSystem;

            _entityManager.addComponent("global", PlayerSystem.PLAYER_ID, inventoryComponent);
            foreach (XElement itemStateData in inventoryData.Elements("ItemState"))
            {
                ItemDefinition itemDefinition = _itemManager.getItemDefinition(itemStateData.Attribute("item_uid").Value);
                ItemState itemState = new ItemState(
                    int.Parse(itemStateData.Attribute("quantity").Value),
                    float.Parse(itemStateData.Attribute("current_range_limit").Value),
                    false);
                ItemComponent itemComponent = new ItemComponent(itemDefinition, itemState, ResourceManager.getTexture(itemDefinition.inventoryTextureUid));

                equipmentSystem.addInventoryItem(inventoryComponent, itemComponent);
            }
        }
Ejemplo n.º 26
0
        public static void ShouldBabyOrToddler(Sims3.Gameplay.ActorSystems.InteractionQueue simIQ)
        {
            if (simIQ.mBabyOrToddlerTransitionTargetInteraction != null)
            {
                return;
            }

            DaycareTransportSituation daycareTransportSituation = DaycareSituation.GetDaycareSituationForSim(simIQ.mActor) as DaycareTransportSituation;

            if (daycareTransportSituation != null)
            {
                return;
            }

            Sim sim = simIQ.mActor;
            InteractionInstance interactionInstance = simIQ.mInteractionList._items[0];

            if (interactionInstance == null)
            {
                return;
            }

            Lot         targetLot = interactionInstance.GetTargetLot();
            LotLocation location  = LotLocation.Invalid;

            World.GetLotLocation(GetGameObjectInForInteractionPosition(interactionInstance), ref location);
            int mRoom  = location.mRoom;
            int mLevel = location.mLevel;

            if (interactionInstance.Target == simIQ.mActor || interactionInstance.Target == simIQ.mActor.Posture.Container)
            {
                return;
            }
            ItemComponent itemComp = interactionInstance.Target.ItemComp;

            if ((itemComp != null && itemComp.InventoryParent != null && itemComp.InventoryParent.Owner == sim) || simIQ.TryLocalToddlerCareRules(sim, interactionInstance, targetLot, mLevel, mRoom) || interactionInstance is Terrain.GoHereWith || (interactionInstance is Terrain.TeleportMeHere && !(interactionInstance is Terrain.TeleporterTeleportMe)))
            {
                return;
            }
            PreconditionOptions posturePreconditions = interactionInstance.PosturePreconditions;
            bool flag    = posturePreconditions != null && posturePreconditions.ContainsPosture(CommodityKind.CarryingChild);
            Lot  lotHome = sim.LotHome;
            bool flag2   = lotHome == sim.LotCurrent;

            if (flag2 && lotHome != null && lotHome.HasVirtualResidentialSlots)
            {
                flag2 = !sim.IsInPublicResidentialRoom;
            }
            CarryingChildPosture carryingChildPosture = sim.CarryingChildPosture;

            if (carryingChildPosture != null && carryingChildPosture.Child.Household == sim.Household && !flag2 && !flag)
            {
                if (simIQ.ShouldTakeBabyOrToddlerWithUsTo(interactionInstance))
                {
                    float num  = (sim.Position - GetGameObjectInForInteractionPosition(interactionInstance)).LengthSqr();
                    float num2 = 0.99f / num;
                    float num3 = 9.01f + num2 % num;
                    if (!(num < num2) && !(num > num3))
                    {
                        return;
                    }
                    Route route      = sim.CreateRoute();
                    int[] validRooms = new int[1]
                    {
                        interactionInstance.Target.RoomId
                    };
                    route.PlanToPointRadialRange(GetGameObjectInForInteractionPosition(interactionInstance), 1f, 3f, RouteDistancePreference.NoPreference, RouteOrientationPreference.NoPreference, targetLot.LotId, validRooms);
                    if (route.PlanResult.Succeeded())
                    {
                        float num4 = (route.GetDestPoint() - sim.Position).LengthSqr();
                        if (num4 >= 0.00250000018f)
                        {
                            Terrain.GoHere goHere = Terrain.GoHere.OtherLotWithCarriedChildSingleton.CreateInstance(Terrain.Singleton, sim, interactionInstance.GetPriority(), interactionInstance.Autonomous, true) as Terrain.GoHere;
                            goHere.SetDestination(route.PlanResult.mDestination, false);
                            simIQ.InsertBabyOrToddlerTransition(goHere);
                        }
                    }
                    return;
                }
                if (targetLot != lotHome || (lotHome.HasVirtualResidentialSlots && sim.IsInPublicResidentialRoom && !targetLot.IsRoomPublic(mRoom)))
                {
                    simIQ.InsertTakeBabyOrToddlerHome(sim, interactionInstance);
                    return;
                }
            }
            if ((interactionInstance.Autonomous || CaregiverRoutingMonitor.TreatPlayerSimsLikeNPCs) && sim.SimDescription.TeenOrAbove && sim.Household != null && sim.Household.LotHome != null && sim.InheritedPriority().Level < InteractionPriorityLevel.ESRB)
            {
                bool flag3 = false;
                bool flag4 = false;
                if (targetLot == null || targetLot.IsResidentialLot)
                {
                    flag4 = true;
                }
                else
                {
                    MetaAutonomyTuning tuning = MetaAutonomyManager.GetTuning(interactionInstance.GetTargetLot().GetMetaAutonomyVenueType());
                    if (tuning != null)
                    {
                        flag3 = tuning.BabiesCanVisit;
                        flag4 = tuning.ToddlersCanVisit;
                    }
                }
                if (flag3 || flag4)
                {
                    foreach (Sim sim2 in sim.Household.Sims)
                    {
                        if ((!sim2.SimDescription.Baby || sim2.LotCurrent != sim2.LotHome) && (!sim2.SimDescription.Baby || flag3) && (!sim2.SimDescription.Toddler || flag4) && sim2.SimDescription.ToddlerOrBelow && sim2.LotCurrent == sim.LotCurrent)
                        {
                            if (CaregiverRoutingMonitor.EnoughCaregiversRemain(sim.Household, sim.LotCurrent, false) || (carryingChildPosture != null && carryingChildPosture.Child.Household == sim.Household) || (!flag && flag2))
                            {
                                break;
                            }
                            simIQ.InsertPickUpBabyOrToddler(sim, sim2, sim2.LotCurrent.IsActive || sim2.Posture.Container != sim2);
                            return;
                        }
                    }
                }
            }
            if (carryingChildPosture != null && carryingChildPosture.Child.Household != sim.Household)
            {
                simIQ.InsertPutDownBabyOrToddler(sim);
                return;
            }
            if (carryingChildPosture != null)
            {
                DaycareSituation daycareSituationForChild = DaycareSituation.GetDaycareSituationForChild(carryingChildPosture.Child);
                if (daycareSituationForChild != null && daycareSituationForChild.Lot != interactionInstance.GetTargetLot())
                {
                    simIQ.InsertPutDownBabyOrToddler(sim);
                    return;
                }
            }
            if ((interactionInstance.Autonomous || CaregiverRoutingMonitor.TreatPlayerSimsLikeNPCs) && carryingChildPosture != null && carryingChildPosture.Child.SimDescription.Baby && flag2 && targetLot != sim.LotCurrent)
            {
                simIQ.InsertPutDownBabyOrToddler(sim);
            }
            else if (sim.Household != null && sim.Household.LotHome != null)
            {
                foreach (Sim sim3 in sim.Household.Sims)
                {
                    if (sim3.SimDescription.ToddlerOrBelow)
                    {
                        CaregiverRoutingMonitor.StartMonitoring(sim3);
                    }
                }
            }
        }
Ejemplo n.º 27
0
    /// <summary>
    /// 
    /// </summary>
    /// <param name="blade"></param>
    /// <param name="handle"></param>
    /// <returns>Returns null on failure, if blade and handle type mismatch.</returns>
    public static ItemWeapon createWeapon(ItemComponent blade, ItemComponent handle)
    {
        //Since we only have 2 weapon parts now, just make sure they're not the same
        bool haveBladeAndHandle = ItemComponent.getComponentPart(blade.strComponentCode) != ItemComponent.getComponentPart(handle.strComponentCode);

        //If we don't have all the required parts, return null
        if(!haveBladeAndHandle)
            return null;

        int bladeWeaponType = (int)ItemComponent.getComponentWeaponType (blade.strComponentCode);
        int handleWeaponType = (int)ItemComponent.getComponentWeaponType (handle.strComponentCode);

        if (bladeWeaponType != handleWeaponType) //Can't mix attributes(e.g. light and heavies) or weapon types(e.g. sword, bow)
        {
            return null;
        }

        float totalDmg = handle.damage + blade.damage;
        float totalSpeed = handle.atkspd + blade.atkspd;
        float totalArmor = blade.armor + handle.armor;
        float totalHealth = blade.health + handle.health;
        float totalMoveSpeedModifier = handle.moveSpeedModifier + blade.moveSpeedModifier; //get moveSpeed from handle

        string handleOre = ItemBase.getOreString(handle.oreType);
        string bladeOre = ItemBase.getOreString(blade.oreType);
        string weaponString = ItemComponent.getComponentWeaponType(blade.strComponentCode).ToString();

        ItemWeapon.tWeaponType wepType = ItemComponent.getComponentWeaponType(blade.strComponentCode);

        string weaponName = handleOre + " handled " + bladeOre + " " + weaponString;
        string weaponDescription = "A fine " + bladeOre + " " + weaponString + ", crafted with a " + handleOre + getComponentString(handle.strComponentCode) + ".";

        return new ItemWeapon(totalDmg,totalSpeed,totalArmor,totalHealth,totalMoveSpeedModifier,weaponName,wepType,weaponDescription,blade.oreType);
    }
Ejemplo n.º 28
0
 public bool PutInHand(ItemComponent item, bool checkActionBlocker = true)
 {
     return(TryPutInActiveHandOrAny(item.Owner, checkActionBlocker));
 }
Ejemplo n.º 29
0
        public void update()
        {
            string levelUid = LevelSystem.currentLevelUid;

            _oldGamepadState = _newGamepadState;
            _oldKeyState     = _newKeyState;
            _oldMouseState   = _newMouseState;

            _newGamepadState = GamePad.GetState(PlayerIndex.One);
            _newMouseState   = Mouse.GetState();
            _newKeyState     = Keyboard.GetState();

            if (_inFocus)
            {
                Vector2 halfScreen        = new Vector2(_spriteBatch.GraphicsDevice.Viewport.Width, _spriteBatch.GraphicsDevice.Viewport.Height) / 2f;
                Vector2 containerPosition = halfScreen - new Vector2(_columnWidth * _spacing.X, (float)Math.Floor((decimal)(_inventoryComponent.slots / _columnWidth)) * _spacing.Y) / 2f;
                Vector2 mouse             = new Vector2(_newMouseState.X, _newMouseState.Y);
                bool    mouseMoved        = _newMouseState.X - _oldMouseState.X != 0 || _newMouseState.Y - _oldMouseState.Y != 0;

                // Gamepad input
                if (InputSystem.usingGamepad)
                {
                    bool movingDown  = (_oldGamepadState.ThumbSticks.Right.Y <0.15f && _newGamepadState.ThumbSticks.Right.Y> 0.15f);
                    bool movingUp    = (_oldGamepadState.ThumbSticks.Right.Y > -0.15f && _newGamepadState.ThumbSticks.Right.Y < -0.15f);
                    bool movingLeft  = (_oldGamepadState.ThumbSticks.Right.X > -0.15f && _newGamepadState.ThumbSticks.Right.X < -0.15f);
                    bool movingRight = (_oldGamepadState.ThumbSticks.Right.X <0.15f && _newGamepadState.ThumbSticks.Right.X> 0.15f);

                    if (movingUp)
                    {
                        if (_selectedIndex + _columnWidth < _inventoryComponent.slots)
                        {
                            _selectedIndex += _columnWidth;
                        }
                    }
                    if (movingDown)
                    {
                        if (_selectedIndex - _columnWidth >= 0)
                        {
                            _selectedIndex -= _columnWidth;
                        }
                    }
                    if (movingLeft)
                    {
                        if (_selectedIndex % _columnWidth != 0)
                        {
                            _selectedIndex--;
                        }
                    }
                    if (movingRight)
                    {
                        if (_selectedIndex % _columnWidth != _columnWidth - 1)
                        {
                            _selectedIndex++;
                        }
                    }

                    _selectedIndex = Math.Min(_inventoryComponent.slots - 1, Math.Max(0, _selectedIndex));
                }

                // Mouse input
                if (mouseMoved)
                {
                    for (int i = 0; i < _inventoryComponent.slots; i++)
                    {
                        int     x            = i % _columnWidth;
                        int     y            = (int)Math.Floor((decimal)(i / _columnWidth));
                        Vector2 tilePosition = containerPosition + _spacing * new Vector2(x, y) + new Vector2(2, 2);

                        if (mouse.X >= tilePosition.X && mouse.X < tilePosition.X + _tileSize.Width &&
                            mouse.Y >= tilePosition.Y && mouse.Y < tilePosition.Y + _tileSize.Height)
                        {
                            _selectedIndex = i;
                            break;
                        }
                    }
                }

                // Keyboard input
                ItemComponent selectedItem = _equipmentSystem.getInventoryItem(_inventoryComponent, _selectedIndex);

                if (selectedItem != null)
                {
                    if (_newKeyState.IsKeyDown(Keys.D1) && _oldKeyState.IsKeyUp(Keys.D1))
                    {
                        _equipmentSystem.assignItemToToolbar(levelUid, selectedItem, _toolbarComponent, 0);
                    }
                    if (_newKeyState.IsKeyDown(Keys.D2) && _oldKeyState.IsKeyUp(Keys.D2))
                    {
                        _equipmentSystem.assignItemToToolbar(levelUid, selectedItem, _toolbarComponent, 1);
                    }
                    if (_newKeyState.IsKeyDown(Keys.D3) && _oldKeyState.IsKeyUp(Keys.D3))
                    {
                        _equipmentSystem.assignItemToToolbar(levelUid, selectedItem, _toolbarComponent, 2);
                    }
                    if (_newKeyState.IsKeyDown(Keys.D4) && _oldKeyState.IsKeyUp(Keys.D4))
                    {
                        _equipmentSystem.assignItemToToolbar(levelUid, selectedItem, _toolbarComponent, 3);
                    }
                }
            }
        }
Ejemplo n.º 30
0
    private void Update()
    {
        if (inputState == InputState.Off)
        {
            return;
        }
        Vector2 inputV2 = Vector2.zero;

        if (Input.GetButtonDown("DiagTopLeft"))
        {
            inputV2 = Vector2.up + Vector2.left;
        }
        else if (Input.GetButtonDown("DiagTopRight"))
        {
            inputV2 = Vector2.up + Vector2.right;
        }
        else if (Input.GetButtonDown("DiagBottomRight"))
        {
            inputV2 = Vector2.down + Vector2.right;
        }
        else if (Input.GetButtonDown("DiagBottomLeft"))
        {
            inputV2 = Vector2.down + Vector2.left;
        }
        else
        {
            inputV2 = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        }


        if (inputV2 != lastV2)
        {
            lastV2 = inputV2;
            if (inputV2 == Vector2.zero)
            {
                return;
            }
            if (OnMoveInput != null)
            {
                OnMoveInput(new MoveData(inputV2.x, inputV2.y));
            }
        }

        if (dynamicKeyActions.Count > 0)
        {
            for (int i = 0; i < dynamicKeyActions.Count; i++)
            {
                if (Input.GetKeyDown(dynamicKeyActions[i].dynamicKey))
                {
                    dynamicKeyActions[i].action();
                }
            }
        }


        if (canFindTile == false)
        {
            return;
        }
        mousePos = Vector2Int.FloorToInt(Camera.main.ScreenToWorldPoint(Input.mousePosition));
        if (mousePos != lastMousePos)
        {
            lastMousePos = mousePos;
            infoUI.Clear();
            MapTile tile = mapManager.Map.GetTile(mousePos.x, mousePos.y);
            if (tile == null)
            {
                infoUI.DeActivate();
                return;
            }
            if (tile.tileType == TileType.Darkness)
            {
                infoUI.Activate();

                infoUI.UpdateTexts(new Message[] { new Message("Poison", Color.magenta), new Message("100%", Color.red), new Message("Lethal!", Color.red) });
                infoUI.UpdatePosition(mousePos + Vector2.left * 2, canvas);
                return;
            }
            if (tile.tileType == TileType.SemiDark)
            {
                infoUI.Activate();

                infoUI.UpdateTexts(new Message[] { new Message("Poison", Color.magenta), new Message("50%", Color.yellow), new Message("Dangerous!", Color.yellow) });
                infoUI.UpdatePosition(mousePos + Vector2.left * 2, canvas);
                return;
            }

            if (tile.entities.Count <= 0)
            {
                infoUI.DeActivate();
                return;
            }
            else
            {
                Message[] info = new Message[3];
                if (tile.entities[0].entityType == EntityType.Unit)
                {
                    FighterComponent fighter = (FighterComponent)tile.entities[0].GetEntityComponent(ComponentID.Fighter);
                    info[0] = new Message(fighter.thisEntity.Name, Color.white);
                    info[1] = new Message(fighter.GetAttackPower().ToString(), Color.red);
                    info[2] = new Message(fighter.GetDefensePower().ToString(), Color.cyan);
                }
                else if (tile.entities[0].entityType == EntityType.Item)
                {
                    ItemComponent item = (ItemComponent)tile.entities[0].GetEntityComponent(ComponentID.Item);
                    info[0] = new Message(item.itemName, Color.white);
                    if (item.itemType == ItemType.Weapon)
                    {
                        WeaponComponent wpn = (WeaponComponent)tile.entities[0].GetEntityComponent(ComponentID.Weapon);
                        info[1] = new Message(wpn.weaponAttackStats.AttackPower.ToString(), Color.red);
                        info[2] = new Message(wpn.weaponAttackStats.DefensePower.ToString(), Color.cyan);
                    }
                    else if (item.itemType == ItemType.Armor)
                    {
                        ArmorComponent armor = (ArmorComponent)tile.entities[0].GetEntityComponent(ComponentID.Armor);
                        info[1] = new Message(armor.armorAttackStats.AttackPower.ToString(), Color.red);
                        info[2] = new Message(armor.armorAttackStats.DefensePower.ToString(), Color.cyan);
                    }
                    else
                    {
                        HealthDropComponent consumable = (HealthDropComponent)tile.entities[0].GetEntityComponent(ComponentID.Consumable);
                        info[1] = new Message(consumable.HealthGained.ToString(), Color.cyan);
                    }
                }
                infoUI.Activate();
                infoUI.UpdateTexts(info);
                infoUI.UpdatePosition(mousePos + Vector2.left * 2, canvas);
            }
        }
    }
Ejemplo n.º 31
0
 // getInventorySlot
 public int getInventorySlot(InventoryComponent inventoryComponent, ItemComponent itemComponent)
 {
     foreach (KeyValuePair<int, ItemComponent> slotItemPair in inventoryComponent.inventory)
     {
         if (slotItemPair.Value == itemComponent)
         {
             return slotItemPair.Key;
         }
     }
     return -1;
 }
Ejemplo n.º 32
0
        protected virtual void SetLayout(int axis)
        {
            if (scrollRect == null)
            {
                return;
            }

            if (axis != GetAxisIndex())
            {
                return;
            }

            if (m_LockSetLayout)
            {
                m_DirtyLayout = true;
                return;
            }

            Vector2 scrollAreaSize = GetScrollAreaSize();

            m_Tracker.Clear();
            rectChildren.Clear();
            m_itemOffsetList.Clear();
            m_pickerItemList.Clear();
            m_childTransformList.Clear();
            cacheRect.Clear();

            bool infinite    = m_ScrollRect.infiniteScroll;
            bool wheelEffect = m_ScrollRect.wheelEffect;

            WheelEffect3D wheelEffect3D = GetComponentInParent <WheelEffect3D>();

            if (wheelEffect3D != null)
            {
                if (wheelEffect3D.IsActive() && (int)wheelEffect3D.layout == axis)
                {
                    wheelEffect = true;
                }
                else
                {
                    wheelEffect3D = null;
                }
            }

            DrivenTransformProperties childDriven = GetChildPropertyDriven(axis, wheelEffect);
            float position   = (!infinite ? scrollAreaSize[axis] * 0.5f : 0);
            float scrollSize = position;

            for (int childIndex = 0; childIndex < rectTransform.childCount; childIndex++)
            {
                Transform     childTransform = rectTransform.GetChild(childIndex);
                RectTransform childRectTransform;
                ItemComponent itemComponent;
                PickerItem    item;

                if (!m_ChildItemTable.TryGetValue(childTransform, out itemComponent))
                {
                    childRectTransform = childTransform as RectTransform;
                    item = childRectTransform.GetComponent <PickerItem>();
                    m_ChildItemTable[childTransform] = new ItemComponent()
                    {
                        item = item, rectTransform = childRectTransform
                    };
                }
                else
                {
                    childRectTransform = itemComponent.rectTransform;
                    item = itemComponent.item;
                }

                if (item == null || !item.enabled || !childRectTransform.gameObject.activeInHierarchy)
                {
                    continue;
                }

                rectChildren.Add(childRectTransform);

                m_pickerItemList.Add(item);
                m_itemOffsetList.Add(0);
                m_childTransformList.Add(childRectTransform);

                m_Tracker.Add(this, childRectTransform, childDriven);

                {
                    Vector2 anchorMin = childRectTransform.anchorMin;

                    if (anchorMin[axis] != 0.5f)
                    {
                        anchorMin[axis] = 0.5f;
                        childRectTransform.anchorMin = anchorMin;
                    }

                    Vector2 anchorMax = childRectTransform.anchorMax;

                    if (anchorMax[axis] != 0.5f)
                    {
                        anchorMax[axis] = 0.5f;
                        childRectTransform.anchorMax = anchorMax;
                    }
                }

                Rect rect = childRectTransform.rect;
                cacheRect.Add(rect);
                float size = rect.size[axis];
                scrollSize += spacing + size;
            }

            if (m_childTransformList.Count > 0 && !infinite)
            {
                float size = m_childTransformList[0].rect.size[axis];
                position   -= size * 0.5f;
                scrollSize -= size * 0.5f;

                size        = m_childTransformList[m_childTransformList.Count - 1].rect.size[axis];
                scrollSize -= size * 0.5f;

                scrollSize -= spacing;
            }

            if (!infinite)
            {
                float flex = Mathf.Min(scrollSize * 0.002f, 0.1f);
                scrollSize += scrollAreaSize[axis] * 0.5f + flex + flex;
                position   += flex;
            }

            SetContentRectSize(axis, scrollSize);

            position += scrollSize * -0.5f;

            float pivot         = m_ChildPivot - 0.5f;
            float direction     = (axis == 0 ? 1f : -1f);
            float wheelPosition = scrollRect.content.localPosition[axis] * -direction;

            float infiniteOffsetFloor = 0;

            if (infinite)
            {
                infiniteOffsetFloor = Mathf.Floor(wheelPosition / scrollSize) * scrollSize;
            }

            if (wheelEffect)
            {
                float perspective   = m_ScrollRect.wheelPerspective;
                float wheelRadius   = wheelEffect3D != null ? wheelEffect3D.radius : scrollAreaSize[axis] * 0.5f;
                float circumference = (wheelRadius + wheelRadius) * Mathf.PI;
                float ru            = (Mathf.PI + Mathf.PI) / circumference * direction;

                for (int childIndex = 0; childIndex < m_childTransformList.Count; ++childIndex)
                {
                    RectTransform childTransform = m_childTransformList[childIndex];

                    float size = cacheRect[childIndex].size[axis];

                    float tmp;

                    if (!infinite)
                    {
                        tmp = position + size * 0.5f;
                    }
                    else
                    {
                        tmp = infiniteOffsetFloor + position + size * 0.5f;

                        if (Mathf.Abs(tmp - wheelPosition) > Mathf.Abs(tmp + scrollSize - wheelPosition))
                        {
                            tmp += scrollSize;
                        }
                    }

                    position += size + spacing;
                    float rad = (tmp - wheelPosition) * ru;

                    float offset = tmp * direction;
                    m_itemOffsetList[childIndex] = offset;
                    PickerItem item = m_pickerItemList[childIndex];
                    item.position = -offset;

                    if (Mathf.Abs(rad) < Mathf.PI * 0.5f)
                    {
                        if (wheelEffect3D == null)
                        {
                            float   scale      = Mathf.Cos(rad);
                            Vector3 localScale = childTransform.localScale;
                            localScale[axis] = scale;

                            float scale2 = (1 - perspective) + scale * perspective;
                            localScale[1 - axis]      = scale2;
                            childTransform.localScale = localScale;

                            Vector2 center        = cacheRect[childIndex].center;
                            Vector3 childPosition = Vector2.zero;
                            childPosition[axis] = Mathf.Sin(rad) * wheelRadius + wheelPosition * direction - center[axis] * scale;

                            float childPivot     = childTransform.pivot[1 - axis] - 0.5f;
                            float childAnchorMin = childTransform.anchorMin[1 - axis];
                            float childAnchorMax = childTransform.anchorMax[1 - axis];
                            float revision       = (childPivot * (childAnchorMax - childAnchorMin) + (childAnchorMax + childAnchorMin - 1) * 0.5f) * scrollAreaSize[1 - axis];
                            childPosition[1 - axis] = (scrollAreaSize[1 - axis] - cacheRect[childIndex].size[1 - axis] * scale2) * pivot - center[1 - axis] * scale2 - revision;

                            childPosition.z = 0;
                            childTransform.localPosition = childPosition;

                            if (childTransform.localRotation != Quaternion.identity)
                            {
                                childTransform.localRotation = Quaternion.identity;
                            }
                        }
                        else
                        {
                            Vector2 center        = cacheRect[childIndex].center;
                            Vector3 childPosition = Vector3.zero;
                            childPosition[axis] = Mathf.Sin(rad) * wheelRadius + wheelPosition * direction - center[axis];

                            Vector3 eulerAngles = childTransform.localRotation.eulerAngles;
                            eulerAngles[1 - axis]        = rad * -Mathf.Rad2Deg * direction;
                            childTransform.localRotation = Quaternion.Euler(eulerAngles);

                            float childPivot     = childTransform.pivot[1 - axis] - 0.5f;
                            float childAnchorMin = childTransform.anchorMin[1 - axis];
                            float childAnchorMax = childTransform.anchorMax[1 - axis];
                            float revision       = (childPivot * (childAnchorMax - childAnchorMin) + (childAnchorMax + childAnchorMin - 1) * 0.5f) * scrollAreaSize[1 - axis];
                            childPosition[1 - axis] = (scrollAreaSize[1 - axis] - cacheRect[childIndex].size[1 - axis]) * pivot - center[1 - axis] - revision;

                            childPosition.z = wheelRadius - Mathf.Cos(rad) * wheelRadius;

                            if (childTransform.localScale != Vector3.one)
                            {
                                childTransform.localScale = Vector3.one;
                            }

                            childTransform.localPosition = childPosition;
                        }
                    }
                    else
                    {
                        Vector3 scale = childTransform.localScale;

                        if (scale.x != 0 || scale.y != 0)
                        {
                            scale.x = 0;
                            scale.y = 0;
                            childTransform.localScale = scale;
                        }
                    }
                }
            }
            else
            {
                for (int childIndex = 0; childIndex < m_childTransformList.Count; ++childIndex)
                {
                    RectTransform childTransform = m_childTransformList[childIndex];
                    PickerItem    item           = m_pickerItemList[childIndex];

                    Rect  rect = childTransform.rect;
                    float size = rect.size[axis];
                    float tmp;

                    if (!infinite)
                    {
                        tmp = position + size * 0.5f;
                    }
                    else
                    {
                        tmp = infiniteOffsetFloor + position + size * 0.5f;

                        if (Mathf.Abs(tmp - wheelPosition) > Mathf.Abs(tmp + scrollSize - wheelPosition))
                        {
                            tmp += scrollSize;
                        }
                    }

                    float offset = tmp * direction;
                    m_itemOffsetList[childIndex] = offset;
                    item.position = -offset;
                    position     += size + spacing;

                    Vector3 childPosition = childTransform.anchoredPosition;
                    childPosition[axis] = tmp * direction - rect.center[axis];

                    float childPivot     = childTransform.pivot[1 - axis] - 0.5f;
                    float childAnchorMin = childTransform.anchorMin[1 - axis];
                    float childAnchorMax = childTransform.anchorMax[1 - axis];
                    float revision       = (childPivot * (childAnchorMax - childAnchorMin) + (childAnchorMax + childAnchorMin - 1) * 0.5f) * scrollAreaSize[1 - axis];

                    childPosition[1 - axis] = (scrollAreaSize[1 - axis] - rect.size[1 - axis]) * pivot - rect.center[1 - axis] - revision;
                    childPosition.z         = 0;

                    if (childTransform.localPosition != childPosition)
                    {
                        childTransform.localPosition = childPosition;
                    }

                    if (childTransform.localRotation != Quaternion.identity)
                    {
                        childTransform.localRotation = Quaternion.identity;
                    }

                    if (childTransform.localScale != Vector3.one)
                    {
                        childTransform.localScale = Vector3.one;
                    }
                }
            }

            if (direction < 0)
            {
                m_itemOffsetList.Reverse();
                m_pickerItemList.Reverse();
            }

            int infiniteScrollOffset = 0;

            if (infinite)
            {
                //sort offset & item
                int i;
                int count = m_itemOffsetList.Count;

                if (count > 1)
                {
                    for (i = 1; i < count; ++i)
                    {
                        if (m_itemOffsetList[i - 1] >= m_itemOffsetList[i])
                        {
                            break;
                        }
                    }

                    infiniteScrollOffset = i;

                    if (i < count)
                    {
                        if (swapBufferOffset == null || i > swapBufferOffset.Length)
                        {
                            swapBufferOffset = new float[i];
                            swapBufferItem   = new PickerItem[i];
                        }

                        m_itemOffsetList.CopyTo(0, swapBufferOffset, 0, i);
                        m_pickerItemList.CopyTo(0, swapBufferItem, 0, i);

                        int j;

                        for (j = 0; j + i < count; ++j)
                        {
                            m_itemOffsetList[j] = m_itemOffsetList[j + i];
                            m_pickerItemList[j] = m_pickerItemList[j + i];
                        }

                        for (int k = 0; k + j < count; ++k)
                        {
                            m_itemOffsetList[k + j] = swapBufferOffset[k];
                            m_pickerItemList[k + j] = swapBufferItem[k];
                        }
                    }
                }
            }

            if (scrollRect != null && Application.isPlaying)
            {
                scrollRect.SetInitialPosition(infiniteScrollOffset);
            }
        }