Implement command completion suggestions.

This commit is contained in:
BruceChen 2022-12-06 15:50:17 +08:00
parent 5d2589b10f
commit 84cf749344
115 changed files with 4684 additions and 2695 deletions

View file

@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -11,76 +10,44 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "animation <mainhand|offhand>"; } }
public override string CmdDesc { get { return Translations.cmd_animation_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l =>
l.Literal("help").Then(l =>
l.Literal(CmdName).Executes(c => {
LogUsage(handler.Log);
return 1;
})
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
.Then(l => l.Literal("mainhand")
.Executes(r => GetUsage(r.Source, "mainhand")))
.Then(l => l.Literal("offhand")
.Executes(r => GetUsage(r.Source, "offhand")))
)
);
dispatcher.Register(l =>
l.Literal(CmdName).Then(l =>
l.Literal("mainhand")
.Executes(c => {
return LogExecuteResult(handler.Log, handler.DoAnimation(0));
})
)
);
dispatcher.Register(l =>
l.Literal(CmdName).Then(l =>
l.Literal("0")
.Redirect(dispatcher.GetRoot().GetChild(CmdName).GetChild("mainhand"))
)
);
dispatcher.Register(l =>
l.Literal(CmdName).Then(l =>
l.Literal("offhand")
.Executes(c => {
return LogExecuteResult(handler.Log, handler.DoAnimation(1));
})
)
);
dispatcher.Register(l =>
l.Literal(CmdName).Then(l =>
l.Literal("1")
.Redirect(dispatcher.GetRoot().GetChild(CmdName).GetChild("offhand"))
)
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => DoAnimation(r.Source, handler, mainhand: true))
.Then(l => l.Literal("mainhand")
.Executes(r => DoAnimation(r.Source, handler, mainhand: true)))
.Then(l => l.Literal("offhand")
.Executes(r => DoAnimation(r.Source, handler, mainhand: false)))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (HasArg(command))
return r.SetAndReturn(cmd switch
{
string[] args = GetArgs(command);
if (args.Length > 0)
{
if (args[0] == "mainhand" || args[0] == "0")
{
handler.DoAnimation(0);
return Translations.general_done;
}
else if (args[0] == "offhand" || args[0] == "1")
{
handler.DoAnimation(1);
return Translations.general_done;
}
else
{
return GetCmdDescTranslated();
}
}
else
{
return GetCmdDescTranslated();
}
}
else return GetCmdDescTranslated();
#pragma warning disable format // @formatter:off
"mainhand" => GetCmdDescTranslated(),
"offhand" => GetCmdDescTranslated(),
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private static int DoAnimation(CmdResult r, McClient handler, bool mainhand)
{
return r.SetAndReturn(handler.DoAnimation(mainhand ? 1 : 0));
}
}
}

View file

@ -1,10 +1,12 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.Mapping;
using static MinecraftClient.CommandHandler.CmdResult;
namespace MinecraftClient.Commands
{
@ -14,142 +16,162 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "bed leave|sleep <x> <y> <z>|sleep <radius>"; } }
public override string CmdDesc { get { return Translations.cmd_bed_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
.Then(l => l.Literal("leave")
.Executes(r => GetUsage(r.Source, "leave")))
.Then(l => l.Literal("sleep")
.Executes(r => GetUsage(r.Source, "sleep")))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Literal("leave")
.Executes(r => DoLeaveBed(r.Source, handler)))
.Then(l => l.Literal("sleep")
.Then(l => l.Argument("Location", MccArguments.Location())
.Executes(r => DoSleepBedWithLocation(r.Source, handler, MccArguments.GetLocation(r, "Location"))))
.Then(l => l.Argument("Radius", Arguments.Double())
.Executes(r => DoSleepBedWithRadius(r.Source, handler, Arguments.GetDouble(r, "Radius")))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
string[] args = GetArgs(command);
if (args.Length >= 1)
return r.SetAndReturn(cmd switch
{
string subcommand = args[0].ToLower().Trim();
#pragma warning disable format // @formatter:off
"leave" => GetCmdDescTranslated(),
"sleep" => GetCmdDescTranslated(),
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
if (subcommand.Equals("leave") || subcommand.Equals("l"))
private static int DoLeaveBed(CmdResult r, McClient handler)
{
return r.SetAndReturn(Translations.cmd_bed_leaving, handler.SendEntityAction(Protocol.EntityActionType.LeaveBed));
}
private static int DoSleepBedWithRadius(CmdResult r, McClient handler, double radius)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
handler.Log.Info(string.Format(Translations.cmd_bed_searching, radius));
Location current = handler.GetCurrentLocation();
Location bedLocation = current;
Material[] bedMaterialList = new Material[]
{
Material.BlackBed,
Material.BlueBed,
Material.BrownBed,
Material.CyanBed,
Material.GrayBed,
Material.GreenBed,
Material.LightBlueBed,
Material.LightGrayBed,
Material.LimeBed,
Material.MagentaBed,
Material.OrangeBed,
Material.PinkBed,
Material.PurpleBed,
Material.RedBed,
Material.WhiteBed,
Material.YellowBed
};
bool found = false;
foreach (Material material in bedMaterialList)
{
List<Location> beds = handler.GetWorld().FindBlock(current, material, radius);
if (beds.Count > 0)
{
handler.SendEntityAction(Protocol.EntityActionType.LeaveBed);
return Translations.cmd_bed_leaving;
}
if (subcommand.Equals("sleep") || subcommand.Equals("s"))
{
if (!handler.GetTerrainEnabled())
return Translations.error_terrain_not_enabled;
if (args.Length == 2)
{
if (!int.TryParse(args[1], NumberStyles.Any, CultureInfo.CurrentCulture, out int radius))
return CmdUsage;
handler.GetLogger().Info(string.Format(Translations.cmd_bed_searching, radius));
Location current = handler.GetCurrentLocation();
Location bedLocation = current;
Material[] bedMaterialList = new Material[]{
Material.BlackBed,
Material.BlueBed,
Material.BrownBed,
Material.CyanBed,
Material.GrayBed,
Material.GreenBed,
Material.LightBlueBed,
Material.LightGrayBed,
Material.LimeBed,
Material.MagentaBed,
Material.OrangeBed,
Material.PinkBed,
Material.PurpleBed,
Material.RedBed,
Material.WhiteBed,
Material.YellowBed
};
bool found = false;
foreach (Material material in bedMaterialList)
{
List<Location> beds = handler.GetWorld().FindBlock(current, material, radius);
if (beds.Count > 0)
{
found = true;
bedLocation = beds.First();
break;
}
}
if (!found)
return Translations.cmd_bed_bed_not_found;
handler.Log.Info(string.Format(Translations.cmd_bed_found_a_bed_at, bedLocation.X, bedLocation.Y, bedLocation.Z));
if (!Movement.CheckChunkLoading(handler.GetWorld(), current, bedLocation))
return string.Format(Translations.cmd_move_chunk_not_loaded, bedLocation.X, bedLocation.Y, bedLocation.Z);
if (handler.MoveTo(bedLocation))
{
Task.Factory.StartNew(() =>
{
bool atTheLocation = false;
DateTime timeout = DateTime.Now.AddSeconds(60);
while (DateTime.Now < timeout)
{
if (handler.GetCurrentLocation() == bedLocation || handler.GetCurrentLocation().Distance(bedLocation) <= 2.0)
{
atTheLocation = true;
break;
}
}
if (!atTheLocation)
{
handler.Log.Info(string.Format(Translations.cmd_bed_failed_to_reach_in_time, bedLocation.X, bedLocation.Y, bedLocation.Z));
return;
}
handler.Log.Info(string.Format(Translations.cmd_bed_moving, bedLocation.X, bedLocation.Y, bedLocation.Z));
bool res = handler.PlaceBlock(bedLocation, Direction.Down);
handler.Log.Info(string.Format(
Translations.cmd_bed_trying_to_use,
bedLocation.X,
bedLocation.Y,
bedLocation.Z,
res ? Translations.cmd_bed_in : Translations.cmd_bed_not_in
));
});
return "";
}
return Translations.cmd_bed_cant_reach_safely;
}
if (args.Length >= 3)
{
Location block = Location.Parse(handler.GetCurrentLocation(), args[1], args[2], args[3]).ToFloor();
Location blockCenter = block.ToCenter();
if (!handler.GetWorld().GetBlock(block).Type.IsBed())
return string.Format(Translations.cmd_bed_not_a_bed, blockCenter.X, blockCenter.Y, blockCenter.Z);
bool res = handler.PlaceBlock(block, Direction.Down);
return string.Format(
Translations.cmd_bed_trying_to_use,
blockCenter.X,
blockCenter.Y,
blockCenter.Z,
res ? Translations.cmd_bed_in : Translations.cmd_bed_not_in
);
}
found = true;
bedLocation = beds.First();
break;
}
}
return CmdUsage;
if (!found)
return r.SetAndReturn(Status.Fail, Translations.cmd_bed_bed_not_found);
handler.Log.Info(string.Format(Translations.cmd_bed_found_a_bed_at, bedLocation.X, bedLocation.Y, bedLocation.Z));
if (!Movement.CheckChunkLoading(handler.GetWorld(), current, bedLocation))
return r.SetAndReturn(Status.FailChunkNotLoad,
string.Format(Translations.cmd_move_chunk_not_loaded, bedLocation.X, bedLocation.Y, bedLocation.Z));
if (handler.MoveTo(bedLocation))
{
Task.Factory.StartNew(() =>
{
bool atTheLocation = false;
DateTime timeout = DateTime.Now.AddSeconds(60);
while (DateTime.Now < timeout)
{
if (handler.GetCurrentLocation() == bedLocation || handler.GetCurrentLocation().Distance(bedLocation) <= 2.0)
{
atTheLocation = true;
break;
}
}
if (!atTheLocation)
{
handler.Log.Info(string.Format(Translations.cmd_bed_failed_to_reach_in_time, bedLocation.X, bedLocation.Y, bedLocation.Z));
return;
}
handler.Log.Info(string.Format(Translations.cmd_bed_moving, bedLocation.X, bedLocation.Y, bedLocation.Z));
bool res = handler.PlaceBlock(bedLocation, Direction.Down);
handler.Log.Info(string.Format(
Translations.cmd_bed_trying_to_use,
bedLocation.X,
bedLocation.Y,
bedLocation.Z,
res ? Translations.cmd_bed_in : Translations.cmd_bed_not_in
));
});
return r.SetAndReturn(Status.Done);
}
else
{
return r.SetAndReturn(Status.Fail, Translations.cmd_bed_cant_reach_safely);
}
}
private static int DoSleepBedWithLocation(CmdResult r, McClient handler, Location block)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
block.ToAbsolute(handler.GetCurrentLocation());
Location blockCenter = block.ToCenter();
if (!handler.GetWorld().GetBlock(block).Type.IsBed())
return r.SetAndReturn(Status.Fail,
string.Format(Translations.cmd_bed_not_a_bed, blockCenter.X, blockCenter.Y, blockCenter.Z));
return r.SetAndReturn(Status.Done, string.Format(
Translations.cmd_bed_trying_to_use,
blockCenter.X,
blockCenter.Y,
blockCenter.Z,
handler.PlaceBlock(block, Direction.Down) ? Translations.cmd_bed_in : Translations.cmd_bed_not_in
));
}
}
}

View file

@ -1,7 +1,9 @@
using System.Collections.Generic;
using System.Text;
using System.Text;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.Mapping;
using static MinecraftClient.CommandHandler.CmdResult;
namespace MinecraftClient.Commands
{
@ -11,40 +13,60 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "blockinfo <x> <y> <z> [-s]"; } }
public override string CmdDesc { get { return Translations.cmd_blockinfo_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
.Then(l => l.Literal("-s")
.Executes(r => GetUsage(r.Source, "-s")))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => LogBlockInfo(r.Source, handler, handler.GetCurrentLocation(), false))
.Then(l => l.Literal("-s")
.Executes(r => LogBlockInfo(r.Source, handler, handler.GetCurrentLocation(), true)))
.Then(l => l.Argument("Location", MccArguments.Location())
.Executes(r => LogBlockInfo(r.Source, handler, MccArguments.GetLocation(r, "Location"), false))
.Then(l => l.Literal("-s")
.Executes(r => LogBlockInfo(r.Source, handler, MccArguments.GetLocation(r, "Location"), true))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
"-s" => GetCmdDescTranslated(),
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private static int LogBlockInfo(CmdResult r, McClient handler, Location targetBlock, bool reportSurrounding)
{
if (!handler.GetTerrainEnabled())
return Translations.error_terrain_not_enabled;
return r.SetAndReturn(Status.FailNeedTerrain);
string[] args = GetArgs(command);
if (args.Length < 3)
return CmdUsage;
bool reportSurrounding = args.Length >= 4 && args[3].Equals("-s", System.StringComparison.OrdinalIgnoreCase);
Location current = handler.GetCurrentLocation();
Location targetBlockLocation = Location.Parse(current, args[0], args[1], args[2]);
Block block = handler.GetWorld().GetBlock(targetBlockLocation);
targetBlock.ToAbsolute(handler.GetCurrentLocation());
Block block = handler.GetWorld().GetBlock(targetBlock);
handler.Log.Info($"{Translations.cmd_blockinfo_BlockType}: {block.GetTypeString()}");
if (reportSurrounding)
{
StringBuilder sb = new();
sb.AppendLine($"{Translations.cmd_blockinfo_BlocksAround}:");
Block blockXPositive = handler.GetWorld().GetBlock(new Location(targetBlockLocation.X + 1, targetBlockLocation.Y, targetBlockLocation.Z));
Block blockXNegative = handler.GetWorld().GetBlock(new Location(targetBlockLocation.X - 1, targetBlockLocation.Y, targetBlockLocation.Z));
Block blockYPositive = handler.GetWorld().GetBlock(new Location(targetBlockLocation.X, targetBlockLocation.Y + 1, targetBlockLocation.Z));
Block blockYNegative = handler.GetWorld().GetBlock(new Location(targetBlockLocation.X, targetBlockLocation.Y - 1, targetBlockLocation.Z));
Block blockZPositive = handler.GetWorld().GetBlock(new Location(targetBlockLocation.X, targetBlockLocation.Y, targetBlockLocation.Z + 1));
Block blockZNegative = handler.GetWorld().GetBlock(new Location(targetBlockLocation.X, targetBlockLocation.Y, targetBlockLocation.Z - 1));
Block blockXPositive = handler.GetWorld().GetBlock(new Location(targetBlock.X + 1, targetBlock.Y, targetBlock.Z));
Block blockXNegative = handler.GetWorld().GetBlock(new Location(targetBlock.X - 1, targetBlock.Y, targetBlock.Z));
Block blockYPositive = handler.GetWorld().GetBlock(new Location(targetBlock.X, targetBlock.Y + 1, targetBlock.Z));
Block blockYNegative = handler.GetWorld().GetBlock(new Location(targetBlock.X, targetBlock.Y - 1, targetBlock.Z));
Block blockZPositive = handler.GetWorld().GetBlock(new Location(targetBlock.X, targetBlock.Y, targetBlock.Z + 1));
Block blockZNegative = handler.GetWorld().GetBlock(new Location(targetBlock.X, targetBlock.Y, targetBlock.Z - 1));
sb.AppendLine($"[X {Translations.cmd_blockinfo_Positive}] {Translations.cmd_blockinfo_BlockType}: {blockXPositive.GetTypeString()}");
sb.AppendLine($"[X {Translations.cmd_blockinfo_Negative}] {Translations.cmd_blockinfo_BlockType}: {blockXNegative.GetTypeString()}");
@ -61,9 +83,7 @@ namespace MinecraftClient.Commands
handler.Log.Info(sb.ToString());
}
return "";
return r.SetAndReturn(Status.Done);
}
}
}

View file

@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Text;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.Scripting;
namespace MinecraftClient.Commands
{
@ -11,69 +13,82 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "bots [list|unload <bot name|all>]"; } }
public override string CmdDesc { get { return Translations.cmd_bots_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
.Then(l => l.Literal("list")
.Executes(r => GetUsage(r.Source, "list")))
.Then(l => l.Literal("unload")
.Executes(r => GetUsage(r.Source, "unload")))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => DoListBot(r.Source, handler))
.Then(l => l.Literal("list")
.Executes(r => DoListBot(r.Source, handler)))
.Then(l => l.Literal("unload")
.Then(l => l.Argument("BotName", MccArguments.BotName())
.Executes(r => DoUnloadBot(r.Source, handler, Arguments.GetString(r, "BotName")))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (HasArg(command))
return r.SetAndReturn(cmd switch
{
string[] args = GetArgs(command);
#pragma warning disable format // @formatter:off
"list" => GetCmdDescTranslated(),
"unload" => GetCmdDescTranslated(),
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
if (args.Length == 1)
{
if (args[0].Equals("list", StringComparison.OrdinalIgnoreCase))
{
StringBuilder sb = new();
private int DoListBot(CmdResult r, McClient handler)
{
int length = handler.GetLoadedChatBots().Count;
if (length == 0)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_bots_noloaded);
int length = handler.GetLoadedChatBots().Count;
if (length == 0)
return Translations.cmd_bots_noloaded;
for (int i = 0; i < length; i++)
{
sb.Append(handler.GetLoadedChatBots()[i].GetType().Name);
if (i != length - 1)
sb.Append(" ,");
}
return Translations.cmd_bots_list + ": " + sb.ToString();
}
}
else if (args.Length == 2)
{
if (args[0].Equals("unload", StringComparison.OrdinalIgnoreCase))
{
string botName = args[1].Trim();
if (botName.ToLower().Equals("all", StringComparison.OrdinalIgnoreCase))
{
if (handler.GetLoadedChatBots().Count == 0)
return Translations.cmd_bots_noloaded;
handler.UnloadAllBots();
return Translations.cmd_bots_unloaded_all;
}
else
{
ChatBot? bot = handler.GetLoadedChatBots().Find(bot => bot.GetType().Name.ToLower() == botName.ToLower());
if (bot == null)
return string.Format(Translations.cmd_bots_notfound, botName);
handler.BotUnLoad(bot);
return string.Format(Translations.cmd_bots_unloaded, botName);
}
}
}
StringBuilder sb = new();
for (int i = 0; i < length; i++)
{
sb.Append(handler.GetLoadedChatBots()[i].GetType().Name);
if (i != length - 1)
sb.Append(" ,");
}
return GetCmdDescTranslated();
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_bots_list + ": " + sb.ToString());
}
private int DoUnloadBot(CmdResult r, McClient handler, string botName)
{
if (botName.ToLower().Equals("all", StringComparison.OrdinalIgnoreCase))
{
if (handler.GetLoadedChatBots().Count == 0)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_bots_noloaded);
else
{
handler.UnloadAllBots();
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_bots_unloaded_all);
}
}
else
{
ChatBot? bot = handler.GetLoadedChatBots().Find(bot => bot.GetType().Name.ToLower() == botName.ToLower());
if (bot == null)
return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_bots_notfound, botName));
else
{
handler.BotUnLoad(bot);
return r.SetAndReturn(CmdResult.Status.Done, string.Format(Translations.cmd_bots_unloaded, botName));
}
}
}
}
}

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using static MinecraftClient.CommandHandler.CmdResult;
namespace MinecraftClient.Commands
{
@ -10,39 +11,41 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "changeslot <1-9>"; } }
public override string CmdDesc { get { return Translations.cmd_changeSlot_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Argument("Slot", Arguments.Integer(1, 9))
.Executes(r => DoChangeSlot(r.Source, handler, Arguments.GetInteger(r, "Slot"))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoChangeSlot(CmdResult r, McClient handler, int slot)
{
if (!handler.GetInventoryEnabled())
return Translations.extra_inventory_required;
return r.SetAndReturn(Status.FailNeedInventory);
if (HasArg(command))
{
short slot;
try
{
slot = Convert.ToInt16(GetArg(command));
}
catch (FormatException)
{
return Translations.cmd_changeSlot_nan;
}
if (slot >= 1 && slot <= 9)
{
if (handler.ChangeSlot(slot -= 1))
{
return string.Format(Translations.cmd_changeSlot_changed, (slot += 1));
}
else
{
return Translations.cmd_changeSlot_fail;
}
}
}
return GetCmdDescTranslated();
if (handler.ChangeSlot((short)(slot - 1)))
return r.SetAndReturn(Status.Done, string.Format(Translations.cmd_changeSlot_changed, slot));
else
return r.SetAndReturn(Status.Fail, Translations.cmd_changeSlot_fail);
}
}
}

View file

@ -1,9 +1,10 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.Mapping;
using static MinecraftClient.CommandHandler.CmdResult;
namespace MinecraftClient.Commands
{
@ -13,252 +14,267 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "chunk status [chunkX chunkZ|locationX locationY locationZ]"; } }
public override string CmdDesc { get { return Translations.cmd_chunk_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
.Then(l => l.Literal("status")
.Executes(r => GetUsage(r.Source, "status")))
.Then(l => l.Literal("_setloading")
.Executes(r => GetUsage(r.Source, "_setloading")))
.Then(l => l.Literal("_setloaded")
.Executes(r => GetUsage(r.Source, "_setloaded")))
.Then(l => l.Literal("_delete")
.Executes(r => GetUsage(r.Source, "_delete")))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Literal("status")
.Executes(r => LogChunkStatus(r.Source, handler))
.Then(l => l.Argument("Location", MccArguments.Location())
.Executes(r => LogChunkStatus(r.Source, handler, pos: MccArguments.GetLocation(r, "Location"))))
.Then(l => l.Argument("Chunk", MccArguments.Tuple())
.Executes(r => LogChunkStatus(r.Source, handler, markedChunkPos: MccArguments.GetTuple(r, "Chunk")))))
.Then(l => l.Literal("_setloading")
.Then(l => l.Argument("Location", MccArguments.Location())
.Executes(r => DebugSetLoading(r.Source, handler, pos: MccArguments.GetLocation(r, "Location"))))
.Then(l => l.Argument("Chunk", MccArguments.Tuple())
.Executes(r => DebugSetLoading(r.Source, handler, markedChunkPos: MccArguments.GetTuple(r, "Chunk")))))
.Then(l => l.Literal("_setloaded")
.Then(l => l.Argument("Location", MccArguments.Location())
.Executes(r => DebugSetLoaded(r.Source, handler, pos: MccArguments.GetLocation(r, "Location"))))
.Then(l => l.Argument("Chunk", MccArguments.Tuple())
.Executes(r => DebugSetLoaded(r.Source, handler, markedChunkPos: MccArguments.GetTuple(r, "Chunk")))))
.Then(l => l.Literal("_delete")
.Then(l => l.Argument("Location", MccArguments.Location())
.Executes(r => DebugDelete(r.Source, handler, pos: MccArguments.GetLocation(r, "Location"))))
.Then(l => l.Argument("Chunk", MccArguments.Tuple())
.Executes(r => DebugDelete(r.Source, handler, markedChunkPos: MccArguments.GetTuple(r, "Chunk")))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (HasArg(command))
return r.SetAndReturn(cmd switch
{
string[] args = GetArgs(command);
if (args.Length > 0)
#pragma warning disable format // @formatter:off
"status" => GetCmdDescTranslated(),
"_setloading" => GetCmdDescTranslated(),
"_setloaded" => GetCmdDescTranslated(),
"_delete" => GetCmdDescTranslated(),
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private static int LogChunkStatus(CmdResult r, McClient handler, Location? pos = null, Tuple<int, int>? markedChunkPos = null)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
World world = handler.GetWorld();
Location current = handler.GetCurrentLocation();
if (pos.HasValue)
pos.Value.ToAbsolute(current);
(int markChunkX, int markChunkZ) = markedChunkPos ??
(pos.HasValue ? new(pos.Value.ChunkX, pos.Value.ChunkZ) : new(current.ChunkX, current.ChunkZ));
StringBuilder sb = new();
sb.Append(World.GetChunkLoadingStatus(handler.GetWorld()));
sb.Append('\n');
sb.AppendLine(string.Format(Translations.cmd_chunk_current, current, current.ChunkX, current.ChunkZ));
if (markedChunkPos != null)
{
sb.Append(Translations.cmd_chunk_marked);
if (pos.HasValue)
sb.Append(string.Format("X:{0:0.00} Y:{1:0.00} Z:{2:0.00}, ", pos.Value.X, pos.Value.Y, pos.Value.Z));
sb.AppendLine(string.Format(Translations.cmd_chunk_chunk_pos, markChunkX, markChunkZ)); ;
}
int consoleHeight = Math.Max(Math.Max(Console.BufferHeight, Settings.Config.Main.Advanced.MinTerminalHeight) - 2, 25);
if (consoleHeight % 2 == 0)
--consoleHeight;
int consoleWidth = Math.Max(Math.Max(Console.BufferWidth, Settings.Config.Main.Advanced.MinTerminalWidth) / 2, 17);
if (consoleWidth % 2 == 0)
--consoleWidth;
int startZ = current.ChunkZ - consoleHeight, endZ = current.ChunkZ + consoleHeight;
int startX = current.ChunkX - consoleWidth, endX = current.ChunkX + consoleWidth;
int leftMost = endX, rightMost = startX, topMost = endZ, bottomMost = startZ;
for (int z = startZ; z <= endZ; z++)
{
for (int x = startX; x <= endX; ++x)
{
if (args[0] == "status")
if (world[x, z] != null)
{
World world = handler.GetWorld();
Location current = handler.GetCurrentLocation();
Tuple<int, int>? markedChunkPos = ParseChunkPos(args);
(int markChunkX, int markChunkZ) = markedChunkPos ?? (new(current.ChunkX, current.ChunkZ));
StringBuilder sb = new();
sb.Append(World.GetChunkLoadingStatus(handler.GetWorld()));
sb.Append('\n');
sb.AppendLine(string.Format(Translations.cmd_chunk_current, current, current.ChunkX, current.ChunkZ));
if (markedChunkPos != null)
{
sb.Append(Translations.cmd_chunk_marked);
if (args.Length == 1 + 3)
sb.Append(String.Format("X:{0:0.00} Y:{1:0.00} Z:{2:0.00}, ",
double.Parse(args[1], NumberStyles.Any, CultureInfo.CurrentCulture),
double.Parse(args[2], NumberStyles.Any, CultureInfo.CurrentCulture),
double.Parse(args[3], NumberStyles.Any, CultureInfo.CurrentCulture)));
sb.AppendLine(string.Format(Translations.cmd_chunk_chunk_pos, markChunkX, markChunkZ));;
}
int consoleHeight = Math.Max(Math.Max(Console.BufferHeight, Settings.Config.Main.Advanced.MinTerminalHeight) - 2, 25);
if (consoleHeight % 2 == 0)
--consoleHeight;
int consoleWidth = Math.Max(Math.Max(Console.BufferWidth, Settings.Config.Main.Advanced.MinTerminalWidth) / 2, 17);
if (consoleWidth % 2 == 0)
--consoleWidth;
int startZ = current.ChunkZ - consoleHeight, endZ = current.ChunkZ + consoleHeight;
int startX = current.ChunkX - consoleWidth, endX = current.ChunkX + consoleWidth;
int leftMost = endX, rightMost = startX, topMost = endZ, bottomMost = startZ;
for (int z = startZ; z <= endZ; z++)
{
for (int x = startX; x <= endX; ++x)
{
if (world[x, z] != null)
{
leftMost = Math.Min(leftMost, x);
rightMost = Math.Max(rightMost, x);
topMost = Math.Min(topMost, z);
bottomMost = Math.Max(bottomMost, z);
}
}
}
// Include the player's location
topMost = Math.Min(topMost, current.ChunkZ);
bottomMost = Math.Max(bottomMost, current.ChunkZ);
leftMost = Math.Min(leftMost, current.ChunkX);
rightMost = Math.Max(rightMost, current.ChunkX);
// Empty one row and one column each
--leftMost; ++rightMost; --topMost; ++bottomMost;
// Resize according to limitations
if ((bottomMost - topMost + 1) > consoleHeight)
{
int delta = (bottomMost - topMost + 1) - consoleHeight;
if (bottomMost - (delta + 1) / 2 < current.ChunkZ + 1)
{
int bottomReduce = bottomMost - (current.ChunkZ + 1);
bottomMost -= bottomReduce;
topMost += delta - bottomReduce;
}
else if (topMost + delta / 2 > current.ChunkZ - 1)
{
int topAdd = topMost - (current.ChunkZ - 1);
topMost += topAdd;
bottomMost -= delta - topAdd;
}
else
{
topMost += delta / 2;
bottomMost -= (delta + 1) / 2;
}
}
if ((rightMost - leftMost + 1) > consoleWidth)
{
int delta = (rightMost - leftMost + 1) - consoleWidth;
if (rightMost - (delta + 1) / 2 < current.ChunkX + 1)
{
int rightReduce = rightMost - (current.ChunkX + 1);
rightMost -= rightReduce;
leftMost += delta - rightReduce;
}
else if (leftMost + delta / 2 > current.ChunkX - 1)
{
int leftAdd = leftMost - (current.ChunkX - 1);
leftMost += leftAdd;
rightMost -= delta - leftAdd;
}
else
{
leftMost += delta / 2;
rightMost -= (delta + 1) / 2;
}
}
// Try to include the marker chunk
if (markedChunkPos != null &&
(((Math.Max(bottomMost, markChunkZ) - Math.Min(topMost, markChunkZ) + 1) > consoleHeight) ||
((Math.Max(rightMost, markChunkX) - Math.Min(leftMost, markChunkX) + 1) > consoleWidth)))
sb.AppendLine(Translations.cmd_chunk_outside);
else
{
topMost = Math.Min(topMost, markChunkZ);
bottomMost = Math.Max(bottomMost, markChunkZ);
leftMost = Math.Min(leftMost, markChunkX);
rightMost = Math.Max(rightMost, markChunkX);
}
// \ud83d\udd33: 🔳, \ud83d\udfe8: 🟨, \ud83d\udfe9: 🟩, \u25A1: □, \u25A3: ▣, \u25A0: ■
string[] chunkStatusStr = Settings.Config.Main.Advanced.EnableEmoji ?
new string[] { "\ud83d\udd33", "\ud83d\udfe8", "\ud83d\udfe9" } : new string[] { "\u25A1", "\u25A3", "\u25A0" };
// Output
for (int z = topMost; z <= bottomMost; ++z)
{
for (int x = leftMost; x <= rightMost; ++x)
{
if (z == current.ChunkZ && x == current.ChunkX)
sb.Append("§z"); // Player Location: background gray
else if (z == markChunkZ && x == markChunkX)
sb.Append("§w"); // Marked chunk: background red
ChunkColumn? chunkColumn = world[x, z];
if (chunkColumn == null)
sb.Append(chunkStatusStr[0]);
else if (chunkColumn.FullyLoaded)
sb.Append(chunkStatusStr[2]);
else
sb.Append(chunkStatusStr[1]);
if ((z == current.ChunkZ && x == current.ChunkX) || (z == markChunkZ && x == markChunkX))
sb.Append("§r"); // Reset background color
}
sb.Append('\n');
}
sb.AppendLine(string.Format(Translations.cmd_chunk_icon, "§z §r", "§w §r", chunkStatusStr[0], chunkStatusStr[1], chunkStatusStr[2]));
return sb.ToString();
leftMost = Math.Min(leftMost, x);
rightMost = Math.Max(rightMost, x);
topMost = Math.Min(topMost, z);
bottomMost = Math.Max(bottomMost, z);
}
else if (args[0] == "setloading") // For debugging
{
Tuple<int, int>? chunkPos = ParseChunkPos(args);
if (chunkPos != null)
{
handler.Log.Info(Translations.cmd_chunk_for_debug);
World world = handler.GetWorld();
(int chunkX, int chunkZ) = chunkPos;
ChunkColumn? chunkColumn = world[chunkX, chunkZ];
if (chunkColumn != null)
chunkColumn.FullyLoaded = false;
return (chunkColumn == null) ? "Fail: chunk dosen't exist!" :
String.Format("Successfully marked chunk ({0}, {1}) as loading.", chunkX, chunkZ);
}
else
return GetCmdDescTranslated();
}
else if (args[0] == "setloaded") // For debugging
{
Tuple<int, int>? chunkPos = ParseChunkPos(args);
if (chunkPos != null)
{
handler.Log.Info(Translations.cmd_chunk_for_debug);
World world = handler.GetWorld();
(int chunkX, int chunkZ) = chunkPos;
ChunkColumn? chunkColumn = world[chunkX, chunkZ];
if (chunkColumn != null)
chunkColumn.FullyLoaded = true;
return (chunkColumn == null) ? "Fail: chunk dosen't exist!" :
String.Format("Successfully marked chunk ({0}, {1}) as loaded.", chunkX, chunkZ);
}
else
return GetCmdDescTranslated();
}
else if (args[0] == "delete") // For debugging
{
Tuple<int, int>? chunkPos = ParseChunkPos(args);
if (chunkPos != null)
{
handler.Log.Info(Translations.cmd_chunk_for_debug);
World world = handler.GetWorld();
(int chunkX, int chunkZ) = chunkPos;
world[chunkX, chunkZ] = null;
return String.Format("Successfully deleted chunk ({0}, {1}).", chunkX, chunkZ);
}
else
return GetCmdDescTranslated();
}
else
return GetCmdDescTranslated();
}
}
// Include the player's location
topMost = Math.Min(topMost, current.ChunkZ);
bottomMost = Math.Max(bottomMost, current.ChunkZ);
leftMost = Math.Min(leftMost, current.ChunkX);
rightMost = Math.Max(rightMost, current.ChunkX);
// Empty one row and one column each
--leftMost; ++rightMost; --topMost; ++bottomMost;
// Resize according to limitations
if ((bottomMost - topMost + 1) > consoleHeight)
{
int delta = (bottomMost - topMost + 1) - consoleHeight;
if (bottomMost - (delta + 1) / 2 < current.ChunkZ + 1)
{
int bottomReduce = bottomMost - (current.ChunkZ + 1);
bottomMost -= bottomReduce;
topMost += delta - bottomReduce;
}
else if (topMost + delta / 2 > current.ChunkZ - 1)
{
int topAdd = topMost - (current.ChunkZ - 1);
topMost += topAdd;
bottomMost -= delta - topAdd;
}
else
return GetCmdDescTranslated();
{
topMost += delta / 2;
bottomMost -= (delta + 1) / 2;
}
}
if ((rightMost - leftMost + 1) > consoleWidth)
{
int delta = (rightMost - leftMost + 1) - consoleWidth;
if (rightMost - (delta + 1) / 2 < current.ChunkX + 1)
{
int rightReduce = rightMost - (current.ChunkX + 1);
rightMost -= rightReduce;
leftMost += delta - rightReduce;
}
else if (leftMost + delta / 2 > current.ChunkX - 1)
{
int leftAdd = leftMost - (current.ChunkX - 1);
leftMost += leftAdd;
rightMost -= delta - leftAdd;
}
else
{
leftMost += delta / 2;
rightMost -= (delta + 1) / 2;
}
}
// Try to include the marker chunk
if (markedChunkPos != null &&
(((Math.Max(bottomMost, markChunkZ) - Math.Min(topMost, markChunkZ) + 1) > consoleHeight) ||
((Math.Max(rightMost, markChunkX) - Math.Min(leftMost, markChunkX) + 1) > consoleWidth)))
sb.AppendLine(Translations.cmd_chunk_outside);
else
return GetCmdDescTranslated();
{
topMost = Math.Min(topMost, markChunkZ);
bottomMost = Math.Max(bottomMost, markChunkZ);
leftMost = Math.Min(leftMost, markChunkX);
rightMost = Math.Max(rightMost, markChunkX);
}
// \ud83d\udd33: 🔳, \ud83d\udfe8: 🟨, \ud83d\udfe9: 🟩, \u25A1: □, \u25A3: ▣, \u25A0: ■
string[] chunkStatusStr = Settings.Config.Main.Advanced.EnableEmoji ?
new string[] { "\ud83d\udd33", "\ud83d\udfe8", "\ud83d\udfe9" } : new string[] { "\u25A1", "\u25A3", "\u25A0" };
// Output
for (int z = topMost; z <= bottomMost; ++z)
{
for (int x = leftMost; x <= rightMost; ++x)
{
if (z == current.ChunkZ && x == current.ChunkX)
sb.Append("§z"); // Player Location: background gray
else if (z == markChunkZ && x == markChunkX)
sb.Append("§w"); // Marked chunk: background red
ChunkColumn? chunkColumn = world[x, z];
if (chunkColumn == null)
sb.Append(chunkStatusStr[0]);
else if (chunkColumn.FullyLoaded)
sb.Append(chunkStatusStr[2]);
else
sb.Append(chunkStatusStr[1]);
if ((z == current.ChunkZ && x == current.ChunkX) || (z == markChunkZ && x == markChunkX))
sb.Append("§r"); // Reset background color
}
sb.Append('\n');
}
sb.Append(string.Format(Translations.cmd_chunk_icon, "§z §r", "§w §r", chunkStatusStr[0], chunkStatusStr[1], chunkStatusStr[2]));
handler.Log.Info(sb.ToString());
return r.SetAndReturn(Status.Done);
}
private static Tuple<int, int>? ParseChunkPos(string[] args)
private static int DebugSetLoading(CmdResult r, McClient handler, Location? pos = null, Tuple<int, int>? markedChunkPos = null)
{
try
{
int chunkX, chunkZ;
if (args.Length == 1 + 3)
{
Location pos = new(
double.Parse(args[1], NumberStyles.Any, CultureInfo.CurrentCulture),
double.Parse(args[2], NumberStyles.Any, CultureInfo.CurrentCulture),
double.Parse(args[3], NumberStyles.Any, CultureInfo.CurrentCulture)
);
chunkX = pos.ChunkX;
chunkZ = pos.ChunkZ;
}
else if (args.Length == 1 + 2)
{
chunkX = int.Parse(args[1], NumberStyles.Any, CultureInfo.CurrentCulture);
chunkZ = int.Parse(args[2], NumberStyles.Any, CultureInfo.CurrentCulture);
}
else
return null;
return new(chunkX, chunkZ);
}
catch (FormatException)
{
return null;
}
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
if (pos.HasValue)
pos.Value.ToAbsolute(handler.GetCurrentLocation());
handler.Log.Info(Translations.cmd_chunk_for_debug);
(int chunkX, int chunkZ) = markedChunkPos ?? new(pos!.Value.ChunkX, pos!.Value.ChunkZ);
ChunkColumn? chunkColumn = handler.GetWorld()[chunkX, chunkZ];
if (chunkColumn != null)
chunkColumn.FullyLoaded = false;
if (chunkColumn == null)
return r.SetAndReturn(Status.Fail, "Fail: chunk dosen't exist!");
else
return r.SetAndReturn(Status.Done, string.Format("Successfully marked chunk ({0}, {1}) as loading.", chunkX, chunkZ));
}
private static int DebugSetLoaded(CmdResult r, McClient handler, Location? pos = null, Tuple<int, int>? markedChunkPos = null)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
if (pos.HasValue)
pos.Value.ToAbsolute(handler.GetCurrentLocation());
handler.Log.Info(Translations.cmd_chunk_for_debug);
(int chunkX, int chunkZ) = markedChunkPos ?? new(pos!.Value.ChunkX, pos!.Value.ChunkZ);
ChunkColumn? chunkColumn = handler.GetWorld()[chunkX, chunkZ];
if (chunkColumn != null)
chunkColumn.FullyLoaded = false;
if (chunkColumn == null)
return r.SetAndReturn(Status.Fail, "Fail: chunk dosen't exist!");
else
return r.SetAndReturn(Status.Done, string.Format("Successfully marked chunk ({0}, {1}) as loaded.", chunkX, chunkZ));
}
private static int DebugDelete(CmdResult r, McClient handler, Location? pos = null, Tuple<int, int>? markedChunkPos = null)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
if (pos.HasValue)
pos.Value.ToAbsolute(handler.GetCurrentLocation());
handler.Log.Info(Translations.cmd_chunk_for_debug);
(int chunkX, int chunkZ) = markedChunkPos ?? new(pos!.Value.ChunkX, pos!.Value.ChunkZ);
handler.GetWorld()[chunkX, chunkZ] = null;
return r.SetAndReturn(Status.Done, string.Format("Successfully deleted chunk ({0}, {1}).", chunkX, chunkZ));
}
}
}

