From f9482906ae7ce4dfd41bb4236e094be5d4fa7689 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 2 Jul 2017 01:32:07 -0400 Subject: split TrainerMod commands into separate classes (#302) --- .../Framework/Commands/ITrainerCommand.cs | 34 ++++++ .../Framework/Commands/Other/DebugCommand.cs | 33 ++++++ .../Commands/Other/ShowDataFilesCommand.cs | 26 +++++ .../Commands/Other/ShowGameFilesCommand.cs | 26 +++++ .../Commands/Player/AddFlooringCommand.cs | 47 ++++++++ .../Framework/Commands/Player/AddItemCommand.cs | 68 ++++++++++++ .../Framework/Commands/Player/AddRingCommand.cs | 47 ++++++++ .../Commands/Player/AddWallpaperCommand.cs | 47 ++++++++ .../Framework/Commands/Player/AddWeaponCommand.cs | 88 +++++++++++++++ .../Framework/Commands/Player/ListItemsCommand.cs | 120 +++++++++++++++++++++ .../Framework/Commands/Player/SetColorCommand.cs | 79 ++++++++++++++ .../Framework/Commands/Player/SetHealthCommand.cs | 72 +++++++++++++ .../Commands/Player/SetImmunityCommand.cs | 40 +++++++ .../Framework/Commands/Player/SetLevelCommand.cs | 73 +++++++++++++ .../Commands/Player/SetMaxHealthCommand.cs | 40 +++++++ .../Commands/Player/SetMaxStaminaCommand.cs | 40 +++++++ .../Framework/Commands/Player/SetMoneyCommand.cs | 72 +++++++++++++ .../Framework/Commands/Player/SetNameCommand.cs | 47 ++++++++ .../Framework/Commands/Player/SetSpeedCommand.cs | 40 +++++++ .../Framework/Commands/Player/SetStaminaCommand.cs | 72 +++++++++++++ .../Framework/Commands/Player/SetStyleCommand.cs | 102 ++++++++++++++++++ .../Framework/Commands/Saves/LoadCommand.cs | 28 +++++ .../Framework/Commands/Saves/SaveCommand.cs | 27 +++++ .../Framework/Commands/TrainerCommand.cs | 72 +++++++++++++ .../Commands/World/DownMineLevelCommand.cs | 28 +++++ .../Framework/Commands/World/FreezeTimeCommand.cs | 72 +++++++++++++ .../Framework/Commands/World/SetDayCommand.cs | 45 ++++++++ .../Commands/World/SetMineLevelCommand.cs | 42 ++++++++ .../Framework/Commands/World/SetSeasonCommand.cs | 47 ++++++++ .../Framework/Commands/World/SetTimeCommand.cs | 46 ++++++++ .../Framework/Commands/World/SetYearCommand.cs | 45 ++++++++ 31 files changed, 1665 insertions(+) create mode 100644 src/TrainerMod/Framework/Commands/ITrainerCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Other/DebugCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Other/ShowDataFilesCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Other/ShowGameFilesCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/AddFlooringCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/AddItemCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/AddRingCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/AddWallpaperCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/AddWeaponCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/SetColorCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/SetHealthCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/SetImmunityCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/SetLevelCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/SetMaxHealthCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/SetMaxStaminaCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/SetMoneyCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/SetNameCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/SetSpeedCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/SetStaminaCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Player/SetStyleCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Saves/LoadCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/Saves/SaveCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/TrainerCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/World/DownMineLevelCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/World/FreezeTimeCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/World/SetDayCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/World/SetMineLevelCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/World/SetSeasonCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/World/SetTimeCommand.cs create mode 100644 src/TrainerMod/Framework/Commands/World/SetYearCommand.cs (limited to 'src/TrainerMod/Framework/Commands') diff --git a/src/TrainerMod/Framework/Commands/ITrainerCommand.cs b/src/TrainerMod/Framework/Commands/ITrainerCommand.cs new file mode 100644 index 00000000..55f36ceb --- /dev/null +++ b/src/TrainerMod/Framework/Commands/ITrainerCommand.cs @@ -0,0 +1,34 @@ +using StardewModdingAPI; + +namespace TrainerMod.Framework.Commands +{ + /// A TrainerMod command to register. + internal interface ITrainerCommand + { + /********* + ** Accessors + *********/ + /// The command name the user must type. + string Name { get; } + + /// The command description. + string Description { get; } + + /// Whether the command needs to perform logic when the game updates. + bool NeedsUpdate { get; } + + + /********* + ** Public methods + *********/ + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + void Handle(IMonitor monitor, string command, string[] args); + + /// Perform any logic needed on update tick. + /// Writes messages to the console and log file. + void Update(IMonitor monitor); + } +} diff --git a/src/TrainerMod/Framework/Commands/Other/DebugCommand.cs b/src/TrainerMod/Framework/Commands/Other/DebugCommand.cs new file mode 100644 index 00000000..ad38d1ba --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Other/DebugCommand.cs @@ -0,0 +1,33 @@ +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Other +{ + /// A command which sends a debug command to the game. + internal class DebugCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public DebugCommand() + : base("debug", "Run one of the game's debug commands; for example, 'debug warp FarmHouse 1 1' warps the player to the farmhouse.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // submit command + string debugCommand = string.Join(" ", args); + string oldOutput = Game1.debugOutput; + Game1.game1.parseDebugInput(debugCommand); + + // show result + monitor.Log(Game1.debugOutput != oldOutput + ? $"> {Game1.debugOutput}" + : "Sent debug command to the game, but there was no output.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Other/ShowDataFilesCommand.cs b/src/TrainerMod/Framework/Commands/Other/ShowDataFilesCommand.cs new file mode 100644 index 00000000..b2985bb1 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Other/ShowDataFilesCommand.cs @@ -0,0 +1,26 @@ +using System.Diagnostics; +using StardewModdingAPI; + +namespace TrainerMod.Framework.Commands.Other +{ + /// A command which shows the data files. + internal class ShowDataFilesCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public ShowDataFilesCommand() + : base("show_data_files", "Opens the folder containing the save and log files.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + Process.Start(Constants.DataPath); + monitor.Log($"OK, opening {Constants.DataPath}.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Other/ShowGameFilesCommand.cs b/src/TrainerMod/Framework/Commands/Other/ShowGameFilesCommand.cs new file mode 100644 index 00000000..5695ce9a --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Other/ShowGameFilesCommand.cs @@ -0,0 +1,26 @@ +using System.Diagnostics; +using StardewModdingAPI; + +namespace TrainerMod.Framework.Commands.Other +{ + /// A command which shows the game files. + internal class ShowGameFilesCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public ShowGameFilesCommand() + : base("show_game_files", "Opens the game folder.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + Process.Start(Constants.ExecutionPath); + monitor.Log($"OK, opening {Constants.ExecutionPath}.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/AddFlooringCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddFlooringCommand.cs new file mode 100644 index 00000000..57bd39e3 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/AddFlooringCommand.cs @@ -0,0 +1,47 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; +using StardewValley.Objects; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which adds a floor item to the player inventory. + internal class AddFlooringCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public AddFlooringCommand() + : base("player_addflooring", "Gives the player a flooring item.\n\nUsage: player_addflooring \n- flooring: the flooring ID (ranges from 0 to 39).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + this.LogArgumentsInvalid(monitor, command); + return; + } + if (!int.TryParse(args[0], out int floorID)) + { + this.LogArgumentNotInt(monitor, command); + return; + } + if (floorID < 0 || floorID > 39) + { + monitor.Log("There is no such flooring ID (must be between 0 and 39).", LogLevel.Error); + return; + } + + // handle + Wallpaper wallpaper = new Wallpaper(floorID, isFloor: true); + Game1.player.addItemByMenuIfNecessary(wallpaper); + monitor.Log($"OK, added flooring {floorID} to your inventory.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/AddItemCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddItemCommand.cs new file mode 100644 index 00000000..6d3cf968 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/AddItemCommand.cs @@ -0,0 +1,68 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which adds an item to the player inventory. + internal class AddItemCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public AddItemCommand() + : base("player_additem", $"Gives the player an item.\n\nUsage: player_additem [count] [quality]\n- item: the item ID (use the 'list_items' command to see a list).\n- count (optional): how many of the item to give.\n- quality (optional): one of {Object.lowQuality} (normal), {Object.medQuality} (silver), {Object.highQuality} (gold), or {Object.bestQuality} (iridium).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + this.LogArgumentsInvalid(monitor, command); + return; + } + if (!int.TryParse(args[0], out int itemID)) + { + this.LogUsageError(monitor, "The item ID must be an integer.", command); + return; + } + + // parse arguments + int count = 1; + int quality = 0; + if (args.Length > 1) + { + if (!int.TryParse(args[1], out count)) + { + this.LogUsageError(monitor, "The optional count is invalid.", command); + return; + } + } + if (args.Length > 2) + { + if (!int.TryParse(args[2], out quality)) + { + this.LogUsageError(monitor, "The optional quality is invalid.", command); + return; + } + } + + // spawn item + var item = new Object(itemID, count) { quality = quality }; + if (item.Name == "Error Item") + { + monitor.Log("There is no such item ID.", LogLevel.Error); + return; + } + + // add to inventory + Game1.player.addItemByMenuIfNecessary(item); + monitor.Log($"OK, added {item.Name} to your inventory.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/AddRingCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddRingCommand.cs new file mode 100644 index 00000000..d62d8b5b --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/AddRingCommand.cs @@ -0,0 +1,47 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; +using StardewValley.Objects; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which adds a ring to the player inventory. + internal class AddRingCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public AddRingCommand() + : base("player_addring", "Gives the player a ring.\n\nUsage: player_addring \n- item: the ring ID (use the 'list_items' command to see a list).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + this.LogArgumentsInvalid(monitor, command); + return; + } + if (!int.TryParse(args[0], out int ringID)) + { + monitor.Log(" is invalid", LogLevel.Error); + return; + } + if (ringID < Ring.ringLowerIndexRange || ringID > Ring.ringUpperIndexRange) + { + monitor.Log($"There is no such ring ID (must be between {Ring.ringLowerIndexRange} and {Ring.ringUpperIndexRange}).", LogLevel.Error); + return; + } + + // handle + Ring ring = new Ring(ringID); + Game1.player.addItemByMenuIfNecessary(ring); + monitor.Log($"OK, added {ring.Name} to your inventory.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/AddWallpaperCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddWallpaperCommand.cs new file mode 100644 index 00000000..e02b05a4 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/AddWallpaperCommand.cs @@ -0,0 +1,47 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; +using StardewValley.Objects; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which adds a wallpaper item to the player inventory. + internal class AddWallpaperCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public AddWallpaperCommand() + : base("player_addwallpaper", "Gives the player a wallpaper.\n\nUsage: player_addwallpaper \n- wallpaper: the wallpaper ID (ranges from 0 to 111).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + this.LogArgumentsInvalid(monitor, command); + return; + } + if (!int.TryParse(args[0], out int wallpaperID)) + { + this.LogArgumentNotInt(monitor, command); + return; + } + if (wallpaperID < 0 || wallpaperID > 111) + { + monitor.Log("There is no such wallpaper ID (must be between 0 and 111).", LogLevel.Error); + return; + } + + // handle + Wallpaper wallpaper = new Wallpaper(wallpaperID); + Game1.player.addItemByMenuIfNecessary(wallpaper); + monitor.Log($"OK, added wallpaper {wallpaperID} to your inventory.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/AddWeaponCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddWeaponCommand.cs new file mode 100644 index 00000000..ee94093f --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/AddWeaponCommand.cs @@ -0,0 +1,88 @@ +using System.Collections.Generic; +using System.Linq; +using StardewModdingAPI; +using StardewValley; +using StardewValley.Tools; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which adds a weapon to the player inventory. + internal class AddWeaponCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public AddWeaponCommand() + : base("player_addweapon", "Gives the player a weapon.\n\nUsage: player_addweapon \n- item: the weapon ID (use the 'list_items' command to see a list).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + this.LogArgumentsInvalid(monitor, command); + return; + } + if (!int.TryParse(args[0], out int weaponID)) + { + this.LogUsageError(monitor, "The weapon ID must be an integer.", command); + return; + } + + // get raw weapon data + if (!Game1.content.Load>("Data\\weapons").TryGetValue(weaponID, out string data)) + { + monitor.Log("There is no such weapon ID.", LogLevel.Error); + return; + } + + // get raw weapon type + int type; + { + string[] fields = data.Split('/'); + string typeStr = fields.Length > 8 ? fields[8] : null; + if (!int.TryParse(typeStr, out type)) + { + monitor.Log("Could not parse the data for the weapon with that ID.", LogLevel.Error); + return; + } + } + + // get weapon + Tool weapon; + switch (type) + { + case MeleeWeapon.stabbingSword: + case MeleeWeapon.dagger: + case MeleeWeapon.club: + case MeleeWeapon.defenseSword: + weapon = new MeleeWeapon(weaponID); + break; + + case 4: + weapon = new Slingshot(weaponID); + break; + + default: + monitor.Log($"The specified weapon has unknown type '{type}' in the game data.", LogLevel.Error); + return; + } + + // validate weapon + if (weapon.Name == null) + { + monitor.Log("That weapon doesn't seem to be valid.", LogLevel.Error); + return; + } + + // add weapon + Game1.player.addItemByMenuIfNecessary(weapon); + monitor.Log($"OK, added {weapon.Name} to your inventory.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs b/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs new file mode 100644 index 00000000..a1b9aceb --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using StardewModdingAPI; +using StardewValley; +using StardewValley.Objects; +using TrainerMod.Framework.ItemData; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which list items available to spawn. + internal class ListItemsCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public ListItemsCommand() + : base("list_items", "Lists and searches items in the game data.\n\nUsage: list_items [search]\n- search (optional): an arbitrary search string to filter by.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + var matches = this.GetItems(args).ToArray(); + + // show matches + string summary = "Searching...\n"; + if (matches.Any()) + monitor.Log(summary + this.GetTableString(matches, new[] { "type", "id", "name" }, val => new[] { val.Type.ToString(), val.ID.ToString(), val.Name }), LogLevel.Info); + else + monitor.Log(summary + "No items found", LogLevel.Info); + } + + + /********* + ** Private methods + *********/ + /// Get all items which can be searched and added to the player's inventory through the console. + /// The search string to find. + private IEnumerable GetItems(string[] searchWords) + { + // normalise search term + searchWords = searchWords?.Where(word => !string.IsNullOrWhiteSpace(word)).ToArray(); + if (searchWords?.Any() == false) + searchWords = null; + + // find matches + return ( + from item in this.GetItems() + let term = $"{item.ID}|{item.Type}|{item.Name}" + where searchWords == null || searchWords.All(word => term.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) != -1) + select item + ); + } + + /// Get all items which can be searched and added to the player's inventory through the console. + private IEnumerable GetItems() + { + // objects + foreach (int id in Game1.objectInformation.Keys) + { + ISearchItem obj = id >= Ring.ringLowerIndexRange && id <= Ring.ringUpperIndexRange + ? new SearchableRing(id) + : (ISearchItem)new SearchableObject(id); + if (obj.IsValid) + yield return obj; + } + + // weapons + foreach (int id in Game1.content.Load>("Data\\weapons").Keys) + { + ISearchItem weapon = new SearchableWeapon(id); + if (weapon.IsValid) + yield return weapon; + } + } + + /// Get an ASCII table for a set of tabular data. + /// The data type. + /// The data to display. + /// The table header. + /// Returns a set of fields for a data value. + private string GetTableString(IEnumerable data, string[] header, Func getRow) + { + // get table data + int[] widths = header.Select(p => p.Length).ToArray(); + string[][] rows = data + .Select(item => + { + string[] fields = getRow(item); + if (fields.Length != widths.Length) + throw new InvalidOperationException($"Expected {widths.Length} columns, but found {fields.Length}: {string.Join(", ", fields)}"); + + for (int i = 0; i < fields.Length; i++) + widths[i] = Math.Max(widths[i], fields[i].Length); + + return fields; + }) + .ToArray(); + + // render fields + List lines = new List(rows.Length + 2) + { + header, + header.Select((value, i) => "".PadRight(widths[i], '-')).ToArray() + }; + lines.AddRange(rows); + + return string.Join( + Environment.NewLine, + lines.Select(line => string.Join(" | ", + line.Select((field, i) => field.PadRight(widths[i], ' ')).ToArray()) + ) + ); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/SetColorCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetColorCommand.cs new file mode 100644 index 00000000..00907fba --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/SetColorCommand.cs @@ -0,0 +1,79 @@ +using Microsoft.Xna.Framework; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which edits the color of a player feature. + internal class SetColorCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetColorCommand() + : base("player_changecolor", "Sets the color of a player feature.\n\nUsage: player_changecolor \n- target: what to change (one of 'hair', 'eyes', or 'pants').\n- color: a color value in RGB format, like (255,255,255).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (args.Length <= 2) + { + this.LogArgumentsInvalid(monitor, command); + return; + } + if (!this.TryParseColor(args[1], out Color color)) + { + this.LogUsageError(monitor, "The color should be an RBG value like '255,150,0'.", command); + return; + } + + // handle + switch (args[0]) + { + case "hair": + Game1.player.hairstyleColor = color; + monitor.Log("OK, your hair color is updated.", LogLevel.Info); + break; + + case "eyes": + Game1.player.changeEyeColor(color); + monitor.Log("OK, your eye color is updated.", LogLevel.Info); + break; + + case "pants": + Game1.player.pantsColor = color; + monitor.Log("OK, your pants color is updated.", LogLevel.Info); + break; + + default: + this.LogArgumentsInvalid(monitor, command); + break; + } + } + + + /********* + ** Private methods + *********/ + /// Try to parse a color from a string. + /// The input string. + /// The color to set. + private bool TryParseColor(string input, out Color color) + { + string[] colorHexes = input.Split(new[] { ',' }, 3); + if (int.TryParse(colorHexes[0], out int r) && int.TryParse(colorHexes[1], out int g) && int.TryParse(colorHexes[2], out int b)) + { + color = new Color(r, g, b); + return true; + } + + color = Color.Transparent; + return false; + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/SetHealthCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetHealthCommand.cs new file mode 100644 index 00000000..d3f06459 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/SetHealthCommand.cs @@ -0,0 +1,72 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which edits the player's current health. + internal class SetHealthCommand : TrainerCommand + { + /********* + ** Properties + *********/ + /// Whether to keep the player's health at its maximum. + private bool InfiniteHealth; + + + /********* + ** Accessors + *********/ + /// Whether the command needs to perform logic when the game updates. + public override bool NeedsUpdate => this.InfiniteHealth; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetHealthCommand() + : base("player_sethealth", "Sets the player's health.\n\nUsage: player_sethealth [value]\n- value: an integer amount, or 'inf' for infinite health.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + monitor.Log($"You currently have {(this.InfiniteHealth ? "infinite" : Game1.player.health.ToString())} health. Specify a value to change it.", LogLevel.Info); + return; + } + + // handle + string amountStr = args[0]; + if (amountStr == "inf") + { + this.InfiniteHealth = true; + monitor.Log("OK, you now have infinite health.", LogLevel.Info); + } + else + { + this.InfiniteHealth = false; + if (int.TryParse(amountStr, out int amount)) + { + Game1.player.health = amount; + monitor.Log($"OK, you now have {Game1.player.health} health.", LogLevel.Info); + } + else + this.LogArgumentNotInt(monitor, command); + } + } + + /// Perform any logic needed on update tick. + /// Writes messages to the console and log file. + public override void Update(IMonitor monitor) + { + if (this.InfiniteHealth) + Game1.player.health = Game1.player.maxHealth; + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/SetImmunityCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetImmunityCommand.cs new file mode 100644 index 00000000..ff74f981 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/SetImmunityCommand.cs @@ -0,0 +1,40 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which edits the player's current immunity. + internal class SetImmunityCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetImmunityCommand() + : base("player_setimmunity", "Sets the player's immunity.\n\nUsage: player_setimmunity [value]\n- value: an integer amount.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + monitor.Log($"You currently have {Game1.player.immunity} immunity. Specify a value to change it.", LogLevel.Info); + return; + } + + // handle + if (int.TryParse(args[0], out int amount)) + { + Game1.player.immunity = amount; + monitor.Log($"OK, you now have {Game1.player.immunity} immunity.", LogLevel.Info); + } + else + this.LogArgumentNotInt(monitor, command); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/SetLevelCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetLevelCommand.cs new file mode 100644 index 00000000..4982a0b8 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/SetLevelCommand.cs @@ -0,0 +1,73 @@ +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which edits the player's current level for a skill. + internal class SetLevelCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetLevelCommand() + : base("player_setlevel", "Sets the player's specified skill to the specified value.\n\nUsage: player_setlevel \n- skill: the skill to set (one of 'luck', 'mining', 'combat', 'farming', 'fishing', or 'foraging').\n- value: the target level (a number from 1 to 10).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (args.Length <= 2) + { + this.LogArgumentsInvalid(monitor, command); + return; + } + if (!int.TryParse(args[1], out int level)) + { + this.LogArgumentNotInt(monitor, command); + return; + } + + // handle + switch (args[0]) + { + case "luck": + Game1.player.LuckLevel = level; + monitor.Log($"OK, your luck skill is now {Game1.player.LuckLevel}.", LogLevel.Info); + break; + + case "mining": + Game1.player.MiningLevel = level; + monitor.Log($"OK, your mining skill is now {Game1.player.MiningLevel}.", LogLevel.Info); + break; + + case "combat": + Game1.player.CombatLevel = level; + monitor.Log($"OK, your combat skill is now {Game1.player.CombatLevel}.", LogLevel.Info); + break; + + case "farming": + Game1.player.FarmingLevel = level; + monitor.Log($"OK, your farming skill is now {Game1.player.FarmingLevel}.", LogLevel.Info); + break; + + case "fishing": + Game1.player.FishingLevel = level; + monitor.Log($"OK, your fishing skill is now {Game1.player.FishingLevel}.", LogLevel.Info); + break; + + case "foraging": + Game1.player.ForagingLevel = level; + monitor.Log($"OK, your foraging skill is now {Game1.player.ForagingLevel}.", LogLevel.Info); + break; + + default: + this.LogUsageError(monitor, "That isn't a valid skill.", command); + break; + } + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/SetMaxHealthCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetMaxHealthCommand.cs new file mode 100644 index 00000000..73ba252a --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/SetMaxHealthCommand.cs @@ -0,0 +1,40 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which edits the player's maximum health. + internal class SetMaxHealthCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetMaxHealthCommand() + : base("player_setmaxhealth", "Sets the player's max health.\n\nUsage: player_setmaxhealth [value]\n- value: an integer amount.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + monitor.Log($"You currently have {Game1.player.maxHealth} max health. Specify a value to change it.", LogLevel.Info); + return; + } + + // handle + if (int.TryParse(args[0], out int maxHealth)) + { + Game1.player.maxHealth = maxHealth; + monitor.Log($"OK, you now have {Game1.player.maxHealth} max health.", LogLevel.Info); + } + else + this.LogArgumentNotInt(monitor, command); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/SetMaxStaminaCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetMaxStaminaCommand.cs new file mode 100644 index 00000000..c21f6592 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/SetMaxStaminaCommand.cs @@ -0,0 +1,40 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which edits the player's maximum stamina. + internal class SetMaxStaminaCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetMaxStaminaCommand() + : base("player_setmaxstamina", "Sets the player's max stamina.\n\nUsage: player_setmaxstamina [value]\n- value: an integer amount.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + monitor.Log($"You currently have {Game1.player.MaxStamina} max stamina. Specify a value to change it.", LogLevel.Info); + return; + } + + // handle + if (int.TryParse(args[0], out int amount)) + { + Game1.player.MaxStamina = amount; + monitor.Log($"OK, you now have {Game1.player.MaxStamina} max stamina.", LogLevel.Info); + } + else + this.LogArgumentNotInt(monitor, command); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/SetMoneyCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetMoneyCommand.cs new file mode 100644 index 00000000..ad74499d --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/SetMoneyCommand.cs @@ -0,0 +1,72 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which edits the player's current money. + internal class SetMoneyCommand : TrainerCommand + { + /********* + ** Properties + *********/ + /// Whether to keep the player's money at a set value. + private bool InfiniteMoney; + + + /********* + ** Accessors + *********/ + /// Whether the command needs to perform logic when the game updates. + public override bool NeedsUpdate => this.InfiniteMoney; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetMoneyCommand() + : base("player_setmoney", "Sets the player's money.\n\nUsage: player_setmoney \n- value: an integer amount, or 'inf' for infinite money.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + monitor.Log($"You currently have {(this.InfiniteMoney ? "infinite" : Game1.player.Money.ToString())} gold. Specify a value to change it.", LogLevel.Info); + return; + } + + // handle + string amountStr = args[0]; + if (amountStr == "inf") + { + this.InfiniteMoney = true; + monitor.Log("OK, you now have infinite money.", LogLevel.Info); + } + else + { + this.InfiniteMoney = false; + if (int.TryParse(amountStr, out int amount)) + { + Game1.player.Money = amount; + monitor.Log($"OK, you now have {Game1.player.Money} gold.", LogLevel.Info); + } + else + this.LogArgumentNotInt(monitor, command); + } + } + + /// Perform any logic needed on update tick. + /// Writes messages to the console and log file. + public override void Update(IMonitor monitor) + { + if (this.InfiniteMoney) + Game1.player.money = 999999; + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/SetNameCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetNameCommand.cs new file mode 100644 index 00000000..8284d882 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/SetNameCommand.cs @@ -0,0 +1,47 @@ +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which edits the player's name. + internal class SetNameCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetNameCommand() + : base("player_setname", "Sets the player's name.\n\nUsage: player_setname \n- target: what to rename (one of 'player' or 'farm').\n- name: the new name to set.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (args.Length <= 1) + { + monitor.Log($"Your name is currently '{Game1.player.Name}'. Type 'help player_setname' for usage.", LogLevel.Info); + return; + } + + // handle + string target = args[0]; + switch (target) + { + case "player": + Game1.player.Name = args[1]; + monitor.Log($"OK, your player's name is now {Game1.player.Name}.", LogLevel.Info); + break; + case "farm": + Game1.player.farmName = args[1]; + monitor.Log($"OK, your farm's name is now {Game1.player.Name}.", LogLevel.Info); + break; + default: + this.LogArgumentsInvalid(monitor, command); + break; + } + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/SetSpeedCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetSpeedCommand.cs new file mode 100644 index 00000000..a8c05d0c --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/SetSpeedCommand.cs @@ -0,0 +1,40 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which edits the player's current added speed. + internal class SetSpeedCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetSpeedCommand() + : base("player_setspeed", "Sets the player's added speed to the specified value.\n\nUsage: player_setspeed \n- value: an integer amount (0 is normal).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + monitor.Log($"You currently have {Game1.player.addedSpeed} added speed. Specify a value to change it.", LogLevel.Info); + return; + } + if (!int.TryParse(args[0], out int addedSpeed)) + { + this.LogArgumentNotInt(monitor, command); + return; + } + + // handle + Game1.player.addedSpeed = addedSpeed; + monitor.Log($"OK, your added speed is now {Game1.player.addedSpeed}.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/SetStaminaCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetStaminaCommand.cs new file mode 100644 index 00000000..55a55eab --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/SetStaminaCommand.cs @@ -0,0 +1,72 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which edits the player's current stamina. + internal class SetStaminaCommand : TrainerCommand + { + /********* + ** Properties + *********/ + /// Whether to keep the player's stamina at its maximum. + private bool InfiniteStamina; + + + /********* + ** Accessors + *********/ + /// Whether the command needs to perform logic when the game updates. + public override bool NeedsUpdate => this.InfiniteStamina; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetStaminaCommand() + : base("player_setstamina", "Sets the player's stamina.\n\nUsage: player_setstamina [value]\n- value: an integer amount, or 'inf' for infinite stamina.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + monitor.Log($"You currently have {(this.InfiniteStamina ? "infinite" : Game1.player.Stamina.ToString())} stamina. Specify a value to change it.", LogLevel.Info); + return; + } + + // handle + string amountStr = args[0]; + if (amountStr == "inf") + { + this.InfiniteStamina = true; + monitor.Log("OK, you now have infinite stamina.", LogLevel.Info); + } + else + { + this.InfiniteStamina = false; + if (int.TryParse(amountStr, out int amount)) + { + Game1.player.Stamina = amount; + monitor.Log($"OK, you now have {Game1.player.Stamina} stamina.", LogLevel.Info); + } + else + this.LogArgumentNotInt(monitor, command); + } + } + + /// Perform any logic needed on update tick. + /// Writes messages to the console and log file. + public override void Update(IMonitor monitor) + { + if (this.InfiniteStamina) + Game1.player.stamina = Game1.player.MaxStamina; + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/SetStyleCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetStyleCommand.cs new file mode 100644 index 00000000..9ef5f88b --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/SetStyleCommand.cs @@ -0,0 +1,102 @@ +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which edits a player style. + internal class SetStyleCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetStyleCommand() + : base("player_changestyle", "Sets the style of a player feature.\n\nUsage: player_changecolor .\n- target: what to change (one of 'hair', 'shirt', 'skin', 'acc', 'shoe', 'swim', or 'gender').\n- value: the integer style ID.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (args.Length <= 1) + { + this.LogArgumentsInvalid(monitor, command); + return; + } + if (!int.TryParse(args[1], out int styleID)) + { + this.LogArgumentsInvalid(monitor, command); + return; + } + + // handle + switch (args[0]) + { + case "hair": + Game1.player.changeHairStyle(styleID); + monitor.Log("OK, your hair style is updated.", LogLevel.Info); + break; + + case "shirt": + Game1.player.changeShirt(styleID); + monitor.Log("OK, your shirt style is updated.", LogLevel.Info); + break; + + case "acc": + Game1.player.changeAccessory(styleID); + monitor.Log("OK, your accessory style is updated.", LogLevel.Info); + break; + + case "skin": + Game1.player.changeSkinColor(styleID); + monitor.Log("OK, your skin color is updated.", LogLevel.Info); + break; + + case "shoe": + Game1.player.changeShoeColor(styleID); + monitor.Log("OK, your shoe style is updated.", LogLevel.Info); + break; + + case "swim": + switch (styleID) + { + case 0: + Game1.player.changeOutOfSwimSuit(); + monitor.Log("OK, you're no longer in your swimming suit.", LogLevel.Info); + break; + case 1: + Game1.player.changeIntoSwimsuit(); + monitor.Log("OK, you're now in your swimming suit.", LogLevel.Info); + break; + default: + this.LogUsageError(monitor, "The swim value should be 0 (no swimming suit) or 1 (swimming suit).", command); + break; + } + break; + + case "gender": + switch (styleID) + { + case 0: + Game1.player.changeGender(true); + monitor.Log("OK, you're now male.", LogLevel.Info); + break; + case 1: + Game1.player.changeGender(false); + monitor.Log("OK, you're now female.", LogLevel.Info); + break; + default: + this.LogUsageError(monitor, "The gender value should be 0 (male) or 1 (female).", command); + break; + } + break; + + default: + this.LogArgumentsInvalid(monitor, command); + break; + } + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Saves/LoadCommand.cs b/src/TrainerMod/Framework/Commands/Saves/LoadCommand.cs new file mode 100644 index 00000000..1a70b54c --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Saves/LoadCommand.cs @@ -0,0 +1,28 @@ +using StardewModdingAPI; +using StardewValley; +using StardewValley.Menus; + +namespace TrainerMod.Framework.Commands.Saves +{ + /// A command which shows the load screen. + internal class LoadCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public LoadCommand() + : base("load", "Shows the load screen.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + monitor.Log("Triggering load menu...", LogLevel.Info); + Game1.hasLoadedGame = false; + Game1.activeClickableMenu = new LoadGameMenu(); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Saves/SaveCommand.cs b/src/TrainerMod/Framework/Commands/Saves/SaveCommand.cs new file mode 100644 index 00000000..8ce9738d --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Saves/SaveCommand.cs @@ -0,0 +1,27 @@ +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.Saves +{ + /// A command which saves the game. + internal class SaveCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SaveCommand() + : base("save", "Saves the game? Doesn't seem to work.") { } + + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + monitor.Log("Saving the game...", LogLevel.Info); + SaveGame.Save(); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/TrainerCommand.cs b/src/TrainerMod/Framework/Commands/TrainerCommand.cs new file mode 100644 index 00000000..1b18b44b --- /dev/null +++ b/src/TrainerMod/Framework/Commands/TrainerCommand.cs @@ -0,0 +1,72 @@ +using StardewModdingAPI; + +namespace TrainerMod.Framework.Commands +{ + /// The base implementation for a trainer command. + internal abstract class TrainerCommand : ITrainerCommand + { + /********* + ** Accessors + *********/ + /// The command name the user must type. + public string Name { get; } + + /// The command description. + public string Description { get; } + + /// Whether the command needs to perform logic when the game updates. + public virtual bool NeedsUpdate { get; } = false; + + + /********* + ** Public methods + *********/ + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public abstract void Handle(IMonitor monitor, string command, string[] args); + + /// Perform any logic needed on update tick. + /// Writes messages to the console and log file. + public virtual void Update(IMonitor monitor) { } + + + /********* + ** Protected methods + *********/ + /// Construct an instance. + /// The command name the user must type. + /// The command description. + protected TrainerCommand(string name, string description) + { + this.Name = name; + this.Description = description; + } + + /// Log an error indicating incorrect usage. + /// Writes messages to the console and log file. + /// A sentence explaining the problem. + /// The name of the command. + protected void LogUsageError(IMonitor monitor, string error, string command) + { + monitor.Log($"{error} Type 'help {command}' for usage.", LogLevel.Error); + } + + /// Log an error indicating a value must be an integer. + /// Writes messages to the console and log file. + /// The name of the command. + protected void LogArgumentNotInt(IMonitor monitor, string command) + { + this.LogUsageError(monitor, "The value must be a whole number.", command); + } + + /// Log an error indicating a value is invalid. + /// Writes messages to the console and log file. + /// The name of the command. + protected void LogArgumentsInvalid(IMonitor monitor, string command) + { + this.LogUsageError(monitor, "The arguments are invalid.", command); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/World/DownMineLevelCommand.cs b/src/TrainerMod/Framework/Commands/World/DownMineLevelCommand.cs new file mode 100644 index 00000000..2700a0dc --- /dev/null +++ b/src/TrainerMod/Framework/Commands/World/DownMineLevelCommand.cs @@ -0,0 +1,28 @@ +using StardewModdingAPI; +using StardewValley; +using StardewValley.Locations; + +namespace TrainerMod.Framework.Commands.World +{ + /// A command which moves the player to the next mine level. + internal class DownMineLevelCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public DownMineLevelCommand() + : base("world_downminelevel", "Goes down one mine level.") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + int level = (Game1.currentLocation as MineShaft)?.mineLevel ?? 0; + monitor.Log($"OK, warping you to mine level {level + 1}.", LogLevel.Info); + Game1.enterMine(false, level + 1, ""); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/World/FreezeTimeCommand.cs b/src/TrainerMod/Framework/Commands/World/FreezeTimeCommand.cs new file mode 100644 index 00000000..89cd68cb --- /dev/null +++ b/src/TrainerMod/Framework/Commands/World/FreezeTimeCommand.cs @@ -0,0 +1,72 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.World +{ + /// A command which freezes the current time. + internal class FreezeTimeCommand : TrainerCommand + { + /********* + ** Properties + *********/ + /// The time of day at which to freeze time. + internal static int FrozenTime; + + /// Whether to freeze time. + private bool FreezeTime; + + + /********* + ** Accessors + *********/ + /// Whether the command needs to perform logic when the game updates. + public override bool NeedsUpdate => this.FreezeTime; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public FreezeTimeCommand() + : base("world_freezetime", "Freezes or resumes time.\n\nUsage: world_freezetime [value]\n- value: one of 0 (resume), 1 (freeze), or blank (toggle).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + if (args.Any()) + { + if (int.TryParse(args[0], out int value)) + { + if (value == 0 || value == 1) + { + this.FreezeTime = value == 1; + FreezeTimeCommand.FrozenTime = Game1.timeOfDay; + monitor.Log($"OK, time is now {(this.FreezeTime ? "frozen" : "resumed")}.", LogLevel.Info); + } + else + this.LogUsageError(monitor, "The value should be 0 (not frozen), 1 (frozen), or empty (toggle).", command); + } + else + this.LogArgumentNotInt(monitor, command); + } + else + { + this.FreezeTime = !this.FreezeTime; + FreezeTimeCommand.FrozenTime = Game1.timeOfDay; + monitor.Log($"OK, time is now {(this.FreezeTime ? "frozen" : "resumed")}.", LogLevel.Info); + } + } + + /// Perform any logic needed on update tick. + /// Writes messages to the console and log file. + public override void Update(IMonitor monitor) + { + if (this.FreezeTime) + Game1.timeOfDay = FreezeTimeCommand.FrozenTime; + } + } +} diff --git a/src/TrainerMod/Framework/Commands/World/SetDayCommand.cs b/src/TrainerMod/Framework/Commands/World/SetDayCommand.cs new file mode 100644 index 00000000..e47b76a7 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/World/SetDayCommand.cs @@ -0,0 +1,45 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.World +{ + /// A command which sets the current day. + internal class SetDayCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetDayCommand() + : base("world_setday", "Sets the day to the specified value.\n\nUsage: world_setday .\n- value: the target day (a number from 1 to 28).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + monitor.Log($"The current date is {Game1.currentSeason} {Game1.dayOfMonth}. Specify a value to change the day.", LogLevel.Info); + return; + } + if (!int.TryParse(args[0], out int day)) + { + this.LogArgumentNotInt(monitor, command); + return; + } + if (day > 28 || day <= 0) + { + this.LogUsageError(monitor, "That isn't a valid day.", command); + return; + } + + // handle + Game1.dayOfMonth = day; + monitor.Log($"OK, the date is now {Game1.currentSeason} {Game1.dayOfMonth}.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/World/SetMineLevelCommand.cs b/src/TrainerMod/Framework/Commands/World/SetMineLevelCommand.cs new file mode 100644 index 00000000..bfcc566f --- /dev/null +++ b/src/TrainerMod/Framework/Commands/World/SetMineLevelCommand.cs @@ -0,0 +1,42 @@ +using System; +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.World +{ + /// A command which moves the player to the given mine level. + internal class SetMineLevelCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetMineLevelCommand() + : base("world_setminelevel", "Sets the mine level?\n\nUsage: world_setminelevel \n- value: The target level (a number starting at 1).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + this.LogArgumentsInvalid(monitor, command); + return; + } + if (!int.TryParse(args[0], out int level)) + { + this.LogArgumentNotInt(monitor, command); + return; + } + + // handle + level = Math.Max(1, level); + monitor.Log($"OK, warping you to mine level {level}.", LogLevel.Info); + Game1.enterMine(true, level, ""); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/World/SetSeasonCommand.cs b/src/TrainerMod/Framework/Commands/World/SetSeasonCommand.cs new file mode 100644 index 00000000..d60f8601 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/World/SetSeasonCommand.cs @@ -0,0 +1,47 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.World +{ + /// A command which sets the current season. + internal class SetSeasonCommand : TrainerCommand + { + /********* + ** Properties + *********/ + /// The valid season names. + private readonly string[] ValidSeasons = { "winter", "spring", "summer", "fall" }; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetSeasonCommand() + : base("world_setseason", "Sets the season to the specified value.\n\nUsage: world_setseason \n- season: the target season (one of 'spring', 'summer', 'fall', 'winter').") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + monitor.Log($"The current season is {Game1.currentSeason}. Specify a value to change it.", LogLevel.Info); + return; + } + if (!this.ValidSeasons.Contains(args[0])) + { + this.LogUsageError(monitor, "That isn't a valid season name.", command); + return; + } + + // handle + Game1.currentSeason = args[0]; + monitor.Log($"OK, the date is now {Game1.currentSeason} {Game1.dayOfMonth}.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/World/SetTimeCommand.cs b/src/TrainerMod/Framework/Commands/World/SetTimeCommand.cs new file mode 100644 index 00000000..4ecff485 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/World/SetTimeCommand.cs @@ -0,0 +1,46 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.World +{ + /// A command which sets the current time. + internal class SetTimeCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetTimeCommand() + : base("world_settime", "Sets the time to the specified value.\n\nUsage: world_settime \n- value: the target time in military time (like 0600 for 6am and 1800 for 6pm).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + monitor.Log($"The current time is {Game1.timeOfDay}. Specify a value to change it.", LogLevel.Info); + return; + } + if (!int.TryParse(args[0], out int time)) + { + this.LogArgumentNotInt(monitor, command); + return; + } + if (time > 2600 || time < 600) + { + this.LogUsageError(monitor, "That isn't a valid time.", command); + return; + } + + // handle + Game1.timeOfDay = time; + FreezeTimeCommand.FrozenTime = Game1.timeOfDay; + monitor.Log($"OK, the time is now {Game1.timeOfDay.ToString().PadLeft(4, '0')}.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/World/SetYearCommand.cs b/src/TrainerMod/Framework/Commands/World/SetYearCommand.cs new file mode 100644 index 00000000..6b2b0d93 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/World/SetYearCommand.cs @@ -0,0 +1,45 @@ +using System.Linq; +using StardewModdingAPI; +using StardewValley; + +namespace TrainerMod.Framework.Commands.World +{ + /// A command which sets the current year. + internal class SetYearCommand : TrainerCommand + { + /********* + ** Public methods + *********/ + /// Construct an instance. + public SetYearCommand() + : base("world_setyear", "Sets the year to the specified value.\n\nUsage: world_setyear \n- year: the target year (a number starting from 1).") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, string[] args) + { + // validate + if (!args.Any()) + { + monitor.Log($"The current year is {Game1.year}. Specify a value to change the year.", LogLevel.Info); + return; + } + if (!int.TryParse(args[0], out int year)) + { + this.LogArgumentNotInt(monitor, command); + return; + } + if (year < 1) + { + this.LogUsageError(monitor, "That isn't a valid year.", command); + return; + } + + // handle + Game1.year = year; + monitor.Log($"OK, the year is now {Game1.year}.", LogLevel.Info); + } + } +} -- cgit From 2ca49fba62f59135c2ed3ec7958cb78073ff486b Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 2 Jul 2017 02:45:02 -0400 Subject: encapsulate TrainerMod's argument parsing (#302) --- .../Framework/Commands/ArgumentParser.cs | 158 +++++++++++++++++++++ .../Framework/Commands/ITrainerCommand.cs | 2 +- .../Framework/Commands/Other/DebugCommand.cs | 2 +- .../Commands/Other/ShowDataFilesCommand.cs | 2 +- .../Commands/Other/ShowGameFilesCommand.cs | 2 +- .../Commands/Player/AddFlooringCommand.cs | 22 +-- .../Framework/Commands/Player/AddItemCommand.cs | 41 ++---- .../Framework/Commands/Player/AddRingCommand.cs | 22 +-- .../Commands/Player/AddWallpaperCommand.cs | 22 +-- .../Framework/Commands/Player/AddWeaponCommand.cs | 15 +- .../Framework/Commands/Player/ListItemsCommand.cs | 4 +- .../Framework/Commands/Player/SetColorCommand.cs | 23 ++- .../Framework/Commands/Player/SetHealthCommand.cs | 6 +- .../Commands/Player/SetImmunityCommand.cs | 6 +- .../Framework/Commands/Player/SetLevelCommand.cs | 18 +-- .../Commands/Player/SetMaxHealthCommand.cs | 8 +- .../Commands/Player/SetMaxStaminaCommand.cs | 6 +- .../Framework/Commands/Player/SetMoneyCommand.cs | 4 +- .../Framework/Commands/Player/SetNameCommand.cs | 33 +++-- .../Framework/Commands/Player/SetSpeedCommand.cs | 19 +-- .../Framework/Commands/Player/SetStaminaCommand.cs | 4 +- .../Framework/Commands/Player/SetStyleCommand.cs | 24 +--- .../Framework/Commands/Saves/LoadCommand.cs | 2 +- .../Framework/Commands/Saves/SaveCommand.cs | 2 +- .../Framework/Commands/TrainerCommand.cs | 20 +-- .../Commands/World/DownMineLevelCommand.cs | 2 +- .../Framework/Commands/World/FreezeTimeCommand.cs | 23 ++- .../Framework/Commands/World/SetDayCommand.cs | 16 +-- .../Commands/World/SetMineLevelCommand.cs | 15 +- .../Framework/Commands/World/SetSeasonCommand.cs | 13 +- .../Framework/Commands/World/SetTimeCommand.cs | 16 +-- .../Framework/Commands/World/SetYearCommand.cs | 16 +-- src/TrainerMod/TrainerMod.cs | 3 +- src/TrainerMod/TrainerMod.csproj | 1 + 34 files changed, 290 insertions(+), 282 deletions(-) create mode 100644 src/TrainerMod/Framework/Commands/ArgumentParser.cs (limited to 'src/TrainerMod/Framework/Commands') diff --git a/src/TrainerMod/Framework/Commands/ArgumentParser.cs b/src/TrainerMod/Framework/Commands/ArgumentParser.cs new file mode 100644 index 00000000..bce068f1 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/ArgumentParser.cs @@ -0,0 +1,158 @@ +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using StardewModdingAPI; + +namespace TrainerMod.Framework.Commands +{ + /// Provides methods for parsing command-line arguments. + internal class ArgumentParser : IReadOnlyList + { + /********* + ** Properties + *********/ + /// The command name for errors. + private readonly string CommandName; + + /// The arguments to parse. + private readonly string[] Args; + + /// Writes messages to the console and log file. + private readonly IMonitor Monitor; + + + /********* + ** Accessors + *********/ + /// Get the number of arguments. + public int Count => this.Args.Length; + + /// Get the argument at the specified index in the list. + /// The zero-based index of the element to get. + public string this[int index] => this.Args[index]; + + /// A method which parses a string argument into the given value. + /// The expected argument type. + /// The argument to parse. + /// The parsed value. + /// Returns whether the argument was successfully parsed. + public delegate bool ParseDelegate(string input, out T output); + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The command name for errors. + /// The arguments to parse. + /// Writes messages to the console and log file. + public ArgumentParser(string commandName, string[] args, IMonitor monitor) + { + this.CommandName = commandName; + this.Args = args; + this.Monitor = monitor; + } + + /// Try to read a string argument. + /// The argument index. + /// The argument name for error messages. + /// The parsed value. + /// Whether to show an error if the argument is missing. + /// Require that the argument match one of the given values. + public bool TryGet(int index, string name, out string value, bool required = true, string[] oneOf = null) + { + value = null; + + // validate + if (this.Args.Length < index + 1) + { + if (required) + this.LogError($"Argument {index} ({name}) is required."); + return false; + } + if (oneOf?.Any() == true && !oneOf.Contains(this.Args[index])) + { + this.LogError($"Argument {index} ({name}) must be one of {string.Join(", ", oneOf)}."); + return false; + } + + // get value + value = this.Args[index]; + return true; + } + + /// Try to read an integer argument. + /// The argument index. + /// The argument name for error messages. + /// The parsed value. + /// Whether to show an error if the argument is missing. + /// The minimum value allowed. + /// The maximum value allowed. + public bool TryGetInt(int index, string name, out int value, bool required = true, int? min = null, int? max = null) + { + value = 0; + + // get argument + if (!this.TryGet(index, name, out string raw, required)) + return false; + + // parse + if (!int.TryParse(raw, out value)) + { + this.LogIntFormatError(index, name, min, max); + return false; + } + + // validate + if ((min.HasValue && value < min) || (max.HasValue && value > max)) + { + this.LogIntFormatError(index, name, min, max); + return false; + } + + return true; + } + + /// Returns an enumerator that iterates through the collection. + /// An enumerator that can be used to iterate through the collection. + public IEnumerator GetEnumerator() + { + return ((IEnumerable)this.Args).GetEnumerator(); + } + + /// Returns an enumerator that iterates through a collection. + /// An object that can be used to iterate through the collection. + IEnumerator IEnumerable.GetEnumerator() + { + return this.GetEnumerator(); + } + + + /********* + ** Private methods + *********/ + /// Log a usage error. + /// The message describing the error. + private void LogError(string message) + { + this.Monitor.Log($"{message} Type 'help {this.CommandName}' for usage.", LogLevel.Error); + } + + /// Print an error for an invalid int argument. + /// The argument index. + /// The argument name for error messages. + /// The minimum value allowed. + /// The maximum value allowed. + private void LogIntFormatError(int index, string name, int? min, int? max) + { + if (min.HasValue && max.HasValue) + this.LogError($"Argument {index} ({name}) must be an integer between {min} and {max}."); + else if (min.HasValue) + this.LogError($"Argument {index} ({name}) must be an integer and at least {min}."); + else if (max.HasValue) + this.LogError($"Argument {index} ({name}) must be an integer and at most {max}."); + else + this.LogError($"Argument {index} ({name}) must be an integer."); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/ITrainerCommand.cs b/src/TrainerMod/Framework/Commands/ITrainerCommand.cs index 55f36ceb..3d97e799 100644 --- a/src/TrainerMod/Framework/Commands/ITrainerCommand.cs +++ b/src/TrainerMod/Framework/Commands/ITrainerCommand.cs @@ -25,7 +25,7 @@ namespace TrainerMod.Framework.Commands /// Writes messages to the console and log file. /// The command name. /// The command arguments. - void Handle(IMonitor monitor, string command, string[] args); + void Handle(IMonitor monitor, string command, ArgumentParser args); /// Perform any logic needed on update tick. /// Writes messages to the console and log file. diff --git a/src/TrainerMod/Framework/Commands/Other/DebugCommand.cs b/src/TrainerMod/Framework/Commands/Other/DebugCommand.cs index ad38d1ba..8c6e9f3b 100644 --- a/src/TrainerMod/Framework/Commands/Other/DebugCommand.cs +++ b/src/TrainerMod/Framework/Commands/Other/DebugCommand.cs @@ -17,7 +17,7 @@ namespace TrainerMod.Framework.Commands.Other /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { // submit command string debugCommand = string.Join(" ", args); diff --git a/src/TrainerMod/Framework/Commands/Other/ShowDataFilesCommand.cs b/src/TrainerMod/Framework/Commands/Other/ShowDataFilesCommand.cs index b2985bb1..367a70c6 100644 --- a/src/TrainerMod/Framework/Commands/Other/ShowDataFilesCommand.cs +++ b/src/TrainerMod/Framework/Commands/Other/ShowDataFilesCommand.cs @@ -17,7 +17,7 @@ namespace TrainerMod.Framework.Commands.Other /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { Process.Start(Constants.DataPath); monitor.Log($"OK, opening {Constants.DataPath}.", LogLevel.Info); diff --git a/src/TrainerMod/Framework/Commands/Other/ShowGameFilesCommand.cs b/src/TrainerMod/Framework/Commands/Other/ShowGameFilesCommand.cs index 5695ce9a..67fa83a3 100644 --- a/src/TrainerMod/Framework/Commands/Other/ShowGameFilesCommand.cs +++ b/src/TrainerMod/Framework/Commands/Other/ShowGameFilesCommand.cs @@ -17,7 +17,7 @@ namespace TrainerMod.Framework.Commands.Other /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { Process.Start(Constants.ExecutionPath); monitor.Log($"OK, opening {Constants.ExecutionPath}.", LogLevel.Info); diff --git a/src/TrainerMod/Framework/Commands/Player/AddFlooringCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddFlooringCommand.cs index 57bd39e3..1bc96466 100644 --- a/src/TrainerMod/Framework/Commands/Player/AddFlooringCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/AddFlooringCommand.cs @@ -1,5 +1,4 @@ -using System.Linq; -using StardewModdingAPI; +using StardewModdingAPI; using StardewValley; using StardewValley.Objects; @@ -19,24 +18,11 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate - if (!args.Any()) - { - this.LogArgumentsInvalid(monitor, command); + // read arguments + if (!args.TryGetInt(0, "floor ID", out int floorID, min: 0, max: 39)) return; - } - if (!int.TryParse(args[0], out int floorID)) - { - this.LogArgumentNotInt(monitor, command); - return; - } - if (floorID < 0 || floorID > 39) - { - monitor.Log("There is no such flooring ID (must be between 0 and 39).", LogLevel.Error); - return; - } // handle Wallpaper wallpaper = new Wallpaper(floorID, isFloor: true); diff --git a/src/TrainerMod/Framework/Commands/Player/AddItemCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddItemCommand.cs index 6d3cf968..190d040a 100644 --- a/src/TrainerMod/Framework/Commands/Player/AddItemCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/AddItemCommand.cs @@ -1,5 +1,4 @@ -using System.Linq; -using StardewModdingAPI; +using StardewModdingAPI; using StardewValley; namespace TrainerMod.Framework.Commands.Player @@ -18,39 +17,15 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate - if (!args.Any()) - { - this.LogArgumentsInvalid(monitor, command); + // read arguments + if (!args.TryGetInt(0, "item ID", out int itemID, min: 0)) return; - } - if (!int.TryParse(args[0], out int itemID)) - { - this.LogUsageError(monitor, "The item ID must be an integer.", command); - return; - } - - // parse arguments - int count = 1; - int quality = 0; - if (args.Length > 1) - { - if (!int.TryParse(args[1], out count)) - { - this.LogUsageError(monitor, "The optional count is invalid.", command); - return; - } - } - if (args.Length > 2) - { - if (!int.TryParse(args[2], out quality)) - { - this.LogUsageError(monitor, "The optional quality is invalid.", command); - return; - } - } + if (!args.TryGetInt(1, "count", out int count, min: 1, required: false)) + count = 1; + if (!args.TryGetInt(2, "quality", out int quality, min: Object.lowQuality, max: Object.bestQuality, required: false)) + quality = Object.lowQuality; // spawn item var item = new Object(itemID, count) { quality = quality }; diff --git a/src/TrainerMod/Framework/Commands/Player/AddRingCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddRingCommand.cs index d62d8b5b..93c5b2a5 100644 --- a/src/TrainerMod/Framework/Commands/Player/AddRingCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/AddRingCommand.cs @@ -1,5 +1,4 @@ -using System.Linq; -using StardewModdingAPI; +using StardewModdingAPI; using StardewValley; using StardewValley.Objects; @@ -19,24 +18,11 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate - if (!args.Any()) - { - this.LogArgumentsInvalid(monitor, command); + // parse arguments + if (!args.TryGetInt(0, "ring ID", out int ringID, min: Ring.ringLowerIndexRange, max: Ring.ringUpperIndexRange)) return; - } - if (!int.TryParse(args[0], out int ringID)) - { - monitor.Log(" is invalid", LogLevel.Error); - return; - } - if (ringID < Ring.ringLowerIndexRange || ringID > Ring.ringUpperIndexRange) - { - monitor.Log($"There is no such ring ID (must be between {Ring.ringLowerIndexRange} and {Ring.ringUpperIndexRange}).", LogLevel.Error); - return; - } // handle Ring ring = new Ring(ringID); diff --git a/src/TrainerMod/Framework/Commands/Player/AddWallpaperCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddWallpaperCommand.cs index e02b05a4..dddb9ffd 100644 --- a/src/TrainerMod/Framework/Commands/Player/AddWallpaperCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/AddWallpaperCommand.cs @@ -1,5 +1,4 @@ -using System.Linq; -using StardewModdingAPI; +using StardewModdingAPI; using StardewValley; using StardewValley.Objects; @@ -19,24 +18,11 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate - if (!args.Any()) - { - this.LogArgumentsInvalid(monitor, command); + // parse arguments + if (!args.TryGetInt(0, "wallpaper ID", out int wallpaperID, min: 0, max: 111)) return; - } - if (!int.TryParse(args[0], out int wallpaperID)) - { - this.LogArgumentNotInt(monitor, command); - return; - } - if (wallpaperID < 0 || wallpaperID > 111) - { - monitor.Log("There is no such wallpaper ID (must be between 0 and 111).", LogLevel.Error); - return; - } // handle Wallpaper wallpaper = new Wallpaper(wallpaperID); diff --git a/src/TrainerMod/Framework/Commands/Player/AddWeaponCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddWeaponCommand.cs index ee94093f..c4ea3d6f 100644 --- a/src/TrainerMod/Framework/Commands/Player/AddWeaponCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/AddWeaponCommand.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Linq; using StardewModdingAPI; using StardewValley; using StardewValley.Tools; @@ -20,19 +19,11 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate - if (!args.Any()) - { - this.LogArgumentsInvalid(monitor, command); + // parse arguments + if (!args.TryGetInt(0, "weapon ID", out int weaponID, min: 0)) return; - } - if (!int.TryParse(args[0], out int weaponID)) - { - this.LogUsageError(monitor, "The weapon ID must be an integer.", command); - return; - } // get raw weapon data if (!Game1.content.Load>("Data\\weapons").TryGetValue(weaponID, out string data)) diff --git a/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs b/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs index a1b9aceb..68adf8c2 100644 --- a/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs @@ -22,9 +22,9 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - var matches = this.GetItems(args).ToArray(); + var matches = this.GetItems(args.ToArray()).ToArray(); // show matches string summary = "Searching...\n"; diff --git a/src/TrainerMod/Framework/Commands/Player/SetColorCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetColorCommand.cs index 00907fba..28ace0df 100644 --- a/src/TrainerMod/Framework/Commands/Player/SetColorCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/SetColorCommand.cs @@ -18,22 +18,23 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate - if (args.Length <= 2) - { - this.LogArgumentsInvalid(monitor, command); + // parse arguments + if (!args.TryGet(0, "target", out string target, oneOf: new[] { "hair", "eyes", "pants" })) return; - } - if (!this.TryParseColor(args[1], out Color color)) + if (!args.TryGet(1, "color", out string rawColor)) + return; + + // parse color + if (!this.TryParseColor(rawColor, out Color color)) { - this.LogUsageError(monitor, "The color should be an RBG value like '255,150,0'.", command); + this.LogUsageError(monitor, "Argument 1 (color) must be an RBG value like '255,150,0'."); return; } // handle - switch (args[0]) + switch (target) { case "hair": Game1.player.hairstyleColor = color; @@ -49,10 +50,6 @@ namespace TrainerMod.Framework.Commands.Player Game1.player.pantsColor = color; monitor.Log("OK, your pants color is updated.", LogLevel.Info); break; - - default: - this.LogArgumentsInvalid(monitor, command); - break; } } diff --git a/src/TrainerMod/Framework/Commands/Player/SetHealthCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetHealthCommand.cs index d3f06459..f64e9035 100644 --- a/src/TrainerMod/Framework/Commands/Player/SetHealthCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/SetHealthCommand.cs @@ -32,9 +32,9 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate + // no-argument mode if (!args.Any()) { monitor.Log($"You currently have {(this.InfiniteHealth ? "infinite" : Game1.player.health.ToString())} health. Specify a value to change it.", LogLevel.Info); @@ -57,7 +57,7 @@ namespace TrainerMod.Framework.Commands.Player monitor.Log($"OK, you now have {Game1.player.health} health.", LogLevel.Info); } else - this.LogArgumentNotInt(monitor, command); + this.LogArgumentNotInt(monitor); } } diff --git a/src/TrainerMod/Framework/Commands/Player/SetImmunityCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetImmunityCommand.cs index ff74f981..59b28a3c 100644 --- a/src/TrainerMod/Framework/Commands/Player/SetImmunityCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/SetImmunityCommand.cs @@ -18,7 +18,7 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { // validate if (!args.Any()) @@ -28,13 +28,11 @@ namespace TrainerMod.Framework.Commands.Player } // handle - if (int.TryParse(args[0], out int amount)) + if (args.TryGetInt(0, "amount", out int amount, min: 0)) { Game1.player.immunity = amount; monitor.Log($"OK, you now have {Game1.player.immunity} immunity.", LogLevel.Info); } - else - this.LogArgumentNotInt(monitor, command); } } } diff --git a/src/TrainerMod/Framework/Commands/Player/SetLevelCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetLevelCommand.cs index 4982a0b8..b223aa9f 100644 --- a/src/TrainerMod/Framework/Commands/Player/SetLevelCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/SetLevelCommand.cs @@ -17,22 +17,16 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { // validate - if (args.Length <= 2) - { - this.LogArgumentsInvalid(monitor, command); + if (!args.TryGet(0, "skill", out string skill, oneOf: new[] { "luck", "mining", "combat", "farming", "fishing", "foraging" })) return; - } - if (!int.TryParse(args[1], out int level)) - { - this.LogArgumentNotInt(monitor, command); + if (!args.TryGetInt(1, "level", out int level, min: 0, max: 10)) return; - } // handle - switch (args[0]) + switch (skill) { case "luck": Game1.player.LuckLevel = level; @@ -63,10 +57,6 @@ namespace TrainerMod.Framework.Commands.Player Game1.player.ForagingLevel = level; monitor.Log($"OK, your foraging skill is now {Game1.player.ForagingLevel}.", LogLevel.Info); break; - - default: - this.LogUsageError(monitor, "That isn't a valid skill.", command); - break; } } } diff --git a/src/TrainerMod/Framework/Commands/Player/SetMaxHealthCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetMaxHealthCommand.cs index 73ba252a..4b9d87dc 100644 --- a/src/TrainerMod/Framework/Commands/Player/SetMaxHealthCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/SetMaxHealthCommand.cs @@ -18,7 +18,7 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { // validate if (!args.Any()) @@ -28,13 +28,11 @@ namespace TrainerMod.Framework.Commands.Player } // handle - if (int.TryParse(args[0], out int maxHealth)) + if (args.TryGetInt(0, "amount", out int amount, min: 1)) { - Game1.player.maxHealth = maxHealth; + Game1.player.maxHealth = amount; monitor.Log($"OK, you now have {Game1.player.maxHealth} max health.", LogLevel.Info); } - else - this.LogArgumentNotInt(monitor, command); } } } diff --git a/src/TrainerMod/Framework/Commands/Player/SetMaxStaminaCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetMaxStaminaCommand.cs index c21f6592..3997bb1b 100644 --- a/src/TrainerMod/Framework/Commands/Player/SetMaxStaminaCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/SetMaxStaminaCommand.cs @@ -18,7 +18,7 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { // validate if (!args.Any()) @@ -28,13 +28,11 @@ namespace TrainerMod.Framework.Commands.Player } // handle - if (int.TryParse(args[0], out int amount)) + if (args.TryGetInt(0, "amount", out int amount, min: 1)) { Game1.player.MaxStamina = amount; monitor.Log($"OK, you now have {Game1.player.MaxStamina} max stamina.", LogLevel.Info); } - else - this.LogArgumentNotInt(monitor, command); } } } diff --git a/src/TrainerMod/Framework/Commands/Player/SetMoneyCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetMoneyCommand.cs index ad74499d..55e069a4 100644 --- a/src/TrainerMod/Framework/Commands/Player/SetMoneyCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/SetMoneyCommand.cs @@ -32,7 +32,7 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { // validate if (!args.Any()) @@ -57,7 +57,7 @@ namespace TrainerMod.Framework.Commands.Player monitor.Log($"OK, you now have {Game1.player.Money} gold.", LogLevel.Info); } else - this.LogArgumentNotInt(monitor, command); + this.LogArgumentNotInt(monitor); } } diff --git a/src/TrainerMod/Framework/Commands/Player/SetNameCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetNameCommand.cs index 8284d882..3fd4475c 100644 --- a/src/TrainerMod/Framework/Commands/Player/SetNameCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/SetNameCommand.cs @@ -17,29 +17,34 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate - if (args.Length <= 1) - { - monitor.Log($"Your name is currently '{Game1.player.Name}'. Type 'help player_setname' for usage.", LogLevel.Info); + // parse arguments + if (!args.TryGet(0, "target", out string target, oneOf: new[] { "player", "farm" })) return; - } + args.TryGet(1, "name", out string name, required: false); // handle - string target = args[0]; switch (target) { case "player": - Game1.player.Name = args[1]; - monitor.Log($"OK, your player's name is now {Game1.player.Name}.", LogLevel.Info); + if (!string.IsNullOrWhiteSpace(name)) + { + Game1.player.Name = args[1]; + monitor.Log($"OK, your name is now {Game1.player.Name}.", LogLevel.Info); + } + else + monitor.Log($"Your name is currently '{Game1.player.Name}'. Type 'help player_setname' for usage.", LogLevel.Info); break; + case "farm": - Game1.player.farmName = args[1]; - monitor.Log($"OK, your farm's name is now {Game1.player.Name}.", LogLevel.Info); - break; - default: - this.LogArgumentsInvalid(monitor, command); + if (!string.IsNullOrWhiteSpace(name)) + { + Game1.player.farmName = args[1]; + monitor.Log($"OK, your farm's name is now {Game1.player.farmName}.", LogLevel.Info); + } + else + monitor.Log($"Your farm's name is currently '{Game1.player.farmName}'. Type 'help player_setname' for usage.", LogLevel.Info); break; } } diff --git a/src/TrainerMod/Framework/Commands/Player/SetSpeedCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetSpeedCommand.cs index a8c05d0c..40b87b62 100644 --- a/src/TrainerMod/Framework/Commands/Player/SetSpeedCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/SetSpeedCommand.cs @@ -1,5 +1,4 @@ -using System.Linq; -using StardewModdingAPI; +using StardewModdingAPI; using StardewValley; namespace TrainerMod.Framework.Commands.Player @@ -18,22 +17,14 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate - if (!args.Any()) - { - monitor.Log($"You currently have {Game1.player.addedSpeed} added speed. Specify a value to change it.", LogLevel.Info); + // parse arguments + if (!args.TryGetInt(0, "added speed", out int amount, min: 0)) return; - } - if (!int.TryParse(args[0], out int addedSpeed)) - { - this.LogArgumentNotInt(monitor, command); - return; - } // handle - Game1.player.addedSpeed = addedSpeed; + Game1.player.addedSpeed = amount; monitor.Log($"OK, your added speed is now {Game1.player.addedSpeed}.", LogLevel.Info); } } diff --git a/src/TrainerMod/Framework/Commands/Player/SetStaminaCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetStaminaCommand.cs index 55a55eab..d44d1370 100644 --- a/src/TrainerMod/Framework/Commands/Player/SetStaminaCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/SetStaminaCommand.cs @@ -32,7 +32,7 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { // validate if (!args.Any()) @@ -57,7 +57,7 @@ namespace TrainerMod.Framework.Commands.Player monitor.Log($"OK, you now have {Game1.player.Stamina} stamina.", LogLevel.Info); } else - this.LogArgumentNotInt(monitor, command); + this.LogArgumentNotInt(monitor); } } diff --git a/src/TrainerMod/Framework/Commands/Player/SetStyleCommand.cs b/src/TrainerMod/Framework/Commands/Player/SetStyleCommand.cs index 9ef5f88b..96e34af2 100644 --- a/src/TrainerMod/Framework/Commands/Player/SetStyleCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/SetStyleCommand.cs @@ -17,22 +17,16 @@ namespace TrainerMod.Framework.Commands.Player /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate - if (args.Length <= 1) - { - this.LogArgumentsInvalid(monitor, command); + // parse arguments + if (!args.TryGet(0, "target", out string target, oneOf: new[] { "hair", "shirt", "acc", "skin", "shoe", "swim", "gender" })) return; - } - if (!int.TryParse(args[1], out int styleID)) - { - this.LogArgumentsInvalid(monitor, command); + if (!args.TryGetInt(1, "style ID", out int styleID)) return; - } // handle - switch (args[0]) + switch (target) { case "hair": Game1.player.changeHairStyle(styleID); @@ -71,7 +65,7 @@ namespace TrainerMod.Framework.Commands.Player monitor.Log("OK, you're now in your swimming suit.", LogLevel.Info); break; default: - this.LogUsageError(monitor, "The swim value should be 0 (no swimming suit) or 1 (swimming suit).", command); + this.LogUsageError(monitor, "The swim value should be 0 (no swimming suit) or 1 (swimming suit)."); break; } break; @@ -88,14 +82,10 @@ namespace TrainerMod.Framework.Commands.Player monitor.Log("OK, you're now female.", LogLevel.Info); break; default: - this.LogUsageError(monitor, "The gender value should be 0 (male) or 1 (female).", command); + this.LogUsageError(monitor, "The gender value should be 0 (male) or 1 (female)."); break; } break; - - default: - this.LogArgumentsInvalid(monitor, command); - break; } } } diff --git a/src/TrainerMod/Framework/Commands/Saves/LoadCommand.cs b/src/TrainerMod/Framework/Commands/Saves/LoadCommand.cs index 1a70b54c..121ad9a6 100644 --- a/src/TrainerMod/Framework/Commands/Saves/LoadCommand.cs +++ b/src/TrainerMod/Framework/Commands/Saves/LoadCommand.cs @@ -18,7 +18,7 @@ namespace TrainerMod.Framework.Commands.Saves /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { monitor.Log("Triggering load menu...", LogLevel.Info); Game1.hasLoadedGame = false; diff --git a/src/TrainerMod/Framework/Commands/Saves/SaveCommand.cs b/src/TrainerMod/Framework/Commands/Saves/SaveCommand.cs index 8ce9738d..5f6941e9 100644 --- a/src/TrainerMod/Framework/Commands/Saves/SaveCommand.cs +++ b/src/TrainerMod/Framework/Commands/Saves/SaveCommand.cs @@ -18,7 +18,7 @@ namespace TrainerMod.Framework.Commands.Saves /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { monitor.Log("Saving the game...", LogLevel.Info); SaveGame.Save(); diff --git a/src/TrainerMod/Framework/Commands/TrainerCommand.cs b/src/TrainerMod/Framework/Commands/TrainerCommand.cs index 1b18b44b..4715aa04 100644 --- a/src/TrainerMod/Framework/Commands/TrainerCommand.cs +++ b/src/TrainerMod/Framework/Commands/TrainerCommand.cs @@ -25,7 +25,7 @@ namespace TrainerMod.Framework.Commands /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public abstract void Handle(IMonitor monitor, string command, string[] args); + public abstract void Handle(IMonitor monitor, string command, ArgumentParser args); /// Perform any logic needed on update tick. /// Writes messages to the console and log file. @@ -47,26 +47,16 @@ namespace TrainerMod.Framework.Commands /// Log an error indicating incorrect usage. /// Writes messages to the console and log file. /// A sentence explaining the problem. - /// The name of the command. - protected void LogUsageError(IMonitor monitor, string error, string command) + protected void LogUsageError(IMonitor monitor, string error) { - monitor.Log($"{error} Type 'help {command}' for usage.", LogLevel.Error); + monitor.Log($"{error} Type 'help {this.Name}' for usage.", LogLevel.Error); } /// Log an error indicating a value must be an integer. /// Writes messages to the console and log file. - /// The name of the command. - protected void LogArgumentNotInt(IMonitor monitor, string command) + protected void LogArgumentNotInt(IMonitor monitor) { - this.LogUsageError(monitor, "The value must be a whole number.", command); - } - - /// Log an error indicating a value is invalid. - /// Writes messages to the console and log file. - /// The name of the command. - protected void LogArgumentsInvalid(IMonitor monitor, string command) - { - this.LogUsageError(monitor, "The arguments are invalid.", command); + this.LogUsageError(monitor, "The value must be a whole number."); } } } diff --git a/src/TrainerMod/Framework/Commands/World/DownMineLevelCommand.cs b/src/TrainerMod/Framework/Commands/World/DownMineLevelCommand.cs index 2700a0dc..4e62cf77 100644 --- a/src/TrainerMod/Framework/Commands/World/DownMineLevelCommand.cs +++ b/src/TrainerMod/Framework/Commands/World/DownMineLevelCommand.cs @@ -18,7 +18,7 @@ namespace TrainerMod.Framework.Commands.World /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { int level = (Game1.currentLocation as MineShaft)?.mineLevel ?? 0; monitor.Log($"OK, warping you to mine level {level + 1}.", LogLevel.Info); diff --git a/src/TrainerMod/Framework/Commands/World/FreezeTimeCommand.cs b/src/TrainerMod/Framework/Commands/World/FreezeTimeCommand.cs index 89cd68cb..13d08398 100644 --- a/src/TrainerMod/Framework/Commands/World/FreezeTimeCommand.cs +++ b/src/TrainerMod/Framework/Commands/World/FreezeTimeCommand.cs @@ -35,23 +35,18 @@ namespace TrainerMod.Framework.Commands.World /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { if (args.Any()) { - if (int.TryParse(args[0], out int value)) - { - if (value == 0 || value == 1) - { - this.FreezeTime = value == 1; - FreezeTimeCommand.FrozenTime = Game1.timeOfDay; - monitor.Log($"OK, time is now {(this.FreezeTime ? "frozen" : "resumed")}.", LogLevel.Info); - } - else - this.LogUsageError(monitor, "The value should be 0 (not frozen), 1 (frozen), or empty (toggle).", command); - } - else - this.LogArgumentNotInt(monitor, command); + // parse arguments + if (!args.TryGetInt(0, "value", out int value, min: 0, max: 1)) + return; + + // handle + this.FreezeTime = value == 1; + FreezeTimeCommand.FrozenTime = Game1.timeOfDay; + monitor.Log($"OK, time is now {(this.FreezeTime ? "frozen" : "resumed")}.", LogLevel.Info); } else { diff --git a/src/TrainerMod/Framework/Commands/World/SetDayCommand.cs b/src/TrainerMod/Framework/Commands/World/SetDayCommand.cs index e47b76a7..54267384 100644 --- a/src/TrainerMod/Framework/Commands/World/SetDayCommand.cs +++ b/src/TrainerMod/Framework/Commands/World/SetDayCommand.cs @@ -18,24 +18,18 @@ namespace TrainerMod.Framework.Commands.World /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate + // no-argument mode if (!args.Any()) { monitor.Log($"The current date is {Game1.currentSeason} {Game1.dayOfMonth}. Specify a value to change the day.", LogLevel.Info); return; } - if (!int.TryParse(args[0], out int day)) - { - this.LogArgumentNotInt(monitor, command); - return; - } - if (day > 28 || day <= 0) - { - this.LogUsageError(monitor, "That isn't a valid day.", command); + + // parse arguments + if (!args.TryGetInt(0, "day", out int day, min: 1, max: 28)) return; - } // handle Game1.dayOfMonth = day; diff --git a/src/TrainerMod/Framework/Commands/World/SetMineLevelCommand.cs b/src/TrainerMod/Framework/Commands/World/SetMineLevelCommand.cs index bfcc566f..225ec091 100644 --- a/src/TrainerMod/Framework/Commands/World/SetMineLevelCommand.cs +++ b/src/TrainerMod/Framework/Commands/World/SetMineLevelCommand.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using StardewModdingAPI; using StardewValley; @@ -19,19 +18,11 @@ namespace TrainerMod.Framework.Commands.World /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate - if (!args.Any()) - { - this.LogArgumentsInvalid(monitor, command); + // parse arguments + if (!args.TryGetInt(0, "mine level", out int level, min: 1)) return; - } - if (!int.TryParse(args[0], out int level)) - { - this.LogArgumentNotInt(monitor, command); - return; - } // handle level = Math.Max(1, level); diff --git a/src/TrainerMod/Framework/Commands/World/SetSeasonCommand.cs b/src/TrainerMod/Framework/Commands/World/SetSeasonCommand.cs index d60f8601..96c3d920 100644 --- a/src/TrainerMod/Framework/Commands/World/SetSeasonCommand.cs +++ b/src/TrainerMod/Framework/Commands/World/SetSeasonCommand.cs @@ -25,22 +25,21 @@ namespace TrainerMod.Framework.Commands.World /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate + // no-argument mode if (!args.Any()) { monitor.Log($"The current season is {Game1.currentSeason}. Specify a value to change it.", LogLevel.Info); return; } - if (!this.ValidSeasons.Contains(args[0])) - { - this.LogUsageError(monitor, "That isn't a valid season name.", command); + + // parse arguments + if (!args.TryGet(0, "season", out string season, oneOf: this.ValidSeasons)) return; - } // handle - Game1.currentSeason = args[0]; + Game1.currentSeason = season; monitor.Log($"OK, the date is now {Game1.currentSeason} {Game1.dayOfMonth}.", LogLevel.Info); } } diff --git a/src/TrainerMod/Framework/Commands/World/SetTimeCommand.cs b/src/TrainerMod/Framework/Commands/World/SetTimeCommand.cs index 4ecff485..c827ea5e 100644 --- a/src/TrainerMod/Framework/Commands/World/SetTimeCommand.cs +++ b/src/TrainerMod/Framework/Commands/World/SetTimeCommand.cs @@ -18,24 +18,18 @@ namespace TrainerMod.Framework.Commands.World /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate + // no-argument mode if (!args.Any()) { monitor.Log($"The current time is {Game1.timeOfDay}. Specify a value to change it.", LogLevel.Info); return; } - if (!int.TryParse(args[0], out int time)) - { - this.LogArgumentNotInt(monitor, command); - return; - } - if (time > 2600 || time < 600) - { - this.LogUsageError(monitor, "That isn't a valid time.", command); + + // parse arguments + if (!args.TryGetInt(0, "time", out int time, min: 600, max: 2600)) return; - } // handle Game1.timeOfDay = time; diff --git a/src/TrainerMod/Framework/Commands/World/SetYearCommand.cs b/src/TrainerMod/Framework/Commands/World/SetYearCommand.cs index 6b2b0d93..760fc170 100644 --- a/src/TrainerMod/Framework/Commands/World/SetYearCommand.cs +++ b/src/TrainerMod/Framework/Commands/World/SetYearCommand.cs @@ -18,24 +18,18 @@ namespace TrainerMod.Framework.Commands.World /// Writes messages to the console and log file. /// The command name. /// The command arguments. - public override void Handle(IMonitor monitor, string command, string[] args) + public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - // validate + // no-argument mode if (!args.Any()) { monitor.Log($"The current year is {Game1.year}. Specify a value to change the year.", LogLevel.Info); return; } - if (!int.TryParse(args[0], out int year)) - { - this.LogArgumentNotInt(monitor, command); - return; - } - if (year < 1) - { - this.LogUsageError(monitor, "That isn't a valid year.", command); + + // parse arguments + if (!args.TryGetInt(0, "year", out int year, min: 1)) return; - } // handle Game1.year = year; diff --git a/src/TrainerMod/TrainerMod.cs b/src/TrainerMod/TrainerMod.cs index 047bbbfe..5db02cd6 100644 --- a/src/TrainerMod/TrainerMod.cs +++ b/src/TrainerMod/TrainerMod.cs @@ -58,7 +58,8 @@ namespace TrainerMod /// The command arguments. private void HandleCommand(ITrainerCommand command, string commandName, string[] args) { - command.Handle(this.Monitor, commandName, args); + ArgumentParser argParser = new ArgumentParser(commandName, args, this.Monitor); + command.Handle(this.Monitor, commandName, argParser); } /// Find all commands in the assembly. diff --git a/src/TrainerMod/TrainerMod.csproj b/src/TrainerMod/TrainerMod.csproj index 1702c577..ee17f970 100644 --- a/src/TrainerMod/TrainerMod.csproj +++ b/src/TrainerMod/TrainerMod.csproj @@ -51,6 +51,7 @@ Properties\GlobalAssemblyInfo.cs + -- cgit From a0c4746c27656d6617853890d270072c13843c64 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 2 Jul 2017 17:22:36 -0400 Subject: add list_item_types command (#302) --- .../Commands/Player/ListItemTypesCommand.cs | 53 ++++++++++++++++++++++ .../Framework/Commands/Player/ListItemsCommand.cs | 39 ---------------- .../Framework/Commands/TrainerCommand.cs | 43 +++++++++++++++++- src/TrainerMod/TrainerMod.csproj | 1 + 4 files changed, 96 insertions(+), 40 deletions(-) create mode 100644 src/TrainerMod/Framework/Commands/Player/ListItemTypesCommand.cs (limited to 'src/TrainerMod/Framework/Commands') diff --git a/src/TrainerMod/Framework/Commands/Player/ListItemTypesCommand.cs b/src/TrainerMod/Framework/Commands/Player/ListItemTypesCommand.cs new file mode 100644 index 00000000..5f14edbb --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/ListItemTypesCommand.cs @@ -0,0 +1,53 @@ +using System.Linq; +using StardewModdingAPI; +using TrainerMod.Framework.ItemData; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which list item types. + internal class ListItemTypesCommand : TrainerCommand + { + /********* + ** Properties + *********/ + /// Provides methods for searching and constructing items. + private readonly ItemRepository Items = new ItemRepository(); + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public ListItemTypesCommand() + : base("list_item_types", "Lists item types you can filter in other commands.\n\nUsage: list_item_types") { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, ArgumentParser args) + { + // validate + if (!Context.IsWorldReady) + { + monitor.Log("You need to load a save to use this command.", LogLevel.Error); + return; + } + + // handle + ItemType[] matches = + ( + from item in this.Items.GetAll() + orderby item.Type.ToString() + select item.Type + ) + .Distinct() + .ToArray(); + string summary = "Searching...\n"; + if (matches.Any()) + monitor.Log(summary + this.GetTableString(matches, new[] { "type" }, val => new[] { val.ToString() }), LogLevel.Info); + else + monitor.Log(summary + "No item types found.", LogLevel.Info); + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs b/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs index 68adf8c2..30c3de3b 100644 --- a/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs @@ -77,44 +77,5 @@ namespace TrainerMod.Framework.Commands.Player yield return weapon; } } - - /// Get an ASCII table for a set of tabular data. - /// The data type. - /// The data to display. - /// The table header. - /// Returns a set of fields for a data value. - private string GetTableString(IEnumerable data, string[] header, Func getRow) - { - // get table data - int[] widths = header.Select(p => p.Length).ToArray(); - string[][] rows = data - .Select(item => - { - string[] fields = getRow(item); - if (fields.Length != widths.Length) - throw new InvalidOperationException($"Expected {widths.Length} columns, but found {fields.Length}: {string.Join(", ", fields)}"); - - for (int i = 0; i < fields.Length; i++) - widths[i] = Math.Max(widths[i], fields[i].Length); - - return fields; - }) - .ToArray(); - - // render fields - List lines = new List(rows.Length + 2) - { - header, - header.Select((value, i) => "".PadRight(widths[i], '-')).ToArray() - }; - lines.AddRange(rows); - - return string.Join( - Environment.NewLine, - lines.Select(line => string.Join(" | ", - line.Select((field, i) => field.PadRight(widths[i], ' ')).ToArray()) - ) - ); - } } } diff --git a/src/TrainerMod/Framework/Commands/TrainerCommand.cs b/src/TrainerMod/Framework/Commands/TrainerCommand.cs index 4715aa04..abe9ee41 100644 --- a/src/TrainerMod/Framework/Commands/TrainerCommand.cs +++ b/src/TrainerMod/Framework/Commands/TrainerCommand.cs @@ -1,4 +1,7 @@ -using StardewModdingAPI; +using System; +using System.Collections.Generic; +using System.Linq; +using StardewModdingAPI; namespace TrainerMod.Framework.Commands { @@ -58,5 +61,43 @@ namespace TrainerMod.Framework.Commands { this.LogUsageError(monitor, "The value must be a whole number."); } + + /// Get an ASCII table to show tabular data in the console. + /// The data type. + /// The data to display. + /// The table header. + /// Returns a set of fields for a data value. + protected string GetTableString(IEnumerable data, string[] header, Func getRow) + { + // get table data + int[] widths = header.Select(p => p.Length).ToArray(); + string[][] rows = data + .Select(item => + { + string[] fields = getRow(item); + if (fields.Length != widths.Length) + throw new InvalidOperationException($"Expected {widths.Length} columns, but found {fields.Length}: {string.Join(", ", fields)}"); + + for (int i = 0; i < fields.Length; i++) + widths[i] = Math.Max(widths[i], fields[i].Length); + + return fields; + }) + .ToArray(); + + // render fields + List lines = new List(rows.Length + 2) + { + header, + header.Select((value, i) => "".PadRight(widths[i], '-')).ToArray() + }; + lines.AddRange(rows); + + return string.Join( + Environment.NewLine, + lines.Select(line => string.Join(" | ", line.Select((field, i) => field.PadRight(widths[i], ' ')).ToArray()) + ) + ); + } } } diff --git a/src/TrainerMod/TrainerMod.csproj b/src/TrainerMod/TrainerMod.csproj index 18abf42f..8e4e2b2e 100644 --- a/src/TrainerMod/TrainerMod.csproj +++ b/src/TrainerMod/TrainerMod.csproj @@ -55,6 +55,7 @@ + -- cgit From 40e8d3da0e204117d0a6de91b368ef420eb31df0 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 2 Jul 2017 17:37:30 -0400 Subject: migrate list_items command to new item repository (#302) --- release-notes.md | 2 + .../Framework/Commands/Player/ListItemsCommand.cs | 55 ++++++++++------------ src/TrainerMod/Framework/ItemData/ISearchItem.cs | 21 --------- .../Framework/ItemData/SearchableObject.cs | 48 ------------------- .../Framework/ItemData/SearchableRing.cs | 48 ------------------- .../Framework/ItemData/SearchableWeapon.cs | 48 ------------------- src/TrainerMod/TrainerMod.csproj | 4 -- 7 files changed, 27 insertions(+), 199 deletions(-) delete mode 100644 src/TrainerMod/Framework/ItemData/ISearchItem.cs delete mode 100644 src/TrainerMod/Framework/ItemData/SearchableObject.cs delete mode 100644 src/TrainerMod/Framework/ItemData/SearchableRing.cs delete mode 100644 src/TrainerMod/Framework/ItemData/SearchableWeapon.cs (limited to 'src/TrainerMod/Framework/Commands') diff --git a/release-notes.md b/release-notes.md index 816c2b68..e23a1e45 100644 --- a/release-notes.md +++ b/release-notes.md @@ -16,6 +16,8 @@ For players: * SMAPI no longer loads mods known to be obsolete or unneeded. * SMAPI now lists mods in an easier-to-read format in the console. * When the `ObjectInformation.xnb` is broken, SMAPI now prints one error to the console instead of a warning flood. (The individual issues are still listed in the log file if needed.) +* TrainerMod's `list_items` command now shows all item types in the game. You can search specific item types like `list_items weapons`, and use `list_item_types` to see a list of types. +* TrainerMod's `list_items` with search keywords now also searches items' translated names. For modders: * You can now specify minimum dependency versions in `manifest.json`. diff --git a/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs b/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs index 30c3de3b..7f4f454c 100644 --- a/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs +++ b/src/TrainerMod/Framework/Commands/Player/ListItemsCommand.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.Linq; using StardewModdingAPI; -using StardewValley; -using StardewValley.Objects; using TrainerMod.Framework.ItemData; namespace TrainerMod.Framework.Commands.Player @@ -11,6 +9,13 @@ namespace TrainerMod.Framework.Commands.Player /// A command which list items available to spawn. internal class ListItemsCommand : TrainerCommand { + /********* + ** Properties + *********/ + /// Provides methods for searching and constructing items. + private readonly ItemRepository Items = new ItemRepository(); + + /********* ** Public methods *********/ @@ -24,12 +29,24 @@ namespace TrainerMod.Framework.Commands.Player /// The command arguments. public override void Handle(IMonitor monitor, string command, ArgumentParser args) { - var matches = this.GetItems(args.ToArray()).ToArray(); + // validate + if (!Context.IsWorldReady) + { + monitor.Log("You need to load a save to use this command.", LogLevel.Error); + return; + } - // show matches + // handle + SearchableItem[] matches = + ( + from item in this.GetItems(args.ToArray()) + orderby item.Type.ToString(), item.Name + select item + ) + .ToArray(); string summary = "Searching...\n"; if (matches.Any()) - monitor.Log(summary + this.GetTableString(matches, new[] { "type", "id", "name" }, val => new[] { val.Type.ToString(), val.ID.ToString(), val.Name }), LogLevel.Info); + monitor.Log(summary + this.GetTableString(matches, new[] { "type", "name", "id" }, val => new[] { val.Type.ToString(), val.Name, val.ID.ToString() }), LogLevel.Info); else monitor.Log(summary + "No items found", LogLevel.Info); } @@ -40,7 +57,7 @@ namespace TrainerMod.Framework.Commands.Player *********/ /// Get all items which can be searched and added to the player's inventory through the console. /// The search string to find. - private IEnumerable GetItems(string[] searchWords) + private IEnumerable GetItems(string[] searchWords) { // normalise search term searchWords = searchWords?.Where(word => !string.IsNullOrWhiteSpace(word)).ToArray(); @@ -49,33 +66,11 @@ namespace TrainerMod.Framework.Commands.Player // find matches return ( - from item in this.GetItems() - let term = $"{item.ID}|{item.Type}|{item.Name}" + from item in this.Items.GetAll() + let term = $"{item.ID}|{item.Type}|{item.Name}|{item.DisplayName}" where searchWords == null || searchWords.All(word => term.IndexOf(word, StringComparison.CurrentCultureIgnoreCase) != -1) select item ); } - - /// Get all items which can be searched and added to the player's inventory through the console. - private IEnumerable GetItems() - { - // objects - foreach (int id in Game1.objectInformation.Keys) - { - ISearchItem obj = id >= Ring.ringLowerIndexRange && id <= Ring.ringUpperIndexRange - ? new SearchableRing(id) - : (ISearchItem)new SearchableObject(id); - if (obj.IsValid) - yield return obj; - } - - // weapons - foreach (int id in Game1.content.Load>("Data\\weapons").Keys) - { - ISearchItem weapon = new SearchableWeapon(id); - if (weapon.IsValid) - yield return weapon; - } - } } } diff --git a/src/TrainerMod/Framework/ItemData/ISearchItem.cs b/src/TrainerMod/Framework/ItemData/ISearchItem.cs deleted file mode 100644 index db30da77..00000000 --- a/src/TrainerMod/Framework/ItemData/ISearchItem.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace TrainerMod.Framework.ItemData -{ - /// An item that can be searched and added to the player's inventory through the console. - internal interface ISearchItem - { - /********* - ** Accessors - *********/ - /// Whether the item is valid. - bool IsValid { get; } - - /// The item ID. - int ID { get; } - - /// The item name. - string Name { get; } - - /// The item type. - ItemType Type { get; } - } -} \ No newline at end of file diff --git a/src/TrainerMod/Framework/ItemData/SearchableObject.cs b/src/TrainerMod/Framework/ItemData/SearchableObject.cs deleted file mode 100644 index 7e44a315..00000000 --- a/src/TrainerMod/Framework/ItemData/SearchableObject.cs +++ /dev/null @@ -1,48 +0,0 @@ -using StardewValley; - -namespace TrainerMod.Framework.ItemData -{ - /// An object that can be searched and added to the player's inventory through the console. - internal class SearchableObject : ISearchItem - { - /********* - ** Properties - *********/ - /// The underlying item. - private readonly Item Item; - - - /********* - ** Accessors - *********/ - /// Whether the item is valid. - public bool IsValid => this.Item != null && this.Item.Name != "Broken Item"; - - /// The item ID. - public int ID => this.Item.parentSheetIndex; - - /// The item name. - public string Name => this.Item.Name; - - /// The item type. - public ItemType Type => ItemType.Object; - - - /********* - ** Accessors - *********/ - /// Construct an instance. - /// The item ID. - public SearchableObject(int id) - { - try - { - this.Item = new Object(id, 1); - } - catch - { - // invalid - } - } - } -} \ No newline at end of file diff --git a/src/TrainerMod/Framework/ItemData/SearchableRing.cs b/src/TrainerMod/Framework/ItemData/SearchableRing.cs deleted file mode 100644 index 20b6aef2..00000000 --- a/src/TrainerMod/Framework/ItemData/SearchableRing.cs +++ /dev/null @@ -1,48 +0,0 @@ -using StardewValley.Objects; - -namespace TrainerMod.Framework.ItemData -{ - /// A ring that can be searched and added to the player's inventory through the console. - internal class SearchableRing : ISearchItem - { - /********* - ** Properties - *********/ - /// The underlying item. - private readonly Ring Ring; - - - /********* - ** Accessors - *********/ - /// Whether the item is valid. - public bool IsValid => this.Ring != null; - - /// The item ID. - public int ID => this.Ring.parentSheetIndex; - - /// The item name. - public string Name => this.Ring.Name; - - /// The item type. - public ItemType Type => ItemType.Ring; - - - /********* - ** Accessors - *********/ - /// Construct an instance. - /// The ring ID. - public SearchableRing(int id) - { - try - { - this.Ring = new Ring(id); - } - catch - { - // invalid - } - } - } -} \ No newline at end of file diff --git a/src/TrainerMod/Framework/ItemData/SearchableWeapon.cs b/src/TrainerMod/Framework/ItemData/SearchableWeapon.cs deleted file mode 100644 index 70d659ee..00000000 --- a/src/TrainerMod/Framework/ItemData/SearchableWeapon.cs +++ /dev/null @@ -1,48 +0,0 @@ -using StardewValley.Tools; - -namespace TrainerMod.Framework.ItemData -{ - /// A weapon that can be searched and added to the player's inventory through the console. - internal class SearchableWeapon : ISearchItem - { - /********* - ** Properties - *********/ - /// The underlying item. - private readonly MeleeWeapon Weapon; - - - /********* - ** Accessors - *********/ - /// Whether the item is valid. - public bool IsValid => this.Weapon != null; - - /// The item ID. - public int ID => this.Weapon.initialParentTileIndex; - - /// The item name. - public string Name => this.Weapon.Name; - - /// The item type. - public ItemType Type => ItemType.Weapon; - - - /********* - ** Accessors - *********/ - /// Construct an instance. - /// The weapon ID. - public SearchableWeapon(int id) - { - try - { - this.Weapon = new MeleeWeapon(id); - } - catch - { - // invalid - } - } - } -} \ No newline at end of file diff --git a/src/TrainerMod/TrainerMod.csproj b/src/TrainerMod/TrainerMod.csproj index 8e4e2b2e..332833df 100644 --- a/src/TrainerMod/TrainerMod.csproj +++ b/src/TrainerMod/TrainerMod.csproj @@ -83,11 +83,7 @@ - - - - -- cgit From f904b3da9728ee51c76e95915b78623a7638de26 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 2 Jul 2017 18:17:20 -0400 Subject: add unified player_add command which adds any item type (#302) --- release-notes.md | 7 +- .../Framework/Commands/ArgumentParser.cs | 7 +- .../Framework/Commands/Player/AddCommand.cs | 81 ++++++++++++++++++++++ .../Commands/Player/AddFlooringCommand.cs | 33 --------- .../Framework/Commands/Player/AddItemCommand.cs | 43 ------------ .../Framework/Commands/Player/AddRingCommand.cs | 33 --------- .../Commands/Player/AddWallpaperCommand.cs | 33 --------- .../Framework/Commands/Player/AddWeaponCommand.cs | 79 --------------------- src/TrainerMod/TrainerMod.csproj | 6 +- 9 files changed, 91 insertions(+), 231 deletions(-) create mode 100644 src/TrainerMod/Framework/Commands/Player/AddCommand.cs delete mode 100644 src/TrainerMod/Framework/Commands/Player/AddFlooringCommand.cs delete mode 100644 src/TrainerMod/Framework/Commands/Player/AddItemCommand.cs delete mode 100644 src/TrainerMod/Framework/Commands/Player/AddRingCommand.cs delete mode 100644 src/TrainerMod/Framework/Commands/Player/AddWallpaperCommand.cs delete mode 100644 src/TrainerMod/Framework/Commands/Player/AddWeaponCommand.cs (limited to 'src/TrainerMod/Framework/Commands') diff --git a/release-notes.md b/release-notes.md index e23a1e45..4b4a3447 100644 --- a/release-notes.md +++ b/release-notes.md @@ -16,8 +16,11 @@ For players: * SMAPI no longer loads mods known to be obsolete or unneeded. * SMAPI now lists mods in an easier-to-read format in the console. * When the `ObjectInformation.xnb` is broken, SMAPI now prints one error to the console instead of a warning flood. (The individual issues are still listed in the log file if needed.) -* TrainerMod's `list_items` command now shows all item types in the game. You can search specific item types like `list_items weapons`, and use `list_item_types` to see a list of types. -* TrainerMod's `list_items` with search keywords now also searches items' translated names. +* Revamped TrainerMod's item commands: + * `player_add` is a new command which lets you add any game item to your inventory (including tools, weapons, equipment, craftables, wallpaper, etc). This replaces the former `player_additem`, `player_addring`, and `player_addweapon`. + * `list_items` now shows all items in the game. You can search by item type like `list_items weapon`, or search by item name like `list_items galaxy sword`. + * `list_items` now also matches translated item names when playing in another language. + * `list_item_types` is a new command to see a list of item types. For modders: * You can now specify minimum dependency versions in `manifest.json`. diff --git a/src/TrainerMod/Framework/Commands/ArgumentParser.cs b/src/TrainerMod/Framework/Commands/ArgumentParser.cs index bce068f1..6bcd3ff8 100644 --- a/src/TrainerMod/Framework/Commands/ArgumentParser.cs +++ b/src/TrainerMod/Framework/Commands/ArgumentParser.cs @@ -1,4 +1,5 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using System.Linq; using StardewModdingAPI; @@ -58,7 +59,7 @@ namespace TrainerMod.Framework.Commands /// The argument name for error messages. /// The parsed value. /// Whether to show an error if the argument is missing. - /// Require that the argument match one of the given values. + /// Require that the argument match one of the given values (case-insensitive). public bool TryGet(int index, string name, out string value, bool required = true, string[] oneOf = null) { value = null; @@ -70,7 +71,7 @@ namespace TrainerMod.Framework.Commands this.LogError($"Argument {index} ({name}) is required."); return false; } - if (oneOf?.Any() == true && !oneOf.Contains(this.Args[index])) + if (oneOf?.Any() == true && !oneOf.Contains(this.Args[index], StringComparer.InvariantCultureIgnoreCase)) { this.LogError($"Argument {index} ({name}) must be one of {string.Join(", ", oneOf)}."); return false; diff --git a/src/TrainerMod/Framework/Commands/Player/AddCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddCommand.cs new file mode 100644 index 00000000..47840202 --- /dev/null +++ b/src/TrainerMod/Framework/Commands/Player/AddCommand.cs @@ -0,0 +1,81 @@ +using System; +using System.Linq; +using StardewModdingAPI; +using StardewValley; +using TrainerMod.Framework.ItemData; +using Object = StardewValley.Object; + +namespace TrainerMod.Framework.Commands.Player +{ + /// A command which adds an item to the player inventory. + internal class AddCommand : TrainerCommand + { + /********* + ** Properties + *********/ + /// Provides methods for searching and constructing items. + private readonly ItemRepository Items = new ItemRepository(); + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public AddCommand() + : base("player_add", AddCommand.GetDescription()) + { } + + /// Handle the command. + /// Writes messages to the console and log file. + /// The command name. + /// The command arguments. + public override void Handle(IMonitor monitor, string command, ArgumentParser args) + { + // read arguments + if (!args.TryGet(0, "item type", out string rawType, oneOf: Enum.GetNames(typeof(ItemType)))) + return; + if (!args.TryGetInt(1, "item ID", out int id, min: 0)) + return; + if (!args.TryGetInt(2, "count", out int count, min: 1, required: false)) + count = 1; + if (!args.TryGetInt(3, "quality", out int quality, min: Object.lowQuality, max: Object.bestQuality, required: false)) + quality = Object.lowQuality; + ItemType type = (ItemType)Enum.Parse(typeof(ItemType), rawType, ignoreCase: true); + + // find matching item + SearchableItem match = this.Items.GetAll().FirstOrDefault(p => p.Type == type && p.ID == id); + if (match == null) + { + monitor.Log($"There's no {type} item with ID {id}.", LogLevel.Error); + return; + } + + // apply count & quality + match.Item.Stack = count; + if (match.Item is Object obj) + obj.quality = quality; + + // add to inventory + Game1.player.addItemByMenuIfNecessary(match.Item); + monitor.Log($"OK, added {match.Name} ({match.Type} #{match.ID}) to your inventory.", LogLevel.Info); + } + + /********* + ** Private methods + *********/ + private static string GetDescription() + { + string[] typeValues = Enum.GetNames(typeof(ItemType)); + return "Gives the player an item.\n" + + "\n" + + "Usage: player_add [count] [quality]\n" + + $"- type: the item type (one of {string.Join(", ", typeValues)}).\n" + + "- item: the item ID (use the 'list_items' command to see a list).\n" + + "- count (optional): how many of the item to give.\n" + + $"- quality (optional): one of {Object.lowQuality} (normal), {Object.medQuality} (silver), {Object.highQuality} (gold), or {Object.bestQuality} (iridium).\n" + + "\n" + + "This example adds the galaxy sword to your inventory:\n" + + " player_add weapon 4"; + } + } +} diff --git a/src/TrainerMod/Framework/Commands/Player/AddFlooringCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddFlooringCommand.cs deleted file mode 100644 index 1bc96466..00000000 --- a/src/TrainerMod/Framework/Commands/Player/AddFlooringCommand.cs +++ /dev/null @@ -1,33 +0,0 @@ -using StardewModdingAPI; -using StardewValley; -using StardewValley.Objects; - -namespace TrainerMod.Framework.Commands.Player -{ - /// A command which adds a floor item to the player inventory. - internal class AddFlooringCommand : TrainerCommand - { - /********* - ** Public methods - *********/ - /// Construct an instance. - public AddFlooringCommand() - : base("player_addflooring", "Gives the player a flooring item.\n\nUsage: player_addflooring \n- flooring: the flooring ID (ranges from 0 to 39).") { } - - /// Handle the command. - /// Writes messages to the console and log file. - /// The command name. - /// The command arguments. - public override void Handle(IMonitor monitor, string command, ArgumentParser args) - { - // read arguments - if (!args.TryGetInt(0, "floor ID", out int floorID, min: 0, max: 39)) - return; - - // handle - Wallpaper wallpaper = new Wallpaper(floorID, isFloor: true); - Game1.player.addItemByMenuIfNecessary(wallpaper); - monitor.Log($"OK, added flooring {floorID} to your inventory.", LogLevel.Info); - } - } -} diff --git a/src/TrainerMod/Framework/Commands/Player/AddItemCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddItemCommand.cs deleted file mode 100644 index 190d040a..00000000 --- a/src/TrainerMod/Framework/Commands/Player/AddItemCommand.cs +++ /dev/null @@ -1,43 +0,0 @@ -using StardewModdingAPI; -using StardewValley; - -namespace TrainerMod.Framework.Commands.Player -{ - /// A command which adds an item to the player inventory. - internal class AddItemCommand : TrainerCommand - { - /********* - ** Public methods - *********/ - /// Construct an instance. - public AddItemCommand() - : base("player_additem", $"Gives the player an item.\n\nUsage: player_additem [count] [quality]\n- item: the item ID (use the 'list_items' command to see a list).\n- count (optional): how many of the item to give.\n- quality (optional): one of {Object.lowQuality} (normal), {Object.medQuality} (silver), {Object.highQuality} (gold), or {Object.bestQuality} (iridium).") { } - - /// Handle the command. - /// Writes messages to the console and log file. - /// The command name. - /// The command arguments. - public override void Handle(IMonitor monitor, string command, ArgumentParser args) - { - // read arguments - if (!args.TryGetInt(0, "item ID", out int itemID, min: 0)) - return; - if (!args.TryGetInt(1, "count", out int count, min: 1, required: false)) - count = 1; - if (!args.TryGetInt(2, "quality", out int quality, min: Object.lowQuality, max: Object.bestQuality, required: false)) - quality = Object.lowQuality; - - // spawn item - var item = new Object(itemID, count) { quality = quality }; - if (item.Name == "Error Item") - { - monitor.Log("There is no such item ID.", LogLevel.Error); - return; - } - - // add to inventory - Game1.player.addItemByMenuIfNecessary(item); - monitor.Log($"OK, added {item.Name} to your inventory.", LogLevel.Info); - } - } -} diff --git a/src/TrainerMod/Framework/Commands/Player/AddRingCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddRingCommand.cs deleted file mode 100644 index 93c5b2a5..00000000 --- a/src/TrainerMod/Framework/Commands/Player/AddRingCommand.cs +++ /dev/null @@ -1,33 +0,0 @@ -using StardewModdingAPI; -using StardewValley; -using StardewValley.Objects; - -namespace TrainerMod.Framework.Commands.Player -{ - /// A command which adds a ring to the player inventory. - internal class AddRingCommand : TrainerCommand - { - /********* - ** Public methods - *********/ - /// Construct an instance. - public AddRingCommand() - : base("player_addring", "Gives the player a ring.\n\nUsage: player_addring \n- item: the ring ID (use the 'list_items' command to see a list).") { } - - /// Handle the command. - /// Writes messages to the console and log file. - /// The command name. - /// The command arguments. - public override void Handle(IMonitor monitor, string command, ArgumentParser args) - { - // parse arguments - if (!args.TryGetInt(0, "ring ID", out int ringID, min: Ring.ringLowerIndexRange, max: Ring.ringUpperIndexRange)) - return; - - // handle - Ring ring = new Ring(ringID); - Game1.player.addItemByMenuIfNecessary(ring); - monitor.Log($"OK, added {ring.Name} to your inventory.", LogLevel.Info); - } - } -} diff --git a/src/TrainerMod/Framework/Commands/Player/AddWallpaperCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddWallpaperCommand.cs deleted file mode 100644 index dddb9ffd..00000000 --- a/src/TrainerMod/Framework/Commands/Player/AddWallpaperCommand.cs +++ /dev/null @@ -1,33 +0,0 @@ -using StardewModdingAPI; -using StardewValley; -using StardewValley.Objects; - -namespace TrainerMod.Framework.Commands.Player -{ - /// A command which adds a wallpaper item to the player inventory. - internal class AddWallpaperCommand : TrainerCommand - { - /********* - ** Public methods - *********/ - /// Construct an instance. - public AddWallpaperCommand() - : base("player_addwallpaper", "Gives the player a wallpaper.\n\nUsage: player_addwallpaper \n- wallpaper: the wallpaper ID (ranges from 0 to 111).") { } - - /// Handle the command. - /// Writes messages to the console and log file. - /// The command name. - /// The command arguments. - public override void Handle(IMonitor monitor, string command, ArgumentParser args) - { - // parse arguments - if (!args.TryGetInt(0, "wallpaper ID", out int wallpaperID, min: 0, max: 111)) - return; - - // handle - Wallpaper wallpaper = new Wallpaper(wallpaperID); - Game1.player.addItemByMenuIfNecessary(wallpaper); - monitor.Log($"OK, added wallpaper {wallpaperID} to your inventory.", LogLevel.Info); - } - } -} diff --git a/src/TrainerMod/Framework/Commands/Player/AddWeaponCommand.cs b/src/TrainerMod/Framework/Commands/Player/AddWeaponCommand.cs deleted file mode 100644 index c4ea3d6f..00000000 --- a/src/TrainerMod/Framework/Commands/Player/AddWeaponCommand.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System.Collections.Generic; -using StardewModdingAPI; -using StardewValley; -using StardewValley.Tools; - -namespace TrainerMod.Framework.Commands.Player -{ - /// A command which adds a weapon to the player inventory. - internal class AddWeaponCommand : TrainerCommand - { - /********* - ** Public methods - *********/ - /// Construct an instance. - public AddWeaponCommand() - : base("player_addweapon", "Gives the player a weapon.\n\nUsage: player_addweapon \n- item: the weapon ID (use the 'list_items' command to see a list).") { } - - /// Handle the command. - /// Writes messages to the console and log file. - /// The command name. - /// The command arguments. - public override void Handle(IMonitor monitor, string command, ArgumentParser args) - { - // parse arguments - if (!args.TryGetInt(0, "weapon ID", out int weaponID, min: 0)) - return; - - // get raw weapon data - if (!Game1.content.Load>("Data\\weapons").TryGetValue(weaponID, out string data)) - { - monitor.Log("There is no such weapon ID.", LogLevel.Error); - return; - } - - // get raw weapon type - int type; - { - string[] fields = data.Split('/'); - string typeStr = fields.Length > 8 ? fields[8] : null; - if (!int.TryParse(typeStr, out type)) - { - monitor.Log("Could not parse the data for the weapon with that ID.", LogLevel.Error); - return; - } - } - - // get weapon - Tool weapon; - switch (type) - { - case MeleeWeapon.stabbingSword: - case MeleeWeapon.dagger: - case MeleeWeapon.club: - case MeleeWeapon.defenseSword: - weapon = new MeleeWeapon(weaponID); - break; - - case 4: - weapon = new Slingshot(weaponID); - break; - - default: - monitor.Log($"The specified weapon has unknown type '{type}' in the game data.", LogLevel.Error); - return; - } - - // validate weapon - if (weapon.Name == null) - { - monitor.Log("That weapon doesn't seem to be valid.", LogLevel.Error); - return; - } - - // add weapon - Game1.player.addItemByMenuIfNecessary(weapon); - monitor.Log($"OK, added {weapon.Name} to your inventory.", LogLevel.Info); - } - } -} diff --git a/src/TrainerMod/TrainerMod.csproj b/src/TrainerMod/TrainerMod.csproj index 332833df..99a15c8f 100644 --- a/src/TrainerMod/TrainerMod.csproj +++ b/src/TrainerMod/TrainerMod.csproj @@ -57,11 +57,7 @@ - - - - - + -- cgit