From 5de6569bb1e63727e632d6459309b955e7ab7d5c Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 12 May 2018 17:34:40 -0400 Subject: minor cleanup --- src/SMAPI.Mods.ConsoleCommands/ModEntry.cs | 74 ++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/SMAPI.Mods.ConsoleCommands/ModEntry.cs (limited to 'src/SMAPI.Mods.ConsoleCommands/ModEntry.cs') diff --git a/src/SMAPI.Mods.ConsoleCommands/ModEntry.cs b/src/SMAPI.Mods.ConsoleCommands/ModEntry.cs new file mode 100644 index 00000000..7588043d --- /dev/null +++ b/src/SMAPI.Mods.ConsoleCommands/ModEntry.cs @@ -0,0 +1,74 @@ +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 + { + /********* + ** Properties + *********/ + /// 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 + GameEvents.UpdateTick += this.GameEvents_UpdateTick; + } + + + /********* + ** Private methods + *********/ + /// The method invoked when the game updates its state. + /// The event sender. + /// The event arguments. + private void GameEvents_UpdateTick(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) + ); + } + } +} -- cgit