View file

@ -1,13 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinecraftClient.Commands
{
public class CommandSource
{
public string UserName { get; set; } = string.Empty;
}
}

View file

@ -1,5 +1,7 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using static MinecraftClient.CommandHandler.CmdResult;
namespace MinecraftClient.Commands
{
@ -9,31 +11,65 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "connect <server> [account]"; } }
public override string CmdDesc { get { return Translations.cmd_connect_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Argument("ServerNick", MccArguments.ServerNick())
.Executes(r => DoConnect(r.Source, handler, Arguments.GetString(r, "ServerNick"), string.Empty))
.Then(l => l.Argument("AccountNick", MccArguments.AccountNick())
.Executes(r => DoConnect(r.Source, handler, Arguments.GetString(r, "ServerNick"), Arguments.GetString(r, "AccountNick")))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient? handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (HasArg(command))
return r.SetAndReturn(cmd switch
{
string[] args = GetArgs(command);
if (args.Length > 1)
{
if (!Settings.Config.Main.Advanced.SetAccount(args[1]))
{
return string.Format(Translations.cmd_connect_unknown, args[1]);
}
}
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
if (Settings.Config.Main.SetServerIP(new Settings.MainConfigHealper.MainConfig.ServerInfoConfig(args[0]), true))
{
Program.Restart(keepAccountAndServerSettings: true);
return "";
}
else return string.Format(Translations.cmd_connect_invalid_ip, args[0]);
private int DoConnect(CmdResult r, McClient handler, string server, string account)
{
if (!string.IsNullOrWhiteSpace(account) && !Settings.Config.Main.Advanced.SetAccount(account))
return r.SetAndReturn(Status.Fail, string.Format(Translations.cmd_connect_unknown, account));
if (Settings.Config.Main.SetServerIP(new Settings.MainConfigHealper.MainConfig.ServerInfoConfig(server), true))
{
Program.Restart(keepAccountAndServerSettings: true);
return r.SetAndReturn(Status.Done);
}
else
{
return r.SetAndReturn(Status.Fail, string.Format(Translations.cmd_connect_invalid_ip, server));
}
}
internal static string DoConnect(string command)
{
string[] args = GetArgs(command);
if (args.Length > 1 && !Settings.Config.Main.Advanced.SetAccount(args[1]))
return string.Format(Translations.cmd_connect_unknown, args[1]);
if (Settings.Config.Main.SetServerIP(new Settings.MainConfigHealper.MainConfig.ServerInfoConfig(args[0]), true))
{
Program.Restart(keepAccountAndServerSettings: true);
return string.Empty;
}
else
{
return string.Format(Translations.cmd_connect_invalid_ip, args[0]);
}
else return GetCmdDescTranslated();
}
}
}

View file

@ -1,5 +1,6 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -9,20 +10,46 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "debug [on|off]"; } }
public override string CmdDesc { get { return Translations.cmd_debug_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => SetDebugMode(r.Source, true))
.Then(l => l.Literal("on")
.Executes(r => SetDebugMode(r.Source, false, true)))
.Then(l => l.Literal("off")
.Executes(r => SetDebugMode(r.Source, false, false)))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (HasArg(command))
Settings.Config.Logging.DebugMessages = (GetArg(command).ToLower() == "on");
else
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int SetDebugMode(CmdResult r, bool flip, bool mode = false)
{
if (flip)
Settings.Config.Logging.DebugMessages = !Settings.Config.Logging.DebugMessages;
if (Settings.Config.Logging.DebugMessages)
return Translations.cmd_debug_state_on;
else
return Translations.cmd_debug_state_off;
Settings.Config.Logging.DebugMessages = mode;
if (Settings.Config.Logging.DebugMessages)
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_debug_state_on);
else
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_debug_state_off);
}
}
}

View file

@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.Mapping;
using static MinecraftClient.CommandHandler.CmdResult;
namespace MinecraftClient.Commands
{
@ -11,53 +13,68 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "dig <x> <y> <z>"; } }
public override string CmdDesc { get { return Translations.cmd_dig_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => DigLookAt(r.Source, handler))
.Then(l => l.Argument("Location", MccArguments.Location())
.Executes(r => DigAt(r.Source, handler, MccArguments.GetLocation(r, "Location"))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DigAt(CmdResult r, McClient handler, Location blockToBreak)
{
if (!handler.GetTerrainEnabled())
return Translations.extra_terrainandmovement_required;
return r.SetAndReturn(Status.FailNeedTerrain);
string[] args = GetArgs(command);
if (args.Length == 0)
Location current = handler.GetCurrentLocation();
blockToBreak = blockToBreak.ToAbsolute(current);
if (blockToBreak.DistanceSquared(current.EyesLocation()) > 25)
return r.SetAndReturn(Status.Fail, Translations.cmd_dig_too_far);
Block block = handler.GetWorld().GetBlock(blockToBreak);
if (block.Type == Material.Air)
return r.SetAndReturn(Status.Fail, Translations.cmd_dig_no_block);
else if (handler.DigBlock(blockToBreak))
{
(bool hasBlock, Location blockLoc, Block block) = RaycastHelper.RaycastBlock(handler, 4.5, false);
if (!hasBlock)
return Translations.cmd_dig_too_far;
else if (block.Type == Material.Air)
return Translations.cmd_dig_no_block;
else if (handler.DigBlock(blockLoc, lookAtBlock: false))
return string.Format(Translations.cmd_dig_dig, blockLoc.X, blockLoc.Y, blockLoc.Z, block.GetTypeString());
else
return Translations.cmd_dig_fail;
}
else if (args.Length == 3)
{
try
{
Location current = handler.GetCurrentLocation();
Location blockToBreak = Location.Parse(current.ToFloor(), args[0], args[1], args[2]);
if (blockToBreak.DistanceSquared(current.EyesLocation()) > 25)
return Translations.cmd_dig_too_far;
Block block = handler.GetWorld().GetBlock(blockToBreak);
if (block.Type == Material.Air)
return Translations.cmd_dig_no_block;
else if (handler.DigBlock(blockToBreak))
{
blockToBreak = blockToBreak.ToCenter();
return string.Format(Translations.cmd_dig_dig, blockToBreak.X, blockToBreak.Y, blockToBreak.Z, block.GetTypeString());
}
else
return Translations.cmd_dig_fail;
}
catch (FormatException) { return GetCmdDescTranslated(); }
blockToBreak = blockToBreak.ToCenter();
return r.SetAndReturn(Status.Done, string.Format(Translations.cmd_dig_dig, blockToBreak.X, blockToBreak.Y, blockToBreak.Z, block.GetTypeString()));
}
else
{
return GetCmdDescTranslated();
}
return r.SetAndReturn(Status.Fail, Translations.cmd_dig_fail);
}
private int DigLookAt(CmdResult r, McClient handler)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
(bool hasBlock, Location blockLoc, Block block) = RaycastHelper.RaycastBlock(handler, 4.5, false);
if (!hasBlock)
return r.SetAndReturn(Status.Fail, Translations.cmd_dig_too_far);
else if (block.Type == Material.Air)
return r.SetAndReturn(Status.Fail, Translations.cmd_dig_no_block);
else if (handler.DigBlock(blockLoc, lookAtBlock: false))
return r.SetAndReturn(Status.Done, string.Format(Translations.cmd_dig_dig, blockLoc.X, blockLoc.Y, blockLoc.Z, block.GetTypeString()));
else
return r.SetAndReturn(Status.Fail, Translations.cmd_dig_fail);
}
}
}

View file

@ -1,57 +1,64 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.Inventory;
using static MinecraftClient.CommandHandler.CmdResult;
namespace MinecraftClient.Commands
{
class DropItem : Command
{
public override string CmdName { get { return "dropitem"; } }
public override string CmdUsage { get { return "/dropitem <itemtype>"; } }
public override string CmdUsage { get { return "dropitem <itemtype>"; } }
public override string CmdDesc { get { return Translations.cmd_dropItem_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Argument("ItemType", MccArguments.ItemType())
.Executes(r => DoDropItem(r.Source, handler, MccArguments.GetItemType(r, "ItemType"))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoDropItem(CmdResult r, McClient handler, ItemType itemType)
{
if (!handler.GetInventoryEnabled())
{
return Translations.extra_inventory_required;
}
if (HasArg(command))
{
string arg = GetArg(command);
if (Enum.TryParse(arg, true, out ItemType itemType))
{
int inventoryId;
var inventories = handler.GetInventories();
List<int> availableIds = inventories.Keys.ToList();
availableIds.Remove(0); // remove player inventory ID from list
if (availableIds.Count == 1)
inventoryId = availableIds[0]; // one container, use it
else
inventoryId = 0;
var p = inventories[inventoryId];
int[] targetItems = p.SearchItem(itemType);
foreach (int slot in targetItems)
{
handler.DoWindowAction(inventoryId, slot, WindowActionType.DropItemStack);
}
return string.Format(Translations.cmd_dropItem_dropped, itemType.ToString(), inventoryId);
}
else
{
return string.Format(Translations.cmd_dropItem_unknown_item, arg);
}
}
return r.SetAndReturn(Status.FailNeedTerrain);
int inventoryId;
var inventories = handler.GetInventories();
List<int> availableIds = inventories.Keys.ToList();
availableIds.Remove(0); // remove player inventory ID from list
if (availableIds.Count == 1)
inventoryId = availableIds[0]; // one container, use it
else
{
return CmdUsage;
}
inventoryId = 0;
var p = inventories[inventoryId];
int[] targetItems = p.SearchItem(itemType);
foreach (int slot in targetItems)
handler.DoWindowAction(inventoryId, slot, WindowActionType.DropItemStack);
return r.SetAndReturn(Status.Done, string.Format(Translations.cmd_dropItem_dropped, Item.GetTypeString(itemType), inventoryId));
}
}
}

View file

@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Linq;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.Inventory;
namespace MinecraftClient.Commands
@ -11,80 +12,96 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "enchant <top|middle|bottom>"; } }
public override string CmdDesc { get { return Translations.cmd_enchant_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
.Then(l => l.Literal("top")
.Executes(r => GetUsage(r.Source, "top")))
.Then(l => l.Literal("middle")
.Executes(r => GetUsage(r.Source, "middle")))
.Then(l => l.Literal("bottom")
.Executes(r => GetUsage(r.Source, "bottom")))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Literal("top")
.Executes(r => DoEnchant(r.Source, handler, slotId: 0)))
.Then(l => l.Literal("middle")
.Executes(r => DoEnchant(r.Source, handler, slotId: 1)))
.Then(l => l.Literal("bottom")
.Executes(r => DoEnchant(r.Source, handler, slotId: 2)))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (!handler.GetInventoryEnabled())
return Translations.error_inventoryhandling_not_enabled;
if (HasArg(command))
return r.SetAndReturn(cmd switch
{
string slot = GetArg(command).ToLower().Trim();
#pragma warning disable format // @formatter:off
"top" => GetCmdDescTranslated(),
"middle" => GetCmdDescTranslated(),
"bottom" => GetCmdDescTranslated(),
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
int slotId = slot switch
private int DoEnchant(CmdResult r, McClient handler, int slotId)
{
Container? enchantingTable = null;
foreach (var (id, container) in handler.GetInventories())
{
if (container.Type == ContainerType.Enchantment)
{
"top" => 0,
"middle" => 1,
"bottom" => 2,
_ => -1
};
if (slotId == -1)
return Translations.cmd_enchant_invalid_slot;
Container? enchantingTable = null;
foreach (var (id, container) in handler.GetInventories())
{
if (container.Type == ContainerType.Enchantment)
{
enchantingTable = container;
break;
}
enchantingTable = container;
break;
}
if (enchantingTable == null)
return Translations.cmd_enchant_enchanting_table_not_opened;
int[] emptySlots = enchantingTable.GetEmpytSlots();
if (emptySlots.Contains(0))
return Translations.cmd_enchant_enchanting_no_item;
if (emptySlots.Contains(1))
return Translations.cmd_enchant_enchanting_no_lapis;
Item lapisSlot = enchantingTable.Items[1];
if (lapisSlot.Type != ItemType.LapisLazuli)
return Translations.cmd_enchant_enchanting_no_lapis;
if (lapisSlot.Count < 3)
return Translations.cmd_enchant_enchanting_no_lapis;
EnchantmentData? enchantment = handler.GetLastEnchantments();
if (enchantment == null)
return Translations.cmd_enchant_no_enchantments;
short requiredLevel = slotId switch
{
0 => enchantment.TopEnchantmentLevelRequirement,
1 => enchantment.MiddleEnchantmentLevelRequirement,
2 => enchantment.BottomEnchantmentLevelRequirement,
_ => 9999
};
if (handler.GetLevel() < requiredLevel)
return string.Format(Translations.cmd_enchant_no_levels, handler.GetLevel(), requiredLevel);
return handler.ClickContainerButton(enchantingTable.ID, slotId) ? Translations.cmd_enchant_clicked : Translations.cmd_enchant_not_clicked;
}
return GetCmdDescTranslated();
if (enchantingTable == null)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_enchant_enchanting_table_not_opened);
int[] emptySlots = enchantingTable.GetEmpytSlots();
if (emptySlots.Contains(0))
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_enchant_enchanting_no_item);
if (emptySlots.Contains(1))
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_enchant_enchanting_no_lapis);
Item lapisSlot = enchantingTable.Items[1];
if (lapisSlot.Type != ItemType.LapisLazuli || lapisSlot.Count < 3)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_enchant_enchanting_no_lapis);
EnchantmentData? enchantment = handler.GetLastEnchantments();
if (enchantment == null)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_enchant_no_enchantments);
short requiredLevel = slotId switch
{
0 => enchantment.TopEnchantmentLevelRequirement,
1 => enchantment.MiddleEnchantmentLevelRequirement,
2 => enchantment.BottomEnchantmentLevelRequirement,
_ => 9999
};
if (handler.GetLevel() < requiredLevel)
return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_enchant_no_levels, handler.GetLevel(), requiredLevel));
else
{
if (handler.ClickContainerButton(enchantingTable.ID, slotId))
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_enchant_clicked);
else
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_enchant_not_clicked);
}
}
}
}

