Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Reflection;
- using UnityEngine;
- using Rust;
- using Oxide.Game.Rust.Cui;
- namespace Oxide.Plugins
- {
- [Info("Player Trade Tweaked", "emu/Visagalis", "0.1.2", ResourceId = 1242)]
- class PlayerTrade : RustPlugin
- {
- #region Strings //this is now properly formatted, only the chat commands are missing (line 913)
- public const string s_TradeRequestPlayer = "Trade request sent to {0}";
- public const string s_TradeRequestOther = "{0} wants to trade with you! Type /tra to accept";
- public const string s_TradeRequestDeclined = "{0} declined your trade request!";
- public const string s_TradeRequestNotFound = "Cannot find player named {0}";
- public const string s_TradeRequestPlayerBusy = "You already have a trade request pending! Type /trd to decline";
- public const string s_TradeRequestOtherBusy = "{0} is already trading!";
- public const string s_WrongTradeRequest = "Usage: /trr \"partial or full player name\"";
- public const string s_WrongOffer = "Usage: /tro \"partial or full item name\" amount";
- public const string s_WrongOfferBlueprint = "Usage: /trob \"partial or full blueprint name\"";
- public const string s_TradeOfferFailed = "You don't have {0}";
- public const string s_TradeCanceled = "Trade canceled!";
- public const string s_NoItemFound = "No item found with that name!";
- public const string s_Disconnected = "You disconnected! Trade canceled.";
- public const string s_DisconnectedOther = "Your partner disconnected! Trade canceled.";
- public const string s_Death = "You died! Trade canceled.";
- public const string s_DeathOther = "Your partner died! Trade canceled.";
- public const string s_TookDamage = "You took damage! Trade canceled.";
- public const string s_TookDamageOther = "Your partner took damage! Trade canceled.";
- public const string s_TradeMade = "Trade successful!";
- public const string s_TimeOut = "{0} failed to answer your trade request in time.";
- public const string s_TimeOutOther = "You failed to answer the trade request in time.";
- public const string s_TooFar = "Your partner is too far away!";
- public const string s_RangeGet = "Trading range is {0}";
- public const string s_CooldownGet = "Trade cooldown is {0}";
- public const string s_TradePartner = "You are trading with {0}";
- public const string s_TradeSuccessful = "Transaction complete!";
- public const string s_YouGet = "You get";
- public const string s_YouGive = "You give";
- public const string s_PlayerReady = "You are ready";
- public const string s_OtherReady = "Partner is ready";
- #endregion
- #region Config
- private const float defaultTradeDistance = 0f;
- private const float defaultTradeCooldown = 0f;
- private static float tradeDistance = defaultTradeDistance;
- private static float tradeCooldown = defaultTradeCooldown;
- private static float timeOut = 30f;
- protected override void LoadDefaultConfig()
- {
- PrintWarning("Creating a new configuration file.");
- Config.Clear();
- Config["TradeRange"] = defaultTradeDistance;
- Config["TradeCooldown"] = defaultTradeCooldown;
- SaveConfig();
- }
- override protected void LoadConfig()
- {
- tradeDistance = GetConfig<float>("TradeRange", defaultTradeDistance);
- tradeCooldown = GetConfig<float>("TradeCooldown", defaultTradeCooldown);
- }
- T GetConfig<T>(string key, T defaultValue) {
- try {
- var val = Config[key];
- if (val == null)
- return defaultValue;
- if (val is List<object>) {
- var t = typeof(T).GetGenericArguments()[0];
- if (t == typeof(String)) {
- var cval = new List<string>();
- foreach (var v in val as List<object>)
- cval.Add((string)v);
- val = cval;
- } else if (t == typeof(int)) {
- var cval = new List<int>();
- foreach (var v in val as List<object>)
- cval.Add(Convert.ToInt32(v));
- val = cval;
- }
- } else if (val is Dictionary<string, object>) {
- var t = typeof(T).GetGenericArguments()[1];
- if (t == typeof(int)) {
- var cval = new Dictionary<string,int>();
- foreach (var v in val as Dictionary<string, object>)
- cval.Add(Convert.ToString(v.Key), Convert.ToInt32(v.Value));
- val = cval;
- }
- }
- return (T)Convert.ChangeType(val, typeof(T));
- } catch (Exception ex) {
- return defaultValue;
- }
- }
- [ChatCommand("traderange")]
- private void SetRange(BasePlayer player, string command, string[] args)
- {
- if(args.Length == 0)
- {
- PrintToChat(player, string.Format(s_RangeGet, tradeDistance));
- return;
- }
- if(args.Length != 1 || !player.IsAdmin())
- return;
- float range;
- bool isValid = float.TryParse(args[0], out range);
- if(!isValid)
- return;
- Config["TradeRange"] = range;
- SaveConfig();
- LoadConfig();
- PrintToChat(player, "Trade range set to " + range);
- }
- [ChatCommand("tradecooldown")]
- private void SetLimit(BasePlayer player, string command, string[] args)
- {
- if(args.Length == 0)
- {
- PrintToChat(player, string.Format(s_CooldownGet, tradeCooldown));
- return;
- }
- if(args.Length != 1 || !player.IsAdmin())
- return;
- float cooldown;
- bool isValid = float.TryParse(args[0], out cooldown);
- if(!isValid)
- return;
- Config["TradeCooldown"] = cooldown;
- SaveConfig();
- LoadConfig();
- PrintToChat(player, "Trade cooldown set to " + cooldown);
- }
- #endregion
- #region Oxide Hooks
- private void OnPlayerInit(BasePlayer player)
- {
- AddTrader(player);
- }
- private void OnServerInitialized()
- {
- LoadConfig();
- initGUI();
- for (int i = 0; i < BasePlayer.activePlayerList.Count; i++)
- {
- AddTrader(BasePlayer.activePlayerList[i]);
- }
- }
- private void AddTrader(BasePlayer player)
- {
- if(player.GetComponent<Trader>() == null)
- player.gameObject.AddComponent<Trader>();
- }
- private void OnItemRemovedFromContainer(ItemContainer container, Item item)
- {
- Trader trader;
- if(container.playerOwner != null)
- {
- trader = Trader.GetTrader(container.playerOwner);
- if(trader != null)
- {
- trader.CheckOfferedItems();
- }
- }
- }
- private void OnPlayerDisconnected(BasePlayer player)
- {
- CancelTrade(player, s_Disconnected, s_DisconnectedOther);
- }
- private void OnEntityDeath(BaseCombatEntity entity, HitInfo hitInfo)
- {
- CancelTrade(entity as BasePlayer, s_Death, s_DeathOther);
- }
- private void OnEntityTakeDamage(BaseCombatEntity entity, HitInfo hitInfo)
- {
- CancelTrade(entity as BasePlayer, s_TookDamage, s_TookDamageOther);
- }
- #endregion
- private void CancelTrade(BasePlayer player, string message, string partnerMessage)
- {
- if(player == null)
- return;
- Trader trader = player.GetComponent<Trader>();
- TradeSession session;
- if(trader != null)
- {
- session = trader.GetTradeSession();
- if(session != null)
- {
- PrintToChat(player, message);
- PrintToChat(trader.GetOther().GetPlayer(), partnerMessage);
- session.CloseSession();
- }
- }
- }
- #region Commands
- [ChatCommand("tra")]
- private void AcceptTradeRequest(BasePlayer player, string command, string[] args)
- {
- Trader trader = player.GetComponent<Trader>();
- if (trader == null)
- return;
- TradeSession session = trader.GetTradeSession();
- if(session != null)
- session.AcceptRequest();
- }
- [ChatCommand("tro")]
- private void OfferItem(BasePlayer player, string command, string[] args)
- {
- Trader trader = player.GetComponent<Trader>();
- if(trader == null)
- return;
- TradeSession session = trader.GetTradeSession();
- if(session == null || !session.IsAccepted())
- return;
- TradeItem tradeItem;
- int amount;
- bool isAmountValid;
- ItemDefinition itemDef;
- if(args.Length == 1 || args.Length == 2)
- {
- itemDef = FindItemByDisplayName(args[0]);
- if(args.Length == 2)
- isAmountValid = int.TryParse(args[1], out amount);
- else
- {
- isAmountValid = true;
- amount = 1;
- }
- if(itemDef != null && isAmountValid)
- {
- tradeItem = new TradeItem(itemDef, amount);
- trader.OfferItem(tradeItem);
- return;
- }
- else if(itemDef == null)
- {
- PrintToChat(player, s_NoItemFound);
- return;
- }
- }
- PrintToChat(player, s_WrongOffer);
- }
- [ChatCommand("tror")]
- private void RemoveOffer(BasePlayer player, string command, string[] args)
- {
- Trader trader = Trader.GetTrader(player);
- if(trader == null)
- return;
- TradeSession session = trader.GetTradeSession();
- if(session == null)
- return;
- trader.RemoveLastOffer();
- }
- [ChatCommand("trob")]
- private void OfferBlueprint(BasePlayer player, string command, string[] args)
- {
- Trader trader = player.GetComponent<Trader>();
- if(trader == null)
- return;
- TradeSession session = trader.GetTradeSession();
- if(session == null || !session.IsAccepted())
- return;
- TradeItem tradeItem;
- ItemDefinition itemDef;
- if(args.Length == 1)
- {
- itemDef = FindItemByDisplayName(args[0]);
- if(itemDef != null)
- {
- tradeItem = new TradeItem(itemDef, 1, true);
- trader.OfferItem(tradeItem);
- }
- else
- {
- PrintToChat(player, s_NoItemFound);
- }
- return;
- }
- PrintToChat(player, s_WrongOfferBlueprint);
- }
- [ChatCommand("trd")]
- private void DeclineTrade(BasePlayer player, string command, string[] args)
- {
- Trader trader = player.GetComponent<Trader>();
- Trader other;
- if(trader == null)
- return;
- TradeSession session = trader.GetTradeSession();
- if(session != null)
- {
- other = trader.GetOther();
- session.CloseSession();
- if(other != null)
- PrintToChat(other.GetPlayer(), string.Format(s_TradeRequestDeclined, player.displayName));
- }
- }
- [ChatCommand("trl")]
- private void LockTradeOffer(BasePlayer player, string command, string[] args)
- {
- Trader trader = player.GetComponent<Trader>();
- if(trader != null && trader.GetTradeSession() != null)
- trader.AcceptTrade();
- }
- [ChatCommand("trr")]
- private void SendTradeRequest(BasePlayer player, string command, string[] args)
- {
- Trader trader = player.GetComponent<Trader>();
- BasePlayer partner = null;
- if(args.Length == 1)
- partner = GetPlayerByName(args[0]);
- else
- {
- PrintToChat(player, s_WrongTradeRequest);
- return;
- }
- if(trader != null)
- {
- if(partner == null || partner == player)
- PrintToChat(player, string.Format(s_TradeRequestNotFound, args[0]));
- else
- {
- if (player.HasPlayerFlag(BasePlayer.PlayerFlags.InBuildingPrivilege)
- || player.HasPlayerFlag(BasePlayer.PlayerFlags.HasBuildingPrivilege))
- {
- PrintToChat(player, "You can't trade because, you are in range of [Tool Cupboard]!");
- return;
- }
- if (partner.HasPlayerFlag(BasePlayer.PlayerFlags.InBuildingPrivilege)
- || partner.HasPlayerFlag(BasePlayer.PlayerFlags.HasBuildingPrivilege))
- {
- PrintToChat(player, "You can't trade because, your partner is in range of [Tool Cupboard]!");
- PrintToChat(partner, player.displayName + " tried to trade with you, but couldn't because you are in range of [Tool Cupboard]!");
- return;
- }
- trader.RequestTrade(partner);
- }
- }
- }
- #endregion
- class Trader : MonoBehaviour
- {
- private BasePlayer player;
- private TradeSession currentTradeSession;
- private float timeOfRequest;
- private float timeOfLastTrade;
- private List<TradeItem> offeredItems = new List<TradeItem>();
- private bool tradeAccepted;
- void Awake()
- {
- player = GetComponent<BasePlayer>();
- if(player == null)
- {
- Debug.LogError("Trader is not a BasePlayer");
- GameObject.Destroy(this);
- }
- }
- void Update()
- {
- if(currentTradeSession != null)
- {
- if(!IsCloseEnoughTo(GetOther()))
- {
- player.ChatMessage(s_TooFar);
- GetOther().GetPlayer().ChatMessage(s_TooFar);
- currentTradeSession.CloseSession();
- }
- if(!currentTradeSession.IsAccepted() && Time.time - timeOfRequest > timeOut)
- {
- currentTradeSession.TimeOut();
- }
- }
- }
- public BasePlayer GetPlayer()
- {
- return player;
- }
- public TradeSession GetTradeSession()
- {
- return currentTradeSession;
- }
- public List<TradeItem> GetOfferedItems()
- {
- return offeredItems;
- }
- public void SetTradeSession(TradeSession session)
- {
- currentTradeSession = session;
- }
- public bool IsCloseEnoughTo(Trader other)
- {
- if(tradeDistance <= 0)
- return true;
- Vector3 playerPos = player.transform.position;
- Vector3 otherPos = other.transform.position;
- if(Vector3.Distance(playerPos, otherPos) <= tradeDistance)
- return true;
- else
- return false;
- }
- public void RequestTrade(Trader partner)
- {
- TradeSession newTrade;
- float lastTradeTimePassed = Time.time - partner.GetTimeOfLastTrade();
- bool abort = false;
- if(lastTradeTimePassed < tradeCooldown)
- {
- player.ChatMessage(partner.GetPlayer().displayName + " cannot trade for " + (int)(tradeCooldown - lastTradeTimePassed) + " seconds");
- abort = true;
- }
- lastTradeTimePassed = Time.time - timeOfLastTrade;
- if(lastTradeTimePassed < tradeCooldown)
- {
- player.ChatMessage("You cannot trade for " + (int)(tradeCooldown - lastTradeTimePassed) + " seconds");
- abort = true;
- }
- if(abort)
- return;
- if(this.GetTradeSession() != null)
- {
- player.ChatMessage(s_TradeRequestPlayerBusy);
- return;
- }
- if(partner.GetTradeSession() != null)
- {
- player.ChatMessage(string.Format(s_TradeRequestOtherBusy, partner.GetPlayer().displayName));
- return;
- }
- partner.GetPlayer().ChatMessage(string.Format(s_TradeRequestOther, player.displayName));
- player.ChatMessage(string.Format(s_TradeRequestPlayer, partner.GetPlayer().displayName));
- timeOfRequest = Time.time;
- partner.SetTimeOfRequest(Time.time);
- newTrade = new TradeSession(this, partner);
- this.SetTradeSession(newTrade);
- partner.SetTradeSession(newTrade);
- }
- public void SetTimeOfRequest(float time)
- {
- timeOfRequest = time;
- }
- public void SetTimeOfLastTrade(float time)
- {
- timeOfLastTrade = time;
- }
- public float GetTimeOfLastTrade()
- {
- return timeOfLastTrade;
- }
- public void RequestTrade(BasePlayer partner)
- {
- Trader partnerTrader = partner.GetComponent<Trader>();
- if(partnerTrader != null)
- this.RequestTrade(partnerTrader);
- }
- public void ClearTradeSession()
- {
- tradeAccepted = false;
- offeredItems.Clear();
- currentTradeSession = null;
- DestroyTradeGUI();
- }
- public static Trader GetTrader(BasePlayer player)
- {
- if(player == null)
- return null;
- return player.GetComponent<Trader>();
- }
- public bool GetTradeAccepted()
- {
- return tradeAccepted;
- }
- private void OnItemOffered()
- {
- tradeAccepted = false;
- CuiHelper.DestroyUi(player, "PlayerAccepted");
- CuiHelper.DestroyUi(player, "OtherAccepted");
- }
- public void AcceptTrade()
- {
- if(tradeAccepted)
- return;
- Trader other = GetOther();
- tradeAccepted = true;
- CuiElementContainer playerAcceptIndicatorContainer = new CuiElementContainer();
- playerAcceptIndicatorContainer.Add(playerAcceptIndicatorGUI);
- CuiHelper.AddUi(player, playerAcceptIndicatorContainer);
- CuiElementContainer otherAcceptIndicatorContainer = new CuiElementContainer();
- otherAcceptIndicatorContainer.Add(otherAcceptIndicatorGUI);
- CuiHelper.AddUi(other.GetPlayer(), otherAcceptIndicatorContainer);
- if (tradeAccepted && other.GetTradeAccepted())
- currentTradeSession.MakeTrade();
- }
- public void OfferItem(TradeItem item)
- {
- if(this.HasItem(item))
- offeredItems.Add(item);
- else
- {
- player.ChatMessage(string.Format(s_TradeOfferFailed, item.GetItemDef().displayName.english + " " + item.GetAmount() + "x"));
- return;
- }
- currentTradeSession.GetPartner().OnItemOffered();
- currentTradeSession.GetInitiator().OnItemOffered();
- UpdateOfferGUI();
- }
- public void RemoveLastOffer()
- {
- if(currentTradeSession == null)
- return;
- if(offeredItems.Count > 0)
- offeredItems.Remove(offeredItems[offeredItems.Count-1]);
- currentTradeSession.GetPartner().OnItemOffered();
- currentTradeSession.GetInitiator().OnItemOffered();
- UpdateOfferGUI();
- }
- private bool HasItem(TradeItem item)
- {
- if(item.IsBlueprint())
- {
- Item[] items = player.inventory.AllItems();
- for(int i = 0; i < items.Length; i++)
- {
- if(items[i].info.itemid == item.GetItemDef().itemid && items[i].IsBlueprint())
- return true;
- }
- }
- else
- {
- int hasAmount;
- int tradedAmount = 0;
- hasAmount = player.inventory.GetAmount(item.GetItemDef().itemid);
- foreach(TradeItem offered in offeredItems)
- {
- if(offered.GetItemDef().itemid == item.GetItemDef().itemid)
- tradedAmount += offered.GetAmount();
- }
- if(hasAmount - tradedAmount >= item.GetAmount())
- return true;
- }
- return false;
- }
- public void CheckOfferedItems()
- {
- if(currentTradeSession == null)
- return;
- if(currentTradeSession.IsMakingTrade())
- return;
- List<TradeItem> offersToRemove = new List<TradeItem>();
- foreach(TradeItem item in offeredItems)
- {
- if(!HasItem(item))
- offersToRemove.Add(item);
- }
- foreach(TradeItem item in offersToRemove)
- {
- offeredItems.Remove(item);
- }
- UpdateOfferGUI();
- }
- private void UpdateOfferGUI()
- {
- BasePlayer other = GetOther().GetPlayer();
- string s_OfferedItems = TradeItem.ListToString(offeredItems);
- playerOfferIndicatorText.Text = otherOfferIndicatorText.Text = s_OfferedItems;
- CuiHelper.DestroyUi(player, "PlayerOfferList");
- CuiHelper.DestroyUi(other, "OtherOfferList");
- CuiElementContainer playerOfferIndicatorContainer = new CuiElementContainer();
- playerOfferIndicatorContainer.Add(playerOfferIndicatorGUI);
- CuiElementContainer otherOfferIndicatorContainer = new CuiElementContainer();
- otherOfferIndicatorContainer.Add(otherOfferIndicatorGUI);
- CuiHelper.AddUi(player, playerOfferIndicatorContainer);
- CuiHelper.AddUi(other, otherOfferIndicatorContainer);
- }
- public Trader GetOther()
- {
- if(currentTradeSession != null)
- {
- if(this.IsInitiator())
- return currentTradeSession.GetPartner();
- else
- return currentTradeSession.GetInitiator();
- }
- return null;
- }
- public bool IsInitiator()
- {
- if(currentTradeSession != null)
- {
- if(currentTradeSession.GetInitiator() == this)
- return true;
- }
- return false;
- }
- public void CreateTradeGUI()
- {
- CuiElementContainer baseTradeGUI = new CuiElementContainer();
- baseTradeGUI.Add(partnerLabelPanelGUI);
- baseTradeGUI.Add(infoPanelGUI);
- baseTradeGUI.Add(infoLabelGUI);
- baseTradeGUI.Add(tradePanelGUI);
- baseTradeGUI.Add(playerPanelGUI);
- baseTradeGUI.Add(otherPanelGUI);
- baseTradeGUI.Add(playerOfferLabelGUI);
- baseTradeGUI.Add(otherOfferLabelGUI);
- CuiPanel buttonsPanel = new CuiPanel { Image = { Color = "0 0 0 0" }, RectTransform = { AnchorMin = "0.75 0.8", AnchorMax = "0.85 0.88" } };
- CuiButton cancel = new CuiButton
- {
- Button =
- {
- Command = "tradeCancel",
- Close = "InfoPanel",
- Color = "1.0 0.0 0.0 1.0"
- },
- RectTransform =
- {
- AnchorMin = "0 0",
- AnchorMax = "1 0.4",
- },
- Text =
- {
- Text = "Decline",
- FontSize = 16,
- Align = TextAnchor.MiddleCenter
- }
- };
- CuiButton accept = new CuiButton
- {
- Button =
- {
- Command = "tradeAccept",
- Close = "InfoPanel",
- Color = "0.2 0.8 0.2 1.0"
- },
- RectTransform =
- {
- AnchorMin = "0 0.6",
- AnchorMax = "1 1",
- },
- Text =
- {
- Text = "Accept",
- FontSize = 16,
- Align = TextAnchor.MiddleCenter
- }
- };
- baseTradeGUI.Add(buttonsPanel, "HUD/Overlay", "buttonPanel");
- baseTradeGUI.Add(accept, "buttonPanel", "buttonAccept");
- baseTradeGUI.Add(cancel, "buttonPanel", "buttonDecline");
- CuiElementContainer partnerIndicatorContainer = new CuiElementContainer();
- partnerIndicatorText.Text = string.Format(s_TradePartner, GetOther().GetPlayer().displayName);
- partnerIndicatorContainer.Add(partnerIndicatorGUI);
- CuiHelper.AddUi(player, baseTradeGUI);
- CuiHelper.AddUi(player, partnerIndicatorContainer);
- }
- public void DestroyTradeGUI()
- {
- CuiHelper.DestroyUi(player, "TradePanel");
- CuiHelper.DestroyUi(player, "PlayerPanel");
- CuiHelper.DestroyUi(player, "OtherPanel");
- CuiHelper.DestroyUi(player, "InfoPanel");
- CuiHelper.DestroyUi(player, "InfoLabel");
- CuiHelper.DestroyUi(player, "PlayerAccepted");
- CuiHelper.DestroyUi(player, "OtherAccepted");
- CuiHelper.DestroyUi(player, "PlayerOfferLabel");
- CuiHelper.DestroyUi(player, "OtherOfferLabel");
- CuiHelper.DestroyUi(player, "PlayerOfferList");
- CuiHelper.DestroyUi(player, "OtherOfferList");
- CuiHelper.DestroyUi(player, "PartnerLabelPanel");
- CuiHelper.DestroyUi(player, "PartnerLabel");
- CuiHelper.DestroyUi(player, "buttonPanel");
- CuiHelper.DestroyUi(player, "buttonAccept");
- CuiHelper.DestroyUi(player, "buttonDecline");
- }
- }
- #region JSON
- public static void initGUI()
- {
- otherOfferIndicatorGUI.Components.Add(otherOfferIndicatorText);
- otherOfferIndicatorGUI.Components.Add(otherOfferIndicatorRect);
- partnerIndicatorGUI.Components.Add(partnerIndicatorText);
- partnerIndicatorGUI.Components.Add(partnerIndicatorRect);
- playerAcceptIndicatorText.Text = s_PlayerReady;
- playerAcceptIndicatorGUI.Components.Add(playerAcceptIndicatorText);
- playerAcceptIndicatorGUI.Components.Add(playerAcceptIndicatorRect);
- otherAcceptIndicatorText.Text = s_OtherReady;
- otherAcceptIndicatorGUI.Components.Add(otherAcceptIndicatorText);
- otherAcceptIndicatorGUI.Components.Add(otherAcceptIndicatorRect);
- playerOfferIndicatorGUI.Components.Add(playerOfferIndicatorText);
- playerOfferIndicatorGUI.Components.Add(playerOfferIndicatorRect);
- partnerLabelPanelGUI.Components.Add(partnerLabelPanelImage);
- partnerLabelPanelGUI.Components.Add(partnerLabelPanelRect);
- infoPanelGUI.Components.Add(infoPanelImage);
- infoPanelGUI.Components.Add(infoPanelRect);
- infoLabelGUI.Components.Add(infoLabelText);
- infoLabelGUI.Components.Add(infoLabelRect);
- tradePanelGUI.Components.Add(tradePanelImage);
- tradePanelGUI.Components.Add(tradePanelRect);
- playerPanelGUI.Components.Add(playerPanelImage);
- playerPanelGUI.Components.Add(playerPanelRect);
- otherPanelGUI.Components.Add(otherPanelImage);
- otherPanelGUI.Components.Add(otherPanelRect);
- playerOfferLabelText.Text = s_YouGive;
- playerOfferLabelGUI.Components.Add(playerOfferLabelText);
- playerOfferLabelGUI.Components.Add(playerOfferLabelRect);
- otherOfferLabelText.Text = s_YouGet;
- otherOfferLabelGUI.Components.Add(otherOfferLabelText);
- otherOfferLabelGUI.Components.Add(otherOfferLabelRect);
- }
- public static CuiElement partnerIndicatorGUI = new CuiElement { Parent = "PartnerLabelPanel", Name = "PartnerLabel", FadeOut = 0.5f };
- public static CuiTextComponent partnerIndicatorText = new CuiTextComponent { Align = TextAnchor.MiddleCenter, FadeIn = 0.5f, FontSize = 22 };
- public static CuiRectTransformComponent partnerIndicatorRect = new CuiRectTransformComponent { AnchorMin = "0 0", AnchorMax = "1 1" };
- public static CuiElement otherOfferIndicatorGUI = new CuiElement { Name = "OtherOfferList", FadeOut = 0.5f, Parent = "OtherPanel" };
- public static CuiTextComponent otherOfferIndicatorText = new CuiTextComponent { Align = TextAnchor.UpperCenter, Color = "1.0 0.4 0.0 1.0", FadeIn = 0.5f, FontSize = 20 };
- public static CuiRectTransformComponent otherOfferIndicatorRect = new CuiRectTransformComponent { AnchorMin = "0 0.1", AnchorMax = "1 0.9" };
- public static CuiElement playerAcceptIndicatorGUI = new CuiElement { Name = "PlayerAccepted", FadeOut = 0.5f, Parent = "PlayerPanel" };
- public static CuiTextComponent playerAcceptIndicatorText = new CuiTextComponent { Align = TextAnchor.LowerCenter, Color = "0.1 1.0 0.1 1.0", FadeIn = 0.5f, FontSize = 24 };
- public static CuiRectTransformComponent playerAcceptIndicatorRect = new CuiRectTransformComponent { AnchorMin = "0 0.02", AnchorMax = "1 0.2" };
- public static CuiElement otherAcceptIndicatorGUI = new CuiElement { Name = "OtherAccepted", FadeOut = 0.5f, Parent = "OtherPanel" };
- public static CuiTextComponent otherAcceptIndicatorText = new CuiTextComponent { Align = TextAnchor.LowerCenter, Color = "0.1 1.0 0.1 1.0", FadeIn = 0.5f, FontSize = 24 };
- public static CuiRectTransformComponent otherAcceptIndicatorRect = new CuiRectTransformComponent { AnchorMin = "0 0.02", AnchorMax = "1 0.2" };
- public static CuiElement playerOfferIndicatorGUI = new CuiElement { Name = "PlayerOfferList", FadeOut = 0.5f, Parent = "PlayerPanel" };
- public static CuiTextComponent playerOfferIndicatorText = new CuiTextComponent { Align = TextAnchor.UpperCenter, Color = "1.0 0.4 0.0 1.0", FadeIn = 0.5f, FontSize = 20 };
- public static CuiRectTransformComponent playerOfferIndicatorRect = new CuiRectTransformComponent { AnchorMin = "0 0.1", AnchorMax = "1 0.9" };
- private static CuiElement partnerLabelPanelGUI = new CuiElement { Name = "PartnerLabelPanel", Parent = "HUD/Overlay", FadeOut = 0.5f };
- private static CuiImageComponent partnerLabelPanelImage = new CuiImageComponent { FadeIn = 0.5f, Color = "0.5 0.5 0.5 0.5" };
- private static CuiRectTransformComponent partnerLabelPanelRect = new CuiRectTransformComponent { AnchorMin = "0.35 0.92", AnchorMax = "0.75 0.98" };
- private static CuiElement infoPanelGUI = new CuiElement { Name = "InfoPanel", Parent = "HUD/Overlay", FadeOut = 0.5f };
- private static CuiImageComponent infoPanelImage = new CuiImageComponent { FadeIn = 0.5f, Color = "0.5 0.5 0.5 0.5" };
- private static CuiRectTransformComponent infoPanelRect = new CuiRectTransformComponent { AnchorMin = "0.78 0.3", AnchorMax = "0.98 0.5" };
- /* TODO
- Remove last offer: /tror
- Lock/Accept trade offer: /trl
- Cancel trade: /trd"",
- */
- private static CuiElement infoLabelGUI = new CuiElement { Name = "InfoLabel", FadeOut = 0.5f, Parent = "InfoPanel" };
- private static CuiTextComponent infoLabelText = new CuiTextComponent { Align = TextAnchor.MiddleCenter, FadeIn = 0.5f, FontSize = 16, Text = "Chat commands:\nOffer items: /tro ''item name'' amount\nOffer blueprint: /trob ''item name''" };
- private static CuiRectTransformComponent infoLabelRect = new CuiRectTransformComponent { AnchorMin = "0 0", AnchorMax = "1 1" };
- private static CuiElement tradePanelGUI = new CuiElement { Name = "TradePanel", Parent = "HUD/Overlay", FadeOut = 0.5f };
- private static CuiImageComponent tradePanelImage = new CuiImageComponent { FadeIn = 0.5f, Color = "0.5 0.5 0.5 0.5" };
- private static CuiRectTransformComponent tradePanelRect = new CuiRectTransformComponent { AnchorMin = "0.35 0.15", AnchorMax = "0.75 0.9" };
- private static CuiElement playerPanelGUI = new CuiElement { Name = "PlayerPanel", Parent = "TradePanel", FadeOut = 0.5f };
- private static CuiImageComponent playerPanelImage = new CuiImageComponent { FadeIn = 0.5f, Color = "0.5 0.5 0.5 0.5" };
- private static CuiRectTransformComponent playerPanelRect = new CuiRectTransformComponent { AnchorMin = "0.05 0.05", AnchorMax = "0.475 0.95" };
- private static CuiElement otherPanelGUI = new CuiElement { Name = "OtherPanel", Parent = "TradePanel", FadeOut = 0.5f };
- private static CuiImageComponent otherPanelImage = new CuiImageComponent { FadeIn = 0.5f, Color = "0.5 0.5 0.5 0.5" };
- private static CuiRectTransformComponent otherPanelRect = new CuiRectTransformComponent { AnchorMin = "0.525 0.05", AnchorMax = "0.95 0.95" };
- private static CuiElement playerOfferLabelGUI = new CuiElement { Name = "PlayerOfferLabel", FadeOut = 0.5f, Parent = "PlayerPanel" };
- private static CuiTextComponent playerOfferLabelText = new CuiTextComponent { Align = TextAnchor.UpperCenter, FadeIn = 0.5f, FontSize = 24 };
- private static CuiRectTransformComponent playerOfferLabelRect = new CuiRectTransformComponent { AnchorMin = "0 0.9", AnchorMax = "1 1" };
- private static CuiElement otherOfferLabelGUI = new CuiElement { Name = "OtherOfferLabel", FadeOut = 0.5f, Parent = "OtherPanel" };
- private static CuiTextComponent otherOfferLabelText = new CuiTextComponent { Align = TextAnchor.UpperCenter, FadeIn = 0.5f, FontSize = 24 };
- private static CuiRectTransformComponent otherOfferLabelRect = new CuiRectTransformComponent { AnchorMin = "0 0.9", AnchorMax = "1 1" };
- #endregion
- class TradeSession
- {
- private Trader initiator;
- private Trader partner;
- private bool requestAccepted;
- private bool makingTrade;
- public TradeSession(Trader initiator, Trader partner)
- {
- this.initiator = initiator;
- this.partner = partner;
- }
- public void TimeOut()
- {
- initiator.GetPlayer().ChatMessage(string.Format(s_TimeOut, partner.GetPlayer().displayName));
- partner.GetPlayer().ChatMessage(s_TimeOutOther);
- CloseSession();
- }
- public void AcceptRequest()
- {
- if(requestAccepted)
- return;
- requestAccepted = true;
- initiator.CreateTradeGUI();
- partner.CreateTradeGUI();
- }
- public void CloseSession()
- {
- initiator.ClearTradeSession();
- partner.ClearTradeSession();
- }
- public bool IsMakingTrade()
- {
- return makingTrade;
- }
- public bool IsAccepted()
- {
- return requestAccepted;
- }
- public void MakeTrade()
- {
- makingTrade = true;
- List<TradeItem> initiatorOffered = initiator.GetOfferedItems();
- List<TradeItem> partnerOffered = partner.GetOfferedItems();
- TransferOffered(initiator, partner);
- TransferOffered(partner, initiator);
- if(initiatorOffered.Count > 0 || partnerOffered.Count > 0)
- {
- initiator.SetTimeOfLastTrade(Time.time);
- partner.SetTimeOfLastTrade(Time.time);
- initiator.GetPlayer().ChatMessage(s_TradeSuccessful);
- partner.GetPlayer().ChatMessage(s_TradeSuccessful);
- }
- CloseSession();
- makingTrade = false;
- }
- public static void TransferOffered(Trader from, Trader to)
- {
- int amountLeft;
- Item itemToGive;
- PlayerInventory fromInventory = from.GetPlayer().inventory;
- PlayerInventory toInventory = to.GetPlayer().inventory;
- List<TradeItem> offered = from.GetOfferedItems();
- Item[] offeredItems;
- foreach(TradeItem item in offered)
- {
- itemToGive = null;
- amountLeft = item.GetAmount();
- offeredItems = fromInventory.AllItems();
- for(int i = 0; i < offeredItems.Length; i++)
- {
- if(amountLeft <= 0)
- break;
- if(offeredItems[i].info.itemid == item.GetItemDef().itemid && item.IsBlueprint() == offeredItems[i].IsBlueprint())
- {
- itemToGive = offeredItems[i];
- if(!item.IsBlueprint())
- {
- if(offeredItems[i].amount > amountLeft)
- itemToGive = itemToGive.SplitItem(amountLeft);
- amountLeft -= itemToGive.amount;
- }
- if(!toInventory.GiveItem(itemToGive))
- {
- itemToGive.Drop(to.GetPlayer().transform.position, Vector3.zero);
- }
- }
- }
- }
- }
- public Trader GetInitiator()
- {
- return initiator;
- }
- public Trader GetPartner()
- {
- return partner;
- }
- }
- class TradeItem
- {
- private ItemDefinition itemDef;
- private int amount;
- private bool isBlueprint;
- private bool isMoney;
- public TradeItem(ItemDefinition itemDef, int amount, bool isBlueprint = false, bool isMoney = false)
- {
- this.itemDef = itemDef;
- this.amount = amount;
- this.isBlueprint = isBlueprint;
- this.isMoney = isMoney;
- }
- public ItemDefinition GetItemDef()
- {
- return itemDef;
- }
- public int GetAmount()
- {
- return amount;
- }
- public bool IsBlueprint()
- {
- return isBlueprint;
- }
- public bool IsMoney()
- {
- return isMoney;
- }
- public static string ListToString(List<TradeItem> itemList)
- {
- string str = "";
- foreach(TradeItem item in itemList)
- {
- if(!item.IsMoney())
- str = str + item.GetItemDef().displayName.english;
- else
- str = str + "Money";
- if(item.IsBlueprint())
- {
- str = str + "(Blueprint)\n";
- }
- else
- {
- str = str + "("+item.GetAmount()+"x)\n";
- }
- }
- return str;
- }
- }
- private ItemDefinition FindItemByDisplayName(string name)
- {
- List<ItemDefinition> itemList = ItemManager.GetItemDefinitions();
- ItemDefinition foundItem = null;
- name = name.ToLower();
- string current;
- string last;
- foreach(ItemDefinition item in itemList)
- {
- current = item.displayName.english.ToLower();
- if(current.Contains(name))
- {
- if(foundItem != null)
- {
- last = foundItem.displayName.english.ToLower();
- if(last.Replace(name, "").Length > current.Replace(name, "").Length)
- {
- foundItem = item;
- }
- }
- else
- foundItem = item;
- }
- }
- return foundItem;
- }
- private BasePlayer GetPlayerByName(string name)
- {
- string currentName;
- string lastName;
- BasePlayer foundPlayer = null;
- name = name.ToLower();
- foreach(BasePlayer player in BasePlayer.activePlayerList)
- {
- currentName = player.displayName.ToLower();
- if(currentName.Contains(name))
- {
- if(foundPlayer != null)
- {
- lastName = foundPlayer.displayName;
- if(currentName.Replace(name, "").Length < lastName.Replace(name, "").Length)
- {
- foundPlayer = player;
- }
- }
- foundPlayer = player;
- }
- }
- return foundPlayer;
- }
- [ConsoleCommand("tradeAccept")]
- private void tradeAccept(ConsoleSystem.Arg arg)
- {
- var player = arg.connection.player as BasePlayer;
- if (player == null)
- return;
- Trader trader = player.GetComponent<Trader>();
- if (trader != null && trader.GetTradeSession() != null)
- {
- if (player.HasPlayerFlag(BasePlayer.PlayerFlags.InBuildingPrivilege)
- || player.HasPlayerFlag(BasePlayer.PlayerFlags.HasBuildingPrivilege))
- {
- CancelTrade(player, "You are too close to [Tool Cupboard]. Trade canceled.", "Your partner is too close to [Tool Cupboard]. Trace canceled.");
- return;
- }
- var partner = trader.GetTradeSession().GetPartner().GetPlayer();
- if (partner.HasPlayerFlag(BasePlayer.PlayerFlags.InBuildingPrivilege)
- || partner.HasPlayerFlag(BasePlayer.PlayerFlags.HasBuildingPrivilege))
- {
- CancelTrade(partner, "You are too close to [Tool Cupboard]. Trade canceled.", "Your partner is too close to [Tool Cupboard]. Trace canceled.");
- return;
- }
- trader.AcceptTrade();
- }
- }
- [ConsoleCommand("tradeCancel")]
- private void tradeCancel(ConsoleSystem.Arg arg)
- {
- var player = arg.connection.player as BasePlayer;
- if (player == null)
- return;
- Trader trader = player.GetComponent<Trader>();
- Trader other;
- if (trader == null)
- return;
- TradeSession session = trader.GetTradeSession();
- if (session != null)
- {
- other = trader.GetOther();
- session.CloseSession();
- if (other != null)
- PrintToChat(other.GetPlayer(), string.Format(s_TradeRequestDeclined, player.displayName));
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement