MrWolfRanger

HuntRPG

Feb 28th, 2021
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 129.91 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6.  
  7. using Oxide.Core;
  8. using Oxide.Core.Configuration;
  9. using Oxide.Core.Libraries;
  10. using Oxide.Core.Plugins;
  11. using Oxide.Game.Rust.Cui;
  12.  
  13. using Newtonsoft.Json;
  14. using Newtonsoft.Json.Converters;
  15. using Newtonsoft.Json.Serialization;
  16.  
  17. using UnityEngine;
  18.  
  19. using Oxide.Plugins.HuntRPGExt;
  20. using Oxide.Plugins.HuntRPGExt.Keys;
  21.  
  22. using Random = UnityEngine.Random;
  23. using Time = UnityEngine.Time;
  24. using Timer = Oxide.Plugins.Timer;
  25.  
  26. namespace Oxide.Plugins
  27. {
  28. [Info("Hunt RPG", "Default", "1.7.9")]
  29. [Description("An RPG system with level, stats, skills, and specializations")]
  30. public class HuntRPG : RustPlugin
  31. {
  32. /*
  33. * TODO:
  34. * Implement Economics better
  35. * Reintroduce increasing max health <-- Working on currently
  36. * Patch up the skills.
  37. * Remove researcher.
  38. * Make maximum level changeable within the config.
  39. * Make plugin all UI based.
  40. * LoOk PrEtTy
  41. */
  42.  
  43. [PluginReference]
  44. private Plugin Pets;
  45. [PluginReference]
  46. private Plugin EventManager;
  47. [PluginReference]
  48. private Plugin PopupNotifications;
  49. [PluginReference]
  50. private Plugin Economics;
  51. [PluginReference]
  52. private Plugin MagazinBoost;
  53. [PluginReference]
  54. private Plugin InstantCraft;
  55. private bool initialized;
  56. private bool updatePlayerData;
  57. private readonly DynamicConfigFile huntDataFile;
  58. private VersionNumber DataVersion;
  59.  
  60. private HuntData Data;
  61. private string ChatPrefix;
  62. private ulong[] Trainer;
  63. private Dictionary<HRK, Skill> SkillTable;
  64. private Dictionary<ResourceDispenser.GatherType, float> ExpRateTable;
  65. private Dictionary<int, string> TameTable;
  66. private Dictionary<string, ItemInfo> ItemTable;
  67. private Dictionary<string, int> ResearchTable;
  68. private Dictionary<BuildingGrade.Enum, float> UpgradeBuildingTable;
  69. private string[] AllowedEntites;
  70. private bool AdminReset;
  71. private bool ShowHud;
  72. private bool ShowProfile;
  73. private uint DefaultHud;
  74. private float NightXP;
  75. private float DeleteProfileAfter;
  76. private float DeathReducer;
  77. private Dictionary<string, string> itemShortname;
  78.  
  79. private readonly Dictionary<ulong, float> PlayerLastPercentChange;
  80. private readonly Dictionary<ulong, Dictionary<HRK, float>> SkillsCooldowns;
  81. private readonly Dictionary<ulong, GUIInfo> GUIInfo;
  82. private readonly Random randomGenerator;
  83. private readonly int playersMask = LayerMask.GetMask("Player (Server)");
  84. private readonly int triggerMask = LayerMask.GetMask("Trigger");
  85.  
  86. private double EcoBoost;
  87. private int MaximumLevel;
  88. private Vector3 position;
  89.  
  90. public HuntRPG()
  91. {
  92. DataVersion = new VersionNumber(1, 0, 1);
  93.  
  94. GUIInfo = new Dictionary<ulong, GUIInfo>();
  95. PlayerLastPercentChange = new Dictionary<ulong, float>();
  96. SkillsCooldowns = new Dictionary<ulong, Dictionary<HRK, float>>();
  97. huntDataFile = Interface.Oxide.DataFileSystem.GetFile(HK.DataFileName);
  98. }
  99.  
  100. #region Hooks
  101.  
  102. void OnServerInitialized()
  103. {
  104. if (!initialized) OnTerrainInitialized();
  105. if (ItemTable == null)
  106. {
  107. DefaultItems();
  108. ItemTable = ReadFromConfig<Dictionary<string, ItemInfo>>(HK.ItemTable);
  109. }
  110. foreach (var player in BasePlayer.activePlayerList)
  111. OnPlayerConnected(player);
  112. }
  113.  
  114. void Unload()
  115. {
  116. foreach (var player in BasePlayer.activePlayerList)
  117. {
  118. GUIInfo guiInfo;
  119. if (!GUIInfo.TryGetValue(player.userID, out guiInfo)) continue;
  120. DestroyUi(player, guiInfo.LastHud);
  121. DestroyUi(player, guiInfo.LastMain);
  122. }
  123. SaveRpg();
  124. RPGInfo.OnUnload();
  125. }
  126.  
  127. void OnTerrainInitialized()
  128. {
  129. initialized = true;
  130. var configVersion = new VersionNumber();
  131. if (Config[HK.ConfigVersion] != null)
  132. configVersion = ReadFromConfig<VersionNumber>(HK.ConfigVersion);
  133. var dataVersion = new VersionNumber();
  134. if (Config[HK.DataVersion] != null)
  135. dataVersion = ReadFromConfig<VersionNumber>(HK.DataVersion);
  136. var needDataUpdate = !DataVersion.Equals(dataVersion);
  137. UpdateLang();
  138. LoadRpg(dataVersion);
  139. if (!needDataUpdate)
  140. {
  141. PrintToChat(_(HMK.Loaded));
  142. return;
  143. }
  144. updatePlayerData = true;
  145. UpdateData();
  146. }
  147.  
  148. void OnPlayerConnected(BasePlayer player)
  149. {
  150. if (player.HasPlayerFlag(BasePlayer.PlayerFlags.ReceivingSnapshot))
  151. {
  152. timer.Once(2, () => OnPlayerConnected(player));
  153. return;
  154. }
  155. if (updatePlayerData) ChatMessage(player, HMK.DataUpdated);
  156. var rpgInfo = FindRpgInfo(player);
  157. if (rpgInfo.Preferences.ShowProfile) ChatMessage(player, Profile(rpgInfo, player));
  158. var steamId = player.userID;
  159. if (!PlayerLastPercentChange.ContainsKey(steamId))
  160. PlayerLastPercentChange.Add(steamId, CurrentPercent(FindRpgInfo(player)));
  161. UpdateEffectsPlayer(player, rpgInfo);
  162. if (!ShowHud) return;
  163. timer.Once(1, () => GuiInit(player));
  164. }
  165.  
  166. void OnEntityTakeDamage(BasePlayer player, HitInfo hitInfo, BaseCombatEntity entity)
  167. {
  168. if (player is NPCPlayer) return;
  169. if (!(player.userID >= 76560000000000000L || player.userID <= 0L)) return;
  170. var rpgInfo = FindRpgInfo(player);
  171. if (rpgInfo == null) return;
  172. var attacker = hitInfo.Initiator as BasePlayer;
  173. var victim = hitInfo.Initiator;
  174. if (victim is BasePlayer)
  175. {
  176.  
  177. if (Random.Range(0f, 1f) <= rpgInfo.GetEvasion())
  178. {
  179. ChatMessage(player, HMK.Dodged);
  180. if (!(victim is NPCPlayer))
  181. {
  182. ChatMessage(attacker, HMK.TargetDodged);
  183. }
  184. hitInfo.damageTypes.ScaleAll(0);
  185. }
  186. }
  187. if (rpgInfo.GetBlock() <= 1 && rpgInfo.GetBlock() >= 0)
  188. {
  189. hitInfo.damageTypes.ScaleAll(1 - rpgInfo.GetBlock());
  190. }
  191. //ExpGain(rpgInfo, (int) Math.Ceiling(100.0 * 1.0), attacker);
  192. //return;
  193. //TODO Make actually work/Implement better.
  194. }
  195.  
  196.  
  197. //For reference
  198.  
  199. /*var rpgInfo = FindRpgInfo(player);
  200. if (rpgInfo == null) return;
  201. if (player.displayName == null) return;
  202. if (player.userID< 2147483647) return;
  203. var attacker = hitInfo.Initiator as BasePlayer;
  204. ExpGain(rpgInfo, (int) Math.Ceiling(100.0 * 1.0), attacker);
  205. return;*/
  206.  
  207. object OnPlayerAttack(BasePlayer player, HitInfo hitInfo)
  208. {
  209. if (player == null || hitInfo?.Weapon?.GetItem() == null || !player.CanBuild()) return null;
  210. Skill skill;
  211. if (SkillTable.TryGetValue(HRK.Blinkarrow, out skill) && !skill.Enabled)
  212. return null;
  213. if (!hitInfo.Weapon.GetOwnerItemDefinition().shortname.Equals("bow.hunting") && !hitInfo.Weapon.GetOwnerItemDefinition().shortname.Equals("bow.compound"))
  214. return null;
  215. var rpgInfo = FindRpgInfo(player);
  216. int skillPoints;
  217. if (!rpgInfo.Skills.TryGetValue(HRK.Blinkarrow, out skillPoints))
  218. {
  219. ChatMessage(player, HMK.NotLearnedSkill);
  220. return null;
  221. }
  222. var playerCooldowns = PlayerCooldowns(player.userID);
  223. float availableAt = 0;
  224. var time = Time.realtimeSinceStartup;
  225. var isReady = /*player.IsAdmin || */IsSkillReady(playerCooldowns, ref availableAt, time, HRK.Blinkarrow);
  226. if (!isReady)
  227. {
  228. ChatMessage(player, HMK.BlinkedRecently, TimeLeft(availableAt, time));
  229. }
  230. if (isReady)
  231. {
  232. if (rpgInfo.Preferences.AutoToggleBlinkArrow)
  233. rpgInfo.Preferences.UseBlinkArrow = true;
  234. if (!rpgInfo.Preferences.UseBlinkArrow) return null;
  235. Vector3 newPos = blinkArrow(hitInfo);
  236. if (!IsBuildingAllowed(newPos, player))
  237. {
  238. ChatMessage(player, HMK.CantBlinkOther);
  239. return null;
  240. }
  241. TeleportPlayerTo(player, newPos);
  242. SetCooldown(skillPoints, time, playerCooldowns, HRK.Blinkarrow);
  243. }
  244. if (!rpgInfo.Preferences.UseBlinkArrow) return null;
  245. if (rpgInfo.Preferences.AutoToggleBlinkArrow)
  246. rpgInfo.Preferences.UseBlinkArrow = false;
  247. return null;
  248. }
  249.  
  250. private static Vector3 blinkArrow(HitInfo hitInfo)
  251. {
  252. return GetGround(hitInfo.HitPositionWorld);
  253. }
  254.  
  255.  
  256. void OnEntityKill(BaseNetworkable networkable)
  257. {
  258. var oven = networkable as BaseOven;
  259. if (oven != null)
  260. {
  261. Data.Furnaces.Remove(EntityId(oven));
  262. return;
  263. }
  264. var quarry = networkable as MiningQuarry;
  265. if (quarry != null)
  266. {
  267. Data.Quarries.Remove(EntityId(quarry));
  268. return;
  269. }
  270. }
  271.  
  272. void OnPlayerDeath(BasePlayer player, HitInfo hitInfo)
  273. {
  274. var rpgInfo = FindRpgInfo(player);
  275. if (rpgInfo == null) return;
  276. if (player.displayName == null) return;
  277. if (player.userID < 2147483647) return;
  278. if (EventManager != null && (bool)EventManager.CallHook("isPlaying", player)) return;
  279. FindRpgInfo(player).Died(DeathReducer);
  280. ChatMessage(player, HMK.Died, DeathReducer);
  281. }
  282.  
  283. object OnItemCraft(ItemCraftTask task, BasePlayer crafter)
  284. {
  285. if (!ItemTable.ContainsKey(task.blueprint.targetItem.shortname))
  286. return null;
  287.  
  288. var rpgInfo = FindRpgInfo(crafter);
  289. var craftingTime = task.blueprint.time;
  290. var amountToReduce = craftingTime * rpgInfo.GetCraftingReducer();
  291. craftingTime -= amountToReduce;
  292. if (!task.blueprint.name.Contains("(Clone)"))
  293. task.blueprint = UnityEngine.Object.Instantiate(task.blueprint);
  294. task.blueprint.time = craftingTime;
  295. if (rpgInfo.Preferences.ShowCraftMessage)
  296. ChatMessage(crafter, HMK.CraftingEnd, craftingTime, amountToReduce);
  297. return null;
  298. }
  299.  
  300.  
  301.  
  302.  
  303. void OnDispenserGather(ResourceDispenser dispenser, BaseEntity entity, Item item)
  304. {
  305. var player = entity.ToPlayer();
  306. if (player == null) return;
  307. var rpgInfo = FindRpgInfo(player);
  308. if (rpgInfo == null) return;
  309. var gatherType = dispenser.gatherType;
  310. HRK skillType;
  311. switch (gatherType)
  312. {
  313. case ResourceDispenser.GatherType.Tree:
  314. skillType = HRK.Lumberjack;
  315. break;
  316. case ResourceDispenser.GatherType.Ore:
  317. skillType = HRK.Miner;
  318. break;
  319. case ResourceDispenser.GatherType.Flesh:
  320. skillType = HRK.Hunter;
  321. break;
  322. default:
  323. ExpGain(rpgInfo, item.amount, player);
  324. return;
  325. }
  326. int skillPoints;
  327. if (rpgInfo.Skills.TryGetValue(skillType, out skillPoints))
  328. item.amount = GatherModifierInt(skillPoints, skillType, item.amount);
  329. ExpGain(rpgInfo, (int)Math.Ceiling(item.amount * ExpRateTable[gatherType]), player);
  330. Economics?.Call("Deposit", player.UserIDString, (double)item.amount * EcoBoost);
  331. //TODO Patch up and make work better.
  332. }
  333.  
  334. void OnCollectiblePickup(Item item, BasePlayer player)
  335. {
  336. var rpgInfo = FindRpgInfo(player);
  337. if (rpgInfo == null)
  338. return;
  339. int skillPoints;
  340. if (rpgInfo.Skills.TryGetValue(HRK.Gatherer, out skillPoints))
  341. item.amount = GatherModifierInt(skillPoints, HRK.Gatherer, item.amount);
  342. ExpGain(rpgInfo, (int)Math.Ceiling(item.amount * ExpRateTable[ResourceDispenser.GatherType.Ore] * 2), player);
  343. Economics?.Call("Deposit", player.UserIDString, (double)item.amount * EcoBoost);
  344. }
  345.  
  346. void OnItemDeployed(Deployer deployer, BaseEntity baseEntity)
  347. {
  348. OnEntityDeployedInternal(deployer.GetOwnerPlayer(), baseEntity as BaseOven, Data.Furnaces);
  349. }
  350.  
  351. void OnItemAddedToContainer(ItemContainer container, Item item)
  352. {
  353. if (container.playerOwner == null) return;
  354. var rpgInfo = FindRpgInfo(container.playerOwner);
  355. if (rpgInfo == null) return;
  356. UpdateMagazin(item, rpgInfo);
  357. UpdateGather(item, rpgInfo);
  358. }
  359.  
  360. void OnPlayerHealthChange(BasePlayer player)
  361. {
  362. if (player == null)
  363. return;
  364. UpdateHud(player, true, false);
  365.  
  366. }
  367.  
  368. void OnEntityBuilt(Planner planner, GameObject gameObject)
  369. {
  370. var entity = gameObject.GetComponent<BaseEntity>();
  371. OnEntityDeployedInternal(planner.GetOwnerPlayer(), entity as BaseOven, Data.Furnaces);
  372. OnEntityDeployedInternal(planner.GetOwnerPlayer(), entity as MiningQuarry, Data.Quarries);
  373. var buildingBlock = entity as BuildingBlock;
  374. if (buildingBlock != null) OnStructureUpgrade(buildingBlock, planner.GetOwnerPlayer(), buildingBlock.grade);
  375. }
  376.  
  377. void OnConsumeFuel(BaseOven oven, Item fuel, ItemModBurnable burnable)
  378. {
  379. if (oven == null) return;
  380. var instanceId = EntityId(oven);
  381. ulong playerFurnace;
  382. if (!Data.Furnaces.TryGetValue(instanceId, out playerFurnace))
  383. return;
  384. var player = FindPlayer(playerFurnace);
  385. var rpgInfo = player == null ? FindRpgInfo(playerFurnace) : FindRpgInfo(player);
  386. if (rpgInfo == null)
  387. return;
  388. int skillLevel;
  389. if (!rpgInfo.Skills.TryGetValue(HRK.Blacksmith, out skillLevel))
  390. return;
  391. var skill = SkillTable[HRK.Blacksmith];
  392. var skillChance = skillLevel * skill.Modifiers[HRK.Chance].Args[0];
  393. if (Random.Range(0f, 1f) > skillChance)
  394. return;
  395. var rate = skillLevel / (float)skill.MaxLevel * skill.Modifiers[HRK.RessRate].Args[0];
  396. var items = oven.inventory.itemList.ToArray();
  397. foreach (var item in items)
  398. {
  399. var itemModCookable = item.info.GetComponent<ItemModCookable>();
  400. if (itemModCookable?.becomeOnCooked == null || item.temperature < itemModCookable.lowTemp || item.temperature > itemModCookable.highTemp || itemModCookable.cookTime < 0) continue;
  401. if (oven.inventory.Take(null, item.info.itemid, 1) != 1) continue;
  402. var itemToGive = ItemManager.Create(itemModCookable.becomeOnCooked, (int)Math.Ceiling(itemModCookable.amountOfBecome * rate));
  403. if (!itemToGive.MoveToContainer(oven.inventory))
  404. itemToGive.Drop(oven.inventory.dropPosition, oven.inventory.dropVelocity);
  405. }
  406. }
  407.  
  408. object OnStructureUpgrade(BuildingBlock buildingBlock, BasePlayer player, BuildingGrade.Enum grade)
  409. {
  410. NextTick(() =>
  411. {
  412. if (buildingBlock == null)
  413. return;
  414. if (buildingBlock.grade != grade) return;
  415. var items = buildingBlock.blockDefinition.grades[(int)grade].costToBuild;
  416. var total = 0;
  417. foreach (var item in items)
  418. total += (int)item.amount;
  419. var experience = (int)Math.Ceiling(UpgradeBuildingTable[grade] * total);
  420. ExpGain(FindRpgInfo(player), experience, player);
  421. });
  422. return null;
  423. }
  424.  
  425.  
  426. void OnDispenserBonus(ResourceDispenser dispenser, BasePlayer player, Item item)
  427. {
  428. var rpgInfo = FindRpgInfo(player);
  429. if (rpgInfo == null)
  430. return;
  431. var gatherType = dispenser.gatherType;
  432. HRK skillType;
  433. switch (gatherType)
  434. {
  435. case ResourceDispenser.GatherType.Tree:
  436. skillType = HRK.Lumberjack;
  437. break;
  438. case ResourceDispenser.GatherType.Ore:
  439. skillType = HRK.Miner;
  440. break;
  441. case ResourceDispenser.GatherType.Flesh:
  442. skillType = HRK.Hunter;
  443. break;
  444. default:
  445. ExpGain(rpgInfo, item.amount, player);
  446. return;
  447. }
  448.  
  449. int skillPoints;
  450. if (rpgInfo.Skills.TryGetValue(skillType, out skillPoints))
  451. item.amount = GatherModifierInt(skillPoints, skillType, item.amount);
  452. ExpGain(rpgInfo, (int)Math.Ceiling(item.amount * ExpRateTable[gatherType]), player);
  453. if (Economics == null)
  454. return;
  455. Economics.Call("Deposit", player.UserIDString, (double)item.amount * EcoBoost);
  456. return;
  457. }
  458. void OnPlayerDisconnected(BasePlayer player)
  459. {
  460. GUIInfo.Remove(player.userID);
  461. }
  462.  
  463. void OnUseNPC(BasePlayer npc, BasePlayer player)
  464. {
  465. if (!Trainer.Contains(npc.userID)) return;
  466. NpcGui(player);
  467. }
  468.  
  469. void OnServerSave()
  470. {
  471. SaveRpg();
  472. }
  473.  
  474. void OnServerShutdown()
  475. {
  476. SaveRpg();
  477. }
  478.  
  479. #region Hooks
  480. bool GiveEXP(BasePlayer player, int xp)
  481. {
  482. if (player == null || xp <= 0) return false;
  483. ExpGain(FindRpgInfo(player), xp, player);
  484. return true;
  485. }
  486. #endregion
  487.  
  488. #region Internal
  489. private bool OnAttackedInternal(BasePlayer player, HitInfo hitInfo)
  490. {
  491. var attacker = hitInfo.Initiator as BasePlayer;
  492. if (!(hitInfo.Initiator is BaseNpc || attacker != null && player.userID != attacker.userID)) return false;
  493. var rpgInfo = FindRpgInfo(player);
  494. if (Random.Range(0f, 1f) <= rpgInfo.GetEvasion())
  495. {
  496. ChatMessage(player, HMK.Dodged);
  497. ChatMessage(attacker, HMK.TargetDodged);
  498. return true;
  499. }
  500. if (player.displayName == null) return false;
  501. if (player.userID < 700000000) return false;
  502. hitInfo.damageTypes.ScaleAll(1 - rpgInfo.GetBlock());
  503. return false;
  504. }
  505.  
  506. private void OnEntityDeployedInternal(BasePlayer player, BaseEntity entity, IDictionary<string, ulong> data)
  507. {
  508. if (player == null || entity == null) return;
  509. if (!AllowedEntites.Contains(EntityName(entity), StringComparer.OrdinalIgnoreCase)) return;
  510. var instanceId = EntityId(entity);
  511. if (data.ContainsKey(instanceId))
  512. {
  513. ChatMessage(player, HMK.IdAlreadyExists, instanceId);
  514. return;
  515. }
  516. data.Add(instanceId, player.userID);
  517. }
  518. #endregion
  519. #endregion
  520.  
  521. #region Commands
  522. [ChatCommand("h")]
  523. void cmdHuntShortcut(BasePlayer player, string command, string[] args)
  524. {
  525. HandleChatCommand(player, args);
  526. }
  527.  
  528. [ChatCommand("hunt")]
  529. void cmdHunt(BasePlayer player, string command, string[] args)
  530. {
  531. HandleChatCommand(player, args);
  532. }
  533.  
  534. [ChatCommand("hg")]
  535. void cmdHuntGui(BasePlayer player, string command, string[] args)
  536. {
  537. if (Trainer.Length > 0 && !player.IsAdmin) return;
  538. ProfileGui(player);
  539. }
  540.  
  541. [ConsoleCommand("hunt.cmd")]
  542. private void cmdCmd(ConsoleSystem.Arg arg)
  543. {
  544. var player = arg.Player();
  545. GUIInfo guiInfo;
  546. if (player == null || !GUIInfo.TryGetValue(player.userID, out guiInfo))
  547. return;
  548. if (Trainer.Length > 0 && !IsNPCInRange(player.transform.position) && !IsAdmin(arg))
  549. {
  550. DestroyUi(player, guiInfo.LastMain);
  551. return;
  552. }
  553. HandleChatCommand(player, arg.Args, true);
  554. if (Trainer.Length > 0) NpcGui(player, true);
  555. else ProfileGui(player, true);
  556. }
  557.  
  558. [ConsoleCommand("hunt.saverpg")]
  559. private void cmdSaveRPG(ConsoleSystem.Arg arg)
  560. {
  561. if (!IsAdmin(arg)) return;
  562. SaveRpg();
  563. }
  564.  
  565. [ConsoleCommand("hunt.resetrpg")]
  566. private void cmdResetRPG(ConsoleSystem.Arg arg)
  567. {
  568. if (!IsAdmin(arg)) return;
  569. foreach (var rpgInfoPair in Data.Profiles)
  570. rpgInfoPair.Value.ResetSkills();
  571. Data.Profiles.Clear();
  572. Data.Furnaces.Clear();
  573. Data.Quarries.Clear();
  574. SaveRpg();
  575. }
  576.  
  577. [ConsoleCommand("hunt.lvlup")]
  578. private void cmdLevelUp(ConsoleSystem.Arg arg)
  579. {
  580. if (!IsAdmin(arg) || !arg.HasArgs()) return;
  581. var player = arg.Player();
  582. int desiredLevel;
  583. if (arg.HasArgs(2))
  584. {
  585. player = FindPlayer(arg.GetString(0));
  586. desiredLevel = arg.GetInt(1);
  587. }
  588. else
  589. desiredLevel = arg.GetInt(0);
  590. if (player == null)
  591. {
  592. arg.ReplyWith(_(HMK.NotFoundPlayer, arg.Player()));
  593. return;
  594. }
  595. var rpgInfo = FindRpgInfo(player);
  596. if (desiredLevel == 0 || desiredLevel <= rpgInfo.Level) return;
  597. rpgInfo.LevelUp(desiredLevel);
  598. NotifyLevelUp(player, rpgInfo);
  599. arg.ReplyWith(_(HMK.PlayerLevelUp, arg.Player(), player.displayName, desiredLevel));
  600. }
  601.  
  602. [ConsoleCommand("hunt.lvlreset")]
  603. private void cmdLvlReset(ConsoleSystem.Arg arg)
  604. {
  605. if (AdminReset && !IsAdmin(arg)) return;
  606. var player = arg.Player();
  607. if (arg.HasArgs() && IsAdmin(arg))
  608. player = FindPlayer(arg.GetString(0));
  609. var rpgInfo = player == null ? FindRpgInfo(Convert.ToUInt64(arg.GetString(0))) : FindRpgInfo(player);
  610. if (rpgInfo == null)
  611. {
  612. arg.ReplyWith(_(HMK.NotFoundPlayer, arg.Player()));
  613. return;
  614. }
  615. rpgInfo.Reset();
  616. if (player != null) UpdateEffectsPlayer(player, rpgInfo);
  617. arg.ReplyWith(_(HMK.PlayerLevelUp, arg.Player(), player?.displayName, 0));
  618. }
  619.  
  620. [ConsoleCommand("hunt.statreset")]
  621. private void cmdStatReset(ConsoleSystem.Arg arg)
  622. {
  623. if (AdminReset && !IsAdmin(arg)) return;
  624. var player = arg.Player();
  625. if (arg.HasArgs() && IsAdmin(arg))
  626. {
  627. var target = arg.GetString(0);
  628. if (target.Equals("*"))
  629. {
  630. foreach (var rpgInfoPair in Data.Profiles)
  631. {
  632. rpgInfoPair.Value.ResetStats();
  633. player = FindPlayer(rpgInfoPair.Key);
  634. if (player != null) UpdateEffectsPlayer(player, rpgInfoPair.Value);
  635. }
  636. SaveRpg();
  637. arg.ReplyWith(_(HMK.StatResetPlayer, arg.Player(), "All players"));
  638. return;
  639. }
  640. player = FindPlayer(target);
  641. }
  642. var rpgInfo = player == null ? FindRpgInfo(Convert.ToUInt64(arg.GetString(0))) : FindRpgInfo(player);
  643. if (rpgInfo == null)
  644. {
  645. arg.ReplyWith(_(HMK.NotFoundPlayer, arg.Player()));
  646. return;
  647. }
  648. rpgInfo.ResetStats();
  649. if (player != null) UpdateEffectsPlayer(player, rpgInfo);
  650. arg.ReplyWith(player == arg.Player() ? _(HMK.StatReset, arg.Player()) : _(HMK.StatResetPlayer, arg.Player(), player?.displayName));
  651. }
  652.  
  653. [ConsoleCommand("hunt.skillreset")]
  654. private void cmdSkillReset(ConsoleSystem.Arg arg)
  655. {
  656. if (AdminReset && !IsAdmin(arg)) return;
  657. var player = arg.Player();
  658. if (arg.HasArgs() && IsAdmin(arg))
  659. {
  660. var target = arg.GetString(0);
  661. if (target.Equals("*"))
  662. {
  663. foreach (var rpgInfoPair in Data.Profiles)
  664. {
  665. rpgInfoPair.Value.ResetSkills();
  666. player = FindPlayer(rpgInfoPair.Key);
  667. if (player != null) UpdateGatherPlayer(player, rpgInfoPair.Value);
  668. }
  669. SaveRpg();
  670. arg.ReplyWith(_(HMK.SkillResetPlayer, arg.Player(), "All players"));
  671. return;
  672. }
  673. player = FindPlayer(target);
  674. }
  675. var rpgInfo = player == null ? FindRpgInfo(Convert.ToUInt64(arg.GetString(0))) : FindRpgInfo(player);
  676. if (rpgInfo == null)
  677. {
  678. arg.ReplyWith(_(HMK.NotFoundPlayer, arg.Player()));
  679. return;
  680. }
  681. rpgInfo.ResetSkills();
  682. if (player != null) UpdateGatherPlayer(player, rpgInfo);
  683. arg.ReplyWith(player == arg.Player() ? _(HMK.SkillReset, arg.Player()) : _(HMK.SkillResetPlayer, arg.Player(), player?.displayName));
  684. }
  685.  
  686. [ConsoleCommand("hunt.genxptable")]
  687. private void cmdGenerateXPTable(ConsoleSystem.Arg arg)
  688. {
  689. if (!IsAdmin(arg)) return;
  690. arg.ReplyWith(_(HMK.GenerateXp, arg.Player()));
  691. var baseXP = arg.HasArgs() ? arg.GetInt(0) : HKD.BaseXp;
  692. var levelMultiplier = arg.HasArgs(2) ? arg.GetFloat(1) : HKD.LevelMultiplier;
  693. var levelModule = arg.HasArgs(3) ? arg.GetInt(2) : HKD.LevelModule;
  694. var moduleReducer = arg.HasArgs(4) ? arg.GetFloat(3) : HKD.ModuleReducer;
  695. //TODO merge old levels to new?
  696. var xpTable = HuntTablesGenerator.GenerateXPTable(HKD.MaximumLevel, baseXP, levelMultiplier, levelModule, moduleReducer);
  697. Config[HK.XPTable] = xpTable;
  698. RPGInfo.XPTable = xpTable.Values.ToArray();
  699. SaveConfig();
  700. }
  701.  
  702. private void HandleChatCommand(BasePlayer player, string[] args, bool npc = false)
  703. {
  704. if (args.Length == 0)
  705. {
  706. ChatMessage(player, HMK.Help);
  707. return;
  708. }
  709. var rpgInfo = FindRpgInfo(player);
  710. var cmdArg = args[0].ToLower();
  711. switch (cmdArg)
  712. {
  713. case "about":
  714. ChatMessage(player, HMK.About);
  715. return;
  716. case "shortcuts":
  717. ChatMessage(player, HMK.Shortcuts);
  718. return;
  719. case "p":
  720. case "profile":
  721. ChatMessage(player, Profile(rpgInfo, player));
  722. return;
  723. case "pp":
  724. case "profilepreferences":
  725. ChatMessage(player, HMK.ProfilePreferences);
  726. return;
  727. case "skill":
  728. DisplaySkillCommand(player, args);
  729. return;
  730. case "skilllist":
  731. ListSkills(player);
  732. return;
  733. case "lvlup":
  734. LevelUpChatHandler(player, args, rpgInfo);
  735. return;
  736. case "xp":
  737. ChatMessage(player, XPProgression(player, rpgInfo));
  738. return;
  739. case "xp%":
  740. ChangePlayerXPMessagePreference(player, args, rpgInfo);
  741. return;
  742. case "craftmsg":
  743. ToggleCraftMessage(player, rpgInfo);
  744. return;
  745. case "ba":
  746. ToggleBlinkArrow(player, rpgInfo);
  747. return;
  748. case "aba":
  749. ToggleAutoBlinkArrow(player, rpgInfo);
  750. return;
  751. case "sp":
  752. ToggleShowProfile(player, rpgInfo);
  753. return;
  754. case "sh":
  755. ToggleShowHud(player, rpgInfo);
  756. return;
  757. case "top":
  758. ShowTop(player);
  759. return;
  760. case "popup":
  761. HMK msgType;
  762. try
  763. {
  764. msgType = (HMK)Enum.Parse(typeof(HMK), args[1], true);
  765. }
  766. catch (System.Exception)
  767. {
  768. return;
  769. }
  770. PopupNotifications?.Call("CreatePopupNotification", _(msgType, player), player);
  771. return;
  772. }
  773. if (Trainer.Length > 0 && !IsNPCInRange(player.transform.position) && !player.IsAdmin)
  774. {
  775. ChatMessage(player, HMK.NeedNpc);
  776. return;
  777. }
  778. switch (cmdArg)
  779. {
  780. case "lvlreset":
  781. if (AdminReset && !player.IsAdmin)
  782. {
  783. ChatMessage(player, HMK.NotAnAdmin);
  784. return;
  785. }
  786. rpgInfo.Reset();
  787. UpdateEffectsPlayer(player, rpgInfo);
  788. return;
  789. case "sts":
  790. case "statset":
  791. SetStatsCommand(player, args, rpgInfo, npc);
  792. return;
  793. case "statreset":
  794. if (AdminReset && !player.IsAdmin)
  795. {
  796. ChatMessage(player, HMK.NotAnAdmin);
  797. return;
  798. }
  799. rpgInfo.ResetStats();
  800. UpdateEffectsPlayer(player, rpgInfo);
  801. return;
  802. case "sks":
  803. case "skillset":
  804. SetSkillsCommand(player, args, rpgInfo, npc);
  805. return;
  806. case "skillreset":
  807. if (AdminReset && !player.IsAdmin)
  808. {
  809. ChatMessage(player, HMK.NotAnAdmin);
  810. return;
  811. }
  812. rpgInfo.ResetSkills();
  813. UpdateGatherPlayer(player, rpgInfo);
  814. return;
  815. default:
  816. ChatMessage(player, HMK.InvalidCommand, args[0]);
  817. return;
  818. }
  819. }
  820.  
  821. private void ListSkills(BasePlayer player)
  822. {
  823. var sb = new StringBuilder();
  824. foreach (var skill in SkillTable.Values)
  825. {
  826. if (!skill.Enabled) continue;
  827. sb.Clear();
  828. SkillInfo(player, sb, skill, 100);
  829. ChatMessage(player, sb.ToString());
  830. }
  831. }
  832.  
  833. private void SkillInfo(BasePlayer player, StringBuilder sb, Skill skill, int cut = 0)
  834. {
  835. sb.AppendLine(_(HMK.SkillInfoHeader, player, skill.Name, skill.RequiredLevel));
  836. for (var i = 0; i < skill.RequiredSkills.Count; i++)
  837. sb.AppendLine($"Lvl {i + 1}: " + string.Join(" | ", skill.RequiredSkills[i].Select(s => $"{s.Key} Lvl {s.Value}").ToArray()));
  838. for (var i = 0; i < skill.RequiredStats.Count; i++)
  839. sb.AppendLine($"Lvl {i + 1}: " + string.Join(" | ", skill.RequiredStats[i].Select(s => $"{s.Key}: {s.Value}").ToArray()));
  840. var cost = FindRpgInfo(player).GetSkillPointsCostNext(skill);
  841. if (cost > 1)
  842. sb.AppendLine(_(HMK.SkillCost, player, cost));
  843.  
  844. var description = skill.Description != HMK.None ? _(skill.Description, player) : string.Empty;
  845. if (cut > 0)
  846. sb.Append(description.Length > cut ? $"{description.Substring(0, cut)}..." : description);
  847. else
  848. sb.Append(description);
  849. if (cut <= 0 && skill.Usage != HMK.None)
  850. {
  851. sb.AppendLine();
  852. sb.Append(_(HMK.Usage, player, _(skill.Usage, player)));
  853. }
  854. }
  855.  
  856. private void ShowTop(BasePlayer player)
  857. {
  858. var players = Data.Profiles.Values.ToArray();
  859. Array.Sort(players, (a, b) =>
  860. {
  861. if (a.Level != b.Level) return a.Level > b.Level ? -1 : 1;
  862. if (a.Experience == b.Experience) return 0;
  863. return a.Experience > b.Experience ? -1 : 1;
  864. });
  865. for (var i = 0; i < 10; i++)
  866. ChatMessage(player, HMK.TopPlayer, i + 1, players[i].SteamName, players[i].Level);
  867. }
  868.  
  869. private void ToggleAutoBlinkArrow(BasePlayer player, RPGInfo rpgInfo)
  870. {
  871. rpgInfo.Preferences.AutoToggleBlinkArrow = !rpgInfo.Preferences.AutoToggleBlinkArrow;
  872. var toggleBlinkArrowStatus = rpgInfo.Preferences.AutoToggleBlinkArrow ? _(HMK.On, player) : _(HMK.Off, player);
  873. ChatMessage(player, HMK.BlinkToggle, toggleBlinkArrowStatus);
  874. }
  875.  
  876. private void ToggleBlinkArrow(BasePlayer player, RPGInfo rpgInfo)
  877. {
  878. rpgInfo.Preferences.UseBlinkArrow = !rpgInfo.Preferences.UseBlinkArrow;
  879. var blinkArrowStatus = rpgInfo.Preferences.UseBlinkArrow ? _(HMK.On, player) : _(HMK.Off, player);
  880. ChatMessage(player, HMK.BlinkStatus, blinkArrowStatus);
  881. }
  882.  
  883. private void ToggleCraftMessage(BasePlayer player, RPGInfo rpgInfo)
  884. {
  885. rpgInfo.Preferences.ShowCraftMessage = !rpgInfo.Preferences.ShowCraftMessage;
  886. var craftMessageStatus = rpgInfo.Preferences.ShowCraftMessage ? _(HMK.On, player) : _(HMK.Off, player);
  887. ChatMessage(player, HMK.CraftMessage, craftMessageStatus);
  888. }
  889.  
  890. private void ToggleShowProfile(BasePlayer player, RPGInfo rpgInfo)
  891. {
  892. rpgInfo.Preferences.ShowProfile = !rpgInfo.Preferences.ShowProfile;
  893. var showProfileStatus = rpgInfo.Preferences.ShowProfile ? _(HMK.On, player) : _(HMK.Off, player);
  894. ChatMessage(player, HMK.ProfileMessage, showProfileStatus);
  895. }
  896.  
  897. private void ToggleShowHud(BasePlayer player, RPGInfo rpgInfo)
  898. {
  899. rpgInfo.Preferences.ShowHud++;
  900. if (rpgInfo.Preferences.ShowHud > 2)
  901. rpgInfo.Preferences.ShowHud = 0;
  902. if (rpgInfo.Preferences.ShowHud > 0)
  903. UpdateHud(player);
  904. else
  905. {
  906. GUIInfo guiInfo;
  907. if (GUIInfo.TryGetValue(player.userID, out guiInfo))
  908. DestroyUi(player, guiInfo.LastHud);
  909. }
  910. }
  911.  
  912. private void DisplaySkillCommand(BasePlayer player, string[] args)
  913. {
  914. var commandArgs = args?.Length - 1 ?? 0;
  915. if (commandArgs != 1)
  916. {
  917. ChatMessage(player, HMK.InvalidCommand, args[0]);
  918. return;
  919. }
  920. HRK skillType;
  921. try
  922. {
  923. skillType = (HRK)Enum.Parse(typeof(HRK), args[1], true);
  924. }
  925. catch (System.Exception)
  926. {
  927. ChatMessage(player, HMK.InvalidSkillName);
  928. return;
  929. }
  930. Skill skill;
  931. if (!SkillTable.TryGetValue(skillType, out skill) || !skill.Enabled)
  932. {
  933. ChatMessage(player, HMK.InvalidSkillName);
  934. return;
  935. }
  936. var sb = new StringBuilder();
  937. SkillInfo(player, sb, skill);
  938. ChatMessage(player, sb.ToString());
  939. }
  940.  
  941. private void SetSkillsCommand(BasePlayer player, string[] args, RPGInfo rpgInfo, bool npc = false)
  942. {
  943. var commandArgs = args?.Length - 1 ?? 0;
  944. if (args == null || commandArgs < 2 || commandArgs % 2 != 0)
  945. {
  946. ChatMessage(player, HMK.InvalidCommand, args[0]);
  947. return;
  948. }
  949. var pairs = commandArgs / 2 + 1;
  950. for (var i = 1; i < pairs; i++)
  951. {
  952. var index = i * 2 - 1;
  953. HRK skillType;
  954. try
  955. {
  956. skillType = (HRK)Enum.Parse(typeof(HRK), args[index], true);
  957. }
  958. catch
  959. {
  960. ChatMessage(player, HMK.InvalidCommand, args[0]);
  961. continue;
  962. }
  963. int level;
  964. if (!int.TryParse(args[index + 1], out level))
  965. {
  966. ChatMessage(player, HMK.InvalidCommand, args[0]);
  967. continue;
  968. }
  969.  
  970. Skill skill;
  971. if (SkillTable.TryGetValue(skillType, out skill))
  972. {
  973. if (!skill.Enabled)
  974. {
  975. ChatMessage(player, HMK.SkillDisabled);
  976. continue;
  977. }
  978. HMK reason;
  979. var levelsAdded = rpgInfo.AddSkill(skill, level, out reason, Pets);
  980. if (levelsAdded > 0)
  981. {
  982. if (!npc) ChatMessage(player, HMK.SkillUp, skill.Name, levelsAdded);
  983. switch (skill.Type)
  984. {
  985. case HRK.Lumberjack:
  986. case HRK.Miner:
  987. case HRK.Hunter:
  988. UpdateGatherPlayer(player, rpgInfo);
  989. break;
  990. }
  991. }
  992. else
  993. {
  994. if (reason == HMK.NotEnoughPoints)
  995. ChatMessage(player, reason, rpgInfo.GetSkillPointsCostNext(skill, level));
  996. else
  997. ChatMessage(player, reason);
  998. ChatMessage(player, HMK.SkillInfo);
  999. }
  1000. }
  1001. else
  1002. ChatMessage(player, HMK.InvalidSkillName);
  1003. }
  1004. UpdateHud(player, true);
  1005. }
  1006.  
  1007. private void SetStatsCommand(BasePlayer player, string[] args, RPGInfo rpgInfo, bool npc = false)
  1008. {
  1009. var commandArgs = args?.Length - 1 ?? 0;
  1010. if (commandArgs < 2 || commandArgs % 2 != 0)
  1011. {
  1012. ChatMessage(player, HMK.InvalidCommand, args[0]);
  1013. return;
  1014. }
  1015. var pairs = commandArgs / 2 + 1;
  1016. for (var i = 1; i < pairs; i++)
  1017. {
  1018. var index = i * 2 - 1;
  1019. int points;
  1020. if (!int.TryParse(args[index + 1], out points))
  1021. {
  1022. ChatMessage(player, HMK.InvalidCommand, args[index + 1]);
  1023. continue;
  1024. }
  1025. HRK statType;
  1026. try
  1027. {
  1028. statType = (HRK)Enum.Parse(typeof(HRK), args[index], true);
  1029. }
  1030. catch
  1031. {
  1032. ChatMessage(player, HMK.InvalidCommand, args[index]);
  1033. continue;
  1034. }
  1035.  
  1036. switch (statType)
  1037. {
  1038. case HRK.Agi:
  1039. case HRK.Int:
  1040. case HRK.Str:
  1041. if (rpgInfo.AddStat(statType, points))
  1042. {
  1043. if (!npc) ChatMessage(player, (HMK)Enum.Parse(typeof(HMK), statType + "Color", true), $"+{points}");
  1044. }
  1045. else
  1046. ChatMessage(player, HMK.NotEnoughPoints, rpgInfo.GetStatPointsCost(statType, points));
  1047. break;
  1048. default:
  1049. ChatMessage(player, HMK.InvalidCommand, args[index]);
  1050. break;
  1051. }
  1052. }
  1053. UpdateHud(player, true);
  1054. }
  1055.  
  1056. private void LevelUpChatHandler(BasePlayer player, string[] args, RPGInfo rpgInfo)
  1057. {
  1058. if (!player.IsAdmin) return;
  1059. var commandArgs = args?.Length - 1 ?? 0;
  1060. if (args == null || commandArgs > 2 || commandArgs < 1)
  1061. {
  1062. ChatMessage(player, HMK.InvalidCommand, args[0]);
  1063. return;
  1064. }
  1065. var callerPlayer = player;
  1066. var levelIndex = 1;
  1067. if (commandArgs == 2)
  1068. {
  1069. levelIndex = 2;
  1070. player = FindPlayer(args[1].ToLower());
  1071. if (player == null)
  1072. {
  1073. ChatMessage(callerPlayer, HMK.NotFoundPlayer);
  1074. return;
  1075. }
  1076. rpgInfo = FindRpgInfo(player);
  1077. }
  1078. int desiredLevel;
  1079. if (!int.TryParse(args[levelIndex], out desiredLevel))
  1080. {
  1081. ChatMessage(callerPlayer, HMK.InvalidCommand, args[0]);
  1082. return;
  1083. }
  1084. if (desiredLevel <= rpgInfo.Level) return;
  1085. rpgInfo.LevelUp(desiredLevel);
  1086. NotifyLevelUp(player, rpgInfo);
  1087. if (callerPlayer != player)
  1088. ChatMessage(callerPlayer, HMK.PlayerLevelUp, player.displayName, desiredLevel);
  1089. }
  1090.  
  1091. private void ChangePlayerXPMessagePreference(BasePlayer player, string[] args, RPGInfo rpgInfo)
  1092. {
  1093. var commandArgs = args.Length - 1;
  1094. if (commandArgs != 1)
  1095. {
  1096. ChatMessage(player, HMK.InvalidCommand, args[0]);
  1097. return;
  1098. }
  1099. float xpPercent;
  1100. if (!float.TryParse(args[1], out xpPercent))
  1101. {
  1102. ChatMessage(player, HMK.InvalidCommand, args[0]);
  1103. return;
  1104. }
  1105. rpgInfo.Preferences.ShowXPMessagePercent = xpPercent / 100;
  1106. ChatMessage(player, HMK.XpMessage, rpgInfo.Preferences.ShowXPMessagePercent);
  1107. }
  1108.  
  1109. private bool IsAdmin(ConsoleSystem.Arg arg)
  1110. {
  1111. if (arg.Connection == null || arg.Player().IsAdmin) return true;
  1112. arg.ReplyWith(_(HMK.NotAnAdmin, arg.Player()));
  1113. return false;
  1114. }
  1115. #endregion
  1116.  
  1117. #region Config
  1118. protected override void LoadDefaultConfig() => DefaultConfig();
  1119.  
  1120. private void DefaultConfig()
  1121. {
  1122. //Config.Clear();
  1123. //this will only be called if there is not a config file, or it needs updating
  1124. Config[HK.ConfigVersion] = Version;
  1125. Config[HK.DataVersion] = DataVersion;
  1126. Config[HK.AdminReset] = GetConfig(HK.AdminReset, false);
  1127. Config[HK.MaximumLevel] = GetConfig(HK.MaximumLevel, 200);
  1128. Config[HK.ShowHud] = GetConfig(HK.ShowHud, true);
  1129. Config[HK.ShowProfile] = GetConfig(HK.ShowProfile, false);
  1130. Config[HK.DefaultHud] = GetConfig(HK.DefaultHud, 1);
  1131. Config[HK.NightXP] = GetConfig(HK.NightXP, 2);
  1132. Config[HK.EcoBoost] = GetConfig(HK.EcoBoost, 1);
  1133. Config[HK.DeleteProfileAfterOfflineDays] = GetConfig(HK.DeleteProfileAfterOfflineDays, 0);
  1134. Config[HK.Trainer] = GetConfig(HK.Trainer, new ulong[0]);
  1135. Config[HK.DeathReducerK] = GetConfig(HK.DeathReducerK, HKD.DeathReducer);
  1136. Config[HK.Defaults] = HuntTablesGenerator.GenerateDefaults();
  1137. Config[HK.XPTable] = HuntTablesGenerator.GenerateXPTable(HKD.MaximumLevel, HKD.BaseXp, HKD.LevelMultiplier, HKD.LevelModule, HKD.ModuleReducer).OrderBy(e => e.Key).ToDictionary(e => e.Key, e => e.Value);
  1138. Config[HK.ExpRateTable] = HuntTablesGenerator.GenerateExpRateTable();
  1139. Config[HK.MaxStatsTable] = HuntTablesGenerator.GenerateMaxStatsTable();
  1140. Config[HK.SkillTable] = HuntTablesGenerator.GenerateSkillTable();
  1141. Config[HK.ResearchSkillTable] = HuntTablesGenerator.GenerateResearchTable();
  1142. Config[HK.UpgradeBuildTable] = HuntTablesGenerator.GenerateUpgradeBuildingTable();
  1143. Config[HK.ChatPrefix] = GetConfig(HK.ChatPrefix, "<color=#ADD8E6>Hunt</color>: {0}");
  1144. Config[HK.TameTable] = HuntTablesGenerator.GenerateTameTable();
  1145. Config[HK.AllowedEntities] = HuntTablesGenerator.GenerateAllowedEntites();
  1146. SaveConfig();
  1147. }
  1148.  
  1149. private void DefaultItems()
  1150. {
  1151. Config[HK.ItemTable] = HuntTablesGenerator.GenerateItemTable();
  1152. SaveConfig();
  1153. }
  1154.  
  1155. private void UpdateLang()
  1156. {
  1157. var messagesConfig = new Dictionary<HMK, string>
  1158. {
  1159. {
  1160. HMK.Help, string.Join("\n", new[]
  1161. {
  1162. "To get an overview about the Hunt RPG, type \"/hunt about\"",
  1163. "To see you available shortcuts commdands, type \"/hunt shortcuts\"",
  1164. "To see you player profile, type \"/hunt profile\"",
  1165. "To see you current xp, type \"/hunt xp\"",
  1166. "To see how to change you profile preferences, type \"/hunt profilepreferences\"",
  1167. "To use an easy to use GUI to spend point type \"/hg\""
  1168. })
  1169. },
  1170. {
  1171. HMK.Shortcuts, string.Join("\n", new[]
  1172. {
  1173. "\"/hunt\" = \"/h\"",
  1174. "\"/hunt profile\" = \"/h p\"",
  1175. "\"/hunt profilepreferences\" = \"/h pp\"",
  1176. "\"/hunt statset\" = \"/h sts\".",
  1177. "You can set multiple stats at a time like this \"/h sts agi 30 str 45\".",
  1178. "\"/hunt skillset\" = \"/h sks\"",
  1179. "You can set multiple skillpoints at a time like this \"/h sks lumberjack 3 miner 2\".",
  1180. })
  1181. },
  1182. {
  1183. HMK.ProfilePreferences, string.Join("\n", new[]
  1184. {
  1185. "To see change the % changed need to show the xp message, type \"/hunt xp% <percentnumber>\"",
  1186. "To toggle crafting message type \"/hunt craftmsg\"",
  1187. "To toggle blink arrow skill type \"/hunt ba\"",
  1188. "To toggle blink arrow skill auto toggle type \"/hunt aba\"",
  1189. "To toggle auto show profile \"/hunt sp\""
  1190. })
  1191. },
  1192. {
  1193. HMK.About, string.Join("\n", new[]
  1194. {
  1195. "=================================================",
  1196. "The Hunt RPG system in development.",
  1197. "Currently maintained by Default.",
  1198. "It is consisted of levels, stats atributes, skills and later on specializations.",
  1199. "Currently there are 3 attributes, each of then give you and specific enhancement.",
  1200. "Strength reduces the damage you take, and allows for more ammo in magazines.",
  1201. "Agillity gives you dodge chance",
  1202. "Intelligence decreases your items crafting time",
  1203. "Right now you can level up by gathering resources.",
  1204. "Each level gives you 1 point in each attribute. And 3 more to distribute.",
  1205. "Each level gives you 1 skill point to distribute",
  1206. "Each skill have its required level, and later on it will require specific stats.",
  1207. "To see the all the available skills and its description type \"/hunt skilllist\"",
  1208. "To learn more about Hunt RPG go to the plugin page at <link>",
  1209. "================================================="
  1210. })
  1211. },
  1212. {
  1213. HMK.DataUpdated, string.Join("\n", new[]
  1214. {
  1215. "<color=#FFFF00>Plugin was updated to new version!</color>",
  1216. "<color=#FFA500>Your profile needed to be reset, but your level was saved. You just need to redistribute.</color>",
  1217. "<color=#FF0000>Furnaces were not saved though, so build new ones for the blacksmith skill to be applied (If you have, or when you get it)!</color>"
  1218. })
  1219. },
  1220. {HMK.InvalidCommand, "You ran the \"{0}\" command incorrectly. Type \"/hunt\" to get help"},
  1221. {HMK.SkillInfo, "Type \"/hunt skill <skillname>\" to see the skill info"},
  1222. {HMK.NotEnoughPoints, "<color=#FFA500>You don't have enought points to set! Cost: {0}</color>"},
  1223. {HMK.NotEnoughLevels, "<color=#FFA500>You dont have the minimum level to learn this skill!</color>"},
  1224. {HMK.NotEnoughStrength, "<color=#FFA500>You dont have enough strength to learn this skill!</color>"},
  1225. {HMK.NotEnoughAgility, "<color=#FFA500>You dont have enough agility to learn this skill!</color>"},
  1226. {HMK.NotEnoughIntelligence, "<color=#FFA500>You dont have enough intelligence to learn this skill!</color>"},
  1227. {HMK.NotEnoughSkill, "<color=#FFA500>You dont have the required skill to learn this skill!</color>"},
  1228. {HMK.InvalidSkillName, "<color=#FFA500>There is no such skill! Type \"/hunt skilllist\" to see the available skills</color>"},
  1229. {HMK.SkillDisabled, "<color=#FFA500>This skill is blocked in this server.</color>"},
  1230. {HMK.NotFoundItem, "<color=#FFA500>Item {0} not found.</color>"},
  1231. {HMK.ResearchBlocked, "<color=#FFA500>Item {0} research is blocked by in this server.</color>"},
  1232. {HMK.NotLearnedSkill, "<color=#FFA500>You havent learned this skill yet.</color>"},
  1233. {HMK.AlreadyAtMaxLevel, "<color=#FFA500>You have mastered this skill already!</color>"},
  1234. {HMK.IdAlreadyExists, "<color=#FFFF00>Entity id already exists for {0}!</color>"},
  1235. {HMK.PetsPlugin, "Pets plugin was not found, disabling taming skill"},
  1236. {HMK.BuildingOwnersPlugin, "Building Owners plugin was not found, disabling blink to arrow skill"},
  1237. {HMK.Died, "Oh no man! You just died! You lost {0:P} of XP because of this..."},
  1238. {HMK.CantBlink, "Can't blink there!"},
  1239. {HMK.CantBlinkOther, "Can't blink to other player house!"},
  1240. {HMK.BlinkedRecently, "Blinked recently! You might get dizzy, give it a rest. Time left to blink again: {0}"},
  1241. {HMK.BlinkToggle, "Auto Toggle Blink Arrow is now: {0}"},
  1242. {HMK.BlinkStatus, "Blink Arrow is now: {0}"},
  1243. {HMK.CraftingEnd, "Crafting will end in {0:F} seconds. Reduced in {1:F} seconds"},
  1244. {HMK.CraftMessage, "Craft message is now: {0}"},
  1245. {HMK.NotFoundPlayer, "Player not found."},
  1246. {HMK.NotAnAdmin, "You are not an admin."},
  1247. {HMK.On, "On"},
  1248. {HMK.Off, "Off"},
  1249. {HMK.XpMessage, "XP will be shown at every {0:P} change"},
  1250. {HMK.AvailableSkills, "Available Skills:"},
  1251. {HMK.Dodged, "You <color=#FFOOOO>dodged</color> an attack!"},
  1252. {HMK.TargetDodged, "Your target <color=#FFOOOO>Dodged</color>"},
  1253. {HMK.LevelUp, "<color=#FFFF00>Level Up! You are now level {0}</color>"},
  1254. {HMK.CurrentXp, "Current XP: {0:P}{1}"},
  1255. {HMK.NightXp, " Bonus Night Exp On"},
  1256. {HMK.Level, "Level: {0}"},
  1257. {HMK.LevelShort, "Lvl: {0}"},
  1258. {HMK.DamageBlock, "Damage Block: {0:P}"},
  1259. {HMK.EvasionChance, "Evasion Chance: {0:P}"},
  1260. {HMK.CraftingReducer, "Crafting Reducer: {0:P}"},
  1261. {HMK.StatPoints, "Stat points: {0}"},
  1262. {HMK.SkillPoints, "Skill points: {0}"},
  1263. {HMK.ResearchItem, "In order to research an item you must have it on your inventory"},
  1264. {HMK.ResearchType, "You can't research items of this type"},
  1265. {HMK.ResearchSkill, "Your research skills are not high enough. Required {0}"},
  1266. {HMK.ResearchSuccess, "You managed to reverse enginier the {0}. The blueprint its on your inventory"},
  1267. {HMK.ResearchFail, "OPS! While you were trying to research the {0} you accidently broke it."},
  1268. {HMK.ResearchReuse, "You have tried this moments ago, give it a rest. Time left to research again: {0}"},
  1269. {HMK.PlayerLevelUp, "Player {0} lvlup to {1}"},
  1270. {HMK.AgiColor, "<color=#008000>Agi: {0}</color>"},
  1271. {HMK.StrColor, "<color=#FF0000>Str: {0}</color>"},
  1272. {HMK.IntColor, "<color=#0000FF>Int: {0}</color>"},
  1273. {HMK.Agi, "Agi: {0}"},
  1274. {HMK.Str, "Str: {0}"},
  1275. {HMK.Int, "Int: {0}"},
  1276. {HMK.StatReset, "You reset your stats."},
  1277. {HMK.StatResetPlayer, "{0} stats reset."},
  1278. {HMK.SkillReset, "You reset your skills."},
  1279. {HMK.SkillResetPlayer, "{0} skills reset."},
  1280. {HMK.ProfileMessage, "Auto show profile is now: {0}"},
  1281. {HMK.NeedNpc, "You cannot teach yourself. Go to the next trainer!"},
  1282. {HMK.GenerateXp, "Generating XP table..."},
  1283. {HMK.SkillsHeader, "========<color=#800080>Skills</color>========"},
  1284. {HMK.ProfileHeader, "========{0}========"},
  1285. {
  1286. HMK.Loaded, string.Join("\n", new[]
  1287. {
  1288. "<color=#ADD8E6>Hunt</color>: RPG Loaded!",
  1289. "<color=#ADD8E6>Hunt</color>: To see the Hunt RPG help type \"/hunt\" or \"/h\"",
  1290. "<color=#ADD8E6>Hunt</color>: To open the GUI type \"/hg\""
  1291. })
  1292. },
  1293. {HMK.StatusLoad, "{0} profiles, {1} furnaces, {2} quarries loaded"},
  1294. {HMK.StatusSave, "{0} profiles, {1} furnaces, {2} quarries saved"},
  1295. {HMK.TopPlayer, "{0}. {1} Lvl {2}"},
  1296. {HMK.SkillUp, "<color=#800080>{0}: +{1}</color>"},
  1297. {HMK.SkillCost, "Each skill level costs {0} skillpoints."},
  1298. {HMK.SkillInfoHeader, "<color=#ADD8E6>{0}</color> - Required: Lvl: {1}"},
  1299. {HMK.Usage, "<color=#008080>Usage:</color> {0}"},
  1300. {HMK.LumberjackDesc, "This skill allows you to gather wood faster. Each point gives you more wood per hit."},
  1301. {HMK.MinerDesc, "This skill allows you to gather stones faster. Each point gives you more stones per hit."},
  1302. {HMK.HunterDesc, "This skill allows you to gather resources faster from animals. Each point gives you more resources per hit."},
  1303. {HMK.GathererDesc, "This skill allows you to gather more resources from pickup. Each point gives you more resources."},
  1304. {HMK.ResearcherDesc, "This skill allows you to research items you have. Each level enables a type of type to be researched and decreases 2 minutes of cooldown. Table: Level 1 - Tools (10 min); Level 2 - Clothes (8 min); Level 3 - Construction and Resources (6 min); Level 4 - Ammunition and Medic (4 min); Level 5 - Weapons (2 min)"},
  1305. {HMK.BlacksmithDesc, "This skill allows your furnaces to melt more resources each time. Each level gives increase the productivity by 1."},
  1306. {HMK.BlinkarrowDesc, "This skill allows you to blink to your arrow destination from time to time. Each level deacreases the cooldown in 2 minutes."},
  1307. {HMK.TamerDesc, "This skill allows you to tame a animal as your pet. Level 1 allows chicken, level 2 allows boar, level 3 allows stag, level 4 allows wolf, level 5 allows bear, level 6 allows horse."},
  1308. {HMK.BlinkarrowUsage, "Just shoot an Arrow at desired blink location. To toogle this skill type \"/h ba\" . To change the auto toggle for this skill type \"/h aba\""},
  1309. {HMK.ResearcherUsage, "To research an item type \"/research \"Item Name\"\". In order to research an item, you must have it on your invetory, and have the required skill level for that item tier."},
  1310. {HMK.TamerUsage, "Type \"/pet\" to toggle taming. To tame get close to the animal and press your USE button(E). After tamed press USE looking at something, if its terrain he will move, if its a player or other animal it he will attack. If looking at him it will start following you. To set the pet free type \"/pet free\"."},
  1311. {HMK.ButtonClose, "Close"},
  1312. {HMK.ButtonResetSkills, "Reset Skills"},
  1313. {HMK.ButtonResetStats, "Reset Stats"},
  1314. {HMK.AgiDesc, "Agillity gives you the chance to <colour=#FF0000>dodge</color> an attack!"},
  1315. {HMK.StrDesc, "Strength gives you the ability to hold more ammunition in guns. More on the way!"},
  1316. {HMK.IntDesc, "Intelligence decreases your items crafting time"}
  1317. };
  1318. lang.RegisterMessages(messagesConfig.ToDictionary(m => m.Key.ToString(), m => m.Value), this);
  1319. }
  1320.  
  1321. private void UpdateData()
  1322. {
  1323. if (!updatePlayerData) return;
  1324. // this will only be called if this version requires a data wipe and the config is outdated.
  1325. Puts("This version needs a wipe to data file.");
  1326. Puts("Dont worry levels will be kept! =]");
  1327. var keys = Data.Profiles.Keys.ToArray();
  1328. foreach (var key in keys)
  1329. {
  1330. var value = Data.Profiles[key];
  1331. var displayName = FindPlayer(key)?.displayName ?? value.SteamName;
  1332. var rpgInfo = new RPGInfo(displayName, DefaultHud, ShowProfile);
  1333. rpgInfo.LevelUp(value.Level);
  1334. Data.Profiles[key] = rpgInfo;
  1335. }
  1336. Puts("Data file updated.");
  1337. Config[HK.DataVersion] = DataVersion;
  1338. SaveConfig();
  1339. SaveRpg();
  1340. updatePlayerData = false;
  1341. }
  1342.  
  1343. private void LoadRpg(VersionNumber dataVersion)
  1344. {
  1345. RPGInfo.Perm = permission;
  1346. var defaults = ReadFromConfig<HuntDefaults>(HK.Defaults);
  1347. RPGInfo.XPTable = ReadFromConfig<Dictionary<int, long>>(HK.XPTable).OrderBy(e => e.Key).ToDictionary(e => e.Key, e => e.Value).Values.ToArray();
  1348. RPGInfo.MaxLevel = defaults.MaximumLevel;
  1349. RPGInfo.MaxStatsTable = ReadFromConfig<Dictionary<HRK, HuntRPGExt.Modifier>>(HK.MaxStatsTable);
  1350. RPGInfo.SkillPointsGain = defaults.SkillPointsGain;
  1351. RPGInfo.SkillPointsPerLevel = defaults.SkillPointsPerLevel;
  1352. RPGInfo.StatPointsGain = defaults.StatPointsGain;
  1353. RPGInfo.StatPointsPerLevel = defaults.StatPointsPerLevel;
  1354. RPGInfo.TameTable = ReadFromConfig<Dictionary<int, string>>(HK.TameTable);
  1355. var newStructure = dataVersion < new VersionNumber(0, 9, 3);
  1356. if (newStructure)
  1357. huntDataFile.Settings.ContractResolver = new IgnoreJsonPropertyResolver();
  1358. Data = huntDataFile.ReadObject<HuntData>();
  1359. if (newStructure)
  1360. huntDataFile.Settings.ContractResolver = new DefaultContractResolver();
  1361. ChatPrefix = ReadFromConfig<string>(HK.ChatPrefix);
  1362. ExpRateTable = ReadFromConfig<Dictionary<ResourceDispenser.GatherType, float>>(HK.ExpRateTable);
  1363. SkillTable = ReadFromConfig<Dictionary<HRK, Skill>>(HK.SkillTable);
  1364. ItemTable = ReadFromConfig<Dictionary<string, ItemInfo>>(HK.ItemTable);
  1365. ResearchTable = ReadFromConfig<Dictionary<string, int>>(HK.ResearchSkillTable);
  1366. UpgradeBuildingTable = ReadFromConfig<Dictionary<BuildingGrade.Enum, float>>(HK.UpgradeBuildTable);
  1367. AllowedEntites = ReadFromConfig<string[]>(HK.AllowedEntities);
  1368. AdminReset = ReadFromConfig<bool>(HK.AdminReset);
  1369. ShowHud = ReadFromConfig<bool>(HK.ShowHud);
  1370. ShowProfile = ReadFromConfig<bool>(HK.ShowProfile);
  1371. DefaultHud = ReadFromConfig<uint>(HK.DefaultHud);
  1372. NightXP = ReadFromConfig<float>(HK.NightXP);
  1373. EcoBoost = ReadFromConfig<double>(HK.EcoBoost);
  1374. DeleteProfileAfter = ReadFromConfig<int>(HK.DeleteProfileAfterOfflineDays);
  1375. Trainer = ReadFromConfig<ulong[]>(HK.Trainer);
  1376. DeathReducer = ReadFromConfig<float>(HK.DeathReducerK);
  1377. itemShortname = new Dictionary<string, string>();
  1378. foreach (var item in ItemManager.itemList)
  1379. {
  1380. var itemDisplayName = item.displayName.translated.ToLower();
  1381. if (!itemShortname.ContainsKey(itemDisplayName))
  1382. {
  1383. itemShortname.Add(itemDisplayName, item.shortname);
  1384. }
  1385. }
  1386.  
  1387. Puts(_(HMK.StatusLoad, Data.Profiles.Count, Data.Furnaces.Count, Data.Quarries.Count));
  1388.  
  1389. if (Pets == null)
  1390. {
  1391. Puts(_(HMK.PetsPlugin));
  1392. SkillTable[HRK.Tamer].Enabled = false;
  1393. }
  1394. SkillTable[HRK.Researcher].Enabled = false;
  1395. if (DeleteProfileAfter <= 0) return;
  1396. var now = Facepunch.Math.Epoch.Current;
  1397. var delTime = now - 86400 * DeleteProfileAfter;
  1398. var toRemove = new List<ulong>();
  1399. foreach (var profile in Data.Profiles)
  1400. {
  1401. if (profile.Value.LastSeen == 0)
  1402. {
  1403. profile.Value.LastSeen = now;
  1404. continue;
  1405. }
  1406. if (profile.Value.LastSeen < delTime)
  1407. {
  1408. toRemove.Add(profile.Key);
  1409. var data = Data.Furnaces.Where(pair => pair.Value == profile.Key).Select(pair => pair.Key).ToArray();
  1410. foreach (var key in data)
  1411. Data.Furnaces.Remove(key);
  1412. data = Data.Quarries.Where(pair => pair.Value == profile.Key).Select(pair => pair.Key).ToArray();
  1413. foreach (var key in data)
  1414. Data.Quarries.Remove(key);
  1415. }
  1416. }
  1417. foreach (var userId in toRemove)
  1418. Data.Profiles.Remove(userId);
  1419. }
  1420.  
  1421. private T ReadFromConfig<T>(string configKey)
  1422. {
  1423. return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(Config[configKey]));
  1424. }
  1425.  
  1426. private object GetConfig(string key, object defaultValue)
  1427. {
  1428. var value = Config[key];
  1429. if (value == null)
  1430. Config[key] = value = defaultValue;
  1431. return value;
  1432. }
  1433.  
  1434. private void SaveRpg(bool showMsgs = true)
  1435. {
  1436. if (Data == null) return;
  1437. //if (showMsgs)
  1438. // Puts("Data being saved...");
  1439. huntDataFile.WriteObject(Data);
  1440. if (!showMsgs) return;
  1441. Puts(_(HMK.StatusSave, Data.Profiles.Count, Data.Furnaces.Count, Data.Quarries.Count));
  1442. }
  1443. #endregion
  1444.  
  1445. #region CUI
  1446. private void GuiInit(BasePlayer player)
  1447. {
  1448. if (player == null) return;
  1449.  
  1450. if (player.HasPlayerFlag(BasePlayer.PlayerFlags.ReceivingSnapshot))
  1451. timer.Once(1, () => GuiInit(player));
  1452. else
  1453. UpdateHud(player);
  1454. }
  1455.  
  1456. private static CuiLabel CreateLabel(string text, int i, float rowHeight, TextAnchor align = TextAnchor.MiddleLeft, int fontSize = 15, string xMin = "0", string xMax = "1", string color = "1.0 1.0 1.0 1.0")
  1457. {
  1458. return new CuiLabel
  1459. {
  1460. Text =
  1461. {
  1462. Text = text,
  1463. FontSize = fontSize,
  1464. Align = align,
  1465. Color = color
  1466. },
  1467. RectTransform =
  1468. {
  1469. AnchorMin = $"{xMin} {1 - rowHeight*i + i * .002f}",
  1470. AnchorMax = $"{xMax} {1 - rowHeight*(i-1) + i * .002f}"
  1471. }
  1472. };
  1473. }
  1474.  
  1475. private static CuiButton CreateButton(string command, int i, float rowHeight, int fontSize = 15, string content = "+", string xMin = "0", string xMax = "1")
  1476. {
  1477. return new CuiButton
  1478. {
  1479. Button =
  1480. {
  1481. Command = command,
  1482. Color = "0.8 0.8 0.8 0.2"
  1483. },
  1484. RectTransform =
  1485. {
  1486. AnchorMin = $"{xMin} {1 - rowHeight*i + i * .002f}",
  1487. AnchorMax = $"{xMax} {1 - rowHeight*(i-1) + i * .002f}"
  1488. },
  1489. Text =
  1490. {
  1491. Text = content,
  1492. FontSize = fontSize,
  1493. Align = TextAnchor.MiddleCenter
  1494. }
  1495. };
  1496. }
  1497.  
  1498. private static CuiPanel CreatePanel(string anchorMin, string anchorMax, string color = "0 0 0 0")
  1499. {
  1500. return new CuiPanel
  1501. {
  1502. Image =
  1503. {
  1504. Color = color
  1505. },
  1506. RectTransform =
  1507. {
  1508. AnchorMin = anchorMin,
  1509. AnchorMax = anchorMax
  1510. }
  1511. };
  1512. }
  1513.  
  1514. private void NpcGui(BasePlayer player, bool repaint = false)
  1515. {
  1516. if (player == null) return;
  1517. var rpgInfo = FindRpgInfo(player);
  1518. GUIInfo guiInfo;
  1519. if (!GUIInfo.TryGetValue(player.userID, out guiInfo))
  1520. GUIInfo[player.userID] = guiInfo = new GUIInfo();
  1521. else
  1522. {
  1523. DestroyUi(player, guiInfo.LastInfo);
  1524. DestroyUi(player, guiInfo.LastStats);
  1525. DestroyUi(player, guiInfo.LastSkills);
  1526. }
  1527.  
  1528. const float height = 1 / (6f * 1.5f);
  1529. var heightS = 1f / (Math.Min(6, SkillTable.Count(skill => skill.Value.Enabled)) * 1.75f);
  1530. var elements = new CuiElementContainer();
  1531. if (!repaint || string.IsNullOrEmpty(guiInfo.LastMain))
  1532. {
  1533. guiInfo.LastMain = elements.Add(new CuiPanel
  1534. {
  1535. Image =
  1536. {
  1537. Color = "0.1 0.1 0.1 0.8"
  1538. },
  1539. RectTransform =
  1540. {
  1541. AnchorMin = "0 0",
  1542. AnchorMax = "1 1"
  1543. },
  1544. CursorEnabled = true
  1545. });
  1546. elements.Add(new CuiButton
  1547. {
  1548. Button =
  1549. {
  1550. Close = guiInfo.LastMain,
  1551. Color = "0.8 0.8 0.8 0.2"
  1552. },
  1553. RectTransform =
  1554. {
  1555. AnchorMin = "0.45 0.92",
  1556. AnchorMax = "0.55 0.98"
  1557. },
  1558. Text =
  1559. {
  1560. Text = _(HMK.ButtonClose, player),
  1561. FontSize = 20,
  1562. Align = TextAnchor.MiddleCenter
  1563. }
  1564. }, guiInfo.LastMain);
  1565. elements.Add(CreateLabel(rpgInfo.SteamName, 3, .06f, TextAnchor.MiddleCenter, 30, "0.3", "0.7"), guiInfo.LastMain);
  1566. var statsButtons = elements.Add(CreatePanel("0.4 0.1", "0.45 0.5"), guiInfo.LastMain);
  1567. elements.Add(CreateButton("hunt.cmd statset agi 1", 3, heightS, 18), statsButtons);
  1568. //elements.Add(CreateButton("hunt.cmd statset agi 10", 4, heightS, 18), statsButtons);
  1569. elements.Add(CreateButton("hunt.cmd statset str 1", 4, heightS, 18), statsButtons);
  1570. elements.Add(CreateButton("hunt.cmd statset int 1", 5, heightS, 18), statsButtons);
  1571. var skillsButtons = elements.Add(CreatePanel("0.8 0.1", "0.85 0.5"), guiInfo.LastMain);
  1572. var i = 3;
  1573. foreach (var skill in SkillTable.Where(skill => skill.Value.Enabled))
  1574. {
  1575. int level;
  1576. rpgInfo.Skills.TryGetValue(skill.Key, out level);
  1577. elements.Add(CreateButton($"hunt.cmd skillset {skill.Key} 1", i++, heightS, 18), skillsButtons);
  1578. }
  1579. if (!AdminReset || player.IsAdmin)
  1580. {
  1581. elements.Add(CreateButton("hunt.cmd statreset", 25, .04f, 18, _(HMK.ButtonResetStats, player), "0.2", "0.45"), guiInfo.LastMain);
  1582. elements.Add(CreateButton("hunt.cmd skillreset", 25, .04f, 18, _(HMK.ButtonResetSkills, player), "0.6", "0.85"), guiInfo.LastMain);
  1583. }
  1584. }
  1585.  
  1586. var info = guiInfo.LastInfo = elements.Add(CreatePanel("0.3 0.5", "0.7 0.8"), guiInfo.LastMain);
  1587. elements.Add(CreateLabel(_(HMK.Level, player, rpgInfo.Level), 1, height, TextAnchor.MiddleCenter, 20), info);
  1588. elements.Add(CreateLabel(XPProgression(player, rpgInfo), 2, height, TextAnchor.MiddleCenter, 20), info);
  1589. elements.Add(CreateLabel(_(HMK.DamageBlock, player, rpgInfo.GetBlock()), 4, height, TextAnchor.MiddleCenter, 20), info);
  1590. elements.Add(CreateLabel(_(HMK.EvasionChance, player, rpgInfo.GetEvasion()), 5, height, TextAnchor.MiddleCenter, 20), info);
  1591. elements.Add(CreateLabel(_(HMK.CraftingReducer, player, rpgInfo.GetCraftingReducer()), 6, height, TextAnchor.MiddleCenter, 20), info);
  1592.  
  1593. var stats = guiInfo.LastStats = elements.Add(CreatePanel("0.2 0.1", "0.39 0.5"), guiInfo.LastMain);
  1594. elements.Add(CreateLabel(_(HMK.StatPoints, player, rpgInfo.StatsPoints), 1, heightS, TextAnchor.MiddleLeft, 20), stats);
  1595. //elements.Add(CreateLabel(_(HMK.Agi, player, $"{rpgInfo.Agility} ({rpgInfo.GetStatPointsCost(HRK.Agi)})"), 3, heightS, TextAnchor.MiddleLeft, 18), stats);
  1596. elements.Add(CreateButton($"hunt.cmd popup {HMK.AgiDesc}", 3, heightS, 18, _(HMK.Agi, player, $"{rpgInfo.Agility} ({rpgInfo.GetStatPointsCost(HRK.Agi)})")), stats);
  1597. elements.Add(CreateButton($"hunt.cmd popup {HMK.StrDesc}", 4, heightS, 18, _(HMK.Str, player, $"{rpgInfo.Strength} ({rpgInfo.GetStatPointsCost(HRK.Str)})")), stats);
  1598. elements.Add(CreateButton($"hunt.cmd popup {HMK.IntDesc}", 5, heightS, 18, _(HMK.Int, player, $"{rpgInfo.Intelligence} ({rpgInfo.GetStatPointsCost(HRK.Int)})")), stats);
  1599.  
  1600. var skills = guiInfo.LastSkills = elements.Add(CreatePanel("0.6 0.1", "0.79 0.5"), guiInfo.LastMain);
  1601. elements.Add(CreateLabel(_(HMK.SkillPoints, player, rpgInfo.SkillPoints), 1, heightS, TextAnchor.MiddleLeft, 20), skills);
  1602. var j = 3;
  1603. foreach (var skill in SkillTable.Where(skill => skill.Value.Enabled))
  1604. {
  1605. int level;
  1606. rpgInfo.Skills.TryGetValue(skill.Key, out level);
  1607. //elements.Add(CreateLabel($"{skill.Value.Name}: {level}/{skill.Value.MaxLevel} ({rpgInfo.GetSkillPointsCostNext(skill.Value)})", j++, heightS, TextAnchor.MiddleLeft, 18), skills);
  1608. elements.Add(CreateButton($"hunt.cmd popup {skill.Value.Description}", j++, heightS, 18, $"{skill.Value.Name}: {level}/{skill.Value.MaxLevel} ({rpgInfo.GetSkillPointsCostNext(skill.Value)})"), skills);
  1609. }
  1610. CuiHelper.AddUi(player, elements);
  1611. }
  1612.  
  1613. private void ProfileGui(BasePlayer player, bool repaint = false)
  1614. {
  1615. if (player == null) return;
  1616. var rpgInfo = FindRpgInfo(player);
  1617. GUIInfo guiInfo;
  1618. if (!GUIInfo.TryGetValue(player.userID, out guiInfo))
  1619. GUIInfo[player.userID] = guiInfo = new GUIInfo();
  1620. else
  1621. DestroyUi(player, guiInfo.LastContent);
  1622.  
  1623. var skills = SkillTable.Where(skill => skill.Value.Enabled).ToArray();
  1624. var height = 1f / (9.5f + skills.Length) - .002f;
  1625.  
  1626. var elements = new CuiElementContainer();
  1627. if (!repaint || string.IsNullOrEmpty(guiInfo.LastMain))
  1628. {
  1629. guiInfo.LastMain = elements.Add(new CuiPanel
  1630. {
  1631. Image =
  1632. {
  1633. Color = "0.1 0.1 0.1 0.8"
  1634. },
  1635. RectTransform =
  1636. {
  1637. AnchorMin = "0.8 0.25",
  1638. AnchorMax = "0.995 0.845"
  1639. },
  1640. CursorEnabled = true
  1641. });
  1642. elements.Add(new CuiButton
  1643. {
  1644. Button =
  1645. {
  1646. Close = guiInfo.LastMain,
  1647. Color = "0.8 0.8 0.8 0.2"
  1648. },
  1649. RectTransform =
  1650. {
  1651. AnchorMin = "0.86 0.93",
  1652. AnchorMax = "0.97 0.99"
  1653. },
  1654. Text =
  1655. {
  1656. Text = "X",
  1657. FontSize = 20,
  1658. Align = TextAnchor.MiddleCenter
  1659. }
  1660. }, guiInfo.LastMain);
  1661. elements.Add(CreateLabel(rpgInfo.SteamName, 1, height, TextAnchor.MiddleLeft, 18, "0.06", "0.85"), guiInfo.LastMain);
  1662. var buttonsName = elements.Add(CreatePanel("0.86 0", "0.97 0.925"), guiInfo.LastMain);
  1663. elements.Add(CreateButton("hunt.cmd statset agi 1", 6, height), buttonsName);
  1664. elements.Add(CreateButton("hunt.cmd statset str 1", 7, height), buttonsName);
  1665. elements.Add(CreateButton("hunt.cmd statset int 1", 8, height), buttonsName);
  1666. var i = 9;
  1667. foreach (var skill in skills)
  1668. {
  1669. int level;
  1670. rpgInfo.Skills.TryGetValue(skill.Key, out level);
  1671. elements.Add(CreateButton($"hunt.cmd skillset {skill.Key} 1", i++, height), buttonsName);
  1672. }
  1673. if (!AdminReset || player.IsAdmin)
  1674. {
  1675. elements.Add(CreateButton("hunt.cmd statreset", i++, height, 15, "R"), buttonsName);
  1676. elements.Add(CreateButton("hunt.cmd skillreset", i, height, 15, "R"), buttonsName);
  1677. }
  1678. }
  1679. var contentName = guiInfo.LastContent = elements.Add(CreatePanel("0.06 0", "0.85 0.925"), guiInfo.LastMain);
  1680. elements.Add(CreateLabel(_(HMK.Level, player, rpgInfo.Level), 1, height), contentName);
  1681. elements.Add(CreateLabel(_(HMK.DamageBlock, player, rpgInfo.GetBlock()), 2, height), contentName);
  1682. elements.Add(CreateLabel(_(HMK.EvasionChance, player, rpgInfo.GetEvasion()), 3, height), contentName);
  1683. elements.Add(CreateLabel(_(HMK.CraftingReducer, player, rpgInfo.GetCraftingReducer()), 4, height), contentName);
  1684. elements.Add(CreateLabel(XPProgression(player, rpgInfo), 5, height), contentName);
  1685. elements.Add(CreateLabel(_(HMK.Agi, player, $"{rpgInfo.Agility} ({rpgInfo.GetStatPointsCost(HRK.Agi)})"), 6, height), contentName);
  1686. elements.Add(CreateLabel(_(HMK.Str, player, $"{rpgInfo.Strength} ({rpgInfo.GetStatPointsCost(HRK.Str)})"), 7, height), contentName);
  1687. elements.Add(CreateLabel(_(HMK.Int, player, $"{rpgInfo.Intelligence} ({rpgInfo.GetStatPointsCost(HRK.Int)})"), 8, height), contentName);
  1688. var j = 9;
  1689. foreach (var skill in skills)
  1690. {
  1691. int level;
  1692. rpgInfo.Skills.TryGetValue(skill.Key, out level);
  1693. elements.Add(CreateLabel($"{skill.Value.Name}: {level}/{skill.Value.MaxLevel} ({rpgInfo.GetSkillPointsCostNext(skill.Value)})", j++, height), contentName);
  1694. }
  1695. elements.Add(CreateLabel(_(HMK.StatPoints, player, rpgInfo.StatsPoints), j++, height), contentName);
  1696. elements.Add(CreateLabel(_(HMK.SkillPoints, player, rpgInfo.SkillPoints), j, height), contentName);
  1697. CuiHelper.AddUi(player, elements);
  1698. }
  1699.  
  1700. private void UpdateHud(BasePlayer player, bool repaint = false, bool points = true)
  1701. {
  1702. if (player == null || !ShowHud) return;
  1703. var rpgInfo = FindRpgInfo(player);
  1704. if (rpgInfo == null || rpgInfo.Preferences.ShowHud == 0) return;
  1705. GUIInfo guiInfo;
  1706. if (!GUIInfo.TryGetValue(player.userID, out guiInfo))
  1707. GUIInfo[player.userID] = guiInfo = new GUIInfo();
  1708. else
  1709. {
  1710. if (guiInfo.LastHudTime > Interface.Oxide.Now)
  1711. {
  1712. if (guiInfo.LastHudTimer == null) guiInfo.LastHudTimer = timer.Once(1, () => UpdateHud(player, repaint, points));
  1713. return;
  1714. }
  1715. guiInfo.LastHudTimer?.Destroy();
  1716. guiInfo.LastHudTimer = null;
  1717. guiInfo.LastHudTime = Interface.Oxide.Now + 1;
  1718. }
  1719.  
  1720. var elements = new CuiElementContainer();
  1721. if (!repaint || string.IsNullOrEmpty(guiInfo.LastHud))
  1722. {
  1723. DestroyUi(player, guiInfo.LastHud);
  1724. //elements.Add(CreateLabel($"{_(HMK.Level, player, rpgInfo.Level)}/{XPTable.Length}", 2, 1 / 3f), guiInfo.LastHud);
  1725. //AnchorMin = "0.822 0.045",
  1726. //AnchorMax = "0.9734 0.117"
  1727. if (rpgInfo.Preferences.ShowHud == 1)
  1728. guiInfo.LastHud = elements.Add(CreatePanel("0.0266 0.045", "0.178 0.117"));
  1729. else
  1730. guiInfo.LastHud = elements.Add(CreatePanel("0 0", "1 0.03"));
  1731. }
  1732.  
  1733. if (points) DestroyUi(player, guiInfo.LastHudFirst);
  1734. DestroyUi(player, guiInfo.LastHudSecond);
  1735.  
  1736. //TODO Rework entire UI
  1737.  
  1738. if (rpgInfo.Preferences.ShowHud == 1)
  1739. {
  1740. if (points)
  1741. {
  1742. guiInfo.LastHudFirst = elements.Add(CreatePanel("4.15 0.71", "5.15 1", "0.16 0.16 0.16 0.8"), guiInfo.LastHud);
  1743. elements.Add(CreateLabel($"{_(HMK.StatPoints, player, rpgInfo.StatsPoints)} {_(HMK.SkillPoints, player, rpgInfo.SkillPoints)}", 1, 1, TextAnchor.MiddleCenter, 15, "0", "1", "1.0 1.0 1.0 0.3"), guiInfo.LastHudFirst);
  1744. }
  1745. guiInfo.LastHudSecond = elements.Add(CreatePanel("4.15 0.21", "5.15 0.70", "0.16 0.16 0.16 0.8"), guiInfo.LastHud);
  1746. elements.Add(CreateLabel($"{rpgInfo.Level}", 1, 1, TextAnchor.MiddleCenter, 15, "0", "0.19", "1.0 1.0 1.0 0.3"), guiInfo.LastHudSecond);
  1747. elements.Add(CreatePanel("0.2 0.1", $"{.2f + .77f * CurrentPercent(rpgInfo)} 0.88", "0.8392156862745098 0.6823529411764706 0 0.5"), guiInfo.LastHudSecond);
  1748. elements.Add(CreateLabel($"{rpgInfo.Experience}/{rpgInfo.RequiredExperience()}", 1, 1, TextAnchor.MiddleCenter, 15, "0.2", "1", "1.0 1.0 1.0 0.3"), guiInfo.LastHudSecond);
  1749. //elements.Add(CreateLabel($"{player._health}/{player._maxHealth}", 1, 1, TextAnchor.MiddleCenter, 15, "1.0", "2.55", "1.0 1.0 1.0 0.3"), guiInfo.LastHudSecond);
  1750. }
  1751. else
  1752. {
  1753. if (points)
  1754. {
  1755. guiInfo.LastHudFirst = elements.Add(CreatePanel("0.45 0.2", "0.55 1", "0.13 0.13 0.13 0"), guiInfo.LastHud);
  1756. elements.Add(CreateLabel($"{_(HMK.Level, player, rpgInfo.Level)}", 1, 1, TextAnchor.MiddleCenter, 15, "0", "0.95", "1.0 0.6470588235294118 0.0 0.6"), guiInfo.LastHudFirst);
  1757. }
  1758. guiInfo.LastHudSecond = elements.Add(CreatePanel("0 0", "1 0.2", "0.13 0.13 0.13 0.75"), guiInfo.LastHud);
  1759. elements.Add(CreatePanel("0.0015 0.3", $"{.9985f * CurrentPercent(rpgInfo)} 0.7", "1.0 0.6470588235294118 0.0 0.6"), guiInfo.LastHudSecond);
  1760. }
  1761.  
  1762. //Puts(CuiHelper.ToJson(elements));
  1763. CuiHelper.AddUi(player, elements);
  1764. }
  1765.  
  1766.  
  1767. //TODO Make another UI for maximum health and finish implementing maximum health changes.
  1768. /*private void HealthGui(BasePlayer player, bool repaint = false)
  1769. {
  1770. if (player == null) return;
  1771. var rpgInfo = FindRpgInfo(player);
  1772. if (rpgInfo == null || rpgInfo.Preferences.ShowHud == 0) return;
  1773. GUIInfo guiInfo;
  1774. if (!GUIInfo.TryGetValue(player.userID, out guiInfo))
  1775. GUIInfo[player.userID] = guiInfo = new GUIInfo();
  1776. else
  1777. {
  1778. if (guiInfo.LastHudTime > Interface.Oxide.Now)
  1779. {
  1780. if (guiInfo.LastHudTimer == null) guiInfo.LastHudTimer = timer.Once(1, () => HealthGui(player, repaint));
  1781. return;
  1782. }
  1783. guiInfo.LastHudTimer?.Destroy();
  1784. guiInfo.LastHudTimer = null;
  1785. guiInfo.LastHudTime = Interface.Oxide.Now + 1;
  1786. }
  1787.  
  1788. var elements = new CuiElementContainer();
  1789.  
  1790.  
  1791.  
  1792. elements.Add(CreateLabel($"{player._health}/{player._maxHealth}", 1, 1, TextAnchor.MiddleCenter, 15, "1.0", "2.55", "1.0 1.0 1.0 0.3"), guiInfo.LastHudSecond);
  1793.  
  1794. }*/
  1795.  
  1796.  
  1797.  
  1798.  
  1799.  
  1800. #endregion
  1801.  
  1802. private void ExpGain(RPGInfo rpgInfo, int experience, BasePlayer player)
  1803. {
  1804. var steamId = player.userID;
  1805. if (IsNight())
  1806. experience = (int)(experience * NightXP);
  1807. if (rpgInfo.AddExperience(experience))
  1808. {
  1809. NotifyLevelUp(player, rpgInfo);
  1810. PlayerLastPercentChange[steamId] = 0;
  1811. }
  1812. else if (!ShowHud)
  1813. {
  1814. var currentPercent = CurrentPercent(rpgInfo);
  1815. float lastPercent;
  1816. if (!PlayerLastPercentChange.TryGetValue(steamId, out lastPercent))
  1817. PlayerLastPercentChange.Add(steamId, lastPercent = currentPercent);
  1818. var percentChange = currentPercent - lastPercent;
  1819. if (percentChange >= rpgInfo.Preferences.ShowXPMessagePercent)
  1820. {
  1821. ChatMessage(player, XPProgression(player, rpgInfo));
  1822. PlayerLastPercentChange[steamId] = currentPercent;
  1823. }
  1824. }
  1825. UpdateHud(player, true, false);
  1826. }
  1827.  
  1828. private void NotifyLevelUp(BasePlayer player, RPGInfo rpgInfo)
  1829. {
  1830. ChatMessage(player, HMK.LevelUp, rpgInfo.Level);
  1831. if (rpgInfo.Preferences.ShowProfile) ChatMessage(player, Profile(rpgInfo, player));
  1832. UpdateHud(player, true);
  1833. //SaveRPG(false);
  1834. }
  1835.  
  1836. private string Profile(RPGInfo rpgInfo, BasePlayer player)
  1837. {
  1838. var sb = new StringBuilder();
  1839. sb.AppendLine();
  1840. sb.AppendLine(_(HMK.ProfileHeader, player, rpgInfo.SteamName));
  1841. sb.AppendLine(_(HMK.Level, player, rpgInfo.Level));
  1842. sb.AppendLine(_(HMK.DamageBlock, player, rpgInfo.GetBlock()));
  1843. sb.AppendLine(_(HMK.EvasionChance, player, rpgInfo.GetEvasion()));
  1844. sb.AppendLine(_(HMK.CraftingReducer, player, rpgInfo.GetCraftingReducer()));
  1845. sb.AppendLine(XPProgression(player, rpgInfo));
  1846. var Agi = _(HMK.AgiColor, player, $"{rpgInfo.Agility} ({rpgInfo.GetStatPointsCost(HRK.Agi)})");
  1847. var Str = _(HMK.StrColor, player, $"{rpgInfo.Strength} ({rpgInfo.GetStatPointsCost(HRK.Str)})");
  1848. var Int = _(HMK.IntColor, player, $"{rpgInfo.Intelligence} ({rpgInfo.GetStatPointsCost(HRK.Int)})");
  1849. sb.AppendLine($"{Agi} | {Str} | {Int}");
  1850. sb.AppendLine(_(HMK.StatPoints, player, rpgInfo.StatsPoints));
  1851. sb.AppendLine(_(HMK.SkillPoints, player, rpgInfo.SkillPoints));
  1852. sb.AppendLine(_(HMK.SkillsHeader, player));
  1853. foreach (var skill in SkillTable.Where(skill => skill.Value.Enabled))
  1854. {
  1855. int level;
  1856. rpgInfo.Skills.TryGetValue(skill.Key, out level);
  1857. sb.AppendLine($"{skill.Value.Name}: {level}/{skill.Value.MaxLevel} ({rpgInfo.GetSkillPointsCostNext(skill.Value)})");
  1858. }
  1859. sb.AppendLine("====================");
  1860. return sb.ToString();
  1861. }
  1862.  
  1863. #region Skill
  1864. private void UpdateGatherPlayer(BasePlayer player, RPGInfo rpgInfo)
  1865. {
  1866. foreach (var item in player.inventory.AllItems())
  1867. UpdateGather(item, rpgInfo);
  1868. }
  1869.  
  1870. private void UpdateMagazinPlayer(BasePlayer player, RPGInfo rpgInfo)
  1871. {
  1872. if (MagazinBoost == true) return;
  1873. foreach (var item in player.inventory.AllItems())
  1874. UpdateMagazin(item, rpgInfo);
  1875. }
  1876.  
  1877. private void UpdateEffectsPlayer(BasePlayer player, RPGInfo rpgInfo)
  1878. {
  1879. foreach (var item in player.inventory.AllItems())
  1880. {
  1881. UpdateGather(item, rpgInfo);
  1882. if (MagazinBoost == true) return;
  1883. UpdateMagazin(item, rpgInfo);
  1884. }
  1885. }
  1886.  
  1887. private void UpdateGather(Item item, RPGInfo rpgInfo)
  1888. {
  1889. var melee = item.GetHeldEntity() as BaseMelee;
  1890. if (melee == null) return;
  1891. var defaultMelee = GameManager.server.FindPrefab(melee.PrefabName).GetComponent<BaseMelee>();
  1892. UpdateGatherPropertyEntry(melee.gathering.Tree, defaultMelee.gathering.Tree, rpgInfo, HRK.Lumberjack);
  1893. //SendReply(item.GetOwnerPlayer(), "Item: {0} G: {1:0.00} C: {2:0.00} D: {3:0.00}", item.info.shortname, defaultMelee.gathering.Tree.gatherDamage, defaultMelee.gathering.Tree.conditionLost, defaultMelee.gathering.Tree.destroyFraction);
  1894. //SendReply(item.GetOwnerPlayer(), "Item: {0} G: {1:0.00} C: {2:0.00} D: {3:0.00}", item.info.shortname, melee.gathering.Tree.gatherDamage, melee.gathering.Tree.conditionLost, melee.gathering.Tree.destroyFraction);
  1895. UpdateGatherPropertyEntry(melee.gathering.Ore, defaultMelee.gathering.Ore, rpgInfo, HRK.Miner);
  1896. UpdateGatherPropertyEntry(melee.gathering.Flesh, defaultMelee.gathering.Flesh, rpgInfo, HRK.Hunter);
  1897. }
  1898.  
  1899. private void UpdateGatherPropertyEntry(ResourceDispenser.GatherPropertyEntry entry, ResourceDispenser.GatherPropertyEntry defaultEntry, RPGInfo rpgInfo, HRK skillType)
  1900. {
  1901. int skillPoints;
  1902. float modifier;
  1903. float reducer;
  1904. if (rpgInfo.Skills.TryGetValue(skillType, out skillPoints))
  1905. {
  1906. modifier = GatherModifier(skillPoints, skillType);
  1907. reducer = Mathf.Lerp(.5f, 1, 1 - modifier / GatherModifier(SkillTable[skillType].MaxLevel, skillType));
  1908. }
  1909. else
  1910. {
  1911. modifier = 1;
  1912. reducer = 1;
  1913. }
  1914. entry.gatherDamage = modifier * defaultEntry.gatherDamage;
  1915. entry.conditionLost = reducer * defaultEntry.conditionLost;
  1916. entry.destroyFraction = reducer * defaultEntry.destroyFraction;
  1917. }
  1918.  
  1919. private void UpdateMagazin(Item item, RPGInfo rpgInfo)
  1920. {
  1921. if (MagazinBoost == true) return;
  1922. var projectile = item.GetHeldEntity() as BaseProjectile;
  1923. if (projectile == null) return;
  1924. var capacity = (int)(projectile.primaryMagazine.definition.builtInSize * (1f + rpgInfo.Strength / (RPGInfo.XPTable.Length * 2.0f)));
  1925. if (projectile.primaryMagazine.capacity == capacity) return;
  1926. projectile.primaryMagazine.contents += capacity - projectile.primaryMagazine.capacity;
  1927. projectile.primaryMagazine.capacity = capacity;
  1928. projectile.SendNetworkUpdateImmediate();
  1929. item.GetOwnerPlayer()?.inventory.ServerUpdate(0f);
  1930. }
  1931.  
  1932. private void SetCooldown(int skillPoints, float time, Dictionary<HRK, float> playerCooldowns, HRK skillKey)
  1933. {
  1934. playerCooldowns[skillKey] = CooldownModifier(skillPoints, skillKey, time);
  1935. }
  1936.  
  1937. private Dictionary<HRK, float> PlayerCooldowns(ulong steamId)
  1938. {
  1939. Dictionary<HRK, float> playerCooldowns;
  1940. if (!SkillsCooldowns.TryGetValue(steamId, out playerCooldowns))
  1941. SkillsCooldowns.Add(steamId, playerCooldowns = new Dictionary<HRK, float>());
  1942. return playerCooldowns;
  1943. }
  1944.  
  1945. private float GatherModifier(int skillpoints, HRK skillType)
  1946. {
  1947. //TODO cache values?
  1948. return (float)Math.Pow(SkillTable[skillType].Modifiers[HRK.Gather].Args[0], skillpoints);
  1949. //var skill = SkillTable[skillType];
  1950. //return 1f + skillpoints / (float)skill.MaxLevel * skill.Modifiers[HRK.Gather].Args[0];
  1951. }
  1952.  
  1953. private int GatherModifierInt(int skillpoints, HRK skillType, int value)
  1954. {
  1955. return (int)Math.Ceiling(GatherModifier(skillpoints, skillType) * value);
  1956. }
  1957.  
  1958. private float CooldownModifier(int skillpoints, HRK skillKey, float currenttime)
  1959. {
  1960. var modifier = SkillTable[skillKey].Modifiers[HRK.Cooldown];
  1961. var baseCooldown = modifier.Args[0] * 60f;
  1962. var timeToReduce = (skillpoints - 1f) * modifier.Args[1] * 60f;
  1963. var finalCooldown = baseCooldown - timeToReduce;
  1964. return finalCooldown + currenttime;
  1965. }
  1966. #endregion
  1967.  
  1968. #region Message
  1969. private string _(HMK key, params object[] args)
  1970. {
  1971. return _(key, (string)null, args);
  1972. }
  1973.  
  1974. private string _(HMK key, BasePlayer player, params object[] args)
  1975. {
  1976. return _(key, player?.UserIDString, args);
  1977. }
  1978.  
  1979. private string _(HMK key, string userid = null, params object[] args)
  1980. {
  1981. var message = lang.GetMessage(key.ToString(), this, userid);
  1982. return message != null ? args.Length > 0 ? string.Format(message, args) : message : string.Empty;
  1983. }
  1984.  
  1985. private void ChatMessage(BasePlayer player, string message)
  1986. {
  1987. if (player?.net == null) return;
  1988. player.ChatMessage(string.Format(ChatPrefix, message));
  1989. }
  1990.  
  1991. private void ChatMessage(BasePlayer player, HMK key, params object[] args)
  1992. {
  1993. if (player?.net == null) return;
  1994. ChatMessage(player, _(key, player.UserIDString, args));
  1995. }
  1996. #endregion
  1997.  
  1998. #region Util
  1999. private RPGInfo FindRpgInfo(BasePlayer player)
  2000. {
  2001. if (Data == null) return null;
  2002. var userId = player.userID;
  2003. RPGInfo config;
  2004. if (Data.Profiles.TryGetValue(userId, out config))
  2005. {
  2006. config.SetUserId(userId);
  2007. config.SteamName = player.displayName;
  2008. config.LastSeen = Facepunch.Math.Epoch.Current;
  2009. return config;
  2010. }
  2011. if (player.displayName == null) return null;
  2012. if (player.userID < 70000000000) return null;
  2013. Data.Profiles[userId] = config = new RPGInfo(player.displayName, DefaultHud, ShowProfile);
  2014. config.SetUserId(userId);
  2015. //SaveRPG();
  2016. return config;
  2017. }
  2018.  
  2019. private RPGInfo FindRpgInfo(ulong userId)
  2020. {
  2021. RPGInfo config;
  2022. Data.Profiles.TryGetValue(userId, out config);
  2023. config?.SetUserId(userId);
  2024. return config;
  2025. }
  2026.  
  2027. private bool IsBuildingAllowed(Vector3 position, BasePlayer player)
  2028. {
  2029. var hits = Physics.OverlapSphere(position, 2f, triggerMask);
  2030. foreach (var collider in hits)
  2031. {
  2032. var buildingPrivlidge = collider.GetComponentInParent<BuildingPrivlidge>();
  2033. if (buildingPrivlidge == null) continue;
  2034. if (!buildingPrivlidge.IsAuthed(player)) return false;
  2035. }
  2036. return true;
  2037. }
  2038.  
  2039. private string XPProgression(BasePlayer player, RPGInfo rpgInfo)
  2040. {
  2041. var percent = CurrentPercent(rpgInfo);
  2042. var nightBonus = string.Empty;
  2043. if (IsNight())
  2044. nightBonus = _(HMK.NightXp, player);
  2045. return _(HMK.CurrentXp, player, percent, nightBonus);
  2046. }
  2047.  
  2048. private float CurrentPercent(RPGInfo rpgInfo)
  2049. {
  2050. var requiredXp = rpgInfo.RequiredExperience();
  2051. return requiredXp <= 0 ? 1 : Mathf.Clamp01(rpgInfo.Experience / (float)requiredXp);
  2052. }
  2053.  
  2054. private bool IsNPCInRange(Vector3 pos)
  2055. {
  2056. return Physics.OverlapSphere(pos, 3, playersMask).Select(col => col.GetComponentInParent<BasePlayer>()).Any(player => player != null && Trainer.Contains(player.userID));
  2057. }
  2058.  
  2059. private static void TeleportPlayerTo(BasePlayer player, Vector3 position)
  2060. {
  2061. player.MovePosition(position);
  2062. player.ClientRPCPlayer(null, player, "ForcePositionTo", position);
  2063. //TODO replace later
  2064. //ForcePlayerPosition(player, position);
  2065. }
  2066.  
  2067. private static Vector3 GetGround(Vector3 position)
  2068. {
  2069. var height = TerrainMeta.HeightMap.GetHeight(position);
  2070. position.y = Math.Max(position.y, height);
  2071. return position;
  2072. /*var raycastHits = Physics.RaycastAll(position, Vector3.forward, 25f).GetEnumerator();
  2073. var nearestDistance = 9999f;
  2074. var nearestPoint = Vector3.zero;
  2075. while (raycastHits.MoveNext())
  2076. {
  2077. if (raycastHits.Current == null) continue;
  2078. var raycastHit = (RaycastHit)raycastHits.Current;
  2079. if (raycastHit.distance < nearestDistance)
  2080. {
  2081. nearestDistance = raycastHit.distance;
  2082. nearestPoint = raycastHit.point;
  2083. }
  2084. }
  2085. return nearestPoint;*/
  2086. }
  2087.  
  2088. private static bool IsNight()
  2089. {
  2090. var dateTime = TOD_Sky.Instance.Cycle.DateTime;
  2091. return dateTime.Hour >= 19 || dateTime.Hour <= 5;
  2092. }
  2093.  
  2094. private static bool IsSkillReady(Dictionary<HRK, float> playerCooldowns, ref float availableAt, float time, HRK skillKey)
  2095. {
  2096. bool isReady;
  2097. if (playerCooldowns.TryGetValue(skillKey, out availableAt))
  2098. {
  2099. isReady = time >= availableAt;
  2100. }
  2101. else
  2102. {
  2103. isReady = true;
  2104. playerCooldowns.Add(skillKey, availableAt);
  2105. }
  2106. return isReady;
  2107. }
  2108.  
  2109. private static BasePlayer FindPlayer(string nameOrIdOrIp)
  2110. {
  2111. foreach (var activePlayer in BasePlayer.activePlayerList)
  2112. {
  2113. if (activePlayer.UserIDString == nameOrIdOrIp)
  2114. return activePlayer;
  2115. if (activePlayer.displayName.Contains(nameOrIdOrIp, CompareOptions.OrdinalIgnoreCase))
  2116. return activePlayer;
  2117. if (activePlayer.net?.connection != null && activePlayer.net.connection.ipaddress == nameOrIdOrIp)
  2118. return activePlayer;
  2119. }
  2120. foreach (var sleepingPlayer in BasePlayer.sleepingPlayerList)
  2121. {
  2122. if (sleepingPlayer.UserIDString == nameOrIdOrIp)
  2123. return sleepingPlayer;
  2124. if (sleepingPlayer.displayName.Contains(nameOrIdOrIp, CompareOptions.OrdinalIgnoreCase))
  2125. return sleepingPlayer;
  2126. }
  2127. return null;
  2128. }
  2129.  
  2130. private static BasePlayer FindPlayer(ulong userId)
  2131. {
  2132. foreach (var activePlayer in BasePlayer.activePlayerList)
  2133. {
  2134. if (activePlayer.userID == userId)
  2135. return activePlayer;
  2136. }
  2137. foreach (var sleepingPlayer in BasePlayer.sleepingPlayerList)
  2138. {
  2139. if (sleepingPlayer.userID == userId)
  2140. return sleepingPlayer;
  2141. }
  2142. return null;
  2143. }
  2144.  
  2145. private static string TimeLeft(float availableAt, float time)
  2146. {
  2147. var timeLeft = availableAt - time;
  2148. var formatableTime = new DateTime(TimeSpan.FromSeconds(timeLeft).Ticks);
  2149. return $"{formatableTime:mm\\:ss}";
  2150. }
  2151.  
  2152. private static string EntityId(BaseEntity entity)
  2153. {
  2154. if (entity == null) return "XYZ";
  2155. var position = entity.transform.position;
  2156. return $"X{position.x}Y{position.y}Z{position.z}";
  2157. }
  2158.  
  2159. private static string EntityName(BaseEntity entity)
  2160. {
  2161. var name = entity.ShortPrefabName;
  2162. var pos = name.LastIndexOf(".", StringComparison.Ordinal);
  2163. if (pos >= 0) name = name.Substring(0, pos);
  2164. return name;
  2165. }
  2166.  
  2167. private void DestroyUi(BasePlayer player, string name)
  2168. {
  2169. if (!string.IsNullOrEmpty(name)) CuiHelper.DestroyUi(player, name);
  2170. }
  2171. #endregion
  2172.  
  2173. public class IgnoreJsonPropertyResolver : DefaultContractResolver
  2174. {
  2175. private Dictionary<string, string> PropertyMappings { get; set; }
  2176.  
  2177. public IgnoreJsonPropertyResolver()
  2178. {
  2179. PropertyMappings = new Dictionary<string, string>();
  2180. var types = new[] { typeof(RPGInfo), typeof(ProfilePreferences) };
  2181. foreach (var type in types)
  2182. {
  2183. var fields = type.GetFields();
  2184. foreach (var fieldInfo in fields)
  2185. {
  2186. var jsonProperty = fieldInfo.GetCustomAttributes(typeof(JsonPropertyAttribute), false);
  2187. if (jsonProperty.Length > 0)
  2188. {
  2189. PropertyMappings.Add(((JsonPropertyAttribute)jsonProperty[0]).PropertyName, fieldInfo.Name);
  2190. }
  2191. }
  2192. var properties = type.GetProperties();
  2193. foreach (var propertyInfo in properties)
  2194. {
  2195. var jsonProperty = propertyInfo.GetCustomAttributes(typeof(JsonPropertyAttribute), false);
  2196. if (jsonProperty.Length > 0)
  2197. {
  2198. PropertyMappings.Add(((JsonPropertyAttribute)jsonProperty[0]).PropertyName, propertyInfo.Name);
  2199. }
  2200. }
  2201. }
  2202. }
  2203.  
  2204. protected string ResolvePropertyName(string propertyName)
  2205. {
  2206. string resolvedName;
  2207. return PropertyMappings.TryGetValue(propertyName, out resolvedName) ? resolvedName : base.ResolvePropertyName(propertyName);
  2208. }
  2209. }
  2210. }
  2211. }
  2212.  
  2213. namespace Oxide.Plugins.HuntRPGExt
  2214. {
  2215. public static class HuntTablesGenerator
  2216. {
  2217. public static Dictionary<int, long> GenerateXPTable(int maxLevel, int baseExp, float levelMultiplier, int levelModule, float moduleReducer)
  2218. {
  2219. var xpTable = new Dictionary<int, long>();
  2220. long currentLevel = baseExp;
  2221. xpTable.Add(0, baseExp);
  2222. for (var i = 1; i < maxLevel; i++)
  2223. {
  2224. if (i % levelModule == 0)
  2225. levelMultiplier -= moduleReducer;
  2226. if (levelMultiplier < 1.01f) levelMultiplier = 1.01f;
  2227. currentLevel = (long)(currentLevel * levelMultiplier);
  2228. xpTable.Add(i, currentLevel);
  2229. }
  2230. return xpTable;
  2231. }
  2232.  
  2233. public static Dictionary<HRK, Skill> GenerateSkillTable()
  2234. {
  2235. var skillTable = new Dictionary<HRK, Skill>();
  2236. var lumberJack = new Skill(HRK.Lumberjack, HMK.LumberjackDesc, 0, 20);
  2237. var woodAndFleshModifier = new Modifier( /*HRK.Gather, */new[] { 1.035265f });
  2238. lumberJack.AddModifier(HRK.Gather, woodAndFleshModifier);
  2239. skillTable.Add(HRK.Lumberjack, lumberJack);
  2240. var miner = new Skill(HRK.Miner, HMK.MinerDesc, 0, 20);
  2241. miner.AddModifier(HRK.Gather, new Modifier( /*HRK.Gather, */new[] { 1.02048f }));
  2242. skillTable.Add(HRK.Miner, miner);
  2243. var hunter = new Skill(HRK.Hunter, HMK.HunterDesc, 0, 20);
  2244. hunter.AddModifier(HRK.Gather, woodAndFleshModifier);
  2245. skillTable.Add(HRK.Hunter, hunter);
  2246. var gatherer = new Skill(HRK.Gatherer, HMK.GathererDesc, 0, 20);
  2247. gatherer.AddModifier(HRK.Gather, woodAndFleshModifier);
  2248. skillTable.Add(HRK.Gatherer, gatherer);
  2249. var researcher = new Skill(HRK.Researcher, HMK.ResearcherDesc, 30, 5)
  2250. {
  2251. SkillPointsPerLevel = 7,
  2252. Usage = HMK.ResearcherUsage,
  2253. Enabled = false
  2254. };
  2255. researcher.AddRequiredStat("int", researcher.RequiredLevel * 3);
  2256. researcher.AddModifier(HRK.Cooldown, new Modifier( /*HRK.Cooldown, */new[] { 10f, 2f }));
  2257. researcher.AddModifier(HRK.Chance, new Modifier( /*HRK.Chance, */new[] { .6f }));
  2258. skillTable.Add(HRK.Researcher, researcher);
  2259. var blacksmith = new Skill(HRK.Blacksmith, HMK.BlacksmithDesc, 30, 5)
  2260. {
  2261. SkillPointsPerLevel = 7
  2262. };
  2263. blacksmith.AddRequiredStat("str", (int)Math.Floor(blacksmith.RequiredLevel * 2.5f));
  2264. blacksmith.AddModifier(HRK.Chance, new Modifier( /*HRK.Chance, */new[] { .15f }));
  2265. blacksmith.AddModifier(HRK.RessRate, new Modifier( /*HRK.RessRate, */new[] { .5f }));
  2266. skillTable.Add(HRK.Blacksmith, blacksmith);
  2267. var blinkarrow = new Skill(HRK.Blinkarrow, HMK.BlinkarrowDesc, 150, 5)
  2268. {
  2269. Usage = HMK.BlinkarrowUsage,
  2270. SkillPointsPerLevel = 10,
  2271. Enabled = false
  2272. };
  2273. blinkarrow.AddModifier(HRK.Cooldown, new Modifier( /*HRK.Cooldown, */new[] { 9f, 2f }));
  2274. blinkarrow.AddRequiredStat("agi", blinkarrow.RequiredLevel * 2);
  2275. skillTable.Add(HRK.Blinkarrow, blinkarrow);
  2276. var tamer = new Skill(HRK.Tamer, HMK.TamerDesc, 50, 6)
  2277. {
  2278. SkillPointsPerLevel = 5,
  2279. Usage = HMK.TamerUsage
  2280. };
  2281. skillTable.Add(HRK.Tamer, tamer);
  2282. return skillTable;
  2283. }
  2284.  
  2285. public static Dictionary<string, ItemInfo> GenerateItemTable(Dictionary<string, ItemInfo> itemDict = null)
  2286. {
  2287. if (itemDict == null) itemDict = new Dictionary<string, ItemInfo>();
  2288. var definitions = ItemManager.itemList;
  2289. foreach (var definition in definitions)
  2290. {
  2291. var key = definition.shortname;
  2292. itemDict.Add(key, new ItemInfo
  2293. {
  2294. DisplayName = definition.displayName.translated,
  2295. CanResearch = true,
  2296. ItemCategory = definition.category.ToString()
  2297. });
  2298. }
  2299. return itemDict;
  2300. }
  2301.  
  2302. public static Dictionary<string, int> GenerateResearchTable()
  2303. {
  2304. return new Dictionary<string, int>
  2305. {
  2306. {"Tool", 1},
  2307. {"Attire", 2},
  2308. {"Construction", 3},
  2309. {"Resources", 3},
  2310. {"Medical", 4},
  2311. {"Ammunition", 4},
  2312. {"Weapon", 5}
  2313. };
  2314. }
  2315.  
  2316. public static Dictionary<int, string> GenerateTameTable()
  2317. {
  2318. return new Dictionary<int, string>
  2319. {
  2320. {1, HPK.CanTameChicken},
  2321. {2, HPK.CanTameBoar},
  2322. {3, HPK.CanTameStag},
  2323. {4, HPK.CanTameWolf},
  2324. {5, HPK.CanTameBear},
  2325. {6, HPK.CanTameHorse}
  2326. };
  2327. }
  2328.  
  2329. public static Dictionary<BuildingGrade.Enum, float> GenerateUpgradeBuildingTable()
  2330. {
  2331. return new Dictionary<BuildingGrade.Enum, float>
  2332. {
  2333. {BuildingGrade.Enum.Twigs, 1f},
  2334. {BuildingGrade.Enum.Wood, 1f},
  2335. {BuildingGrade.Enum.Stone, 1f},
  2336. {BuildingGrade.Enum.Metal, 1f},
  2337. {BuildingGrade.Enum.TopTier, 1f}
  2338. };
  2339. }
  2340.  
  2341. public static Dictionary<string, object> GenerateDefaults()
  2342. {
  2343. return new Dictionary<string, object>
  2344. {
  2345. {HK.SkillPointsGain, HKD.SkillPointsGain},
  2346. {HK.SkillPointsPerLevel, HKD.SkillPointsPerLevel},
  2347. {HK.StatPointsGain, HKD.StatPointsGain},
  2348. {HK.StatPointsPerLevel, HKD.StatPointsPerLevel},
  2349. {HK.MaximumLevel, HKD.MaximumLevel}
  2350. };
  2351. }
  2352.  
  2353. public static Dictionary<HRK, Modifier> GenerateMaxStatsTable()
  2354. {
  2355. return new Dictionary<HRK, Modifier>
  2356. {
  2357. {HRK.str_block_percent_gain, new Modifier(new[] {1.00095f, .5f})},
  2358. {HRK.agi_evasion_percent_gain, new Modifier(new[] {1.000625f, .5f})},
  2359. {HRK.int_crafting_reducer_percent, new Modifier(new[] {1.001f, .5f})}
  2360. };
  2361. }
  2362.  
  2363. public static Dictionary<ResourceDispenser.GatherType, float> GenerateExpRateTable()
  2364. {
  2365. return new Dictionary<ResourceDispenser.GatherType, float>
  2366. {
  2367. {ResourceDispenser.GatherType.Tree, .5f},
  2368. {ResourceDispenser.GatherType.Ore, .5f},
  2369. {ResourceDispenser.GatherType.Flesh, 5f}
  2370. };
  2371. }
  2372.  
  2373. public static List<string> GenerateAllowedEntites()
  2374. {
  2375. return new List<string>
  2376. {
  2377. "furnace",
  2378. "furnace.large",
  2379. "refinery_small_deployed",
  2380. "campfire",
  2381. "bbq"
  2382. };
  2383. }
  2384. }
  2385.  
  2386.  
  2387. public struct ItemInfo
  2388. {
  2389. public string DisplayName;
  2390. public bool CanResearch;
  2391. public string ItemCategory;
  2392. }
  2393.  
  2394. public class ProfilePreferences
  2395. {
  2396. [JsonProperty("sxpmp")]
  2397. public float ShowXPMessagePercent;
  2398. [JsonProperty("sp")]
  2399. public bool ShowProfile;
  2400. [JsonProperty("scm")]
  2401. public bool ShowCraftMessage;
  2402. [JsonProperty("sh")]
  2403. public uint ShowHud;
  2404. [JsonProperty("uba")]
  2405. public bool UseBlinkArrow;
  2406. [JsonProperty("atba")]
  2407. public bool AutoToggleBlinkArrow;
  2408.  
  2409. public ProfilePreferences(uint defaultHud, bool showProfile)
  2410. {
  2411. ShowXPMessagePercent = .25f;
  2412. ShowProfile = showProfile;
  2413. ShowCraftMessage = false;
  2414. ShowHud = defaultHud;
  2415. UseBlinkArrow = true;
  2416. AutoToggleBlinkArrow = true;
  2417. }
  2418. }
  2419.  
  2420. public class GUIInfo
  2421. {
  2422. public string LastMain;
  2423. public string LastContent;
  2424. public string LastInfo;
  2425. public string LastStats;
  2426. public string LastSkills;
  2427. public string LastHud;
  2428. public string LastHudFirst;
  2429. public string LastHudSecond;
  2430. public float LastHudTime;
  2431. public Timer LastHudTimer;
  2432. }
  2433.  
  2434. public class RPGInfo
  2435. {
  2436. private float evasionCache;
  2437. private int agility;
  2438. [JsonProperty("agi")]
  2439. public int Agility
  2440. {
  2441. get { return agility; }
  2442. set
  2443. {
  2444. agility = value;
  2445. evasionCache = -1f;
  2446. }
  2447. }
  2448.  
  2449. private float blockCache;
  2450. private int strength;
  2451. [JsonProperty("str")]
  2452. public int Strength
  2453. {
  2454. get { return strength; }
  2455. set
  2456. {
  2457. strength = value;
  2458. blockCache = -1f;
  2459. }
  2460. }
  2461.  
  2462. private float craftCache;
  2463. private int intelligence;
  2464. [JsonProperty("int")]
  2465. public int Intelligence
  2466. {
  2467. get { return intelligence; }
  2468. set
  2469. {
  2470. intelligence = value;
  2471. craftCache = -1f;
  2472. }
  2473. }
  2474.  
  2475.  
  2476. [JsonProperty("sn")]
  2477. public string SteamName;
  2478. [JsonProperty("l")]
  2479. public int Level;
  2480. [JsonProperty("xp")]
  2481. public long Experience;
  2482. [JsonProperty("statp")]
  2483. public int StatsPoints;
  2484. [JsonProperty("skillp")]
  2485. public int SkillPoints;
  2486. [JsonProperty("s")]
  2487. public Dictionary<HRK, int> Skills;
  2488. [JsonProperty("p")]
  2489. public ProfilePreferences Preferences;
  2490. [JsonProperty("ls")]
  2491. public long LastSeen;
  2492. private ulong userId;
  2493. public static long[] XPTable = new long[0];
  2494. public static Dictionary<HRK, Modifier> MaxStatsTable = new Dictionary<HRK, Modifier>();
  2495. public static Dictionary<int, string> TameTable = new Dictionary<int, string>();
  2496. public static float SkillPointsGain = HKD.SkillPointsGain;
  2497. public static float StatPointsGain = HKD.StatPointsGain;
  2498. public static int SkillPointsPerLevel = HKD.SkillPointsPerLevel;
  2499. public static int StatPointsPerLevel = HKD.StatPointsPerLevel;
  2500. public static int MaxLevel = HKD.MaximumLevel;
  2501. public static Permission Perm;
  2502. private static int[] skillCostCache;
  2503. private static int[] statCostCache;
  2504.  
  2505. public RPGInfo(string steamName, uint defaultHud, bool showProfile)
  2506. {
  2507. SteamName = steamName;
  2508. Level = 0;
  2509. Skills = new Dictionary<HRK, int>();
  2510. Preferences = new ProfilePreferences(defaultHud, showProfile);
  2511. }
  2512.  
  2513. public void SetUserId(ulong userId)
  2514. {
  2515. this.userId = userId;
  2516. }
  2517.  
  2518. public bool AddExperience(long xp)
  2519. {
  2520. if (Level >= XPTable.Length) return false;
  2521. Experience += xp;
  2522. var requiredXp = XPTable[Level];
  2523. if (Experience < requiredXp) return false;
  2524. Experience -= requiredXp;
  2525. LevelUp();
  2526. return true;
  2527. }
  2528.  
  2529. public void LevelUp(int desiredLevel)
  2530. {
  2531. var levelsToUp = desiredLevel - Level;
  2532. for (var i = 0; i < levelsToUp; i++)
  2533. AddExperience(RequiredExperience());
  2534. }
  2535.  
  2536. public long RequiredExperience()
  2537. {
  2538. return Level >= XPTable.Length ? 0 : XPTable[Level];
  2539. }
  2540.  
  2541. public void Died(float percent)
  2542. {
  2543. Experience -= (long)(Experience * percent);
  2544. if (Experience < 0)
  2545. Experience = 0;
  2546. }
  2547.  
  2548. private void LevelUp()
  2549. {
  2550. Level++;
  2551. Agility++;
  2552. Strength++;
  2553. Intelligence++;
  2554. StatsPoints += StatPointsPerLevel;
  2555. SkillPoints += SkillPointsPerLevel;
  2556. if (Level >= XPTable.Length) Experience = 0;
  2557. }
  2558.  
  2559. public bool AddStat(HRK stat, int points)
  2560. {
  2561. if (stat != HRK.Agi && stat != HRK.Int && stat != HRK.Str) return false;
  2562. points = Math.Abs(points);
  2563. if (StatsPoints < points) return false;
  2564. var pointsCost = GetStatPointsCost(stat, points);
  2565. if (StatsPoints < pointsCost) return false;
  2566. switch (stat)
  2567. {
  2568. case HRK.Agi:
  2569. Agility += points;
  2570. break;
  2571. case HRK.Int:
  2572. Intelligence += points;
  2573. break;
  2574. case HRK.Str:
  2575. Strength += points;
  2576. break;
  2577. default:
  2578. return false;
  2579. }
  2580. StatsPoints -= pointsCost;
  2581. return true;
  2582. }
  2583.  
  2584. public void Reset()
  2585. {
  2586. Level = 0;
  2587. ResetStats();
  2588. }
  2589.  
  2590. public void ResetStats()
  2591. {
  2592. ResetSkills();
  2593. StatsPoints = Level * StatPointsPerLevel;
  2594. Agility = Intelligence = Strength = Level;
  2595. }
  2596.  
  2597. public void ResetSkills()
  2598. {
  2599. int skillLevel;
  2600. if (Skills.TryGetValue(HRK.Tamer, out skillLevel))
  2601. {
  2602. Perm.RevokeUserPermission(userId.ToString(), HPK.CanTame);
  2603. for (var j = 1; j <= skillLevel; j++)
  2604. Perm.RevokeUserPermission(userId.ToString(), TameTable[j]);
  2605. }
  2606. Skills.Clear();
  2607. SkillPoints = Level * SkillPointsPerLevel;
  2608. }
  2609.  
  2610. public int AddSkill(Skill skill, int level, out HMK reason, Plugin pets = null)
  2611. {
  2612. int existingLevel;
  2613. Skills.TryGetValue(skill.Type, out existingLevel);
  2614. if (existingLevel >= skill.MaxLevel)
  2615. {
  2616. reason = HMK.AlreadyAtMaxLevel;
  2617. return 0;
  2618. }
  2619. var levelsToAdd = Math.Abs(level);
  2620. if (levelsToAdd + existingLevel > skill.MaxLevel) levelsToAdd = skill.MaxLevel - existingLevel;
  2621. if (levelsToAdd <= 0)
  2622. {
  2623. reason = HMK.Empty;
  2624. return 0;
  2625. }
  2626. var requiredPoints = GetSkillPointsCost(skill, existingLevel, levelsToAdd);
  2627. if (SkillPoints < requiredPoints)
  2628. {
  2629. reason = HMK.NotEnoughPoints;
  2630. return 0;
  2631. }
  2632. if (Level < skill.RequiredLevel)
  2633. {
  2634. reason = HMK.NotEnoughLevels;
  2635. return 0;
  2636. }
  2637. if (skill.RequiredSkills.Count > existingLevel)
  2638. foreach (var requiredSkill in skill.RequiredSkills[existingLevel])
  2639. {
  2640. int tempLevel;
  2641. if (!Skills.TryGetValue(requiredSkill.Key, out tempLevel) || tempLevel < requiredSkill.Value)
  2642. {
  2643. reason = HMK.NotEnoughSkill;
  2644. return 0;
  2645. }
  2646. }
  2647. if (skill.RequiredStats.Count > existingLevel)
  2648. foreach (var requiredStat in skill.RequiredStats[existingLevel])
  2649. {
  2650. switch (requiredStat.Key.ToLower())
  2651. {
  2652. case "str":
  2653. if (Strength < requiredStat.Value)
  2654. {
  2655. reason = HMK.NotEnoughStrength;
  2656. return 0;
  2657. }
  2658. break;
  2659. case "agi":
  2660. if (Agility < requiredStat.Value)
  2661. {
  2662. reason = HMK.NotEnoughAgility;
  2663. return 0;
  2664. }
  2665. break;
  2666. case "int":
  2667. if (Intelligence < requiredStat.Value)
  2668. {
  2669. reason = HMK.NotEnoughIntelligence;
  2670. return 0;
  2671. }
  2672. break;
  2673. default:
  2674. reason = HMK.InvalidCommand;
  2675. return 0;
  2676. }
  2677. }
  2678. if (existingLevel > 0)
  2679. {
  2680. if (levelsToAdd > 0)
  2681. Skills[skill.Type] += levelsToAdd;
  2682. }
  2683. else
  2684. {
  2685. Skills.Add(skill.Type, levelsToAdd);
  2686. }
  2687. if (skill.Type == HRK.Tamer && pets != null)
  2688. {
  2689. var skillLevel = Skills[HRK.Tamer];
  2690. Perm.GrantUserPermission(userId.ToString(), HPK.CanTame, pets);
  2691. for (var j = 1; j <= skillLevel; j++)
  2692. Perm.GrantUserPermission(userId.ToString(), TameTable[j], pets);
  2693. }
  2694. reason = HMK.Empty;
  2695. SkillPoints -= requiredPoints;
  2696. return levelsToAdd;
  2697. }
  2698.  
  2699. public float GetEvasion()
  2700. {
  2701. if (evasionCache >= 0) return evasionCache;
  2702. var args = MaxStatsTable[HRK.agi_evasion_percent_gain].Args;
  2703. evasionCache = Mathf.Clamp((float)(Math.Pow(args[0], Agility) - 1), 0, args[1]);
  2704. return evasionCache;
  2705. }
  2706.  
  2707. public float GetBlock()
  2708. {
  2709. if (blockCache >= 0) return blockCache;
  2710. var args = MaxStatsTable[HRK.str_block_percent_gain].Args;
  2711. blockCache = Mathf.Clamp((float)(Math.Pow(args[0], Strength) - 1), 0, args[1]);
  2712. return blockCache;
  2713. }
  2714.  
  2715. public float GetCraftingReducer()
  2716. {
  2717. if (craftCache >= 0) return craftCache;
  2718. var args = MaxStatsTable[HRK.int_crafting_reducer_percent].Args;
  2719. craftCache = Mathf.Clamp((float)(Math.Pow(args[0], Intelligence) - 1), 0, args[1]);
  2720. return craftCache;
  2721. }
  2722.  
  2723. public int GetSkillPointsCostNext(Skill skill, int levelsToAdd = 1)
  2724. {
  2725. int existingLevel;
  2726. Skills.TryGetValue(skill.Type, out existingLevel);
  2727. levelsToAdd = Math.Abs(levelsToAdd);
  2728. if (levelsToAdd + existingLevel > skill.MaxLevel) levelsToAdd = skill.MaxLevel - existingLevel;
  2729. if (levelsToAdd < 0) levelsToAdd = 1;
  2730. return GetSkillPointsCost(skill, existingLevel, levelsToAdd);
  2731. }
  2732.  
  2733. private static int GetSkillPointsCost(Skill skill, int level, int add = 1)
  2734. {
  2735. if (SkillPointsGain <= 1) return skill.SkillPointsPerLevel * add;
  2736. if (skillCostCache == null || skillCostCache.Length < XPTable.Length)
  2737. {
  2738. skillCostCache = new int[XPTable.Length];
  2739. for (var i = 0; i < XPTable.Length; i++)
  2740. skillCostCache[i] = Math.Max((int)Math.Ceiling(Math.Pow(SkillPointsGain, i) - 1), 1);
  2741. }
  2742. var target = level + add;
  2743. if (target > skillCostCache.Length)
  2744. {
  2745. var size = skillCostCache.Length - 1;
  2746. Array.Resize(ref skillCostCache, target);
  2747. for (var i = size; i < target; i++)
  2748. skillCostCache[i] = Math.Max((int)Math.Ceiling(Math.Pow(SkillPointsGain, i) - 1), 1);
  2749. }
  2750. var points = 0;
  2751. for (var i = level; i < target; i++)
  2752. points += skill.SkillPointsPerLevel + skillCostCache[i];
  2753. return points;
  2754. }
  2755.  
  2756. public int GetStatPointsCost(HRK stat, int add = 1)
  2757. {
  2758. if (StatPointsGain <= 1) return add;
  2759. var level = 0;
  2760. switch (stat)
  2761. {
  2762. case HRK.Agi:
  2763. level = Agility;
  2764. break;
  2765. case HRK.Int:
  2766. level = Intelligence;
  2767. break;
  2768. case HRK.Str:
  2769. level = Strength;
  2770. break;
  2771. }
  2772. level -= Level;
  2773. if (level < 0) return 1;
  2774. if (statCostCache == null || statCostCache.Length < XPTable.Length)
  2775. {
  2776. statCostCache = new int[XPTable.Length];
  2777. for (var i = 0; i < XPTable.Length; i++)
  2778. statCostCache[i] = Math.Max((int)Math.Ceiling(Math.Pow(StatPointsGain, i) - 1), 1);
  2779. }
  2780. var target = level + add;
  2781. if (target > statCostCache.Length)
  2782. {
  2783. var size = statCostCache.Length - 1;
  2784. Array.Resize(ref statCostCache, target);
  2785. for (var i = size; i < target; i++)
  2786. statCostCache[i] = Math.Max((int)Math.Ceiling(Math.Pow(StatPointsGain, i) - 1), 1);
  2787. }
  2788. var points = 0;
  2789. for (var i = level; i < target; i++)
  2790. points += statCostCache[i];
  2791. return points;
  2792. }
  2793.  
  2794. public static void OnUnload()
  2795. {
  2796. MaxStatsTable = null;
  2797. TameTable = null;
  2798. XPTable = null;
  2799. skillCostCache = null;
  2800. statCostCache = null;
  2801. Perm = null;
  2802. }
  2803. }
  2804.  
  2805. public class Skill
  2806. {
  2807. public string Name;
  2808. public HRK Type;
  2809. public bool Enabled;
  2810. public HMK Description;
  2811. public HMK Usage;
  2812. public int RequiredLevel;
  2813. public int MaxLevel;
  2814. public List<Dictionary<HRK, int>> RequiredSkills;
  2815. public Dictionary<HRK, Modifier> Modifiers;
  2816. public List<Dictionary<string, int>> RequiredStats;
  2817. public int SkillPointsPerLevel;
  2818.  
  2819. public Skill(HRK type, HMK description, int requiredLevel, int maxLevel)
  2820. {
  2821. Name = type.ToString();
  2822. Type = type;
  2823. Enabled = true;
  2824. Description = description;
  2825. RequiredLevel = requiredLevel;
  2826. MaxLevel = maxLevel;
  2827. RequiredSkills = new List<Dictionary<HRK, int>>();
  2828. Modifiers = new Dictionary<HRK, Modifier>();
  2829. RequiredStats = new List<Dictionary<string, int>>();
  2830. SkillPointsPerLevel = 1;
  2831. }
  2832.  
  2833. public void AddRequiredStat(string stat, int points, int level = 1)
  2834. {
  2835. while (RequiredStats.Count < level)
  2836. RequiredStats.Add(new Dictionary<string, int>());
  2837. if (!RequiredStats[level - 1].ContainsKey(stat))
  2838. RequiredStats[level - 1].Add(stat, points);
  2839. }
  2840.  
  2841. public void AddRequiredSkill(HRK skillName, int pointsNeeded, int level = 1)
  2842. {
  2843. while (RequiredSkills.Count < level)
  2844. RequiredSkills.Add(new Dictionary<HRK, int>());
  2845. if (!RequiredSkills[level - 1].ContainsKey(skillName))
  2846. RequiredSkills[level - 1].Add(skillName, pointsNeeded);
  2847. }
  2848.  
  2849. public void AddModifier(HRK modifier, Modifier handler)
  2850. {
  2851. if (!Modifiers.ContainsKey(modifier))
  2852. Modifiers.Add(modifier, handler);
  2853. }
  2854. }
  2855.  
  2856. public struct Modifier
  2857. {
  2858. public Modifier( /*HRK identifier, */ float[] args)
  2859. {
  2860. //Identifier = identifier;
  2861. Args = args;
  2862. }
  2863.  
  2864. //public HRK Identifier;
  2865.  
  2866. public float[] Args;
  2867. }
  2868.  
  2869. public class HuntData
  2870. {
  2871. [JsonProperty(HK.Furnaces)]
  2872. public Dictionary<string, ulong> Furnaces { get; } = new Dictionary<string, ulong>();
  2873.  
  2874. [JsonProperty(HK.Quarries)]
  2875. public Dictionary<string, ulong> Quarries { get; } = new Dictionary<string, ulong>();
  2876.  
  2877. [JsonProperty(HK.Profile)]
  2878. public Dictionary<ulong, RPGInfo> Profiles { get; } = new Dictionary<ulong, RPGInfo>();
  2879. }
  2880.  
  2881. public class HuntDefaults
  2882. {
  2883. public float SkillPointsGain;
  2884. public float StatPointsGain;
  2885. public int SkillPointsPerLevel;
  2886. public int StatPointsPerLevel;
  2887. public int MaximumLevel;
  2888. public HuntDefaults()
  2889. {
  2890. SkillPointsGain = HKD.SkillPointsGain;
  2891. StatPointsGain = HKD.StatPointsGain;
  2892. SkillPointsPerLevel = HKD.SkillPointsPerLevel;
  2893. StatPointsPerLevel = HKD.StatPointsPerLevel;
  2894. MaximumLevel = HKD.MaximumLevel;
  2895. }
  2896.  
  2897. }
  2898. }
  2899.  
  2900. namespace Oxide.Plugins.HuntRPGExt.Keys
  2901. {
  2902. //config keys
  2903. static class HK
  2904. {
  2905. public const string Defaults = "Defaults";
  2906. public const string SkillPointsGain = "SkillPointsGain";
  2907. public const string StatPointsGain = "StatPointsGain";
  2908. public const string DeleteProfileAfterOfflineDays = "DeleteProfileAfterOfflineDays";
  2909. public const string ShowHud = "SHOWHUD";
  2910. public const string ShowProfile = "SHOWPROFILE";
  2911. public const string DefaultHud = "DEFAULTHUD";
  2912. public const string ConfigVersion = "VERSION";
  2913. public const string DataVersion = "DATA_VERSION";
  2914. public const string DataFileName = "RPGData";
  2915. public const string Profile = "PROFILE";
  2916. public const string Furnaces = "FURNACES";
  2917. public const string Quarries = "QUARRIES";
  2918. public const string ChatPrefix = "CHATPREFIX";
  2919. public const string XPTable = "XPTABLE";
  2920. public const string ExpRateTable = "EXPRATETABLE";
  2921. public const string MaxStatsTable = "MAXSTATSTABLE";
  2922. public const string SkillTable = "SKILLTABLE";
  2923. public const string ItemTable = "ITEMTABLE";
  2924. public const string ResearchSkillTable = "RESEARCHSKILLTABLE";
  2925. public const string TameTable = "TAMETABLE";
  2926. public const string UpgradeBuildTable = "UPGRADEBUILDTABLE";
  2927. public const string AllowedEntities = "ALLOWEDENTITIES";
  2928. public const string AdminReset = "ADMINRESET";
  2929. public const string NightXP = "NIGHTXP";
  2930. public const string EcoBoost = "ECOBOOST";
  2931. public const string Trainer = "TRAINER";
  2932. public const string DeathReducerK = "DEATHREDUCER";
  2933. public const string SkillPointsPerLevel = "SkillPointsPerLevel";
  2934. public const string StatPointsPerLevel = "StatPointsPerLevel";
  2935. public const string MaximumLevel = "MaxLevel";
  2936. }
  2937.  
  2938. //defaults
  2939. static class HKD
  2940. {
  2941. public const int MaximumLevel = 2002;
  2942. public const float SkillPointsGain = 1.0975f;
  2943. public const float StatPointsGain = 1.015f;
  2944. public const int SkillPointsPerLevel = 2;
  2945. public const int StatPointsPerLevel = 3;
  2946. public const int BaseXp = 383;
  2947. public const float LevelMultiplier = 1.088f;
  2948. public const int LevelModule = 10;
  2949. public const float ModuleReducer = .0055f;
  2950. public const float DeathReducer = .05f;
  2951. }
  2952.  
  2953. [JsonConverter(typeof(StringEnumConverter))]
  2954. public enum HMK
  2955. {
  2956. None,
  2957. About,
  2958. Agi,
  2959. AgiColor,
  2960. AlreadyAtMaxLevel,
  2961. AvailableSkills,
  2962. BlinkStatus,
  2963. BlinkToggle,
  2964. BlinkedRecently,
  2965. BuildingOwnersPlugin,
  2966. ButtonClose,
  2967. ButtonResetSkills,
  2968. ButtonResetStats,
  2969. CantBlink,
  2970. CantBlinkOther,
  2971. CraftMessage,
  2972. CraftingEnd,
  2973. CraftingReducer,
  2974. CurrentXp,
  2975. DamageBlock,
  2976. DataUpdated,
  2977. Died,
  2978. Dodged,
  2979. TargetDodged,
  2980. Empty,
  2981. EvasionChance,
  2982. GenerateXp,
  2983. Help,
  2984. IdAlreadyExists,
  2985. Int,
  2986. IntColor,
  2987. InvalidCommand,
  2988. InvalidSkillName,
  2989. NotFoundItem,
  2990. Level,
  2991. LevelUp,
  2992. NeedNpc,
  2993. NightXp,
  2994. NotAnAdmin,
  2995. NotEnoughAgility,
  2996. NotEnoughIntelligence,
  2997. NotEnoughLevels,
  2998. NotEnoughPoints,
  2999. NotEnoughStrength,
  3000. Off,
  3001. On,
  3002. PetsPlugin,
  3003. PlayerLevelUp,
  3004. NotFoundPlayer,
  3005. ProfilePreferences,
  3006. ProfileMessage,
  3007. ResearchBlocked,
  3008. ResearchFail,
  3009. ResearchItem,
  3010. ResearchReuse,
  3011. ResearchSkill,
  3012. ResearchSuccess,
  3013. ResearchType,
  3014. Shortcuts,
  3015. SkillDisabled,
  3016. SkillInfo,
  3017. NotLearnedSkill,
  3018. SkillPoints,
  3019. SkillReset,
  3020. SkillResetPlayer,
  3021. StatPoints,
  3022. StatReset,
  3023. StatResetPlayer,
  3024. Str,
  3025. StrColor,
  3026. XpMessage,
  3027. NotEnoughSkill,
  3028. SkillsHeader,
  3029. Loaded,
  3030. StatusLoad,
  3031. StatusSave,
  3032. TopPlayer,
  3033. ProfileHeader,
  3034. SkillUp,
  3035. SkillInfoHeader,
  3036. Usage,
  3037. LevelShort,
  3038. SkillCost,
  3039. LumberjackDesc,
  3040. MinerDesc,
  3041. HunterDesc,
  3042. GathererDesc,
  3043. BlacksmithDesc,
  3044. ResearcherDesc,
  3045. TamerDesc,
  3046. BlinkarrowDesc,
  3047. ResearcherUsage,
  3048. TamerUsage,
  3049. BlinkarrowUsage,
  3050. AgiDesc,
  3051. StrDesc,
  3052. IntDesc
  3053. }
  3054.  
  3055. //permission keys
  3056. public static class HPK
  3057. {
  3058. public const string CanTame = "cannpc";
  3059. public const string CanTameChicken = "canchicken";
  3060. public const string CanTameBoar = "canboar";
  3061. public const string CanTameStag = "canstag";
  3062. public const string CanTameWolf = "canwolf";
  3063. public const string CanTameBear = "canbear";
  3064. public const string CanTameHorse = "canhorse";
  3065. }
  3066.  
  3067. [JsonConverter(typeof(StringEnumConverter))]
  3068. public enum HRK
  3069. {
  3070. Tamer,
  3071. Blinkarrow,
  3072. Blacksmith,
  3073. Researcher,
  3074. Lumberjack,
  3075. Miner,
  3076. Hunter,
  3077. Gatherer,
  3078. Gather,
  3079. Cooldown,
  3080. int_crafting_reducer_percent,
  3081. agi_evasion_percent_gain,
  3082. str_block_percent_gain,
  3083. Agi,
  3084. Int,
  3085. Str,
  3086. Chance,
  3087. RessRate
  3088. }
  3089. }
  3090.  
Advertisement
Add Comment
Please, Sign In to add comment