View file

@ -1,172 +1,321 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.Inventory;
using MinecraftClient.Mapping;
using static MinecraftClient.CommandHandler.CmdResult;
namespace MinecraftClient.Commands
{
class Entitycmd : Command
{
public override string CmdName { get { return "entity"; } }
public override string CmdUsage { get { return "entity <id|entitytype> <attack|use>"; } }
public override string CmdUsage { get { return "entity [near] <id|entitytype> <attack|use>"; } }
public override string CmdDesc { get { return string.Empty; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
private enum ActionType { Attack, Use, List };
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
.Then(l => l.Literal("near")
.Executes(r => GetUsage(r.Source, "near")))
.Then(l => l.Literal("attack")
.Executes(r => GetUsage(r.Source, "attack")))
.Then(l => l.Literal("use")
.Executes(r => GetUsage(r.Source, "use")))
.Then(l => l.Literal("list")
.Executes(r => GetUsage(r.Source, "list")))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => GetFullEntityList(r.Source, handler))
.Then(l => l.Literal("near")
.Executes(r => GetClosetEntityList(r.Source, handler))
.Then(l => l.Argument("EntityID", Arguments.Integer())
.Executes(r => OperateWithId(r.Source, handler, Arguments.GetInteger(r, "EntityID"), ActionType.List))
.Then(l => l.Literal("attack")
.Executes(r => OperateWithId(r.Source, handler, Arguments.GetInteger(r, "EntityID"), ActionType.Attack)))
.Then(l => l.Literal("use")
.Executes(r => OperateWithId(r.Source, handler, Arguments.GetInteger(r, "EntityID"), ActionType.Use)))
.Then(l => l.Literal("list")
.Executes(r => OperateWithId(r.Source, handler, Arguments.GetInteger(r, "EntityID"), ActionType.List))))
.Then(l => l.Argument("EntityType", MccArguments.EntityType())
.Executes(r => OperateWithType(r.Source, handler, true, MccArguments.GetEntityType(r, "EntityType"), ActionType.List))
.Then(l => l.Literal("attack")
.Executes(r => OperateWithType(r.Source, handler, near: true, MccArguments.GetEntityType(r, "EntityType"), ActionType.Attack)))
.Then(l => l.Literal("use")
.Executes(r => OperateWithType(r.Source, handler, near: true, MccArguments.GetEntityType(r, "EntityType"), ActionType.Use)))
.Then(l => l.Literal("list")
.Executes(r => OperateWithType(r.Source, handler, near: true, MccArguments.GetEntityType(r, "EntityType"), ActionType.List)))))
.Then(l => l.Argument("EntityID", Arguments.Integer())
.Executes(r => OperateWithId(r.Source, handler, Arguments.GetInteger(r, "EntityID"), ActionType.List))
.Then(l => l.Literal("attack")
.Executes(r => OperateWithId(r.Source, handler, Arguments.GetInteger(r, "EntityID"), ActionType.Attack)))
.Then(l => l.Literal("use")
.Executes(r => OperateWithId(r.Source, handler, Arguments.GetInteger(r, "EntityID"), ActionType.Use)))
.Then(l => l.Literal("list")
.Executes(r => OperateWithId(r.Source, handler, Arguments.GetInteger(r, "EntityID"), ActionType.List))))
.Then(l => l.Argument("EntityType", MccArguments.EntityType())
.Executes(r => OperateWithType(r.Source, handler, true, MccArguments.GetEntityType(r, "EntityType"), ActionType.List))
.Then(l => l.Literal("attack")
.Executes(r => OperateWithType(r.Source, handler, near: false, MccArguments.GetEntityType(r, "EntityType"), ActionType.Attack)))
.Then(l => l.Literal("use")
.Executes(r => OperateWithType(r.Source, handler, near: false, MccArguments.GetEntityType(r, "EntityType"), ActionType.Use)))
.Then(l => l.Literal("list")
.Executes(r => OperateWithType(r.Source, handler, near: false, MccArguments.GetEntityType(r, "EntityType"), ActionType.List))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (handler.GetEntityHandlingEnabled())
return r.SetAndReturn(cmd switch
{
string[] args = GetArgs(command);
if (args.Length >= 1)
#pragma warning disable format // @formatter:off
"near" => GetCmdDescTranslated(),
"attack" => GetCmdDescTranslated(),
"use" => GetCmdDescTranslated(),
"list" => GetCmdDescTranslated(),
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int GetFullEntityList(CmdResult r, McClient handler)
{
if (!handler.GetEntityHandlingEnabled())
return r.SetAndReturn(Status.FailNeedEntity);
Dictionary<int, Entity> entities = handler.GetEntities();
StringBuilder response = new();
response.AppendLine(Translations.cmd_entityCmd_entities);
foreach (var entity2 in entities)
response.AppendLine(GetEntityInfoShort(entity2.Value));
response.Append(GetCmdDescTranslated());
handler.Log.Info(response.ToString());
return r.SetAndReturn(Status.Done);
}
private int GetClosetEntityList(CmdResult r, McClient handler)
{
if (!handler.GetEntityHandlingEnabled())
return r.SetAndReturn(Status.FailNeedEntity);
if (TryGetClosetEntity(handler.GetEntities(), handler.GetCurrentLocation(), null, out Entity? closest))
{
handler.Log.Info(GetEntityInfoDetailed(handler, closest));
return r.SetAndReturn(Status.Done);
}
else
return r.SetAndReturn(Status.Fail, Translations.cmd_entityCmd_not_found);
}
private int OperateWithId(CmdResult r, McClient handler, int entityID, ActionType action)
{
if (!handler.GetEntityHandlingEnabled())
return r.SetAndReturn(Status.FailNeedEntity);
if (handler.GetEntities().TryGetValue(entityID, out Entity? entity))
{
handler.Log.Info(InteractionWithEntity(handler, entity, action));
return r.SetAndReturn(Status.Done);
}
else
return r.SetAndReturn(Status.Fail, Translations.cmd_entityCmd_not_found);
}
private int OperateWithType(CmdResult r, McClient handler, bool near, EntityType entityType, ActionType action)
{
if (!handler.GetEntityHandlingEnabled())
return r.SetAndReturn(Status.FailNeedEntity);
if (near)
{
if (TryGetClosetEntity(handler.GetEntities(), handler.GetCurrentLocation(), entityType, out Entity? closest))
{
try
handler.Log.Info(InteractionWithEntity(handler, closest, action));
return r.SetAndReturn(Status.Done);
}
else
return r.SetAndReturn(Status.Fail, Translations.cmd_entityCmd_not_found);
}
else
{
if (action == ActionType.Attack || action == ActionType.Use)
{
string actionst = Translations.cmd_entityCmd_attacked;
int actioncount = 0;
foreach (var entity2 in handler.GetEntities())
{
int entityID = int.Parse(args[0], NumberStyles.Any, CultureInfo.CurrentCulture);
if (entityID != 0)
if (entity2.Value.Type == entityType)
{
if (handler.GetEntities().ContainsKey(entityID))
if (action == ActionType.Attack)
{
string action = args.Length > 1
? args[1].ToLower()
: "list";
switch (action)
{
case "attack":
handler.InteractEntity(entityID, InteractType.Attack);
return Translations.cmd_entityCmd_attacked;
case "use":
handler.InteractEntity(entityID, InteractType.Interact);
return Translations.cmd_entityCmd_used;
default:
Entity entity = handler.GetEntities()[entityID];
int id = entity.ID;
float health = entity.Health;
int latency = entity.Latency;
Item item = entity.Item;
string? nickname = entity.Name;
string? customname = entity.CustomName;
EntityPose pose = entity.Pose;
EntityType type = entity.Type;
double distance = Math.Round(entity.Location.Distance(handler.GetCurrentLocation()), 2);
string color = "§a"; // Green
if (health < 10)
color = "§c"; // Red
else if (health < 15)
color = "§e"; // Yellow
string location = $"X:{Math.Round(entity.Location.X, 2)}, Y:{Math.Round(entity.Location.Y, 2)}, Z:{Math.Round(entity.Location.Z, 2)}";
StringBuilder done = new();
done.Append($"{Translations.cmd_entityCmd_entity}: {id}\n [MCC] Type: {entity.GetTypeString()}");
if (!string.IsNullOrEmpty(nickname))
done.Append($"\n [MCC] {Translations.cmd_entityCmd_nickname}: {nickname}");
else if (!string.IsNullOrEmpty(customname))
done.Append($"\n [MCC] {Translations.cmd_entityCmd_customname}: {customname.Replace("&", "§")}§8");
if (type == EntityType.Player)
done.Append($"\n [MCC] {Translations.cmd_entityCmd_latency}: {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)
{
string? displayName = item.DisplayName;
if (string.IsNullOrEmpty(displayName))
done.Append($"\n [MCC] {Translations.cmd_entityCmd_item}: {item.GetTypeString()} x{item.Count}");
else
done.Append($"\n [MCC] {Translations.cmd_entityCmd_item}: {item.GetTypeString()} x{item.Count} - {displayName}§8");
}
if (entity.Equipment.Count >= 1 && entity.Equipment != null)
{
done.Append($"\n [MCC] {Translations.cmd_entityCmd_equipment}:");
if (entity.Equipment.ContainsKey(0) && entity.Equipment[0] != null)
done.Append($"\n [MCC] {Translations.cmd_entityCmd_mainhand}: {entity.Equipment[0].GetTypeString()} x{entity.Equipment[0].Count}");
if (entity.Equipment.ContainsKey(1) && entity.Equipment[1] != null)
done.Append($"\n [MCC] {Translations.cmd_entityCmd_offhand}: {entity.Equipment[1].GetTypeString()} x{entity.Equipment[1].Count}");
if (entity.Equipment.ContainsKey(5) && entity.Equipment[5] != null)
done.Append($"\n [MCC] {Translations.cmd_entityCmd_helmet}: {entity.Equipment[5].GetTypeString()} x{entity.Equipment[5].Count}");
if (entity.Equipment.ContainsKey(4) && entity.Equipment[4] != null)
done.Append($"\n [MCC] {Translations.cmd_entityCmd_chestplate}: {entity.Equipment[4].GetTypeString()} x{entity.Equipment[4].Count}");
if (entity.Equipment.ContainsKey(3) && entity.Equipment[3] != null)
done.Append($"\n [MCC] {Translations.cmd_entityCmd_leggings}: {entity.Equipment[3].GetTypeString()} x{entity.Equipment[3].Count}");
if (entity.Equipment.ContainsKey(2) && entity.Equipment[2] != null)
done.Append($"\n [MCC] {Translations.cmd_entityCmd_boots}: {entity.Equipment[2].GetTypeString()} x{entity.Equipment[2].Count}");
}
done.Append($"\n [MCC] {Translations.cmd_entityCmd_pose}: {pose}");
done.Append($"\n [MCC] {Translations.cmd_entityCmd_health}: {color}{health}§8");
done.Append($"\n [MCC] {Translations.cmd_entityCmd_distance}: {distance}");
done.Append($"\n [MCC] {Translations.cmd_entityCmd_location}: {location}");
return done.ToString();
}
handler.InteractEntity(entity2.Key, InteractType.Attack);
actionst = Translations.cmd_entityCmd_attacked;
}
else return Translations.cmd_entityCmd_not_found;
}
else
{
EntityType interacttype = Enum.Parse<EntityType>(args[0]);
string actionst = Translations.cmd_entityCmd_attacked;
int actioncount = 0;
foreach (var entity2 in handler.GetEntities())
else if (action == ActionType.Use)
{
if (entity2.Value.Type == interacttype)
{
string action = args.Length > 1
? args[1].ToLower()
: "list";
if (action == "attack")
{
handler.InteractEntity(entity2.Key, InteractType.Attack);
actionst = Translations.cmd_entityCmd_attacked;
actioncount++;
}
else if (action == "use")
{
handler.InteractEntity(entity2.Key, InteractType.Interact);
actionst = Translations.cmd_entityCmd_used;
actioncount++;
}
else return GetCmdDescTranslated();
}
handler.InteractEntity(entity2.Key, InteractType.Interact);
actionst = Translations.cmd_entityCmd_used;
}
return actioncount + " " + actionst;
actioncount++;
}
}
catch (FormatException) { return GetCmdDescTranslated(); }
handler.Log.Info(actioncount + " " + actionst);
return r.SetAndReturn(Status.Done);
}
else
{
Dictionary<int, Entity> entities = handler.GetEntities();
StringBuilder response = new();
response.AppendLine(Translations.cmd_entityCmd_entities);
foreach (var entity2 in entities)
foreach (var entity2 in handler.GetEntities())
{
int id = entity2.Key;
float health = entity2.Value.Health;
int latency = entity2.Value.Latency;
string? nickname = entity2.Value.Name;
string? customname = entity2.Value.CustomName;
EntityPose pose = entity2.Value.Pose;
EntityType type = entity2.Value.Type;
Item item = entity2.Value.Item;
string location = $"X:{Math.Round(entity2.Value.Location.X, 2)}, Y:{Math.Round(entity2.Value.Location.Y, 2)}, Z:{Math.Round(entity2.Value.Location.Z, 2)}";
if (type == EntityType.Item || type == EntityType.ItemFrame || type == EntityType.EyeOfEnder || type == EntityType.Egg || type == EntityType.EnderPearl || type == EntityType.Potion || type == EntityType.Fireball || type == EntityType.FireworkRocket)
response.AppendLine($" #{id}: {Translations.cmd_entityCmd_type}: {entity2.Value.GetTypeString()}, {Translations.cmd_entityCmd_item}: {item.GetTypeString()}, {Translations.cmd_entityCmd_location}: {location}");
else if (type == EntityType.Player && !string.IsNullOrEmpty(nickname))
response.AppendLine($" #{id}: {Translations.cmd_entityCmd_type}: {entity2.Value.GetTypeString()}, {Translations.cmd_entityCmd_nickname}: §8{nickname}§8, {Translations.cmd_entityCmd_latency}: {latency}, {Translations.cmd_entityCmd_health}: {health}, {Translations.cmd_entityCmd_pose}: {pose}, {Translations.cmd_entityCmd_location}: {location}");
else if (type == EntityType.Player && !string.IsNullOrEmpty(customname))
response.AppendLine($" #{id}: {Translations.cmd_entityCmd_type}: {entity2.Value.GetTypeString()}, {Translations.cmd_entityCmd_customname}: §8{customname.Replace("&", "§")}§8, {Translations.cmd_entityCmd_latency}: {latency}, {Translations.cmd_entityCmd_health}: {health}, {Translations.cmd_entityCmd_pose}: {pose}, {Translations.cmd_entityCmd_location}: {location}");
else
response.AppendLine($" #{id}: {Translations.cmd_entityCmd_type}: {entity2.Value.GetTypeString()}, {Translations.cmd_entityCmd_health}: {health}, {Translations.cmd_entityCmd_location}: {location}");
if (entity2.Value.Type == entityType)
{
response.AppendLine(GetEntityInfoShort(entity2.Value));
}
}
response.Append(GetCmdDescTranslated());
return response.ToString();
handler.Log.Info(response.ToString());
return r.SetAndReturn(Status.Done);
}
}
else return Translations.extra_entity_required;
}
private static string GetEntityInfoShort(Entity entity)
{
int id = entity.ID;
float health = entity.Health;
int latency = entity.Latency;
string? nickname = entity.Name;
string? customname = entity.CustomName;
EntityPose pose = entity.Pose;
EntityType type = entity.Type;
Item item = entity.Item;
string location = $"X:{Math.Round(entity.Location.X, 2)}, Y:{Math.Round(entity.Location.Y, 2)}, Z:{Math.Round(entity.Location.Z, 2)}";
if (type == EntityType.Item || type == EntityType.ItemFrame || type == EntityType.EyeOfEnder || type == EntityType.Egg || type == EntityType.EnderPearl || type == EntityType.Potion || type == EntityType.Fireball || type == EntityType.FireworkRocket)
return $" #{id}: {Translations.cmd_entityCmd_type}: {entity.GetTypeString()}, {Translations.cmd_entityCmd_item}: {item.GetTypeString()}, {Translations.cmd_entityCmd_location}: {location}";
else if (type == EntityType.Player && !string.IsNullOrEmpty(nickname))
return $" #{id}: {Translations.cmd_entityCmd_type}: {entity.GetTypeString()}, {Translations.cmd_entityCmd_nickname}: §8{nickname}§8, {Translations.cmd_entityCmd_latency}: {latency}, {Translations.cmd_entityCmd_health}: {health}, {Translations.cmd_entityCmd_pose}: {pose}, {Translations.cmd_entityCmd_location}: {location}";
else if (type == EntityType.Player && !string.IsNullOrEmpty(customname))
return $" #{id}: {Translations.cmd_entityCmd_type}: {entity.GetTypeString()}, {Translations.cmd_entityCmd_customname}: §8{customname.Replace("&", "§")}§8, {Translations.cmd_entityCmd_latency}: {latency}, {Translations.cmd_entityCmd_health}: {health}, {Translations.cmd_entityCmd_pose}: {pose}, {Translations.cmd_entityCmd_location}: {location}";
else
return $" #{id}: {Translations.cmd_entityCmd_type}: {entity.GetTypeString()}, {Translations.cmd_entityCmd_health}: {health}, {Translations.cmd_entityCmd_location}: {location}";
}
private static string GetEntityInfoDetailed(McClient handler, Entity entity)
{
StringBuilder sb = new();
int id = entity.ID;
float health = entity.Health;
int latency = entity.Latency;
Item item = entity.Item;
string? nickname = entity.Name;
string? customname = entity.CustomName;
EntityPose pose = entity.Pose;
EntityType type = entity.Type;
double distance = Math.Round(entity.Location.Distance(handler.GetCurrentLocation()), 2);
string location = $"X:{Math.Round(entity.Location.X, 2)}, Y:{Math.Round(entity.Location.Y, 2)}, Z:{Math.Round(entity.Location.Z, 2)}";
string color = "§a"; // Green
if (health < 10)
color = "§c"; // Red
else if (health < 15)
color = "§e"; // Yellow
sb.Append($"{Translations.cmd_entityCmd_entity}: {id}\n [MCC] Type: {entity.GetTypeString()}");
if (!string.IsNullOrEmpty(nickname))
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_nickname}: {nickname}");
else if (!string.IsNullOrEmpty(customname))
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_customname}: {customname.Replace("&", "§")}§8");
if (type == EntityType.Player)
{
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_latency}: {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)
{
string? displayName = item.DisplayName;
if (string.IsNullOrEmpty(displayName))
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_item}: {item.GetTypeString()} x{item.Count}");
else
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_item}: {item.GetTypeString()} x{item.Count} - {displayName}§8");
}
if (entity.Equipment.Count >= 1 && entity.Equipment != null)
{
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_equipment}:");
if (entity.Equipment.ContainsKey(0) && entity.Equipment[0] != null)
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_mainhand}: {entity.Equipment[0].GetTypeString()} x{entity.Equipment[0].Count}");
if (entity.Equipment.ContainsKey(1) && entity.Equipment[1] != null)
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_offhand}: {entity.Equipment[1].GetTypeString()} x{entity.Equipment[1].Count}");
if (entity.Equipment.ContainsKey(5) && entity.Equipment[5] != null)
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_helmet}: {entity.Equipment[5].GetTypeString()} x{entity.Equipment[5].Count}");
if (entity.Equipment.ContainsKey(4) && entity.Equipment[4] != null)
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_chestplate}: {entity.Equipment[4].GetTypeString()} x{entity.Equipment[4].Count}");
if (entity.Equipment.ContainsKey(3) && entity.Equipment[3] != null)
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_leggings}: {entity.Equipment[3].GetTypeString()} x{entity.Equipment[3].Count}");
if (entity.Equipment.ContainsKey(2) && entity.Equipment[2] != null)
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_boots}: {entity.Equipment[2].GetTypeString()} x{entity.Equipment[2].Count}");
}
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_pose}: {pose}");
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_health}: {color}{health}§8");
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_distance}: {distance}");
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_location}: {location}");
return sb.ToString();
}
private static bool TryGetClosetEntity(Dictionary<int, Entity> entities, Location location, EntityType? entityType, [NotNullWhen(true)] out Entity? closest)
{
closest = null;
bool find = false;
double closest_distance = double.PositiveInfinity;
foreach (var entity in entities)
{
if (entityType.HasValue && entity.Value.Type != entityType)
continue;
double distance = Math.Round(entity.Value.Location.Distance(location), 2);
if (distance < closest_distance)
{
find = true;
closest = entity.Value;
closest_distance = distance;
}
}
return find;
}
private static string InteractionWithEntity(McClient handler, Entity entity, ActionType action)
{
switch (action)
{
case ActionType.Attack:
handler.InteractEntity(entity.ID, InteractType.Attack);
return Translations.cmd_entityCmd_attacked;
case ActionType.Use:
handler.InteractEntity(entity.ID, InteractType.Interact);
return Translations.cmd_entityCmd_used;
case ActionType.List:
return GetEntityInfoDetailed(handler, entity);
default:
goto case ActionType.List;
}
}
}
}
}

