Example #1
0
        private void RestPlayer(float dt)
        {
            double hoursPassed = Api.World.Calendar.TotalHours - hoursTotal;

            // Since waking up takes an hour, we take away one hour from the sleepEfficiency
            float sleepEff = sleepEfficiency - 1f / 12;

            if (hoursPassed > 0)
            {
                int tempStormSleep = Api.World.Config.GetString("temporalStormSleeping", "0").ToInt();
                if (tempStormSleep == 0 && Api.ModLoader.GetModSystem <SystemTemporalStability>().StormStrength > 0)
                {
                    MountedBy.TryUnmount();
                    return;
                }

                EntityBehaviorTiredness ebt = MountedBy?.GetBehavior("tiredness") as EntityBehaviorTiredness;
                if (ebt != null)
                {
                    float newval = Math.Max(0, ebt.Tiredness - (float)hoursPassed / sleepEff);
                    ebt.Tiredness = newval;
                    if (newval <= 0)
                    {
                        MountedBy.TryUnmount();
                    }
                }

                hoursTotal = Api.World.Calendar.TotalHours;
            }
        }
Example #2
0
 public bool TryTriggerFlee(EntityAgent agent)
 {
     if (agent.GetBehavior <EntityBehaviorEmotionStates>() == null)
     {
         return(false);
     }
     return(agent.GetBehavior <EntityBehaviorEmotionStates>().TryTriggerState("fleeondamage"));
 }
        public AiActionBase(EntityAgent entity)
        {
            this.entity = entity;
            this.world  = entity.World;
            rand        = new Random((int)entity.EntityId);

            this.pathTraverser = entity.GetBehavior <EntityBehaviorTaskAI>().PathTraverser;
        }
Example #4
0
        public static LandClaim CreateClaim(EntityAgent entity, int protectionLevel = 1)
        {
            string entityName = entity.GetBehavior <EntityBehaviorNameTag>()?.DisplayName;

            return(new LandClaim()
            {
                OwnedByEntityId = entity.EntityId,
                ProtectionLevel = protectionLevel,
                LastKnownOwnerName = Lang.Get("item-creature-" + entity.Code) + (entityName == null ? "" : " " + entityName)
            });
        }
Example #5
0
        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;
        }
Example #6
0
 public override void OnHeldInteractStop(float secondsUsed, ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel)
 {
     // Add the efects once the interaction has finalized.
     if (secondsUsed > 0.7f && byEntity.World.Side == EnumAppSide.Server)
     {
         EntityBehaviorAllomancy allomancy = (EntityBehaviorAllomancy)byEntity.GetBehavior("allomancy");
         if (allomancy != null)
         {
             allomancy.Helper.EnableAllPowers();
             slot.TakeOut(1);
             allomancy.Helper.Debug();
         }
     }
 }
Example #7
0
        private void RestPlayer(float dt)
        {
            double hoursPassed = api.World.Calendar.TotalHours - hoursTotal;

            // Since waking up takes an hour, we take away one hour from the sleepEfficiency
            float sleepEff = sleepEfficiency - 1f / 12;

            if (hoursPassed > 0)
            {
                EntityBehaviorTiredness ebt = MountedBy?.GetBehavior("tiredness") as EntityBehaviorTiredness;
                if (ebt != null)
                {
                    float newval = Math.Max(0, ebt.Tiredness - (float)hoursPassed / sleepEff);
                    ebt.Tiredness = newval;
                    if (newval <= 0)
                    {
                        MountedBy.TryUnmount();
                    }
                }

                hoursTotal = api.World.Calendar.TotalHours;
            }
        }
 public override void OnHeldInteractStop(float secondsUsed, ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel)
 {
     // Add the efects once the interaction has finalized.
     if (secondsUsed > 0.7f && byEntity.World.Side == EnumAppSide.Server)
     {
         EntityBehaviorAllomancy allomancy = (EntityBehaviorAllomancy)byEntity.GetBehavior("allomancy");
         if (allomancy != null)
         {
             JsonObject attr   = slot.Itemstack.Collectible.Attributes;
             float      amount = attr["amount"].AsFloat();
             string     metal  = attr["metal"].AsString();
             allomancy.Helper.IncrementMetalReserve(metal, amount);
             slot.TakeOut(1);
             allomancy.Helper.Debug();
         }
     }
 }
        public override void OnEntityReceiveDamage(DamageSource damageSource, ref float damage)
        {
            if (damageSource.Source == EnumDamageSource.Fall && entity.World.Config.GetString("creatureHostility") == "passive" && entity.World.Config.GetString("creatureHostility") == "off")
            {
                return;
            }

            var beh = entity.GetBehavior <EntityBehaviorHealth>();

            healthRel = beh.Health / beh.MaxHealth;

            long sourceEntityId = damageSource.SourceEntity?.EntityId ?? 0;


            if (TryTriggerState("alarmherdondamage", sourceEntityId) && damageSource.SourceEntity != null && (entity as EntityAgent).HerdId > 0)
            {
                EmotionState state = availableStates.First((s) => s.Code == "alarmherdondamage");
                entity.World.GetNearestEntity(entity.ServerPos.XYZ, state.NotifyRange, state.NotifyRange, (e) =>
                {
                    EntityAgent agent = e as EntityAgent;
                    if (e.EntityId != entity.EntityId && agent != null && agent.Alive && agent.HerdId == (entity as EntityAgent).HerdId)
                    {
                        agent.GetBehavior <EntityBehaviorEmotionStates>().TryTriggerState("aggressiveondamage", sourceEntityId);
                    }

                    return(false);
                });
            }


            if (TryTriggerState("aggressiveondamage", sourceEntityId))
            {
                if (TryTriggerState("aggressivealarmondamage", sourceEntityId))
                {
                }
            }

            if (TryTriggerState("fleeondamage", sourceEntityId))
            {
                if (TryTriggerState("fleealarmondamage", sourceEntityId))
                {
                }
            }
        }
