Skip to main content
GameDev.net gamedev.net
🔒 Locked

C# code for dev console message handling

Started by Fluxtah Oct 28, 2005 at 10:06 AM 0 replies 350+ views
Original Post
Fluxtah
Fluxtah
Hi, I was looking for some feedback on my Console class (maybe it should be called ConsoleMessageManager). As I have no programming friends its difficult to get any critisisms and help that might make me a better programmer so I thought I would post it here :D It is a singleton class designed to take a console message and raise an event that any listeners can pick up and process. To use it all you have to is hook up the Command event to a handler anywhere in your application, this way any class such as a Player class and/or a GameRules class can pick up the message and do whatever it needs to. Its very basic, I have much more to add to it (maybe use delegates so I can register specific messages with context help and auto-completion) but I just want to make sure I am on the right track :) cheers!

	public class ConsoleCommandEventArgs : EventArgs 
	{
		public string Command;
		public string[] CommandArgs;
		public ConsoleCommandEventArgs(string command, string[] args) 
		{
			this.Command = command;
			this.CommandArgs = args;
		}
	}


	public delegate void ConsoleCommandEventHandler(object sender, ConsoleCommandEventArgs e);

	public sealed class Console
	{
		public event ConsoleCommandEventHandler Command;    

		static readonly Console instance = new Console();

		static Console()
		{
			
		}


		Console()
		{

		}


		public void ExecuteCommand(string command)
		{
			// trim any whitespace from beginning and end of the string
			command = command.Trim().ToLower();

			// make sure there are no double spaces, args should be seperated by single
			// spaces only
			command = System.Text.RegularExpressions.Regex.Replace(command,@"[\s]+"," ");
			
			string cmd;
			string[] args = null;

			// do we have args? if so then grab the command and
			// populate our args array, if not then make our args a
			// zero length array
			if(command.IndexOf(" ")>-1)
			{
				cmd = command.Substring(0,command.IndexOf(" "));
				command = command.Remove(0,command.IndexOf(" ")+1); // remove the command from the args
				args = command.Split(' ');
			}
			else
			{
				cmd = command;
				args = new string[0];
			}

			ConsoleCommandEventArgs e = new ConsoleCommandEventArgs(cmd,args);
			OnCommand(e);
		}


		void OnCommand(ConsoleCommandEventArgs e)
		{
			if(Command!=null)
			{
				Command(this, e);
			}
		}


		public static Console Instance
		{
			get
			{
				return instance;
			}
		}
	}
A wise man can learn more from a foolish question, than a fool can learn from a wise answer - Bruce Lee

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.