using System; using System.Collections.Generic; using System.Linq; using StardewModdingAPI.Events; using StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands; namespace StardewModdingAPI.Mods.ConsoleCommands { /// The main entry point for the mod. public class ModEntry : Mod { /********* ** Fields *********/ /// The commands to handle. private ITrainerCommand[] Commands; /********* ** Public methods *********/ /// The mod entry point, called after the mod is first loaded. /// Provides simplified APIs for writing mods. public override void Entry(IModHelper helper) { // register commands this.Commands = this.ScanForCommands().ToArray(); foreach (ITrainerCommand command in this.Commands) helper.ConsoleCommands.Add(command.Name, command.Description, (name, args) => this.HandleCommand(command, name, args)); // hook events helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked; } /********* ** Private methods *********/ /// The method invoked when the game updates its state. /// The event sender. /// The event arguments. private void OnUpdateTicked(object sender, EventArgs e) { if (!Context.IsWorldReady) return; foreach (ITrainerCommand command in this.Commands) { if (command.NeedsUpdate) command.Update(this.Monitor); } } /// Handle a console command. /// The command to invoke. /// The command name specified by the user. /// The command arguments. private void HandleCommand(ITrainerCommand command, string commandName, string[] args) { ArgumentParser argParser = new ArgumentParser(commandName, args, this.Monitor); command.Handle(this.Monitor, commandName, argParser); } /// Find all commands in the assembly. private IEnumerable ScanForCommands() { return ( from type in this.GetType().Assembly.GetTypes() where !type.IsAbstract && typeof(ITrainerCommand).IsAssignableFrom(type) select (ITrainerCommand)Activator.CreateInstance(type) ); } } }