Example #10
0
        public void DidMount(EntityAgent entityAgent)
        {
            if (MountedBy != null)
            {
                return;
            }

            MountedBy = entityAgent;
            if (api.Side == EnumAppSide.Server)
            {
                RegisterGameTickListener(RestPlayer, 200);
                hoursTotal = api.World.Calendar.TotalHours;
            }

            EntityBehaviorTiredness ebt = MountedBy?.GetBehavior("tiredness") as EntityBehaviorTiredness;

            if (ebt != null)
            {
                ebt.IsSleeping = true;
            }
        }
Example #11
0
        public override void OnHeldInteractStop(float secondsUsed, ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel)
        {
            sound?.Stop();
            sound = null;

            if (secondsUsed >= 3.4f)
            {
                string code = GetBlockMaterialCode(slot.Itemstack);

                if (api.Side == EnumAppSide.Server)
                {
                    CreateDrop(byEntity, code.Split('-')[1]);
                }

                RemoveMaterial(slot);
                slot.MarkDirty();
                (byEntity as EntityPlayer)?.Player?.InventoryManager.BroadcastHotbarSlot();

                byEntity.GetBehavior <EntityBehaviorHunger>()?.ConsumeSaturation(4f);
            }
        }
        public void Compose()
        {
            var tabs = new GuiTab[] { new GuiTab()
                                      {
                                          Name = Lang.Get("Local goods"), DataInt = 0
                                      }, new GuiTab()
                                      {
                                          Name = Lang.Get("Auction house"), DataInt = 1
                                      }, new GuiTab()
                                      {
                                          Name = Lang.Get("Your Auctions"), DataInt = 2
                                      } };
            var tabBounds = ElementBounds.Fixed(0, -24, 500, 25);
            var tabFont   = CairoFont.WhiteDetailText();

            if (!auctionHouseEnabled)
            {
                tabs = new GuiTab[] { new GuiTab()
                                      {
                                          Name = Lang.Get("Local goods"), DataInt = 0
                                      } };
            }


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

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


            ElementBounds leftButton  = ElementBounds.Fixed(EnumDialogArea.LeftFixed, 0, 0, 0, 0).WithFixedPadding(8, 5);
            ElementBounds rightButton = ElementBounds.Fixed(EnumDialogArea.RightFixed, 0, 0, 0, 0).WithFixedPadding(8, 5);


            string traderName = owningEntity.GetBehavior <EntityBehaviorNameTag>().DisplayName;
            string dlgTitle   = Lang.Get("tradingwindow-" + owningEntity.Code.Path, traderName);

            if (curTab > 0)
            {
                dlgTitle = Lang.Get("tradertabtitle-" + curTab);
            }

            SingleComposer =
                capi.Gui
                .CreateCompo("traderdialog-" + owningEntity.EntityId, dialogBounds)
                .AddShadedDialogBG(bgBounds, true)
                .AddDialogTitleBar(dlgTitle, OnTitleBarClose)
                .AddHorizontalTabs(tabs, tabBounds, OnTabClicked, tabFont, tabFont.Clone().WithColor(GuiStyle.ActiveButtonTextColor), "tabs")
                .BeginChildElements(bgBounds)
            ;

            SingleComposer.GetHorizontalTabs("tabs").activeElement = curTab;

            if (curTab == 0)
            {
                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 costTextBounds  = ElementBounds.Fixed(pad, 85 + 2 * pad + leftTopSlotBounds.fixedHeight + leftBotSlotBounds.fixedHeight, 200, 25);
                ElementBounds offerTextBounds = ElementBounds.Fixed(leftTopSlotBounds.fixedWidth + pad + 20, 85 + 2 * pad + leftTopSlotBounds.fixedHeight + leftBotSlotBounds.fixedHeight, 200, 25);

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


                double daysLeft       = (owningEntity as EntityTrader).NextRefreshTotalDays();
                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
                .AddStaticText(daysLeftString, deliveryTextFont, ElementBounds.Fixed(pad, 20 + pad, 500, 25))

                .AddStaticText(Lang.Get("You can Buy"), CairoFont.WhiteDetailText(), ElementBounds.Fixed(pad, 50 + pad, 200, 25))
                .AddStaticText(Lang.Get("You can Sell"), CairoFont.WhiteDetailText(), ElementBounds.Fixed(leftTopSlotBounds.fixedWidth + pad + 20, 50 + pad, 200, 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(), costTextBounds, "costText")
                // Player money
                .AddDynamicText("", CairoFont.WhiteDetailText(), playerMoneyBounds, "playerMoneyText")
                // Offer
                .AddDynamicText("", CairoFont.WhiteDetailText(), offerTextBounds, "gainText")
                // Trader money
                .AddDynamicText("", CairoFont.WhiteDetailText(), traderMoneyBounds, "traderMoneyText")

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

                .EndChildElements()
                .Compose()
                ;

                SingleComposer.GetButton("buysellButton").Enabled = false;
                CalcAndUpdateAssetsDisplay();
                return;
            }

            double        listHeight      = 377;
            ElementBounds stackListBounds = ElementBounds.Fixed(0, 25, 700, listHeight); //.FixedUnder(searchFieldBounds, 5);

            clipBounds = stackListBounds.ForkBoundingParent();
            ElementBounds insetBounds = stackListBounds.FlatCopy().FixedGrow(3).WithFixedOffset(0, 0);

            ElementBounds scrollbarBounds = insetBounds.CopyOffsetedSibling(3 + stackListBounds.fixedWidth + 7).WithFixedWidth(20);

            if (curTab == 1)
            {
                auctions = auctionSys.activeAuctions;

                SingleComposer
                .BeginClip(clipBounds)
                .AddInset(insetBounds, 3)
                .AddCellList(stackListBounds, createCell, auctionSys.activeAuctions, "stacklist")
                .EndClip()
                .AddVerticalScrollbar(OnNewScrollbarValue, scrollbarBounds, "scrollbar")

                .AddSmallButton(Lang.Get("Goodbye!"), OnByeClicked, leftButton.FixedUnder(clipBounds, 20))
                .AddSmallButton(Lang.Get("Buy"), OnBuyAuctionClicked, rightButton.FixedUnder(clipBounds, 20), EnumButtonStyle.Normal, EnumTextOrientation.Left, "buyauction")
                ;
            }

            if (curTab == 2)
            {
                auctions = auctionSys.ownAuctions;

                ElementBounds button    = ElementBounds.Fixed(EnumDialogArea.RightFixed, 0, 0, 0, 0).WithFixedPadding(8, 5);
                string        placeStr  = Lang.Get("Place Auction");
                string        cancelStr = Lang.Get("Cancel Auction");

                double placelen  = CairoFont.ButtonText().GetTextExtents(placeStr).Width / RuntimeEnv.GUIScale;
                double cancellen = CairoFont.ButtonText().GetTextExtents(cancelStr).Width / RuntimeEnv.GUIScale;

                SingleComposer
                .BeginClip(clipBounds)
                .AddInset(insetBounds, 3)
                .AddCellList(stackListBounds, createCell, auctionSys.ownAuctions, "stacklist")
                .EndClip()
                .AddVerticalScrollbar(OnNewScrollbarValue, scrollbarBounds, "scrollbar")

                .AddSmallButton(Lang.Get("Goodbye!"), OnByeClicked, leftButton.FixedUnder(clipBounds, 20))
                .AddSmallButton(Lang.Get("Place Auction"), OnCreateAuction, rightButton.FixedUnder(clipBounds, 20), EnumButtonStyle.Normal, EnumTextOrientation.Left, "placeAuction")
                .AddSmallButton(cancelStr, OnCancelAuction, button.FlatCopy().FixedUnder(clipBounds, 20).WithFixedAlignmentOffset(-placelen, 0), EnumButtonStyle.Normal, EnumTextOrientation.Center, "cancelAuction")
                .AddSmallButton(Lang.Get("Collect Funds"), OnCollectFunds, button.FlatCopy().FixedUnder(clipBounds, 20).WithFixedAlignmentOffset(-placelen, 0), EnumButtonStyle.Normal, EnumTextOrientation.Center, "collectFunds")
                .AddSmallButton(Lang.Get("Retrieve Items"), OnRetrieveItems, button.FixedUnder(clipBounds, 20).WithFixedAlignmentOffset(-placelen, 0), EnumButtonStyle.Normal, EnumTextOrientation.Center, "retrieveItems")
                ;
            }

            if (curTab == 1 || curTab == 2)
            {
                selectedElem = null;
                listElem     = SingleComposer.GetCellList <Auction>("stacklist");
                listElem.BeforeCalcBounds();
                listElem.UnscaledCellVerPadding = 0;
                listElem.unscaledCellSpacing    = 5;
                SingleComposer.EndChildElements().Compose();

                updateScrollbarBounds();


                didClickAuctionElem(-1);
            }
        }
Example #13
0
        public override bool OnHeldInteractStep(float secondsUsed, ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel)
        {
            if (byEntity.Attributes.GetBool("isInsertGear", false))
            {
                if (!(byEntity.LeftHandItemSlot?.Itemstack?.Collectible is ItemTemporalGear))
                {
                    return(false);
                }

                if (byEntity.World.Side == EnumAppSide.Client)
                {
                    ModelTransform tf = new ModelTransform();
                    tf.EnsureDefaultValues();


                    tf.Translation.Set(0, -Math.Min(0.2f, secondsUsed * 0.8f), -Math.Min(0.6f, secondsUsed * 3 * 0.8f));
                    //tf.Rotation.X = Math.Min(60, secondsUsed * 90 * 4f);
                    tf.Origin.Set(0.3f, 0, 0.5f);
                    tf.Rotation.X = Math.Min(135, secondsUsed * 90 * 7.5f * 0.8f);
                    tf.Rotation.Z = -Math.Min(30, secondsUsed * 90 * 1.667f * 0.8f);


                    if (secondsUsed > 1f)
                    {
                        tf.Translation.Y += Math.Min(0.75f, (secondsUsed - 1f) * 20);
                        tf.Translation.X -= Math.Min(0.2f, secondsUsed - 1f);
                        tf.Rotation.Z    -= Math.Min(130, (secondsUsed - 1f) * 90 * 20);
                    }

                    if (secondsUsed > 1.1f && !byEntity.Attributes.GetBool("stabPlayed", false))
                    {
                        byEntity.World.PlaySoundAt(new AssetLocation("sounds/player/stab"), byEntity, (byEntity as EntityPlayer)?.Player, false, 12, 0.3f);
                        byEntity.Attributes.SetBool("stabPlayed", true);
                    }

                    byEntity.Controls.UsingHeldItemTransformBefore = tf;


                    ModelTransform tfleft = new ModelTransform();
                    tfleft.EnsureDefaultValues();

                    byEntity.LeftHandItemSlot.Itemstack.Collectible.FpHandTransform.Rotation.Y = 0;

                    tfleft.Translation.Set(Math.Min(0.6f, secondsUsed * 4), Math.Min(0.2f, secondsUsed), 0);

                    if (secondsUsed >= 1.4f)
                    {
                        tfleft.Translation.Z += (secondsUsed - 1.4f) * 1.2f;
                        tfleft.Translation.Y += Math.Min(0.1f, (secondsUsed - 1.4f) * 1.2f);
                        tfleft.Translation.X += (secondsUsed - 1.4f) * 1.2f;
                    }
                    byEntity.Controls.LeftUsingHeldItemTransformBefore = tfleft;


                    return(true);
                }
                else
                {
                    if (secondsUsed > 1.1f && !byEntity.Attributes.GetBool("didHurt", false))
                    {
                        api.World.Logger.Notification("Server did hurt");

                        byEntity.ReceiveDamage(new DamageSource()
                        {
                            DamageTier = 0, Source = EnumDamageSource.Internal, Type = EnumDamageType.PiercingAttack
                        }, 2);
                        slot?.Itemstack?.Collectible.DamageItem(byEntity.World, byEntity, slot, 1);

                        byEntity.Attributes.SetBool("didHurt", true);
                    }

                    if (secondsUsed >= 1.95f && !byEntity.Attributes.GetBool("stabPlayed", false))
                    {
                        api.World.Logger.Notification("Server did stab played");

                        byEntity.GetBehavior <EntityBehaviorTemporalStabilityAffected>().AddStability(0.30);

                        byEntity.LeftHandItemSlot.TakeOut(1);
                        byEntity.LeftHandItemSlot.MarkDirty();

                        ((byEntity as EntityPlayer)?.Player as IServerPlayer)?.BroadcastPlayerData();

                        int h = 110 + api.World.Rand.Next(15);
                        int v = 100 + api.World.Rand.Next(50);
                        particlesStab.MinPos = byEntity.SidedPos.XYZ.Add(byEntity.CollisionBox.X1, 0, byEntity.CollisionBox.Z1);
                        particlesStab.AddPos = new Vec3d(byEntity.CollisionBox.XSize, byEntity.CollisionBox.Y2, byEntity.CollisionBox.ZSize);
                        particlesStab.Color  = ColorUtil.ReverseColorBytes(ColorUtil.HsvToRgba(h, 180, v, 150));
                        api.World.SpawnParticles(particlesStab);

                        byEntity.Attributes.SetBool("stabPlayed", true);
                    }

                    return(secondsUsed < 2f);
                }
            }


            // Crappy fix to make animal harvesting not buggy T_T
            if (api.Side == EnumAppSide.Server)
            {
                return(true);
            }



            EntityBehaviorHarvestable bh;

            if (entitySel != null && (bh = entitySel.Entity.GetBehavior <EntityBehaviorHarvestable>()) != null && bh.Harvestable)
            {
                if (byEntity.World.Side == EnumAppSide.Client)
                {
                    ModelTransform tf = new ModelTransform();
                    tf.EnsureDefaultValues();

                    tf.Translation.Set(0, 0, -Math.Min(0.6f, secondsUsed * 2));
                    tf.Rotation.Y = Math.Min(20, secondsUsed * 90 * 2f);


                    if (secondsUsed > 0.4f)
                    {
                        tf.Translation.X += (float)Math.Cos(secondsUsed * 15) / 10;
                        tf.Translation.Z += (float)Math.Sin(secondsUsed * 5) / 30;
                    }

                    byEntity.Controls.UsingHeldItemTransformBefore = tf;
                }

                //byEntity.World.Logger.Debug("{0} knife interact step: Seconds: {1}/{2}", byEntity.World.Side, secondsUsed, bh.HarvestDuration );

                return(secondsUsed < bh.GetHarvestDuration(byEntity) + 0.15f);
            }

            return(false);
        }
        void CalcAndUpdateAssetsDisplay()
        {
            int playerAssets = traderInventory.GetPlayerAssets(capi.World.Player);

            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));
        }
