C#:
using System.Collections.Generic;
using Oxide.Core;
using Oxide.Game.Rust.Cui;
using UnityEngine;
using Newtonsoft.Json;
using System;
using Oxide.Core.Plugins;
using System.Linq;
using Oxide.Core.Libraries.Covalence;
namespace Oxide.Plugins {
[Info("MagicItems", "Qbis", "1.1.2")]
public class MagicItems : RustPlugin {
#region [Vars]
[PluginReference]
Plugin ImageLibrary;
private Dictionary<ulong, Dictionary<int, playerMagicItem>> playersMagicItems = new Dictionary<ulong, Dictionary<int, playerMagicItem>>();
private List<ulong> OnPlayerWear = new List<ulong>();
public class playerMagicItem {
public ulong skinID;
public string name;
public int itemGatherPrecent;
public int itemDamagePrecent;
public int itemProtectPrecent;
public bool IsColdProtect;
public bool IsBleedingProtect;
public bool IsFastGather;
public int itemRadiationDamage;
public Dictionary<string, string> permissions;
public Dictionary<string, string> groups;
}
#endregion
#region [Config]
private PluginConfig config;
protected override void LoadDefaultConfig() {
config = PluginConfig.DefaultConfig();
}
protected override void LoadConfig() {
base.LoadConfig();
config = Config.ReadObject<PluginConfig>();
if (config.PluginVersion < Version) UpdateConfigValues();
Config.WriteObject(config, true);
}
private void UpdateConfigValues() {
PluginConfig baseConfig = PluginConfig.DefaultConfig();
if (config.PluginVersion < Version) {
PrintWarning("Plugin update detected! Checking config values...");
if (Version == new VersionNumber(1, 1, 0)) {
foreach (var item in config.magicItems) {
item.permissions = new Dictionary<string, string>();
item.groups = new Dictionary<string, string>();
if (item.skinID == 2358748270) {
item.permissions.Add("signartist.url", "Рисование на табличках");
item.groups.Add("Miner", "Дает группу 'Добытчик'");
}
}
}
if (Version == new VersionNumber(1, 1, 1)) {
config.itemMainShortname = "glue";
}
config.PluginVersion = Version;
PrintWarning("Config checked completed!");
}
config.PluginVersion = Version;
}
protected override void SaveConfig() {
Config.WriteObject(config);
}
private class PluginConfig {
[JsonProperty("Выпадает не более 1 предмета за раз/с 1 ящика")]
public bool onlyOneItem;
[JsonProperty("Выпадают ли артефакты после смерти")]
public bool onDeathDrop;
[JsonProperty("Основной предмет для магических преметов (shortname)")]
public string itemMainShortname;
[JsonProperty("Все ящики, с которых могут упасть магические предметы (для добавления в сам предмет убедитесь, что тут есть этот ящик!)")]
public List<string> dropBoxes;
[JsonProperty("Количество слотов для преметов по привилегиям")]
public Dictionary<string, int> playersMaxSlot;
[JsonProperty("Магические предметы")]
public List<MagicItemsSettings> magicItems;
[JsonProperty("Настройки оповещения и интерфейса")]
public BroadcastSettings broadcast;
[JsonProperty("Версия конфига")]
public VersionNumber PluginVersion = new VersionNumber();
public static PluginConfig DefaultConfig() {
return new PluginConfig() {
onlyOneItem = true, onDeathDrop = true, itemMainShortname = "glue", playersMaxSlot = new Dictionary<string, int>() {
["magicitems.default"]
= 1, ["magicitems.vip"] = 2, ["magicitems.premium"] = 3,
}
, dropBoxes = new List<string>() {
"crate_normal", "crate_normal_2", "crate_tools", "bradley_crate", "crate_basic", "crate_elite", "crate_mine", "supply_drop", "codelockedhackablecrate", "heli_crate"
}
, magicItems = new List<MagicItemsSettings>() {
new MagicItemsSettings() {
name = "Артефакт добычи", imageUrl = "https://i.imgur.com/66vrZFB.png", skinID = 2358748270, itemDropContainers = new Dictionary<string, int>(), itemDropGather = new Dictionary<string, int>() {
["sulfure-ore"]
= 5, ["stone-ore"] = 5, ["metal-ore"] = 5
}
, IsFastGather = true, itemGatherPrecent = 50, itemDamagePrecent = 0, itemProtectPrecent = 0, itemRadiationDamage = 0, IsBleedingProtect = false, IsColdProtect = false, permissions = new Dictionary<string, string>() {
["signartist.url"]
= "Рисование на табличках"
}
, groups = new Dictionary<string, string>() {
["Miner"]
= "Дает группу 'Добытчик'"
}
}
, new MagicItemsSettings() {
name = "Меч силы", imageUrl = "https://i.imgur.com/978jemJ.png", skinID = 2360703637, itemDropContainers = new Dictionary<string, int>() {
["crate_elite"]
= 15
}
, itemDropGather = new Dictionary<string, int>(), IsFastGather = false, itemGatherPrecent = 0, itemRadiationDamage = 3, itemDamagePrecent = 10, itemProtectPrecent = 0, IsBleedingProtect = false, IsColdProtect = false, permissions = new Dictionary<string, string>(), groups = new Dictionary<string, string>()
}
, new MagicItemsSettings() {
name = "Накидка", imageUrl = "https://i.imgur.com/oI21TIn.png", skinID = 2361459327, itemDropContainers = new Dictionary<string, int>() {
["crate_elite"]
= 15
}
, itemDropGather = new Dictionary<string, int>(), IsFastGather = false, itemGatherPrecent = 0, itemDamagePrecent = 0, itemRadiationDamage = 0, itemProtectPrecent = 10, IsBleedingProtect = false, IsColdProtect = true, permissions = new Dictionary<string, string>(), groups = new Dictionary<string, string>()
}
, new MagicItemsSettings() {
name = "Бутыль крови", imageUrl = "https://i.imgur.com/XEqkn5L.png", skinID = 2361427324, itemDropContainers = new Dictionary<string, int>() {
["crate_elite"]
= 25
}
, itemDropGather = new Dictionary<string, int>(), IsFastGather = false, itemGatherPrecent = 0, itemDamagePrecent = 0, itemRadiationDamage = 0, itemProtectPrecent = 0, IsBleedingProtect = true, IsColdProtect = false, permissions = new Dictionary<string, string>(), groups = new Dictionary<string, string>()
}
}
, broadcast = new BroadcastSettings() {
broadcastChatDrop = true, isButtonActive = true, Amin = "0.648125 0.02500001", Amax = "0.6960313 0.1041667", buttonImage = "https://i.imgur.com/1nfaYn6.png"
}
, PluginVersion = new VersionNumber()
}
;
}
}
public class MagicItemsSettings {
[JsonProperty("Имя предмета")]
public string name;
[JsonProperty("АйдиСкина предмета (у всех предметов должен быть разный!)")]
public ulong skinID;
[JsonProperty("Ссылка на картинку")]
public string imageUrl;
[JsonProperty("Укажите из каких ящиков и шанс выпадения (от 1 до 100) (если не нужно - оставьте пустым)")]
public Dictionary<string, int> itemDropContainers;
[JsonProperty("Укажите из каких руд при добыче и шанс выпадения (от 1 до 100) (если не нужно - оставьте пустым)")]
public Dictionary<string, int> itemDropGather;
[JsonProperty("На сколько процентов предмет увеличивает добычу ресурсов")]
public int itemGatherPrecent;
[JsonProperty("На сколько процентов предмет увеличивает урон по врагам")]
public int itemDamagePrecent;
[JsonProperty("На сколько процентов предмет защищает от урона")]
public int itemProtectPrecent;
[JsonProperty("Защищает ли предмет от жары и холода")]
public bool IsColdProtect;
[JsonProperty("Защищает ли предмет от кровотечения")]
public bool IsBleedingProtect;
[JsonProperty("Быстрая добыча ресурсов")]
public bool IsFastGather;
[JsonProperty("Радиации за каждое попадание по игроку")]
public int itemRadiationDamage;
[JsonProperty("Какие привилегии дает предмет")]
public Dictionary<string, string> permissions;
[JsonProperty("Какие группы дает предмет")]
public Dictionary<string, string> groups;
}
public class BroadcastSettings {
[JsonProperty("Выводить ли сообщение в чат о том, что выпал магический предмет из камня в чат")]
public bool broadcastChatDrop;
[JsonProperty("Активна ли кнопка открытия")]
public bool isButtonActive;
[JsonProperty("Ссылка на картинку для кнопки")]
public string buttonImage;
[JsonProperty("Кнопка открытия: Amin")]
public string Amin;
[JsonProperty("Кнопка открытия: Amax")]
public string Amax;
}
#endregion
#region [Oxide]
private void OnPlayerConnected(BasePlayer player) {
if (config.broadcast.isButtonActive) CreateUIOpenButton(player);
foreach(var item in config.magicItems) {
if(item.permissions.Count > 0) {
if (!playersMagicItems.ContainsKey(player.userID)) foreach (var perm in item.permissions) permission.RevokeUserPermission(player.UserIDString, perm.Key);
}
if (item.groups.Count > 0) {
if (!playersMagicItems.ContainsKey(player.userID)) foreach (var group in item.groups) permission.RemoveUserGroup(player.UserIDString, group.Key);
}
}
}
private void OnServerInitialized() {
foreach (var perm in config.playersMaxSlot) permission.RegisterPermission(perm.Key, this);
foreach (var image in config.magicItems) ImageLibrary?.Call("AddImage", image.imageUrl, image.skinID.ToString());
ImageLibrary?.Call("AddImage", config.broadcast.buttonImage, "button_mi");
foreach (var player in BasePlayer.activePlayerList) {
if(config.broadcast.isButtonActive) CreateUIOpenButton(player);
}
}
private void OnDispenserGather(ResourceDispenser dispenser, BaseEntity entity, Item item) {
if (entity.ToPlayer() == null) return;
if (item == null) return;
var precent = GetPlayerMagicItemStat(entity.ToPlayer(), "itemGatherPrecent") * 1f;
if (precent <= 0) return;
NextTick(() => {
var amount = Convert.ToInt32(item.amount * (precent / 100f));
if (amount <= 0) return;
var bonusItem = ItemManager.CreateByName(item.info.shortname, amount);
if (bonusItem.amount <= 0) return;
entity.ToPlayer().GiveItem(bonusItem);
}
);
}
private void OnDispenserBonus(ResourceDispenser dispenser, BaseEntity entity, Item item) {
if (entity?.ToPlayer() == null) return;
var player = entity.ToPlayer();
foreach(var ditem in config.magicItems.Where(d => d.itemDropGather.Count > 0).ToList()) {
foreach(var drop in ditem.itemDropGather) {
if(dispenser.name.Contains(drop.Key)) {
var rnd = UnityEngine.Random.Range(1, 101);
if (rnd > drop.Value) continue;
var magicitem = ItemManager.CreateByName(config.itemMainShortname, 1, ditem.skinID);
magicitem.name = ditem.name;
player.GiveItem(magicitem);
if(config.broadcast.broadcastChatDrop) player.ChatMessage($"Вам выпал магический предмет : <color=orange>{magicitem.name}</color>");
if (config.onlyOneItem) return;
}
}
}
OnDispenserGather(dispenser, entity, item);
}
private void OnPlayerAttack(BasePlayer attacker, HitInfo hit) {
if (hit.HitEntity == null) return;
Item item = attacker.GetActiveItem();
if (item == null) return;
var precent = GetPlayerMagicItemStat(attacker, "IsFastGather");
if (precent <= 0) return;
BasePlayer target = hit.HitEntity?.ToPlayer();
BaseEntity entity = hit.HitEntity?.GetEntity();
OreResourceEntity ore = entity as OreResourceEntity;
if (ore != null) {
ore._hotSpot?.Kill();
ore._hotSpot = null;
}
TreeEntity tree = entity as TreeEntity;
if (tree != null) tree.hasBonusGame = false;
if (!(entity is OreResourceEntity || entity is TreeEntity || entity.PrefabName.Contains("driftwood") || entity.PrefabName.Contains("dead_log"))) return;
if (target != null && !target.IsNpc) return;
hit.gatherScale = 5;
}
private void OnEntityTakeDamage(BaseCombatEntity entity, HitInfo info) {
if (entity?.ToPlayer() == null) return;
if (info?.Initiator?.ToPlayer() == null) return;
BasePlayer attacker = info.InitiatorPlayer.ToPlayer();
BasePlayer victim = entity.ToPlayer();
var precentDamage = GetPlayerMagicItemStat(attacker, "itemDamagePrecent");
var precentProtect = GetPlayerMagicItemStat(victim, "itemProtectPrecent");
var radiation = GetPlayerMagicItemStat(attacker, "itemRadiationDamage");
if (radiation > 0) victim.metabolism.radiation_poison.value += radiation;
float precent = (precentDamage - precentProtect) / 100f;
info.damageTypes.ScaleAll(1f + precent);
//Server.Broadcast($"{precentDamage} - {precentProtect} - {precent} - {info.damageTypes.Total()} - {victim.Health()}");
}
private void OnPlayerSleep(BasePlayer player) {
if (player == null) return;
var precent = GetPlayerMagicItemStat(player, "IsColdProtect");
if (precent <= 0) return;
PlayerNoTemperature(player);
}
private void OnPlayerSleepEnded(BasePlayer player) {
if (player == null) return;
var precent = GetPlayerMagicItemStat(player, "IsColdProtect");
if (precent <= 0) return;
PlayerNoTemperature(player);
}
private void OnRunPlayerMetabolism(PlayerMetabolism metabolism) {
if (metabolism.bleeding.value < 1) return;
var player = metabolism.GetComponent<BasePlayer>();
if (player == null) return;
var precent = GetPlayerMagicItemStat(player, "IsBleedingProtect");
if (precent <= 0) return;
metabolism.bleeding.value = 0;
}
private object OnPlayerDeath(BasePlayer player, HitInfo info) {
if (player == null) return null;
if(config.broadcast.isButtonActive) CuiHelper.DestroyUi(player, "MIbuttonpanel");
if (!config.onDeathDrop) return null;
if (!playersMagicItems.ContainsKey(player.userID)) return null;
if (playersMagicItems[player.userID].Count <= 0) return null;
foreach(var slot in playersMagicItems[player.userID].Values) {
if (slot.permissions.Count > 0) foreach (var perm in slot.permissions) permission.RevokeUserPermission(player.UserIDString, perm.Key);
if (slot.groups.Count > 0) foreach (var group in slot.groups) permission.RemoveUserGroup(player.UserIDString, group.Key);
var item = ItemManager.CreateByName(config.itemMainShortname, 1, slot.skinID);
item.name = slot.name;
item.Drop(player.transform.position, new Vector3());
}
playersMagicItems.Remove(player.userID);
return null;
}
private void OnPlayerRespawned(BasePlayer player) {
if (player == null) return;
if (config.broadcast.isButtonActive) CreateUIOpenButton(player);
}
private object CanCombineDroppedItem(DroppedItem drItem, DroppedItem anotherDrItem) {
if (drItem.item.info.shortname == config.itemMainShortname && anotherDrItem.item.info.shortname == config.itemMainShortname) {
if (drItem.item.skin == 0 && anotherDrItem.item.skin == 0) return null;
if (config.magicItems.Select(p => p.skinID).ToList().Contains(drItem.item.skin) || config.magicItems.Select(p => p.skinID).ToList().Contains(anotherDrItem.item.skin)) return false;
}
return null;
}
private object CanStackItem(Item item, Item targetItem) {
if (item.info.shortname == config.itemMainShortname && targetItem.info.shortname == config.itemMainShortname) {
if (targetItem.skin == 0 && item.skin == 0) return null;
if (targetItem.skin == item.skin && config.magicItems.Select(p => p.skinID).ToList().Contains(targetItem.skin) && config.magicItems.Select(p => p.skinID).ToList().Contains(item.skin)) return false;
}
return null;
}
private object OnLootSpawn(LootContainer container) {
if (container == null) return null;
if (!config.dropBoxes.Contains(container.ShortPrefabName)) return null;
var dropitems = config.magicItems.Where(b => b.itemDropContainers.ContainsKey(container.ShortPrefabName)).ToList();
foreach (var mitem in dropitems) {
var rnd = UnityEngine.Random.Range(1, 101);
if (rnd > mitem.itemDropContainers[container.ShortPrefabName]) continue;
var item = ItemManager.CreateByName(config.itemMainShortname, 1, mitem.skinID);
item.name = mitem.name;
item.MoveToContainer(container.inventory);
if (config.onlyOneItem) return null;
}
return null;
}
#endregion
#region [Functions]
private void PlayerNoTemperature(BasePlayer player) {
player.metabolism.temperature.max = 30;
player.metabolism.temperature.min = 30;
player.metabolism.temperature.value = 30;
player.SendNetworkUpdate();
}
private void PlayerTemperature(BasePlayer player) {
player.metabolism.temperature.max = 100;
player.metabolism.temperature.min = -100;
player.metabolism.temperature.value = 30;
player.SendNetworkUpdate();
}
private int GetPlayerMagicItemStat(BasePlayer player, string stat) {
if (!playersMagicItems.ContainsKey(player.userID)) return 0;
if (playersMagicItems[player.userID].Count <= 0) return 0;
switch (stat) {
case "IsFastGather" : foreach (var item in playersMagicItems[player.userID].Values) {
if(item.IsFastGather) {
return 1;
}
}
return 0;
case "IsBleedingProtect" : foreach (var item in playersMagicItems[player.userID].Values) {
if (item.IsBleedingProtect) {
return 1;
}
}
return 0;
case "IsColdProtect" : foreach (var item in playersMagicItems[player.userID].Values) {
if (item.IsColdProtect) {
return 1;
}
}
return 0;
case "itemGatherPrecent" : foreach (var item in playersMagicItems[player.userID].OrderByDescending(m => m.Value.itemGatherPrecent)) {
if (item.Value.itemGatherPrecent > 0) {
return item.Value.itemGatherPrecent;
}
}
return 0;
case "itemDamagePrecent" : foreach (var item in playersMagicItems[player.userID].OrderByDescending(m => m.Value.itemDamagePrecent)) {
if (item.Value.itemDamagePrecent > 0) {
return item.Value.itemDamagePrecent;
}
}
return 0;
case "itemProtectPrecent" : foreach (var item in playersMagicItems[player.userID].OrderByDescending(m => m.Value.itemProtectPrecent)) {
if (item.Value.itemProtectPrecent > 0) {
return item.Value.itemProtectPrecent;
}
}
return 0;
case "itemRadiationDamage" : foreach (var item in playersMagicItems[player.userID].OrderByDescending(m => m.Value.itemRadiationDamage)) {
if (item.Value.itemRadiationDamage > 0) {
return item.Value.itemRadiationDamage;
}
}
return 0;
}
return 0;
}
private int GetPlayerMaxSlots(BasePlayer player) {
foreach(var slot in config.playersMaxSlot.OrderByDescending(s => s.Value)) {
if (permission.UserHasPermission(player.UserIDString, slot.Key)) return slot.Value;
}
return 0;
}
private string GetMagicItemStatString(ulong id) {
string stats = "";
var magicItem = config.magicItems.Where(p => p.skinID == id).First();
if(magicItem == null) return "Предмет не найден";
if (magicItem.itemGatherPrecent > 0) stats += $"-Добыча ресурсов +{magicItem.itemGatherPrecent}%\n";
if (magicItem.IsFastGather) stats += "-Быстрая добыча ресурсов\n";
if (magicItem.IsBleedingProtect) stats += "-Защита от кровотечения\n";
if (magicItem.IsColdProtect) stats += "-Защита от жары и холода\n";
if (magicItem.itemDamagePrecent > 0) stats += $"-Исходящий урон +{magicItem.itemDamagePrecent}%\n";
if (magicItem.itemProtectPrecent > 0) stats += $"-Получаемый урон -{magicItem.itemProtectPrecent}%\n";
if (magicItem.itemRadiationDamage > 0) stats += $"-Радиации за каждое попадание +{magicItem.itemRadiationDamage}\n";
if (magicItem.permissions.Count > 0) foreach (var perm in magicItem.permissions) stats += $"-{perm.Value}\n";
if (magicItem.groups.Count > 0) foreach (var group in magicItem.groups) stats += $"-{group.Value}\n";
return stats;
}
private Dictionary<ulong, string> GetPlayers(string nameOrId) {
var pl = covalence.Players.FindPlayers(nameOrId).ToList();
return pl.Select(p => new KeyValuePair<ulong, string>(ulong.Parse(p.Id), p.Name)).ToDictionary(x => x.Key, x => x.Value);
}
private BasePlayer FindBasePlayer(ulong userId) {
BasePlayer player = BasePlayer.activePlayerList.FirstOrDefault(p => p.userID == userId);
player = player ?? BasePlayer.sleepingPlayerList.FirstOrDefault(p => p.userID == userId);
return player;
}
private void GivePlayerMagicItem(BasePlayer sender, BasePlayer player, string name) {
foreach (var item in config.magicItems) {
if (item.name.Contains(name)) {
var newitem = ItemManager.CreateByName(config.itemMainShortname, 1, item.skinID);
newitem.name = item.name;
player.GiveItem(newitem);
player.ChatMessage($"Вам выдан магический предмет : {item.name}");
return;
}
}
sender.ChatMessage($"Магический предмет {name} не найден");
}
private void GivePlayerMagicItemById(IPlayer sender, BasePlayer player, ulong skinid) {
foreach (var item in config.magicItems) {
if (item.skinID == skinid) {
var newitem = ItemManager.CreateByName(config.itemMainShortname, 1, item.skinID);
newitem.name = item.name;
player.GiveItem(newitem);
player.ChatMessage($"Вам выдан магический предмет : {item.name}");
return;
}
}
sender.Message($"Магический предмет со скином {skinid} не найден");
}
#endregion
#region [UI]
private void CreateUIOpenButton(BasePlayer player) {
CuiElementContainer container = new CuiElementContainer();
container.Add(new CuiElement {
Parent = "Overlay", Name = "MIbuttonpanel", Components = {
new CuiImageComponent {
Color = "0.83 0.83 0.83 0.05", Material = "assets/content/ui/uibackgroundblur-ingamemenu.mat"
}
, new CuiRectTransformComponent {
AnchorMin = config.broadcast.Amin, AnchorMax = config.broadcast.Amax
}
}
}
);
CreateImage(ref container, "button_icon", "MIbuttonpanel", "1 1 1 1", "button_mi", "0 0", "1 1");
UI.CreateButton(ref container, "MIbuttonpanel", "0 0 0 0", "", 0, "0 0", "1 1", "chat.say /mi");
CuiHelper.DestroyUi(player, "MIbuttonpanel");
CuiHelper.AddUi(player, container);
}
private void CreateUIMi(BasePlayer player, ulong activeitem = 0, uint activitemnetid = 0) {
if (!player.IsAlive() || player.IsWounded() || !player.IsConnected) return;
if (OnPlayerWear.Contains(player.userID)) OnPlayerWear.Remove(player.userID);
CuiElementContainer container = new CuiElementContainer();
container.Add(new CuiElement {
Parent = "Overlay", Name = "MImain", Components = {
new CuiImageComponent {
Color = "0 0 0 0.4", Material = "assets/content/ui/uibackgroundblur-ingamemenu.mat"
}
, new CuiRectTransformComponent {
AnchorMin = "0 0", AnchorMax = "1 1"
}
, new CuiNeedsCursorComponent()
}
}
);
UI.CreateButton(ref container, "MImain", "0 0 0 0", "", 0, "0 0", "1 1", "UI_MI_ACTION close");
UI.CreatePanel(ref container, "MIpanel", "MImain", $"0 0 0 0", "0.20 0.15", "0.80 0.90");
UI.CreatePanel(ref container, "MIactiveslots", "MIpanel", $"0 0 0 0", "0.00390619 0.7486111", "0.9953125 0.9986112");
UI.CreatePanel(ref container, "MIInfo", "MIpanel", $"0 0 0 0", "0 0", "0.3625 0.72");
UI.CreatePanel(ref container, "MIinventory", "MIpanel", $"0 0 0 0", "0.403125 0", "1 0.72");
UI.CreateButton(ref container, "MIpanel", "0 0 0 0", "✘", 28, "0.9350427 0.9369025", "0.9982907 0.998088", "UI_MI_ACTION close");
int maxSlots = GetPlayerMaxSlots(player);
UI.CreatePanelBlur(ref container, "Line", "MIpanel", $"1 1 1 0.6", "0.20390619 0.7347222", "0.7953125 0.7352778");
if (maxSlots > 0) {
UI.CreateTextOutLine(ref container, "MIactiveslots", $"Активные магические предметы", "1 1 1 0.6", $"0 0.7", $"1 1", TextAnchor.MiddleCenter, 18);
for (int i = 0; i < maxSlots; i++) {
UI.CreatePanelBlur(ref container, "Miaslot" + i, "MIactiveslots", $"0.83 0.83 0.83 0.05", $"{0.01418445 + (i * 0.1)} 0.1811112", $"{0.09377461 + (i * 0.1)} 0.6199999");
if (playersMagicItems.ContainsKey(player.userID)) {
if(playersMagicItems[player.userID].ContainsKey(i)) {
CreateImage(ref container, "image" + i, "Miaslot" + i, "1 1 1 1", playersMagicItems[player.userID][i].skinID.ToString(), "0 0", "1 1");
if (activeitem == playersMagicItems[player.userID][i].skinID && activitemnetid == 0) {
UI.CreateTextOutLine(ref container, "MIInfo", $"{playersMagicItems[player.userID][i].name}", "1 1 1 0.6", $"0 0.9", $"0.7 1", TextAnchor.MiddleCenter, 18);
CreateImage(ref container, "imageInfo", "MIInfo", "1 1 1 1", playersMagicItems[player.userID][i].skinID.ToString(), "0.7289744 0.8107076", "0.9794872 0.9864879");
UI.CreateTextOutLine(ref container, "MIInfo", GetMagicItemStatString(playersMagicItems[player.userID][i].skinID), "1 1 1 0.6", $"0.05 0.3", $"1 0.7", TextAnchor.UpperLeft, 15);
UI.CreateButton(ref container, "MIInfo", "0.83 0.83 0.83 0.5", "Снять", 16, "0.251282 0.31720843", "0.7897435 0.38795415", $"UI_MI_ACTION remove {playersMagicItems[player.userID][i].skinID}", TextAnchor.MiddleCenter, "btn_add");
UI.CreatePanelBlur(ref container, "Select", "Miaslot" + i, $"0.33 0.66 1.00 0.03", $"0 0", $"1 1");
}
else UI.CreateButton(ref container, "Miaslot" + i, "0 0 0 0", "", 0, "0 0", "1 1", $"UI_MI_ACTION showactive {playersMagicItems[player.userID][i].skinID}");
}
}
}
}
else UI.CreateTextOutLine(ref container, "MIactiveslots", $"У вас нет доступа с магическим предметам", "1 1 1 0.6", $"0 0.3", $"1 1", TextAnchor.MiddleCenter, 24);
UI.CreateTextOutLine(ref container, "MIinventory", $"Магические предметы в инвентаре", "1 1 1 0.6", $"0 0.9", $"1 1", TextAnchor.MiddleCenter, 18);
int k = 0;
int j = 0;
List<ulong> magicitemsList = config.magicItems.Select(s => s.skinID).ToList();
foreach(var item in player.inventory.containerMain.itemList) {
if (item == null) continue;
if (!magicitemsList.Contains(item.skin)) continue;
UI.CreatePanelBlur(ref container, "iSlot" + k, "MIinventory", $"0.83 0.83 0.83 0.05", $"{0.13943576 + (k * 0.15)} {0.7209063 - (j * 0.175)}", $"{0.2658462 + (k * 0.15)} {0.866182 - (j * 0.175)}");
CreateImage(ref container, "image" + k, "iSlot" + k, "1 1 1 1", item.skin.ToString(), "0 0", "1 1");
if (activitemnetid == item.uid && activeitem == 0) {
UI.CreateTextOutLine(ref container, "MIInfo", $"{item.name}", "1 1 1 0.6", $"0 0.9", $"0.7 1", TextAnchor.MiddleCenter, 18);
CreateImage(ref container, "imageInfo", "MIInfo", "1 1 1 1", item.skin.ToString(), "0.7289744 0.8107076", "0.9794872 0.9864879");
UI.CreateTextOutLine(ref container, "MIInfo", GetMagicItemStatString(item.skin), "1 1 1 0.6", $"0.05 0.3", $"1 0.7", TextAnchor.UpperLeft, 15);
UI.CreateButton(ref container, "MIInfo", "0.83 0.83 0.83 0.5", "Одеть", 16, "0.251282 0.31720843", "0.7897435 0.38795415", $"UI_MI_ACTION add {item.uid}", TextAnchor.MiddleCenter, "btn_add");
UI.CreatePanelBlur(ref container, "Select", "iSlot" + k, $"0.33 0.66 1.00 0.03", $"0 0", $"1 1");
}
else UI.CreateButton(ref container, "iSlot" + k, "0 0 0 0", "", 0, "0 0", "1 1", $"UI_MI_ACTION showinv {item.uid}");
k++;
if (k == 5) {
k = 0;
j++;
}
}
CuiHelper.DestroyUi(player, "MImain");
CuiHelper.AddUi(player, container);
}
[ConsoleCommand("UI_MI_ACTION")]
private void cmd_UI_MI_ACTION(ConsoleSystem.Arg arg) {
BasePlayer player = arg.Player();
if (player == null) return;
if (OnPlayerWear.Contains(player.userID)) return;
var action = arg.Args[0];
if (action == "close") {
CuiHelper.DestroyUi(player, "MImain");
return;
}
if (action == "showactive") {
Effect effect = new Effect("assets/bundled/prefabs/fx/notice/item.select.fx.prefab", player, 0, new Vector3(), new Vector3());
EffectNetwork.Send(effect, player.Connection);
CreateUIMi(player, Convert.ToUInt64(arg.Args[1]));
return;
}
if (action == "showinv") {
Effect effect = new Effect("assets/bundled/prefabs/fx/notice/item.select.fx.prefab", player, 0, new Vector3(), new Vector3());
EffectNetwork.Send(effect, player.Connection);
CreateUIMi(player, 0, Convert.ToUInt32(arg.Args[1]));
return;
}
if (action == "add") {
if (!player.IsAlive() || player.IsWounded() || !player.IsConnected) return;
Effect effect = new Effect("assets/bundled/prefabs/fx/notice/item.select.fx.prefab", player, 0, new Vector3(), new Vector3());
EffectNetwork.Send(effect, player.Connection);
var uid = Convert.ToUInt32(arg.Args[1]);
for (int i = 0; i < 24; i++) {
var item = player.inventory.containerMain.GetSlot(i);
if (item == null) continue;
if (item.uid != uid) continue;
if (!playersMagicItems.ContainsKey(player.userID)) playersMagicItems.Add(player.userID, new Dictionary<int, playerMagicItem>());
if (playersMagicItems[player.userID].Count >= GetPlayerMaxSlots(player)) {
CuiElementContainer container = new CuiElementContainer();
UI.CreateButton(ref container, "MIInfo", "0.83 0.83 0.83 0.5", "Максимум", 16, "0.251282 0.31720843", "0.7897435 0.38795415", $"UI_MI_ACTION add {item.uid}", TextAnchor.MiddleCenter, "btn_add");
CuiHelper.DestroyUi(player, "btn_add");
CuiHelper.AddUi(player, container);
return;
}
foreach (var slot in playersMagicItems[player.userID]) if (slot.Value.skinID == item.skin) {
CuiElementContainer container = new CuiElementContainer();
UI.CreateButton(ref container, "MIInfo", "0.83 0.83 0.83 0.5", "Уже есть", 16, "0.251282 0.31720843", "0.7897435 0.38795415", $"UI_MI_ACTION add {item.uid}", TextAnchor.MiddleCenter, "btn_add");
CuiHelper.DestroyUi(player, "btn_add");
CuiHelper.AddUi(player, container);
return;
}
playerMagicItem magicItemWear = new playerMagicItem();
for (int j = 0; j < GetPlayerMaxSlots(player);
j++) {
if (playersMagicItems[player.userID].ContainsKey(j)) continue;
var magicItem = config.magicItems.Where(p => p.skinID == item.skin).First();
magicItemWear = new playerMagicItem() {
name = item.name, skinID = item.skin, IsBleedingProtect = magicItem.IsBleedingProtect, IsColdProtect = magicItem.IsColdProtect, IsFastGather = magicItem.IsFastGather, itemDamagePrecent = magicItem.itemDamagePrecent, itemGatherPrecent = magicItem.itemGatherPrecent, itemProtectPrecent = magicItem.itemProtectPrecent, itemRadiationDamage = magicItem.itemRadiationDamage, permissions = magicItem.permissions, groups = magicItem.groups
}
;
playersMagicItems[player.userID].Add(j, magicItemWear);
break;
}
item.UseItem(item.amount);
item.MarkDirty();
CuiElementContainer container2 = new CuiElementContainer();
UI.CreateTextOutLine(ref container2, "MIInfo", "Одеваем...", "1 1 1 0.6", "0.251282 0.31720843", "0.7897435 0.38795415", TextAnchor.MiddleCenter, 16, "btn_add");
CuiHelper.DestroyUi(player, "btn_add");
CuiHelper.AddUi(player, container2);
OnPlayerWear.Add(player.userID);
var precent = GetPlayerMagicItemStat(player, "IsColdProtect");
if (precent > 0) PlayerNoTemperature(player);
if(magicItemWear.permissions.Count > 0) foreach(var perm in magicItemWear.permissions) permission.GrantUserPermission(player.UserIDString, perm.Key, null);
if (magicItemWear.groups.Count > 0) foreach (var group in magicItemWear.groups) permission.AddUserGroup(player.UserIDString, group.Key);
timer.Once(1f, () => CreateUIMi(player));
break;
}
return;
}
if(action == "remove") {
if (!player.IsAlive() || player.IsWounded() || !player.IsConnected) return;
Effect effect = new Effect("assets/bundled/prefabs/fx/notice/item.select.fx.prefab", player, 0, new Vector3(), new Vector3());
EffectNetwork.Send(effect, player.Connection);
if (!playersMagicItems.ContainsKey(player.userID)) playersMagicItems.Add(player.userID, new Dictionary<int, playerMagicItem>());
var sid = Convert.ToUInt32(arg.Args[1]);
var slotid = -1;
foreach (var slot in playersMagicItems[player.userID]) if (slot.Value.skinID == sid) slotid = slot.Key;
if (!playersMagicItems[player.userID].ContainsKey(slotid)) return;
var magicItemWear = playersMagicItems[player.userID][slotid];
if (magicItemWear.permissions.Count > 0) foreach (var perm in magicItemWear.permissions) permission.RevokeUserPermission(player.UserIDString, perm.Key);
if (magicItemWear.groups.Count > 0) foreach (var group in magicItemWear.groups) permission.RemoveUserGroup(player.UserIDString, group.Key);
var item = ItemManager.CreateByName(config.itemMainShortname, 1, playersMagicItems[player.userID][slotid].skinID);
item.name = playersMagicItems[player.userID][slotid].name;
player.GiveItem(item);
playersMagicItems[player.userID].Remove(slotid);
var precent = GetPlayerMagicItemStat(player, "IsColdProtect");
if (precent <= 0) PlayerTemperature(player);
CreateUIMi(player);
}
}
#region [UI generator]
public class UI {
public static void CreateButton(ref CuiElementContainer container, string panel, string color, string text, int size, string aMin, string aMax, string command, TextAnchor align = TextAnchor.MiddleCenter, string name = "button", float FadeIn = 0f) {
container.Add(new CuiButton {
Button = {
Color = color, Command = command, FadeIn = FadeIn
}
, RectTransform = {
AnchorMin = aMin, AnchorMax = aMax
}
, Text = {
Text = text, FontSize = size, Align = align
}
}
, panel, name);
}
public static void CreatePanel(ref CuiElementContainer container, string name, string parent, string color, string aMin, string aMax, float Fadeout = 0f, float Fadein = 0f) {
container.Add(new CuiElement {
Name = name, Parent = parent, Components = {
new CuiImageComponent {
Color = color, FadeIn = Fadein
}
, new CuiRectTransformComponent {
AnchorMin = aMin, AnchorMax = aMax
}
}
, FadeOut = Fadeout
}
);
}
public static void CreatePanelBlur(ref CuiElementContainer container, string name, string parent, string color, string aMin, string aMax, float Fadeout = 0f, float Fadein = 0f) {
container.Add(new CuiPanel() {
CursorEnabled = true, RectTransform = {
AnchorMin = aMin, AnchorMax = aMax
}
, Image = {
Color = color, Material = "assets/content/ui/uibackgroundblur-ingamemenu.mat", FadeIn = Fadein
}
, FadeOut = Fadeout
}
, parent, name);
}
public static void CreateText(ref CuiElementContainer container, string parent, string text, string color, string aMin, string aMax, TextAnchor align = TextAnchor.MiddleLeft, int size = 14, string name = "name", float Fadein = 0f) {
container.Add(new CuiElement {
Parent = parent, Name = name, Components = {
new CuiTextComponent() {
Color = color, Text = text, FontSize = size, Align = align, FadeIn = Fadein
}
, new CuiRectTransformComponent {
AnchorMin = aMin , AnchorMax = aMax
}
}
}
);
}
public static void CreateTextOutLine(ref CuiElementContainer container, string parent, string text, string color, string aMin, string aMax, TextAnchor align = TextAnchor.MiddleLeft, int size = 14, string name = "name", float Fadein = 0f) {
container.Add(new CuiElement {
Parent = parent, Name = name, Components = {
new CuiTextComponent() {
Color = color, Text = text, FontSize = size, Align = align, FadeIn = Fadein
}
, new CuiRectTransformComponent {
AnchorMin = aMin , AnchorMax = aMax
}
, new CuiOutlineComponent {
Color = "0 0 0 1"
}
}
}
);
}
}
public void CreateImage(ref CuiElementContainer container, string name, string panel, string color, string image, string aMin, string aMax, float Fadeout = 0f, float Fadein = 0f, ulong skin = 0) {
container.Add(new CuiElement {
Name = name, Parent = panel, Components = {
new CuiRawImageComponent {
Color = color, Png = (string)ImageLibrary.Call("GetImage", image, skin), FadeIn = Fadein
}
, new CuiRectTransformComponent {
AnchorMin = aMin, AnchorMax = aMax
}
,
}
, FadeOut = Fadeout
}
);
}
#endregion
#endregion
#region [Command]
[ChatCommand("mi")]
private void cmdOpenMagicItemPanel(BasePlayer player, string command, string[] args) {
Effect effect = new Effect("assets/bundled/prefabs/fx/notice/item.select.fx.prefab", player, 0, new Vector3(), new Vector3());
EffectNetwork.Send(effect, player.Connection);
CreateUIMi(player);
}
private void GiveMagicItem(IPlayer player, string command, string[] args) {
if (args.Length < 2) {
player.Message ($"Невверно введена команда\n/givemi \"Ник|СтимАйди\" \"Имя предмета\" ");
return;
}
var recivers = GetPlayers(args[0]);
if (recivers == null || recivers.Count == 0) {
player.Message($"Игрок не найден");
return;
}
if (recivers.Count > 1) {
player.Message($"Найдено несколько игроков {string.Join("\n", recivers.Select(p => $" {
p.Value
}
( {
p.Key
}
)").ToArray())}");
return;
}
var Ireciver = recivers.First();
var reciver = FindBasePlayer(Ireciver.Key);
if (reciver == null) {
player.Message($"Игрока нет на сервере");
return;
}
GivePlayerMagicItem(FindBasePlayer(Convert.ToUInt64(player.Id)), reciver, args[1]);
}
private void GiveMagicItemById(IPlayer player, string command, string[] args) {
if (args.Length < 2) {
player.Message($"Невверно введена команда\n/givemi \"Ник|СтимАйди\" \"Скин Айди предмета\" ");
return;
}
var recivers = GetPlayers(args[0]);
if (recivers == null || recivers.Count == 0) {
player.Message($"Игрок не найден");
return;
}
if (recivers.Count > 1) {
player.Message($"Найдено несколько игроков {string.Join("\n", recivers.Select(p => $" {
p.Value
}
( {
p.Key
}
)").ToArray())}");
return;
}
var Ireciver = recivers.First();
var reciver = FindBasePlayer(Ireciver.Key);
if (reciver == null) {
player.Message($"Игрока нет на сервере");
return;
}
var skinid = Convert.ToUInt64(args[1]);
GivePlayerMagicItemById(player, reciver, skinid);
}
#endregion
#region [Data]
void LoadData() {
playersMagicItems = Interface.GetMod().DataFileSystem.ReadObject<Dictionary<ulong, Dictionary<int, p
// ... [Code preview truncated due to length. Full source in attached file] ...