Exemple #1
0
        public List <PSItem> GetAllItemsBySubType(ItemSubType subType)
        {
            List <PSItem> psItemList = new List <PSItem>();

            for (int index = 0; index < this.ItemsBelongingToShip.Count; ++index)
            {
                PSItem psItem = this.ItemsBelongingToShip[index];
                if (psItem.ItemDesign.ItemSubType == subType)
                {
                    psItemList.Add(psItem);
                }
            }
            return(psItemList);
        }
Exemple #2
0
        public List <PSItem> GetAllExistingItemsBySubType(ItemSubType subType)
        {
            List <PSItem> psItemList           = new List <PSItem>();
            List <PSItem> itemsBelongingToShip = this.ItemsBelongingToShip;

            for (int index = 0; index < itemsBelongingToShip.Count; ++index)
            {
                PSItem psItem = itemsBelongingToShip[index];
                if (psItem.ItemDesign.ItemSubType == subType && psItem.Quantity > 0)
                {
                    psItemList.Add(psItem);
                }
            }
            return(psItemList);
        }
Exemple #3
0
        public void MultipleEquipmentTest(ItemSubType type, int maxCount)
        {
            var previousAvatarState = _initialState.GetAvatarState(_avatar1Address);
            var maxLevel            = _tableSheets.CharacterLevelSheet.Max(row => row.Value.Level);
            var expRow      = _tableSheets.CharacterLevelSheet[maxLevel];
            var maxLevelExp = expRow.Exp;

            previousAvatarState.level = maxLevel;
            previousAvatarState.exp   = maxLevelExp;

            var weaponRows = _tableSheets
                             .EquipmentItemSheet
                             .Values
                             .Where(r => r.ItemSubType == type)
                             .Take(maxCount + 1);

            var equipments = new List <Guid>();

            foreach (var row in weaponRows)
            {
                var equipment = ItemFactory.CreateItem(
                    _tableSheets.EquipmentItemSheet[row.Id],
                    new TestRandom())
                                as Equipment;

                equipments.Add(equipment.ItemId);
                previousAvatarState.inventory.AddItem(equipment);
            }

            var state = _initialState.SetState(_avatar1Address, previousAvatarState.Serialize());

            var action = new RankingBattle
            {
                avatarAddress      = _avatar1Address,
                enemyAddress       = _avatar2Address,
                weeklyArenaAddress = _weeklyArenaAddress,
                costumeIds         = new List <Guid>(),
                equipmentIds       = equipments,
            };

            Assert.Throws <DuplicateEquipmentException>(() => action.Execute(new ActionContext
            {
                PreviousStates = state,
                Signer         = _agent1Address,
                Random         = new TestRandom(),
                Rehearsal      = false,
            }));
        }
        public bool TryGetSlot(ItemSubType itemSubType, out EquipmentSlot outSlot)
        {
            foreach (var slot in slots)
            {
                if (slot.ItemSubType != itemSubType)
                {
                    continue;
                }

                outSlot = slot;
                return(true);
            }

            outSlot = default;
            return(false);
        }
Exemple #5
0
 public PurchaseInfo(
     Guid orderId,
     Guid tradableId,
     Address agentAddress,
     Address avatarAddress,
     ItemSubType type,
     FungibleAssetValue itemPrice
     )
 {
     OrderId             = orderId;
     SellerAgentAddress  = agentAddress;
     SellerAvatarAddress = avatarAddress;
     ItemSubType         = type;
     TradableId          = tradableId;
     Price = itemPrice;
 }
Exemple #6
0
        public List <PSItem> GetAllAvailableItemsBySubType(ItemSubType subType)
        {
            List <PSItem> psItemList           = new List <PSItem>();
            List <PSItem> itemsBelongingToShip = this.ItemsBelongingToShip;

            for (int index = 0; index < itemsBelongingToShip.Count; ++index)
            {
                PSItem psItem = itemsBelongingToShip[index];
                ItemManagementInterface managementInterface = psItem as ItemManagementInterface;
                if (psItem.ItemDesign.ItemSubType == subType && managementInterface.QuantityAvailable > 0)
                {
                    psItemList.Add(psItem);
                }
            }
            return(psItemList);
        }
Exemple #7
0
        internal override void Export(string table)
        {
            var vals = new List <object>
            {
                Id,
                Name.DBExport(),
                ItemID.DBExport(),
                Mat.DBExport(Item.Materials),
                ItemType.DBExport(Item.ItemTypes),
                ItemSubType.DBExport(Item.ItemSubTypes),
                ItemValue.DBExport()
            };


            Database.ExportWorldItem(table, vals);
        }
Exemple #8
0
        //BASIC CONSTRUCTORS ====================================================================================
        public Item(ItemClass itemClass, ItemType itemType, ItemSubType itemSubType, ItemIcon icon, ItemFeatures itemFeatures,
                    string basicName, string additionalName, int goldValue, double weight, int level)
        {
            this.Class    = itemClass;
            this.Type     = itemType;
            this.SubType  = itemSubType;
            this.Icon     = icon;
            this.Features = itemFeatures;

            this.BasicName      = basicName;
            this.AdditionalName = additionalName;
            this.GoldValue      = goldValue;
            this.Weight         = weight;
            this.Level          = level;
            this.Name           = this.BasicName + this.AdditionalName;

            this.CalculateHash();
        }
Exemple #9
0
        public void ValidateCostumeThrowCostumeSlotUnlockException(ItemSubType type, int level)
        {
            Address avatarAddress = new PrivateKey().ToAddress();
            Address agentAddress  = new PrivateKey().ToAddress();
            var     avatarState   = GetNewAvatarState(avatarAddress, agentAddress);

            avatarState.level = level - 1;

            var row        = _tableSheets.CostumeItemSheet.Values.First(r => r.ItemSubType == type);
            var costume    = ItemFactory.CreateCostume(row, default);
            var costumeIds = new HashSet <int> {
                costume.Id
            };

            avatarState.inventory.AddItem(costume);

            Assert.Throws <CostumeSlotUnlockException>(() => avatarState.ValidateCostume(costumeIds));
        }