Example #15
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();
        }
Example #17
0
        public override void OnHeldInteractStart(ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel, bool firstEvent, ref EnumHandHandling handling)
        {
            byEntity.Attributes.SetBool("isInsertGear", false);

            if (byEntity.LeftHandItemSlot?.Itemstack?.Collectible is ItemTemporalGear && byEntity.GetBehavior <EntityBehaviorTemporalStabilityAffected>() != null)
            {
                byEntity.Attributes.SetBool("isInsertGear", true);
                byEntity.Attributes.SetBool("stabPlayed", false);
                byEntity.Attributes.SetBool("didHurt", false);

                var healthTree = byEntity.WatchedAttributes.GetTreeAttribute("health") as ITreeAttribute;
                if (healthTree != null && healthTree.GetFloat("currenthealth") <= 2)
                {
                    if (api.Side == EnumAppSide.Client)
                    {
                        (api as ICoreClientAPI).TriggerIngameError(this, "toodangerous", Lang.Get("Cannot apply without dying"));
                    }
                    return;
                }

                handling = EnumHandHandling.PreventDefault;
                return;
            }

            EntityBehaviorHarvestable bh;

            if (byEntity.Controls.Sneak && entitySel != null && (bh = entitySel.Entity.GetBehavior <EntityBehaviorHarvestable>()) != null && bh.Harvestable)
            {
                byEntity.World.PlaySoundAt(new AssetLocation("sounds/player/scrape"), entitySel.Entity, (byEntity as EntityPlayer)?.Player, false, 12);
                handling = EnumHandHandling.PreventDefault;
                return;
            }

            handling = EnumHandHandling.NotHandled;
        }
Example #18
0
        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();
        }