Fix all warnings & Trim (#2226)

* Fix AutoFishing crash
* Fix all warnings
* Remove DotNetZip.
* Fix the usage of HttpClient.
This commit is contained in:
BruceChen 2022-10-02 18:31:08 +08:00 committed by GitHub
parent 4aa6c1c99f
commit 1d52d1eadd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
227 changed files with 2201 additions and 43564 deletions

View file

@ -1,7 +1,5 @@
using System; using System;
using System.Diagnostics;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
namespace MinecraftClient namespace MinecraftClient
{ {
@ -30,14 +28,15 @@ namespace MinecraftClient
/// <param name="action">Action to run</param> /// <param name="action">Action to run</param>
/// <param name="timeout">Maximum timeout</param> /// <param name="timeout">Maximum timeout</param>
/// <returns>True if the action finished whithout timing out</returns> /// <returns>True if the action finished whithout timing out</returns>
public static bool Perform(Action action, TimeSpan timeout) { public static bool Perform(Action action, TimeSpan timeout)
Thread thread = new Thread(new ThreadStart(action)); {
Thread thread = new(new ThreadStart(action));
thread.Start(); thread.Start();
bool success = thread.Join(timeout); bool success = thread.Join(timeout);
if (!success) if (!success)
thread.Interrupt(); thread.Interrupt();
thread = null;
return success; return success;
} }
} }

View file

@ -1,9 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using System.IO;
using static System.Net.WebRequestMethods;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
{ {
@ -12,8 +8,8 @@ namespace MinecraftClient.ChatBots
/// </summary> /// </summary>
public class Alerts : ChatBot public class Alerts : ChatBot
{ {
private string[] dictionary = new string[0]; private string[] dictionary = Array.Empty<string>();
private string[] excludelist = new string[0]; private string[] excludelist = Array.Empty<string>();
private bool logToFile = false; private bool logToFile = false;
/// <summary> /// <summary>

View file

@ -10,14 +10,14 @@ namespace MinecraftClient.ChatBots
public class AntiAFK : ChatBot public class AntiAFK : ChatBot
{ {
private int count; private int count;
private string pingparam; private readonly string pingparam;
private int timeping = 600; private int timeping = 600;
private int timepingMax = -1; private int timepingMax = -1;
private bool useTerrainHandling = false; private bool useTerrainHandling = false;
private bool previousSneakState = false; private bool previousSneakState = false;
private int walkRange = 5; private int walkRange = 5;
private int walkRetries = 10; private readonly int walkRetries = 10;
private Random random = new Random(); private readonly Random random = new();
/// <summary> /// <summary>
/// This bot sends a /ping command every X seconds in order to stay non-afk. /// This bot sends a /ping command every X seconds in order to stay non-afk.
@ -57,7 +57,7 @@ namespace MinecraftClient.ChatBots
else else
{ {
// Handle the random range // Handle the random range
if (pingparam.Contains("-")) if (pingparam.Contains('-'))
{ {
string[] parts = pingparam.Split("-"); string[] parts = pingparam.Split("-");
@ -85,10 +85,7 @@ namespace MinecraftClient.ChatBots
if (timepingMax != -1 && timeping > timepingMax) if (timepingMax != -1 && timeping > timepingMax)
{ {
int temporary = timepingMax; (timeping, timepingMax) = (timepingMax, timeping);
timepingMax = timeping;
timeping = temporary;
LogToConsole(Translations.TryGet("bot.antiafk.swapping")); LogToConsole(Translations.TryGet("bot.antiafk.swapping"));
} }

View file

@ -1,7 +1,7 @@
using MinecraftClient.Mapping; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using MinecraftClient.Mapping;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
{ {
@ -10,22 +10,22 @@ namespace MinecraftClient.ChatBots
/// </summary> /// </summary>
class AutoAttack : ChatBot class AutoAttack : ChatBot
{ {
private Dictionary<int, Entity> entitiesToAttack = new Dictionary<int, Entity>(); // mobs within attack range private readonly Dictionary<int, Entity> entitiesToAttack = new(); // mobs within attack range
private int attackCooldown = 6; private int attackCooldown = 6;
private int attackCooldownCounter = 6; private int attackCooldownCounter = 6;
private Double attackSpeed = 4; private Double attackSpeed = 4;
private Double attackCooldownSeconds; private Double attackCooldownSeconds;
private bool overrideAttackSpeed = false; private readonly bool overrideAttackSpeed = false;
private int attackRange = 4; private readonly int attackRange = 4;
private Double serverTPS; private Double serverTPS;
private float health = 100; private float health = 100;
private bool singleMode = true; private readonly bool singleMode = true;
private bool priorityDistance = true; private readonly bool priorityDistance = true;
private InteractType interactMode; private readonly InteractType interactMode;
private bool attackHostile = true; private readonly bool attackHostile = true;
private bool attackPassive = false; private readonly bool attackPassive = false;
private string listMode = "blacklist"; private readonly string listMode = "blacklist";
private List<EntityType> listedEntites = new(); private readonly List<EntityType> listedEntites = new();
public AutoAttack( public AutoAttack(
string mode, string priority, bool overrideAttackSpeed = false, double cooldownSeconds = 1, InteractType interaction = InteractType.Attack) string mode, string priority, bool overrideAttackSpeed = false, double cooldownSeconds = 1, InteractType interaction = InteractType.Attack)
@ -53,13 +53,13 @@ namespace MinecraftClient.ChatBots
else else
{ {
this.overrideAttackSpeed = overrideAttackSpeed; this.overrideAttackSpeed = overrideAttackSpeed;
this.attackCooldownSeconds = cooldownSeconds; attackCooldownSeconds = cooldownSeconds;
attackCooldown = Convert.ToInt32(Math.Truncate(attackCooldownSeconds / 0.1) + 1); attackCooldown = Convert.ToInt32(Math.Truncate(attackCooldownSeconds / 0.1) + 1);
} }
} }
this.attackHostile = Settings.AutoAttack_Attack_Hostile; attackHostile = Settings.AutoAttack_Attack_Hostile;
this.attackPassive = Settings.AutoAttack_Attack_Passive; attackPassive = Settings.AutoAttack_Attack_Passive;
if (Settings.AutoAttack_ListMode.Length > 0) if (Settings.AutoAttack_ListMode.Length > 0)
{ {
@ -140,7 +140,7 @@ namespace MinecraftClient.ChatBots
if (entitiesToAttack.ContainsKey(priorityEntity)) if (entitiesToAttack.ContainsKey(priorityEntity))
{ {
// check entity distance and health again // check entity distance and health again
if (shouldAttackEntity(entitiesToAttack[priorityEntity])) if (ShouldAttackEntity(entitiesToAttack[priorityEntity]))
{ {
InteractEntity(priorityEntity, interactMode); // hit the entity! InteractEntity(priorityEntity, interactMode); // hit the entity!
SendAnimation(Inventory.Hand.MainHand); // Arm animation SendAnimation(Inventory.Hand.MainHand); // Arm animation
@ -152,7 +152,7 @@ namespace MinecraftClient.ChatBots
foreach (KeyValuePair<int, Entity> entity in entitiesToAttack) foreach (KeyValuePair<int, Entity> entity in entitiesToAttack)
{ {
// check that we are in range once again. // check that we are in range once again.
if (shouldAttackEntity(entity.Value)) if (ShouldAttackEntity(entity.Value))
{ {
InteractEntity(entity.Key, interactMode); // hit the entity! InteractEntity(entity.Key, interactMode); // hit the entity!
} }
@ -169,7 +169,7 @@ namespace MinecraftClient.ChatBots
public override void OnEntitySpawn(Entity entity) public override void OnEntitySpawn(Entity entity)
{ {
shouldAttackEntity(entity); ShouldAttackEntity(entity);
} }
public override void OnEntityDespawn(Entity entity) public override void OnEntityDespawn(Entity entity)
@ -209,7 +209,7 @@ namespace MinecraftClient.ChatBots
if (listedEntites.Count > 0) if (listedEntites.Count > 0)
{ {
bool inList = listedEntites.Contains(entity.Type); bool inList = listedEntites.Contains(entity.Type);
result = listMode.Equals("blacklist") ? (inList ? false : result) : (inList ? true : false); result = listMode.Equals("blacklist") ? (!inList && result) : (inList);
} }
return result; return result;
@ -217,7 +217,7 @@ namespace MinecraftClient.ChatBots
public override void OnEntityMove(Entity entity) public override void OnEntityMove(Entity entity)
{ {
shouldAttackEntity(entity); ShouldAttackEntity(entity);
} }
public override void OnHealthUpdate(float health, int food) public override void OnHealthUpdate(float health, int food)
@ -262,7 +262,7 @@ namespace MinecraftClient.ChatBots
/// </summary> /// </summary>
/// <param name="entity">The entity to handle</param> /// <param name="entity">The entity to handle</param>
/// <returns>If the entity should be attacked</returns> /// <returns>If the entity should be attacked</returns>
public bool shouldAttackEntity(Entity entity) public bool ShouldAttackEntity(Entity entity)
{ {
if (!IsAllowedToAttack(entity) || entity.Health <= 0) if (!IsAllowedToAttack(entity) || entity.Health <= 0)
return false; return false;

View file

@ -1,8 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; using System.IO;
using System.Linq;
using MinecraftClient.Inventory; using MinecraftClient.Inventory;
using MinecraftClient.Mapping; using MinecraftClient.Mapping;
@ -16,23 +15,23 @@ namespace MinecraftClient.ChatBots
private bool craftingFailed = false; private bool craftingFailed = false;
private int inventoryInUse = -2; private int inventoryInUse = -2;
private int index = 0; private int index = 0;
private Recipe recipeInUse; private Recipe? recipeInUse;
private List<ActionStep> actionSteps = new List<ActionStep>(); private readonly List<ActionStep> actionSteps = new();
private Location tableLocation = new Location(); private Location tableLocation = new();
private bool abortOnFailure = true; private bool abortOnFailure = true;
private int updateDebounceValue = 2; private int updateDebounceValue = 2;
private int updateDebounce = 0; private int updateDebounce = 0;
private int updateTimeoutValue = 10; private readonly int updateTimeoutValue = 10;
private int updateTimeout = 0; private int updateTimeout = 0;
private string timeoutAction = "unspecified"; private string timeoutAction = "unspecified";
private string configPath = @"autocraft\config.ini"; private readonly string configPath = @"autocraft\config.ini";
private string lastRecipe = ""; // Used in parsing recipe config private string lastRecipe = ""; // Used in parsing recipe config
private Dictionary<string, Recipe> recipes = new Dictionary<string, Recipe>(); private readonly Dictionary<string, Recipe> recipes = new();
private void resetVar() private void ResetVar()
{ {
craftingFailed = false; craftingFailed = false;
waitingForTable = false; waitingForTable = false;
@ -123,9 +122,10 @@ namespace MinecraftClient.ChatBots
/// Materials needed and their position /// Materials needed and their position
/// </summary> /// </summary>
/// <remarks>position start with 1, from left to right, top to bottom</remarks> /// <remarks>position start with 1, from left to right, top to bottom</remarks>
public Dictionary<int, ItemType> Materials; public Dictionary<int, ItemType>? Materials;
public Recipe() { } public Recipe() { }
public Recipe(Dictionary<int, ItemType> materials, ItemType resultItem, ContainerType type) public Recipe(Dictionary<int, ItemType> materials, ItemType resultItem, ContainerType type)
{ {
Materials = materials; Materials = materials;
@ -141,7 +141,7 @@ namespace MinecraftClient.ChatBots
/// <remarks>so that it can be used in crafting table</remarks> /// <remarks>so that it can be used in crafting table</remarks>
public static Recipe ConvertToCraftingTable(Recipe recipe) public static Recipe ConvertToCraftingTable(Recipe recipe)
{ {
if (recipe.CraftingAreaType == ContainerType.PlayerInventory) if (recipe.CraftingAreaType == ContainerType.PlayerInventory && recipe.Materials != null)
{ {
if (recipe.Materials.ContainsKey(4)) if (recipe.Materials.ContainsKey(4))
{ {
@ -202,7 +202,7 @@ namespace MinecraftClient.ChatBots
string name = args[1]; string name = args[1];
if (recipes.ContainsKey(name)) if (recipes.ContainsKey(name))
{ {
resetVar(); ResetVar();
PrepareCrafting(recipes[name]); PrepareCrafting(recipes[name]);
return ""; return "";
} }
@ -221,32 +221,26 @@ namespace MinecraftClient.ChatBots
else return GetHelp(); else return GetHelp();
} }
private string GetHelp() private static string GetHelp()
{ {
return Translations.Get("bot.autoCraft.available_cmd", "load, list, reload, resetcfg, start, stop, help"); return Translations.Get("bot.autoCraft.available_cmd", "load, list, reload, resetcfg, start, stop, help");
} }
private string GetCommandHelp(string cmd) private string GetCommandHelp(string cmd)
{ {
switch (cmd.ToLower()) return cmd.ToLower() switch
{ {
case "load": #pragma warning disable format // @formatter:off
return Translations.Get("bot.autocraft.help.load"); "load" => Translations.Get("bot.autocraft.help.load"),
case "list": "list" => Translations.Get("bot.autocraft.help.list"),
return Translations.Get("bot.autocraft.help.list"); "reload" => Translations.Get("bot.autocraft.help.reload"),
case "reload": "resetcfg" => Translations.Get("bot.autocraft.help.resetcfg"),
return Translations.Get("bot.autocraft.help.reload"); "start" => Translations.Get("bot.autocraft.help.start"),
case "resetcfg": "stop" => Translations.Get("bot.autocraft.help.stop"),
return Translations.Get("bot.autocraft.help.resetcfg"); "help" => Translations.Get("bot.autocraft.help.help"),
case "start": _ => GetHelp(),
return Translations.Get("bot.autocraft.help.start"); #pragma warning restore format // @formatter:on
case "stop": };
return Translations.Get("bot.autocraft.help.stop");
case "help":
return Translations.Get("bot.autocraft.help.help");
default:
return GetHelp();
}
} }
#region Config handling #region Config handling
@ -312,7 +306,7 @@ namespace MinecraftClient.ChatBots
// local variable for use in parsing config // local variable for use in parsing config
string section = ""; string section = "";
Dictionary<string, Recipe> recipes = new Dictionary<string, Recipe>(); Dictionary<string, Recipe> recipes = new();
foreach (string l in content) foreach (string l in content)
{ {
@ -323,20 +317,20 @@ namespace MinecraftClient.ChatBots
if (line.Length <= 0) if (line.Length <= 0)
continue; continue;
if (line[0] == '[' && line[line.Length - 1] == ']') if (line[0] == '[' && line[^1] == ']')
{ {
section = line.Substring(1, line.Length - 2).ToLower(); section = line[1..^1].ToLower();
continue; continue;
} }
string key = line.Split('=')[0].ToLower(); string key = line.Split('=')[0].ToLower();
if (!(line.Length > (key.Length + 1))) if (!(line.Length > (key.Length + 1)))
continue; continue;
string value = line.Substring(key.Length + 1); string value = line[(key.Length + 1)..];
switch (section) switch (section)
{ {
case "recipe": parseRecipe(key, value); break; case "recipe": ParseRecipe(key, value); break;
case "autocraft": parseMain(key, value); break; case "autocraft": ParseMain(key, value); break;
} }
} }
@ -358,12 +352,12 @@ namespace MinecraftClient.ChatBots
} }
} }
} }
#region Method for parsing different section of config #region Method for parsing different section of config
private void parseMain(string key, string value) private void ParseMain(string key, string value)
{ {
switch (key) switch (key)
{ {
@ -378,7 +372,7 @@ namespace MinecraftClient.ChatBots
else throw new Exception(Translations.Get("bot.autoCraft.exception.invalid_table", key)); else throw new Exception(Translations.Get("bot.autoCraft.exception.invalid_table", key));
break; break;
case "onfailure": case "onfailure":
abortOnFailure = value.ToLower() == "abort" ? true : false; abortOnFailure = value.ToLower() == "abort";
break; break;
case "updatedebounce": case "updatedebounce":
updateDebounceValue = Convert.ToInt32(value); updateDebounceValue = Convert.ToInt32(value);
@ -386,21 +380,21 @@ namespace MinecraftClient.ChatBots
} }
} }
private void parseRecipe(string key, string value) private void ParseRecipe(string key, string value)
{ {
if (key.StartsWith("slot")) if (key.StartsWith("slot"))
{ {
int slot = Convert.ToInt32(key[key.Length - 1].ToString()); int slot = Convert.ToInt32(key[^1].ToString());
if (slot > 0 && slot < 10) if (slot > 0 && slot < 10)
{ {
if (recipes.ContainsKey(lastRecipe)) if (recipes.ContainsKey(lastRecipe))
{ {
ItemType itemType; if (Enum.TryParse(value, true, out ItemType itemType))
if (Enum.TryParse(value, true, out itemType))
{ {
if (recipes[lastRecipe].Materials != null && recipes[lastRecipe].Materials.Count > 0) Dictionary<int, ItemType>? materials = recipes[lastRecipe].Materials;
if (materials != null && materials.Count > 0)
{ {
recipes[lastRecipe].Materials.Add(slot, itemType); materials.Add(slot, itemType);
} }
else else
{ {
@ -450,8 +444,7 @@ namespace MinecraftClient.ChatBots
case "result": case "result":
if (recipes.ContainsKey(lastRecipe)) if (recipes.ContainsKey(lastRecipe))
{ {
ItemType itemType; if (Enum.TryParse(value, true, out ItemType itemType))
if (Enum.TryParse(value, true, out itemType))
{ {
recipes[lastRecipe].ResultItem = itemType; recipes[lastRecipe].ResultItem = itemType;
} }
@ -487,7 +480,7 @@ namespace MinecraftClient.ChatBots
// After table opened, we need to wait for server to update table inventory items // After table opened, we need to wait for server to update table inventory items
waitingForUpdate = true; waitingForUpdate = true;
inventoryInUse = inventoryId; inventoryInUse = inventoryId;
PrepareCrafting(recipeInUse); PrepareCrafting(recipeInUse!);
} }
} }
} }
@ -562,11 +555,14 @@ namespace MinecraftClient.ChatBots
} }
} }
foreach (KeyValuePair<int, ItemType> slot in recipe.Materials) if (recipe.Materials != null)
{ {
// Steps for moving items from inventory to crafting area foreach (KeyValuePair<int, ItemType> slot in recipe.Materials)
actionSteps.Add(new ActionStep(ActionType.LeftClick, inventoryInUse, slot.Value)); {
actionSteps.Add(new ActionStep(ActionType.LeftClick, inventoryInUse, slot.Key)); // Steps for moving items from inventory to crafting area
actionSteps.Add(new ActionStep(ActionType.LeftClick, inventoryInUse, slot.Value));
actionSteps.Add(new ActionStep(ActionType.LeftClick, inventoryInUse, slot.Key));
}
} }
if (actionSteps.Count > 0) if (actionSteps.Count > 0)
{ {
@ -626,15 +622,15 @@ namespace MinecraftClient.ChatBots
else else
{ {
int[] slots = GetInventories()[step.InventoryID].SearchItem(step.ItemType); int[] slots = GetInventories()[step.InventoryID].SearchItem(step.ItemType);
if (slots.Count() > 0) if (slots.Length > 0)
{ {
int ignoredSlot; int ignoredSlot;
if (recipeInUse.CraftingAreaType == ContainerType.PlayerInventory) if (recipeInUse!.CraftingAreaType == ContainerType.PlayerInventory)
ignoredSlot = 9; ignoredSlot = 9;
else else
ignoredSlot = 10; ignoredSlot = 10;
slots = slots.Where(slot => slot >= ignoredSlot).ToArray(); slots = slots.Where(slot => slot >= ignoredSlot).ToArray();
if (slots.Count() > 0) if (slots.Length > 0)
WindowAction(step.InventoryID, slots[0], WindowActionType.LeftClick); WindowAction(step.InventoryID, slots[0], WindowActionType.LeftClick);
else else
craftingFailed = true; craftingFailed = true;
@ -688,7 +684,6 @@ namespace MinecraftClient.ChatBots
} }
HandleError(); HandleError();
} }
} }
/// <summary> /// <summary>

View file

@ -1,8 +1,7 @@
using MinecraftClient.Inventory; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using MinecraftClient.Inventory;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
{ {
@ -18,10 +17,10 @@ namespace MinecraftClient.ChatBots
private bool enable = true; private bool enable = true;
private int updateDebounce = 0; private int updateDebounce = 0;
private int updateDebounceValue = 2; private readonly int updateDebounceValue = 2;
private int inventoryUpdated = -1; private int inventoryUpdated = -1;
private List<ItemType> itemList = new List<ItemType>(); private readonly List<ItemType> itemList = new();
public AutoDrop(string mode, string itemList) public AutoDrop(string mode, string itemList)
{ {
@ -40,17 +39,11 @@ namespace MinecraftClient.ChatBots
/// <returns>Item type array</returns> /// <returns>Item type array</returns>
private ItemType[] ItemListParser(string itemList) private ItemType[] ItemListParser(string itemList)
{ {
string trimed = new string(itemList.Where(c => !char.IsWhiteSpace(c)).ToArray()); string trimed = new(itemList.Where(c => !char.IsWhiteSpace(c)).ToArray());
string[] list = trimed.Split(','); List<ItemType> result = new();
List<ItemType> result = new List<ItemType>(); foreach (string t in trimed.Split(','))
foreach (string t in list) if (Enum.TryParse(t, true, out ItemType item))
{
ItemType item;
if (Enum.TryParse(t, true, out item))
{
result.Add(item); result.Add(item);
}
}
return result.ToArray(); return result.ToArray();
} }
@ -71,8 +64,7 @@ namespace MinecraftClient.ChatBots
case "add": case "add":
if (args.Length >= 2) if (args.Length >= 2)
{ {
ItemType item; if (Enum.TryParse(args[1], true, out ItemType item))
if (Enum.TryParse(args[1], true, out item))
{ {
itemList.Add(item); itemList.Add(item);
return Translations.Get("bot.autoDrop.added", item.ToString()); return Translations.Get("bot.autoDrop.added", item.ToString());
@ -89,8 +81,7 @@ namespace MinecraftClient.ChatBots
case "remove": case "remove":
if (args.Length >= 2) if (args.Length >= 2)
{ {
ItemType item; if (Enum.TryParse(args[1], true, out ItemType item))
if (Enum.TryParse(args[1], true, out item))
{ {
if (itemList.Contains(item)) if (itemList.Contains(item))
{ {
@ -109,7 +100,7 @@ namespace MinecraftClient.ChatBots
} }
else else
{ {
return Translations.Get("cmd.inventory.help.usage") + ": remove <item name>"; return Translations.Get("cmd.inventory.help.usage") + ": remove <item name>";
} }
case "list": case "list":
if (itemList.Count > 0) if (itemList.Count > 0)
@ -155,7 +146,7 @@ namespace MinecraftClient.ChatBots
} }
} }
private string GetHelp() private static string GetHelp()
{ {
return Translations.Get("general.available_cmd", "on, off, add, remove, list, mode"); return Translations.Get("general.available_cmd", "on, off, add, remove, list, mode");
} }

View file

@ -1,8 +1,4 @@
using MinecraftClient.Inventory; using MinecraftClient.Inventory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
{ {
@ -10,7 +6,7 @@ namespace MinecraftClient.ChatBots
{ {
byte LastSlot = 0; byte LastSlot = 0;
public static bool Eating = false; public static bool Eating = false;
private int HungerThreshold = 6; private readonly int HungerThreshold = 6;
private int DelayCounter = 0; private int DelayCounter = 0;
public AutoEat(int Threshold) public AutoEat(int Threshold)

View file

@ -1,9 +1,6 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MinecraftClient.Mapping;
using MinecraftClient.Inventory; using MinecraftClient.Inventory;
using MinecraftClient.Mapping;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
{ {

View file

@ -1,6 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
@ -10,11 +8,11 @@ namespace MinecraftClient.ChatBots
/// </summary> /// </summary>
public class AutoRelog : ChatBot public class AutoRelog : ChatBot
{ {
private static Random random = new Random(); private static readonly Random random = new();
private string[] dictionary = new string[0]; private string[] dictionary = Array.Empty<string>();
private int attempts; private readonly int attempts;
private int delayMin; private readonly int delayMin;
private int delayMax; private readonly int delayMax;
/// <summary> /// <summary>
/// This bot automatically re-join the server if kick message contains predefined string /// This bot automatically re-join the server if kick message contains predefined string
@ -100,7 +98,7 @@ namespace MinecraftClient.ChatBots
return false; return false;
} }
private void LaunchDelayedReconnection(string msg) private void LaunchDelayedReconnection(string? msg)
{ {
int delay = random.Next(delayMin, delayMax); int delay = random.Next(delayMin, delayMax);
LogDebugToConsoleTranslated(String.IsNullOrEmpty(msg) ? "bot.autoRelog.reconnect_always" : "bot.autoRelog.reconnect", msg); LogDebugToConsoleTranslated(String.IsNullOrEmpty(msg) ? "bot.autoRelog.reconnect_always" : "bot.autoRelog.reconnect", msg);
@ -113,7 +111,7 @@ namespace MinecraftClient.ChatBots
{ {
if (Settings.AutoRelog_Enabled) if (Settings.AutoRelog_Enabled)
{ {
AutoRelog bot = new AutoRelog(Settings.AutoRelog_Delay_Min, Settings.AutoRelog_Delay_Max, Settings.AutoRelog_Retries); AutoRelog bot = new(Settings.AutoRelog_Delay_Min, Settings.AutoRelog_Delay_Max, Settings.AutoRelog_Retries);
bot.Initialize(); bot.Initialize();
return bot.OnDisconnect(reason, message); return bot.OnDisconnect(reason, message);
} }

View file

@ -1,6 +1,6 @@
using System; using System;
using System.IO;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
@ -11,9 +11,9 @@ namespace MinecraftClient.ChatBots
/// </summary> /// </summary>
class AutoRespond : ChatBot class AutoRespond : ChatBot
{ {
private string matchesFile; private readonly string matchesFile;
private bool matchColors; private readonly bool matchColors;
private List<RespondRule> respondRules; private List<RespondRule>? respondRules;
private enum MessageType { Public, Private, Other }; private enum MessageType { Public, Private, Other };
/// <summary> /// <summary>
@ -31,13 +31,13 @@ namespace MinecraftClient.ChatBots
/// </summary> /// </summary>
private class RespondRule private class RespondRule
{ {
private Regex regex; private readonly Regex? regex;
private string match; private readonly string? match;
private string actionPublic; private readonly string? actionPublic;
private string actionPrivate; private readonly string? actionPrivate;
private string actionOther; private readonly string? actionOther;
private bool ownersOnly; private readonly bool ownersOnly;
private TimeSpan cooldown; private readonly TimeSpan cooldown;
private DateTime cooldownExpiration; private DateTime cooldownExpiration;
/// <summary> /// <summary>
@ -49,16 +49,16 @@ namespace MinecraftClient.ChatBots
/// <param name="actionOther">Internal command to run for any other messages</param> /// <param name="actionOther">Internal command to run for any other messages</param>
/// <param name="ownersOnly">Only match messages from bot owners</param> /// <param name="ownersOnly">Only match messages from bot owners</param>
/// <param name="cooldown">Minimal cooldown between two matches</param> /// <param name="cooldown">Minimal cooldown between two matches</param>
public RespondRule(Regex regex, string actionPublic, string actionPrivate, string actionOther, bool ownersOnly, TimeSpan cooldown) public RespondRule(Regex regex, string? actionPublic, string? actionPrivate, string? actionOther, bool ownersOnly, TimeSpan cooldown)
{ {
this.regex = regex; this.regex = regex;
this.match = null; match = null;
this.actionPublic = actionPublic; this.actionPublic = actionPublic;
this.actionPrivate = actionPrivate; this.actionPrivate = actionPrivate;
this.actionOther = actionOther; this.actionOther = actionOther;
this.ownersOnly = ownersOnly; this.ownersOnly = ownersOnly;
this.cooldown = cooldown; this.cooldown = cooldown;
this.cooldownExpiration = DateTime.MinValue; cooldownExpiration = DateTime.MinValue;
} }
/// <summary> /// <summary>
@ -69,16 +69,16 @@ namespace MinecraftClient.ChatBots
/// <param name="actionPrivate">Internal command to run for private messages</param> /// <param name="actionPrivate">Internal command to run for private messages</param>
/// <param name="ownersOnly">Only match messages from bot owners</param> /// <param name="ownersOnly">Only match messages from bot owners</param>
/// <param name="cooldown">Minimal cooldown between two matches</param> /// <param name="cooldown">Minimal cooldown between two matches</param>
public RespondRule(string match, string actionPublic, string actionPrivate, string actionOther, bool ownersOnly, TimeSpan cooldown) public RespondRule(string? match, string? actionPublic, string? actionPrivate, string? actionOther, bool ownersOnly, TimeSpan cooldown)
{ {
this.regex = null; regex = null;
this.match = match; this.match = match;
this.actionPublic = actionPublic; this.actionPublic = actionPublic;
this.actionPrivate = actionPrivate; this.actionPrivate = actionPrivate;
this.actionOther = actionOther; this.actionOther = actionOther;
this.ownersOnly = ownersOnly; this.ownersOnly = ownersOnly;
this.cooldown = cooldown; this.cooldown = cooldown;
this.cooldownExpiration = DateTime.MinValue; cooldownExpiration = DateTime.MinValue;
} }
/// <summary> /// <summary>
@ -89,12 +89,12 @@ namespace MinecraftClient.ChatBots
/// <param name="msgType">Type of the message public/private message, or other message</param> /// <param name="msgType">Type of the message public/private message, or other message</param>
/// <param name="localVars">Dictionary to populate with match variables in case of Regex match</param> /// <param name="localVars">Dictionary to populate with match variables in case of Regex match</param>
/// <returns>Internal command to run as a response to this user, or null if no match has been detected</returns> /// <returns>Internal command to run as a response to this user, or null if no match has been detected</returns>
public string Match(string username, string message, MessageType msgType, Dictionary<string, object> localVars) public string? Match(string username, string message, MessageType msgType, Dictionary<string, object> localVars)
{ {
if (DateTime.Now < cooldownExpiration) if (DateTime.Now < cooldownExpiration)
return null; return null;
string toSend = null; string? toSend = null;
if (ownersOnly && (String.IsNullOrEmpty(username) || !Settings.Bots_Owners.Contains(username.ToLower()))) if (ownersOnly && (String.IsNullOrEmpty(username) || !Settings.Bots_Owners.Contains(username.ToLower())))
return null; return null;
@ -166,11 +166,11 @@ namespace MinecraftClient.ChatBots
{ {
if (File.Exists(matchesFile)) if (File.Exists(matchesFile))
{ {
Regex matchRegex = null; Regex? matchRegex = null;
string matchString = null; string? matchString = null;
string matchAction = null; string? matchAction = null;
string matchActionPrivate = null; string? matchActionPrivate = null;
string matchActionOther = null; string? matchActionOther = null;
bool ownersOnly = false; bool ownersOnly = false;
TimeSpan cooldown = TimeSpan.Zero; TimeSpan cooldown = TimeSpan.Zero;
respondRules = new List<RespondRule>(); respondRules = new List<RespondRule>();
@ -182,9 +182,9 @@ namespace MinecraftClient.ChatBots
string line = lineRAW.Split('#')[0].Trim(); string line = lineRAW.Split('#')[0].Trim();
if (line.Length > 0) if (line.Length > 0)
{ {
if (line[0] == '[' && line[line.Length - 1] == ']') if (line[0] == '[' && line[^1] == ']')
{ {
switch (line.Substring(1, line.Length - 2).ToLower()) switch (line[1..^1].ToLower())
{ {
case "match": case "match":
CheckAddMatch(matchRegex, matchString, matchAction, matchActionPrivate, matchActionOther, ownersOnly, cooldown); CheckAddMatch(matchRegex, matchString, matchAction, matchActionPrivate, matchActionOther, ownersOnly, cooldown);
@ -203,7 +203,7 @@ namespace MinecraftClient.ChatBots
string argName = line.Split('=')[0]; string argName = line.Split('=')[0];
if (line.Length > (argName.Length + 1)) if (line.Length > (argName.Length + 1))
{ {
string argValue = line.Substring(argName.Length + 1); string argValue = line[(argName.Length + 1)..];
switch (argName.ToLower()) switch (argName.ToLower())
{ {
case "regex": matchRegex = new Regex(argValue); break; case "regex": matchRegex = new Regex(argValue); break;
@ -236,7 +236,7 @@ namespace MinecraftClient.ChatBots
/// <param name="matchActionPrivate">Action if the matching message is private</param> /// <param name="matchActionPrivate">Action if the matching message is private</param>
/// <param name="ownersOnly">Only match messages from bot owners</param> /// <param name="ownersOnly">Only match messages from bot owners</param>
/// <param name="cooldown">Minimal cooldown between two matches</param> /// <param name="cooldown">Minimal cooldown between two matches</param>
private void CheckAddMatch(Regex matchRegex, string matchString, string matchAction, string matchActionPrivate, string matchActionOther, bool ownersOnly, TimeSpan cooldown) private void CheckAddMatch(Regex? matchRegex, string? matchString, string? matchAction, string? matchActionPrivate, string? matchActionOther, bool ownersOnly, TimeSpan cooldown)
{ {
if (matchRegex != null || matchString != null || matchAction != null || matchActionPrivate != null || matchActionOther != null || ownersOnly || cooldown != TimeSpan.Zero) if (matchRegex != null || matchString != null || matchAction != null || matchActionPrivate != null || matchActionOther != null || ownersOnly || cooldown != TimeSpan.Zero)
{ {
@ -248,7 +248,7 @@ namespace MinecraftClient.ChatBots
{ {
if (matchRegex != null || matchString != null) if (matchRegex != null || matchString != null)
{ {
respondRules.Add(rule); respondRules!.Add(rule);
LogDebugToConsoleTranslated("bot.autoRespond.loaded_match", rule); LogDebugToConsoleTranslated("bot.autoRespond.loaded_match", rule);
} }
else LogDebugToConsoleTranslated("bot.autoRespond.no_trigger", rule); else LogDebugToConsoleTranslated("bot.autoRespond.no_trigger", rule);
@ -264,7 +264,7 @@ namespace MinecraftClient.ChatBots
public override void GetText(string text) public override void GetText(string text)
{ {
//Remove colour codes //Remove colour codes
if (!this.matchColors) if (!matchColors)
text = GetVerbatim(text); text = GetVerbatim(text);
//Get Message type //Get Message type
@ -279,13 +279,13 @@ namespace MinecraftClient.ChatBots
//Do not process messages sent by the bot itself //Do not process messages sent by the bot itself
if (msgType == MessageType.Other || sender != Settings.Username) if (msgType == MessageType.Other || sender != Settings.Username)
{ {
foreach (RespondRule rule in respondRules) foreach (RespondRule rule in respondRules!)
{ {
Dictionary<string, object> localVars = new Dictionary<string, object>(); Dictionary<string, object> localVars = new();
string toPerform = rule.Match(sender, message, msgType, localVars); string? toPerform = rule.Match(sender, message, msgType, localVars);
if (!String.IsNullOrEmpty(toPerform)) if (!String.IsNullOrEmpty(toPerform))
{ {
string response = null; string? response = null;
LogToConsoleTranslated("bot.autoRespond.match_run", toPerform); LogToConsoleTranslated("bot.autoRespond.match_run", toPerform);
PerformInternalCommand(toPerform, ref response, localVars); PerformInternalCommand(toPerform, ref response, localVars);
if (!String.IsNullOrEmpty(response)) if (!String.IsNullOrEmpty(response))

View file

@ -1,7 +1,5 @@
using MinecraftClient.Mapping;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
@ -12,11 +10,11 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "bots [list|unload <bot name|all>]"; } } public override string CmdUsage { get { return "bots [list|unload <bot name|all>]"; } }
public override string CmdDesc { get { return "cmd.bots.desc"; } } public override string CmdDesc { get { return "cmd.bots.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (hasArg(command)) if (HasArg(command))
{ {
string[] args = getArgs(command); string[] args = GetArgs(command);
if (args.Length == 1) if (args.Length == 1)
{ {

View file

@ -1,7 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; using System.IO;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
@ -13,13 +10,13 @@ namespace MinecraftClient.ChatBots
public class ChatLog : ChatBot public class ChatLog : ChatBot
{ {
public enum MessageFilter { AllText, AllMessages, OnlyChat, OnlyWhispers, OnlyInternalCommands }; public enum MessageFilter { AllText, AllMessages, OnlyChat, OnlyWhispers, OnlyInternalCommands };
private bool dateandtime; private readonly bool dateandtime;
private bool saveOther = true; private readonly bool saveOther = true;
private bool saveChat = true; private readonly bool saveChat = true;
private bool savePrivate = true; private readonly bool savePrivate = true;
private bool saveInternal = true; private readonly bool saveInternal = true;
private string logfile; private readonly string logfile;
private object logfileLock = new object(); private readonly object logfileLock = new();
/// <summary> /// <summary>
/// This bot saves the messages received in the specified file, with some filters and date/time tagging. /// This bot saves the messages received in the specified file, with some filters and date/time tagging.
@ -70,15 +67,17 @@ namespace MinecraftClient.ChatBots
public static MessageFilter str2filter(string filtername) public static MessageFilter str2filter(string filtername)
{ {
switch (Settings.ToLowerIfNeed(filtername)) return Settings.ToLowerIfNeed(filtername) switch
{ {
case "all": return MessageFilter.AllText; #pragma warning disable format // @formatter:off
case "messages": return MessageFilter.AllMessages; "all" => MessageFilter.AllText,
case "chat": return MessageFilter.OnlyChat; "messages" => MessageFilter.AllMessages,
case "private": return MessageFilter.OnlyWhispers; "chat" => MessageFilter.OnlyChat,
case "internal": return MessageFilter.OnlyInternalCommands; "private" => MessageFilter.OnlyWhispers,
default: return MessageFilter.AllText; "internal" => MessageFilter.OnlyInternalCommands,
} _ => MessageFilter.AllText,
#pragma warning restore format // @formatter:on
};
} }
public override void GetText(string text) public override void GetText(string text)
@ -89,37 +88,37 @@ namespace MinecraftClient.ChatBots
if (saveChat && IsChatMessage(text, ref message, ref sender)) if (saveChat && IsChatMessage(text, ref message, ref sender))
{ {
save("Chat " + sender + ": " + message); Save("Chat " + sender + ": " + message);
} }
else if (savePrivate && IsPrivateMessage(text, ref message, ref sender)) else if (savePrivate && IsPrivateMessage(text, ref message, ref sender))
{ {
save("Private " + sender + ": " + message); Save("Private " + sender + ": " + message);
} }
else if (saveOther) else if (saveOther)
{ {
save("Other: " + text); Save("Other: " + text);
} }
} }
public override void OnInternalCommand(string commandName,string commandParams, string result) public override void OnInternalCommand(string commandName, string commandParams, string result)
{ {
if (saveInternal) if (saveInternal)
{ {
save(string.Format("Internal {0}({1}): {2}", commandName, commandParams, result)); Save(string.Format("Internal {0}({1}): {2}", commandName, commandParams, result));
} }
} }
private void save(string tosave) private void Save(string tosave)
{ {
if (dateandtime) if (dateandtime)
tosave = GetTimestamp() + ' ' + tosave; tosave = GetTimestamp() + ' ' + tosave;
lock (logfileLock) lock (logfileLock)
{ {
string directory = Path.GetDirectoryName(logfile); string? directory = Path.GetDirectoryName(logfile);
if (!String.IsNullOrEmpty(directory) && !Directory.Exists(directory)) if (!String.IsNullOrEmpty(directory) && !Directory.Exists(directory))
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
FileStream stream = new FileStream(logfile, FileMode.OpenOrCreate); FileStream stream = new(logfile, FileMode.OpenOrCreate);
StreamWriter writer = new StreamWriter(stream); StreamWriter writer = new(stream);
stream.Seek(0, SeekOrigin.End); stream.Seek(0, SeekOrigin.End);
writer.WriteLine(tosave); writer.WriteLine(tosave);
writer.Dispose(); writer.Dispose();

View file

@ -8,8 +8,8 @@ namespace MinecraftClient.ChatBots
{ {
private string? _playerToFollow = null; private string? _playerToFollow = null;
private int _updateCounter = 0; private int _updateCounter = 0;
private int _updateLimit; private readonly int _updateLimit;
private int _stopAtDistance; private readonly int _stopAtDistance;
private bool _unsafeEnabled = false; private bool _unsafeEnabled = false;
public FollowPlayer(int updateLimit = 15, int stopAtDistance = 3) public FollowPlayer(int updateLimit = 15, int stopAtDistance = 3)
@ -112,7 +112,7 @@ namespace MinecraftClient.ChatBots
return; return;
// Stop at specified distance from plater (prevents pushing player around) // Stop at specified distance from plater (prevents pushing player around)
double distance = Distance(entity.Location, GetCurrentLocation()); double distance = entity.Location.Distance(GetCurrentLocation());
if (distance < _stopAtDistance) if (distance < _stopAtDistance)
return; return;
@ -154,14 +154,6 @@ namespace MinecraftClient.ChatBots
} }
} }
private double Distance(Location location1, Location location2)
{
return Math.Sqrt(
((location1.X - location2.X) * (location1.X - location2.X)) +
((location1.Y - location2.Y) * (location1.Y - location2.Y)) +
((location1.Z - location2.Z) * (location1.Z - location2.Z)));
}
private bool CanMoveThere(Location location) private bool CanMoveThere(Location location)
{ {
ChunkColumn? chunkColumn = GetWorld().GetChunkColumn(location); ChunkColumn? chunkColumn = GetWorld().GetChunkColumn(location);

View file

@ -1,6 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
@ -12,14 +10,14 @@ namespace MinecraftClient.ChatBots
public class HangmanGame : ChatBot public class HangmanGame : ChatBot
{ {
private int vie = 0; private int vie = 0;
private int vie_param = 10; private readonly int vie_param = 10;
private int compteur = 0; private int compteur = 0;
private int compteur_param = 3000; //5 minutes private readonly int compteur_param = 3000; //5 minutes
private bool running = false; private bool running = false;
private bool[] discovered; private bool[] discovered;
private string word = ""; private string word = "";
private string letters = ""; private string letters = "";
private bool English; private readonly bool English;
/// <summary> /// <summary>
/// Le jeu du Pendu / Hangman Game /// Le jeu du Pendu / Hangman Game
@ -29,6 +27,7 @@ namespace MinecraftClient.ChatBots
public HangmanGame(bool english) public HangmanGame(bool english)
{ {
English = english; English = english;
discovered = Array.Empty<bool>();
} }
public override void Update() public override void Update()
@ -61,7 +60,7 @@ namespace MinecraftClient.ChatBots
switch (message) switch (message)
{ {
case "start": case "start":
start(); Start();
break; break;
case "stop": case "stop":
running = false; running = false;
@ -108,11 +107,11 @@ namespace MinecraftClient.ChatBots
if (running) if (running)
{ {
SendText(English ? ("Mysterious word: " + word_cached + " (lives : " + vie + ")") SendText(English ? ("Mysterious word: " + WordCached + " (lives : " + vie + ")")
: ("Mot mystère : " + word_cached + " (vie : " + vie + ")")); : ("Mot mystère : " + WordCached + " (vie : " + vie + ")"));
} }
if (winner) if (Winner)
{ {
SendText(English ? ("Congrats, " + username + '!') : ("Félicitations, " + username + " !")); SendText(English ? ("Congrats, " + username + '!') : ("Félicitations, " + username + " !"));
running = false; running = false;
@ -124,22 +123,22 @@ namespace MinecraftClient.ChatBots
} }
} }
private void start() private void Start()
{ {
vie = vie_param; vie = vie_param;
running = true; running = true;
letters = ""; letters = "";
word = chooseword(); word = Chooseword();
compteur = compteur_param; compteur = compteur_param;
discovered = new bool[word.Length]; discovered = new bool[word.Length];
SendText(English ? "Hangman v1.0 - By ORelio" : "Pendu v1.0 - Par ORelio"); SendText(English ? "Hangman v1.0 - By ORelio" : "Pendu v1.0 - Par ORelio");
SendText(English ? ("Mysterious word: " + word_cached + " (lives : " + vie + ")") SendText(English ? ("Mysterious word: " + WordCached + " (lives : " + vie + ")")
: ("Mot mystère : " + word_cached + " (vie : " + vie + ")")); : ("Mot mystère : " + WordCached + " (vie : " + vie + ")"));
SendText(English ? ("Try some letters ... :)") : ("Proposez une lettre ... :)")); SendText(English ? ("Try some letters ... :)") : ("Proposez une lettre ... :)"));
} }
private string chooseword() private string Chooseword()
{ {
if (System.IO.File.Exists(English ? Settings.Hangman_FileWords_EN : Settings.Hangman_FileWords_FR)) if (System.IO.File.Exists(English ? Settings.Hangman_FileWords_EN : Settings.Hangman_FileWords_FR))
{ {
@ -153,7 +152,7 @@ namespace MinecraftClient.ChatBots
} }
} }
private string word_cached private string WordCached
{ {
get get
{ {
@ -170,7 +169,7 @@ namespace MinecraftClient.ChatBots
} }
} }
private bool winner private bool Winner
{ {
get get
{ {

View file

@ -1,8 +1,8 @@
using System; using System;
using System.Collections.Generic;
using System.Data; using System.Data;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Collections.Generic;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
{ {
@ -23,7 +23,7 @@ namespace MinecraftClient.ChatBots
/// <returns>Ignore list</returns> /// <returns>Ignore list</returns>
public static IgnoreList FromFile(string filePath) public static IgnoreList FromFile(string filePath)
{ {
IgnoreList ignoreList = new IgnoreList(); IgnoreList ignoreList = new();
foreach (string line in FileMonitor.ReadAllLinesWithRetries(filePath)) foreach (string line in FileMonitor.ReadAllLinesWithRetries(filePath))
{ {
if (!line.StartsWith("#")) if (!line.StartsWith("#"))
@ -42,7 +42,7 @@ namespace MinecraftClient.ChatBots
/// <param name="filePath">Path to destination file</param> /// <param name="filePath">Path to destination file</param>
public void SaveToFile(string filePath) public void SaveToFile(string filePath)
{ {
List<string> lines = new List<string>(); List<string> lines = new();
lines.Add("#Ignored Players"); lines.Add("#Ignored Players");
foreach (string player in this) foreach (string player in this)
lines.Add(player); lines.Add(player);
@ -62,7 +62,7 @@ namespace MinecraftClient.ChatBots
/// <returns>Mail database</returns> /// <returns>Mail database</returns>
public static MailDatabase FromFile(string filePath) public static MailDatabase FromFile(string filePath)
{ {
MailDatabase database = new MailDatabase(); MailDatabase database = new();
Dictionary<string, Dictionary<string, string>> iniFileDict = INIFile.ParseFile(FileMonitor.ReadAllLinesWithRetries(filePath)); Dictionary<string, Dictionary<string, string>> iniFileDict = INIFile.ParseFile(FileMonitor.ReadAllLinesWithRetries(filePath));
foreach (KeyValuePair<string, Dictionary<string, string>> iniSection in iniFileDict) foreach (KeyValuePair<string, Dictionary<string, string>> iniSection in iniFileDict)
{ {
@ -83,17 +83,21 @@ namespace MinecraftClient.ChatBots
/// <param name="filePath">Path to destination file</param> /// <param name="filePath">Path to destination file</param>
public void SaveToFile(string filePath) public void SaveToFile(string filePath)
{ {
Dictionary<string, Dictionary<string, string>> iniFileDict = new Dictionary<string, Dictionary<string, string>>(); Dictionary<string, Dictionary<string, string>> iniFileDict = new();
int mailCount = 0; int mailCount = 0;
foreach (Mail mail in this) foreach (Mail mail in this)
{ {
mailCount++; mailCount++;
Dictionary<string, string> iniSection = new Dictionary<string, string>(); Dictionary<string, string> iniSection = new()
iniSection["sender"] = mail.Sender; {
iniSection["recipient"] = mail.Recipient; #pragma warning disable format // @formatter:off
iniSection["content"] = mail.Content; ["sender"] = mail.Sender,
iniSection["timestamp"] = mail.DateSent.ToString(); ["recipient"] = mail.Recipient,
iniSection["anonymous"] = mail.Anonymous.ToString(); ["content"] = mail.Content,
["timestamp"] = mail.DateSent.ToString(),
["anonymous"] = mail.Anonymous.ToString()
#pragma warning restore format // @formatter:on
};
iniFileDict["mail" + mailCount] = iniSection; iniFileDict["mail" + mailCount] = iniSection;
} }
FileMonitor.WriteAllLinesWithRetries(filePath, INIFile.Generate(iniFileDict, "Mail Database")); FileMonitor.WriteAllLinesWithRetries(filePath, INIFile.Generate(iniFileDict, "Mail Database"));
@ -105,24 +109,24 @@ namespace MinecraftClient.ChatBots
/// </summary> /// </summary>
private class Mail private class Mail
{ {
private string sender; private readonly string sender;
private string senderLower; private readonly string senderLower;
private string recipient; private readonly string recipient;
private string recipientLower; private readonly string recipientLower;
private string message; private readonly string message;
private DateTime datesent; private readonly DateTime datesent;
private bool delivered; private bool delivered;
private bool anonymous; private readonly bool anonymous;
public Mail(string sender, string recipient, string message, bool anonymous, DateTime datesent) public Mail(string sender, string recipient, string message, bool anonymous, DateTime datesent)
{ {
this.sender = sender; this.sender = sender;
this.senderLower = sender.ToLower(); senderLower = sender.ToLower();
this.recipient = recipient; this.recipient = recipient;
this.recipientLower = recipient.ToLower(); recipientLower = recipient.ToLower();
this.message = message; this.message = message;
this.datesent = datesent; this.datesent = datesent;
this.delivered = false; delivered = false;
this.anonymous = anonymous; this.anonymous = anonymous;
} }
@ -132,9 +136,9 @@ namespace MinecraftClient.ChatBots
public string RecipientLowercase { get { return recipientLower; } } public string RecipientLowercase { get { return recipientLower; } }
public string Content { get { return message; } } public string Content { get { return message; } }
public DateTime DateSent { get { return datesent; } } public DateTime DateSent { get { return datesent; } }
public bool Delivered { get { return delivered; } } public bool Delivered => delivered;
public bool Anonymous { get { return anonymous; } } public bool Anonymous { get { return anonymous; } }
public void setDelivered() { delivered = true; } public void SetDelivered() { delivered = true; }
public override string ToString() public override string ToString()
{ {
@ -145,11 +149,11 @@ namespace MinecraftClient.ChatBots
// Internal variables // Internal variables
private int maxMessageLength = 0; private int maxMessageLength = 0;
private DateTime nextMailSend = DateTime.Now; private DateTime nextMailSend = DateTime.Now;
private MailDatabase mailDatabase = new MailDatabase(); private MailDatabase mailDatabase = new();
private IgnoreList ignoreList = new IgnoreList(); private IgnoreList ignoreList = new();
private FileMonitor mailDbFileMonitor; private FileMonitor? mailDbFileMonitor;
private FileMonitor ignoreListFileMonitor; private FileMonitor? ignoreListFileMonitor;
private object readWriteLock = new object(); private readonly object readWriteLock = new();
/// <summary> /// <summary>
/// Initialization of the Mailer bot /// Initialization of the Mailer bot
@ -207,8 +211,8 @@ namespace MinecraftClient.ChatBots
} }
//Initialize file monitors. In case the bot needs to unload for some reason in the future, do not forget to .Dispose() them //Initialize file monitors. In case the bot needs to unload for some reason in the future, do not forget to .Dispose() them
mailDbFileMonitor = new FileMonitor(Path.GetDirectoryName(Settings.Mailer_DatabaseFile), Path.GetFileName(Settings.Mailer_DatabaseFile), FileMonitorCallback); mailDbFileMonitor = new FileMonitor(Path.GetDirectoryName(Settings.Mailer_DatabaseFile)!, Path.GetFileName(Settings.Mailer_DatabaseFile), FileMonitorCallback);
ignoreListFileMonitor = new FileMonitor(Path.GetDirectoryName(Settings.Mailer_IgnoreListFile), Path.GetFileName(Settings.Mailer_IgnoreListFile), FileMonitorCallback); ignoreListFileMonitor = new FileMonitor(Path.GetDirectoryName(Settings.Mailer_IgnoreListFile)!, Path.GetFileName(Settings.Mailer_IgnoreListFile), FileMonitorCallback);
RegisterChatBotCommand("mailer", Translations.Get("bot.mailer.cmd"), "mailer <getmails|addignored|getignored|removeignored>", ProcessInternalCommand); RegisterChatBotCommand("mailer", Translations.Get("bot.mailer.cmd"), "mailer <getmails|addignored|getignored|removeignored>", ProcessInternalCommand);
} }
@ -246,7 +250,7 @@ namespace MinecraftClient.ChatBots
&& mailDatabase.Count < Settings.Mailer_MaxDatabaseSize && mailDatabase.Count < Settings.Mailer_MaxDatabaseSize
&& mailDatabase.Where(mail => mail.SenderLowercase == usernameLower).Count() < Settings.Mailer_MaxMailsPerPlayer) && mailDatabase.Where(mail => mail.SenderLowercase == usernameLower).Count() < Settings.Mailer_MaxMailsPerPlayer)
{ {
Queue<string> args = new Queue<string>(Command.getArgs(message)); Queue<string> args = new(Command.GetArgs(message));
if (args.Count >= 2) if (args.Count >= 2)
{ {
bool anonymous = (command == "tellonym"); bool anonymous = (command == "tellonym");
@ -257,7 +261,7 @@ namespace MinecraftClient.ChatBots
{ {
if (message.Length <= maxMessageLength) if (message.Length <= maxMessageLength)
{ {
Mail mail = new Mail(username, recipient, message, anonymous, DateTime.Now); Mail mail = new(username, recipient, message, anonymous, DateTime.Now);
LogToConsoleTranslated("bot.mailer.saving", mail.ToString()); LogToConsoleTranslated("bot.mailer.saving", mail.ToString());
lock (readWriteLock) lock (readWriteLock)
{ {
@ -291,12 +295,12 @@ namespace MinecraftClient.ChatBots
LogDebugToConsoleTranslated("bot.mailer.process_mails", DateTime.Now); LogDebugToConsoleTranslated("bot.mailer.process_mails", DateTime.Now);
// Process at most 3 mails at a time to avoid spamming. Other mails will be processed on next mail send // Process at most 3 mails at a time to avoid spamming. Other mails will be processed on next mail send
HashSet<string> onlinePlayersLowercase = new HashSet<string>(GetOnlinePlayers().Select(name => name.ToLower())); HashSet<string> onlinePlayersLowercase = new(GetOnlinePlayers().Select(name => name.ToLower()));
foreach (Mail mail in mailDatabase.Where(mail => !mail.Delivered && onlinePlayersLowercase.Contains(mail.RecipientLowercase)).Take(3)) foreach (Mail mail in mailDatabase.Where(mail => !mail.Delivered && onlinePlayersLowercase.Contains(mail.RecipientLowercase)).Take(3))
{ {
string sender = mail.Anonymous ? "Anonymous" : mail.Sender; string sender = mail.Anonymous ? "Anonymous" : mail.Sender;
SendPrivateMessage(mail.Recipient, sender + " mailed: " + mail.Content); SendPrivateMessage(mail.Recipient, sender + " mailed: " + mail.Content);
mail.setDelivered(); mail.SetDelivered();
LogDebugToConsoleTranslated("bot.mailer.delivered", mail.ToString()); LogDebugToConsoleTranslated("bot.mailer.delivered", mail.ToString());
} }
@ -336,7 +340,7 @@ namespace MinecraftClient.ChatBots
switch (commandName) switch (commandName)
{ {
case "getmails": // Sorry, I (ReinforceZwei) replaced "=" to "-" because it would affect the parsing of translation file (key=value) case "getmails": // Sorry, I (ReinforceZwei) replaced "=" to "-" because it would affect the parsing of translation file (key=value)
return Translations.Get("bot.mailer.cmd.getmails", string.Join("\n", mailDatabase)); return Translations.Get("bot.mailer.cmd.getmails", string.Join("\n", mailDatabase));
case "getignored": case "getignored":
return Translations.Get("bot.mailer.cmd.getignored", string.Join("\n", ignoreList)); return Translations.Get("bot.mailer.cmd.getignored", string.Join("\n", ignoreList));

View file

@ -1,17 +1,17 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing;
using System.IO; using System.IO;
using MinecraftClient.Mapping; using MinecraftClient.Mapping;
using System.Drawing;
using MinecraftClient.Protocol.Handlers; using MinecraftClient.Protocol.Handlers;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
{ {
class Map : ChatBot class Map : ChatBot
{ {
private string baseDirectory = @"Rendered_Maps"; private readonly string baseDirectory = @"Rendered_Maps";
private Dictionary<int, McMap> cachedMaps = new(); private readonly Dictionary<int, McMap> cachedMaps = new();
private bool shouldResize = true; private bool shouldResize = true;
private int resizeTo = 256; private int resizeTo = 256;
private bool autoRenderOnUpdate = true; private bool autoRenderOnUpdate = true;
@ -40,7 +40,7 @@ namespace MinecraftClient.ChatBots
{ {
if (deleteAllOnExit) if (deleteAllOnExit)
{ {
DirectoryInfo di = new DirectoryInfo(baseDirectory); DirectoryInfo di = new(baseDirectory);
FileInfo[] files = di.GetFiles(); FileInfo[] files = di.GetFiles();
foreach (FileInfo file in files) foreach (FileInfo file in files)
@ -101,19 +101,20 @@ namespace MinecraftClient.ChatBots
if (columnsUpdated == 0 && cachedMaps.ContainsKey(mapid)) if (columnsUpdated == 0 && cachedMaps.ContainsKey(mapid))
return; return;
McMap map = new McMap(); McMap map = new()
{
map.MapId = mapid; MapId = mapid,
map.Scale = scale; Scale = scale,
map.TrackingPosition = trackingPosition; TrackingPosition = trackingPosition,
map.Locked = locked; Locked = locked,
map.MapIcons = icons; MapIcons = icons,
map.Width = rowsUpdated; Width = rowsUpdated,
map.Height = columnsUpdated; Height = columnsUpdated,
map.X = mapCoulmnX; X = mapCoulmnX,
map.Z = mapRowZ; Z = mapRowZ,
map.Colors = colors; Colors = colors,
map.LastUpdated = DateTime.Now; LastUpdated = DateTime.Now
};
if (!cachedMaps.ContainsKey(mapid)) if (!cachedMaps.ContainsKey(mapid))
{ {
@ -139,7 +140,7 @@ namespace MinecraftClient.ChatBots
if (File.Exists(fileName)) if (File.Exists(fileName))
File.Delete(fileName); File.Delete(fileName);
Bitmap image = new Bitmap(map.Width, map.Height); Bitmap image = new(map.Width, map.Height);
for (int x = 0; x < map.Width; ++x) for (int x = 0; x < map.Width; ++x)
{ {
@ -168,7 +169,7 @@ namespace MinecraftClient.ChatBots
} }
private Bitmap ResizeBitmap(Bitmap sourceBMP, int width, int height) private Bitmap ResizeBitmap(Bitmap sourceBMP, int width, int height)
{ {
Bitmap result = new Bitmap(width, height); Bitmap result = new(width, height);
using (Graphics g = Graphics.FromImage(result)) using (Graphics g = Graphics.FromImage(result))
g.DrawImage(sourceBMP, 0, 0, width, height); g.DrawImage(sourceBMP, 0, 0, width, height);
return result; return result;

View file

@ -1,8 +1,6 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using static System.Net.Mime.MediaTypeNames;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
{ {
@ -13,8 +11,8 @@ namespace MinecraftClient.ChatBots
public class PlayerListLogger : ChatBot public class PlayerListLogger : ChatBot
{ {
private int count; private int count;
private int timeping; private readonly int timeping;
private string file; private readonly string file;
/// <summary> /// <summary>
/// This bot sends a /list command every X seconds and save the result. /// This bot sends a /list command every X seconds and save the result.
@ -35,24 +33,14 @@ namespace MinecraftClient.ChatBots
count++; count++;
if (count == timeping) if (count == timeping)
{ {
string[] playerList = GetOnlinePlayers(); DateTime now = DateTime.Now;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < playerList.Length; i++)
{
sb.Append(playerList[i]);
// Do not add a comma after the last username
if (i != playerList.Length - 1)
sb.Append(", ");
}
LogDebugToConsole("Saving Player List"); LogDebugToConsole("Saving Player List");
DateTime now = DateTime.Now; StringBuilder sb = new();
string TimeStamp = "[" + now.Year + '/' + now.Month + '/' + now.Day + ' ' + now.Hour + ':' + now.Minute + ']'; sb.AppendLine(string.Format("[{0}/{1}/{2} {3}:{4}]", now.Year, now.Month, now.Day, now.Hour, now.Minute));
System.IO.File.AppendAllText(file, TimeStamp + "\n" + sb.ToString() + "\n\n"); sb.AppendLine(string.Join(", ", GetOnlinePlayers())).AppendLine();
System.IO.File.AppendAllText(file, sb.ToString());
count = 0; count = 0;
} }

View file

@ -1,8 +1,4 @@
using MinecraftClient.Mapping;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -12,7 +8,7 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "reload"; } } public override string CmdUsage { get { return "reload"; } }
public override string CmdDesc { get { return "cmd.reload.desc"; } } public override string CmdDesc { get { return "cmd.reload.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
handler.Log.Info(Translations.TryGet("cmd.reload.started")); handler.Log.Info(Translations.TryGet("cmd.reload.started"));
handler.ReloadSettings(); handler.ReloadSettings();

View file

@ -1,7 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
{ {
@ -17,7 +14,7 @@ namespace MinecraftClient.ChatBots
string command = "", sender = ""; string command = "", sender = "";
if (IsPrivateMessage(text, ref command, ref sender) && Settings.Bots_Owners.Contains(sender.ToLower().Trim())) if (IsPrivateMessage(text, ref command, ref sender) && Settings.Bots_Owners.Contains(sender.ToLower().Trim()))
{ {
string response = ""; string? response = "";
PerformInternalCommand(command, ref response); PerformInternalCommand(command, ref response);
response = GetVerbatim(response); response = GetVerbatim(response);
foreach (char disallowedChar in McClient.GetDisallowedChatCharacters()) foreach (char disallowedChar in McClient.GetDisallowedChatCharacters())

View file

@ -1,7 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using MinecraftClient.Protocol; using MinecraftClient.Protocol;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
@ -11,15 +9,16 @@ namespace MinecraftClient.ChatBots
/// </summary> /// </summary>
public class ReplayCapture : ChatBot public class ReplayCapture : ChatBot
{ {
private ReplayHandler replay; private ReplayHandler? replay;
private int backupInterval = 3000; // Unit: second * 10 private readonly int backupInterval = 3000; // Unit: second * 10
private int backupCounter = -1; private int backupCounter = -1;
public ReplayCapture(int backupInterval) public ReplayCapture(int backupInterval)
{ {
if (backupInterval != -1) if (backupInterval != -1)
this.backupInterval = backupInterval * 10; this.backupInterval = backupInterval * 10;
else this.backupInterval = -1; else
this.backupInterval = -1;
} }
public override void Initialize() public override void Initialize()
@ -34,12 +33,12 @@ namespace MinecraftClient.ChatBots
public override void OnNetworkPacket(int packetID, List<byte> packetData, bool isLogin, bool isInbound) public override void OnNetworkPacket(int packetID, List<byte> packetData, bool isLogin, bool isInbound)
{ {
replay.AddPacket(packetID, packetData, isLogin, isInbound); replay!.AddPacket(packetID, packetData, isLogin, isInbound);
} }
public override void Update() public override void Update()
{ {
if (backupInterval > 0 && replay.RecordRunning) if (backupInterval > 0 && replay!.RecordRunning)
{ {
if (backupCounter <= 0) if (backupCounter <= 0)
{ {
@ -52,7 +51,7 @@ namespace MinecraftClient.ChatBots
public override bool OnDisconnect(DisconnectReason reason, string message) public override bool OnDisconnect(DisconnectReason reason, string message)
{ {
replay.OnShutDown(); replay!.OnShutDown();
return base.OnDisconnect(reason, message); return base.OnDisconnect(reason, message);
} }
@ -60,7 +59,7 @@ namespace MinecraftClient.ChatBots
{ {
try try
{ {
if (replay.RecordRunning) if (replay!.RecordRunning)
{ {
if (args.Length > 0) if (args.Length > 0)
{ {

View file

@ -1,13 +1,10 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
{ {
@ -17,32 +14,32 @@ namespace MinecraftClient.ChatBots
public class Script : ChatBot public class Script : ChatBot
{ {
private string file; private string? file;
private string[] lines = new string[0]; private string[] lines = Array.Empty<string>();
private string[] args = new string[0]; private string[] args = Array.Empty<string>();
private int sleepticks = 10; private int sleepticks = 10;
private int nextline = 0; private int nextline = 0;
private string owner; private readonly string? owner;
private bool csharp; private bool csharp;
private Thread thread; private Thread? thread;
private Dictionary<string, object> localVars; private readonly Dictionary<string, object>? localVars;
public Script(string filename) public Script(string filename)
{ {
ParseArguments(filename); ParseArguments(filename);
} }
public Script(string filename, string ownername, Dictionary<string, object> localVars) public Script(string filename, string? ownername, Dictionary<string, object>? localVars)
: this(filename) : this(filename)
{ {
this.owner = ownername; owner = ownername;
this.localVars = localVars; this.localVars = localVars;
} }
private void ParseArguments(string argstr) private void ParseArguments(string argstr)
{ {
List<string> args = new List<string>(); List<string> args = new();
StringBuilder str = new StringBuilder(); StringBuilder str = new();
bool escape = false; bool escape = false;
bool quotes = false; bool quotes = false;
@ -115,9 +112,9 @@ namespace MinecraftClient.ChatBots
string caller = "Script"; string caller = "Script";
try try
{ {
StackFrame frame = new StackFrame(1); StackFrame frame = new(1);
MethodBase method = frame.GetMethod(); MethodBase method = frame.GetMethod()!;
Type type = method.DeclaringType; Type type = method.DeclaringType!;
caller = type.Name; caller = type.Name;
} }
catch { } catch { }
@ -130,7 +127,7 @@ namespace MinecraftClient.ChatBots
public override void Initialize() public override void Initialize()
{ {
//Load the given file from the startup parameters //Load the given file from the startup parameters
if (LookForScript(ref file)) if (LookForScript(ref file!))
{ {
lines = System.IO.File.ReadAllLines(file, Encoding.UTF8); lines = System.IO.File.ReadAllLines(file, Encoding.UTF8);
csharp = file.EndsWith(".cs"); csharp = file.EndsWith(".cs");
@ -145,7 +142,7 @@ namespace MinecraftClient.ChatBots
if (!String.IsNullOrEmpty(owner)) if (!String.IsNullOrEmpty(owner))
SendPrivateMessage(owner, Translations.Get("bot.script.file_not_found", file)); SendPrivateMessage(owner, Translations.Get("bot.script.file_not_found", file));
UnloadBot(); //No need to keep the bot active UnloadBot(); //No need to keep the bot active
} }
} }
@ -171,8 +168,10 @@ namespace MinecraftClient.ChatBots
SendPrivateMessage(owner, errorMessage); SendPrivateMessage(owner, errorMessage);
LogToConsole(e.InnerException); LogToConsole(e.InnerException);
} }
}); })
thread.Name = "MCC Script - " + file; {
Name = "MCC Script - " + file
};
thread.Start(); thread.Start();
} }
@ -204,7 +203,7 @@ namespace MinecraftClient.ChatBots
int ticks = 10; int ticks = 10;
try try
{ {
ticks = Convert.ToInt32(instruction_line.Substring(5, instruction_line.Length - 5)); ticks = Convert.ToInt32(instruction_line[5..]);
} }
catch { } catch { }
sleepticks = ticks; sleepticks = ticks;

View file

@ -1,8 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization; using System.Globalization;
using System.Text;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
{ {
@ -14,7 +13,7 @@ namespace MinecraftClient.ChatBots
{ {
private class TaskDesc private class TaskDesc
{ {
public string action = null; public string? action = null;
public bool triggerOnFirstLogin = false; public bool triggerOnFirstLogin = false;
public bool triggerOnLogin = false; public bool triggerOnLogin = false;
public bool triggerOnTime = false; public bool triggerOnTime = false;
@ -22,17 +21,17 @@ namespace MinecraftClient.ChatBots
public int triggerOnInterval_Interval = 0; public int triggerOnInterval_Interval = 0;
public int triggerOnInterval_Interval_Max = 0; public int triggerOnInterval_Interval_Max = 0;
public int triggerOnInterval_Interval_Countdown = 0; public int triggerOnInterval_Interval_Countdown = 0;
public List<DateTime> triggerOnTime_Times = new List<DateTime>(); public List<DateTime> triggerOnTime_Times = new();
public bool triggerOnTime_alreadyTriggered = false; public bool triggerOnTime_alreadyTriggered = false;
} }
private static bool firstlogin_done = false; private static bool firstlogin_done = false;
private string tasksfile; private readonly string tasksfile;
private bool serverlogin_done; private bool serverlogin_done;
private List<TaskDesc> tasks = new List<TaskDesc>(); private readonly List<TaskDesc> tasks = new();
private int verifytasks_timeleft = 10; private int verifytasks_timeleft = 10;
private int verifytasks_delay = 10; private readonly int verifytasks_delay = 10;
public ScriptScheduler(string tasksfile) public ScriptScheduler(string tasksfile)
{ {
@ -46,19 +45,19 @@ namespace MinecraftClient.ChatBots
if (System.IO.File.Exists(tasksfile)) if (System.IO.File.Exists(tasksfile))
{ {
LogDebugToConsoleTranslated("bot.scriptScheduler.loading", System.IO.Path.GetFullPath(tasksfile)); LogDebugToConsoleTranslated("bot.scriptScheduler.loading", System.IO.Path.GetFullPath(tasksfile));
TaskDesc current_task = null; TaskDesc? current_task = null;
String[] lines = System.IO.File.ReadAllLines(tasksfile, Encoding.UTF8); string[] lines = System.IO.File.ReadAllLines(tasksfile, Encoding.UTF8);
foreach (string lineRAW in lines) foreach (string lineRAW in lines)
{ {
string line = lineRAW.Split('#')[0].Trim(); string line = lineRAW.Split('#')[0].Trim();
if (line.Length > 0) if (line.Length > 0)
{ {
if (line[0] == '[' && line[line.Length - 1] == ']') if (line[0] == '[' && line[^1] == ']')
{ {
switch (line.Substring(1, line.Length - 2).ToLower()) switch (line[1..^1].ToLower())
{ {
case "task": case "task":
checkAddTask(current_task); CheckAddTask(current_task);
current_task = new TaskDesc(); //Create a blank task current_task = new TaskDesc(); //Create a blank task
break; break;
} }
@ -68,7 +67,7 @@ namespace MinecraftClient.ChatBots
string argName = line.Split('=')[0]; string argName = line.Split('=')[0];
if (line.Length > (argName.Length + 1)) if (line.Length > (argName.Length + 1))
{ {
string argValue = line.Substring(argName.Length + 1); string argValue = line[(argName.Length + 1)..];
switch (argName.ToLower()) switch (argName.ToLower())
{ {
case "triggeronfirstlogin": current_task.triggerOnFirstLogin = Settings.str2bool(argValue); break; case "triggeronfirstlogin": current_task.triggerOnFirstLogin = Settings.str2bool(argValue); break;
@ -77,21 +76,26 @@ namespace MinecraftClient.ChatBots
case "triggeroninterval": current_task.triggerOnInterval = Settings.str2bool(argValue); break; case "triggeroninterval": current_task.triggerOnInterval = Settings.str2bool(argValue); break;
case "timevalue": try { current_task.triggerOnTime_Times.Add(DateTime.ParseExact(argValue, "HH:mm", CultureInfo.InvariantCulture)); } catch { } break; case "timevalue": try { current_task.triggerOnTime_Times.Add(DateTime.ParseExact(argValue, "HH:mm", CultureInfo.InvariantCulture)); } catch { } break;
case "timeinterval": case "timeinterval":
int interval = 1; int interval;
int intervalMax = 0; int intervalMax = 0;
if (argValue.Contains("-")) if (argValue.Contains('-'))
{ {
string[] parts = argValue.Split("-"); string[] parts = argValue.Split("-");
if (parts.Length == 2) if (parts.Length == 2)
{ {
int.TryParse(parts[0].Trim(), out interval); interval = int.Parse(parts[0].Trim());
int.TryParse(parts[1].Trim(), out intervalMax); intervalMax = int.Parse(parts[1].Trim());
}
else
{
interval = 1;
} }
else interval = 1;
} }
else int.TryParse(argValue, out interval); else
{
interval = int.Parse(argValue);
}
current_task.triggerOnInterval_Interval = interval; current_task.triggerOnInterval_Interval = interval;
current_task.triggerOnInterval_Interval_Max = intervalMax; current_task.triggerOnInterval_Interval_Max = intervalMax;
@ -104,7 +108,7 @@ namespace MinecraftClient.ChatBots
} }
} }
} }
checkAddTask(current_task); CheckAddTask(current_task);
} }
else else
{ {
@ -113,7 +117,7 @@ namespace MinecraftClient.ChatBots
} }
} }
private void checkAddTask(TaskDesc current_task) private void CheckAddTask(TaskDesc? current_task)
{ {
//Check if we built a valid task before adding it //Check if we built a valid task before adding it
if (current_task != null) if (current_task != null)
@ -166,7 +170,7 @@ namespace MinecraftClient.ChatBots
{ {
task.triggerOnTime_alreadyTriggered = true; task.triggerOnTime_alreadyTriggered = true;
LogDebugToConsoleTranslated("bot.scriptScheduler.running_time", task.action); LogDebugToConsoleTranslated("bot.scriptScheduler.running_time", task.action);
PerformInternalCommand(task.action); PerformInternalCommand(task.action!);
} }
} }
} }
@ -186,7 +190,7 @@ namespace MinecraftClient.ChatBots
task.triggerOnInterval_Interval_Countdown = time; task.triggerOnInterval_Interval_Countdown = time;
LogDebugToConsoleTranslated("bot.scriptScheduler.running_inverval", task.action); LogDebugToConsoleTranslated("bot.scriptScheduler.running_inverval", task.action);
PerformInternalCommand(task.action); PerformInternalCommand(task.action!);
} }
else task.triggerOnInterval_Interval_Countdown--; else task.triggerOnInterval_Interval_Countdown--;
} }
@ -199,7 +203,7 @@ namespace MinecraftClient.ChatBots
if (task.triggerOnLogin || (firstlogin_done == false && task.triggerOnFirstLogin)) if (task.triggerOnLogin || (firstlogin_done == false && task.triggerOnFirstLogin))
{ {
LogDebugToConsoleTranslated("bot.scriptScheduler.running_login", task.action); LogDebugToConsoleTranslated("bot.scriptScheduler.running_login", task.action);
PerformInternalCommand(task.action); PerformInternalCommand(task.action!);
} }
} }

View file

@ -1,9 +1,4 @@
using System; namespace MinecraftClient.ChatBots
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.ChatBots
{ {
/// <summary> /// <summary>
/// Example of message receiving. /// Example of message receiving.

View file

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
namespace MinecraftClient namespace MinecraftClient
@ -50,12 +49,12 @@ namespace MinecraftClient
/// Return a list of aliases for this command. /// Return a list of aliases for this command.
/// Override this method if you wish to put aliases to the command /// Override this method if you wish to put aliases to the command
/// </summary> /// </summary>
public virtual IEnumerable<string> getCMDAliases() { return new string[0]; } public virtual IEnumerable<string> GetCMDAliases() { return Array.Empty<string>(); }
/// <summary> /// <summary>
/// Check if at least one argument has been passed to the command /// Check if at least one argument has been passed to the command
/// </summary> /// </summary>
public static bool hasArg(string command) public static bool HasArg(string command)
{ {
int first_space = command.IndexOf(' '); int first_space = command.IndexOf(' ');
return (first_space > 0 && first_space < command.Length - 1); return (first_space > 0 && first_space < command.Length - 1);
@ -65,30 +64,25 @@ namespace MinecraftClient
/// Extract the argument string from the command /// Extract the argument string from the command
/// </summary> /// </summary>
/// <returns>Argument or "" if no argument</returns> /// <returns>Argument or "" if no argument</returns>
public static string getArg(string command) public static string GetArg(string command)
{ {
if (hasArg(command)) if (HasArg(command))
{ return command[(command.IndexOf(' ') + 1)..];
return command.Substring(command.IndexOf(' ') + 1); else
} return string.Empty;
else return "";
} }
/// <summary> /// <summary>
/// Extract the arguments as a string array from the command /// Extract the arguments as a string array from the command
/// </summary> /// </summary>
/// <returns>Argument array or empty array if no arguments</returns> /// <returns>Argument array or empty array if no arguments</returns>
public static string[] getArgs(string command) public static string[] GetArgs(string command)
{ {
string[] args = getArg(command).Split(' ', StringSplitOptions.RemoveEmptyEntries); string[] args = GetArg(command).Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (args.Length == 1 && args[0] == "") if (args.Length == 1 && args[0] == string.Empty)
{ return Array.Empty<string>();
return new string[] { };
}
else else
{
return args; return args;
}
} }
/// <summary> /// <summary>
@ -97,7 +91,7 @@ namespace MinecraftClient
/// </summary> /// </summary>
/// <param name="cmdLine">Provided arguments as a string</param> /// <param name="cmdLine">Provided arguments as a string</param>
/// <returns>All extracted arguments in a string list</returns> /// <returns>All extracted arguments in a string list</returns>
public static List<string> parseCommandLine(string cmdLine) public static List<string> ParseCommandLine(string cmdLine)
{ {
var args = new List<string>(); var args = new List<string>();
if (string.IsNullOrWhiteSpace(cmdLine)) return args; if (string.IsNullOrWhiteSpace(cmdLine)) return args;
@ -107,7 +101,7 @@ namespace MinecraftClient
for (int i = 0; i < cmdLine.Length; i++) for (int i = 0; i < cmdLine.Length; i++)
{ {
if ((cmdLine[i] == '"' && i > 0 && cmdLine[i-1] != '\\') || (cmdLine[i] == '"' && i == 0)) if ((cmdLine[i] == '"' && i > 0 && cmdLine[i - 1] != '\\') || (cmdLine[i] == '"' && i == 0))
{ {
if (inQuotedArg) if (inQuotedArg)
{ {
@ -136,7 +130,7 @@ namespace MinecraftClient
{ {
if (cmdLine[i] == '\\' && cmdLine[i + 1] == '\"') if (cmdLine[i] == '\\' && cmdLine[i + 1] == '\"')
{ {
currentArg.Append("\""); currentArg.Append('"');
i += 1; i += 1;
} }
else else

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,11 +8,11 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "animation <mainhand|offhand>"; } } public override string CmdUsage { get { return "animation <mainhand|offhand>"; } }
public override string CmdDesc { get { return "cmd.animation.desc"; } } public override string CmdDesc { get { return "cmd.animation.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (hasArg(command)) if (HasArg(command))
{ {
string[] args = getArgs(command); string[] args = GetArgs(command);
if (args.Length > 0) if (args.Length > 0)
{ {
if (args[0] == "mainhand" || args[0] == "0") if (args[0] == "mainhand" || args[0] == "0")

View file

@ -12,9 +12,9 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "bed leave|sleep <x> <y> <z>|sleep <radius>"; } } public override string CmdUsage { get { return "bed leave|sleep <x> <y> <z>|sleep <radius>"; } }
public override string CmdDesc { get { return "cmd.bed.desc"; } } public override string CmdDesc { get { return "cmd.bed.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
string[] args = getArgs(command); string[] args = GetArgs(command);
if (args.Length >= 1) if (args.Length >= 1)
{ {

View file

@ -1,7 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,17 +9,17 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "changeslot <1-9>"; } } public override string CmdUsage { get { return "changeslot <1-9>"; } }
public override string CmdDesc { get { return "cmd.changeSlot.desc"; } } public override string CmdDesc { get { return "cmd.changeSlot.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (!handler.GetInventoryEnabled()) if (!handler.GetInventoryEnabled())
return Translations.Get("extra.inventory_required"); return Translations.Get("extra.inventory_required");
if (hasArg(command)) if (HasArg(command))
{ {
short slot; short slot;
try try
{ {
slot = Convert.ToInt16(getArg(command)); slot = Convert.ToInt16(GetArg(command));
} }
catch (FormatException) catch (FormatException)
{ {
@ -29,9 +27,9 @@ namespace MinecraftClient.Commands
} }
if (slot >= 1 && slot <= 9) if (slot >= 1 && slot <= 9)
{ {
if (handler.ChangeSlot(slot-=1)) if (handler.ChangeSlot(slot -= 1))
{ {
return Translations.Get("cmd.changeSlot.changed", (slot+=1)); return Translations.Get("cmd.changeSlot.changed", (slot += 1));
} }
else else
{ {

View file

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
using MinecraftClient.Mapping; using MinecraftClient.Mapping;
@ -14,9 +13,9 @@ namespace MinecraftClient.Commands
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (hasArg(command)) if (HasArg(command))
{ {
string[] args = getArgs(command); string[] args = GetArgs(command);
if (args.Length > 0) if (args.Length > 0)
{ {
if (args[0] == "status") if (args[0] == "status")
@ -29,7 +28,7 @@ namespace MinecraftClient.Commands
StringBuilder sb = new(); StringBuilder sb = new();
sb.Append(getChunkLoadingStatus(handler.GetWorld())); sb.Append(World.GetChunkLoadingStatus(handler.GetWorld()));
sb.Append('\n'); sb.Append('\n');
sb.Append(String.Format("Current location{0}, chunk: ({1}, {2}).\n", current, current.ChunkX, current.ChunkZ)); sb.Append(String.Format("Current location{0}, chunk: ({1}, {2}).\n", current, current.ChunkX, current.ChunkZ));
@ -135,7 +134,7 @@ namespace MinecraftClient.Commands
// \ud83d\udd33: 🔳, \ud83d\udfe8: 🟨, \ud83d\udfe9: 🟩, \u25A1: □, \u25A3: ▣, \u25A0: ■ // \ud83d\udd33: 🔳, \ud83d\udfe8: 🟨, \ud83d\udfe9: 🟩, \u25A1: □, \u25A3: ▣, \u25A0: ■
string[] chunkStatusStr = Settings.EnableEmoji ? string[] chunkStatusStr = Settings.EnableEmoji ?
new string[] { "\ud83d\udd33", "\ud83d\udfe8", "\ud83d\udfe9" } : new string[] { "\u25A1", "\u25A3", "\u25A0" }; new string[] { "\ud83d\udd33", "\ud83d\udfe8", "\ud83d\udfe9" } : new string[] { "\u25A1", "\u25A3", "\u25A0" };
// Output // Output
@ -177,7 +176,7 @@ namespace MinecraftClient.Commands
ChunkColumn? chunkColumn = world[chunkX, chunkZ]; ChunkColumn? chunkColumn = world[chunkX, chunkZ];
if (chunkColumn != null) if (chunkColumn != null)
chunkColumn.FullyLoaded = false; chunkColumn.FullyLoaded = false;
return (chunkColumn == null) ? "Fail: chunk dosen't exist!" : return (chunkColumn == null) ? "Fail: chunk dosen't exist!" :
String.Format("Successfully marked chunk ({0}, {1}) as loading.", chunkX, chunkZ); String.Format("Successfully marked chunk ({0}, {1}) as loading.", chunkX, chunkZ);
} }
else else
@ -194,7 +193,7 @@ namespace MinecraftClient.Commands
ChunkColumn? chunkColumn = world[chunkX, chunkZ]; ChunkColumn? chunkColumn = world[chunkX, chunkZ];
if (chunkColumn != null) if (chunkColumn != null)
chunkColumn.FullyLoaded = true; chunkColumn.FullyLoaded = true;
return (chunkColumn == null) ? "Fail: chunk dosen't exist!" : return (chunkColumn == null) ? "Fail: chunk dosen't exist!" :
String.Format("Successfully marked chunk ({0}, {1}) as loaded.", chunkX, chunkZ); String.Format("Successfully marked chunk ({0}, {1}) as loaded.", chunkX, chunkZ);
} }
else else
@ -220,11 +219,11 @@ namespace MinecraftClient.Commands
else else
return GetCmdDescTranslated(); return GetCmdDescTranslated();
} }
else else
return GetCmdDescTranslated(); return GetCmdDescTranslated();
} }
private Tuple<int, int>? ParseChunkPos(string[] args) private static Tuple<int, int>? ParseChunkPos(string[] args)
{ {
try try
{ {
@ -249,19 +248,5 @@ namespace MinecraftClient.Commands
return null; return null;
} }
} }
private string getChunkLoadingStatus(World world)
{
double chunkLoadedRatio;
if (world.chunkCnt == 0)
chunkLoadedRatio = 0;
else
chunkLoadedRatio = (world.chunkCnt - world.chunkLoadNotCompleted) / (double)world.chunkCnt;
string status = Translations.Get("cmd.move.chunk_loading_status",
chunkLoadedRatio, world.chunkCnt - world.chunkLoadNotCompleted, world.chunkCnt);
return status;
}
} }
} }

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,11 +8,11 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "connect <server> [account]"; } } public override string CmdUsage { get { return "connect <server> [account]"; } }
public override string CmdDesc { get { return "cmd.connect.desc"; } } public override string CmdDesc { get { return "cmd.connect.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient? handler, string command, Dictionary<string, object>? localVars)
{ {
if (hasArg(command)) if (HasArg(command))
{ {
string[] args = getArgs(command); string[] args = GetArgs(command);
if (args.Length > 1) if (args.Length > 1)
{ {
if (!Settings.SetAccount(args[1])) if (!Settings.SetAccount(args[1]))

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,11 +8,11 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "debug [on|off]"; } } public override string CmdUsage { get { return "debug [on|off]"; } }
public override string CmdDesc { get { return "cmd.debug.desc"; } } public override string CmdDesc { get { return "cmd.debug.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (hasArg(command)) if (HasArg(command))
{ {
Settings.DebugMessages = (getArg(command).ToLower() == "on"); Settings.DebugMessages = (GetArg(command).ToLower() == "on");
} }
else Settings.DebugMessages = !Settings.DebugMessages; else Settings.DebugMessages = !Settings.DebugMessages;
return Translations.Get(Settings.DebugMessages ? "cmd.debug.state_on" : "cmd.debug.state_off"); return Translations.Get(Settings.DebugMessages ? "cmd.debug.state_on" : "cmd.debug.state_off");

View file

@ -1,7 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using MinecraftClient.Mapping; using MinecraftClient.Mapping;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
@ -12,12 +10,12 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "dig <x> <y> <z>"; } } public override string CmdUsage { get { return "dig <x> <y> <z>"; } }
public override string CmdDesc { get { return "cmd.dig.desc"; } } public override string CmdDesc { get { return "cmd.dig.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (!handler.GetTerrainEnabled()) if (!handler.GetTerrainEnabled())
return Translations.Get("extra.terrainandmovement_required"); return Translations.Get("extra.terrainandmovement_required");
string[] args = getArgs(command); string[] args = GetArgs(command);
if (args.Length == 0) if (args.Length == 0)
{ {
(bool hasBlock, Location blockLoc, Block block) = RaycastHelper.RaycastBlock(handler, 4.5, false); (bool hasBlock, Location blockLoc, Block block) = RaycastHelper.RaycastBlock(handler, 4.5, false);

View file

@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using MinecraftClient.Inventory; using MinecraftClient.Inventory;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
@ -14,17 +13,16 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "/dropitem <itemtype>"; } } public override string CmdUsage { get { return "/dropitem <itemtype>"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (!handler.GetInventoryEnabled()) if (!handler.GetInventoryEnabled())
{ {
return Translations.Get("extra.inventory_required"); return Translations.Get("extra.inventory_required");
} }
if (hasArg(command)) if (HasArg(command))
{ {
string arg = getArg(command); string arg = GetArg(command);
ItemType itemType; if (Enum.TryParse(arg, true, out ItemType itemType))
if (Enum.TryParse(arg, true, out itemType))
{ {
int inventoryId; int inventoryId;
var inventories = handler.GetInventories(); var inventories = handler.GetInventories();

View file

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing;
using MinecraftClient.Inventory; using MinecraftClient.Inventory;
using MinecraftClient.Mapping; using MinecraftClient.Mapping;
@ -12,17 +11,16 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "entity <id|entitytype> <attack|use>"; } } public override string CmdUsage { get { return "entity <id|entitytype> <attack|use>"; } }
public override string CmdDesc { get { return ""; } } public override string CmdDesc { get { return ""; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (handler.GetEntityHandlingEnabled()) if (handler.GetEntityHandlingEnabled())
{ {
string[] args = getArgs(command); string[] args = GetArgs(command);
if (args.Length >= 1) if (args.Length >= 1)
{ {
try try
{ {
int entityID = 0; int entityID = int.Parse(args[0]);
int.TryParse(args[0], out entityID);
if (entityID != 0) if (entityID != 0)
{ {
if (handler.GetEntities().ContainsKey(entityID)) if (handler.GetEntities().ContainsKey(entityID))
@ -44,8 +42,8 @@ namespace MinecraftClient.Commands
float health = entity.Health; float health = entity.Health;
int latency = entity.Latency; int latency = entity.Latency;
Item item = entity.Item; Item item = entity.Item;
string nickname = entity.Name; string? nickname = entity.Name;
string customname = entity.CustomName; string? customname = entity.CustomName;
EntityPose pose = entity.Pose; EntityPose pose = entity.Pose;
EntityType type = entity.Type; EntityType type = entity.Type;
double distance = Math.Round(entity.Location.Distance(handler.GetCurrentLocation()), 2); double distance = Math.Round(entity.Location.Distance(handler.GetCurrentLocation()), 2);
@ -66,7 +64,7 @@ namespace MinecraftClient.Commands
done += Translations.Replace("\n [MCC] ([cmd.entityCmd.latency]): {0}", latency); done += Translations.Replace("\n [MCC] ([cmd.entityCmd.latency]): {0}", latency);
else if (type == EntityType.Item || type == EntityType.ItemFrame || type == Mapping.EntityType.EyeOfEnder || type == Mapping.EntityType.Egg || type == Mapping.EntityType.EnderPearl || type == Mapping.EntityType.Potion || type == Mapping.EntityType.Fireball || type == Mapping.EntityType.FireworkRocket) else if (type == EntityType.Item || type == EntityType.ItemFrame || type == Mapping.EntityType.EyeOfEnder || type == Mapping.EntityType.Egg || type == Mapping.EntityType.EnderPearl || type == Mapping.EntityType.Potion || type == Mapping.EntityType.Fireball || type == Mapping.EntityType.FireworkRocket)
{ {
string displayName = item.DisplayName; string? displayName = item.DisplayName;
if (String.IsNullOrEmpty(displayName)) if (String.IsNullOrEmpty(displayName))
done += Translations.Replace("\n [MCC] ([cmd.entityCmd.item]): {0} x{1}", item.Type, item.Count); done += Translations.Replace("\n [MCC] ([cmd.entityCmd.item]): {0} x{1}", item.Type, item.Count);
else else
@ -100,8 +98,7 @@ namespace MinecraftClient.Commands
} }
else else
{ {
EntityType interacttype = EntityType.Player; EntityType interacttype = Enum.Parse<EntityType>(args[0]);
Enum.TryParse(args[0], out interacttype);
string actionst = "cmd.entityCmd.attacked"; string actionst = "cmd.entityCmd.attacked";
int actioncount = 0; int actioncount = 0;
foreach (var entity2 in handler.GetEntities()) foreach (var entity2 in handler.GetEntities())
@ -134,15 +131,17 @@ namespace MinecraftClient.Commands
else else
{ {
Dictionary<int, Entity> entities = handler.GetEntities(); Dictionary<int, Entity> entities = handler.GetEntities();
List<string> response = new List<string>(); List<string> response = new()
response.Add(Translations.Get("cmd.entityCmd.entities")); {
Translations.Get("cmd.entityCmd.entities")
};
foreach (var entity2 in entities) foreach (var entity2 in entities)
{ {
int id = entity2.Key; int id = entity2.Key;
float health = entity2.Value.Health; float health = entity2.Value.Health;
int latency = entity2.Value.Latency; int latency = entity2.Value.Latency;
string nickname = entity2.Value.Name; string? nickname = entity2.Value.Name;
string customname = entity2.Value.CustomName; string? customname = entity2.Value.CustomName;
EntityPose pose = entity2.Value.Pose; EntityPose pose = entity2.Value.Pose;
EntityType type = entity2.Value.Type; EntityType type = entity2.Value.Type;
Item item = entity2.Value.Item; Item item = entity2.Value.Item;

View file

@ -11,11 +11,11 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "execif <condition/expression> ---> <command>"; } } public override string CmdUsage { get { return "execif <condition/expression> ---> <command>"; } }
public override string CmdDesc { get { return "cmd.execif.desc"; } } public override string CmdDesc { get { return "cmd.execif.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (hasArg(command)) if (HasArg(command))
{ {
string commandsString = getArg(command); string commandsString = GetArg(command);
if (!commandsString.Contains("--->")) if (!commandsString.Contains("--->"))
return GetCmdDescTranslated(); return GetCmdDescTranslated();
@ -41,44 +41,41 @@ namespace MinecraftClient.Commands
var result = interpreter.Eval<bool>(expressionText); var result = interpreter.Eval<bool>(expressionText);
if (result != null) bool shouldExec = result;
/*if (result is bool)
shouldExec = (bool)result;
else if (result is string)
shouldExec = !string.IsNullOrEmpty((string)result) && ((string)result).Trim().Contains("true", StringComparison.OrdinalIgnoreCase);
else if (result is int)
shouldExec = (int)result > 0;
else if (result is double)
shouldExec = (double)result > 0;
else if (result is float)
shouldExec = (float)result > 0;
else if (result is Int16)
shouldExec = (Int16)result > 0;
else if (result is Int32)
shouldExec = (Int32)result > 0;
else if (result is Int64)
shouldExec = (Int64)result > 0;
*/
handler.Log.Debug("[Execif] Result Type: " + result.GetType().Name);
if (shouldExec)
{ {
bool shouldExec = result; string? output = "";
handler.PerformInternalCommand(resultCommand, ref output);
/*if (result is bool) if (string.IsNullOrEmpty(output))
shouldExec = (bool)result; handler.Log.Debug(Translations.TryGet("cmd.execif.executed_no_output", expressionText, resultCommand));
else if (result is string) else handler.Log.Debug(Translations.TryGet("cmd.execif.executed", expressionText, resultCommand, output));
shouldExec = !string.IsNullOrEmpty((string)result) && ((string)result).Trim().Contains("true", StringComparison.OrdinalIgnoreCase);
else if (result is int)
shouldExec = (int)result > 0;
else if (result is double)
shouldExec = (double)result > 0;
else if (result is float)
shouldExec = (float)result > 0;
else if (result is Int16)
shouldExec = (Int16)result > 0;
else if (result is Int32)
shouldExec = (Int32)result > 0;
else if (result is Int64)
shouldExec = (Int64)result > 0;
*/
handler.Log.Debug("[Execif] Result Type: " + result.GetType().Name);
if (shouldExec)
{
string output = "";
handler.PerformInternalCommand(resultCommand, ref output);
if (string.IsNullOrEmpty(output))
handler.Log.Debug(Translations.TryGet("cmd.execif.executed_no_output", expressionText, resultCommand));
else handler.Log.Debug(Translations.TryGet("cmd.execif.executed", expressionText, resultCommand, output));
return "";
}
return ""; return "";
} }
return "";
} }
catch (Exception e) catch (Exception e)
{ {
@ -86,8 +83,6 @@ namespace MinecraftClient.Commands
handler.Log.Error(Translations.TryGet("cmd.execif.error", e.Message)); handler.Log.Error(Translations.TryGet("cmd.execif.error", e.Message));
return ""; return "";
} }
return GetCmdDescTranslated();
} }
return GetCmdDescTranslated(); return GetCmdDescTranslated();

View file

@ -10,11 +10,11 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "execmulti <command 1> -> <command2> -> <command 3> -> ..."; } } public override string CmdUsage { get { return "execmulti <command 1> -> <command2> -> <command 3> -> ..."; } }
public override string CmdDesc { get { return "cmd.execmulti.desc"; } } public override string CmdDesc { get { return "cmd.execmulti.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (hasArg(command)) if (HasArg(command))
{ {
string commandsString = getArg(command); string commandsString = GetArg(command);
if (commandsString.Contains("execmulti", StringComparison.OrdinalIgnoreCase) || commandsString.Contains("execif", StringComparison.OrdinalIgnoreCase)) if (commandsString.Contains("execmulti", StringComparison.OrdinalIgnoreCase) || commandsString.Contains("execif", StringComparison.OrdinalIgnoreCase))
return Translations.TryGet("cmd.execmulti.prevent"); return Translations.TryGet("cmd.execmulti.prevent");
@ -25,16 +25,17 @@ namespace MinecraftClient.Commands
foreach (string cmd in commands) foreach (string cmd in commands)
{ {
string output = ""; string? output = "";
handler.PerformInternalCommand(cmd, ref output); handler.PerformInternalCommand(cmd, ref output);
string log = Translations.TryGet( string log = Translations.TryGet(
"cmd.execmulti.executed", cmd, "cmd.execmulti.executed", cmd,
string.IsNullOrEmpty(output) ? Translations.TryGet("cmd.execmulti.no_result") : Translations.TryGet("cmd.execmulti.result", output)); string.IsNullOrEmpty(output) ? Translations.TryGet("cmd.execmulti.no_result") : Translations.TryGet("cmd.execmulti.result", output));
if (output.Contains("unknown command", StringComparison.OrdinalIgnoreCase)) if (output != null && output.Contains("unknown command", StringComparison.OrdinalIgnoreCase))
handler.Log.Error(log); handler.Log.Error(log);
else handler.Log.Info(log); else
handler.Log.Info(log);
} }
return ""; return "";

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,13 +8,13 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "exit"; } } public override string CmdUsage { get { return "exit"; } }
public override string CmdDesc { get { return "cmd.exit.desc"; } } public override string CmdDesc { get { return "cmd.exit.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient? handler, string command, Dictionary<string, object>? localVars)
{ {
Program.Exit(); Program.Exit();
return ""; return "";
} }
public override IEnumerable<string> getCMDAliases() public override IEnumerable<string> GetCMDAliases()
{ {
return new string[] { "quit" }; return new string[] { "quit" };
} }

View file

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,7 +8,7 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "health"; } } public override string CmdUsage { get { return "health"; } }
public override string CmdDesc { get { return "cmd.health.desc"; } } public override string CmdDesc { get { return "cmd.health.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
return Translations.Get("cmd.health.response", handler.GetHealth(), handler.GetSaturation(), handler.GetLevel(), handler.GetTotalExperience()); return Translations.Get("cmd.health.response", handler.GetHealth(), handler.GetSaturation(), handler.GetLevel(), handler.GetTotalExperience());
} }

View file

@ -16,7 +16,7 @@ namespace MinecraftClient.Commands
{ {
if (handler.GetInventoryEnabled()) if (handler.GetInventoryEnabled())
{ {
string[] args = getArgs(command); string[] args = GetArgs(command);
if (args.Length >= 1) if (args.Length >= 1)
{ {
int inventoryId; int inventoryId;
@ -117,7 +117,7 @@ namespace MinecraftClient.Commands
{ {
inventory.Items.Values inventory.Items.Values
.ToList() .ToList()
.FindAll(item => item.Type == parsedItemType && (shouldUseItemCount ? item.Count == itemCount : true)) .FindAll(item => item.Type == parsedItemType && (!shouldUseItemCount || item.Count == itemCount))
.ForEach(item => .ForEach(item =>
{ {
if (!foundItems.ContainsKey(inventory.ID)) if (!foundItems.ContainsKey(inventory.ID))
@ -183,7 +183,7 @@ namespace MinecraftClient.Commands
response.Append(Translations.Get("cmd.inventory.inventory")); response.Append(Translations.Get("cmd.inventory.inventory"));
response.AppendLine(String.Format(" #{0} - {1}§8", inventoryId, inventory.Title)); response.AppendLine(String.Format(" #{0} - {1}§8", inventoryId, inventory.Title));
string asciiArt = inventory.Type.GetAsciiArt(); string? asciiArt = inventory.Type.GetAsciiArt();
if (asciiArt != null && Settings.DisplayInventoryLayout) if (asciiArt != null && Settings.DisplayInventoryLayout)
response.AppendLine(asciiArt); response.AppendLine(asciiArt);

View file

@ -1,7 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,7 +9,7 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "list"; } } public override string CmdUsage { get { return "list"; } }
public override string CmdDesc { get { return "cmd.list.desc"; } } public override string CmdDesc { get { return "cmd.list.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
return Translations.Get("cmd.list.players", String.Join(", ", handler.GetOnlinePlayers())); return Translations.Get("cmd.list.players", String.Join(", ", handler.GetOnlinePlayers()));
} }

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,11 +8,11 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "log <text>"; } } public override string CmdUsage { get { return "log <text>"; } }
public override string CmdDesc { get { return "cmd.log.desc"; } } public override string CmdDesc { get { return "cmd.log.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (hasArg(command)) if (HasArg(command))
{ {
ConsoleIO.WriteLogLine(getArg(command)); ConsoleIO.WriteLogLine(GetArg(command));
return ""; return "";
} }
else return GetCmdDescTranslated(); else return GetCmdDescTranslated();

View file

@ -1,8 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using MinecraftClient.Mapping; using MinecraftClient.Mapping;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
@ -13,11 +10,11 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "look <x y z|yaw pitch|up|down|east|west|north|south>"; } } public override string CmdUsage { get { return "look <x y z|yaw pitch|up|down|east|west|north|south>"; } }
public override string CmdDesc { get { return "cmd.look.desc"; } } public override string CmdDesc { get { return "cmd.look.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (handler.GetTerrainEnabled()) if (handler.GetTerrainEnabled())
{ {
string[] args = getArgs(command); string[] args = GetArgs(command);
if (args.Length == 0) if (args.Length == 0)
{ {
const double maxDistance = 8.0; const double maxDistance = 8.0;
@ -33,7 +30,7 @@ namespace MinecraftClient.Commands
} }
else if (args.Length == 1) else if (args.Length == 1)
{ {
string dirStr = getArg(command).Trim().ToLower(); string dirStr = GetArg(command).Trim().ToLower();
Direction direction; Direction direction;
switch (dirStr) switch (dirStr)
{ {
@ -53,8 +50,8 @@ namespace MinecraftClient.Commands
{ {
try try
{ {
float yaw = Single.Parse(args[0]); float yaw = float.Parse(args[0]);
float pitch = Single.Parse(args[1]); float pitch = float.Parse(args[1]);
handler.UpdateLocation(handler.GetCurrentLocation(), yaw, pitch); handler.UpdateLocation(handler.GetCurrentLocation(), yaw, pitch);
return Translations.Get("cmd.look.at", yaw.ToString("0.00"), pitch.ToString("0.00")); return Translations.Get("cmd.look.at", yaw.ToString("0.00"), pitch.ToString("0.00"));

View file

@ -11,9 +11,9 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "move <on|off|get|up|down|east|west|north|south|center|x y z|gravity [on|off]> [-f]"; } } public override string CmdUsage { get { return "move <on|off|get|up|down|east|west|north|south|center|x y z|gravity [on|off]> [-f]"; } }
public override string CmdDesc { get { return "walk or start walking. \"-f\": force unsafe movements like falling or touching fire"; } } public override string CmdDesc { get { return "walk or start walking. \"-f\": force unsafe movements like falling or touching fire"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
List<string> args = getArgs(command.ToLower()).ToList(); List<string> args = GetArgs(command.ToLower()).ToList();
bool takeRisk = false; bool takeRisk = false;
if (args.Count < 1) if (args.Count < 1)
@ -21,7 +21,7 @@ namespace MinecraftClient.Commands
string desc = GetCmdDescTranslated(); string desc = GetCmdDescTranslated();
if (handler.GetTerrainEnabled()) if (handler.GetTerrainEnabled())
handler.Log.Info(getChunkLoadingStatus(handler.GetWorld())); handler.Log.Info(World.GetChunkLoadingStatus(handler.GetWorld()));
return desc; return desc;
} }
@ -65,7 +65,7 @@ namespace MinecraftClient.Commands
case "south": direction = Direction.South; break; case "south": direction = Direction.South; break;
case "center": case "center":
Location current = handler.GetCurrentLocation(); Location current = handler.GetCurrentLocation();
Location currentCenter = new Location(Math.Floor(current.X) + 0.5, current.Y, Math.Floor(current.Z) + 0.5); Location currentCenter = new(Math.Floor(current.X) + 0.5, current.Y, Math.Floor(current.Z) + 0.5);
handler.MoveTo(currentCenter, allowDirectTeleport: true); handler.MoveTo(currentCenter, allowDirectTeleport: true);
return Translations.Get("cmd.move.walk", currentCenter, current); return Translations.Get("cmd.move.walk", currentCenter, current);
case "get": return handler.GetCurrentLocation().ToString(); case "get": return handler.GetCurrentLocation().ToString();
@ -81,7 +81,7 @@ namespace MinecraftClient.Commands
{ {
if (handler.MoveTo(goal, allowUnsafe: takeRisk)) if (handler.MoveTo(goal, allowUnsafe: takeRisk))
return Translations.Get("cmd.move.moving", args[0]); return Translations.Get("cmd.move.moving", args[0]);
else else
return takeRisk ? Translations.Get("cmd.move.dir_fail") : Translations.Get("cmd.move.suggestforce"); return takeRisk ? Translations.Get("cmd.move.dir_fail") : Translations.Get("cmd.move.suggestforce");
} }
else return Translations.Get("cmd.move.dir_fail"); else return Translations.Get("cmd.move.dir_fail");
@ -113,19 +113,5 @@ namespace MinecraftClient.Commands
} }
else return Translations.Get("extra.terrainandmovement_required"); else return Translations.Get("extra.terrainandmovement_required");
} }
private string getChunkLoadingStatus(World world)
{
double chunkLoadedRatio;
if (world.chunkCnt == 0)
chunkLoadedRatio = 0;
else
chunkLoadedRatio = (world.chunkCnt - world.chunkLoadNotCompleted) / (double)world.chunkCnt;
string status = Translations.Get("cmd.move.chunk_loading_status",
chunkLoadedRatio, world.chunkCnt - world.chunkLoadNotCompleted, world.chunkCnt);
return status;
}
} }
} }

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,9 +8,9 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "reco [account]"; } } public override string CmdUsage { get { return "reco [account]"; } }
public override string CmdDesc { get { return "cmd.reco.desc"; } } public override string CmdDesc { get { return "cmd.reco.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient? handler, string command, Dictionary<string, object>? localVars)
{ {
string[] args = getArgs(command); string[] args = GetArgs(command);
if (args.Length > 0) if (args.Length > 0)
{ {
if (!Settings.SetAccount(args[0])) if (!Settings.SetAccount(args[0]))

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,7 +8,7 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "respawn"; } } public override string CmdUsage { get { return "respawn"; } }
public override string CmdDesc { get { return "cmd.respawn.desc"; } } public override string CmdDesc { get { return "cmd.respawn.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
handler.SendRespawnPacket(); handler.SendRespawnPacket();
return Translations.Get("cmd.respawn.done"); return Translations.Get("cmd.respawn.done");

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,11 +8,11 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "script <scriptname>"; } } public override string CmdUsage { get { return "script <scriptname>"; } }
public override string CmdDesc { get { return "cmd.script.desc"; } } public override string CmdDesc { get { return "cmd.script.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (hasArg(command)) if (HasArg(command))
{ {
handler.BotLoad(new ChatBots.Script(getArg(command), null, localVars)); handler.BotLoad(new ChatBots.Script(GetArg(command), null, localVars));
return ""; return "";
} }
else return GetCmdDescTranslated(); else return GetCmdDescTranslated();

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,11 +8,11 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "send <text>"; } } public override string CmdUsage { get { return "send <text>"; } }
public override string CmdDesc { get { return "cmd.send.desc"; } } public override string CmdDesc { get { return "cmd.send.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (hasArg(command)) if (HasArg(command))
{ {
handler.SendText(getArg(command)); handler.SendText(GetArg(command));
return ""; return "";
} }
else return GetCmdDescTranslated(); else return GetCmdDescTranslated();

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,14 +8,14 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "set varname=value"; } } public override string CmdUsage { get { return "set varname=value"; } }
public override string CmdDesc { get { return "cmd.set.desc"; } } public override string CmdDesc { get { return "cmd.set.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (hasArg(command)) if (HasArg(command))
{ {
string[] temp = getArg(command).Split('='); string[] temp = GetArg(command).Split('=');
if (temp.Length > 1) if (temp.Length > 1)
{ {
if (Settings.SetVar(temp[0], getArg(command).Substring(temp[0].Length + 1))) if (Settings.SetVar(temp[0], GetArg(command).Substring(temp[0].Length + 1)))
{ {
return ""; //Success return ""; //Success
} }

View file

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -9,16 +8,16 @@ namespace MinecraftClient.Commands
public override string CmdName { get { return "setrnd"; } } public override string CmdName { get { return "setrnd"; } }
public override string CmdUsage { get { return Translations.Get("cmd.setrnd.format"); } } public override string CmdUsage { get { return Translations.Get("cmd.setrnd.format"); } }
public override string CmdDesc { get { return "cmd.setrnd.desc"; } } public override string CmdDesc { get { return "cmd.setrnd.desc"; } }
private static readonly Random rand = new Random(); private static readonly Random rand = new();
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (hasArg(command)) if (HasArg(command))
{ {
string[] args = getArg(command).Split(' '); string[] args = GetArg(command).Split(' ');
if (args.Length > 1) if (args.Length > 1)
{ {
// detect "to" keyword in string // detect "to" keyword in string
if (args.Length == 2 && args[1].Contains("to")) if (args.Length == 2 && args[1].Contains("to"))
{ {
@ -28,7 +27,7 @@ namespace MinecraftClient.Commands
// try to extract the two numbers from the string // try to extract the two numbers from the string
try try
{ {
num1 = Convert.ToInt32(args[1].Substring(0, args[1].IndexOf('t'))); num1 = Convert.ToInt32(args[1][..args[1].IndexOf('t')]);
num2 = Convert.ToInt32(args[1].Substring(args[1].IndexOf('o') + 1, args[1].Length - 1 - args[1].IndexOf('o'))); num2 = Convert.ToInt32(args[1].Substring(args[1].IndexOf('o') + 1, args[1].Length - 1 - args[1].IndexOf('o')));
} }
catch (Exception) catch (Exception)
@ -38,11 +37,7 @@ namespace MinecraftClient.Commands
// switch the values if they were entered in the wrong way // switch the values if they were entered in the wrong way
if (num2 < num1) if (num2 < num1)
{ (num2, num1) = (num1, num2);
int temp = num1;
num1 = num2;
num2 = temp;
}
// create a variable or set it to num1 <= varlue < num2 // create a variable or set it to num1 <= varlue < num2
if (Settings.SetVar(args[0], rand.Next(num1, num2))) if (Settings.SetVar(args[0], rand.Next(num1, num2)))
@ -54,10 +49,10 @@ namespace MinecraftClient.Commands
else else
{ {
// extract all arguments of the command // extract all arguments of the command
string argString = command.Substring(8 + command.Split(' ')[1].Length); string argString = command[(8 + command.Split(' ')[1].Length)..];
// process all arguments similar to regular terminals with quotes and escaping // process all arguments similar to regular terminals with quotes and escaping
List<string> values = parseCommandLine(argString); List<string> values = ParseCommandLine(argString);
// create a variable or set it to one of the values // create a variable or set it to one of the values
if (values.Count > 0 && Settings.SetVar(args[0], values[rand.Next(0, values.Count)])) if (values.Count > 0 && Settings.SetVar(args[0], values[rand.Next(0, values.Count)]))

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -12,14 +9,14 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "Sneak"; } } public override string CmdUsage { get { return "Sneak"; } }
public override string CmdDesc { get { return "cmd.sneak.desc"; } } public override string CmdDesc { get { return "cmd.sneak.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (sneaking) if (sneaking)
{ {
var result = handler.SendEntityAction(Protocol.EntityActionType.StopSneaking); var result = handler.SendEntityAction(Protocol.EntityActionType.StopSneaking);
if (result) if (result)
sneaking = false; sneaking = false;
return Translations.Get(result ? "cmd.sneak.off" : "general.fail"); return Translations.Get(result ? "cmd.sneak.off" : "general.fail");
} }
else else
{ {
@ -28,7 +25,6 @@ namespace MinecraftClient.Commands
sneaking = true; sneaking = true;
return Translations.Get(result ? "cmd.sneak.on" : "general.fail"); return Translations.Get(result ? "cmd.sneak.on" : "general.fail");
} }
} }
} }
} }

View file

@ -1,7 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,7 +9,7 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "tps"; } } public override string CmdUsage { get { return "tps"; } }
public override string CmdDesc { get { return "cmd.tps.desc"; } } public override string CmdDesc { get { return "cmd.tps.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
var tps = Math.Round(handler.GetServerTPS(), 2); var tps = Math.Round(handler.GetServerTPS(), 2);
string color; string color;
@ -19,7 +17,8 @@ namespace MinecraftClient.Commands
color = "§c"; // Red color = "§c"; // Red
else if (tps < 15) else if (tps < 15)
color = "§e"; // Yellow color = "§e"; // Yellow
else color = "§a"; // Green else
color = "§a"; // Green
return Translations.Get("cmd.tps.current") + ": " + color + tps; return Translations.Get("cmd.tps.current") + ": " + color + tps;
} }
} }

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -11,7 +8,7 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "useitem"; } } public override string CmdUsage { get { return "useitem"; } }
public override string CmdDesc { get { return "cmd.useitem.desc"; } } public override string CmdDesc { get { return "cmd.useitem.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars) public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{ {
if (handler.GetInventoryEnabled()) if (handler.GetInventoryEnabled())
{ {

View file

@ -1,8 +1,5 @@
using MinecraftClient.Mapping;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using MinecraftClient.Mapping;
using System.Text;
namespace MinecraftClient.Commands namespace MinecraftClient.Commands
{ {
@ -16,9 +13,9 @@ namespace MinecraftClient.Commands
{ {
if (!handler.GetTerrainEnabled()) if (!handler.GetTerrainEnabled())
return Translations.Get("extra.terrainandmovement_required"); return Translations.Get("extra.terrainandmovement_required");
else if (hasArg(command)) else if (HasArg(command))
{ {
string[] args = getArgs(command); string[] args = GetArgs(command);
if (args.Length >= 3) if (args.Length >= 3)
{ {
Location block = Location.Parse(handler.GetCurrentLocation(), args[0], args[1], args[2]).ToFloor(); Location block = Location.Parse(handler.GetCurrentLocation(), args[0], args[1], args[2]).ToFloor();

View file

@ -1,8 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
using System.Threading;
namespace MinecraftClient namespace MinecraftClient
{ {
@ -14,7 +12,7 @@ namespace MinecraftClient
/// </summary> /// </summary>
public static class ConsoleIO public static class ConsoleIO
{ {
private static IAutoComplete autocomplete_engine; private static IAutoComplete? autocomplete_engine;
/// <summary> /// <summary>
/// Reset the IO mechanism and clear all buffers /// Reset the IO mechanism and clear all buffers
@ -77,8 +75,8 @@ namespace MinecraftClient
public static string ReadLine() public static string ReadLine()
{ {
if (BasicIO) if (BasicIO)
return Console.ReadLine(); return Console.ReadLine() ?? String.Empty;
else else
return ConsoleInteractive.ConsoleReader.RequestImmediateInput(); return ConsoleInteractive.ConsoleReader.RequestImmediateInput();
} }
@ -87,7 +85,7 @@ namespace MinecraftClient
/// </summary> /// </summary>
public static void DebugReadInput() public static void DebugReadInput()
{ {
ConsoleKeyInfo k = new ConsoleKeyInfo(); ConsoleKeyInfo k;
while (true) while (true)
{ {
k = Console.ReadKey(true); k = Console.ReadKey(true);
@ -119,14 +117,11 @@ namespace MinecraftClient
/// </param> /// </param>
public static void WriteLineFormatted(string str, bool acceptnewlines = false, bool? displayTimestamp = null) public static void WriteLineFormatted(string str, bool acceptnewlines = false, bool? displayTimestamp = null)
{ {
StringBuilder output = new StringBuilder(); StringBuilder output = new();
if (!String.IsNullOrEmpty(str)) if (!String.IsNullOrEmpty(str))
{ {
if (displayTimestamp == null) displayTimestamp ??= EnableTimestamps;
{
displayTimestamp = EnableTimestamps;
}
if (displayTimestamp.Value) if (displayTimestamp.Value)
{ {
int hour = DateTime.Now.Hour, minute = DateTime.Now.Minute, second = DateTime.Now.Second; int hour = DateTime.Now.Hour, minute = DateTime.Now.Minute, second = DateTime.Now.Second;
@ -183,10 +178,10 @@ namespace MinecraftClient
public static void AutocompleteHandler(object? sender, ConsoleKey e) public static void AutocompleteHandler(object? sender, ConsoleKey e)
{ {
if (e != ConsoleKey.Tab) return; if (e != ConsoleKey.Tab) return;
if (autocomplete_engine == null) if (autocomplete_engine == null)
return; return;
var buffer = ConsoleInteractive.ConsoleReader.GetBufferContent(); var buffer = ConsoleInteractive.ConsoleReader.GetBufferContent();
autocomplete_engine.AutoComplete(buffer.Text[..buffer.CursorPosition]); autocomplete_engine.AutoComplete(buffer.Text[..buffer.CursorPosition]);
} }

View file

@ -1,12 +1,9 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.IO;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Threading.Tasks;
namespace MinecraftClient.Crypto namespace MinecraftClient.Crypto
{ {
@ -19,8 +16,8 @@ namespace MinecraftClient.Crypto
private bool inStreamEnded = false; private bool inStreamEnded = false;
private byte[] ReadStreamIV = new byte[16]; private readonly byte[] ReadStreamIV = new byte[16];
private byte[] WriteStreamIV = new byte[16]; private readonly byte[] WriteStreamIV = new byte[16];
public Stream BaseStream { get; set; } public Stream BaseStream { get; set; }

View file

@ -1,9 +1,7 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.IO; using System.Text;
namespace MinecraftClient.Crypto namespace MinecraftClient.Crypto
{ {
@ -13,7 +11,7 @@ namespace MinecraftClient.Crypto
public static class CryptoHandler public static class CryptoHandler
{ {
public static byte[]? ClientAESPrivateKey = null; public static byte[]? ClientAESPrivateKey;
/// <summary> /// <summary>
/// Get a cryptographic service for encrypting data using the server's RSA public key /// Get a cryptographic service for encrypting data using the server's RSA public key
@ -21,21 +19,21 @@ namespace MinecraftClient.Crypto
/// <param name="x509key">Byte array containing the encoded key</param> /// <param name="x509key">Byte array containing the encoded key</param>
/// <returns>Returns the corresponding RSA Crypto Service</returns> /// <returns>Returns the corresponding RSA Crypto Service</returns>
public static RSACryptoServiceProvider DecodeRSAPublicKey(byte[] x509key) public static RSACryptoServiceProvider? DecodeRSAPublicKey(byte[] x509key)
{ {
/* Code from StackOverflow no. 18091460 */ /* Code from StackOverflow no. 18091460 */
byte[] SeqOID = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 }; byte[] SeqOID = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 };
System.IO.MemoryStream ms = new System.IO.MemoryStream(x509key); System.IO.MemoryStream ms = new(x509key);
System.IO.BinaryReader reader = new System.IO.BinaryReader(ms); System.IO.BinaryReader reader = new(ms);
if (reader.ReadByte() == 0x30) if (reader.ReadByte() == 0x30)
ReadASNLength(reader); //skip the size ReadASNLength(reader); //skip the size
else else
return null; return null;
int identifierSize = 0; //total length of Object Identifier section int identifierSize; //total length of Object Identifier section
if (reader.ReadByte() == 0x30) if (reader.ReadByte() == 0x30)
identifierSize = ReadASNLength(reader); identifierSize = ReadASNLength(reader);
else else
@ -78,10 +76,12 @@ namespace MinecraftClient.Crypto
byte[] exponent = new byte[exponentSize]; byte[] exponent = new byte[exponentSize];
reader.Read(exponent, 0, exponent.Length); reader.Read(exponent, 0, exponent.Length);
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSACryptoServiceProvider RSA = new();
RSAParameters RSAKeyInfo = new RSAParameters(); RSAParameters RSAKeyInfo = new()
RSAKeyInfo.Modulus = modulus; {
RSAKeyInfo.Exponent = exponent; Modulus = modulus,
Exponent = exponent
};
RSA.ImportParameters(RSAKeyInfo); RSA.ImportParameters(RSAKeyInfo);
return RSA; return RSA;
} }
@ -120,8 +120,9 @@ namespace MinecraftClient.Crypto
public static byte[] GenerateAESPrivateKey() public static byte[] GenerateAESPrivateKey()
{ {
AesManaged AES = new AesManaged(); Aes AES = Aes.Create();
AES.KeySize = 128; AES.GenerateKey(); AES.KeySize = 128;
AES.GenerateKey();
return AES.Key; return AES.Key;
} }
@ -133,9 +134,9 @@ namespace MinecraftClient.Crypto
/// <param name="SecretKey">Secret key chosen by the client</param> /// <param name="SecretKey">Secret key chosen by the client</param>
/// <returns>Returns the corresponding SHA-1 hex hash</returns> /// <returns>Returns the corresponding SHA-1 hex hash</returns>
public static string getServerHash(string serverID, byte[] PublicKey, byte[] SecretKey) public static string GetServerHash(string serverID, byte[] PublicKey, byte[] SecretKey)
{ {
byte[] hash = digest(new byte[][] { Encoding.GetEncoding("iso-8859-1").GetBytes(serverID), SecretKey, PublicKey }); byte[] hash = Digest(new byte[][] { Encoding.GetEncoding("iso-8859-1").GetBytes(serverID), SecretKey, PublicKey });
bool negative = (hash[0] & 0x80) == 0x80; bool negative = (hash[0] & 0x80) == 0x80;
if (negative) { hash = TwosComplementLittleEndian(hash); } if (negative) { hash = TwosComplementLittleEndian(hash); }
string result = GetHexString(hash).TrimStart('0'); string result = GetHexString(hash).TrimStart('0');
@ -149,13 +150,13 @@ namespace MinecraftClient.Crypto
/// <param name="tohash">array of byte arrays to hash</param> /// <param name="tohash">array of byte arrays to hash</param>
/// <returns>Returns the hashed data</returns> /// <returns>Returns the hashed data</returns>
private static byte[] digest(byte[][] tohash) private static byte[] Digest(byte[][] tohash)
{ {
SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); SHA1 sha1 = SHA1.Create();
for (int i = 0; i < tohash.Length; i++) for (int i = 0; i < tohash.Length; i++)
sha1.TransformBlock(tohash[i], 0, tohash[i].Length, tohash[i], 0); sha1.TransformBlock(tohash[i], 0, tohash[i].Length, tohash[i], 0);
sha1.TransformFinalBlock(new byte[] { }, 0, 0); sha1.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
return sha1.Hash; return sha1.Hash!;
} }
/// <summary> /// <summary>

View file

@ -11,8 +11,8 @@ namespace MinecraftClient
/// </summary> /// </summary>
public class FileMonitor : IDisposable public class FileMonitor : IDisposable
{ {
private Tuple<FileSystemWatcher, CancellationTokenSource>? monitor = null; private readonly Tuple<FileSystemWatcher, CancellationTokenSource>? monitor = null;
private Tuple<Thread, CancellationTokenSource>? polling = null; private readonly Tuple<Thread, CancellationTokenSource>? polling = null;
/// <summary> /// <summary>
/// Create a new FileMonitor and start monitoring /// Create a new FileMonitor and start monitoring
@ -24,7 +24,7 @@ namespace MinecraftClient
{ {
if (Settings.DebugMessages) if (Settings.DebugMessages)
{ {
string callerClass = new System.Diagnostics.StackFrame(1).GetMethod().DeclaringType.Name; string callerClass = new System.Diagnostics.StackFrame(1).GetMethod()!.DeclaringType!.Name;
ConsoleIO.WriteLineFormatted(Translations.Get("filemonitor.init", callerClass, Path.Combine(folder, filename))); ConsoleIO.WriteLineFormatted(Translations.Get("filemonitor.init", callerClass, Path.Combine(folder, filename)));
} }
@ -42,14 +42,14 @@ namespace MinecraftClient
{ {
if (Settings.DebugMessages) if (Settings.DebugMessages)
{ {
string callerClass = new System.Diagnostics.StackFrame(1).GetMethod().DeclaringType.Name; string callerClass = new System.Diagnostics.StackFrame(1).GetMethod()!.DeclaringType!.Name;
ConsoleIO.WriteLineFormatted(Translations.Get("filemonitor.fail", callerClass)); ConsoleIO.WriteLineFormatted(Translations.Get("filemonitor.fail", callerClass));
} }
monitor = null; monitor = null;
var cancellationTokenSource = new CancellationTokenSource(); var cancellationTokenSource = new CancellationTokenSource();
polling = new Tuple<Thread, CancellationTokenSource>(new Thread(() => PollingThread(folder, filename, handler, cancellationTokenSource.Token)), cancellationTokenSource); polling = new Tuple<Thread, CancellationTokenSource>(new Thread(() => PollingThread(folder, filename, handler, cancellationTokenSource.Token)), cancellationTokenSource);
polling.Item1.Name = String.Format("{0} Polling thread: {1}", this.GetType().Name, Path.Combine(folder, filename)); polling.Item1.Name = String.Format("{0} Polling thread: {1}", GetType().Name, Path.Combine(folder, filename));
polling.Item1.Start(); polling.Item1.Start();
} }
} }
@ -94,7 +94,7 @@ namespace MinecraftClient
/// <returns>Last write time, or DateTime.MinValue if the file does not exist</returns> /// <returns>Last write time, or DateTime.MinValue if the file does not exist</returns>
private DateTime GetLastWrite(string path) private DateTime GetLastWrite(string path)
{ {
FileInfo fileInfo = new FileInfo(path); FileInfo fileInfo = new(path);
if (fileInfo.Exists) if (fileInfo.Exists)
{ {
return fileInfo.LastWriteTime; return fileInfo.LastWriteTime;
@ -110,11 +110,10 @@ namespace MinecraftClient
/// <param name="encoding">Encoding (default is UTF8)</param> /// <param name="encoding">Encoding (default is UTF8)</param>
/// <exception cref="System.IO.IOException">Thrown when failing to read the file despite multiple retries</exception> /// <exception cref="System.IO.IOException">Thrown when failing to read the file despite multiple retries</exception>
/// <returns>All lines</returns> /// <returns>All lines</returns>
public static string[] ReadAllLinesWithRetries(string filePath, int maxTries = 3, Encoding encoding = null) public static string[] ReadAllLinesWithRetries(string filePath, int maxTries = 3, Encoding? encoding = null)
{ {
int attempt = 0; int attempt = 0;
if (encoding == null) encoding ??= Encoding.UTF8;
encoding = Encoding.UTF8;
while (true) while (true)
{ {
try try
@ -138,11 +137,10 @@ namespace MinecraftClient
/// <param name="lines">The lines to write to the file</param> /// <param name="lines">The lines to write to the file</param>
/// <param name="maxTries">Maximum read attempts</param> /// <param name="maxTries">Maximum read attempts</param>
/// <param name="encoding">Encoding (default is UTF8)</param> /// <param name="encoding">Encoding (default is UTF8)</param>
public static void WriteAllLinesWithRetries(string filePath, IEnumerable<string> lines, int maxTries = 3, Encoding encoding = null) public static void WriteAllLinesWithRetries(string filePath, IEnumerable<string> lines, int maxTries = 3, Encoding? encoding = null)
{ {
int attempt = 0; int attempt = 0;
if (encoding == null) encoding ??= Encoding.UTF8;
encoding = Encoding.UTF8;
while (true) while (true)
{ {
try try

View file

@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Text; using System.Text;
namespace MinecraftClient namespace MinecraftClient
@ -42,9 +41,9 @@ namespace MinecraftClient
string line = lineRaw.Split('#')[0].Trim(); string line = lineRaw.Split('#')[0].Trim();
if (line.Length > 0 && line[0] != ';') if (line.Length > 0 && line[0] != ';')
{ {
if (line[0] == '[' && line[line.Length - 1] == ']') if (line[0] == '[' && line[^1] == ']')
{ {
iniSection = line.Substring(1, line.Length - 2); iniSection = line[1..^1];
if (lowerCase) if (lowerCase)
iniSection = iniSection.ToLower(); iniSection = iniSection.ToLower();
} }
@ -55,7 +54,7 @@ namespace MinecraftClient
argName = argName.ToLower(); argName = argName.ToLower();
if (line.Length > (argName.Length + 1)) if (line.Length > (argName.Length + 1))
{ {
string argValue = line.Substring(argName.Length + 1); string argValue = line[(argName.Length + 1)..];
if (!iniContents.ContainsKey(iniSection)) if (!iniContents.ContainsKey(iniSection))
iniContents[iniSection] = new Dictionary<string, string>(); iniContents[iniSection] = new Dictionary<string, string>();
iniContents[iniSection][argName] = argValue; iniContents[iniSection][argName] = argValue;
@ -73,7 +72,7 @@ namespace MinecraftClient
/// <param name="contents">Data to put into the file</param> /// <param name="contents">Data to put into the file</param>
/// <param name="description">INI file description, inserted as a comment on first line of the INI file</param> /// <param name="description">INI file description, inserted as a comment on first line of the INI file</param>
/// <param name="autoCase">Automatically change first char of section and keys to uppercase</param> /// <param name="autoCase">Automatically change first char of section and keys to uppercase</param>
public static void WriteFile(string iniFile, Dictionary<string, Dictionary<string, string>> contents, string description = null, bool autoCase = true) public static void WriteFile(string iniFile, Dictionary<string, Dictionary<string, string>> contents, string? description = null, bool autoCase = true)
{ {
File.WriteAllLines(iniFile, Generate(contents, description, autoCase), Encoding.UTF8); File.WriteAllLines(iniFile, Generate(contents, description, autoCase), Encoding.UTF8);
} }
@ -85,9 +84,9 @@ namespace MinecraftClient
/// <param name="description">INI file description, inserted as a comment on first line of the INI file</param> /// <param name="description">INI file description, inserted as a comment on first line of the INI file</param>
/// <param name="autoCase">Automatically change first char of section and keys to uppercase</param> /// <param name="autoCase">Automatically change first char of section and keys to uppercase</param>
/// <returns>Lines of the INI file</returns> /// <returns>Lines of the INI file</returns>
public static string[] Generate(Dictionary<string, Dictionary<string, string>> contents, string description = null, bool autoCase = true) public static string[] Generate(Dictionary<string, Dictionary<string, string>> contents, string? description = null, bool autoCase = true)
{ {
List<string> lines = new List<string>(); List<string> lines = new();
if (!String.IsNullOrWhiteSpace(description)) if (!String.IsNullOrWhiteSpace(description))
lines.Add('#' + description); lines.Add('#' + description);
foreach (var section in contents) foreach (var section in contents)
@ -96,10 +95,10 @@ namespace MinecraftClient
lines.Add(""); lines.Add("");
if (!String.IsNullOrEmpty(section.Key)) if (!String.IsNullOrEmpty(section.Key))
{ {
lines.Add("[" + (autoCase ? char.ToUpper(section.Key[0]) + section.Key.Substring(1) : section.Key) + ']'); lines.Add("[" + (autoCase ? char.ToUpper(section.Key[0]) + section.Key[1..] : section.Key) + ']');
foreach (var item in section.Value) foreach (var item in section.Value)
if (!String.IsNullOrEmpty(item.Key)) if (!String.IsNullOrEmpty(item.Key))
lines.Add((autoCase ? char.ToUpper(item.Key[0]) + item.Key.Substring(1) : item.Key) + '=' + item.Value); lines.Add((autoCase ? char.ToUpper(item.Key[0]) + item.Key[1..] : item.Key) + '=' + item.Value);
} }
} }
return lines.ToArray(); return lines.ToArray();

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Inventory namespace MinecraftClient.Inventory
{ {
@ -23,7 +20,7 @@ namespace MinecraftClient.Inventory
/// <summary> /// <summary>
/// title of container /// title of container
/// </summary> /// </summary>
public string Title; public string? Title;
/// <summary> /// <summary>
/// state of container /// state of container
@ -35,11 +32,6 @@ namespace MinecraftClient.Inventory
/// </summary> /// </summary>
public Dictionary<int, Item> Items; public Dictionary<int, Item> Items;
/// <summary>
/// Create an empty container
/// </summary>
public Container() { }
/// <summary> /// <summary>
/// Create an empty container with ID, Type and Title /// Create an empty container with ID, Type and Title
/// </summary> /// </summary>
@ -61,7 +53,7 @@ namespace MinecraftClient.Inventory
/// <param name="type">Container Type</param> /// <param name="type">Container Type</param>
/// <param name="title">Container Title</param> /// <param name="title">Container Title</param>
/// <param name="items">Container Items (key: slot ID, value: item info)</param> /// <param name="items">Container Items (key: slot ID, value: item info)</param>
public Container(int id, ContainerType type, string title, Dictionary<int, Item> items) public Container(int id, ContainerType type, string? title, Dictionary<int, Item> items)
{ {
ID = id; ID = id;
Type = type; Type = type;
@ -130,33 +122,33 @@ namespace MinecraftClient.Inventory
public static ContainerType GetContainerType(int typeID) public static ContainerType GetContainerType(int typeID)
{ {
// https://wiki.vg/Inventory didn't state the inventory ID, assume that list start with 0 // https://wiki.vg/Inventory didn't state the inventory ID, assume that list start with 0
switch (typeID) return typeID switch
{ {
case 0: return ContainerType.Generic_9x1; 0 => ContainerType.Generic_9x1,
case 1: return ContainerType.Generic_9x2; 1 => ContainerType.Generic_9x2,
case 2: return ContainerType.Generic_9x3; 2 => ContainerType.Generic_9x3,
case 3: return ContainerType.Generic_9x4; 3 => ContainerType.Generic_9x4,
case 4: return ContainerType.Generic_9x5; 4 => ContainerType.Generic_9x5,
case 5: return ContainerType.Generic_9x6; 5 => ContainerType.Generic_9x6,
case 6: return ContainerType.Generic_3x3; 6 => ContainerType.Generic_3x3,
case 7: return ContainerType.Anvil; 7 => ContainerType.Anvil,
case 8: return ContainerType.Beacon; 8 => ContainerType.Beacon,
case 9: return ContainerType.BlastFurnace; 9 => ContainerType.BlastFurnace,
case 10: return ContainerType.BrewingStand; 10 => ContainerType.BrewingStand,
case 11: return ContainerType.Crafting; 11 => ContainerType.Crafting,
case 12: return ContainerType.Enchantment; 12 => ContainerType.Enchantment,
case 13: return ContainerType.Furnace; 13 => ContainerType.Furnace,
case 14: return ContainerType.Grindstone; 14 => ContainerType.Grindstone,
case 15: return ContainerType.Hopper; 15 => ContainerType.Hopper,
case 16: return ContainerType.Lectern; 16 => ContainerType.Lectern,
case 17: return ContainerType.Loom; 17 => ContainerType.Loom,
case 18: return ContainerType.Merchant; 18 => ContainerType.Merchant,
case 19: return ContainerType.ShulkerBox; 19 => ContainerType.ShulkerBox,
case 20: return ContainerType.Smoker; 20 => ContainerType.Smoker,
case 21: return ContainerType.Cartography; 21 => ContainerType.Cartography,
case 22: return ContainerType.Stonecutter; 22 => ContainerType.Stonecutter,
default: return ContainerType.Unknown; _ => ContainerType.Unknown,
} };
} }
/// <summary> /// <summary>
@ -166,7 +158,7 @@ namespace MinecraftClient.Inventory
/// <returns>An array of slot ID</returns> /// <returns>An array of slot ID</returns>
public int[] SearchItem(ItemType itemType) public int[] SearchItem(ItemType itemType)
{ {
List<int> result = new List<int>(); List<int> result = new();
if (Items != null) if (Items != null)
{ {
foreach (var item in Items) foreach (var item in Items)
@ -185,7 +177,7 @@ namespace MinecraftClient.Inventory
/// <remarks>Also depending on the container type, some empty slots cannot be used e.g. armor slots. This might cause issues.</remarks> /// <remarks>Also depending on the container type, some empty slots cannot be used e.g. armor slots. This might cause issues.</remarks>
public int[] GetEmpytSlots() public int[] GetEmpytSlots()
{ {
List<int> result = new List<int>(); List<int> result = new();
for (int i = 0; i < Type.SlotCount(); i++) for (int i = 0; i < Type.SlotCount(); i++)
{ {
result.Add(i); result.Add(i);

View file

@ -1,9 +1,4 @@
using System; namespace MinecraftClient.Inventory
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Inventory
{ {
// For MC 1.14 after ONLY // For MC 1.14 after ONLY
public enum ContainerType public enum ContainerType
@ -57,22 +52,24 @@ namespace MinecraftClient.Inventory
{ {
public static ContainerType ToNew(ContainerTypeOld type) public static ContainerType ToNew(ContainerTypeOld type)
{ {
switch (type) return type switch
{ {
case ContainerTypeOld.CONTAINER: return ContainerType.Unknown; #pragma warning disable format // @formatter:off
case ContainerTypeOld.CHEST: return ContainerType.Generic_9x3; ContainerTypeOld.CONTAINER => ContainerType.Unknown,
case ContainerTypeOld.CRAFTING_TABLE: return ContainerType.Crafting; ContainerTypeOld.CHEST => ContainerType.Generic_9x3,
case ContainerTypeOld.FURNACE: return ContainerType.Furnace; ContainerTypeOld.CRAFTING_TABLE => ContainerType.Crafting,
case ContainerTypeOld.DISPENSER: return ContainerType.Generic_3x3; ContainerTypeOld.FURNACE => ContainerType.Furnace,
case ContainerTypeOld.ENCHANTING_TABLE: return ContainerType.Enchantment; ContainerTypeOld.DISPENSER => ContainerType.Generic_3x3,
case ContainerTypeOld.BREWING_STAND: return ContainerType.BrewingStand; ContainerTypeOld.ENCHANTING_TABLE => ContainerType.Enchantment,
case ContainerTypeOld.VILLAGER: return ContainerType.Merchant; ContainerTypeOld.BREWING_STAND => ContainerType.BrewingStand,
case ContainerTypeOld.HOPPER: return ContainerType.Hopper; ContainerTypeOld.VILLAGER => ContainerType.Merchant,
case ContainerTypeOld.DROPPER: return ContainerType.Generic_3x3; ContainerTypeOld.HOPPER => ContainerType.Hopper,
case ContainerTypeOld.SHULKER_BOX: return ContainerType.ShulkerBox; ContainerTypeOld.DROPPER => ContainerType.Generic_3x3,
case ContainerTypeOld.ENTITYHORSE: return ContainerType.Unknown; ContainerTypeOld.SHULKER_BOX => ContainerType.ShulkerBox,
default: return ContainerType.Unknown; ContainerTypeOld.ENTITYHORSE => ContainerType.Unknown,
} _ => ContainerType.Unknown,
#pragma warning restore format // @formatter:on
};
} }
} }
} }

View file

@ -1,9 +1,4 @@
using System; namespace MinecraftClient.Inventory
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Inventory
{ {
public static class ContainerTypeExtensions public static class ContainerTypeExtensions
{ {
@ -14,31 +9,33 @@ namespace MinecraftClient.Inventory
/// <returns>Slot count of the container</returns> /// <returns>Slot count of the container</returns>
public static int SlotCount(this ContainerType c) public static int SlotCount(this ContainerType c)
{ {
switch (c) return c switch
{ {
case ContainerType.PlayerInventory: return 46; #pragma warning disable format // @formatter:off
case ContainerType.Generic_9x3: return 63; ContainerType.PlayerInventory => 46,
case ContainerType.Generic_9x6: return 90; ContainerType.Generic_9x3 => 63,
case ContainerType.Generic_3x3: return 45; ContainerType.Generic_9x6 => 90,
case ContainerType.Crafting: return 46; ContainerType.Generic_3x3 => 45,
case ContainerType.BlastFurnace: return 39; ContainerType.Crafting => 46,
case ContainerType.Furnace: return 39; ContainerType.BlastFurnace => 39,
case ContainerType.Smoker: return 39; ContainerType.Furnace => 39,
case ContainerType.Enchantment: return 38; ContainerType.Smoker => 39,
case ContainerType.BrewingStand: return 41; ContainerType.Enchantment => 38,
case ContainerType.Merchant: return 39; ContainerType.BrewingStand => 41,
case ContainerType.Beacon: return 37; ContainerType.Merchant => 39,
case ContainerType.Anvil: return 39; ContainerType.Beacon => 37,
case ContainerType.Hopper: return 41; ContainerType.Anvil => 39,
case ContainerType.ShulkerBox: return 63; ContainerType.Hopper => 41,
case ContainerType.Loom: return 40; ContainerType.ShulkerBox => 63,
case ContainerType.Stonecutter: return 38; ContainerType.Loom => 40,
case ContainerType.Lectern: return 37; ContainerType.Stonecutter => 38,
case ContainerType.Cartography: return 39; ContainerType.Lectern => 37,
case ContainerType.Grindstone: return 39; ContainerType.Cartography => 39,
case ContainerType.Unknown: return 0; ContainerType.Grindstone => 39,
default: return 0; ContainerType.Unknown => 0,
} _ => 0,
#pragma warning restore format // @formatter:on
};
} }
/// <summary> /// <summary>
@ -46,33 +43,40 @@ namespace MinecraftClient.Inventory
/// </summary> /// </summary>
/// <param name="c"></param> /// <param name="c"></param>
/// <returns>ASCII art representation or NULL if not implemented for this container type</returns> /// <returns>ASCII art representation or NULL if not implemented for this container type</returns>
public static string GetAsciiArt(this ContainerType c) public static string? GetAsciiArt(this ContainerType c)
{ {
switch (c) return c switch
{ {
case ContainerType.PlayerInventory: return DefaultConfigResource.ContainerType_PlayerInventory; #pragma warning disable format // @formatter:off
case ContainerType.Generic_9x3: return DefaultConfigResource.ContainerType_Generic_9x3; ContainerType.PlayerInventory => DefaultConfigResource.ContainerType_PlayerInventory,
case ContainerType.Generic_9x6: return DefaultConfigResource.ContainerType_Generic_9x6; ContainerType.Generic_9x3 => DefaultConfigResource.ContainerType_Generic_9x3,
case ContainerType.Generic_3x3: return DefaultConfigResource.ContainerType_Generic_3x3; ContainerType.Generic_9x6 => DefaultConfigResource.ContainerType_Generic_9x6,
case ContainerType.Crafting: return DefaultConfigResource.ContainerType_Crafting; ContainerType.Generic_3x3 => DefaultConfigResource.ContainerType_Generic_3x3,
case ContainerType.BlastFurnace: return DefaultConfigResource.ContainerType_Furnace; ContainerType.Crafting => DefaultConfigResource.ContainerType_Crafting,
case ContainerType.Furnace: return DefaultConfigResource.ContainerType_Furnace; ContainerType.BlastFurnace => DefaultConfigResource.ContainerType_Furnace,
case ContainerType.Smoker: return DefaultConfigResource.ContainerType_Furnace; ContainerType.Furnace => DefaultConfigResource.ContainerType_Furnace,
case ContainerType.Enchantment: return null; ContainerType.Smoker => DefaultConfigResource.ContainerType_Furnace,
case ContainerType.BrewingStand: return DefaultConfigResource.ContainerType_BrewingStand; ContainerType.Enchantment => null,
case ContainerType.Merchant: return null; ContainerType.BrewingStand => DefaultConfigResource.ContainerType_BrewingStand,
case ContainerType.Beacon: return null; ContainerType.Merchant => null,
case ContainerType.Anvil: return null; ContainerType.Beacon => null,
case ContainerType.Hopper: return DefaultConfigResource.ContainerType_Hopper; ContainerType.Anvil => null,
case ContainerType.ShulkerBox: return DefaultConfigResource.ContainerType_Generic_9x3; ContainerType.Hopper => DefaultConfigResource.ContainerType_Hopper,
case ContainerType.Loom: return null; ContainerType.ShulkerBox => DefaultConfigResource.ContainerType_Generic_9x3,
case ContainerType.Stonecutter: return null; ContainerType.Loom => null,
case ContainerType.Lectern: return null; ContainerType.Stonecutter => null,
case ContainerType.Cartography: return null; ContainerType.Lectern => null,
case ContainerType.Grindstone: return DefaultConfigResource.ContainerType_Grindstone; ContainerType.Cartography => null,
case ContainerType.Unknown: return null; ContainerType.Grindstone => DefaultConfigResource.ContainerType_Grindstone,
default: return null; ContainerType.Unknown => null,
} ContainerType.Generic_9x1 => null,
ContainerType.Generic_9x2 => null,
ContainerType.Generic_9x4 => null,
ContainerType.Generic_9x5 => null,
ContainerType.SmightingTable => null,
_ => null,
#pragma warning restore format // @formatter:on
};
} }
} }
} }

View file

@ -1,9 +1,3 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinecraftClient.Inventory namespace MinecraftClient.Inventory
{ {
/// <summary> /// <summary>

View file

@ -1,7 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
using System.Linq;
namespace MinecraftClient.Inventory namespace MinecraftClient.Inventory
{ {
@ -33,9 +33,9 @@ namespace MinecraftClient.Inventory
/// <param name="nbt">Item Metadata</param> /// <param name="nbt">Item Metadata</param>
public Item(ItemType itemType, int count, Dictionary<string, object>? nbt) public Item(ItemType itemType, int count, Dictionary<string, object>? nbt)
{ {
this.Type = itemType; Type = itemType;
this.Count = count; Count = count;
this.NBT = nbt; NBT = nbt;
} }
/// <summary> /// <summary>
@ -53,50 +53,46 @@ namespace MinecraftClient.Inventory
/// <summary> /// <summary>
/// Retrieve item display name from NBT properties. NULL if no display name is defined. /// Retrieve item display name from NBT properties. NULL if no display name is defined.
/// </summary> /// </summary>
public string DisplayName public string? DisplayName
{ {
get get
{ {
if (NBT != null && NBT.ContainsKey("display")) if (NBT != null && NBT.ContainsKey("display"))
{ {
var displayProperties = NBT["display"] as Dictionary<string, object>; if (NBT["display"] is Dictionary<string, object> displayProperties && displayProperties.ContainsKey("Name"))
if (displayProperties != null && displayProperties.ContainsKey("Name"))
{ {
string displayName = displayProperties["Name"] as string; string? displayName = displayProperties["Name"] as string;
if (!String.IsNullOrEmpty(displayName)) if (!String.IsNullOrEmpty(displayName))
return MinecraftClient.Protocol.ChatParser.ParseText(displayProperties["Name"].ToString()); return MinecraftClient.Protocol.ChatParser.ParseText(displayProperties["Name"].ToString() ?? string.Empty);
} }
} }
return null; return null;
} }
} }
/// <summary> /// <summary>
/// Retrieve item lores from NBT properties. Returns null if no lores is defined. /// Retrieve item lores from NBT properties. Returns null if no lores is defined.
/// </summary> /// </summary>
public string[] Lores public string[]? Lores
{ {
get get
{ {
List<string> lores = new List<string>(); List<string> lores = new();
if (NBT != null && NBT.ContainsKey("display")) if (NBT != null && NBT.ContainsKey("display"))
{ {
var displayProperties = NBT["display"] as Dictionary<string, object>; if (NBT["display"] is Dictionary<string, object> displayProperties && displayProperties.ContainsKey("Lore"))
if (displayProperties != null && displayProperties.ContainsKey("Lore"))
{ {
object[] displayName = displayProperties["Lore"] as object[]; object[] displayName = (object[])displayProperties["Lore"];
foreach (string st in displayName) lores.AddRange(from string st in displayName
{ let str = MinecraftClient.Protocol.ChatParser.ParseText(st.ToString())
string str = MinecraftClient.Protocol.ChatParser.ParseText(st.ToString()); select str);
lores.Add(str);
}
return lores.ToArray(); return lores.ToArray();
} }
} }
return null; return null;
} }
} }
/// <summary> /// <summary>
/// Retrieve item damage from NBT properties. Returns 0 if no damage is defined. /// Retrieve item damage from NBT properties. Returns 0 if no damage is defined.
/// </summary> /// </summary>
@ -109,7 +105,7 @@ namespace MinecraftClient.Inventory
object damage = NBT["Damage"]; object damage = NBT["Damage"];
if (damage != null) if (damage != null)
{ {
return int.Parse(damage.ToString()); return int.Parse(damage.ToString() ?? string.Empty);
} }
} }
return 0; return 0;
@ -118,18 +114,18 @@ namespace MinecraftClient.Inventory
public override string ToString() public override string ToString()
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new();
sb.AppendFormat("x{0,-2} {1}", Count, Type.ToString()); sb.AppendFormat("x{0,-2} {1}", Count, Type.ToString());
string displayName = DisplayName;
string? displayName = DisplayName;
if (!String.IsNullOrEmpty(displayName)) if (!String.IsNullOrEmpty(displayName))
{
sb.AppendFormat(" - {0}§8", displayName); sb.AppendFormat(" - {0}§8", displayName);
}
int damage = Damage; int damage = Damage;
if (damage != 0) if (damage != 0)
{
sb.AppendFormat(" | {0}: {1}", Translations.Get("cmd.inventory.damage"), damage); sb.AppendFormat(" | {0}: {1}", Translations.Get("cmd.inventory.damage"), damage);
}
return sb.ToString(); return sb.ToString();
} }
} }

View file

@ -1,8 +1,5 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
namespace MinecraftClient.Inventory namespace MinecraftClient.Inventory
{ {
@ -11,8 +8,8 @@ namespace MinecraftClient.Inventory
/// </summary> /// </summary>
public class ItemMovingHelper public class ItemMovingHelper
{ {
private Container c; private readonly Container c;
private McClient mc; private readonly McClient mc;
/// <summary> /// <summary>
/// Create a helper that contains useful methods to move item around in container /// Create a helper that contains useful methods to move item around in container
@ -35,7 +32,7 @@ namespace MinecraftClient.Inventory
/// <param name="dest">Dest slot</param> /// <param name="dest">Dest slot</param>
/// <param name="destContainer">Dest slot's container (only if dest slot is in other container)</param> /// <param name="destContainer">Dest slot's container (only if dest slot is in other container)</param>
/// <returns>True if success or false if Failed</returns> /// <returns>True if success or false if Failed</returns>
public bool MoveTo(int source, int dest, Container destContainer = null) public bool MoveTo(int source, int dest, Container? destContainer = null)
{ {
// Condition: source has item and dest has no item // Condition: source has item and dest has no item
if (ValidateSlots(source, dest, destContainer) && if (ValidateSlots(source, dest, destContainer) &&
@ -53,7 +50,7 @@ namespace MinecraftClient.Inventory
/// <param name="slot2">Slot 2</param> /// <param name="slot2">Slot 2</param>
/// <param name="destContainer">Slot2 container (only if slot2 is in other container)</param> /// <param name="destContainer">Slot2 container (only if slot2 is in other container)</param>
/// <returns>True if success or False if Failed</returns> /// <returns>True if success or False if Failed</returns>
public bool Swap(int slot1, int slot2, Container destContainer = null) public bool Swap(int slot1, int slot2, Container? destContainer = null)
{ {
// Condition: Both slot1 and slot2 has item // Condition: Both slot1 and slot2 has item
if (ValidateSlots(slot1, slot2, destContainer) && if (ValidateSlots(slot1, slot2, destContainer) &&
@ -79,7 +76,7 @@ namespace MinecraftClient.Inventory
{ {
if (!HasItem(source)) if (!HasItem(source))
return false; return false;
List<int> availableSlots = new List<int>(slots.Count()); List<int> availableSlots = new(slots.Count());
// filter out different item type or non-empty slots (they will be ignored silently) // filter out different item type or non-empty slots (they will be ignored silently)
foreach (var slot in slots) foreach (var slot in slots)
if (ItemTypeEqual(source, slot) || !HasItem(slot)) if (ItemTypeEqual(source, slot) || !HasItem(slot))
@ -126,7 +123,7 @@ namespace MinecraftClient.Inventory
/// <param name="s2">Slot 2</param> /// <param name="s2">Slot 2</param>
/// <param name="s2Container">Second container (only if slot2 is in other container)</param> /// <param name="s2Container">Second container (only if slot2 is in other container)</param>
/// <returns>The compare result</returns> /// <returns>The compare result</returns>
private bool ValidateSlots(int s1, int s2, Container s2Container = null) private bool ValidateSlots(int s1, int s2, Container? s2Container = null)
{ {
if (s2Container == null) if (s2Container == null)
return (s1 != s2 && s1 < c.Type.SlotCount() && s2 < c.Type.SlotCount()); return (s1 != s2 && s1 < c.Type.SlotCount() && s2 < c.Type.SlotCount());
@ -140,10 +137,9 @@ namespace MinecraftClient.Inventory
/// <param name="slot">Slot ID</param> /// <param name="slot">Slot ID</param>
/// <param name="c">Specify another contianer (only if the slot is in other container)</param> /// <param name="c">Specify another contianer (only if the slot is in other container)</param>
/// <returns>True if has item</returns> /// <returns>True if has item</returns>
private bool HasItem(int slot, Container c = null) private bool HasItem(int slot, Container? c = null)
{ {
if (c == null) c ??= this.c;
c = this.c;
return c.Items.ContainsKey(slot); return c.Items.ContainsKey(slot);
} }
@ -154,7 +150,7 @@ namespace MinecraftClient.Inventory
/// <param name="slot2"></param> /// <param name="slot2"></param>
/// <param name="s2Container">Second container (only if slot2 is in other container)</param> /// <param name="s2Container">Second container (only if slot2 is in other container)</param>
/// <returns>True if they are equal</returns> /// <returns>True if they are equal</returns>
private bool ItemTypeEqual(int slot1, int slot2, Container s2Container = null) private bool ItemTypeEqual(int slot1, int slot2, Container? s2Container = null)
{ {
if (s2Container == null) if (s2Container == null)
{ {

View file

@ -1,14 +1,11 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Inventory.ItemPalettes namespace MinecraftClient.Inventory.ItemPalettes
{ {
public abstract class ItemPalette public abstract class ItemPalette
{ {
protected abstract Dictionary<int, ItemType> GetDict(); protected abstract Dictionary<int, ItemType> GetDict();
private readonly Dictionary<ItemType, int> DictReverse = new Dictionary<ItemType, int>(); private readonly Dictionary<ItemType, int> DictReverse = new();
public ItemPalette() public ItemPalette()
{ {

View file

@ -1,4 +1,3 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Inventory.ItemPalettes namespace MinecraftClient.Inventory.ItemPalettes
@ -9,7 +8,7 @@ namespace MinecraftClient.Inventory.ItemPalettes
/// </summary> /// </summary>
public class ItemPalette115 : ItemPalette public class ItemPalette115 : ItemPalette
{ {
private static Dictionary<int, ItemType> mappings = new Dictionary<int, ItemType>(); private static readonly Dictionary<int, ItemType> mappings = new();
static ItemPalette115() static ItemPalette115()
{ {

View file

@ -1,4 +1,3 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Inventory.ItemPalettes namespace MinecraftClient.Inventory.ItemPalettes
@ -9,7 +8,7 @@ namespace MinecraftClient.Inventory.ItemPalettes
/// </summary> /// </summary>
public class ItemPalette1161 : ItemPalette public class ItemPalette1161 : ItemPalette
{ {
private static Dictionary<int, ItemType> mappings = new Dictionary<int, ItemType>(); private static readonly Dictionary<int, ItemType> mappings = new();
static ItemPalette1161() static ItemPalette1161()
{ {

View file

@ -1,4 +1,3 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Inventory.ItemPalettes namespace MinecraftClient.Inventory.ItemPalettes
@ -9,7 +8,7 @@ namespace MinecraftClient.Inventory.ItemPalettes
/// </summary> /// </summary>
public class ItemPalette1162 : ItemPalette public class ItemPalette1162 : ItemPalette
{ {
private static Dictionary<int, ItemType> mappings = new Dictionary<int, ItemType>(); private static readonly Dictionary<int, ItemType> mappings = new();
static ItemPalette1162() static ItemPalette1162()
{ {

View file

@ -1,11 +1,10 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Inventory.ItemPalettes namespace MinecraftClient.Inventory.ItemPalettes
{ {
public class ItemPalette117 : ItemPalette public class ItemPalette117 : ItemPalette
{ {
private static Dictionary<int, ItemType> mappings = new Dictionary<int, ItemType>(); private static readonly Dictionary<int, ItemType> mappings = new();
static ItemPalette117() static ItemPalette117()
{ {

View file

@ -1,11 +1,10 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Inventory.ItemPalettes namespace MinecraftClient.Inventory.ItemPalettes
{ {
public class ItemPalette118 : ItemPalette public class ItemPalette118 : ItemPalette
{ {
private static Dictionary<int, ItemType> mappings = new Dictionary<int, ItemType>(); private static readonly Dictionary<int, ItemType> mappings = new();
static ItemPalette118() static ItemPalette118()
{ {

View file

@ -1,11 +1,10 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Inventory.ItemPalettes namespace MinecraftClient.Inventory.ItemPalettes
{ {
public class ItemPalette119 : ItemPalette public class ItemPalette119 : ItemPalette
{ {
private static Dictionary<int, ItemType> mappings = new Dictionary<int, ItemType>(); private static readonly Dictionary<int, ItemType> mappings = new();
static ItemPalette119() static ItemPalette119()
{ {

View file

@ -1,8 +1,4 @@
using MinecraftClient.Protocol; using MinecraftClient.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Inventory.ItemPalettes namespace MinecraftClient.Inventory.ItemPalettes
{ {
@ -18,8 +14,8 @@ namespace MinecraftClient.Inventory.ItemPalettes
{ {
DataTypeGenerator.GenerateEnumWithPalette( DataTypeGenerator.GenerateEnumWithPalette(
registriesJsonFile, registriesJsonFile,
"minecraft:item", "minecraft:item",
"ItemType", "ItemType",
"MinecraftClient.Inventory", "MinecraftClient.Inventory",
"ItemPalette", "ItemPalette",
"MinecraftClient.Inventory.ItemPalettes"); "MinecraftClient.Inventory.ItemPalettes");

View file

@ -1,7 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
namespace MinecraftClient.Inventory namespace MinecraftClient.Inventory
{ {

View file

@ -7,7 +7,7 @@
{ {
public Item InputItem1; public Item InputItem1;
public Item OutputItem; public Item OutputItem;
public Item InputItem2; public Item? InputItem2;
public bool TradeDisabled; public bool TradeDisabled;
public int NumberOfTradeUses; public int NumberOfTradeUses;
public int MaximumNumberOfTradeUses; public int MaximumNumberOfTradeUses;
@ -16,18 +16,18 @@
public float PriceMultiplier; public float PriceMultiplier;
public int Demand; public int Demand;
public VillagerTrade(Item inputItem1, Item outputItem, Item inputItem2, bool tradeDisabled, int numberOfTradeUses, int maximumNumberOfTradeUses, int xp, int specialPrice, float priceMultiplier, int demand) public VillagerTrade(Item inputItem1, Item outputItem, Item? inputItem2, bool tradeDisabled, int numberOfTradeUses, int maximumNumberOfTradeUses, int xp, int specialPrice, float priceMultiplier, int demand)
{ {
this.InputItem1 = inputItem1; InputItem1 = inputItem1;
this.OutputItem = outputItem; OutputItem = outputItem;
this.InputItem2 = inputItem2; InputItem2 = inputItem2;
this.TradeDisabled = tradeDisabled; TradeDisabled = tradeDisabled;
this.NumberOfTradeUses = numberOfTradeUses; NumberOfTradeUses = numberOfTradeUses;
this.MaximumNumberOfTradeUses = maximumNumberOfTradeUses; MaximumNumberOfTradeUses = maximumNumberOfTradeUses;
this.Xp = xp; Xp = xp;
this.SpecialPrice = specialPrice; SpecialPrice = specialPrice;
this.PriceMultiplier = priceMultiplier; PriceMultiplier = priceMultiplier;
this.Demand = demand; Demand = demand;
} }
} }
} }

View file

@ -1,9 +1,4 @@
using System; namespace MinecraftClient.Inventory
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Inventory
{ {
/// <summary> /// <summary>
/// Represents mouse interactions with an inventory window /// Represents mouse interactions with an inventory window

View file

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
namespace MinecraftClient namespace MinecraftClient
@ -27,7 +26,7 @@ namespace MinecraftClient
public class JSONData public class JSONData
{ {
public enum DataType { Object, Array, String }; public enum DataType { Object, Array, String };
private DataType type; private readonly DataType type;
public DataType Type { get { return type; } } public DataType Type { get { return type; } }
public Dictionary<string, JSONData> Properties; public Dictionary<string, JSONData> Properties;
public List<JSONData> DataArray; public List<JSONData> DataArray;
@ -137,9 +136,20 @@ namespace MinecraftClient
break; break;
//Number //Number
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case '-': case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
case '-':
data = new JSONData(JSONData.DataType.String); data = new JSONData(JSONData.DataType.String);
StringBuilder sb = new StringBuilder(); StringBuilder sb = new();
while ((toparse[cursorpos] >= '0' && toparse[cursorpos] <= '9') || toparse[cursorpos] == '.' || toparse[cursorpos] == '-') while ((toparse[cursorpos] >= '0' && toparse[cursorpos] <= '9') || toparse[cursorpos] == '.' || toparse[cursorpos] == '-')
{ {
sb.Append(toparse[cursorpos]); sb.Append(toparse[cursorpos]);

View file

@ -1,16 +1,13 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; using System.IO;
namespace MinecraftClient.Logger namespace MinecraftClient.Logger
{ {
public class FileLogLogger : FilteredLogger public class FileLogLogger : FilteredLogger
{ {
private string logFile; private readonly string logFile;
private bool prependTimestamp; private readonly bool prependTimestamp;
private object logFileLock = new object(); private readonly object logFileLock = new();
public FileLogLogger(string file, bool prependTimestamp = false) public FileLogLogger(string file, bool prependTimestamp = false)
{ {
@ -34,13 +31,13 @@ namespace MinecraftClient.Logger
if (prependTimestamp) if (prependTimestamp)
msg = GetTimestamp() + ' ' + msg; msg = GetTimestamp() + ' ' + msg;
string directory = Path.GetDirectoryName(logFile); string? directory = Path.GetDirectoryName(logFile);
if (!String.IsNullOrEmpty(directory) && !Directory.Exists(directory)) if (!String.IsNullOrEmpty(directory) && !Directory.Exists(directory))
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
lock (logFileLock) lock (logFileLock)
{ {
FileStream stream = new FileStream(logFile, FileMode.OpenOrCreate); FileStream stream = new(logFile, FileMode.OpenOrCreate);
StreamWriter writer = new StreamWriter(stream); StreamWriter writer = new(stream);
stream.Seek(0, SeekOrigin.End); stream.Seek(0, SeekOrigin.End);
writer.WriteLine(msg); writer.WriteLine(msg);
writer.Dispose(); writer.Dispose();

View file

@ -1,8 +1,4 @@
using System; using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace MinecraftClient.Logger namespace MinecraftClient.Logger
{ {
@ -12,9 +8,9 @@ namespace MinecraftClient.Logger
protected bool ShouldDisplay(FilterChannel channel, string msg) protected bool ShouldDisplay(FilterChannel channel, string msg)
{ {
Regex regexToUse = null; Regex? regexToUse = null;
// Convert to bool for XOR later. Whitelist = 0, Blacklist = 1 // Convert to bool for XOR later. Whitelist = 0, Blacklist = 1
bool filterMode = Settings.FilterMode == Settings.FilterModeEnum.Blacklist ? true : false; bool filterMode = Settings.FilterMode == Settings.FilterModeEnum.Blacklist;
switch (channel) switch (channel)
{ {
case FilterChannel.Chat: regexToUse = Settings.ChatFilter; break; case FilterChannel.Chat: regexToUse = Settings.ChatFilter; break;

View file

@ -1,9 +1,4 @@
using System; namespace MinecraftClient.Logger
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Logger
{ {
public interface ILogger public interface ILogger
{ {

View file

@ -1,9 +1,4 @@
using System; namespace MinecraftClient.Logger
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Logger
{ {
/// <summary> /// <summary>
/// Abstract class providing basic implementation of the ILogger interface /// Abstract class providing basic implementation of the ILogger interface
@ -30,7 +25,7 @@ namespace MinecraftClient.Logger
public void Chat(object msg) public void Chat(object msg)
{ {
Chat(msg.ToString()); Chat(msg.ToString() ?? string.Empty);
} }
public abstract void Debug(string msg); public abstract void Debug(string msg);
@ -42,7 +37,7 @@ namespace MinecraftClient.Logger
public void Debug(object msg) public void Debug(object msg)
{ {
Debug(msg.ToString()); Debug(msg.ToString() ?? string.Empty);
} }
public abstract void Error(string msg); public abstract void Error(string msg);
@ -54,7 +49,7 @@ namespace MinecraftClient.Logger
public void Error(object msg) public void Error(object msg)
{ {
Error(msg.ToString()); Error(msg.ToString() ?? string.Empty);
} }
public abstract void Info(string msg); public abstract void Info(string msg);
@ -66,7 +61,7 @@ namespace MinecraftClient.Logger
public void Info(object msg) public void Info(object msg)
{ {
Info(msg.ToString()); Info(msg.ToString() ?? string.Empty);
} }
public abstract void Warn(string msg); public abstract void Warn(string msg);
@ -78,12 +73,12 @@ namespace MinecraftClient.Logger
public void Warn(object msg) public void Warn(object msg)
{ {
Warn(msg.ToString()); Warn(msg.ToString() ?? string.Empty);
} }
protected virtual void Log(object msg) protected virtual void Log(object msg)
{ {
ConsoleIO.WriteLineFormatted(msg.ToString()); ConsoleIO.WriteLineFormatted(msg.ToString() ?? string.Empty);
} }
protected virtual void Log(string msg) protected virtual void Log(string msg)

View file

@ -1,8 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text;
using MinecraftClient.Mapping.BlockPalettes; using MinecraftClient.Mapping.BlockPalettes;
namespace MinecraftClient.Mapping namespace MinecraftClient.Mapping
@ -18,7 +15,7 @@ namespace MinecraftClient.Mapping
/// Get or set global block ID to Material mapping /// Get or set global block ID to Material mapping
/// The global Palette is a concept introduced with Minecraft 1.13 /// The global Palette is a concept introduced with Minecraft 1.13
/// </summary> /// </summary>
public static BlockPalette Palette { get; set; } public static BlockPalette Palette { get; set; } = new Palette112();
/// <summary> /// <summary>
/// Storage for block ID and metadata, as ushort for compatibility, performance and lower memory footprint /// Storage for block ID and metadata, as ushort for compatibility, performance and lower memory footprint
@ -45,13 +42,13 @@ namespace MinecraftClient.Mapping
if (Palette.IdHasMetadata) if (Palette.IdHasMetadata)
{ {
if (value > (ushort.MaxValue >> 4) || value < 0) if (value > (ushort.MaxValue >> 4) || value < 0)
throw new ArgumentOutOfRangeException("value", "Invalid block ID. Accepted range: 0-4095"); throw new ArgumentOutOfRangeException(nameof(value), "Invalid block ID. Accepted range: 0-4095");
blockIdAndMeta = (ushort)(value << 4 | BlockMeta); blockIdAndMeta = (ushort)(value << 4 | BlockMeta);
} }
else else
{ {
if (value > ushort.MaxValue || value < 0) if (value > ushort.MaxValue || value < 0)
throw new ArgumentOutOfRangeException("value", "Invalid block ID. Accepted range: 0-65535"); throw new ArgumentOutOfRangeException(nameof(value), "Invalid block ID. Accepted range: 0-65535");
blockIdAndMeta = (ushort)value; blockIdAndMeta = (ushort)value;
} }
} }
@ -100,9 +97,9 @@ namespace MinecraftClient.Mapping
{ {
if (!Palette.IdHasMetadata) if (!Palette.IdHasMetadata)
throw new InvalidOperationException("Current global Palette does not support block Metadata"); throw new InvalidOperationException("Current global Palette does not support block Metadata");
this.blockIdAndMeta = 0; blockIdAndMeta = 0;
this.BlockId = type; BlockId = type;
this.BlockMeta = metadata; BlockMeta = metadata;
} }
/// <summary> /// <summary>
@ -112,7 +109,7 @@ namespace MinecraftClient.Mapping
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public Block(ushort typeAndMeta) public Block(ushort typeAndMeta)
{ {
this.blockIdAndMeta = typeAndMeta; blockIdAndMeta = typeAndMeta;
} }
/// <summary> /// <summary>

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Mapping.BlockPalettes namespace MinecraftClient.Mapping.BlockPalettes
{ {

View file

@ -1,7 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.IO; using System.IO;
using System.Linq;
using System.Text; using System.Text;
namespace MinecraftClient.Mapping.BlockPalettes namespace MinecraftClient.Mapping.BlockPalettes
@ -42,13 +42,13 @@ namespace MinecraftClient.Mapping.BlockPalettes
/// <param name="outputEnum">output path for material.cs</param> /// <param name="outputEnum">output path for material.cs</param>
/// <remarks>java -cp minecraft_server.jar net.minecraft.data.Main --reports</remarks> /// <remarks>java -cp minecraft_server.jar net.minecraft.data.Main --reports</remarks>
/// <returns>state => block name mappings</returns> /// <returns>state => block name mappings</returns>
public static void JsonToClass(string blocksJsonFile, string outputClass, string outputEnum = null) public static void JsonToClass(string blocksJsonFile, string outputClass, string? outputEnum = null)
{ {
string outputPalettePath = Path.Combine(Path.GetDirectoryName(blocksJsonFile), outputClass + "XXX.cs"); string outputPalettePath = Path.Combine(Path.GetDirectoryName(blocksJsonFile)!, outputClass + "XXX.cs");
string outputEnumPath = Path.Combine(Path.GetDirectoryName(blocksJsonFile), outputEnum + "XXX.cs"); string outputEnumPath = Path.Combine(Path.GetDirectoryName(blocksJsonFile)!, outputEnum + "XXX.cs");
HashSet<int> knownStates = new HashSet<int>(); HashSet<int> knownStates = new();
Dictionary<string, HashSet<int>> blocks = new Dictionary<string, HashSet<int>>(); Dictionary<string, HashSet<int>> blocks = new();
Json.JSONData palette = Json.ParseJson(File.ReadAllText(blocksJsonFile, Encoding.UTF8)); Json.JSONData palette = Json.ParseJson(File.ReadAllText(blocksJsonFile, Encoding.UTF8));
foreach (KeyValuePair<string, Json.JSONData> item in palette.Properties) foreach (KeyValuePair<string, Json.JSONData> item in palette.Properties)
@ -76,17 +76,16 @@ namespace MinecraftClient.Mapping.BlockPalettes
} }
} }
HashSet<string> materials = new HashSet<string>(); HashSet<string> materials = new();
List<string> outFile = new List<string>(); List<string> outFile = new();
outFile.AddRange(new[] { outFile.AddRange(new[] {
"using System;",
"using System.Collections.Generic;", "using System.Collections.Generic;",
"", "",
"namespace MinecraftClient.Mapping.BlockPalettes", "namespace MinecraftClient.Mapping.BlockPalettes",
"{", "{",
" public class PaletteXXX : BlockPalette", " public class PaletteXXX : BlockPalette",
" {", " {",
" private static Dictionary<int, Material> materials = new Dictionary<int, Material>();", " private static readonly Dictionary<int, Material> materials = new();",
"", "",
" static PaletteXXX()", " static PaletteXXX()",
" {", " {",
@ -103,7 +102,7 @@ namespace MinecraftClient.Mapping.BlockPalettes
if (idList.Count > 1) if (idList.Count > 1)
{ {
idList.Sort(); idList.Sort();
Queue<int> idQueue = new Queue<int>(idList); Queue<int> idQueue = new(idList);
while (idQueue.Count > 0) while (idQueue.Count > 0)
{ {

View file

@ -1,4 +1,3 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Mapping.BlockPalettes namespace MinecraftClient.Mapping.BlockPalettes
@ -11,7 +10,7 @@ namespace MinecraftClient.Mapping.BlockPalettes
/// </summary> /// </summary>
public class Palette112 : BlockPalette public class Palette112 : BlockPalette
{ {
private static Dictionary<int, Material> materials = new Dictionary<int, Material>() private static readonly Dictionary<int, Material> materials = new()
{ {
{ 0, Material.Air }, { 0, Material.Air },
{ 1, Material.Stone }, { 1, Material.Stone },

View file

@ -1,4 +1,3 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Mapping.BlockPalettes namespace MinecraftClient.Mapping.BlockPalettes
@ -9,7 +8,7 @@ namespace MinecraftClient.Mapping.BlockPalettes
/// </summary> /// </summary>
public class Palette113 : BlockPalette public class Palette113 : BlockPalette
{ {
private static Dictionary<int, Material> materials = new Dictionary<int, Material>(); private static readonly Dictionary<int, Material> materials = new();
static Palette113() static Palette113()
{ {

View file

@ -1,4 +1,3 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Mapping.BlockPalettes namespace MinecraftClient.Mapping.BlockPalettes
@ -9,7 +8,7 @@ namespace MinecraftClient.Mapping.BlockPalettes
/// </summary> /// </summary>
public class Palette114 : BlockPalette public class Palette114 : BlockPalette
{ {
private static Dictionary<int, Material> materials = new Dictionary<int, Material>(); private static readonly Dictionary<int, Material> materials = new();
static Palette114() static Palette114()
{ {

View file

@ -1,4 +1,3 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Mapping.BlockPalettes namespace MinecraftClient.Mapping.BlockPalettes
@ -9,7 +8,7 @@ namespace MinecraftClient.Mapping.BlockPalettes
/// </summary> /// </summary>
public class Palette115 : BlockPalette public class Palette115 : BlockPalette
{ {
private static Dictionary<int, Material> materials = new Dictionary<int, Material>(); private static readonly Dictionary<int, Material> materials = new();
static Palette115() static Palette115()
{ {

View file

@ -1,11 +1,10 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Mapping.BlockPalettes namespace MinecraftClient.Mapping.BlockPalettes
{ {
public class Palette116 : BlockPalette public class Palette116 : BlockPalette
{ {
private static Dictionary<int, Material> materials = new Dictionary<int, Material>(); private static readonly Dictionary<int, Material> materials = new();
static Palette116() static Palette116()
{ {

View file

@ -1,11 +1,10 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Mapping.BlockPalettes namespace MinecraftClient.Mapping.BlockPalettes
{ {
public class Palette117 : BlockPalette public class Palette117 : BlockPalette
{ {
private static Dictionary<int, Material> materials = new Dictionary<int, Material>(); private static readonly Dictionary<int, Material> materials = new();
static Palette117() static Palette117()
{ {

View file

@ -1,11 +1,10 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Mapping.BlockPalettes namespace MinecraftClient.Mapping.BlockPalettes
{ {
public class Palette119 : BlockPalette public class Palette119 : BlockPalette
{ {
private static Dictionary<int, Material> materials = new Dictionary<int, Material>(); private static readonly Dictionary<int, Material> materials = new();
static Palette119() static Palette119()
{ {

View file

@ -1,9 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
namespace MinecraftClient.Mapping namespace MinecraftClient.Mapping
{ {

View file

@ -1,8 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MinecraftClient.Mapping namespace MinecraftClient.Mapping
{ {

View file

@ -1,8 +1,3 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Mapping namespace MinecraftClient.Mapping
{ {
/// <summary> /// <summary>

View file

@ -1,8 +1,3 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Mapping namespace MinecraftClient.Mapping
{ {
/// <summary> /// <summary>

View file

@ -1,8 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinecraftClient.Mapping namespace MinecraftClient.Mapping
{ {
@ -120,7 +117,7 @@ namespace MinecraftClient.Mapping
/// </summary> /// </summary>
public Dimension() public Dimension()
{ {
this.Name = "minecraft:overworld"; Name = "minecraft:overworld";
} }
/// <summary> /// <summary>
@ -130,73 +127,66 @@ namespace MinecraftClient.Mapping
/// <param name="nbt">The dimension type (NBT Tag Compound)</param> /// <param name="nbt">The dimension type (NBT Tag Compound)</param>
public Dimension(string name, Dictionary<string, object> nbt) public Dimension(string name, Dictionary<string, object> nbt)
{ {
if (name == null) Name = name ?? throw new ArgumentNullException(nameof(name));
throw new ArgumentNullException("name");
if (nbt == null)
throw new ArgumentNullException("nbt Data");
this.Name = name; if (nbt == null)
throw new ArgumentNullException(nameof(nbt));
if (nbt.ContainsKey("piglin_safe")) if (nbt.ContainsKey("piglin_safe"))
this.piglinSafe = 1 == (byte)nbt["piglin_safe"]; piglinSafe = Convert.ToBoolean(nbt["piglin_safe"]);
if (nbt.ContainsKey("monster_spawn_light_level")) if (nbt.ContainsKey("monster_spawn_light_level"))
{ {
try try
{ {
var monsterSpawnLightLevelObj = nbt["monster_spawn_light_level"]; var monsterSpawnLightLevelObj = nbt["monster_spawn_light_level"];
if (monsterSpawnLightLevelObj.GetType() == typeof(int)) try
this.monsterSpawnMinLightLevel = this.monsterSpawnMaxLightLevel = (int)monsterSpawnLightLevelObj; {
else monsterSpawnMinLightLevel = monsterSpawnMaxLightLevel = Convert.ToInt32(monsterSpawnLightLevelObj);
}
catch (Exception)
{ {
var inclusive = (Dictionary<string, object>)(((Dictionary<string, object>)monsterSpawnLightLevelObj)["value"]); var inclusive = (Dictionary<string, object>)(((Dictionary<string, object>)monsterSpawnLightLevelObj)["value"]);
this.monsterSpawnMinLightLevel = (int)inclusive["min_inclusive"]; monsterSpawnMinLightLevel = Convert.ToInt32(inclusive["min_inclusive"]);
this.monsterSpawnMaxLightLevel = (int)inclusive["max_inclusive"]; monsterSpawnMaxLightLevel = Convert.ToInt32(inclusive["max_inclusive"]);
} }
} }
catch (KeyNotFoundException) { } catch (KeyNotFoundException) { }
} }
if (nbt.ContainsKey("monster_spawn_block_light_limit")) if (nbt.ContainsKey("monster_spawn_block_light_limit"))
this.monsterSpawnBlockLightLimit = (int)nbt["monster_spawn_block_light_limit"]; monsterSpawnBlockLightLimit = Convert.ToInt32(nbt["monster_spawn_block_light_limit"]);
if (nbt.ContainsKey("natural")) if (nbt.ContainsKey("natural"))
this.natural = 1 == (byte)nbt["natural"]; natural = Convert.ToBoolean(nbt["natural"]);
if (nbt.ContainsKey("ambient_light")) if (nbt.ContainsKey("ambient_light"))
this.ambientLight = (float)nbt["ambient_light"]; ambientLight = (float)Convert.ToDouble(nbt["ambient_light"]);
if (nbt.ContainsKey("fixed_time")) if (nbt.ContainsKey("fixed_time"))
this.fixedTime = (long)nbt["fixed_time"]; fixedTime = Convert.ToInt64(nbt["fixed_time"]);
if (nbt.ContainsKey("infiniburn")) if (nbt.ContainsKey("infiniburn"))
this.infiniburn = (string)nbt["infiniburn"]; infiniburn = Convert.ToString(nbt["infiniburn"]) ?? string.Empty;
if (nbt.ContainsKey("respawn_anchor_works")) if (nbt.ContainsKey("respawn_anchor_works"))
this.respawnAnchorWorks = 1 == (byte)nbt["respawn_anchor_works"]; respawnAnchorWorks = Convert.ToBoolean(nbt["respawn_anchor_works"]);
if (nbt.ContainsKey("has_skylight")) if (nbt.ContainsKey("has_skylight"))
this.hasSkylight = 1 == (byte)nbt["has_skylight"]; hasSkylight = Convert.ToBoolean(nbt["has_skylight"]);
if (nbt.ContainsKey("bed_works")) if (nbt.ContainsKey("bed_works"))
this.bedWorks = 1 == (byte)nbt["bed_works"]; bedWorks = Convert.ToBoolean(nbt["bed_works"]);
if (nbt.ContainsKey("effects")) if (nbt.ContainsKey("effects"))
this.effects = (string)nbt["effects"]; effects = Convert.ToString(nbt["effects"]) ?? string.Empty;
if (nbt.ContainsKey("has_raids")) if (nbt.ContainsKey("has_raids"))
this.hasRaids = 1 == (byte)nbt["has_raids"]; hasRaids = Convert.ToBoolean(nbt["has_raids"]);
if (nbt.ContainsKey("min_y")) if (nbt.ContainsKey("min_y"))
this.minY = (int)nbt["min_y"]; minY = Convert.ToInt32(nbt["min_y"]);
if (nbt.ContainsKey("height")) if (nbt.ContainsKey("height"))
this.height = (int)nbt["height"]; height = Convert.ToInt32(nbt["height"]);
if (nbt.ContainsKey("min_y") && nbt.ContainsKey("height")) if (nbt.ContainsKey("min_y") && nbt.ContainsKey("height"))
this.maxY = this.minY + this.height; maxY = minY + height;
if (nbt.ContainsKey("logical_height") && nbt["logical_height"].GetType() != typeof(byte)) if (nbt.ContainsKey("logical_height") && nbt["logical_height"].GetType() != typeof(byte))
this.logicalHeight = (int)nbt["logical_height"]; logicalHeight = Convert.ToInt32(nbt["logical_height"]);
if (nbt.ContainsKey("coordinate_scale")) if (nbt.ContainsKey("coordinate_scale"))
{ coordinateScale = Convert.ToDouble(nbt["coordinate_scale"]);
var coordinateScaleObj = nbt["coordinate_scale"];
if (coordinateScaleObj.GetType() == typeof(float))
this.coordinateScale = (float)coordinateScaleObj;
else
this.coordinateScale = (double)coordinateScaleObj;
}
if (nbt.ContainsKey("ultrawarm")) if (nbt.ContainsKey("ultrawarm"))
this.ultrawarm = 1 == (byte)nbt["ultrawarm"]; ultrawarm = Convert.ToBoolean(nbt["ultrawarm"]);
if (nbt.ContainsKey("has_ceiling")) if (nbt.ContainsKey("has_ceiling"))
this.hasCeiling = 1 == (byte)nbt["has_ceiling"]; hasCeiling = Convert.ToBoolean(nbt["has_ceiling"]);
} }
} }
} }

View file

@ -1,9 +1,4 @@
using System; namespace MinecraftClient.Mapping
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Mapping
{ {
/// <summary> /// <summary>
/// Represents a unit movement in the world /// Represents a unit movement in the world

View file

@ -23,12 +23,12 @@ namespace MinecraftClient.Mapping
/// Nickname of the entity if it is a player. /// Nickname of the entity if it is a player.
/// </summary> /// </summary>
public string? Name; public string? Name;
/// <summary> /// <summary>
/// CustomName of the entity. /// CustomName of the entity.
/// </summary> /// </summary>
public string CustomNameJson; public string? CustomNameJson;
/// <summary> /// <summary>
/// IsCustomNameVisible of the entity. /// IsCustomNameVisible of the entity.
/// </summary> /// </summary>
@ -37,8 +37,8 @@ namespace MinecraftClient.Mapping
/// <summary> /// <summary>
/// CustomName of the entity. /// CustomName of the entity.
/// </summary> /// </summary>
public string CustomName; public string? CustomName;
/// <summary> /// <summary>
/// Latency of the entity if it is a player. /// Latency of the entity if it is a player.
/// </summary> /// </summary>
@ -77,21 +77,21 @@ namespace MinecraftClient.Mapping
/// Health of the entity /// Health of the entity
/// </summary> /// </summary>
public float Health; public float Health;
/// <summary> /// <summary>
/// Item of the entity if ItemFrame or Item /// Item of the entity if ItemFrame or Item
/// </summary> /// </summary>
public Item Item; public Item Item;
/// <summary> /// <summary>
/// Entity pose in the Minecraft world /// Entity pose in the Minecraft world
/// </summary> /// </summary>
public EntityPose Pose; public EntityPose Pose;
/// <summary> /// <summary>
/// Entity metadata /// Entity metadata
/// </summary> /// </summary>
public Dictionary<int, object?> Metadata; public Dictionary<int, object?>? Metadata;
/// <summary> /// <summary>
/// Entity equipment /// Entity equipment
@ -107,11 +107,11 @@ namespace MinecraftClient.Mapping
public Entity(int ID, EntityType type, Location location) public Entity(int ID, EntityType type, Location location)
{ {
this.ID = ID; this.ID = ID;
this.Type = type; Type = type;
this.Location = location; Location = location;
this.Health = 1.0f; Health = 1.0f;
this.Equipment = new Dictionary<int, Item>(); Equipment = new Dictionary<int, Item>();
this.Item = new Item(ItemType.Air, 0, null); Item = new Item(ItemType.Air, 0, null);
} }
/// <summary> /// <summary>
@ -123,14 +123,14 @@ namespace MinecraftClient.Mapping
public Entity(int ID, EntityType type, Location location, byte yaw, byte pitch, int objectData) public Entity(int ID, EntityType type, Location location, byte yaw, byte pitch, int objectData)
{ {
this.ID = ID; this.ID = ID;
this.Type = type; Type = type;
this.Location = location; Location = location;
this.Health = 1.0f; Health = 1.0f;
this.Equipment = new Dictionary<int, Item>(); Equipment = new Dictionary<int, Item>();
this.Item = new Item(ItemType.Air, 0, null); Item = new Item(ItemType.Air, 0, null);
this.Yaw = yaw * (1 / 256) * 360; // to angle in 360 degree Yaw = yaw * (1 / 256) * 360; // to angle in 360 degree
this.Pitch = pitch * (1 / 256) * 360; Pitch = pitch * (1 / 256) * 360;
this.ObjectData = objectData; ObjectData = objectData;
} }
/// <summary> /// <summary>
@ -144,15 +144,15 @@ namespace MinecraftClient.Mapping
public Entity(int ID, EntityType type, Location location, Guid uuid, string? name, byte yaw, byte pitch) public Entity(int ID, EntityType type, Location location, Guid uuid, string? name, byte yaw, byte pitch)
{ {
this.ID = ID; this.ID = ID;
this.Type = type; Type = type;
this.Location = location; Location = location;
this.UUID = uuid; UUID = uuid;
this.Name = name; Name = name;
this.Health = 1.0f; Health = 1.0f;
this.Equipment = new Dictionary<int, Item>(); Equipment = new Dictionary<int, Item>();
this.Item = new Item(ItemType.Air, 0, null); Item = new Item(ItemType.Air, 0, null);
this.Yaw = yaw * (1 / 256) * 360; // to angle in 360 degree Yaw = yaw * (1 / 256) * 360; // to angle in 360 degree
this.Pitch = pitch * (1 / 256) * 360; Pitch = pitch * (1 / 256) * 360;
} }
} }
} }

View file

@ -1,7 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Mapping.EntityPalettes namespace MinecraftClient.Mapping.EntityPalettes
{ {
@ -17,7 +14,7 @@ namespace MinecraftClient.Mapping.EntityPalettes
/// Get mapping dictionary for pre-1.14 non-living entities. /// Get mapping dictionary for pre-1.14 non-living entities.
/// </summary> /// </summary>
/// <returns>Palette dictionary for non-living entities (pre-1.14)</returns> /// <returns>Palette dictionary for non-living entities (pre-1.14)</returns>
protected virtual Dictionary<int, EntityType> GetDictNonLiving() protected virtual Dictionary<int, EntityType>? GetDictNonLiving()
{ {
return null; return null;
} }
@ -30,7 +27,7 @@ namespace MinecraftClient.Mapping.EntityPalettes
public EntityType FromId(int id, bool living) public EntityType FromId(int id, bool living)
{ {
Dictionary<int, EntityType> entityTypes = GetDict(); Dictionary<int, EntityType> entityTypes = GetDict();
Dictionary<int, EntityType> entityTypesNonLiving = GetDictNonLiving(); Dictionary<int, EntityType>? entityTypesNonLiving = GetDictNonLiving();
if (entityTypesNonLiving != null && !living) if (entityTypesNonLiving != null && !living)
{ {

View file

@ -1,5 +1,4 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
namespace MinecraftClient.Mapping.EntityPalettes namespace MinecraftClient.Mapping.EntityPalettes
{ {

View file

@ -1,4 +1,3 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Mapping.EntityPalettes namespace MinecraftClient.Mapping.EntityPalettes

View file

@ -1,4 +1,3 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace MinecraftClient.Mapping.EntityPalettes namespace MinecraftClient.Mapping.EntityPalettes
@ -9,7 +8,7 @@ namespace MinecraftClient.Mapping.EntityPalettes
/// </summary> /// </summary>
public class EntityPalette114 : EntityPalette public class EntityPalette114 : EntityPalette
{ {
private static Dictionary<int, EntityType> mappings = new Dictionary<int, EntityType>(); private static readonly Dictionary<int, EntityType> mappings = new();
static EntityPalette114() static EntityPalette114()
{ {

Some files were not shown because too many files have changed in this diff Show more