private bool OnCreateAuctionConfirm()
        {
            var cmp    = Composers["tradercreateauction"];
            int monehs = InventoryTrader.GetPlayerAssets(capi.World.Player.Entity);
            int weeks  = cmp.GetDropDown("duration").SelectedValue.ToInt(1);
            int price  = (int)cmp.GetNumberInput("price").GetValue();

            if (price < 1)
            {
                capi.TriggerIngameError(this, "atleast1gear", Lang.Get("Must sell item for at least 1 gear"));
                return(true);
            }

            if (monehs < auctionSys.GetDepositCost(auctionSlotInv[0]) * weeks / auctionSys.DurationWeeksMul)
            {
                capi.TriggerIngameError(this, "notenoughgears", Lang.Get("Not enough gears to pay the deposit"));
                return(true);
            }



            auctionSys.PlaceAuctionClient(owningEntity, price, weeks);
            OnCreateAuctionClose();

            lastPrice = price;

            auctionSlotInv[0].Itemstack = null;

            capi.Gui.PlaySound(new AssetLocation("effect/receptionbell.ogg"));


            return(true);
        }
        void CalcAndUpdateAssetsDisplay()
        {
            int playerAssets = InventoryTrader.GetPlayerAssets(capi.World.Player.Entity);

            SingleComposer.GetDynamicText("playerMoneyText")?.SetNewText(Lang.Get("You have {0} Gears", playerAssets));

            int traderAssets = traderInventory.GetTraderAssets();

            SingleComposer.GetDynamicText("traderMoneyText")?.SetNewText(Lang.Get("{0} has {1} Gears", owningEntity.GetBehavior <EntityBehaviorNameTag>().DisplayName, traderAssets));
        }
        public override void FromBytes(BinaryReader reader, bool forClient)
        {
            base.FromBytes(reader, forClient);

            if (Inventory == null)
            {
                Inventory = new InventoryTrader("traderInv", "" + EntityId, null);
            }

            Inventory.FromTreeAttributes(GetOrCreateTradeStore());
        }
        public void PurchaseAuction(long auctionId, EntityAgent buyerEntity, Entity auctioneerEntity, bool withDelivery, out string failureCode)
        {
            if (auctions.TryGetValue(auctionId, out var auction))
            {
                if ((buyerEntity as EntityPlayer)?.PlayerUID == auction.SellerUid)
                {
                    failureCode = "ownauction";
                    return;
                }

                // Already purchased
                if (auction.BuyerName != null)
                {
                    failureCode = "alreadypurchased";
                    return;
                }

                int monehs        = InventoryTrader.GetPlayerAssets(buyerEntity);
                int deliveryCosts = withDelivery ? DeliveryCostsByDistance(auctioneerEntity.Pos.XYZ, auction.SrcAuctioneerEntityPos) : 0;

                int totalcost = auction.Price + deliveryCosts;

                if (monehs < totalcost)
                {
                    failureCode = "notenoughgears";
                    return;
                }

                InventoryTrader.DeductFromEntity(sapi, buyerEntity, totalcost);
                (auctioneerEntity as EntityTrader).Inventory?.GiveToTrader((int)(auction.Price * SalesCutRate + deliveryCosts));

                string buyerName = buyerEntity.GetBehavior <EntityBehaviorNameTag>()?.DisplayName;
                if (buyerName == null)
                {
                    buyerName = buyerEntity.Properties.Code.ToShortString();
                }

                auction.BuyerName              = buyerName;
                auction.WithDelivery           = withDelivery;
                auction.BuyerUid               = (buyerEntity as EntityPlayer)?.PlayerUID;
                auction.RetrievableTotalHours  = sapi.World.Calendar.TotalHours + 1 + 3 * deliveryCosts;
                auction.DstAuctioneerEntityId  = withDelivery ? auctioneerEntity.EntityId : auction.SrcAuctioneerEntityId;
                auction.DstAuctioneerEntityPos = withDelivery ? auctioneerEntity.Pos.XYZ : auction.SrcAuctioneerEntityPos;
                auction.State = EnumAuctionState.Sold;

                sendAuctions(new Auction[] { auction }, null);

                failureCode = null;
                return;
            }

            failureCode = "nosuchauction";
            return;
        }
        public override void Initialize(EntityProperties properties, ICoreAPI api, long InChunkIndex3d)
        {
            base.Initialize(properties, api, InChunkIndex3d);

            if (Inventory == null)
            {
                Inventory = new InventoryTrader("traderInv", "" + EntityId, api);
            }

            if (api.Side == EnumAppSide.Server)
            {
                try
                {
                    string json = Properties.Server.Attributes["tradeProps"].ToJsonToken();
                    TradeProps = new JsonObject(json).AsObject <TradeProperties>();
                } catch (Exception e)
                {
                    api.World.Logger.Error("Failed deserializing TradeProperties for trader {0}, exception logged to verbose debug", properties.Code);
                    api.World.Logger.VerboseDebug("Failed deserializing TradeProperties: {0}", e);
                    api.World.Logger.VerboseDebug("=================");
                    api.World.Logger.VerboseDebug("Tradeprops json:");
                    api.World.Logger.VerboseDebug("{0}", Properties.Server.Attributes["tradeProps"].ToJsonToken());
                }

                if (OutfitCodes == null)
                {
                    OutfitCodes = api.ModLoader.GetModSystem <TraderOutfits>().GetRandomOutfit();
                }
            }
            else
            {
                talkUtil = new TalkUtil(api as ICoreClientAPI, this);
            }

            try
            {
                Inventory.LateInitialize("traderInv-" + EntityId, api, this);
            } catch (Exception e)
            {
                api.World.Logger.Error("Failed initializing trader inventory. Will recreate. Exception logged to verbose debug");
                api.World.Logger.VerboseDebug("Failed initializing trader inventory. Will recreate. Exception {0}", e);

                WatchedAttributes.RemoveAttribute("traderInventory");
                Inventory = new InventoryTrader("traderInv", "" + EntityId, api);
                Inventory.LateInitialize("traderInv-" + EntityId, api, this);

                RefreshBuyingSellingInventory();
            }

            (AnimManager as TraderAnimationManager).Personality = this.Personality;
            this.Personality = this.Personality; // to update the talkutil
        }