View file

@ -1,99 +1,94 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Brigadier.NET;
using Brigadier.NET.Builder;
using DynamicExpresso;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
class ExecIf : Command
{
public override string CmdName { get { return "execif"; } }
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 Translations.cmd_execif_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Argument("Condition", Arguments.String())
.Then(l => l.Argument("Command", Arguments.String())
.Executes(r => HandleCommand(r.Source, handler, Arguments.GetString(r, "Condition"), Arguments.GetString(r, "Command")))))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (HasArg(command))
return r.SetAndReturn(cmd switch
{
string commandsString = GetArg(command);
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
if (!commandsString.Contains("--->"))
return GetCmdDescTranslated();
private int HandleCommand(CmdResult r, McClient handler, string expressionText, string resultCommand)
{
try
{
var interpreter = new Interpreter();
interpreter.SetVariable("MCC", handler);
string[] parts = commandsString.Split("--->", StringSplitOptions.TrimEntries)
.ToList()
.ConvertAll(command => command.Trim())
.ToArray();
foreach (KeyValuePair<string, object> entry in Settings.Config.AppVar.GetVariables())
interpreter.SetVariable(entry.Key, entry.Value);
if (parts.Length == 0)
return GetCmdDescTranslated();
var result = interpreter.Eval<bool>(expressionText);
string expressionText = parts[0];
string resultCommand = parts[1];
bool shouldExec = result;
try
/*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)
{
var interpreter = new Interpreter();
interpreter.SetVariable("MCC", handler);
CmdResult output = new();
handler.PerformInternalCommand(resultCommand, ref output);
foreach (KeyValuePair<string, object> entry in Settings.Config.AppVar.GetVariables())
interpreter.SetVariable(entry.Key, entry.Value);
var result = interpreter.Eval<bool>(expressionText);
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)
{
string? output = "";
handler.PerformInternalCommand(resultCommand, ref output);
if (string.IsNullOrEmpty(output))
handler.Log.Debug(string.Format(Translations.cmd_execif_executed_no_output, expressionText, resultCommand));
else
handler.Log.Debug(string.Format(Translations.cmd_execif_executed, expressionText, resultCommand, output));
return "";
}
return "";
return r.SetAndReturn(CmdResult.Status.Done, string.Format(Translations.cmd_execif_executed, expressionText, resultCommand, output));
}
catch (Exception e)
else
{
handler.Log.Error(string.Format(Translations.cmd_execif_error_occured, command));
handler.Log.Error(string.Format(Translations.cmd_execif_error, e.Message));
return "";
return r.SetAndReturn(CmdResult.Status.Done);
}
}
return GetCmdDescTranslated();
catch (Exception e)
{
handler.Log.Error(string.Format(Translations.cmd_execif_error, e.Message));
return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_execif_error_occured, expressionText + " ---> " + resultCommand));
}
}
}
}

View file

@ -2,6 +2,8 @@
using System.Collections.Generic;
using System.Linq;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -11,42 +13,47 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "execmulti <command 1> -> <command2> -> <command 3> -> ..."; } }
public override string CmdDesc { get { return Translations.cmd_execmulti_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Argument("Commands", Arguments.GreedyString())
.Executes(r => HandleCommand(r.Source, handler, Arguments.GetString(r, "Commands"))))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (HasArg(command))
return r.SetAndReturn(cmd switch
{
string commandsString = GetArg(command);
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
if (commandsString.Contains("execmulti", StringComparison.OrdinalIgnoreCase) || commandsString.Contains("execif", StringComparison.OrdinalIgnoreCase))
return Translations.cmd_execmulti_prevent;
private int HandleCommand(CmdResult r, McClient handler, string commandsString)
{
if (commandsString.Contains("execmulti", StringComparison.OrdinalIgnoreCase) || commandsString.Contains("execif", StringComparison.OrdinalIgnoreCase))
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_execmulti_prevent);
IEnumerable<string> commands = commandsString.Split("->", StringSplitOptions.TrimEntries)
.ToList()
.FindAll(command => !string.IsNullOrEmpty(command));
IEnumerable<string> commands = commandsString.Split("->", StringSplitOptions.TrimEntries)
.ToList()
.FindAll(command => !string.IsNullOrEmpty(command));
foreach (string cmd in commands)
{
string? output = "";
handler.PerformInternalCommand(cmd, ref output);
string log = string.Format(
Translations.cmd_execmulti_executed, cmd,
string.IsNullOrEmpty(output) ? Translations.cmd_execmulti_no_result : string.Format(Translations.cmd_execmulti_result, output));
if (output != null && output.Contains("unknown command", StringComparison.OrdinalIgnoreCase))
handler.Log.Error(log);
else
handler.Log.Info(log);
}
return "";
foreach (string cmd in commands)
{
CmdResult output = new();
handler.PerformInternalCommand(cmd, ref output);
handler.Log.Info(string.Format(Translations.cmd_execmulti_executed, cmd, string.Format(Translations.cmd_execmulti_result, output)));
}
return GetCmdDescTranslated();
return r.SetAndReturn(CmdResult.Status.Done);
}
}
}

View file

@ -1,5 +1,6 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -9,19 +10,48 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "exit"; } }
public override string CmdDesc { get { return Translations.cmd_exit_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
var exit = dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => DoExit(r.Source, 0))
.Then(l => l.Argument("ExitCode", Arguments.Integer())
.Executes(r => DoExit(r.Source, Arguments.GetInteger(r, "ExitCode"))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
dispatcher.Register(l => l.Literal("quit")
.Executes(r => DoExit(r.Source, 0))
.Redirect(exit)
);
}
public override string Run(McClient? handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoExit(CmdResult r, int code = 0)
{
Program.Exit(code);
return r.SetAndReturn(CmdResult.Status.Done);
}
internal static string DoExit(string command)
{
Program.Exit();
return "";
}
public override IEnumerable<string> GetCMDAliases()
{
return new string[] { "quit" };
return string.Empty;
}
}
}

View file

@ -1,5 +1,6 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -9,13 +10,34 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "health"; } }
public override string CmdDesc { get { return Translations.cmd_health_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => LogHealth(r.Source, handler))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return string.Format(Translations.cmd_health_response, handler.GetHealth(), handler.GetSaturation(), handler.GetLevel(), handler.GetTotalExperience());
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int LogHealth(CmdResult r, McClient handler)
{
return r.SetAndReturn(CmdResult.Status.Done, string.Format(Translations.cmd_health_response, handler.GetHealth(), handler.GetSaturation(), handler.GetLevel(), handler.GetTotalExperience()));
}
}
}

View file

@ -0,0 +1,33 @@
using System;
using System.Text;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
internal class Help : Command
{
public override string CmdName => throw new NotImplementedException();
public override string CmdDesc => throw new NotImplementedException();
public override string CmdUsage => throw new NotImplementedException();
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l =>
l.Literal("help")
.Executes(r => LogHelp(r.Source, handler, dispatcher))
);
}
private int LogHelp(CmdResult r, McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
var usage = dispatcher.GetSmartUsage(dispatcher.GetRoot(), CmdResult.Empty);
StringBuilder sb = new();
foreach (var item in usage)
sb.AppendLine(Settings.Config.Main.Advanced.InternalCmdChar.ToChar() + item.Value);
handler.Log.Info(string.Format(Translations.icmd_list, sb.ToString(), Settings.Config.Main.Advanced.InternalCmdChar.ToChar()));
return r.SetAndReturn(CmdResult.Status.Done);
}
}
}

View file

@ -1,9 +1,10 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.Inventory;
namespace MinecraftClient.Commands
@ -14,270 +15,374 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return GetBasicUsage(); } }
public override string CmdDesc { get { return Translations.cmd_inventory_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
.Then(l => l.Literal("list")
.Executes(r => GetUsage(r.Source, "list")))
.Then(l => l.Literal("close")
.Executes(r => GetUsage(r.Source, "close")))
.Then(l => l.Literal("click")
.Executes(r => GetUsage(r.Source, "click")))
.Then(l => l.Literal("drop")
.Executes(r => GetUsage(r.Source, "drop")))
.Then(l => l.Literal("creativegive")
.Executes(r => GetUsage(r.Source, "creativegive")))
.Then(l => l.Literal("creativedelete")
.Executes(r => GetUsage(r.Source, "creativedelete")))
.Then(l => l.Literal("inventories")
.Executes(r => GetUsage(r.Source, "inventories")))
.Then(l => l.Literal("search")
.Executes(r => GetUsage(r.Source, "search")))
.Then(l => l.Literal("help")
.Executes(r => GetUsage(r.Source, "help")))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => ListAllInventories(r.Source, handler))
.Then(l => l.Literal("creativegive")
.Then(l => l.Argument("Slot", Arguments.Integer(0, 89))
.Then(l => l.Argument("ItemType", MccArguments.ItemType())
.Then(l => l.Argument("Count", Arguments.Integer(min: 1))
.Executes(r => DoCreativeGive(r.Source, handler, Arguments.GetInteger(r, "Slot"), MccArguments.GetItemType(r, "ItemType"), Arguments.GetInteger(r, "Count")))))))
.Then(l => l.Literal("creativedelete")
.Then(l => l.Argument("Slot", Arguments.Integer(0, 89))
.Executes(r => DoCreativeDelete(r.Source, handler, Arguments.GetInteger(r, "Slot")))))
.Then(l => l.Literal("inventories")
.Executes(r => ListAvailableInventories(r.Source, handler)))
.Then(l => l.Literal("search")
.Then(l => l.Argument("ItemType", MccArguments.ItemType())
.Executes(r => SearchItem(r.Source, handler, MccArguments.GetItemType(r, "ItemType"), null))
.Then(l => l.Argument("Count", Arguments.Integer(0, 64))
.Executes(r => SearchItem(r.Source, handler, MccArguments.GetItemType(r, "ItemType"), Arguments.GetInteger(r, "Count"))))))
.Then(l => l.Argument("InventoryId", MccArguments.InventoryId())
.Then(l => l.Literal("close")
.Executes(r => DoCloseAction(r.Source, handler, Arguments.GetInteger(r, "InventoryId"))))
.Then(l => l.Literal("list")
.Executes(r => DoListAction(r.Source, handler, Arguments.GetInteger(r, "InventoryId"))))
.Then(l => l.Literal("click")
.Then(l => l.Argument("Slot", Arguments.Integer(0, 89))
.Executes(r => DoClickAction(r.Source, handler, Arguments.GetInteger(r, "InventoryId"), Arguments.GetInteger(r, "Slot"), WindowActionType.LeftClick))
.Then(l => l.Argument("Action", MccArguments.InventoryAction())
.Executes(r => DoClickAction(r.Source, handler, Arguments.GetInteger(r, "InventoryId"), Arguments.GetInteger(r, "Slot"), MccArguments.GetInventoryAction(r, "Action"))))))
.Then(l => l.Literal("drop")
.Then(l => l.Argument("Slot", Arguments.Integer(0, 89))
.Executes(r => DoDropAction(r.Source, handler, Arguments.GetInteger(r, "InventoryId"), Arguments.GetInteger(r, "Slot"), WindowActionType.DropItem))
.Then(l => l.Literal("all")
.Executes(r => DoDropAction(r.Source, handler, Arguments.GetInteger(r, "InventoryId"), Arguments.GetInteger(r, "Slot"), WindowActionType.DropItemStack))))))
.Then(l => l.Literal("player")
.Then(l => l.Literal("list")
.Executes(r => DoListAction(r.Source, handler, inventoryId: 0)))
.Then(l => l.Literal("click")
.Then(l => l.Argument("Slot", Arguments.Integer(0, 45))
.Executes(r => DoClickAction(r.Source, handler, inventoryId: 0, Arguments.GetInteger(r, "Slot"), WindowActionType.LeftClick))
.Then(l => l.Argument("Action", MccArguments.InventoryAction())
.Executes(r => DoClickAction(r.Source, handler, inventoryId: 0, Arguments.GetInteger(r, "Slot"), MccArguments.GetInventoryAction(r, "Action"))))))
.Then(l => l.Literal("drop")
.Then(l => l.Argument("Slot", Arguments.Integer(0, 45))
.Executes(r => DoDropAction(r.Source, handler, inventoryId: 0, Arguments.GetInteger(r, "Slot"), WindowActionType.DropItem))
.Then(l => l.Literal("all")
.Executes(r => DoDropAction(r.Source, handler, inventoryId: 0, Arguments.GetInteger(r, "Slot"), WindowActionType.DropItemStack))))))
.Then(l => l.Literal("container")
.Then(l => l.Literal("close")
.Executes(r => DoCloseAction(r.Source, handler, inventoryId: null)))
.Then(l => l.Literal("list")
.Executes(r => DoListAction(r.Source, handler, inventoryId: null)))
.Then(l => l.Literal("click")
.Then(l => l.Argument("Slot", Arguments.Integer(0, 89))
.Executes(r => DoClickAction(r.Source, handler, inventoryId: null, Arguments.GetInteger(r, "Slot"), WindowActionType.LeftClick))
.Then(l => l.Argument("Action", MccArguments.InventoryAction())
.Executes(r => DoClickAction(r.Source, handler, inventoryId: null, Arguments.GetInteger(r, "Slot"), MccArguments.GetInventoryAction(r, "Action"))))))
.Then(l => l.Literal("drop")
.Then(l => l.Argument("Slot", Arguments.Integer(0, 89))
.Executes(r => DoDropAction(r.Source, handler, inventoryId: null, Arguments.GetInteger(r, "Slot"), WindowActionType.DropItem))
.Then(l => l.Literal("all")
.Executes(r => DoDropAction(r.Source, handler, inventoryId: null, Arguments.GetInteger(r, "Slot"), WindowActionType.DropItemStack))))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (handler.GetInventoryEnabled())
string usageStr = ' ' + Translations.cmd_inventory_help_usage + ": ";
return r.SetAndReturn(cmd switch
{
string[] args = GetArgs(command);
if (args.Length >= 1)
{
int inventoryId;
if (args[0].ToLower() == "creativegive")
{
if (args.Length >= 4)
{
if (!int.TryParse(args[1], NumberStyles.Any, CultureInfo.CurrentCulture, out int slot))
return GetCmdDescTranslated();
#pragma warning disable format // @formatter:off
"list" => Translations.cmd_inventory_help_list + usageStr + "/inventory <player|container|<id>> list",
"close" => Translations.cmd_inventory_help_close + usageStr + "/inventory <player|container|<id>> close",
"click" => Translations.cmd_inventory_help_click + usageStr + "/inventory <player|container|<id>> click <slot> [left|right|middle|shift]\nDefault is left click",
"drop" => Translations.cmd_inventory_help_drop + usageStr + "/inventory <player|container|<id>> drop <slot> [all]\nAll means drop full stack",
"creativegive" => Translations.cmd_inventory_help_creativegive + usageStr + "/inventory creativegive <slot> <itemtype> <amount>",
"creativedelete" => Translations.cmd_inventory_help_creativedelete + usageStr + "/inventory creativedelete <slot>",
"inventories" => Translations.cmd_inventory_help_inventories + usageStr + "/inventory inventories",
"search" => Translations.cmd_inventory_help_search + usageStr + "/inventory search <item type> [count]",
"help" => GetCmdDescTranslated(),
"action" => Translations.cmd_inventory_help_unknown + GetAvailableActions(),
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
if (Enum.TryParse(args[2], true, out ItemType itemType))
{
if (handler.GetGamemode() == 1)
{
if (!int.TryParse(args[3], NumberStyles.Any, CultureInfo.CurrentCulture, out int count))
return GetCmdDescTranslated();
private int GetMaximumInventoryId(McClient handler)
{
List<int> availableIds = handler.GetInventories().Keys.ToList();
return availableIds.Max(); // use foreground container
}
if (handler.DoCreativeGive(slot, itemType, count, null))
return string.Format(Translations.cmd_inventory_creative_done, itemType, count, slot);
else
return Translations.cmd_inventory_creative_fail;
}
else
return Translations.cmd_inventory_need_creative;
}
else
return GetCmdDescTranslated();
}
else
return GetCmdDescTranslated();
}
else if (args[0].ToLower() == "creativedelete")
{
if (args.Length >= 2)
{
if (!int.TryParse(args[1], NumberStyles.Any, CultureInfo.CurrentCulture, out int slot))
return GetCmdDescTranslated();
private int ListAllInventories(CmdResult r, McClient handler)
{
if (!handler.GetInventoryEnabled())
{
handler.Log.Info(Translations.extra_inventory_required);
return -1;
}
StringBuilder response = new();
response.Append(Translations.cmd_inventory_inventories).Append(":\n");
foreach ((int invId, Container inv) in handler.GetInventories())
response.AppendLine(String.Format(" #{0}: {1}§8", invId, inv.Title));
response.Append(CmdUsage);
handler.Log.Info(response.ToString());
return r.SetAndReturn(CmdResult.Status.Done);
}
if (handler.GetGamemode() == 1)
{
if (handler.DoCreativeGive(slot, ItemType.Null, 0, null))
return string.Format(Translations.cmd_inventory_creative_delete, slot);
else
return Translations.cmd_inventory_creative_fail;
}
else
return Translations.cmd_inventory_need_creative;
}
else
return GetCmdDescTranslated();
}
else if (args[0].ToLower().StartsWith("p"))
{
// player inventory is always ID 0
inventoryId = 0;
}
else if (args[0].ToLower().StartsWith("c"))
{
List<int> availableIds = handler.GetInventories().Keys.ToList();
availableIds.Remove(0); // remove player inventory ID from list
if (availableIds.Count > 0)
inventoryId = availableIds.Max(); // use foreground container
else
return Translations.cmd_inventory_container_not_found;
}
else if (args[0].ToLower().StartsWith("inventories") || args[0].ToLower().StartsWith("i"))
{
Dictionary<int, Container> inventories = handler.GetInventories();
List<int> availableIds = inventories.Keys.ToList();
StringBuilder response = new();
response.AppendLine(Translations.cmd_inventory_inventories_available);
private int DoCreativeGive(CmdResult r, McClient handler, int slot, ItemType itemType, int count)
{
if (!handler.GetInventoryEnabled())
return r.SetAndReturn(CmdResult.Status.FailNeedInventory);
foreach (int id in availableIds)
response.AppendLine(String.Format(" #{0} - {1}§8", id, inventories[id].Title));
return response.ToString();
}
else if (args[0].ToLower().StartsWith("search") || args[0].ToLower().StartsWith("s"))
{
if (args.Length < 2)
return GetCmdDescTranslated();
if (!Enum.TryParse(args[1], true, out ItemType parsedItemType))
return GetCmdDescTranslated();
bool shouldUseItemCount = args.Length >= 3;
int itemCount = 0;
if (shouldUseItemCount && !int.TryParse(args[2], NumberStyles.Any, CultureInfo.CurrentCulture, out itemCount))
return GetCmdDescTranslated();
Dictionary<int, Container> inventories = handler.GetInventories();
Dictionary<int, List<Item>> foundItems = new();
List<Container> availableInventories = inventories.Values.ToList();
availableInventories.ForEach(inventory =>
{
inventory.Items.Values
.ToList()
.FindAll(item => item.Type == parsedItemType && (!shouldUseItemCount || item.Count == itemCount))
.ForEach(item =>
{
if (!foundItems.ContainsKey(inventory.ID))
{
foundItems.Add(inventory.ID, new List<Item>() { item });
return;
}
List<Item> invItems = foundItems[inventory.ID];
invItems.Add(item);
foundItems.Remove(inventory.ID);
foundItems.Add(inventory.ID, invItems);
});
});
if (foundItems.Count == 0)
return Translations.cmd_inventory_no_found_items;
StringBuilder response = new();
response.AppendLine(Translations.cmd_inventory_found_items + ":");
foreach ((int invId, List<Item> itemsList) in new SortedDictionary<int, List<Item>>(foundItems))
{
if (itemsList.Count > 0)
{
response.AppendLine(String.Format("{0} (#{1}):", inventories[invId].Title, invId));
foreach (Item item in itemsList)
response.AppendLine(String.Format("\t- {0}", item.ToFullString()));
response.AppendLine(" ");
}
}
return response.ToString();
}
else if (args[0].ToLower() == "help")
{
if (args.Length >= 2)
return GetSubCommandHelp(args[1]);
else
return GetHelp();
}
else if (!int.TryParse(args[0], NumberStyles.Any, CultureInfo.CurrentCulture, out inventoryId))
return GetCmdDescTranslated();
Container? inventory = handler.GetInventory(inventoryId);
if (inventory == null)
return string.Format(Translations.cmd_inventory_not_exist, inventoryId);
string action = args.Length > 1 ? args[1].ToLower() : "list";
if (action == "close")
{
if (handler.CloseInventory(inventoryId))
return string.Format(Translations.cmd_inventory_close, inventoryId);
else
return string.Format(Translations.cmd_inventory_close_fail, inventoryId);
}
else if (action == "list")
{
StringBuilder response = new();
response.Append(Translations.cmd_inventory_inventory);
response.AppendLine(String.Format(" #{0} - {1}§8", inventoryId, inventory.Title));
string? asciiArt = inventory.Type.GetAsciiArt();
if (asciiArt != null && Settings.Config.Main.Advanced.ShowInventoryLayout)
response.AppendLine(asciiArt);
int selectedHotbar = handler.GetCurrentSlot() + 1;
foreach ((int itemId, Item item) in new SortedDictionary<int, Item>(inventory.Items))
{
bool isHotbar = inventory.IsHotbar(itemId, out int hotbar);
string hotbarString = isHotbar ? (hotbar + 1).ToString() : " ";
if ((hotbar + 1) == selectedHotbar)
hotbarString = ">" + hotbarString;
response.AppendLine(String.Format("{0,2} | #{1,-2}: {2}", hotbarString, itemId, item.ToFullString()));
}
if (inventoryId == 0)
response.AppendLine(string.Format(Translations.cmd_inventory_hotbar, (handler.GetCurrentSlot() + 1)));
response.Remove(response.Length - 1, 1); // Remove last '\n'
return response.ToString();
}
else if (action == "click" && args.Length >= 3)
{
if (!int.TryParse(args[2], NumberStyles.Any, CultureInfo.CurrentCulture, out int slot))
return GetCmdDescTranslated();
WindowActionType actionType = WindowActionType.LeftClick;
string keyName = Translations.cmd_inventory_left;
if (args.Length >= 4)
{
string b = args[3];
if (b.ToLower()[0] == 'r')
(actionType, keyName) = (WindowActionType.RightClick, Translations.cmd_inventory_right);
else if (b.ToLower()[0] == 'm')
(actionType, keyName) = (WindowActionType.MiddleClick, Translations.cmd_inventory_middle);
}
handler.DoWindowAction(inventoryId, slot, actionType);
return string.Format(Translations.cmd_inventory_clicking, keyName, slot, inventoryId);
}
else if (action == "shiftclick" && args.Length >= 3)
{
if (!int.TryParse(args[2], NumberStyles.Any, CultureInfo.CurrentCulture, out int slot))
return GetCmdDescTranslated();
if (!handler.DoWindowAction(inventoryId, slot, WindowActionType.ShiftClick))
return Translations.cmd_inventory_shiftclick_fail;
return string.Format(Translations.cmd_inventory_shiftclick, slot, inventoryId);
}
else if (action == "drop" && args.Length >= 3)
{
if (!int.TryParse(args[2], NumberStyles.Any, CultureInfo.CurrentCulture, out int slot))
return GetCmdDescTranslated();
// check item exist
if (!inventory.Items.ContainsKey(slot))
return string.Format(Translations.cmd_inventory_no_item, slot);
WindowActionType actionType = WindowActionType.DropItem;
if (args.Length >= 4 && args[3].ToLower() == "all")
actionType = WindowActionType.DropItemStack;
if (handler.DoWindowAction(inventoryId, slot, actionType))
{
if (actionType == WindowActionType.DropItemStack)
return string.Format(Translations.cmd_inventory_drop_stack, slot);
else
return string.Format(Translations.cmd_inventory_drop, slot);
}
else
return "Failed";
}
else
return GetCmdDescTranslated();
}
if (handler.GetGamemode() == 1)
{
if (handler.DoCreativeGive(slot, itemType, count, null))
return r.SetAndReturn(CmdResult.Status.Done, string.Format(Translations.cmd_inventory_creative_done, itemType, count, slot));
else
{
StringBuilder response = new();
response.Append(Translations.cmd_inventory_inventories).Append(":\n");
foreach ((int invId, Container inv) in handler.GetInventories())
response.AppendLine(String.Format(" #{0}: {1}§8", invId, inv.Title));
response.Append(CmdUsage);
return response.ToString();
}
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_inventory_creative_fail);
}
else
return Translations.extra_inventory_required;
{
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_inventory_need_creative);
}
}
private int DoCreativeDelete(CmdResult r, McClient handler, int slot)
{
if (!handler.GetInventoryEnabled())
return r.SetAndReturn(CmdResult.Status.FailNeedInventory);
if (handler.GetGamemode() == 1)
{
if (handler.DoCreativeGive(slot, ItemType.Null, 0, null))
return r.SetAndReturn(CmdResult.Status.Done, string.Format(Translations.cmd_inventory_creative_delete, slot));
else
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_inventory_creative_fail);
}
else
{
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_inventory_need_creative);
}
}
private int ListAvailableInventories(CmdResult r, McClient handler)
{
if (!handler.GetInventoryEnabled())
return r.SetAndReturn(CmdResult.Status.FailNeedInventory);
Dictionary<int, Container> inventories = handler.GetInventories();
List<int> availableIds = inventories.Keys.ToList();
StringBuilder response = new();
response.AppendLine(Translations.cmd_inventory_inventories_available);
foreach (int id in availableIds)
response.AppendLine(String.Format(" #{0} - {1}§8", id, inventories[id].Title));
handler.Log.Info(response.ToString());
return r.SetAndReturn(CmdResult.Status.Done);
}
private int SearchItem(CmdResult r, McClient handler, ItemType itemType, int? itemCount)
{
if (!handler.GetInventoryEnabled())
return r.SetAndReturn(CmdResult.Status.FailNeedInventory);
Dictionary<int, Container> inventories = handler.GetInventories();
Dictionary<int, List<Item>> foundItems = new();
List<Container> availableInventories = inventories.Values.ToList();
availableInventories.ForEach(inventory =>
{
inventory.Items.Values
.ToList()
.FindAll(item => item.Type == itemType && (!itemCount.HasValue || item.Count == itemCount))
.ForEach(item =>
{
if (!foundItems.ContainsKey(inventory.ID))
{
foundItems.Add(inventory.ID, new List<Item>() { item });
return;
}
List<Item> invItems = foundItems[inventory.ID];
invItems.Add(item);
foundItems.Remove(inventory.ID);
foundItems.Add(inventory.ID, invItems);
});
});
if (foundItems.Count == 0)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_inventory_no_found_items);
StringBuilder response = new();
response.AppendLine(Translations.cmd_inventory_found_items + ":");
foreach ((int invId, List<Item> itemsList) in new SortedDictionary<int, List<Item>>(foundItems))
{
if (itemsList.Count > 0)
{
response.AppendLine(String.Format("{0} (#{1}):", inventories[invId].Title, invId));
foreach (Item item in itemsList)
response.AppendLine(String.Format("\t- {0}", item.ToFullString()));
response.AppendLine(" ");
}
}
handler.Log.Info(response.ToString());
return r.SetAndReturn(CmdResult.Status.Done);
}
private int DoCloseAction(CmdResult r, McClient handler, int? inventoryId)
{
if (!handler.GetInventoryEnabled())
return r.SetAndReturn(CmdResult.Status.FailNeedInventory);
if (!inventoryId.HasValue)
{
inventoryId = GetMaximumInventoryId(handler);
if (inventoryId == 0)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_inventory_container_not_found);
}
Container? inventory = handler.GetInventory(inventoryId.Value);
if (inventory == null)
return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_inventory_not_exist, inventoryId));
if (handler.CloseInventory(inventoryId.Value))
return r.SetAndReturn(CmdResult.Status.Done, string.Format(Translations.cmd_inventory_close, inventoryId));
else
return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_inventory_close_fail, inventoryId));
}
private int DoListAction(CmdResult r, McClient handler, int? inventoryId)
{
if (!handler.GetInventoryEnabled())
return r.SetAndReturn(CmdResult.Status.FailNeedInventory);
if (!inventoryId.HasValue)
{
inventoryId = GetMaximumInventoryId(handler);
if (inventoryId == 0)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_inventory_container_not_found);
}
Container? inventory = handler.GetInventory(inventoryId.Value);
if (inventory == null)
return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_inventory_not_exist, inventoryId));
StringBuilder response = new();
response.Append(Translations.cmd_inventory_inventory);
response.AppendLine(String.Format(" #{0} - {1}§8", inventoryId, inventory.Title));
string? asciiArt = inventory.Type.GetAsciiArt();
if (asciiArt != null && Settings.Config.Main.Advanced.ShowInventoryLayout)
response.AppendLine(asciiArt);
int selectedHotbar = handler.GetCurrentSlot() + 1;
foreach ((int itemId, Item item) in new SortedDictionary<int, Item>(inventory.Items))
{
bool isHotbar = inventory.IsHotbar(itemId, out int hotbar);
string hotbarString = isHotbar ? (hotbar + 1).ToString() : " ";
if ((hotbar + 1) == selectedHotbar)
hotbarString = ">" + hotbarString;
response.AppendLine(String.Format("{0,2} | #{1,-2}: {2}", hotbarString, itemId, item.ToFullString()));
}
if (inventoryId == 0)
response.AppendLine(string.Format(Translations.cmd_inventory_hotbar, (handler.GetCurrentSlot() + 1)));
response.Remove(response.Length - 1, 1); // Remove last '\n'
handler.Log.Info(response.ToString());
return r.SetAndReturn(CmdResult.Status.Done);
}
private int DoClickAction(CmdResult r, McClient handler, int? inventoryId, int slot, WindowActionType actionType)
{
if (!handler.GetInventoryEnabled())
return r.SetAndReturn(CmdResult.Status.FailNeedInventory);
if (!inventoryId.HasValue)
{
inventoryId = GetMaximumInventoryId(handler);
if (inventoryId == 0)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_inventory_container_not_found);
}
Container? inventory = handler.GetInventory(inventoryId.Value);
if (inventory == null)
return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_inventory_not_exist, inventoryId));
string keyName = actionType switch
{
WindowActionType.LeftClick => Translations.cmd_inventory_left,
WindowActionType.RightClick => Translations.cmd_inventory_right,
WindowActionType.MiddleClick => Translations.cmd_inventory_middle,
WindowActionType.ShiftClick => Translations.cmd_inventory_shiftclick,
_ => "unknown",
};
handler.Log.Info(string.Format(Translations.cmd_inventory_clicking, keyName, slot, inventoryId));
return r.SetAndReturn(handler.DoWindowAction(inventoryId.Value, slot, actionType));
}
private int DoDropAction(CmdResult r, McClient handler, int? inventoryId, int slot, WindowActionType actionType)
{
if (!handler.GetInventoryEnabled())
return r.SetAndReturn(CmdResult.Status.FailNeedInventory);
if (!inventoryId.HasValue)
{
inventoryId = GetMaximumInventoryId(handler);
if (inventoryId == 0)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_inventory_container_not_found);
}
Container? inventory = handler.GetInventory(inventoryId.Value);
if (inventory == null)
return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_inventory_not_exist, inventoryId));
// check item exist
if (!inventory.Items.ContainsKey(slot))
return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_inventory_no_item, slot));
if (handler.DoWindowAction(inventoryId.Value, slot, actionType))
{
if (actionType == WindowActionType.DropItemStack)
return r.SetAndReturn(CmdResult.Status.Done, string.Format(Translations.cmd_inventory_drop_stack, slot));
else
return r.SetAndReturn(CmdResult.Status.Done, string.Format(Translations.cmd_inventory_drop, slot));
}
else
{
return r.SetAndReturn(CmdResult.Status.Fail, "Drop Failed");
}
}
#region Methods for commands help
private static string GetAvailableActions()
@ -290,31 +395,6 @@ namespace MinecraftClient.Commands
return Translations.cmd_inventory_help_basic + ": /inventory <player|container|<id>> <action>.";
}
private static string GetHelp()
{
return string.Format(Translations.cmd_inventory_help_help, GetAvailableActions());
}
private static string GetSubCommandHelp(string cmd)
{
string usageStr = ' ' + Translations.cmd_inventory_help_usage + ": ";
return cmd switch
{
#pragma warning disable format // @formatter:off
"list" => Translations.cmd_inventory_help_list + usageStr + "/inventory <player|container|<id>> list",
"close" => Translations.cmd_inventory_help_close + usageStr + "/inventory <player|container|<id>> close",
"click" => Translations.cmd_inventory_help_click + usageStr + "/inventory <player|container|<id>> click <slot> [left|right|middle]\nDefault is left click",
"shiftclick" => Translations.cmd_inventory_help_shiftclick + usageStr + "/inventory <player|container|<id>> shiftclick <slot>",
"drop" => Translations.cmd_inventory_help_drop + usageStr + "/inventory <player|container|<id>> drop <slot> [all]\nAll means drop full stack",
"creativegive" => Translations.cmd_inventory_help_creativegive + usageStr + "/inventory creativegive <slot> <itemtype> <amount>",
"creativedelete" => Translations.cmd_inventory_help_creativedelete + usageStr + "/inventory creativedelete <slot>",
"inventories" => Translations.cmd_inventory_help_inventories + usageStr + "/inventory inventories",
"search" => Translations.cmd_inventory_help_search + usageStr + "/inventory search <item type> [count]",
"help" => GetHelp(),
_ => Translations.cmd_inventory_help_unknown + GetAvailableActions(),
#pragma warning restore format // @formatter:on
};
}
#endregion
}
}

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -10,13 +11,34 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "list"; } }
public override string CmdDesc { get { return Translations.cmd_list_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => DoListPlayers(r.Source, handler))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return string.Format(Translations.cmd_list_players, String.Join(", ", handler.GetOnlinePlayers()));
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoListPlayers(CmdResult r, McClient handler)
{
return r.SetAndReturn(CmdResult.Status.Done, string.Format(Translations.cmd_list_players, String.Join(", ", handler.GetOnlinePlayers())));
}
}
}

View file

@ -1,5 +1,6 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -9,18 +10,35 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "log <text>"; } }
public override string CmdDesc { get { return Translations.cmd_log_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Argument("String", Arguments.GreedyString())
.Executes(r => DoLog(r.Source, Arguments.GetString(r, "String"))))
.Then(l => l.Literal("_help")
.Executes(r => GetUsage(r.Source, string.Empty)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (HasArg(command))
return r.SetAndReturn(cmd switch
{
ConsoleIO.WriteLogLine(GetArg(command));
return "";
}
else return GetCmdDescTranslated();
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoLog(CmdResult r, string command)
{
return r.SetAndReturn(CmdResult.Status.Done, command);
}
}
}

View file

@ -1,8 +1,9 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.Mapping;
using static MinecraftClient.CommandHandler.CmdResult;
namespace MinecraftClient.Commands
{
@ -12,74 +13,102 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "look <x y z|yaw pitch|up|down|east|west|north|south>"; } }
public override string CmdDesc { get { return Translations.cmd_look_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
.Then(l => l.Literal("direction")
.Executes(r => GetUsage(r.Source, "direction")))
.Then(l => l.Literal("angle")
.Executes(r => GetUsage(r.Source, "angle")))
.Then(l => l.Literal("location")
.Executes(r => GetUsage(r.Source, "location")))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => LogCurrentLooking(r.Source, handler))
.Then(l => l.Literal("up")
.Executes(r => LookAtDirection(r.Source, handler, Direction.Up)))
.Then(l => l.Literal("down")
.Executes(r => LookAtDirection(r.Source, handler, Direction.Down)))
.Then(l => l.Literal("east")
.Executes(r => LookAtDirection(r.Source, handler, Direction.East)))
.Then(l => l.Literal("west")
.Executes(r => LookAtDirection(r.Source, handler, Direction.West)))
.Then(l => l.Literal("north")
.Executes(r => LookAtDirection(r.Source, handler, Direction.North)))
.Then(l => l.Literal("south")
.Executes(r => LookAtDirection(r.Source, handler, Direction.South)))
.Then(l => l.Argument("Yaw", Arguments.Float())
.Then(l => l.Argument("Pitch", Arguments.Float())
.Executes(r => LookAtAngle(r.Source, handler, Arguments.GetFloat(r, "Yaw"), Arguments.GetFloat(r, "Pitch")))))
.Then(l => l.Argument("Location", MccArguments.Location())
.Executes(r => LookAtLocation(r.Source, handler, MccArguments.GetLocation(r, "Location"))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (handler.GetTerrainEnabled())
return r.SetAndReturn(cmd switch
{
string[] args = GetArgs(command);
if (args.Length == 0)
{
const double maxDistance = 8.0;
(bool hasBlock, Location target, Block block) = RaycastHelper.RaycastBlock(handler, maxDistance, false);
if (!hasBlock)
return string.Format(Translations.cmd_look_noinspection, maxDistance);
else
{
Location current = handler.GetCurrentLocation(), target_center = target.ToCenter();
return string.Format(Translations.cmd_look_inspection, block.Type, target.X, target.Y, target.Z,
current.Distance(target_center), current.EyesLocation().Distance(target_center));
}
}
else if (args.Length == 1)
{
string dirStr = GetArg(command).Trim().ToLower();
Direction direction;
switch (dirStr)
{
case "up": direction = Direction.Up; break;
case "down": direction = Direction.Down; break;
case "east": direction = Direction.East; break;
case "west": direction = Direction.West; break;
case "north": direction = Direction.North; break;
case "south": direction = Direction.South; break;
default: return string.Format(Translations.cmd_look_unknown, dirStr);
}
#pragma warning disable format // @formatter:off
"direction" => GetCmdDescTranslated(),
"angle" => GetCmdDescTranslated(),
"location" => GetCmdDescTranslated(),
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
handler.UpdateLocation(handler.GetCurrentLocation(), direction);
return "Looking " + dirStr;
}
else if (args.Length == 2)
{
try
{
float yaw = float.Parse(args[0], NumberStyles.Any, CultureInfo.CurrentCulture);
float pitch = float.Parse(args[1], NumberStyles.Any, CultureInfo.CurrentCulture);
private int LogCurrentLooking(CmdResult r, McClient handler)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
handler.UpdateLocation(handler.GetCurrentLocation(), yaw, pitch);
return string.Format(Translations.cmd_look_at, yaw.ToString("0.00"), pitch.ToString("0.00"));
}
catch (FormatException) { return GetCmdDescTranslated(); }
}
else if (args.Length == 3)
{
try
{
Location current = handler.GetCurrentLocation();
Location block = Location.Parse(current, args[0], args[1], args[2]);
handler.UpdateLocation(current, block);
return string.Format(Translations.cmd_look_block, block);
}
catch (FormatException) { return CmdUsage; }
}
else return GetCmdDescTranslated();
const double maxDistance = 8.0;
(bool hasBlock, Location target, Block block) = RaycastHelper.RaycastBlock(handler, maxDistance, false);
if (!hasBlock)
{
return r.SetAndReturn(Status.Fail, string.Format(Translations.cmd_look_noinspection, maxDistance));
}
else return Translations.extra_terrainandmovement_required;
else
{
Location current = handler.GetCurrentLocation(), target_center = target.ToCenter();
return r.SetAndReturn(Status.Done, string.Format(Translations.cmd_look_inspection, block.Type, target.X, target.Y, target.Z,
current.Distance(target_center), current.EyesLocation().Distance(target_center)));
}
}
private int LookAtDirection(CmdResult r, McClient handler, Direction direction)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
handler.UpdateLocation(handler.GetCurrentLocation(), direction);
return r.SetAndReturn(Status.Done, "Looking " + direction.ToString());
}
private int LookAtAngle(CmdResult r, McClient handler, float yaw, float pitch)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
handler.UpdateLocation(handler.GetCurrentLocation(), yaw, pitch);
return r.SetAndReturn(Status.Done, string.Format(Translations.cmd_look_at, yaw.ToString("0.00"), pitch.ToString("0.00")));
}
private int LookAtLocation(CmdResult r, McClient handler, Location location)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
Location current = handler.GetCurrentLocation();
handler.UpdateLocation(current, location);
return r.SetAndReturn(Status.Done, string.Format(Translations.cmd_look_block, location));
}
}
}

View file

@ -1,8 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.Mapping;
using static MinecraftClient.CommandHandler.CmdResult;
namespace MinecraftClient.Commands
{
@ -12,111 +13,183 @@ 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 CmdDesc { get { return Translations.cmd_move_desc + " \"-f\": " + Translations.cmd_move_desc_force; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
.Then(l => l.Literal("enable")
.Executes(r => GetUsage(r.Source, "enable")))
.Then(l => l.Literal("gravity")
.Executes(r => GetUsage(r.Source, "gravity")))
.Then(l => l.Literal("direction")
.Executes(r => GetUsage(r.Source, "direction")))
.Then(l => l.Literal("center")
.Executes(r => GetUsage(r.Source, "center")))
.Then(l => l.Literal("get")
.Executes(r => GetUsage(r.Source, "get")))
.Then(l => l.Literal("location")
.Executes(r => GetUsage(r.Source, "location")))
.Then(l => l.Literal("-f")
.Executes(r => GetUsage(r.Source, "-f")))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Literal("on")
.Executes(r => SetMovementEnable(r.Source, handler, enable: true)))
.Then(l => l.Literal("off")
.Executes(r => SetMovementEnable(r.Source, handler, enable: false)))
.Then(l => l.Literal("gravity")
.Executes(r => SetGravityEnable(r.Source, handler, enable: null))
.Then(l => l.Literal("on")
.Executes(r => SetGravityEnable(r.Source, handler, enable: true)))
.Then(l => l.Literal("off")
.Executes(r => SetGravityEnable(r.Source, handler, enable: false))))
.Then(l => l.Literal("up")
.Executes(r => MoveOnDirection(r.Source, handler, Direction.Up, false))
.Then(l => l.Literal("-f")
.Executes(r => MoveOnDirection(r.Source, handler, Direction.Up, true))))
.Then(l => l.Literal("down")
.Executes(r => MoveOnDirection(r.Source, handler, Direction.Down, false))
.Then(l => l.Literal("-f")
.Executes(r => MoveOnDirection(r.Source, handler, Direction.Down, true))))
.Then(l => l.Literal("east")
.Executes(r => MoveOnDirection(r.Source, handler, Direction.East, false))
.Then(l => l.Literal("-f")
.Executes(r => MoveOnDirection(r.Source, handler, Direction.East, true))))
.Then(l => l.Literal("west")
.Executes(r => MoveOnDirection(r.Source, handler, Direction.West, false))
.Then(l => l.Literal("-f")
.Executes(r => MoveOnDirection(r.Source, handler, Direction.West, true))))
.Then(l => l.Literal("north")
.Executes(r => MoveOnDirection(r.Source, handler, Direction.North, false))
.Then(l => l.Literal("-f")
.Executes(r => MoveOnDirection(r.Source, handler, Direction.North, true))))
.Then(l => l.Literal("south")
.Executes(r => MoveOnDirection(r.Source, handler, Direction.South, false))
.Then(l => l.Literal("-f")
.Executes(r => MoveOnDirection(r.Source, handler, Direction.South, true))))
.Then(l => l.Literal("center")
.Executes(r => MoveToCenter(r.Source, handler)))
.Then(l => l.Literal("get")
.Executes(r => GetCurrentLocation(r.Source, handler)))
.Then(l => l.Argument("location", MccArguments.Location())
.Executes(r => MoveToLocation(r.Source, handler, MccArguments.GetLocation(r, "location"), false))
.Then(l => l.Literal("-f")
.Executes(r => MoveToLocation(r.Source, handler, MccArguments.GetLocation(r, "location"), true))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
List<string> args = GetArgs(command.ToLower()).ToList();
bool takeRisk = false;
if (args.Count < 1)
return r.SetAndReturn(cmd switch
{
string desc = GetCmdDescTranslated();
#pragma warning disable format // @formatter:off
"enable" => GetCmdDescTranslated(),
"gravity" => GetCmdDescTranslated(),
"direction" => GetCmdDescTranslated(),
"center" => GetCmdDescTranslated(),
"get" => GetCmdDescTranslated(),
"location" => GetCmdDescTranslated(),
"-f" => GetCmdDescTranslated(),
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
if (handler.GetTerrainEnabled())
handler.Log.Info(World.GetChunkLoadingStatus(handler.GetWorld()));
return desc;
}
if (args.Contains("-f"))
{
takeRisk = true;
args.Remove("-f");
}
if (args[0] == "on")
private int SetMovementEnable(CmdResult r, McClient handler, bool enable)
{
if (enable)
{
handler.SetTerrainEnabled(true);
return Translations.cmd_move_enable;
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_move_enable);
}
else if (args[0] == "off")
else
{
handler.SetTerrainEnabled(false);
return Translations.cmd_move_disable;
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_move_disable);
}
else if (args[0] == "gravity")
}
private int SetGravityEnable(CmdResult r, McClient handler, bool? enable)
{
if (enable.HasValue)
Settings.InternalConfig.GravityEnabled = enable.Value;
if (Settings.InternalConfig.GravityEnabled)
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_move_gravity_enabled);
else
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_move_gravity_disabled);
}
private int GetCurrentLocation(CmdResult r, McClient handler)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
return r.SetAndReturn(Status.Done, handler.GetCurrentLocation().ToString());
}
private int MoveToCenter(CmdResult r, McClient handler)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
Location current = handler.GetCurrentLocation();
Location currentCenter = new(Math.Floor(current.X) + 0.5, current.Y, Math.Floor(current.Z) + 0.5);
handler.MoveTo(currentCenter, allowDirectTeleport: true);
return r.SetAndReturn(Status.Done, string.Format(Translations.cmd_move_walk, currentCenter, current));
}
private int MoveOnDirection(CmdResult r, McClient handler, Direction direction, bool takeRisk)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
Location goal = Movement.Move(handler.GetCurrentLocation(), direction);
if (!Movement.CheckChunkLoading(handler.GetWorld(), handler.GetCurrentLocation(), goal))
return r.SetAndReturn(Status.FailChunkNotLoad, string.Format(Translations.cmd_move_chunk_not_loaded, goal.X, goal.Y, goal.Z));
if (Movement.CanMove(handler.GetWorld(), handler.GetCurrentLocation(), direction))
{
if (args.Count >= 2)
Settings.InternalConfig.GravityEnabled = (args[1] == "on");
if (Settings.InternalConfig.GravityEnabled)
return Translations.cmd_move_gravity_enabled;
else return Translations.cmd_move_gravity_disabled;
if (handler.MoveTo(goal, allowUnsafe: takeRisk))
return r.SetAndReturn(Status.Done, string.Format(Translations.cmd_move_moving, direction.ToString()));
else
return r.SetAndReturn(Status.Fail, takeRisk ? Translations.cmd_move_dir_fail : Translations.cmd_move_suggestforce);
}
else if (handler.GetTerrainEnabled())
else
{
if (args.Count == 1)
{
Direction direction;
switch (args[0])
{
case "up": direction = Direction.Up; break;
case "down": direction = Direction.Down; break;
case "east": direction = Direction.East; break;
case "west": direction = Direction.West; break;
case "north": direction = Direction.North; break;
case "south": direction = Direction.South; break;
case "center":
Location current = handler.GetCurrentLocation();
Location currentCenter = new(Math.Floor(current.X) + 0.5, current.Y, Math.Floor(current.Z) + 0.5);
handler.MoveTo(currentCenter, allowDirectTeleport: true);
return string.Format(Translations.cmd_move_walk, currentCenter, current);
case "get": return handler.GetCurrentLocation().ToString();
default: return string.Format(Translations.cmd_look_unknown, args[0]);
}
Location goal = Movement.Move(handler.GetCurrentLocation(), direction);
if (!Movement.CheckChunkLoading(handler.GetWorld(), handler.GetCurrentLocation(), goal))
return string.Format(Translations.cmd_move_chunk_not_loaded, goal.X, goal.Y, goal.Z);
if (Movement.CanMove(handler.GetWorld(), handler.GetCurrentLocation(), direction))
{
if (handler.MoveTo(goal, allowUnsafe: takeRisk))
return string.Format(Translations.cmd_move_moving, args[0]);
else
return takeRisk ? Translations.cmd_move_dir_fail : Translations.cmd_move_suggestforce;
}
else return Translations.cmd_move_dir_fail;
}
else if (args.Count == 3)
{
try
{
Location current = handler.GetCurrentLocation(), currentCenter = current.ToCenter();
Location goal = Location.Parse(current, args[0], args[1], args[2]);
if (!Movement.CheckChunkLoading(handler.GetWorld(), current, goal))
return string.Format(Translations.cmd_move_chunk_not_loaded, goal.X, goal.Y, goal.Z);
if (takeRisk || Movement.PlayerFitsHere(handler.GetWorld(), goal))
{
if (current.ToFloor() == goal.ToFloor())
handler.MoveTo(goal, allowDirectTeleport: true);
else if (!handler.MoveTo(goal, allowUnsafe: takeRisk))
return takeRisk ? string.Format(Translations.cmd_move_fail, goal) : string.Format(Translations.cmd_move_suggestforce, goal);
return string.Format(Translations.cmd_move_walk, goal, current);
}
else
return string.Format(Translations.cmd_move_suggestforce, goal);
}
catch (FormatException) { return GetCmdDescTranslated(); }
}
else return GetCmdDescTranslated();
return r.SetAndReturn(Status.Fail, Translations.cmd_move_dir_fail);
}
}
private int MoveToLocation(CmdResult r, McClient handler, Location goal, bool takeRisk)
{
if (!handler.GetTerrainEnabled())
return r.SetAndReturn(Status.FailNeedTerrain);
Location current = handler.GetCurrentLocation(), currentCenter = current.ToCenter();
goal.ToAbsolute(current);
if (!Movement.CheckChunkLoading(handler.GetWorld(), current, goal))
return r.SetAndReturn(Status.FailChunkNotLoad, string.Format(Translations.cmd_move_chunk_not_loaded, goal.X, goal.Y, goal.Z));
if (takeRisk || Movement.PlayerFitsHere(handler.GetWorld(), goal))
{
if (current.ToFloor() == goal.ToFloor())
handler.MoveTo(goal, allowDirectTeleport: true);
else if (!handler.MoveTo(goal, allowUnsafe: takeRisk))
return r.SetAndReturn(Status.Fail, takeRisk ? string.Format(Translations.cmd_move_fail, goal) : string.Format(Translations.cmd_move_suggestforce, goal));
return r.SetAndReturn(Status.Done, string.Format(Translations.cmd_move_walk, goal, current));
}
else
{
return r.SetAndReturn(Status.Fail, string.Format(Translations.cmd_move_suggestforce, goal));
}
else return Translations.extra_terrainandmovement_required;
}
}
}

View file

@ -1,5 +1,7 @@
using System.Collections.Generic;
using System;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -9,22 +11,58 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "reco [account]"; } }
public override string CmdDesc { get { return Translations.cmd_reco_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => DoReconnect(r.Source, string.Empty))
.Then(l => l.Argument("AccountNick", MccArguments.AccountNick())
.Executes(r => DoReconnect(r.Source, Arguments.GetString(r, "AccountNick"))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient? handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoReconnect(CmdResult r, string account)
{
if (string.IsNullOrWhiteSpace(account))
{
account = account.Trim();
if (!Settings.Config.Main.Advanced.SetAccount(account))
return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_connect_unknown, account));
}
Program.Restart(keepAccountAndServerSettings: true);
return r.SetAndReturn(CmdResult.Status.Done);
}
internal static string DoReconnect(string command)
{
string[] args = GetArgs(command);
if (args.Length > 0)
{
if (!Settings.Config.Main.Advanced.SetAccount(args[0]))
string account = args[0].Trim();
if (!Settings.Config.Main.Advanced.SetAccount(account))
{
return string.Format(Translations.cmd_connect_unknown, args[0]);
return string.Format(Translations.cmd_connect_unknown, account);
}
}
Program.Restart(keepAccountAndServerSettings: true);
return "";
return String.Empty;
}
}
}

View file

@ -1,5 +1,6 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -9,11 +10,32 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "reload"; } }
public override string CmdDesc { get { return Translations.cmd_reload_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => DoReload(r.Source, handler))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoReload(CmdResult r, McClient handler)
{
handler.Log.Info(Translations.cmd_reload_started);
handler.ReloadSettings();
@ -22,7 +44,7 @@ namespace MinecraftClient.Commands
handler.Log.Warn(Translations.cmd_reload_warning3);
handler.Log.Warn(Translations.cmd_reload_warning4);
return Translations.cmd_reload_finished;
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_reload_finished);
}
}
}

View file

@ -1,5 +1,6 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -9,14 +10,35 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "respawn"; } }
public override string CmdDesc { get { return Translations.cmd_respawn_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => DoRespawn(r.Source, handler))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoRespawn(CmdResult r, McClient handler)
{
handler.SendRespawnPacket();
return Translations.cmd_respawn_done;
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_respawn_done);
}
}
}

View file

@ -1,5 +1,7 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -9,18 +11,36 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "script <scriptname>"; } }
public override string CmdDesc { get { return Translations.cmd_script_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Argument("Script", Arguments.GreedyString())
.Executes(r => DoExecuteScript(r.Source, handler, Arguments.GetString(r, "Script"), null)))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (HasArg(command))
return r.SetAndReturn(cmd switch
{
handler.BotLoad(new ChatBots.Script(GetArg(command), null, localVars));
return "";
}
else return GetCmdDescTranslated();
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoExecuteScript(CmdResult r, McClient handler, string command, Dictionary<string, object>? localVars)
{
handler.BotLoad(new ChatBots.Script(command.Trim(), null, localVars));
return r.SetAndReturn(CmdResult.Status.Done);
}
}
}

View file

@ -1,5 +1,6 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -9,18 +10,34 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "send <text>"; } }
public override string CmdDesc { get { return Translations.cmd_send_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Argument("any", Arguments.GreedyString())
.Executes(r => DoSendText(r.Source, handler, Arguments.GetString(r, "any"))))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (HasArg(command))
return r.SetAndReturn(cmd switch
{
handler.SendText(GetArg(command));
return "";
}
else return GetCmdDescTranslated();
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoSendText(CmdResult r, McClient handler, string command)
{
handler.SendText(command);
return r.SetAndReturn(CmdResult.Status.Done);
}
}
}

View file

@ -1,5 +1,6 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -9,27 +10,50 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "set varname=value"; } }
public override string CmdDesc { get { return Translations.cmd_set_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Argument("Expression", Arguments.GreedyString())
.Executes(r => DoSetVar(r.Source, Arguments.GetString(r, "Expression"))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (HasArg(command))
return r.SetAndReturn(cmd switch
{
string[] temp = GetArg(command).Split('=');
if (temp.Length > 1)
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoSetVar(CmdResult r, string command)
{
string[] temp = command.Trim().Split('=');
if (temp.Length > 1)
{
if (Settings.Config.AppVar.SetVar(temp[0], command[(temp[0].Length + 1)..]))
{
if (Settings.Config.AppVar.SetVar(temp[0], GetArg(command).Substring(temp[0].Length + 1)))
return ""; //Success
else
return Translations.cmd_set_format;
return r.SetAndReturn(CmdResult.Status.Done); //Success
}
else
return GetCmdDescTranslated();
{
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_set_format);
}
}
else
return GetCmdDescTranslated();
{
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_set_format);
}
}
}
}

View file

@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -11,65 +13,61 @@ namespace MinecraftClient.Commands
public override string CmdDesc { get { return Translations.cmd_setrnd_desc; } }
private static readonly Random rand = new();
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
.Then(l => l.Literal("range")
.Executes(r => GetUsage(r.Source, "range")))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Argument("VarName", Arguments.String())
.Then(l => l.Argument("Min", Arguments.Long())
.Then(l => l.Literal("to")
.Then(l => l.Argument("Max", Arguments.Long())
.Executes(r => DoSetRnd(r.Source, Arguments.GetString(r, "VarName"), Arguments.GetLong(r, "Min"), Arguments.GetLong(r, "Max"))))))
.Then(l => l.Argument("Expression", Arguments.GreedyString())
.Executes(r => DoSetRnd(r.Source, Arguments.GetString(r, "VarName"), Arguments.GetString(r, "Expression")))))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (HasArg(command))
return r.SetAndReturn(cmd switch
{
string[] args = GetArg(command).Split(' ');
#pragma warning disable format // @formatter:off
"range" => GetCmdDescTranslated(),
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
if (args.Length > 1)
{
// detect "to" keyword in string
if (args.Length == 2 && args[1].Contains("to"))
{
int num1;
int num2;
private int DoSetRnd(CmdResult r, string var, string argString)
{
// process all arguments similar to regular terminals with quotes and escaping
List<string> values = ParseCommandLine(argString);
// try to extract the two numbers from the string
try
{
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')));
}
catch (Exception)
{
return Translations.cmd_setrndnum_format;
}
// create a variable or set it to one of the values
if (values.Count > 0 && Settings.Config.AppVar.SetVar(var, values[rand.Next(0, values.Count)]))
return r.SetAndReturn(CmdResult.Status.Done, string.Format("Set %{0}% to {1}.", var, Settings.Config.AppVar.GetVar(var)));
else
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_setrndstr_format);
}
// switch the values if they were entered in the wrong way
if (num2 < num1)
(num2, num1) = (num1, num2);
private int DoSetRnd(CmdResult r, string var, long min, long max)
{
// switch the values if they were entered in the wrong way
if (max < min)
(max, min) = (min, max);
// create a variable or set it to num1 <= varlue < num2
if (Settings.Config.AppVar.SetVar(args[0], rand.Next(num1, num2)))
{
return string.Format("Set %{0}% to {1}.", args[0], Settings.Config.AppVar.GetVar(args[0])); //Success
}
else return Translations.cmd_setrndnum_format;
}
else
{
// extract all arguments of the command
string argString = command[(8 + command.Split(' ')[1].Length)..];
// process all arguments similar to regular terminals with quotes and escaping
List<string> values = ParseCommandLine(argString);
// create a variable or set it to one of the values
if (values.Count > 0 && Settings.Config.AppVar.SetVar(args[0], values[rand.Next(0, values.Count)]))
{
return string.Format("Set %{0}% to {1}.", args[0], Settings.Config.AppVar.GetVar(args[0])); //Success
}
else return Translations.cmd_setrndstr_format;
}
}
else return GetCmdDescTranslated();
}
else return GetCmdDescTranslated();
// create a variable or set it to num1 <= varlue < num2
if (Settings.Config.AppVar.SetVar(var, rand.NextInt64(min, max)))
return r.SetAndReturn(CmdResult.Status.Fail, string.Format("Set %{0}% to {1}.", var, Settings.Config.AppVar.GetVar(var)));
else
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_setrndstr_format);
}
}
}

View file

@ -1,34 +1,62 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
public class Sneak : Command
{
private bool sneaking = false;
public override string CmdName { get { return "Sneak"; } }
public override string CmdUsage { get { return "Sneak"; } }
public override string CmdName { get { return "sneak"; } }
public override string CmdUsage { get { return "sneak"; } }
public override string CmdDesc { get { return Translations.cmd_sneak_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => DoSneak(r.Source, handler))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoSneak(CmdResult r, McClient handler)
{
if (sneaking)
{
var result = handler.SendEntityAction(Protocol.EntityActionType.StopSneaking);
if (result)
sneaking = false;
return result ? Translations.cmd_sneak_off : Translations.general_fail;
if (result)
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_sneak_off);
else
return r.SetAndReturn(CmdResult.Status.Fail);
}
else
{
var result = handler.SendEntityAction(Protocol.EntityActionType.StartSneaking);
if (result)
sneaking = true;
return result ? Translations.cmd_sneak_on : Translations.general_fail;
if (result)
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_sneak_on);
else
return r.SetAndReturn(CmdResult.Status.Fail);
}
}
}

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
namespace MinecraftClient.Commands
{
@ -10,11 +11,32 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "tps"; } }
public override string CmdDesc { get { return Translations.cmd_tps_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => DoLogTps(r.Source, handler))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoLogTps(CmdResult r, McClient handler)
{
var tps = Math.Round(handler.GetServerTPS(), 2);
string color;
@ -22,9 +44,9 @@ namespace MinecraftClient.Commands
color = "§c"; // Red
else if (tps < 15)
color = "§e"; // Yellow
else
else
color = "§a"; // Green
return Translations.cmd_tps_current + ": " + color + tps;
return r.SetAndReturn(CmdResult.Status.Done, Translations.cmd_tps_current + ": " + color + tps);
}
}
}

View file

@ -1,5 +1,7 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using static MinecraftClient.CommandHandler.CmdResult;
namespace MinecraftClient.Commands
{
@ -9,18 +11,38 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "useitem"; } }
public override string CmdDesc { get { return Translations.cmd_useitem_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Executes(r => DoUseItem(r.Source, handler))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
if (handler.GetInventoryEnabled())
return r.SetAndReturn(cmd switch
{
handler.UseItemOnHand();
return Translations.cmd_useitem_use;
}
else return Translations.extra_inventory_required;
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int DoUseItem(CmdResult r, McClient handler)
{
if (!handler.GetInventoryEnabled())
return r.SetAndReturn(Status.FailNeedInventory);
handler.UseItemOnHand();
return r.SetAndReturn(Status.Done, Translations.cmd_useitem_use);
}
}
}

View file

@ -1,6 +1,8 @@
using System.Collections.Generic;
using Brigadier.NET;
using Brigadier.NET.Builder;
using MinecraftClient.CommandHandler;
using MinecraftClient.Mapping;
using static MinecraftClient.CommandHandler.CmdResult;
namespace MinecraftClient.Commands
{
@ -10,29 +12,42 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "useblock <x> <y> <z>"; } }
public override string CmdDesc { get { return Translations.cmd_useblock_desc; } }
public override void RegisterCommand(McClient handler, CommandDispatcher<CommandSource> dispatcher)
public override void RegisterCommand(McClient handler, CommandDispatcher<CmdResult> dispatcher)
{
dispatcher.Register(l => l.Literal("help")
.Then(l => l.Literal(CmdName)
.Executes(r => GetUsage(r.Source, string.Empty))
)
);
dispatcher.Register(l => l.Literal(CmdName)
.Then(l => l.Argument("Location", MccArguments.Location())
.Executes(r => UseBlockAtLocation(r.Source, handler, MccArguments.GetLocation(r, "Location"))))
.Then(l => l.Literal("_help")
.Redirect(dispatcher.GetRoot().GetChild("help").GetChild(CmdName)))
);
}
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
private int GetUsage(CmdResult r, string? cmd)
{
return r.SetAndReturn(cmd switch
{
#pragma warning disable format // @formatter:off
_ => GetCmdDescTranslated(),
#pragma warning restore format // @formatter:on
});
}
private int UseBlockAtLocation(CmdResult r, McClient handler, Location block)
{
if (!handler.GetTerrainEnabled())
return Translations.extra_terrainandmovement_required;
else if (HasArg(command))
{
string[] args = GetArgs(command);
if (args.Length >= 3)
{
Location block = Location.Parse(handler.GetCurrentLocation().ToFloor(), args[0], args[1], args[2]).ToFloor();
Location blockCenter = block.ToCenter();
bool res = handler.PlaceBlock(block, Direction.Down);
return string.Format(Translations.cmd_useblock_use, blockCenter.X, blockCenter.Y, blockCenter.Z, res ? "succeeded" : "failed");
}
else
return GetCmdDescTranslated();
}
else
return GetCmdDescTranslated();
return r.SetAndReturn(Status.FailNeedTerrain);
Location current = handler.GetCurrentLocation();
block = block.ToAbsolute(current).ToFloor();
Location blockCenter = block.ToCenter();
bool res = handler.PlaceBlock(block, Direction.Down);
return r.SetAndReturn(string.Format(Translations.cmd_useblock_use, blockCenter.X, blockCenter.Y, blockCenter.Z, res ? "succeeded" : "failed"), res);
}
}
}