C#:
using System.Collections.Generic;
using System;
using Oxide.Core;
using UnityEngine;
using Newtonsoft.Json;
using System.Linq;
namespace Oxide.Plugins {
[Info("XFireGloves", "Scrooge", "2.1.0")]
class XFireGloves : RustPlugin {
protected override void LoadConfig() {
base.LoadConfig();
try {
config = Config.ReadObject<GlovesConfig>();
if (config == null) {
PrintWarning(LanguageEnglish ? "Configuration file is empty! Creating a default configuration!" : "Файл конфигурации пуст! Создание дефолтной конфигурации!");
LoadDefaultConfig();
}
}
catch {
_configInitError = true;
}
if (!_configInitError) {
foreach (KeyValuePair<ulong, GlovesConfig.GlovesSetting> glove in config.Gloves) if (glove.Value.RemoveAll) glove.Value.Remove = true;
SaveConfig();
}
}
private void SendPlayerMessage(BasePlayer player, Item item, bool option) {
if (player.IsDead() || player.IsWounded() || player.IsSleeping()) return;
if (Cooldowns.TryGetValue(player, out DateTime time) && time.Subtract(DateTime.Now).TotalSeconds >= 0) return;
GlovesConfig.GlovesSetting glove = config.Gloves[item.skin];
if (option) Player.Reply(player, string.Format(lang.GetMessage("NO_PERM", this, player.UserIDString), glove.NameGloves));
else Player.Reply(player, string.Format(lang.GetMessage($"{item.skin}_INFO", this, player.UserIDString), glove.NameGloves, glove.GatherValue, glove.PickupValue, !glove.Remove && !glove.RemoveAll ? "∞" : $"{Math.Round((Math.Abs(item.busyTime) / glove.UseValue) * 100, 2)}%", glove.GrowableValue));
Cooldowns[player] = DateTime.Now.AddSeconds(5.0f);
}
private bool _configInitError = false;
[ConsoleCommand("gl_give")]
private void GlovesGive(ConsoleSystem.Arg args) {
if (args.Player() != null || args.Args == null || args.Args.Length < 2) return;
if (ulong.TryParse(args.Args[0], out ulong userID)) {
BasePlayer player = BasePlayer.FindByID(userID);
float defaultCondition = 108160.0f;
if (player != null && ulong.TryParse(args.Args[1], out ulong skinID) && config.Gloves.TryGetValue(skinID, out GlovesConfig.GlovesSetting glove)) {
Item item = ItemManager.CreateByName("burlap.gloves", 1, skinID);
item.name = glove.NameGloves;
if (glove.Remove) item.busyTime = -glove.UseValue;
player.GiveItem(item);
}
}
}
private void OnDispenserGathered(ResourceDispenser dispenser, BasePlayer player, Item item) {
Item attire = player.inventory.containerWear.GetSlot(6);
if (attire != null && config.Gloves.TryGetValue(attire.skin, out GlovesConfig.GlovesSetting glove)) {
if (glove.GatherGloves && !glove.NoRateItemList.Contains(item.info.shortname)) item.amount = (int)Math.Ceiling(item.amount * glove.GatherValue);
if (glove.SmeltGather && glove.SmeltItemList.Contains(item.info.shortname)) {
item.info = Smelting[item.info];
if (item.info.category == ItemCategory.Food) item.instanceData.dataFloat = 86400.0f;
}
}
}
private Dictionary<BasePlayer, DateTime> Cooldowns = new();
private void OnDispenserBonusReceived(ResourceDispenser disp, BasePlayer player, Item item) {
Item attire = player.inventory.containerWear.GetSlot(6);
if (attire != null && config.Gloves.TryGetValue(attire.skin, out GlovesConfig.GlovesSetting glove)) {
if (glove.GatherGloves && !glove.NoRateItemList.Contains(item.info.shortname)) item.amount = (int)Math.Ceiling(item.amount * glove.GatherValue);
if (glove.RadiationBonus) player.metabolism.radiation_poison.value += glove.RadiationBonusValue;
if (glove.SmeltGather && glove.SmeltItemList.Contains(item.info.shortname)) {
item.info = Smelting[item.info];
if (glove.Remove) RemoveGloves(player, attire);
}
else if (glove.RemoveAll) RemoveGloves(player, attire);
}
}
private void OnLootEntity(BasePlayer player, LootContainer lootcontainer) {
if (player == null || lootcontainer.OwnerID != 0) return;
if (!permission.UserHasPermission(player.UserIDString, permGlovesLoot)) return;
lootcontainer.OwnerID = player.userID;
foreach (KeyValuePair<ulong, GlovesConfig.GlovesSetting> glove in config.Gloves) {
if (lootcontainer.inventory.IsFull()) break;
if (glove.Value.Crate.TryGetValue(lootcontainer.ShortPrefabName, out float chanceDrop) && UnityEngine.Random.Range(0f, 100f) < chanceDrop) {
Item item = ItemManager.CreateByName("burlap.gloves", 1, glove.Key);
item.name = glove.Value.NameGloves;
if (glove.Value.Remove) item.busyTime = -glove.Value.UseValue;
item.MoveToContainer(lootcontainer.inventory);
}
}
}
private bool RemoveGloves(BasePlayer player, Item gloves) {
gloves.busyTime += 1;
if (gloves.busyTime >= 0) {
gloves.RemoveFromContainer();
gloves.RemoveFromWorld();
gloves.Remove(0f);
EffectNetwork.Send(new Effect("assets/bundled/prefabs/fx/impacts/slash/cloth/cloth1.prefab", player, 0, new Vector3(), new Vector3()), player.Connection);
Player.Reply(player, lang.GetMessage("BROKEN_GLOVES", this, player.UserIDString));
return true;
}
return false;
}
protected override void LoadDefaultConfig() => config = GlovesConfig.GetNewConfiguration();
private object OnItemRecycle(Item item, Recycler recycler) {
if (item.info.shortname == "burlap.gloves" && config.Gloves.TryGetValue(item.skin, out GlovesConfig.GlovesSetting glove) && glove.RecyclerGloves) {
foreach (GlovesConfig.ItemSetting items in glove.ItemList) if (UnityEngine.Random.Range(0f, 100f) < items.ChanceDrop) {
Item itemc = ItemManager.CreateByName(items.Shortname, items.Max > 1 ? UnityEngine.Random.Range(items.Min, items.Max + 1) : 1, items.SkinID);
itemc.name = items.Name;
itemc.text = items.Text;
itemc.busyTime = -items.UseValue;
recycler.MoveItemToOutput(itemc);
}
item.RemoveFromContainer();
item.RemoveFromWorld();
item.Remove(0f);
return false;
}
return null;
}
protected override void SaveConfig() => Config.WriteObject(config);
private void OnGrowableGathered(GrowableEntity plant, Item item, BasePlayer player) {
Item attire = player.inventory.containerWear.GetSlot(6);
if (attire != null && config.Gloves.TryGetValue(attire.skin, out GlovesConfig.GlovesSetting glove)) {
if (glove.GrowableGloves && !glove.NoRateItemList.Contains(item.info.shortname)) item.amount = (int)(item.amount * glove.GrowableValue);
if (glove.RadiationGrowable) player.metabolism.radiation_poison.value += glove.RadiationGrowableValue;
if (glove.RemoveAll) RemoveGloves(player, attire);
}
}
private const string permGlovesLoot = "xfiregloves.glovesloot";
private void OnServerInitialized() {
if (_configInitError) {
PrintWarning(LanguageEnglish ? "Error reading configuration! Please fix the errors or rename/delete the configuration file so that the plugin automatically creates the default configuration!" : "Ошибка чтения конфигурации! Пожалуйста исправите ошибки или переименуйте/удалите файл конфигурации, чтобы плагин автоматически создал дефолтную конфигурацию!");
NextTick(() => Interface.Oxide.UnloadPlugin(Name));
return;
}
PrintWarning("\n-----------------------------\n" + " Author - Monster\n" + " Discord - Monster#4837 / monster__dev\n" + " Config - v.66740\n" + "-----------------------------");
permission.RegisterPermission(permGlovesLoot, this);
foreach (KeyValuePair<ulong, GlovesConfig.GlovesSetting> glove in config.Gloves) {
if (glove.Value.SmeltItemList == null) glove.Value.SmeltItemList = new HashSet<string>();
if (!permission.PermissionExists(glove.Value.PermUse, this)) permission.RegisterPermission(glove.Value.PermUse, this);
}
Smelt();
foreach (KeyValuePair<ulong, GlovesConfig.GlovesSetting> glove in config.Gloves) glove.Value.SmeltItemList = glove.Value.SmeltItemList.Where(item => SmeltingItemList.Contains(item)).ToHashSet();
SaveConfig();
InitializeLang();
}
private void Smelt() {
Smelting = ItemManager.GetItemDefinitions().Where(i => SmeltingItemList.Contains(i.shortname)).ToDictionary(i => i, i => i.GetComponent<ItemModCookable>()?.becomeOnCooked);
Smelting.Add(ItemManager.FindItemDefinition("wood"), ItemManager.FindItemDefinition("charcoal"));
SmeltingItemList.Add("wood");
}
private Dictionary<ItemDefinition, ItemDefinition> Smelting;
private void Init() {
if (_configInitError) {
Unsubscribe(nameof(OnDispenserGathered));
Unsubscribe(nameof(OnDispenserBonusReceived));
Unsubscribe(nameof(OnCollectiblePickup));
Unsubscribe(nameof(OnGrowableGathered));
Unsubscribe(nameof(OnItemRecycle));
Unsubscribe(nameof(OnLootEntity));
Unsubscribe(nameof(CanWearItem));
}
else {
if (!config.Setting.Permission) Unsubscribe(nameof(OnLootEntity));
}
}
private class GlovesConfig {
internal class ItemSetting {
[JsonProperty(LanguageEnglish ? "Item shortname" : "Шортнейм предмета")]
public string Shortname;
[JsonProperty(LanguageEnglish ? "Item skin" : "Скин предмета")]
public ulong SkinID;
[JsonProperty(LanguageEnglish ? "Item name" : "Имя предмета")]
public string Name;
[JsonProperty(LanguageEnglish ? "Chance [ 100.0 - 100% ]" : "Шанс выпадения [ 100.0 - 100% ]")]
public float ChanceDrop;
[JsonProperty(LanguageEnglish ? "Text [ If it's a note ]" : "Текст [ Если это записка ]")]
public string Text;
[JsonProperty(LanguageEnglish ? "Number of usings [ If it's a glove ]" : "Кол-во юзов [ Если это перчатки ]")]
public int UseValue;
[JsonProperty(LanguageEnglish ? "Minimum amount" : "Минимальное кол-во")]
public int Min;
[JsonProperty(LanguageEnglish ? "Maximum amount" : "Максимальное кол-во")]
public int Max;
public ItemSetting(string shortname, ulong skinid, string name, float chancedrop, string text, int usevalue, int min, int max) {
Shortname = shortname;
SkinID = skinid;
Name = name;
ChanceDrop = chancedrop;
Text = text;
UseValue = usevalue;
Min = min;
Max = max;
}
}
[JsonProperty(LanguageEnglish ? "List of fire gloves" : "Список огненных перчаток")]
public Dictionary<ulong, GlovesSetting> Gloves = new Dictionary<ulong, GlovesSetting>();
[JsonProperty(LanguageEnglish ? "General settings" : "Общие настройки")]
public SettingSetting Setting = new SettingSetting();
internal class GlovesSetting {
[JsonProperty(LanguageEnglish ? "Name of the fire gloves" : "Имя огненных перчаток")]
public string NameGloves;
[JsonProperty(LanguageEnglish ? "Permission to use gloves" : "Разрешение на использование перчаток")]
public string PermUse;
[JsonProperty(LanguageEnglish ? "Rates of mined resources in gloves" : "Рейты добываемых ресурсов в перчатках")]
public double GatherValue;
[JsonProperty(LanguageEnglish ? "Rates of picked resources in gloves" : "Рейты подбираемых ресурсов в перчатках")]
public double PickupValue;
[JsonProperty(LanguageEnglish ? "Rates of harvesting in gloves" : "Рейты на сбор урожая в перчатках")]
public double GrowableValue;
[JsonProperty(LanguageEnglish ? "Amount of radiation when picked resources" : "Кол-во радиации при подборе ресурсов")]
public float RadiationPickupValue;
[JsonProperty(LanguageEnglish ? "Amount of radiation in bonus mining" : "Кол-во радиации при бонусной добыче")]
public float RadiationBonusValue;
[JsonProperty(LanguageEnglish ? "Amount of radiation when harvesting" : "Кол-во радиации при сборе урожая")]
public float RadiationGrowableValue;
[JsonProperty(LanguageEnglish ? "Number of usings" : "Кол-во юзов")]
public int UseValue;
[JsonProperty(LanguageEnglish ? "List of resources that can smelt gloves" : "Список ресурсов которые могут выплавлять перчатки")]
public HashSet<string> SmeltItemList;
[JsonProperty(LanguageEnglish ? "A list of resources that are not affected by rates" : "Список ресурсов на которые не влияют рейты")]
public HashSet<string> NoRateItemList;
[JsonProperty(LanguageEnglish ? "List of custom items after recycling" : "Список кастомных предметов после переработки")]
public List<ItemSetting> ItemList;
[JsonProperty(LanguageEnglish ? "Enable delete gloves after N usings - only for smelting" : "Включить удаление перчаток после N юзов - только при переплавке")]
public bool Remove;
[JsonProperty(LanguageEnglish ? "Enable delete gloves after N usings - when mining/pickup any resources + harvesting" : "Включить удаление перчаток после N юзов - при добыче/подборе любых ресурсов + сбор урожая")]
public bool RemoveAll;
[JsonProperty(LanguageEnglish ? "Enable smelting of mined resources" : "Включить переплавку добываемых ресурсов")]
public bool SmeltGather;
[JsonProperty(LanguageEnglish ? "Enable smelting of pickuped resources" : "Включить переплавку подбираемых ресурсов")]
public bool SmeltPickup;
[JsonProperty(LanguageEnglish ? "Enable mined resource rates" : "Включить рейты добываемых ресурсов")]
public bool GatherGloves;
[JsonProperty(LanguageEnglish ? "Enable pickuped resource rates" : "Включить рейты подбираемых ресурсов")]
public bool PickupGloves;
[JsonProperty(LanguageEnglish ? "Enable harvesting rates" : "Включить рейты на урожай")]
public bool GrowableGloves;
[JsonProperty(LanguageEnglish ? "Enable custom items after recycling fire gloves" : "Включить кастомные предметы после переработке огненных перчаток")]
public bool RecyclerGloves;
[JsonProperty(LanguageEnglish ? "Enable gloves to drop out of crates at a certain chance" : "Включить выпадение перчаток из ящиков с определенным шансом")]
public bool CrateGloves;
[JsonProperty(LanguageEnglish ? "Enable radiation accumulation when pickuping resources" : "Включить накопление радиации при подборе ресурсов")]
public bool RadiationPickup;
[JsonProperty(LanguageEnglish ? "Enable radiation accumulation when bonus mining" : "Включить накопление радиации при бонусной добыче")]
public bool RadiationBonus;
[JsonProperty(LanguageEnglish ? "Enable radiation accumulation when harvesting" : "Включить накопление радиации при сборе урожая")]
public bool RadiationGrowable;
[JsonProperty(LanguageEnglish ? "Customize the gloves drop chance from crates and barrels. Name crate/barrel | Drop chance: 100.0 - 100%" : "Настройка шанса выпадения из ящиков и бочек. Имя ящика/бочки | Шанс выпадения: 100.0 - 100%")]
public Dictionary<string, float> Crate;
public GlovesSetting(string n, string pu, double gv, double pv, double gv2, float rpv, float rbv, float rgv, int uv, HashSet<string> sil, HashSet<string> nril, List<ItemSetting> il, bool rr, bool rall, bool sg, bool sp, bool gg, bool pg, bool gg2, bool rg, bool cg, bool rp, bool rb, bool rg2, Dictionary<string, float> c) {
NameGloves = n;
PermUse = pu;
GatherValue = gv;
PickupValue = pv;
GrowableValue = gv2;
RadiationPickupValue = rpv;
RadiationBonusValue = rbv;
RadiationGrowableValue = rgv;
UseValue = uv;
SmeltItemList = sil;
NoRateItemList = nril;
ItemList = il;
Remove = rr;
RemoveAll = rall;
SmeltGather = sg;
SmeltPickup = sp;
GatherGloves = gg;
PickupGloves = pg;
GrowableGloves = gg2;
RecyclerGloves = rg;
CrateGloves = cg;
RadiationPickup = rp;
RadiationBonus = rb;
RadiationGrowable = rg2;
Crate = c;
}
}
internal class SettingSetting {
[JsonProperty(LanguageEnglish ? "Use permission for a chance to find gloves in crates: xfiregloves.glovesloot" : "Использовать разрешение на шанс найти перчатки в ящиках: xfiregloves.glovesloot")]
public bool Permission;
[JsonProperty(LanguageEnglish ? "Display information in chat when a player puts on gloves" : "Отображать информацию в чате когда игрок надевает перчатки")]
public bool UseInfo;
}
public static GlovesConfig GetNewConfiguration() {
return new GlovesConfig {
Setting = new SettingSetting {
Permission = true, UseInfo = true
}
, Gloves = new Dictionary<ulong, GlovesSetting> {
[1742796979]
= new GlovesSetting(LanguageEnglish ? "Fire gloves" : "Огненные перчатки", "xfiregloves.default", 2.0, 2.0, 1.5, 2.0f, 1.0f, 1.0f, 25, new HashSet<string> {
"chicken.raw", "humanmeat.raw", "bearmeat", "deermeat.raw", "meat.boar", "wolfmeat.raw", "horsemeat.raw", "hq.metal.ore", "metal.ore", "sulfur.ore", "crocodilemeat", "bigcatmeat", "snakemeat", "wood"
}
, new HashSet<string> {
"diesel_barrel"
}
, new List<ItemSetting> {
new ItemSetting("wood", 0, "", 50, "", 0, 50, 100)
}
, true, false, true, true, true, true, false, true, true, true, true, false, new Dictionary<string, float> {
["crate_tools"]
= 50.0f, ["crate_normal_2"] = 50.0f
}
), [841106268] = new GlovesSetting(LanguageEnglish ? "Fire gloves" : "Огненные перчатки", "xfiregloves.default", 1.5, 1.5, 1.2, 2.0f, 1.0f, 1.0f, 25, new HashSet<string> {
"chicken.raw", "humanmeat.raw", "bearmeat", "deermeat.raw", "meat.boar", "wolfmeat.raw", "horsemeat.raw", "hq.metal.ore", "metal.ore", "sulfur.ore", "crocodilemeat", "bigcatmeat", "snakemeat", "wood"
}
, new HashSet<string> {
"diesel_barrel"
}
, new List<ItemSetting> {
new ItemSetting("pistol.revolver", 0, "", 50, "", 0, 1, 1)
}
, true, false, true, true, true, true, false, true, true, true, true, false, new Dictionary<string, float> {
["crate_tools"]
= 50.0f, ["crate_normal_2"] = 50.0f
}
)
}
}
;
}
}
private GlovesConfig config;
private object CanWearItem(PlayerInventory inventory, Item item, int targetSlot) {
if (inventory == null || item.info.shortname != "burlap.gloves") return null;
BasePlayer player = inventory.baseEntity;
if (player != null && config.Gloves.TryGetValue(item.skin, out GlovesConfig.GlovesSetting glove)) {
if (targetSlot != 6) return false;
if (!permission.UserHasPermission(player.UserIDString, glove.PermUse)) {
SendPlayerMessage(player, item, true);
return false;
}
else {
if (config.Setting.UseInfo) SendPlayerMessage(player, item, false);
}
}
return null;
}
private void InitializeLang() {
Dictionary<string, string> langen = new() {
["NO_PERM"]
= "You are not allowed to use <color=orange>{0}</color>!\n\n<size=12>You can purchase a permit at our donation store: <color=#87CEEB>www.monster.dev</color></size>", ["BROKEN_GLOVES"] = "Oops! Gloves are broken!"
}
;
Dictionary<string, string> langru = new() {
["NO_PERM"]
= "Вам не разрешено использовать <color=orange>{0}</color>!\n\n<size=12>Приобрести разрешение можно в нашем донат-магазине: <color=#87CEEB>www.monster.dev</color></size>", ["BROKEN_GLOVES"] = "Упс! Перчатки сломались!"
}
;
Dictionary<string, string> languk = new() {
["NO_PERM"]
= "Вам не дозволено використовувати <color=orange>{0}</color>!\n\n<size=12>Придбати дозвіл можна в нашому донат-магазині: <color=#87CEEB>www.monster.dev</color></size>", ["BROKEN_GLOVES"] = "Ой! Рукавички зламалися!"
}
;
Dictionary<string, string> langes = new() {
["NO_PERM"]
= "No está permitido el uso de <color=orange>{0}</color>!\n\n<size=12>Puedes comprar un permiso en nuestra tienda de donaciones: <color=#87CEEB>www.monster.dev</color></size>", ["BROKEN_GLOVES"] = "¡Uy! ¡Los guantes están rotos!"
}
;
foreach (KeyValuePair<ulong, GlovesConfig.GlovesSetting> glove in config.Gloves) {
string key = $"{glove.Key}_INFO", text = $"{glove.Key}_TEXT";
langen.Add(key, "Wow! You're wearing <color=orange>{0}</color>!\n<size=12>Now you have some advantages!</size>\n\nGather rate: x{1}\nCollectible rate: x{2}\nHarvesting rate: x{4}\nGlove strength: {3}");
langru.Add(key, "Ух! Вы надели <color=orange>{0}</color>!\n<size=12>Теперь у вас есть некоторые преимущества!</size>\n\nРейты добычи: x{1}\nРейты подбора: x{2}\nРейты сбора урожая: x{4}\nПрочность перчаток: {3}");
languk.Add(key, "Ух! Ви вдягнули <color=orange>{0}</color>!\n<size=12>Тепер у вас є деякі переваги!</size>\n\nРейти видобутку: x{1}\nРейти підбору: x{2}\nРейти збирання врожаю: x{4}\nМіцність рукавичок: {3}");
langes.Add(key, "¡Vaya! Llevas <color=orange>{0}</color>!\n<size=12>¡Ahora tienes algunas ventajas!</size>\n\nRitmo de recolección: x{1}\nRitmo de recolección: x{2}\nÍndices de recolección: x{4}\nFuerza del guante: {3}");
}
lang.RegisterMessages(langen, this);
lang.RegisterMessages(langru, this, "ru");
lang.RegisterMessages(languk, this, "uk");
lang.RegisterMessages(langes, this, "es-ES");
}
private void OnCollectiblePickup(CollectibleEntity collectible, BasePlayer player) {
if (collectible.itemList == null) return;
Item attire = player.inventory.containerWear.GetSlot(6);
if (attire != null && config.Gloves.TryGetValue(attire.skin, out GlovesConfig.GlovesSetting glove)) foreach (ItemAmount item in collectible.itemList) {
if (glove.PickupGloves && !glove.NoRateItemList.Contains(item.itemDef.shortname)) item.amount = (int)Math.Ceiling(item.amount * glove.PickupValue);
if (glove.RadiationPickup) player.metabolism.radiation_poison.value += glove.RadiationPickupValue;
if (glove.SmeltPickup && glove.SmeltItemList.Contains(item.itemDef.shortname)) {
item.itemDef = Smelting[item.itemDef];
if (glove.Remove) if (RemoveGloves(player, attire)) break;
}
else if (glove.RemoveAll) {
if (RemoveGloves(player, attire)) break;
}
}
}
private const bool LanguageEnglish = false;
private HashSet<string> SmeltingItemList = new() {
"chicken.raw", "humanmeat.raw", "bearmeat", "deermeat.raw", "meat.boar", "wolfmeat.raw", "horsemeat.raw", "hq.metal.ore", "metal.ore", "sulfur.ore", "crocodilemeat", "bigcatmeat", "snakemeat"
}
;
}
}