Exemple #6
0
        public override void FromBytes(BinaryReader reader, bool forClient)
        {
            base.FromBytes(reader, forClient);

            if (Inventory == null)
            {
                Inventory = new InventoryTrader("traderInv", "" + EntityId, null);
            }

            Inventory.FromTreeAttributes(GetOrCreateTradeStore());

            (AnimManager as TraderAnimationManager).Personality = this.Personality;
        }
        public override void Initialize(EntityProperties properties, ICoreAPI api, long InChunkIndex3d)
        {
            base.Initialize(properties, api, InChunkIndex3d);

            if (Inventory == null)
            {
                Inventory = new InventoryTrader("traderInv", "" + EntityId, api);
            }

            if (api.Side == EnumAppSide.Server)
            {
                try
                {
                    string json = Properties.Server.Attributes["tradeProps"].ToJsonToken();
                    TradeProps = new JsonObject(json).AsObject <TradeProperties>();
                } catch (Exception e)
                {
                    api.World.Logger.Error("Failed deserializing TradeProperties, exception logged to verbose debug");
                    api.World.Logger.VerboseDebug("Failed deserializing TradeProperties: " + e);
                }
            }
            else
            {
                talkUtil = new TalkUtil(api as ICoreClientAPI, this);
            }

            try
            {
                Inventory.LateInitialize("traderInv-" + EntityId, api, this);
            } catch (Exception e)
            {
                api.World.Logger.Error("Failed initializing trader inventory. Will recreate. Exception logged to verbose debug");
                api.World.Logger.VerboseDebug("Failed initializing trader inventory. Will recreate. Exception {0}", e);

                WatchedAttributes.RemoveAttribute("traderInventory");
                Inventory = new InventoryTrader("traderInv", "" + EntityId, api);
                Inventory.LateInitialize("traderInv-" + EntityId, api, this);

                RefreshBuyingSellingInventory();
            }
        }
        public GuiDialogTrader(InventoryTrader traderInventory, EntityAgent owningEntity, ICoreClientAPI capi, int rows = 4, int cols = 4) : base(capi)
        {
            auctionSys = capi.ModLoader.GetModSystem <ModSystemAuction>();
            auctionSys.OnCellUpdateClient = () =>
            {
                listElem?.ReloadCells(auctions);
                updateScrollbarBounds();
            };
            auctionSys.curTraderClient = owningEntity as EntityTrader;

            this.traderInventory = traderInventory;
            this.owningEntity    = owningEntity;
            this.rows            = rows;
            this.cols            = cols;

            if (!auctionSys.createAuctionSlotByPlayer.TryGetValue(capi.World.Player.PlayerUID, out auctionSlotInv))
            {
                auctionSys.createAuctionSlotByPlayer[capi.World.Player.PlayerUID] = auctionSlotInv = new InventoryGeneric(1, "auctionslot-" + capi.World.Player.PlayerUID, capi);
            }

            capi.Network.SendPacketClient(auctionSlotInv.Open(capi.World.Player));

            Compose();
        }
 public ItemSlotBuying(InventoryTrader inventory) : base(inventory)
 {
     this.inv = inventory;
 }
