Correct spelling mistakes

Add custom config path setting to AutoCraft
This commit is contained in:
ReinforceZwei 2020-07-23 20:32:02 +08:00 committed by ORelio
parent 3ff2a18b60
commit 1960235968
5 changed files with 59 additions and 39 deletions

View file

@ -8,7 +8,7 @@ using MinecraftClient.Mapping;
namespace MinecraftClient.ChatBots namespace MinecraftClient.ChatBots
{ {
class AutoCarft : ChatBot class AutoCraft : ChatBot
{ {
private bool waitingForMaterials = false; private bool waitingForMaterials = false;
private bool waitingForUpdate = false; private bool waitingForUpdate = false;
@ -156,14 +156,20 @@ namespace MinecraftClient.ChatBots
} }
} }
public AutoCraft(string configPath = @"autocraft\config.ini")
{
this.configPath = configPath;
}
public override void Initialize() public override void Initialize()
{ {
if (!GetInventoryEnabled()) if (!GetInventoryEnabled())
{ {
ConsoleIO.WriteLogLine("Inventory handling is disabled. AutoCraft will be unloaded"); LogToConsole("Inventory handling is disabled. AutoCraft will be unloaded");
UnloadBot(); UnloadBot();
} }
RegisterChatBotCommand("autocraft", "auto craft", CommandHandler); RegisterChatBotCommand("autocraft", "Auto-crafting ChatBot command", CommandHandler);
RegisterChatBotCommand("ac", "Auto-crafting ChatBot command alias", CommandHandler);
LoadConfig(); LoadConfig();
} }
@ -185,7 +191,7 @@ namespace MinecraftClient.ChatBots
return ""; return "";
case "resetcfg": case "resetcfg":
WriteDefaultConfig(); WriteDefaultConfig();
return "Resetting your config to the default"; return "Resetting your config to default";
case "start": case "start":
if (args.Length >= 2) if (args.Length >= 2)
{ {
@ -196,9 +202,9 @@ namespace MinecraftClient.ChatBots
PrepareCrafting(recipes[name]); PrepareCrafting(recipes[name]);
return ""; return "";
} }
else return "Specified recipe name do not exist. Check your config file."; else return "Specified recipe name does not exist. Check your config file.";
} }
else return "Please specify the recipe name you want to carft."; else return "Please specify the recipe name you want to craft.";
case "stop": case "stop":
StopCrafting(); StopCrafting();
return "AutoCraft stopped"; return "AutoCraft stopped";
@ -213,7 +219,7 @@ namespace MinecraftClient.ChatBots
private string GetHelp() private string GetHelp()
{ {
return "Auto-crafting bot. Available commands: load, list, reload, resetcfg, start, stop, help. Use /autocraft help <cmd name> for more information"; return "Available commands: load, list, reload, resetcfg, start, stop, help. Use /autocraft help <cmd name> for more information. You may use /ac as command alias.";
} }
private string GetCommandHelp(string cmd) private string GetCommandHelp(string cmd)
@ -221,11 +227,11 @@ namespace MinecraftClient.ChatBots
switch (cmd.ToLower()) switch (cmd.ToLower())
{ {
case "load": case "load":
return "Load the config from default location."; return "Load the config file.";
case "list": case "list":
return "List loaded recipes name."; return "List loaded recipes name.";
case "reload": case "reload":
return "Reload the config from default location."; return "Reload the config file.";
case "resetcfg": case "resetcfg":
return "Write the default example config to default location."; return "Write the default example config to default location.";
case "start": case "start":
@ -250,16 +256,16 @@ namespace MinecraftClient.ChatBots
Directory.CreateDirectory(@"autocraft"); Directory.CreateDirectory(@"autocraft");
} }
WriteDefaultConfig(); WriteDefaultConfig();
ConsoleIO.WriteLogLine("[AutoCraft] No config found. Writing a new one."); LogDebugToConsole("No config found. Writing a new one.");
} }
try try
{ {
ParseConfig(); ParseConfig();
ConsoleIO.WriteLogLine("[AutoCraft] Successfully loaded"); LogToConsole("Successfully loaded");
} }
catch (Exception e) catch (Exception e)
{ {
ConsoleIO.WriteLogLine("[AutoCraft] Error while parsing config: \n" + e.Message); LogToConsole("Error while parsing config: \n" + e.Message);
} }
} }
@ -267,17 +273,16 @@ namespace MinecraftClient.ChatBots
{ {
string[] content = string[] content =
{ {
"[autocraft]", "[AutoCraft]",
"# A vaild autocraft config must begin with [autocraft]", "# A valid autocraft config must begin with [AutoCraft]",
"", "",
"tablelocation=0,65,0 # Location of the crafting table if you intended to use it. Terrain and movements must be enabled. Format: x,y,z", "tablelocation=0,65,0 # Location of the crafting table if you intended to use it. Terrain and movements must be enabled. Format: x,y,z",
"onfailure=abort # What to do on crafting failure, abort or wait", "onfailure=abort # What to do on crafting failure, abort or wait",
"updatedebounce=2 # DO NOT change this unless you know what you are doing. Value must be larger than 0, usually between 1-3",
"", "",
"# You can define multiple recipe in a single config file", "# You can define multiple recipes in a single config file",
"# This is an example of how to define a recipe", "# This is an example of how to define a recipe",
"[recipe]", "[Recipe]",
"name=whatever # name could be whatever you like. This must be in the first place", "name=whatever # name could be whatever you like. This field must be defined first",
"type=player # crafting table type: player or table", "type=player # crafting table type: player or table",
"result=StoneButton # the resulting item", "result=StoneButton # the resulting item",
"", "",
@ -292,33 +297,40 @@ namespace MinecraftClient.ChatBots
private void ParseConfig() private void ParseConfig()
{ {
string[] content = File.ReadAllLines(configPath); string[] content = File.ReadAllLines(configPath);
if (content[0] != "[autocraft]") if (content.Length <= 0)
{ {
throw new Exception("Cannot parse this config"); throw new Exception("Empty onfiguration file: " + configPath);
}
if (content[0].ToLower() != "[autocraft]")
{
throw new Exception("Invalid configuration file: " + configPath);
} }
// local variable for use in parsing config // local variable for use in parsing config
string session = ""; string section = "";
Dictionary<string, Recipe> recipes = new Dictionary<string, Recipe>(); Dictionary<string, Recipe> recipes = new Dictionary<string, Recipe>();
string lastRecipe = ""; string lastRecipe = "";
foreach (string l in content) foreach (string l in content)
{ {
// ignore comment start with # // ignore comment start with #
if (l.StartsWith("#")) continue; if (l.StartsWith("#"))
continue;
string line = l.Split('#')[0].Trim(); string line = l.Split('#')[0].Trim();
if (line.Length <= 0) continue; if (line.Length <= 0)
continue;
if (line[0] == '[' && line[line.Length - 1] == ']') if (line[0] == '[' && line[line.Length - 1] == ']')
{ {
session = line.Substring(1, line.Length - 2).ToLower(); section = line.Substring(1, line.Length - 2).ToLower();
continue; continue;
} }
string key = line.Split('=')[0].ToLower(); string key = line.Split('=')[0].ToLower();
if (!(line.Length > (key.Length + 1))) continue; if (!(line.Length > (key.Length + 1)))
continue;
string value = line.Substring(key.Length + 1); string value = line.Substring(key.Length + 1);
switch (session) 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;
@ -339,11 +351,11 @@ namespace MinecraftClient.ChatBots
} }
else else
{ {
throw new Exception("Missing item in recipe"); throw new Exception("Missing item in recipe: " + pair.Key);
} }
} }
#region Local method for parsing different session of config #region Local method for parsing different section of config
void parseMain(string key, string value) void parseMain(string key, string value)
{ {
@ -357,7 +369,7 @@ namespace MinecraftClient.ChatBots
tableLocation.Y = Convert.ToInt32(values[1]); tableLocation.Y = Convert.ToInt32(values[1]);
tableLocation.Z = Convert.ToInt32(values[2]); tableLocation.Z = Convert.ToInt32(values[2]);
} }
else throw new Exception("Invaild config format"); else throw new Exception("Invalid tablelocation format: " + key);
break; break;
case "onfailure": case "onfailure":
abortOnFailure = value.ToLower() == "abort" ? true : false; abortOnFailure = value.ToLower() == "abort" ? true : false;
@ -394,7 +406,7 @@ namespace MinecraftClient.ChatBots
} }
} }
} }
throw new Exception("Invalid config format"); throw new Exception("Invalid slot field in recipe: " + key);
} }
else else
{ {
@ -408,7 +420,7 @@ namespace MinecraftClient.ChatBots
} }
else else
{ {
throw new Exception("Duplicate recipe name specified"); throw new Exception("Duplicate recipe name specified: " + value);
} }
break; break;
case "type": case "type":
@ -549,10 +561,10 @@ namespace MinecraftClient.ChatBots
// Repeat the whole process again // Repeat the whole process again
actionSteps.Add(new ActionStep(ActionType.Repeat)); actionSteps.Add(new ActionStep(ActionType.Repeat));
// Start crafting // Start crafting
ConsoleIO.WriteLogLine("AutoCraft start!"); ConsoleIO.WriteLogLine("Starting AutoCraft: " + recipe.ResultItem);
HandleNextStep(); HandleNextStep();
} }
else ConsoleIO.WriteLogLine("AutoCraft cannot be started. Check your available materials"); else ConsoleIO.WriteLogLine("AutoCraft cannot be started. Check your available materials for crafting " + recipe.ResultItem);
} }
/// <summary> /// <summary>