Exemple #10
0
 public NonFungibleOrder(Address sellerAgentAddress,
                         Address sellerAvatarAddress,
                         Guid orderId,
                         FungibleAssetValue price,
                         Guid tradableId,
                         long startedBlockIndex,
                         ItemSubType itemSubType
                         ) : base(
         sellerAgentAddress,
         sellerAvatarAddress,
         orderId,
         price,
         tradableId,
         startedBlockIndex,
         itemSubType
         )
 {
 }
Exemple #11
0
        internal override void Export(string table)
        {
            base.Export(table);

            table = GetType().Name;

            var vals = new List <object>
            {
                Id,
                HfId.DBExport(),
                EntityId.DBExport(),
                SiteId.DBExport(),
                SkillAtTime,
                ItemID.DBExport(),
                ItemSubType.DBExport(Item.ItemSubTypes)
            };

            Database.ExportWorldItem(table, vals);
        }
Exemple #12
0
    private int GetPartPosition(ItemSubType part)
    {
        int result = 0;

        if (part == ItemSubType.weapon)
        {
            result = 2;
        }
        else if (part == ItemSubType.helmet)
        {
            result = 1;
        }
        else if (part == ItemSubType.shoulder)
        {
            result = 4;
        }
        else if (part == ItemSubType.belt)
        {
            result = 3;
        }
        else if (part == ItemSubType.armpiece)
        {
            result = 5;
        }
        else if (part == ItemSubType.leggings)
        {
            result = 6;
        }
        else if (part == ItemSubType.necklace)
        {
            result = 7;
        }
        else if (part == ItemSubType.ring)
        {
            result = 8;
        }
        else
        {
            result = 0;
        }
        return(result);
    }
Exemple #13
0
        public void UpdateRecipes(ItemSubType type)
        {
            var avatarState = States.Instance.CurrentAvatarState;

            if (avatarState is null)
            {
                return;
            }

            var tableSheets  = Game.Game.instance.TableSheets;
            var equipmentIds = tableSheets.EquipmentItemSheet.Values
                               .Where(r => r.ItemSubType == type)
                               .Select(r => r.Id).ToList();
            var rows = tableSheets.EquipmentItemRecipeSheet.Values
                       .Where(r => equipmentIds.Contains(r.ResultEquipmentId)).ToList();
            var combination = Widget.Find <Combination>();

            combination.LoadRecipeVFXSkipMap();

            for (var index = 0; index < cellViews.Length; index++)
            {
                var cellView = cellViews[index];
                if (index < rows.Count)
                {
                    cellView.Set(rows[index]);
                    var hasNotification = _notificationId == cellView.EquipmentRowData.Id;
                    var isUnlocked      = avatarState.worldInformation
                                          .IsStageCleared(cellView.EquipmentRowData.UnlockStage);
                    var isFirstOpen =
                        !combination.RecipeVFXSkipMap
                        .ContainsKey(cellView.EquipmentRowData.Id) && isUnlocked;

                    cellView.Set(avatarState, hasNotification, isFirstOpen);
                    cellView.Show();
                }
                else
                {
                    cellView.Hide();
                }
            }
        }
Exemple #14
0
    /// <summary>
    /// 卸下功法
    /// </summary>
    public void UnfixGongfa(ItemSubType item_sub_typ, GongfaType gongfa_typ = GongfaType.none)
    {
        switch (item_sub_typ)
        {
        case ItemSubType.Heart:
            for (int i = 0; i < heart_gongfa.Length; i++)
            {
                if (heart_gongfa[i] == null)
                {
                    continue;
                }
                GongfaStaticData equip_gongfa = GetGongfaStaticData(heart_gongfa[i]);
                if (equip_gongfa != null && ((equip_gongfa.type & gongfa_typ) == gongfa_typ))
                {
                    heart_gongfa[i] = null;
                    break;
                }
            }
            break;

        case ItemSubType.Body:
            body_gongfa = null;
            break;

        case ItemSubType.Attack:
            attack_gongfa = null;
            break;

        case ItemSubType.Skill:
            skill_gongfa = null;
            break;

        case ItemSubType.Magic:
            magic_gongfa = null;
            break;
        }
        EventManager.SendEvent(EventTyp.GongfaChange, null);
        UpdateAttr();
    }
Exemple #15
0
    /// <summary>
    /// 创建功法
    /// </summary>
    public static void CreateRandomGongfa(int lv, GongfaType gongfa_typ, int color, List <GongfaStaticData> gongfa_list, List <ItemStaticData> item_list)
    {
        create_id = gongfa_list.Count;
        GongfaStaticData gongfa;
        ItemSubType      sub_type = ItemSubType.Heart;

        if ((gongfa_typ & GongfaType.heart) == GongfaType.heart)
        {
            gongfa = new HeartGongfaStaticData(lv, gongfa_typ, color, create_id);
        }
        else
        {
            gongfa = new SkillGongfaStaticData(lv, gongfa_typ, color, create_id);
            if ((gongfa_typ & GongfaType.attack) == GongfaType.attack)
            {
                sub_type = ItemSubType.Attack;
            }
            else if ((gongfa_typ & GongfaType.body) == GongfaType.body)
            {
                sub_type = ItemSubType.Body;
            }
            else if ((gongfa_typ & GongfaType.skill) == GongfaType.skill)
            {
                sub_type = ItemSubType.Skill;
            }
            else if ((gongfa_typ & GongfaType.magic) == GongfaType.magic)
            {
                sub_type = ItemSubType.Magic;
            }
        }

        if (gongfa != null)
        {
            gongfa_list.Add(gongfa);
            CreateGongfaItem(gongfa, item_list, sub_type);
        }
    }
Exemple #16
0
        internal override void Export(string table)
        {
            base.Export(table);

            table = GetType().Name;

            var vals = new List <object>
            {
                Id,
                EntityId_Attacker.DBExport(),
                EntityId_Defender.DBExport(),
                SiteId.DBExport(),
                Coords.DBExport(),
                ItemID.DBExport(),
                ItemType.DBExport(Item.ItemTypes),
                ItemSubType.DBExport(Item.ItemSubTypes),
                Mat.DBExport(Item.Materials),
                EntityId.DBExport(),
                Hfid.DBExport(),
                StructureId.DBExport()
            };

            Database.ExportWorldItem(table, vals);
        }