Exemple #10
0
        public void PlaceAuction(ItemSlot slot, int quantity, int price, double durationHours, int depositCost, EntityAgent sellerEntity, Entity auctioneerEntity, out string failureCode)
        {
            if (slot.StackSize < quantity)
            {
                failureCode = "notenoughitems";
                return;
            }

            if (GetAuctionsFrom((sellerEntity as EntityPlayer).Player).Count > 30)
            {
                failureCode = "toomanyauctions";
                return;
            }

            int monehs = InventoryTrader.GetPlayerAssets(sellerEntity);

            if (monehs < GetDepositCost(slot) * depositCost)
            {
                failureCode = "notenoughgears";
                return;
            }

            failureCode = null;
            InventoryTrader.DeductFromEntity(sapi, sellerEntity, depositCost);
            (auctioneerEntity as EntityTrader).Inventory?.GiveToTrader(depositCost);


            long id = ++auctionsData.nextAuctionId;

            string sellerName = sellerEntity.GetBehavior <EntityBehaviorNameTag>()?.DisplayName;

            if (sellerName == null)
            {
                sellerName = sellerEntity.Properties.Code.ToShortString();
            }


            float  debt;
            string uid = (sellerEntity as EntityPlayer)?.PlayerUID ?? "";

            auctionsData.DebtToTraderByPlayer.TryGetValue(uid, out debt);

            float traderCutGears = price * SalesCutRate + debt;

            auctionsData.DebtToTraderByPlayer[uid] = traderCutGears - (int)traderCutGears;


            var auction = new Auction()
            {
                AuctionId              = id,
                ExpireTotalHours       = sapi.World.Calendar.TotalHours + durationHours,
                ItemStack              = slot.TakeOut(quantity),
                PostedTotalHours       = sapi.World.Calendar.TotalHours,
                Price                  = price,
                TraderCut              = (int)traderCutGears,
                SellerName             = sellerName,
                SellerUid              = (sellerEntity as EntityPlayer)?.PlayerUID,
                SellerEntityId         = sellerEntity.EntityId,
                SrcAuctioneerEntityPos = auctioneerEntity.Pos.XYZ,
                SrcAuctioneerEntityId  = auctioneerEntity.EntityId
            };

            auctions.Add(id, auction);
            slot.MarkDirty();

            sendAuctions(new Auction[] { auction }, null);
        }
        public GuiDialogTrader(InventoryTrader traderInventory, EntityAgent owningEntity, ICoreClientAPI capi, int rows = 4, int cols = 4) : base(capi)
        {
            this.traderInventory = traderInventory;
            this.owningEntity    = owningEntity;

            double pad = GuiElementItemSlotGrid.unscaledSlotPadding;

            ElementBounds leftTopSlotBounds  = ElementStdBounds.SlotGrid(EnumDialogArea.None, pad, 70 + pad, cols, rows).FixedGrow(2 * pad, 2 * pad);
            ElementBounds rightTopSlotBounds = ElementStdBounds.SlotGrid(EnumDialogArea.None, pad + leftTopSlotBounds.fixedWidth + 20, 70 + pad, cols, rows).FixedGrow(2 * pad, 2 * pad);

            ElementBounds rightBotSlotBounds = ElementStdBounds
                                               .SlotGrid(EnumDialogArea.None, pad + leftTopSlotBounds.fixedWidth + 20, 15 + pad, cols, 1)
                                               .FixedGrow(2 * pad, 2 * pad)
                                               .FixedUnder(rightTopSlotBounds, 5)
            ;

            ElementBounds leftBotSlotBounds = ElementStdBounds
                                              .SlotGrid(EnumDialogArea.None, pad, 15 + pad, cols, 1)
                                              .FixedGrow(2 * pad, 2 * pad)
                                              .FixedUnder(leftTopSlotBounds, 5)
            ;

            //ElementBounds chanceInputBounds = ElementBounds.Fixed(3, 0, 48, 30).FixedUnder(l, -4);

            ElementBounds leftButton  = ElementBounds.Fixed(EnumDialogArea.LeftFixed, 0, 0, 0, 0).WithFixedPadding(10, 1);
            ElementBounds rightButton = ElementBounds.Fixed(EnumDialogArea.RightFixed, 0, 0, 0, 0).WithFixedPadding(10, 1);

            ElementBounds bgBounds = ElementBounds.Fill.WithFixedPadding(GuiStyle.ElementToDialogPadding);

            bgBounds.BothSizing = ElementSizing.FitToChildren;



            ElementBounds costTextBounds  = ElementBounds.Fixed(pad, 85 + 2 * pad + leftTopSlotBounds.fixedHeight + leftBotSlotBounds.fixedHeight, 150, 25);
            ElementBounds offerTextBounds = ElementBounds.Fixed(leftTopSlotBounds.fixedWidth + pad + 20, 85 + 2 * pad + leftTopSlotBounds.fixedHeight + leftBotSlotBounds.fixedHeight, 150, 25);

            ElementBounds traderMoneyBounds = offerTextBounds.FlatCopy().WithFixedOffset(0, offerTextBounds.fixedHeight);
            ElementBounds playerMoneyBounds = costTextBounds.FlatCopy().WithFixedOffset(0, costTextBounds.fixedHeight);

            ElementBounds dialogBounds = ElementStdBounds
                                         .AutosizedMainDialog.WithAlignment(EnumDialogArea.RightMiddle)
                                         .WithFixedAlignmentOffset(-GuiStyle.DialogToScreenPadding, 0);

            string traderName = owningEntity.GetBehavior <EntityBehaviorNameTag>().DisplayName;

            double daysLeft       = 14 - (capi.World.Calendar.TotalDays - owningEntity.WatchedAttributes.GetDouble("lastRefreshTotalDays", 0));
            string daysLeftString = daysLeft < 1 ? Lang.Get("Delievery of new goods in less than 1 day") : Lang.Get("Delievery of new goods in {0} days", (int)daysLeft);

            CairoFont deliveryTextFont = CairoFont.WhiteDetailText();

            deliveryTextFont.Color[3] *= 0.7;

            SingleComposer =
                capi.Gui
                .CreateCompo("traderdialog-" + owningEntity.Code.Path, dialogBounds)
                .AddShadedDialogBG(bgBounds, true)
                .AddDialogTitleBar(Lang.Get("tradingwindow-" + owningEntity.Code.Path, traderName), OnTitleBarClose)
                .BeginChildElements(bgBounds)
                .AddStaticText(daysLeftString, deliveryTextFont, ElementBounds.Fixed(pad, 20 + pad, 300, 25))

                .AddStaticText(Lang.Get("You can Buy"), CairoFont.WhiteDetailText(), ElementBounds.Fixed(pad, 50 + pad, 150, 25))
                .AddStaticText(Lang.Get("You can Sell"), CairoFont.WhiteDetailText(), ElementBounds.Fixed(leftTopSlotBounds.fixedWidth + pad + 20, 50 + pad, 150, 25))

                .AddItemSlotGrid(traderInventory, DoSendPacket, cols, (new int[rows * cols]).Fill(i => i), leftTopSlotBounds, "traderSellingSlots")
                .AddItemSlotGrid(traderInventory, DoSendPacket, cols, (new int[cols]).Fill(i => rows * cols + i), leftBotSlotBounds, "playerBuyingSlots")

                .AddItemSlotGrid(traderInventory, DoSendPacket, cols, (new int[rows * cols]).Fill(i => rows * cols + cols + i), rightTopSlotBounds, "traderBuyingSlots")
                .AddItemSlotGrid(traderInventory, DoSendPacket, cols, (new int[cols]).Fill(i => rows * cols + cols + rows * cols + i), rightBotSlotBounds, "playerSellingSlots")

                .AddStaticText(Lang.Get("trader-yourselection"), CairoFont.WhiteDetailText(), ElementBounds.Fixed(pad, 70 + 2 * pad + leftTopSlotBounds.fixedHeight, 150, 25))
                .AddStaticText(Lang.Get("trader-youroffer"), CairoFont.WhiteDetailText(), ElementBounds.Fixed(leftTopSlotBounds.fixedWidth + pad + 20, 70 + 2 * pad + leftTopSlotBounds.fixedHeight, 150, 25))

                // Cost
                .AddDynamicText("", CairoFont.WhiteDetailText(), EnumTextOrientation.Left, costTextBounds, "costText")
                // Player money
                .AddDynamicText("", CairoFont.WhiteDetailText(), EnumTextOrientation.Left, playerMoneyBounds, "playerMoneyText")
                // Offer
                .AddDynamicText("", CairoFont.WhiteDetailText(), EnumTextOrientation.Left, offerTextBounds, "gainText")
                // Trader money
                .AddDynamicText("", CairoFont.WhiteDetailText(), EnumTextOrientation.Left, traderMoneyBounds, "traderMoneyText")

                .AddSmallButton(Lang.Get("Goodbye!"), OnByeClicked, leftButton.FixedUnder(playerMoneyBounds, 20).WithFixedPadding(8, 5))
                .AddSmallButton(Lang.Get("Buy / Sell"), OnBuySellClicked, rightButton.FixedUnder(traderMoneyBounds, 20).WithFixedPadding(8, 5), EnumButtonStyle.Normal, EnumTextOrientation.Left, "buysellButton")


                .EndChildElements()
                .Compose()
            ;

            SingleComposer.GetButton("buysellButton").Enabled = false;

            CalcAndUpdateAssetsDisplay();
        }
        public GuiDialogTrader(InventoryTrader traderInventory, EntityAgent owningEntity, ICoreClientAPI capi) : base(capi)
        {
            this.traderInventory = traderInventory;
            this.owningEntity    = owningEntity;



            double pad = GuiElementItemSlotGrid.unscaledSlotPadding;

            ElementBounds leftTopSlotBounds  = ElementStdBounds.SlotGrid(EnumDialogArea.None, pad, 40 + pad, 4, 4).FixedGrow(2 * pad, 2 * pad);
            ElementBounds rightTopSlotBounds = ElementStdBounds.SlotGrid(EnumDialogArea.None, pad + leftTopSlotBounds.fixedWidth + 20, 40 + pad, 4, 4).FixedGrow(2 * pad, 2 * pad);

            ElementBounds rightBotSlotBounds = ElementStdBounds.SlotGrid(EnumDialogArea.None, pad + leftTopSlotBounds.fixedWidth + 20, 15 + pad, 4, 1).FixedGrow(2 * pad, 2 * pad).FixedUnder(rightTopSlotBounds, 5);
            ElementBounds leftBotSlotBounds  = ElementStdBounds.SlotGrid(EnumDialogArea.None, pad, 15 + pad, 4, 1).FixedGrow(2 * pad, 2 * pad).FixedUnder(leftTopSlotBounds, 5);

            //ElementBounds chanceInputBounds = ElementBounds.Fixed(3, 0, 48, 30).FixedUnder(l, -4);

            ElementBounds leftButton  = ElementBounds.Fixed(EnumDialogArea.LeftFixed, 0, 0, 0, 0).WithFixedPadding(10, 1);
            ElementBounds rightButton = ElementBounds.Fixed(EnumDialogArea.RightFixed, 0, 0, 0, 0).WithFixedPadding(10, 1);

            ElementBounds bgBounds = ElementBounds.Fill.WithFixedPadding(ElementGeometrics.ElementToDialogPadding);

            bgBounds.BothSizing = ElementSizing.FitToChildren;



            ElementBounds costTextBounds  = ElementBounds.Fixed(pad, 55 + 2 * pad + leftTopSlotBounds.fixedHeight + leftBotSlotBounds.fixedHeight, 150, 25);
            ElementBounds offerTextBounds = ElementBounds.Fixed(leftTopSlotBounds.fixedWidth + pad + 20, 55 + 2 * pad + leftTopSlotBounds.fixedHeight + leftBotSlotBounds.fixedHeight, 150, 25);

            ElementBounds traderMoneyBounds = offerTextBounds.FlatCopy().WithAddedFixedPosition(0, offerTextBounds.fixedHeight);
            ElementBounds playerMoneyBounds = costTextBounds.FlatCopy().WithAddedFixedPosition(0, costTextBounds.fixedHeight);

            ElementBounds dialogBounds = ElementStdBounds
                                         .AutosizedMainDialog.WithAlignment(EnumDialogArea.RightMiddle)
                                         .WithFixedAlignmentOffset(-ElementGeometrics.DialogToScreenPadding, 0);


            SingleComposer =
                capi.Gui
                .CreateCompo("itemlootrandomizer", dialogBounds, false)
                .AddDialogBG(bgBounds, true)
                .AddDialogTitleBar(owningEntity.GetBehavior <EntityBehaviorNameTag>().DisplayName + " Has Wares, If You Have Coin", OnTitleBarClose)
                .BeginChildElements(bgBounds)
                .AddStaticText("You can Buy", CairoFont.WhiteDetailText(), ElementBounds.Fixed(pad, 20 + pad, 150, 25))
                .AddStaticText("You can Sell", CairoFont.WhiteDetailText(), ElementBounds.Fixed(leftTopSlotBounds.fixedWidth + pad + 20, 20 + pad, 150, 25))

                .AddItemSlotGrid(traderInventory, DoSendPacket, 4, (new int[16]).Fill(i => i), leftTopSlotBounds, "traderSellingSlots")
                .AddItemSlotGrid(traderInventory, DoSendPacket, 4, (new int[4]).Fill(i => 16 + i), leftBotSlotBounds, "playerBuyingSlots")

                .AddItemSlotGrid(traderInventory, DoSendPacket, 4, (new int[16]).Fill(i => 16 + 4 + i), rightTopSlotBounds, "traderBuyingSlots")
                .AddItemSlotGrid(traderInventory, DoSendPacket, 4, (new int[4]).Fill(i => 16 + 4 + 16 + i), rightBotSlotBounds, "playerSellingSlots")

                .AddStaticText("Your Selection", CairoFont.WhiteDetailText(), ElementBounds.Fixed(pad, 40 + 2 * pad + leftTopSlotBounds.fixedHeight, 150, 25))
                .AddStaticText("Your Offer", CairoFont.WhiteDetailText(), ElementBounds.Fixed(leftTopSlotBounds.fixedWidth + pad + 20, 40 + 2 * pad + leftTopSlotBounds.fixedHeight, 150, 25))

                // Cost
                .AddDynamicText("", CairoFont.WhiteDetailText(), EnumTextOrientation.Left, costTextBounds, 1, "costText")
                // Player money
                .AddDynamicText("", CairoFont.WhiteDetailText(), EnumTextOrientation.Left, playerMoneyBounds, 1, "playerMoneyText")
                // Offer
                .AddDynamicText("", CairoFont.WhiteDetailText(), EnumTextOrientation.Left, offerTextBounds, 1, "gainText")
                // Trader money
                .AddDynamicText("", CairoFont.WhiteDetailText(), EnumTextOrientation.Left, traderMoneyBounds, 1, "traderMoneyText")

                .AddSmallButton("Goodbye!", OnByeClicked, leftButton.FixedUnder(playerMoneyBounds, 30).WithFixedPadding(8, 5))
                .AddSmallButton("Buy / Sell", OnByeSellClicked, rightButton.FixedUnder(traderMoneyBounds, 30).WithFixedPadding(8, 5), EnumButtonStyle.Normal, EnumTextOrientation.Left, "buysellButton")


                .EndChildElements()
                .Compose()
            ;

            SingleComposer.GetButton("buysellButton").Enabled = false;

            CalcAndUpdateAssetsDisplay();
        }