View file

@ -173,7 +173,12 @@ namespace MinecraftClient.Inventory
return result.ToArray(); return result.ToArray();
} }
public int[] GetEmpytSlot() /// <summary>
/// List empty slots in the container
/// </summary>
/// <returns>An array of slot ID</returns>
/// <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()
{ {
List<int> result = new List<int>(); List<int> result = new List<int>();
for (int i = 0; i < Type.SlotCount(); i++) for (int i = 0; i < Type.SlotCount(); i++)

View file

@ -175,7 +175,7 @@ namespace MinecraftClient
if (Settings.AutoAttack_Enabled) { BotLoad(new ChatBots.AutoAttack()); } if (Settings.AutoAttack_Enabled) { BotLoad(new ChatBots.AutoAttack()); }
if (Settings.AutoFishing_Enabled) { BotLoad(new ChatBots.AutoFishing()); } if (Settings.AutoFishing_Enabled) { BotLoad(new ChatBots.AutoFishing()); }
if (Settings.AutoEat_Enabled) { BotLoad(new ChatBots.AutoEat(Settings.AutoEat_hungerThreshold)); } if (Settings.AutoEat_Enabled) { BotLoad(new ChatBots.AutoEat(Settings.AutoEat_hungerThreshold)); }
if (Settings.AutoCraft_Enabled) { BotLoad(new AutoCarft()); } if (Settings.AutoCraft_Enabled) { BotLoad(new AutoCraft(Settings.AutoCraft_configFile)); }
//Add your ChatBot here by uncommenting and adapting //Add your ChatBot here by uncommenting and adapting
//BotLoad(new ChatBots.YourBot()); //BotLoad(new ChatBots.YourBot());
@ -1181,7 +1181,7 @@ namespace MinecraftClient
} }
if (inventory.Items[slotId].Count > 0) if (inventory.Items[slotId].Count > 0)
{ {
int[] emptySlots = inventory.GetEmpytSlot(); int[] emptySlots = inventory.GetEmpytSlots();
int emptySlot = -2; int emptySlot = -2;
foreach (int slot in emptySlots) foreach (int slot in emptySlots)
{ {
@ -1227,7 +1227,7 @@ namespace MinecraftClient
} }
if (inventory.Items[slotId].Count > 0) if (inventory.Items[slotId].Count > 0)
{ {
int[] emptySlots = inventory.GetEmpytSlot(); int[] emptySlots = inventory.GetEmpytSlots();
int emptySlot = -2; int emptySlot = -2;
foreach (int slot in emptySlots) foreach (int slot in emptySlots)
{ {

View file

@ -77,7 +77,7 @@
<Compile Include="ChatBots\Alerts.cs" /> <Compile Include="ChatBots\Alerts.cs" />
<Compile Include="ChatBots\AntiAFK.cs" /> <Compile Include="ChatBots\AntiAFK.cs" />
<Compile Include="ChatBots\AutoAttack.cs" /> <Compile Include="ChatBots\AutoAttack.cs" />
<Compile Include="ChatBots\AutoCarft.cs" /> <Compile Include="ChatBots\AutoCraft.cs" />
<Compile Include="ChatBots\AutoEat.cs" /> <Compile Include="ChatBots\AutoEat.cs" />
<Compile Include="ChatBots\AutoFishing.cs" /> <Compile Include="ChatBots\AutoFishing.cs" />
<Compile Include="ChatBots\AutoRespond.cs" /> <Compile Include="ChatBots\AutoRespond.cs" />

View file

@ -166,6 +166,7 @@ namespace MinecraftClient
//AutoCraft //AutoCraft
public static bool AutoCraft_Enabled = false; public static bool AutoCraft_Enabled = false;
public static string AutoCraft_configFile = @"autocraft\config.ini";
//Custom app variables and Minecraft accounts //Custom app variables and Minecraft accounts
private static readonly Dictionary<string, object> AppVars = new Dictionary<string, object>(); private static readonly Dictionary<string, object> AppVars = new Dictionary<string, object>();
@ -500,6 +501,7 @@ namespace MinecraftClient
switch (argName.ToLower()) switch (argName.ToLower())
{ {
case "enabled": AutoCraft_Enabled = str2bool(argValue); break; case "enabled": AutoCraft_Enabled = str2bool(argValue); break;
case "configfile": AutoCraft_configFile = argValue; break;
} }
break; break;
@ -716,6 +718,7 @@ namespace MinecraftClient
+ "# Inventory Handling NEED to be enabled first\r\n" + "# Inventory Handling NEED to be enabled first\r\n"
+ "# Enable terrainandmovements if you need to use crafting table\r\n" + "# Enable terrainandmovements if you need to use crafting table\r\n"
+ "enabled=false\r\n" + "enabled=false\r\n"
+ "configfile=autocraft\\config.ini\r\n"
+ "\r\n", Encoding.UTF8); + "\r\n", Encoding.UTF8);
} }