Exemple #17
0
 public void OnTypeToggle(Toggle Tog)
 {
     show_pack = (ItemSubType)int.Parse(Tog.name);
     UpdateUI();
 }
Exemple #18
0
    public static void CreateGongfaItem(GongfaStaticData gongfa, List <ItemStaticData> item_list, ItemSubType sub_type)
    {
        StringBuilder des = new StringBuilder();

        if (gongfa is HeartGongfaStaticData)
        {
            HeartGongfaStaticData gf = (HeartGongfaStaticData)gongfa;
            des.AppendFormat("道点消耗:{0}", gf.need_daodian);
        }
        else if (gongfa is SkillGongfaStaticData)
        {
            SkillGongfaStaticData gf = (SkillGongfaStaticData)gongfa;
            des.AppendFormat("技能冷却:{0}", gf.cool);
            des.AppendLine();
            des.AppendFormat("施法消耗:{0}", gf.cost);
        }
        des.AppendLine();
        des.AppendLine("——————————————————");

        bool isSkill = true;

        for (int i = 0; i < gongfa.attr_id.Length; i++)
        {
            var            attr_id        = gongfa.attr_id[i];
            GongfaAttrData main_attr_data = GongfaAttrConfig.GetAttrConfig(attr_id);
            if (!main_attr_data.isSkill && isSkill)
            {
                isSkill = false;
                des.AppendLine("<color=#E28225FF>装备后可获得以下属性</color>");
            }
            if (isSkill)
            {
                des.AppendLine(DesFormat(main_attr_data.des, gongfa.attr_value[i]));
            }
            else
            {
                des.AppendLine(" " + DesFormat(main_attr_data.des, gongfa.attr_value[i]));
            }
        }
        des.AppendLine("——————————————————");
        for (int i = 0; i < gongfa.ex_id.Length; i++)
        {
            GongfaAttrData congfa_attr_data = GongfaAttrConfig.GetAttrConfig(gongfa.ex_id[i]);
            des.AppendFormat(" <size=10>{1}</size>:<color=#{0}>", GameConst.item_color_str[gongfa.ex_color[i]], GameConst.attr_level_name[i]);
            des.Append(DesFormat(congfa_attr_data.des, gongfa.ex_values[i]));
            des.AppendLine("</color>");
        }
        des.AppendLine("——————————————————");
        if (gongfa.attr_condition[0].Length == 1)
        {
            RoleAttrConfig[] attribute_config = RoleAttrConfigData.GetAttrConfig();
            des.AppendFormat("学习条件:{0}达到{1}", attribute_config[(int)gongfa.attr_condition[0][0]].name, gongfa.value_condition[0]);
        }
        else
        {
            des.AppendFormat("任意一项战斗资质达到{0}", gongfa.value_condition[0]);
        }



        int item_static_id = item_list.Count;
        var item           = new ItemStaticData()
        {
            id       = item_static_id,
            type     = ItemType.Gongfa,
            sub_ype  = sub_type,
            price    = gongfa.price,
            maxcount = 1,
            param    = new int[] { gongfa.id },

            name  = gongfa.name,
            icon  = ItemSubType.Magic - sub_type,
            color = gongfa.color,
            level = gongfa.level,

            des         = des.ToString(),
            attributes  = null,
            attr_values = null,
        };

        item_list.Add(item);
    }
Exemple #19
0
 public override IValue Serialize() =>
 Bencodex.Types.Dictionary.Empty
 .Add("item_id", Id)
 .Add("item_sub_type", ItemSubType.ToString())
 .Add("grade", Grade)
 .Add("elemental_type", ElementalType.ToString());
 internal DestinyItemCategoryDefinition(bool deprecated, DestinyDefinitionDisplayProperties displayProperties, DestinyBreakerTypes grantDestinyBreakerType,
                                        DestinyClassType grantDestinyClass, ItemType grantDestinyItemType, ItemSubType grantDestinySubType, bool groupCategoryOnly, uint[] groupedCategoryHashes,
                                        bool isPlug, string itemTypeRegex, uint[] parentCategoryHashes, string shortTitle, bool visible, string plugCategoryIdentifier, string itemTypeRegexNot,
                                        string originBucketIdentifier, string traitId,
                                        bool blacklisted, uint hash, int index, bool redacted)
 {
     Deprecated              = deprecated;
     DisplayProperties       = displayProperties;
     GrantDestinyBreakerType = grantDestinyBreakerType;
     GrantDestinyClass       = grantDestinyClass;
     GrantDestinyItemType    = grantDestinyItemType;
     GrantDestinySubType     = grantDestinySubType;
     GroupCategoryOnly       = groupCategoryOnly;
     GroupedCategories       = groupedCategoryHashes.DefinitionsAsReadOnlyOrEmpty <DestinyItemCategoryDefinition>(DefinitionsEnum.DestinyItemCategoryDefinition);
     IsPlug                 = isPlug;
     ItemTypeRegex          = itemTypeRegex;
     ParentCategories       = parentCategoryHashes.DefinitionsAsReadOnlyOrEmpty <DestinyItemCategoryDefinition>(DefinitionsEnum.DestinyItemCategoryDefinition);
     ShortTitle             = shortTitle;
     Visible                = visible;
     Blacklisted            = blacklisted;
     Hash                   = hash;
     Index                  = index;
     Redacted               = redacted;
     PlugCategoryIdentifier = plugCategoryIdentifier;
     ItemTypeRegexNot       = itemTypeRegexNot;
     OriginBucketIdentifier = originBucketIdentifier;
     TraitId                = traitId;
 }
Exemple #21
0
 protected override void LoadPlainValueInternal(IImmutableDictionary <string, IValue> plainValue)
 {
     productId           = plainValue[ProductIdKey].ToGuid();
     sellerAvatarAddress = plainValue[SellerAvatarAddressKey].ToAddress();
     itemSubType         = plainValue[ItemSubTypeKey].ToEnum <ItemSubType>();
 }
 public void DeriveAddress_Throw_InvalidItemTypeException(ItemSubType itemSubType)
 {
     Assert.Throws <InvalidItemTypeException>(() => ShardedShopStateV2.DeriveAddress(itemSubType, Guid.NewGuid()));
 }
Exemple #23
0
 public ConsumeableItem(int healValue, ItemClass itemClass, ItemType itemType, ItemSubType itemSubType, ItemIcon itemIcon, ItemFeatures itemFeatures,
                        string basicName, string additionalName, int goldValue, double weight)
     : base(itemClass, itemType, itemSubType, itemIcon, itemFeatures, basicName, additionalName, goldValue, weight, 0)
 {
     this.HealValue = healValue;
 }
Exemple #24
0
        private void Awake()
        {
            _eventTrigger = GetComponent <EventTrigger>();
            if (!_eventTrigger)
            {
                throw new NotFoundComponentException <EventTrigger>();
            }

            EventTrigger.Entry entry = new EventTrigger.Entry();
            entry.eventID = EventTriggerType.PointerClick;
            entry.callback.AddListener(OnClick);
            _eventTrigger.triggers.Add(entry);

            RectTransform = GetComponent <RectTransform>();

            switch (ItemSubType)
            {
            case ItemSubType.FullCostume:
                _requireLevel = GameConfig.RequireCharacterLevel.CharacterFullCostumeSlot;
                break;

            case ItemSubType.HairCostume:
                _requireLevel = GameConfig.RequireCharacterLevel.CharacterHairCostumeSlot;
                break;

            case ItemSubType.EarCostume:
                _requireLevel = GameConfig.RequireCharacterLevel.CharacterEarCostumeSlot;
                break;

            case ItemSubType.EyeCostume:
                _requireLevel = GameConfig.RequireCharacterLevel.CharacterEyeCostumeSlot;
                break;

            case ItemSubType.TailCostume:
                _requireLevel = GameConfig.RequireCharacterLevel.CharacterTailCostumeSlot;
                break;

            case ItemSubType.Title:
                _requireLevel = GameConfig.RequireCharacterLevel.CharacterTitleSlot;
                break;

            case ItemSubType.Weapon:
                _requireLevel = GameConfig.RequireCharacterLevel.CharacterEquipmentSlotWeapon;
                break;

            case ItemSubType.Armor:
                _requireLevel = GameConfig.RequireCharacterLevel.CharacterEquipmentSlotArmor;
                break;

            case ItemSubType.Belt:
                _requireLevel = GameConfig.RequireCharacterLevel.CharacterEquipmentSlotBelt;
                break;

            case ItemSubType.Necklace:
                _requireLevel = GameConfig.RequireCharacterLevel.CharacterEquipmentSlotNecklace;
                break;

            case ItemSubType.Ring:
                _requireLevel = ItemSubTypeIndex == 1
                        ? GameConfig.RequireCharacterLevel.CharacterEquipmentSlotRing1
                        : GameConfig.RequireCharacterLevel.CharacterEquipmentSlotRing2;
                break;

            case ItemSubType.Food:
                switch (ItemSubTypeIndex)
                {
                case 1:
                    _requireLevel = GameConfig.RequireCharacterLevel
                                    .CharacterConsumableSlot1;
                    break;

                case 2:
                    _requireLevel = GameConfig.RequireCharacterLevel
                                    .CharacterConsumableSlot2;
                    break;

                case 3:
                    _requireLevel = GameConfig.RequireCharacterLevel
                                    .CharacterConsumableSlot3;
                    break;

                case 4:
                    _requireLevel = GameConfig.RequireCharacterLevel
                                    .CharacterConsumableSlot4;
                    break;

                case 5:
                    _requireLevel = GameConfig.RequireCharacterLevel
                                    .CharacterConsumableSlot5;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            _messageForCat =
                $"{L10nManager.Localize($"ITEM_SUB_TYPE_{ItemSubType.ToString()}")}\n<sprite name=\"UI_icon_lock_01\"> LV.{_requireLevel}";

            gameObject.AddComponent <ObservablePointerEnterTrigger>()
            .OnPointerEnterAsObservable()
            .Subscribe(x =>
            {
                if (!ShowUnlockTooltip || !IsLock)
                {
                    return;
                }

                if (_cat)
                {
                    _cat.Hide();
                }

                _cat = Widget.Find <MessageCatManager>().Show(true, _messageForCat);
            })
            .AddTo(gameObject);

            gameObject.AddComponent <ObservablePointerExitTrigger>()
            .OnPointerExitAsObservable()
            .Subscribe(x =>
            {
                if (!IsLock || !_cat)
                {
                    return;
                }

                _cat.Hide();
                _cat = null;
            })
            .AddTo(gameObject);
        }
Exemple #25
0
        public void Query(
            [Option('v', Description = "Print more logs.")]
            bool verbose,
            [Option('s', Description = "Path to the chain store.")]
            string storePath,
            [Option(
                 'f',
                 Description = "Optional bottom block hash/index to search.  Genesis by default.")]
            string from = null,
            [Option(
                 't',
                 Description = "Optional topmost block hash/index to search.  Tip by default.")]
            string to = null,
            [Option('F', Description = "Include failed transactions too.")]
            bool includeFails = false,
            [Option(
                 'T',
                 Description = "Filter by item type.  This implicitly filters out transactions " +
                               "made with " + nameof(Buy) + " action version prior to " + nameof(Buy5) +
                               ".  This can be applied multiple times (meaning: match any of them).  " +
                               "The list of available types can be found in " + nameof(ItemSubType) +
                               " enum declared in Lib9c/Model/Item/ItemType.cs file.")]
            string[] itemType = null,
            [Option('c', Description = "Optional chain ID.  Default is the canonical chain ID.")]
            Guid?chainId = null
            )
        {
            using Logger logger = Utils.ConfigureLogger(verbose);
            TextWriter stderr = Console.Error;

            (BlockChain <NCAction> chain, IStore store) =
                Utils.GetBlockChain(logger, storePath, chainId);

            HashSet <ItemSubType> itemTypes = null;

            if (itemType is {} t)
            {
                try
                {
                    itemTypes =
                        t.Select(s => ItemSubType.Parse <ItemSubType>(s, ignoreCase: true))
                        .ToHashSet();
                }
                catch (ArgumentException e)
                {
                    throw new CommandExitedException("-T/--item-type: " + e.Message, 1);
                }
            }

            Block <NCAction> start = Utils.ParseBlockOffset(chain, from, defaultIndex: 0);

            stderr.WriteLine("The bottom block to search: #{0} {1}.", start.Index, start.Hash);
            Block <NCAction> end = Utils.ParseBlockOffset(chain, to);

            stderr.WriteLine("The topmost block to search: #{0} {1}.", end.Index, end.Hash);

            Block <NCAction> block = end;
            int indexWidth         = block.Index.ToString().Length + 1;

            Console.WriteLine(
                "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}",
                $"#IDX".PadRight(indexWidth),
                "HASH".PadRight(BlockHash.Size * 2),
                "TIME".PadRight(DateTimeOffset.Now.ToString("o").Length),
                "TXID".PadRight(TxId.Size * 2),
                "BUYER".PadRight(Address.Size * 2),
                "BUYER AVATER".PadRight(Address.Size * 2),
                "SELLER".PadRight(Address.Size * 2),
                "SELLER AVATER".PadRight(Address.Size * 2),
                "QUANTITY",
                "TOTAL PRICE"
                );

            while (true)
            {
                stderr.WriteLine("Scanning block #{0} {1}...", block.Index, block.Hash);
                stderr.Flush();

                IEnumerable <(Transaction <NCAction>, NCAction)> actions = block.Transactions
                                                                           .Reverse()
                                                                           .Where(tx => includeFails ||
                                                                                  !(chain.GetTxExecution(block.Hash, tx.Id) is { } e) ||
                                                                                  e is TxSuccess)
                                                                           .SelectMany(tx => tx.Actions.Reverse().Select(a => (tx, a)));

                foreach (var(tx, act) in actions)
                {
                    ActionBase          a      = act.InnerAction;
                    IEnumerable <Order> orders = act.InnerAction switch
                    {
                        IBuy0 b0 => new Order[]
                        {
                            new Order
                            {
                                BuyerAvatar  = b0.buyerAvatarAddress,
                                Seller       = b0.sellerAgentAddress,
                                SellerAvatar = b0.sellerAvatarAddress,
                            },
                        },
                        IBuy5 b => b.purchaseInfos.Reverse().Select(p => new Order
                        {
                            BuyerAvatar  = b.buyerAvatarAddress,
                            Seller       = p.SellerAgentAddress,
                            SellerAvatar = p.SellerAvatarAddress,
                            Price        = p.Price,
                            ItemSubType  = p.ItemSubType,
                            Quantity     = p.OrderId is {} oid
                                ? chain.GetState(GetOrderAddress(oid)) is Dictionary rawOrder
                                    ? OrderFactory.Deserialize(rawOrder) is FungibleOrder fo
                                        ? fo.ItemCount
                                        : 1
                                    : (int?)null
                                : (int?)null,
                        }),
Exemple #26
0
        public void Execute_20210604(
            long blockIndex,
            ItemSubType itemSubType,
            string agentAddressHex,
            string avatarAddressHex,
            long shopExpiredBlockIndex,
            long expectedBlockIndex,
            int shopItemCount,
            int itemCount,
            int shopPrice,
            int expectedPrice)
        {
            var avatarState         = _initialState.GetAvatarState(_avatarAddress);
            var sellerAgentAddress  = new Address(agentAddressHex);
            var sellerAvatarAddress = new Address(avatarAddressHex);

            ITradableItem tradableItem;

            switch (itemSubType)
            {
            case ItemSubType.Weapon:
                tradableItem = ItemFactory.CreateItemUsable(
                    _tableSheets.EquipmentItemSheet.OrderedList.First(row => row.ItemSubType == ItemSubType.Weapon),
                    Guid.NewGuid(),
                    1);
                break;

            case ItemSubType.Hourglass:
                var tradableMaterialRow = _tableSheets.MaterialItemSheet.OrderedList
                                          .First(row => row.ItemSubType == ItemSubType.Hourglass);
                tradableItem = ItemFactory.CreateTradableMaterial(tradableMaterialRow);
                tradableItem.RequiredBlockIndex = 1;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(itemSubType), itemSubType, null);
            }

            Assert.Equal(1, tradableItem.RequiredBlockIndex);
            avatarState.inventory.AddItem2((ItemBase)tradableItem, itemCount);

            var previousStates = _initialState;

            previousStates = previousStates.SetState(_avatarAddress, avatarState.Serialize());
            var currencyState      = previousStates.GetGoldCurrency();
            var price              = new FungibleAssetValue(currencyState, expectedPrice, 0);
            var productId          = new Guid("6f460c1a755d48e4ad6765d5f519dbc8");
            var shardedShopAddress = ShardedShopState.DeriveAddress(
                tradableItem.ItemSubType,
                productId);

            Assert.Equal(1, tradableItem.RequiredBlockIndex);
            var shopItem = new ShopItem(
                sellerAgentAddress,
                sellerAvatarAddress,
                Guid.NewGuid(),
                new FungibleAssetValue(currencyState, shopPrice, 0),
                shopExpiredBlockIndex,
                tradableItem,
                shopItemCount
                );

            var shardedShopState = new ShardedShopState(shardedShopAddress);

            shardedShopState.Register(shopItem);
            Assert.Single(shardedShopState.Products);
            previousStates = previousStates.SetState(
                shardedShopAddress,
                shardedShopState.Serialize());

            var sellAction = new Sell6
            {
                sellerAvatarAddress = _avatarAddress,
                tradableId          = tradableItem.TradableId,
                count       = itemCount,
                price       = price,
                itemSubType = tradableItem.ItemSubType,
            };
            var nextState = sellAction.Execute(new ActionContext
            {
                BlockIndex     = blockIndex,
                PreviousStates = previousStates,
                Rehearsal      = false,
                Signer         = _agentAddress,
                Random         = new TestRandom(),
            });

            // Check AvatarState and Inventory
            var nextAvatarState = nextState.GetAvatarState(_avatarAddress);

            Assert.Single(nextAvatarState.inventory.Items);
            Assert.True(nextAvatarState.inventory.TryGetTradableItems(
                            tradableItem.TradableId,
                            expectedBlockIndex,
                            itemCount,
                            out var inventoryItems));
            Assert.Single(inventoryItems);
            ITradableItem nextTradableItem = (ITradableItem)inventoryItems.First().item;

            Assert.Equal(expectedBlockIndex, nextTradableItem.RequiredBlockIndex);

            // Check ShardedShopState and ShopItem
            var nextSerializedShardedShopState = nextState.GetState(shardedShopAddress);

            Assert.NotNull(nextSerializedShardedShopState);
            var nextShardedShopState =
                new ShardedShopState((Dictionary)nextSerializedShardedShopState);

            Assert.Equal(2, nextShardedShopState.Products.Count);
            Assert.Single(nextShardedShopState.Products.Values.Where(s => s.Equals(shopItem)));
            Assert.Single(nextShardedShopState.Products.Values.Where(s => !s.Equals(shopItem)));
            ShopItem nextShopItem = nextShardedShopState.Products.Values.First(s => !s.Equals(shopItem));

            ITradableItem innerShopItem = nextShopItem.TradableFungibleItem;
            int           fungibleCount = itemCount;

            if (itemSubType == ItemSubType.Weapon)
            {
                innerShopItem = nextShopItem.ItemUsable;
                fungibleCount = 0;
            }

            Assert.Equal(price, nextShopItem.Price);
            Assert.Equal(expectedBlockIndex, nextShopItem.ExpiredBlockIndex);
            Assert.Equal(_agentAddress, nextShopItem.SellerAgentAddress);
            Assert.Equal(_avatarAddress, nextShopItem.SellerAvatarAddress);
            Assert.Equal(expectedBlockIndex, innerShopItem.RequiredBlockIndex);
            Assert.Equal(fungibleCount, nextShopItem.TradableFungibleItemCount);

            var mailList = nextAvatarState.mailBox.Where(m => m is SellCancelMail).ToList();

            Assert.Single(mailList);
            var mail = mailList.First() as SellCancelMail;

            Assert.NotNull(mail);
            Assert.Equal(expectedBlockIndex, mail.requiredBlockIndex);

            ITradableItem attachmentItem = itemSubType == ItemSubType.Weapon
                ? (ITradableItem)mail.attachment.itemUsable
                : mail.attachment.tradableFungibleItem;

            Assert.Equal(itemSubType == ItemSubType.Weapon, mail.attachment.tradableFungibleItem is null);
            Assert.Equal(fungibleCount, mail.attachment.tradableFungibleItemCount);
            Assert.Equal(nextTradableItem, attachmentItem);
        }
Exemple #27
0
 public override void Set(IReadOnlyList <string> fields)
 {
     base.Set(fields);
     ItemType    = (ItemType)Enum.Parse(typeof(ItemType), fields[3]);
     ItemSubType = (ItemSubType)Enum.Parse(typeof(ItemSubType), fields[4]);
 }
        public static Type GetItemTypeBy(ItemClass itemClass = ItemClass.None, ItemType itemType = ItemType.None, EqType eqType = EqType.None, ItemSubType itemSubType = ItemSubType.None)
        {
            Type resultType = null;

            if (itemClass == ItemClass.None)
            {
                return(resultType);
            }

            switch (itemClass)
            {
            case ItemClass.Magic:
            {
                if (itemType == ItemType.None)
                {
                    return(resultType);
                }

                switch (itemType)
                {
                case ItemType.Armor:
                {
                    if (eqType == EqType.None)
                    {
                        return(resultType);
                    }

                    switch (eqType)
                    {
                    case EqType.Body:
                    {
                        resultType = typeof(ItemIndex.MagicArmor.Body);
                        break;
                    }

                    case EqType.Boots:
                    {
                        resultType = typeof(ItemIndex.MagicArmor.Boots);
                        break;
                    }

                    case EqType.Gloves:
                    {
                        resultType = typeof(ItemIndex.MagicArmor.Gloves);
                        break;
                    }

                    case EqType.Helmet:
                    {
                        resultType = typeof(ItemIndex.MagicArmor.Helmet);
                        break;
                    }

                    case EqType.Shield:
                    {
                        resultType = typeof(ItemIndex.MagicArmor.Shield);
                        break;
                    }
                    }
                    break;
                }

                case ItemType.Weapon:
                {
                    resultType = typeof(ItemIndex.MagicArmor.Weapon);
                    break;
                }

                case ItemType.Trinket:
                {
                    resultType = typeof(ItemIndex.Trinket);
                    break;
                }
                }

                break;
            }

            case ItemClass.Melle:
            {
                if (itemType == ItemType.None)
                {
                    return(resultType);
                }

                switch (itemType)
                {
                case ItemType.Armor:
                {
                    if (eqType == EqType.None)
                    {
                        return(resultType);
                    }

                    switch (eqType)
                    {
                    case EqType.Body:
                    {
                        resultType = typeof(ItemIndex.MelleArmor.Body);
                        break;
                    }

                    case EqType.Boots:
                    {
                        resultType = typeof(ItemIndex.MelleArmor.Boots);
                        break;
                    }

                    case EqType.Gloves:
                    {
                        resultType = typeof(ItemIndex.MelleArmor.Gloves);
                        break;
                    }

                    case EqType.Helmet:
                    {
                        resultType = typeof(ItemIndex.MelleArmor.Helmet);
                        break;
                    }

                    case EqType.Shield:
                    {
                        resultType = typeof(ItemIndex.MelleArmor.Shield);
                        break;
                    }
                    }
                    break;
                }

                case ItemType.Weapon:
                {
                    resultType = typeof(ItemIndex.MelleArmor.Weapon);
                    break;
                }

                case ItemType.Trinket:
                {
                    resultType = typeof(ItemIndex.Trinket);
                    break;
                }
                }

                break;
            }

            case ItemClass.Ranged:
            {
                if (itemType == ItemType.None)
                {
                    return(resultType);
                }

                switch (itemType)
                {
                case ItemType.Armor:
                {
                    if (eqType == EqType.None || eqType == EqType.Shield)
                    {
                        return(resultType);
                    }

                    switch (eqType)
                    {
                    case EqType.Body:
                    {
                        resultType = typeof(ItemIndex.RangedArmor.Body);
                        break;
                    }

                    case EqType.Boots:
                    {
                        resultType = typeof(ItemIndex.RangedArmor.Boots);
                        break;
                    }

                    case EqType.Gloves:
                    {
                        resultType = typeof(ItemIndex.RangedArmor.Gloves);
                        break;
                    }

                    case EqType.Helmet:
                    {
                        resultType = typeof(ItemIndex.RangedArmor.Helmet);
                        break;
                    }
                    }
                    break;
                }

                case ItemType.Weapon:
                {
                    resultType = typeof(ItemIndex.RangedArmor.Weapon);
                    break;
                }

                case ItemType.Trinket:
                {
                    resultType = typeof(ItemIndex.Trinket);
                    break;
                }
                }

                break;
            }

            case ItemClass.Normal:
            {
                if (itemType == ItemType.None)
                {
                    return(resultType);
                }

                switch (itemType)
                {
                case ItemType.Food:
                {
                    resultType = typeof(ItemIndex.Food);
                    break;
                }

                case ItemType.Junk:
                {
                    if (itemSubType == ItemSubType.None)
                    {
                        return(resultType);
                    }

                    switch (itemSubType)
                    {
                    case ItemSubType.Junk_BodyParts:
                    {
                        resultType = typeof(ItemIndex.Junk.BodyParts);
                        break;
                    }

                    case ItemSubType.Junk_Gems:
                    {
                        resultType = typeof(ItemIndex.Junk.Gems);
                        break;
                    }

                    case ItemSubType.Junk_Generic:
                    {
                        resultType = typeof(ItemIndex.Junk.Generic);
                        break;
                    }

                    case ItemSubType.Junk_Gold:
                    {
                        resultType = typeof(ItemIndex.Junk.Gold);
                        break;
                    }

                    case ItemSubType.Junk_Minerals:
                    {
                        resultType = typeof(ItemIndex.Junk.Minerals);
                        break;
                    }
                    }

                    break;
                }

                case ItemType.Potion:
                {
                    if (itemSubType == ItemSubType.None)
                    {
                        return(resultType);
                    }

                    switch (itemSubType)
                    {
                    case ItemSubType.Potion_Dexterity:
                    {
                        resultType = typeof(ItemIndex.Potions.Dexterity);
                        break;
                    }

                    case ItemSubType.Potion_Health:
                    {
                        resultType = typeof(ItemIndex.Potions.Health);
                        break;
                    }

                    case ItemSubType.Potion_Intelligence:
                    {
                        resultType = typeof(ItemIndex.Potions.Intelligence);
                        break;
                    }

                    case ItemSubType.Potion_Mana:
                    {
                        resultType = typeof(ItemIndex.Potions.Mana);
                        break;
                    }

                    case ItemSubType.Potion_Strength:
                    {
                        resultType = typeof(ItemIndex.Potions.Strength);
                        break;
                    }

                    case ItemSubType.Potion_Armor:
                    {
                        resultType = typeof(ItemIndex.Potions.Armor);
                        break;
                    }
                    }

                    break;
                }

                case ItemType.Gold:
                {
                    resultType = typeof(ItemIndex.Gold);
                    break;
                }
                }

                break;
            }
            }

            return(resultType);
        }
Exemple #29
0
        public static Order Create(Address agentAddress, Address avatarAddress, Guid orderId,
                                   FungibleAssetValue price, Guid tradableId, long startedIndex, ItemSubType itemSubType, int count)
        {
            switch (itemSubType)
            {
            case ItemSubType.Food:
            case ItemSubType.FullCostume:
            case ItemSubType.HairCostume:
            case ItemSubType.EarCostume:
            case ItemSubType.EyeCostume:
            case ItemSubType.TailCostume:
            case ItemSubType.Weapon:
            case ItemSubType.Armor:
            case ItemSubType.Belt:
            case ItemSubType.Necklace:
            case ItemSubType.Ring:
            case ItemSubType.Title:
                return(CreateNonFungibleOrder(agentAddress, avatarAddress, orderId, price, tradableId,
                                              startedIndex, itemSubType));

            case ItemSubType.Hourglass:
            case ItemSubType.ApStone:
                return(CreateFungibleOrder(agentAddress, avatarAddress, orderId, price, tradableId,
                                           startedIndex, count, itemSubType));

            default:
                throw new InvalidItemTypeException($"{nameof(itemSubType)}({itemSubType}) does not support.");
            }
        }
Exemple #30
0
        public override IAccountStateDelta Execute(IActionContext context)
        {
            IActionContext ctx    = context;
            var            states = ctx.PreviousStates;

            if (ctx.Rehearsal)
            {
                states = states.SetState(sellerAvatarAddress, MarkChanged);
                states = ShardedShopState.AddressKeys.Aggregate(states,
                                                                (current, addressKey) =>
                                                                current.SetState(ShardedShopState.DeriveAddress(itemSubType, addressKey), MarkChanged));
                return(states
                       .SetState(ctx.Signer, MarkChanged));
            }

            CheckObsolete(BlockChain.Policy.BlockPolicySource.V100080ObsoleteIndex, context);

            var addressesHex = GetSignerAndOtherAddressesHex(context, sellerAvatarAddress);

            var sw = new Stopwatch();

            sw.Start();
            var started = DateTimeOffset.UtcNow;

            Log.Verbose("{AddressesHex}Sell exec started", addressesHex);


            if (price.Sign < 0)
            {
                throw new InvalidPriceException($"{addressesHex}Aborted as the price is less than zero: {price}.");
            }

            if (!states.TryGetAgentAvatarStates(ctx.Signer, sellerAvatarAddress, out AgentState agentState, out AvatarState avatarState))
            {
                throw new FailedLoadStateException($"{addressesHex}Aborted as the avatar state of the signer was failed to load.");
            }
            sw.Stop();
            Log.Verbose("{AddressesHex}Sell Get AgentAvatarStates: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            if (!avatarState.worldInformation.IsStageCleared(GameConfig.RequireClearedStageLevel.ActionsInShop))
            {
                avatarState.worldInformation.TryGetLastClearedStageId(out var current);
                throw new NotEnoughClearedStageLevelException(addressesHex, GameConfig.RequireClearedStageLevel.ActionsInShop, current);
            }

            Log.Verbose("{AddressesHex}Sell IsStageCleared: {Elapsed}", addressesHex, sw.Elapsed);

            sw.Restart();

            Log.Verbose("{AddressesHex}Execute Sell; seller: {SellerAvatarAddress}", addressesHex, sellerAvatarAddress);

            var  productId         = context.Random.GenerateRandomGuid();
            long expiredBlockIndex = context.BlockIndex + ExpiredBlockIndex;

            // Select an item to sell from the inventory and adjust the quantity.
            if (!avatarState.inventory.TryGetNonFungibleItem(itemId, out INonFungibleItem nonFungibleItem))
            {
                throw new ItemDoesNotExistException(
                          $"{addressesHex}Aborted as the NonFungibleItem ({itemId}) was failed to load from avatar's inventory.");
            }

            ItemSubType nonFungibleItemType = nonFungibleItem is Costume costume
                ? costume.ItemSubType
                : ((ItemUsable)nonFungibleItem).ItemSubType;

            if (!nonFungibleItemType.Equals(itemSubType))
            {
                throw new InvalidItemTypeException($"Expected ItemType: {nonFungibleItemType}. Actual ItemType: {itemSubType}");
            }

            if (nonFungibleItem.RequiredBlockIndex > context.BlockIndex)
            {
                throw new RequiredBlockIndexException(
                          $"{addressesHex}Aborted as the itemUsable to sell ({itemId}) is not available yet; it will be available at the block #{nonFungibleItem.RequiredBlockIndex}.");
            }

            if (nonFungibleItem is Equipment equipment)
            {
                equipment.Unequip();
            }
            nonFungibleItem.RequiredBlockIndex = expiredBlockIndex;

            ShopItem shopItem           = new ShopItem(ctx.Signer, sellerAvatarAddress, productId, price, expiredBlockIndex, nonFungibleItem);
            Address  shardedShopAddress = ShardedShopState.DeriveAddress(itemSubType, productId);

            if (!states.TryGetState(shardedShopAddress, out Bencodex.Types.Dictionary shopStateDict))
            {
                ShardedShopState shardedShopState = new ShardedShopState(shardedShopAddress);
                shopStateDict = (Dictionary)shardedShopState.Serialize();
            }

            Log.Verbose("{AddressesHex}Sell Get ShardedShopState: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            List   products              = (List)shopStateDict[ProductsKey];
            string productKey            = LegacyItemUsableKey;
            string itemIdKey             = LegacyItemIdKey;
            string requiredBlockIndexKey = LegacyRequiredBlockIndexKey;

            if (nonFungibleItem is Costume)
            {
                productKey            = LegacyCostumeKey;
                itemIdKey             = LegacyCostumeItemIdKey;
                requiredBlockIndexKey = RequiredBlockIndexKey;
            }
#pragma warning disable LAA1002
            Dictionary productSerialized = products
                                           .Select(p => (Dictionary)p)
                                           .FirstOrDefault(p =>
                                                           ((Dictionary)p[productKey])[itemIdKey].Equals(nonFungibleItem.NonFungibleId.Serialize()));
#pragma warning restore LAA1002

            // Register new ShopItem
            if (productSerialized.Equals(Dictionary.Empty))
            {
                IValue shopItemSerialized = shopItem.Serialize();
                products = products.Add(shopItemSerialized);
            }
            // Update Registered ShopItem
            else
            {
                // Delete current ShopItem
                products = (List)products.Remove(productSerialized);

                // Update INonfungibleItem.RequiredBlockIndex
                Dictionary item = (Dictionary)productSerialized[productKey];
                item = item.SetItem(requiredBlockIndexKey, expiredBlockIndex.Serialize());

                // Update ShopItem.ExpiredBlockIndex
                productSerialized = productSerialized
                                    .SetItem(ExpiredBlockIndexKey, expiredBlockIndex.Serialize())
                                    .SetItem(productKey, item);
                products = products.Add(productSerialized);
                shopItem = new ShopItem(productSerialized);
            }
            shopStateDict = shopStateDict.SetItem(ProductsKey, new List <IValue>(products));

            sw.Stop();
            Log.Verbose("{AddressesHex}Sell Get Register Item: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            avatarState.updatedAt  = ctx.BlockIndex;
            avatarState.blockIndex = ctx.BlockIndex;

            var result = new SellCancellation.Result
            {
                shopItem   = shopItem,
                itemUsable = shopItem.ItemUsable,
                costume    = shopItem.Costume
            };
            var mail = new SellCancelMail(result, ctx.BlockIndex, ctx.Random.GenerateRandomGuid(), expiredBlockIndex);
            result.id = mail.id;
            avatarState.Update(mail);

            states = states.SetState(sellerAvatarAddress, avatarState.Serialize());
            sw.Stop();
            Log.Verbose("{AddressesHex}Sell Set AvatarState: {Elapsed}", addressesHex, sw.Elapsed);
            sw.Restart();

            states = states.SetState(shardedShopAddress, shopStateDict);
            sw.Stop();
            var ended = DateTimeOffset.UtcNow;
            Log.Verbose("{AddressesHex}Sell Set ShopState: {Elapsed}", addressesHex, sw.Elapsed);
            Log.Verbose("{AddressesHex}Sell Total Executed Time: {Elapsed}", addressesHex, ended - started);

            return(states);
        }