Koenrad

GuiShop

Oct 27th, 2015
715
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 34.75 KB | None | 0 0
  1. //Reference: NLua
  2.  
  3. using System.Collections.Generic;
  4. using System;
  5. using System.Linq;
  6.  
  7. using NLua;
  8.  
  9. using Oxide.Core;
  10. using Oxide.Core.Plugins;
  11. using Oxide.Game.Rust.Cui;
  12.  
  13. using UnityEngine;
  14.  
  15. namespace Oxide.Plugins
  16. {
  17.     [Info("GUIShop", "Reneb & Nogrod", "1.1.1", ResourceId = 1319)]
  18.     class GUIShop : RustPlugin
  19.     {
  20.         private const string ShopOverlayName = "ShopOverlay";
  21.         int playersMask;
  22.  
  23.         //////////////////////////////////////////////////////////////////////////////////////
  24.         // References ////////////////////////////////////////////////////////////////////////
  25.         //////////////////////////////////////////////////////////////////////////////////////
  26.  
  27.         [PluginReference("00-Economics")]
  28.         Plugin Economics;
  29.  
  30.         [PluginReference]
  31.         Plugin Kits;
  32.  
  33.         //////////////////////////////////////////////////////////////////////////////////////
  34.         // Workaround the Blocks of Economics. Hope This wont be needed in the future
  35.         // THX MUGHISI ///////////////////////////////////////////////////////////////////////
  36.         //////////////////////////////////////////////////////////////////////////////////////
  37.          
  38.         private readonly Dictionary<string, LuaFunction> EconomyApi = new Dictionary<string, LuaFunction>();
  39.         void OnServerInitialized()
  40.         {
  41.             InitializeTable();
  42.             if (!Economics)
  43.             {
  44.                 PrintWarning("Economics plugin not found. " + this.Name + "will not function!");
  45.                 return;
  46.             }
  47.             var apiFuncs = (LuaTable)Economics.Call("GetEconomyAPI");
  48.             foreach (KeyValuePair<object, object> method in apiFuncs)
  49.             {
  50.                 var value = method.Value as LuaFunction;
  51.                 if (value != null) EconomyApi.Add(method.Key.ToString(), value);
  52.             }
  53.         }
  54.  
  55.         //////////////////////////////////////////////////////////////////////////////////////
  56.         // Configs Manager ///////////////////////////////////////////////////////////////////
  57.         //////////////////////////////////////////////////////////////////////////////////////
  58.  
  59.         void LoadDefaultConfig() { }
  60.  
  61.         private void CheckCfg<T>(string Key, ref T var)
  62.         {
  63.             if (Config[Key] is T)
  64.                 var = (T)Config[Key];
  65.             else
  66.                 Config[Key] = var;
  67.         }
  68.  
  69.         private static Dictionary<string, object> ShopCategories = DefaultShopCategories();
  70.         private static Dictionary<string, object> Shops = DefaultShops();
  71.  
  72.         static string MessageShowNoEconomics = "Couldn't get informations out of Economics. Is it installed?";
  73.         static string MessageBought = "You've successfully bought {0}x {1}";
  74.         static string MessageSold = "You've successfully sold {0}x {1}";
  75.         static string MessageErrorNoShop = "This shop doesn't seem to exist.";
  76.         static string MessageErrorNoActionShop = "You are not allowed to {0} in this shop";
  77.         static string MessageErrorNoNPC = "The NPC owning this shop was not found around you";
  78.         static string MessageErrorNoActionItem = "You are not allowed to {0} this item here";
  79.         static string MessageErrorItemItem = "WARNING: The admin didn't set this item properly! (item)";
  80.         static string MessageErrorItemNoValid = "WARNING: It seems like it's not a valid item";
  81.         static string MessageErrorRedeemKit = "WARNING: There was an error while giving you this kit";
  82.         static string MessageErrorBuyPrice = "WARNING: No buy price was given by the admin, you can't buy this item";
  83.         static string MessageErrorSellPrice = "WARNING: No sell price was given by the admin, you can't sell this item";
  84.         static string MessageErrorNotEnoughMoney = "You need {0} coins to buy {1} of {2}";
  85.         static string MessageErrorNotEnoughSell = "You don't have enough of this item.";
  86.         static string MessageErrorItemNoExist = "WARNING: The item you are trying to buy doesn't seem to exist";
  87.         static string MessageErrorNPCRange = "You may not use the chat shop. You might need to find the NPC Shops.";
  88.  
  89.         void Init()
  90.         {
  91.             CheckCfg("Shop - Shop Categories", ref ShopCategories);
  92.             CheckCfg("Shop - Shop List", ref Shops);
  93.             CheckCfg("Message - Error - No Econonomics", ref MessageShowNoEconomics);
  94.             CheckCfg("Message - Bought", ref MessageBought);
  95.             CheckCfg("Message - Sold", ref MessageSold);
  96.             CheckCfg("Message - Error - No Shop", ref MessageErrorNoShop);
  97.             CheckCfg("Message - Error - No Action In Shop", ref MessageErrorNoActionShop);
  98.             CheckCfg("Message - Error - No NPC", ref MessageErrorNoNPC);
  99.             CheckCfg("Message - Error - No Action Item", ref MessageErrorNoActionItem);
  100.             CheckCfg("Message - Error - Item Not Set Properly", ref MessageErrorItemItem);
  101.             CheckCfg("Message - Error - Item Not Valid", ref MessageErrorItemNoValid);
  102.             CheckCfg("Message - Error - Redeem Kit", ref MessageErrorRedeemKit);
  103.             CheckCfg("Message - Error - No Buy Price", ref MessageErrorBuyPrice);
  104.             CheckCfg("Message - Error - No Sell Price", ref MessageErrorSellPrice);
  105.             CheckCfg("Message - Error - Not Enough Money", ref MessageErrorNotEnoughMoney);
  106.             CheckCfg("Message - Error - Not Enough Items", ref MessageErrorNotEnoughSell);
  107.             CheckCfg("Message - Error - Item Doesnt Exist", ref MessageErrorItemNoExist);
  108.             CheckCfg("Message - Error - No Chat Shop", ref MessageErrorNPCRange);
  109.             SaveConfig();
  110.         }
  111.  
  112.         //////////////////////////////////////////////////////////////////////////////////////
  113.         // Default Shops for Tutorial purpoise ///////////////////////////////////////////////
  114.         //////////////////////////////////////////////////////////////////////////////////////
  115.         static Dictionary<string, object> DefaultShops()
  116.         {
  117.             var shops = new Dictionary<string, object>
  118.             {
  119.                 {
  120.                     "chat", new Dictionary<string, object>
  121.                     {
  122.                         {"buy", new List<object> {"Build Kit"}},
  123.                         {"description", "You currently have {0} coins to spend in this builders shop"},
  124.                         {"name", "Build"}
  125.                     }
  126.                 },
  127.                 {
  128.                     "5498734", new Dictionary<string, object>
  129.                     {
  130.                         {"description", "You currently have {0} coins to spend in this weapons shop"},
  131.                         {"name", "Weaponsmith Shop"},
  132.                         {"buy", new List<object> {"Assault Rifle", "Bolt Action Rifle"}},
  133.                         {"sell", new List<object> {"Assault Rifle", "Bolt Action Rifle"}}
  134.                     }
  135.                 },
  136.                 {
  137.                     "1234567", new Dictionary<string, object>
  138.                     {
  139.                         {"description", "You currently have {0} coins to spend in this farmers market"},
  140.                         {"name", "Fruit Market"},
  141.                         {"buy", new List<object> {"Apple", "BlueBerries", "Assault Rifle", "Bolt Action Rifle"}},
  142.                         {"sell", new List<object> {"Apple", "BlueBerries", "Assault Rifle", "Bolt Action Rifle"}}
  143.                     }
  144.                 }
  145.             };
  146.             return shops;
  147.         }
  148.         static Dictionary<string, object> DefaultShopCategories()
  149.         {
  150.             var dsc = new Dictionary<string, object>
  151.             {
  152.                 {
  153.                     "Assault Rifle", new Dictionary<string, object>
  154.                     {
  155.                         {"item", "assault rifle"},
  156.                         {"buy", "10"},
  157.                         {"sell", "8"},
  158.                         {"img", "http://vignette3.wikia.nocookie.net/play-rust/images/d/d1/Assault_Rifle_icon.png/revision/latest/scale-to-width-down/100?cb=20150405105940"}
  159.                     }
  160.                 },
  161.                 {
  162.                     "Bolt Action Rifle", new Dictionary<string, object>
  163.                     {
  164.                         {"item", "bolt action rifle"},
  165.                         {"buy", "10"}, {"sell", "8"},
  166.                         {"img", "http://vignette1.wikia.nocookie.net/play-rust/images/5/55/Bolt_Action_Rifle_icon.png/revision/latest/scale-to-width-down/100?cb=20150405111457"}
  167.                     }
  168.                 },
  169.                 {
  170.                     "Build Kit", new Dictionary<string, object>
  171.                     {
  172.                         {"item", "kitbuild"},
  173.                         {"buy", "10"},
  174.                         {"sell", "8"},
  175.                         {"img", "http://oxidemod.org/data/resource_icons/0/715.jpg?1425682952"}
  176.                     }
  177.                 },
  178.                 {
  179.                     "Apple", new Dictionary<string, object>
  180.                     {
  181.                         {"item", "apple"},
  182.                         {"buy", "1"},
  183.                         {"sell", "1"},
  184.                         {"img", "http://vignette2.wikia.nocookie.net/play-rust/images/d/dc/Apple_icon.png/revision/latest/scale-to-width-down/100?cb=20150405103640"}
  185.                     }
  186.                 },
  187.                 {
  188.                     "BlueBerries", new Dictionary<string, object>
  189.                     {
  190.                         {"item", "blueberries"},
  191.                         {"buy", "1"},
  192.                         {"sell", "1"},
  193.                         {"img", "http://vignette1.wikia.nocookie.net/play-rust/images/f/f8/Blueberries_icon.png/revision/latest/scale-to-width-down/100?cb=20150405111338"}
  194.                     }
  195.                 }
  196.             };
  197.             return dsc;
  198.         }
  199.  
  200.  
  201.  
  202.         //////////////////////////////////////////////////////////////////////////////////////
  203.         // Item Management ///////////////////////////////////////////////////////////////////
  204.         //////////////////////////////////////////////////////////////////////////////////////
  205.         readonly Dictionary<string, string> displaynameToShortname = new Dictionary<string, string>();
  206.         private void InitializeTable()
  207.         {
  208.             displaynameToShortname.Clear();
  209.             var ItemsDefinition = ItemManager.itemList;
  210.             foreach (var itemdef in ItemsDefinition)
  211.             {
  212.                 displaynameToShortname.Add(itemdef.displayName.english.ToLower(), itemdef.shortname);
  213.             }
  214.         }
  215.  
  216.         //////////////////////////////////////////////////////////////////////////////////////
  217.         // Oxide Hooks ///////////////////////////////////////////////////////////////////////
  218.         //////////////////////////////////////////////////////////////////////////////////////
  219.  
  220.         void Loaded()
  221.         {
  222.             playersMask = LayerMask.GetMask("Player (Server)");
  223.         }
  224.  
  225.         void OnUseNPC(BasePlayer npc, BasePlayer player)
  226.         {
  227.             if (!Shops.ContainsKey(npc.userID.ToString())) return;
  228.             ShowShop(player, npc.userID.ToString(), 0);
  229.         }
  230.  
  231.         //////////////////////////////////////////////////////////////////////////////////////
  232.         // GUI ///////////////////////////////////////////////////////////////////////////////
  233.         //////////////////////////////////////////////////////////////////////////////////////
  234.  
  235.         private static CuiElementContainer CreateShopOverlay(string shopname)
  236.         {
  237.             return new CuiElementContainer
  238.             {
  239.                 {
  240.                     new CuiPanel
  241.                     {
  242.                         Image = {Color = "0.1 0.1 0.1 0.8"},
  243.                         RectTransform = {AnchorMin = "0 0", AnchorMax = "1 1"},
  244.                         CursorEnabled = true
  245.                     },
  246.                     new CuiElement().Parent,
  247.                     ShopOverlayName
  248.                 },
  249.                 {
  250.                     new CuiLabel
  251.                     {
  252.                         Text = {Text = shopname, FontSize = 30, Align = TextAnchor.MiddleCenter},
  253.                         RectTransform = {AnchorMin = "0.3 0.8", AnchorMax = "0.7 0.9"}
  254.                     },
  255.                     ShopOverlayName
  256.                 },
  257.                 {
  258.                     new CuiLabel
  259.                     {
  260.                         Text = {Text = "Item", FontSize = 20, Align = TextAnchor.MiddleLeft},
  261.                         RectTransform = {AnchorMin = "0.2 0.6", AnchorMax = "0.4 0.65"}
  262.                     },
  263.                     ShopOverlayName
  264.                 },
  265.                 {
  266.                     new CuiLabel
  267.                     {
  268.                         Text = {Text = "Buy", FontSize = 20, Align = TextAnchor.MiddleLeft},
  269.                         RectTransform = {AnchorMin = "0.55 0.6", AnchorMax = "0.7 0.65"}
  270.                     },
  271.                     ShopOverlayName
  272.                 },
  273.                 {
  274.                     new CuiLabel
  275.                     {
  276.                         Text = {Text = "Sell", FontSize = 20, Align = TextAnchor.MiddleLeft},
  277.                         RectTransform = {AnchorMin = "0.75 0.6", AnchorMax = "0.9 0.65"}
  278.                     },
  279.                     ShopOverlayName
  280.                 },
  281.                 {
  282.                     new CuiButton
  283.                     {
  284.                         Button = {Close = ShopOverlayName, Color = "0.5 0.5 0.5 0.2"},
  285.                         RectTransform = {AnchorMin = "0.5 0.15", AnchorMax = "0.7 0.2"},
  286.                         Text = {Text = "Close", FontSize = 20, Align = TextAnchor.MiddleCenter}
  287.                     },
  288.                     ShopOverlayName
  289.                 }
  290.             };
  291.         }
  292.  
  293.         private readonly CuiLabel shopDescription = new CuiLabel
  294.         {
  295.             Text = { Text = "{shopdescription}", FontSize = 15, Align = TextAnchor.MiddleCenter },
  296.             RectTransform = { AnchorMin = "0.2 0.7", AnchorMax = "0.8 0.79" }
  297.         };
  298.  
  299.         private static CuiElementContainer CreateShopItemEntry(string price, float ymax, float ymin, string shop, string item, string color, bool sell = false)
  300.         {
  301.             var container = new CuiElementContainer
  302.             {
  303.                 {
  304.                     new CuiLabel
  305.                     {
  306.                         Text = {Text = price, FontSize = 15, Align = TextAnchor.UpperLeft},
  307.                         RectTransform = {AnchorMin = $"{(sell ? 0.75 : 0.55)} {ymin}", AnchorMax = $"{(sell ? 0.78 : 0.6)} {ymax}"}
  308.                     },
  309.                     ShopOverlayName
  310.                 }
  311.             };
  312.             var steps = new[] { 1, 10, 100, 1000 };
  313.             for (var i = 0; i < steps.Length; i++)
  314.             {
  315.                 container.Add(new CuiButton
  316.                 {
  317.                     Button = { Command = $"shop.{(sell ? "sell" : "buy")} {shop} {item} {steps[i]}", Color = color },
  318.                     RectTransform = { AnchorMin = $"{(sell ? 0.8 : 0.6) + i * 0.03} {ymin}", AnchorMax = $"{(sell ? 0.83 : 0.63) + i * 0.03} {ymax}" },
  319.                     Text = { Text = steps[i].ToString(), FontSize = 15, Align = TextAnchor.MiddleCenter }
  320.                 }, ShopOverlayName);
  321.             }
  322.             return container;
  323.         }
  324.  
  325.         private static CuiElementContainer CreateShopItemIcon(string name, float ymax, float ymin, string url)
  326.         {
  327.             var rawImage = new CuiRawImageComponent();
  328.             if (url.StartsWith("http"))
  329.                 rawImage.Url = url;
  330.             else
  331.                 rawImage.Sprite = url;
  332.             var container = new CuiElementContainer
  333.             {
  334.                 {
  335.                     new CuiLabel
  336.                     {
  337.                         Text = {Text = name, FontSize = 15, Align = TextAnchor.UpperLeft},
  338.                         RectTransform = {AnchorMin = $"0.2 {ymin}", AnchorMax = $"0.4 {ymax}"}
  339.                     },
  340.                     ShopOverlayName
  341.                 },
  342.                 new CuiElement
  343.                 {
  344.                     Parent = ShopOverlayName,
  345.                     Components =
  346.                     {
  347.                         rawImage,
  348.                         new CuiRectTransformComponent {AnchorMin = $"0.1 {ymin}", AnchorMax = $"0.13 {ymax}"}
  349.                     }
  350.                 }
  351.             };
  352.             return container;
  353.         }
  354.  
  355.         private static CuiElementContainer CreateShopChangePage(string currentshop, int shoppageminus, int shoppageplus)
  356.         {
  357.             return new CuiElementContainer
  358.             {
  359.                 {
  360.                     new CuiButton
  361.                     {
  362.                         Button = {Command = $"shop.show {currentshop} {shoppageminus}", Color = "0.5 0.5 0.5 0.2"},
  363.                         RectTransform = {AnchorMin = "0.2 0.15", AnchorMax = "0.3 0.2"},
  364.                         Text = {Text = "<<", FontSize = 20, Align = TextAnchor.MiddleCenter}
  365.                     },
  366.                     ShopOverlayName
  367.                 },
  368.                 {
  369.                     new CuiButton
  370.                     {
  371.                         Button = {Command = $"shop.show {currentshop} {shoppageplus}", Color = "0.5 0.5 0.5 0.2"},
  372.                         RectTransform = {AnchorMin = "0.35 0.15", AnchorMax = "0.45 0.2"},
  373.                         Text = {Text = ">>", FontSize = 20, Align = TextAnchor.MiddleCenter}
  374.                     },
  375.                     ShopOverlayName
  376.                 }
  377.             };
  378.         }
  379.  
  380.         readonly Hash<ulong, int> shopPage = new Hash<ulong, int>();
  381.         void ShowShop(BasePlayer player, string shopid, int from = 0, bool fullRefresh = true)
  382.         {
  383.             shopPage[player.userID] = from;
  384.             if (!Shops.ContainsKey(shopid))
  385.             {
  386.                 SendReply(player, MessageErrorNoShop);
  387.                 return;
  388.             }
  389.             object playerData = EconomyApi["GetUserData"].Call("GetUserData", player.userID.ToString());
  390.             if (playerData == null)
  391.             {
  392.                 SendReply(player, MessageShowNoEconomics);
  393.                 return;
  394.             }
  395.             var table = (LuaTable)(((object[])playerData)[0]);
  396.             var playerCoins = Convert.ToInt32(table[1]);
  397.  
  398.             var shop = (Dictionary<string, object>)Shops[shopid];
  399.  
  400.             shopDescription.Text.Text = string.Format((string)shop["description"], playerCoins);
  401.  
  402.             if (!fullRefresh)
  403.             {
  404.                 CuiHelper.DestroyUi(player, "ShopDescOverlay");
  405.                 CuiHelper.AddUi(player, new CuiElementContainer { { shopDescription, ShopOverlayName, "ShopDescOverlay" } });
  406.                 return;
  407.             }
  408.             CuiHelper.DestroyUi(player, ShopOverlayName);
  409.             var container = CreateShopOverlay((string)shop["name"]);
  410.             container.Add(shopDescription, ShopOverlayName, "ShopDescOverlay");
  411.             if (from < 0)
  412.             {
  413.                 CuiHelper.AddUi(player, container);
  414.                 return;
  415.             }
  416.  
  417.             var itemslist = new Dictionary<string, Dictionary<string, bool>>();
  418.             if (shop.ContainsKey("buy"))
  419.             {
  420.                 foreach (string itemname in (List<object>)shop["buy"])
  421.                 {
  422.                     Dictionary<string, bool> itemEntry;
  423.                     if (!itemslist.TryGetValue(itemname, out itemEntry))
  424.                         itemslist[itemname] = itemEntry = new Dictionary<string, bool>();
  425.                     itemEntry["buy"] = true;
  426.                 }
  427.             }
  428.             if (shop.ContainsKey("sell"))
  429.             {
  430.                 foreach (string itemname in (List<object>)shop["sell"])
  431.                 {
  432.                     Dictionary<string, bool> itemEntry;
  433.                     if (!itemslist.TryGetValue(itemname, out itemEntry))
  434.                         itemslist[itemname] = itemEntry = new Dictionary<string, bool>();
  435.                     itemEntry["sell"] = true;
  436.                 }
  437.             }
  438.             var current = 0;
  439.             foreach (var pair in itemslist)
  440.             {
  441.                 if (!ShopCategories.ContainsKey(pair.Key)) continue;
  442.  
  443.                 if (current >= from && current < from + 7)
  444.                 {
  445.                     var itemdata = (Dictionary<string, object>)ShopCategories[pair.Key];
  446.                     var pos = 0.55f - 0.05f * (current - from);
  447.  
  448.                     container.AddRange(CreateShopItemIcon(pair.Key, pos + 0.05f, pos, (string)itemdata["img"]));
  449.                     if (pair.Value.ContainsKey("buy"))
  450.                         container.AddRange(CreateShopItemEntry((string)itemdata["buy"], pos + 0.05f, pos, $"'{shopid}'", $"'{pair.Key}'", "0 0.6 0 0.1"));
  451.                     if (pair.Value.ContainsKey("sell"))
  452.                         container.AddRange(CreateShopItemEntry((string)itemdata["sell"], pos + 0.05f, pos, $"'{shopid}'", $"'{pair.Key}'", "1 0 0 0.1", true));
  453.                 }
  454.                 current++;
  455.             }
  456.             var minfrom = from <= 7 ? 0 : from - 7;
  457.             var maxfrom = from + 7 >= current ? from : from + 7;
  458.             container.AddRange(CreateShopChangePage(shopid, minfrom, maxfrom));
  459.             CuiHelper.AddUi(player, container);
  460.         }
  461.         //////////////////////////////////////////////////////////////////////////////////////
  462.         // Shop Functions ////////////////////////////////////////////////////////////////////
  463.         //////////////////////////////////////////////////////////////////////////////////////
  464.  
  465.         object CanDoAction(BasePlayer player, string shop, string item, string ttype)
  466.         {
  467.             var shopdata = (Dictionary<string, object>)Shops[shop];
  468.             if (!shopdata.ContainsKey(ttype))
  469.             {
  470.                 return string.Format(MessageErrorNoActionShop, ttype);
  471.             }
  472.             var actiondata = (List<object>)shopdata[ttype];
  473.             if (!actiondata.Contains(item))
  474.             {
  475.                 return string.Format(MessageErrorNoActionItem, ttype);
  476.             }
  477.             return true;
  478.         }
  479.  
  480.         bool CanFindNPC(Vector3 pos, string npcid)
  481.         {
  482.             return Physics.OverlapSphere(pos, 3f, playersMask).Select(col => col.GetComponentInParent<BasePlayer>()).Any(player => player != null && player.userID.ToString() == npcid);
  483.         }
  484.  
  485.         object CanShop(BasePlayer player, string shopname)
  486.         {
  487.             if (!Shops.ContainsKey(shopname))
  488.             {
  489.                 return MessageErrorNoShop;
  490.             }
  491.             if (shopname != "chat" && !CanFindNPC(player.transform.position, shopname))
  492.             {
  493.                 return MessageErrorNoNPC;
  494.             }
  495.             return true;
  496.         }
  497.  
  498.         //////////////////////////////////////////////////////////////////////////////////////
  499.         // Buy Functions /////////////////////////////////////////////////////////////////////
  500.         //////////////////////////////////////////////////////////////////////////////////////
  501.  
  502.         object TryShopBuy(BasePlayer player, string shop, string item, int amount)
  503.         {
  504.             object success = CanShop(player, shop);
  505.             if (success is string)
  506.             {
  507.                 return success;
  508.             }
  509.             success = CanDoAction(player, shop, item, "buy");
  510.             if (success is string)
  511.             {
  512.                 return success;
  513.             }
  514.             success = CanBuy(player, item, amount);
  515.             if (success is string)
  516.             {
  517.                 return success;
  518.             }
  519.             success = TryGive(player, item, amount);
  520.             if (success is string)
  521.             {
  522.                 return success;
  523.             }
  524.             var itemdata = ShopCategories[item] as Dictionary<string, object>;
  525.            // Economics.Call("Withdraw", player, Convert.ToInt32(itemdata["buy"]) * amount);
  526.             return true;
  527.         }
  528.         object TryGive(BasePlayer player, string item, int amount)
  529.         {
  530.             var itemdata = (Dictionary<string, object>)ShopCategories[item];
  531.  
  532.             if (itemdata.ContainsKey("cmd"))
  533.             {
  534.                 var cmds = (List<object>)itemdata["cmd"];
  535.                 foreach (var cmd in cmds)
  536.                 {
  537.                     ConsoleSystem.Run.Server.Normal(cmd.ToString()
  538.                                                                 .Replace("$player.id", player.userID.ToString())
  539.                                                                 .Replace("$player.name", player.displayName)
  540.                                                                 .Replace("$player.x", player.transform.position.x.ToString())
  541.                                                                 .Replace("$player.y", player.transform.position.y.ToString())
  542.                                                                 .Replace("$player.z", player.transform.position.z.ToString()));
  543.                 }
  544.             }
  545.             if (itemdata.ContainsKey("item"))
  546.             {
  547.                 string itemname = itemdata["item"].ToString();
  548.                 object iskit = Kits?.Call("isKit", itemname);
  549.  
  550.                 if (iskit is bool && (bool)iskit)
  551.                 {
  552.                     object successkit = Kits.Call("GiveKit", player, itemname);
  553.                     if (successkit is bool && !(bool)successkit)
  554.                     {
  555.                         return MessageErrorRedeemKit;
  556.                     }
  557.                     return true;
  558.                 }
  559.                 object success = GiveItem(player, itemname, amount, player.inventory.containerMain);
  560.                 if (success is string)
  561.                 {
  562.                     return success;
  563.                 }
  564.             }
  565.             return true;
  566.         }
  567.  
  568.         private object GiveItem(BasePlayer player, string itemname, int amount, ItemContainer pref)
  569.         {
  570.             itemname = itemname.ToLower();
  571.  
  572.             bool isBP = false;
  573.             if (itemname.EndsWith(" bp"))
  574.             {
  575.                 isBP = true;
  576.                 itemname = itemname.Substring(0, itemname.Length - 3);
  577.             }
  578.             if (displaynameToShortname.ContainsKey(itemname))
  579.                 itemname = displaynameToShortname[itemname];
  580.             var definition = ItemManager.FindItemDefinition(itemname);
  581.             if (definition == null)
  582.                 return MessageErrorItemNoExist;
  583.             int stack = definition.stackable;
  584.             if (isBP)
  585.                 stack = 1;
  586.             if (stack < 1) stack = 1;
  587.             for (var i = amount; i > 0; i = i - stack)
  588.             {
  589.                 var giveamount = i >= stack ? stack : i;
  590.                 if (giveamount < 1) return true;
  591.                 player.inventory.GiveItem(ItemManager.CreateByItemID(definition.itemid, giveamount, isBP), pref);
  592.             }
  593.             return true;
  594.         }
  595.         object CanBuy(BasePlayer player, string item, int amount)
  596.         {
  597.             object playerData = EconomyApi["GetUserData"].Call("GetUserData", player.userID.ToString());
  598.             if (playerData == null)
  599.             {
  600.                 return MessageShowNoEconomics;
  601.             }
  602.             var table = (LuaTable)(((object[])playerData)[0]);
  603.             var playerCoins = Convert.ToInt32(table[1]);
  604.             if (!ShopCategories.ContainsKey(item))
  605.             {
  606.                 return MessageErrorItemNoValid;
  607.             }
  608.  
  609.             var itemdata = (Dictionary<string, object>)ShopCategories[item];
  610.             if (!itemdata.ContainsKey("buy"))
  611.             {
  612.                 return MessageErrorBuyPrice;
  613.             }
  614.             var buyprice = Convert.ToInt32(itemdata["buy"]);
  615.            
  616.                     object success = TakeItem(player, "note", buyprice * amount);
  617.             if (success is string)
  618.             {
  619.                 return string.Format(MessageErrorNotEnoughMoney, (buyprice * amount).ToString(), amount.ToString(), item);
  620.             }
  621.             return true;
  622.         }
  623.         //////////////////////////////////////////////////////////////////////////////////////
  624.         // Sell Functions ////////////////////////////////////////////////////////////////////
  625.         //////////////////////////////////////////////////////////////////////////////////////
  626.  
  627.         object TryShopSell(BasePlayer player, string shop, string item, int amount)
  628.         {
  629.             object success = CanShop(player, shop);
  630.             if (success is string)
  631.             {
  632.                 return success;
  633.             }
  634.             success = CanDoAction(player, shop, item, "sell");
  635.             if (success is string)
  636.             {
  637.                 return success;
  638.             }
  639.             success = CanSell(player, item, amount);
  640.             if (success is string)
  641.             {
  642.                 return success;
  643.             }
  644.             success = TrySell(player, item, amount);
  645.             if (success is string)
  646.             {
  647.                 return success;
  648.             }
  649.             var itemdata = (Dictionary<string, object>)ShopCategories[item];
  650.             GiveItem(player, "note", Convert.ToInt32(itemdata["sell"]) * amount, player.inventory.containerMain );
  651.            // Economics.Call("Deposit", player, Convert.ToInt32(itemdata["sell"]) * amount);
  652.             return true;
  653.         }
  654.         object TrySell(BasePlayer player, string item, int amount)
  655.         {
  656.             var itemdata = (Dictionary<string, object>)ShopCategories[item];
  657.             if (!itemdata.ContainsKey("item"))
  658.             {
  659.                 return MessageErrorItemItem;
  660.             }
  661.             string itemname = itemdata["item"].ToString();
  662.             object iskit = Kits?.Call("isKit", itemname);
  663.  
  664.             if (iskit is bool && (bool)iskit)
  665.             {
  666.                 return "You can't sell kits";
  667.             }
  668.             object success = TakeItem(player, itemname, amount);
  669.             if (success is string)
  670.             {
  671.                 return success;
  672.             }
  673.             return true;
  674.         }
  675.         private object TakeItem(BasePlayer player, string itemname, int amount)
  676.         {
  677.             itemname = itemname.ToLower();
  678.  
  679.             bool isBP = false;
  680.             if (itemname.EndsWith(" bp"))
  681.             {
  682.                 //isBP = true;
  683.                 //itemname = itemname.Substring(0, itemname.Length - 3);
  684.                 return "You can't sell blueprints";
  685.             }
  686.             if (displaynameToShortname.ContainsKey(itemname))
  687.                 itemname = displaynameToShortname[itemname];
  688.             var definition = ItemManager.FindItemDefinition(itemname);
  689.             if (definition == null)
  690.                 return MessageErrorItemNoExist;
  691.  
  692.             int pamount = player.inventory.GetAmount(definition.itemid);
  693.             if (pamount < amount)
  694.             {
  695.                 return MessageErrorNotEnoughSell;
  696.             }
  697.  
  698.             player.inventory.Take(null, definition.itemid, amount);
  699.             return true;
  700.         }
  701.         object CanSell(BasePlayer player, string item, int amount)
  702.         {
  703.             if (!ShopCategories.ContainsKey(item))
  704.             {
  705.                 return MessageErrorItemNoValid;
  706.             }
  707.             var itemdata = (Dictionary<string, object>)ShopCategories[item];
  708.             if (!itemdata.ContainsKey("sell"))
  709.             {
  710.                 return MessageErrorSellPrice;
  711.             }
  712.             return true;
  713.         }
  714.         //////////////////////////////////////////////////////////////////////////////////////
  715.         // Chat Commands /////////////////////////////////////////////////////////////////////
  716.         //////////////////////////////////////////////////////////////////////////////////////
  717.         [ChatCommand("shop")]
  718.         void cmdShop(BasePlayer player, string command, string[] args)
  719.         {
  720.             if (!Shops.ContainsKey("chat"))
  721.             {
  722.                 SendReply(player, MessageErrorNPCRange);
  723.                 return;
  724.             }
  725.             ShowShop(player, "chat");
  726.         }
  727.  
  728.         //////////////////////////////////////////////////////////////////////////////////////
  729.         // Console Commands //////////////////////////////////////////////////////////////////
  730.         //////////////////////////////////////////////////////////////////////////////////////
  731.         [ConsoleCommand("shop.show")]
  732.         void ccmdShopShow(ConsoleSystem.Arg arg)
  733.         {
  734.             if (!arg.HasArgs(2)) return;
  735.             var player = arg.connection?.player as BasePlayer;
  736.             if (player == null) return;
  737.             var shopid = arg.GetString(0).Replace("'", "");
  738.             var shoppage = arg.GetInt(1);
  739.             ShowShop(player, shopid, shoppage);
  740.         }
  741.  
  742.         [ConsoleCommand("shop.buy")]
  743.         void ccmdShopBuy(ConsoleSystem.Arg arg)
  744.         {
  745.             if (!arg.HasArgs(3)) return;
  746.             var player = arg.connection?.player as BasePlayer;
  747.             if (player == null) return;
  748.             object success = Interface.Call("canShop", player);
  749.             if (success != null)
  750.             {
  751.                 string message = "You are not allowed to shop at the moment";
  752.                 if (success is string)
  753.                     message = (string)success;
  754.                 SendReply(player, message);
  755.                 return;
  756.             }
  757.  
  758.             string shop = arg.Args[0].Replace("'", "");
  759.             string item = arg.Args[1].Replace("'", "");
  760.             int amount = arg.GetInt(2);
  761.             success = TryShopBuy(player, shop, item, amount);
  762.             if (success is string)
  763.             {
  764.                 SendReply(player, (string)success);
  765.                 return;
  766.             }
  767.             SendReply(player, string.Format(MessageBought, amount, item));
  768.             ShowShop(player, shop, shopPage[player.userID], false);
  769.         }
  770.         [ConsoleCommand("shop.sell")]
  771.         void ccmdShopSell(ConsoleSystem.Arg arg)
  772.         {
  773.             if (!arg.HasArgs(3)) return;
  774.             var player = arg.connection?.player as BasePlayer;
  775.             if (player == null) return;
  776.             object success = Interface.Call("canShop", player);
  777.             if (success != null)
  778.             {
  779.                 string message = "You are not allowed to shop at the moment";
  780.                 if (success is string)
  781.                     message = (string)success;
  782.                 SendReply(player, message);
  783.                 return;
  784.             }
  785.             string shop = arg.Args[0].Replace("'", "");
  786.             string item = arg.Args[1].Replace("'", "");
  787.             int amount = Convert.ToInt32(arg.Args[2]);
  788.             success = TryShopSell(player, shop, item, amount);
  789.             if (success is string)
  790.             {
  791.                 SendReply(player, (string)success);
  792.                 return;
  793.             }
  794.             SendReply(player, string.Format(MessageSold, amount, item));
  795.             ShowShop(player, shop, shopPage[player.userID], false);
  796.         }
  797.     }
  798. }
Advertisement
Add Comment
Please, Sign In to add comment