KeyManager Class

Hello,
Working on a game I’m always doing almost the same thing for the keymanager, and as I’m a bit lazy to redo everytime the same thing I came with a class to handle the key.

Here is the class:


/**
* The KeyManager will help you manage your key action (a key pressed an action).<br/>
* You can add / delete key action<br/>
* You can enable or disable key action, if you want eg to keep them in memory for later use.<br/>
* Here is a short example:<br/>
* 
* This will called the keyRightPressed method of the object referenced by "this"
* {@code
* 	_kmKey = new KeyManager();
* 	_kmKey.addKeyAction(37, this, "keyLeftPressed", []);
*	_kmKey.addKeyAction(39, this, "keyRightPressed", []);
*	_kmKey.addKeyAction(80, this, "pauseEngine", []);
* }
* 
* 
* This will disable (not deleting) all the key except the "P".<br/>
* So then if you're pressing on the direction key left or right nothing will happen.<br/>
* But the "P" key is still active
* {@code
* 	_kmKey.disableAllKey([80]);
* }
* 
* 
* This will enable all the key. You can pass an array of keycode exception as well.<br/>
* Here all the key will be enable again.<br/>
* So when you will press the left or right direction key their action will be executed.
* {@code
* 	_kmKey.enableAllKey();
* }
* 
* @author Xavier MARTIN aka xxlm or zeflasher
* @version 1.0
*/
class net.webbymx.utils.KeyManager {
/* ****************************************************************************
* VARIABLES
**************************************************************************** */
	private var _oKeyPressed:Object;
	private var _oKeyMemory:Object;


/* ****************************************************************************
* 
**************************************************************************** */
/**
* Call like this {@code yourInstance = new KeyManager(); }
*/
	public function KeyManager() { Key.addListener (this); }
	
	
/* ****************************************************************************
* PRIVATE FUNCTIONS
**************************************************************************** */
/*
* Execute the action for the specified key
* @param	k: Key Code Number
* @return Void
*/
	private function doAction(k:Number):Void {
		_oKeyPressed["k_"+k][0][_oKeyPressed["k_"+k][1]].apply(_oKeyPressed["k_"+k][0], _oKeyPressed["k_"+k][2]);
	}
	
	
/*
* Listen the onKeyDown event
* @return Void
*/	
    private function onKeyDown (Void):Void {
		var k: Number = Key.getCode ();
		if (_oKeyPressed["k_"+k] != undefined) doAction(k);
    }
	
	
/*
* Delete the specified key from the memory
* @param	k
* @return Void
*/
	private function delMemory(k:Number):Void {
		delete _oKeyMemory["k_"+k];
	}
	
/* ****************************************************************************
* PUBLIC FUNCTIONS
**************************************************************************** */
/**
* Execute the action for the specified key (keycode)
* @param	k Keycode of the key
* @param	scope Scope of the function
* @param	f Function name
* @param	args Arguments of the function
* @return	Void
*/
	public function addKeyAction (k:Number, scope:Object, f:String, args:Array):Void {
		if (_oKeyPressed == undefined) _oKeyPressed = new Object();
		_oKeyPressed["k_"+k] = new Array(scope, f, args);
	}
	
	
/**
* Delete action for the specified key (keycode)
* @param	k Keycode fo the key
* @return	Void
*/
	public function delKeyAction (k:Number):Void {
		delete _oKeyPressed["k_"+k];
	}
	
	
/**
* Disable the key refered by the keycode passed in the argument
* @param	k Keycode fo the key
* @return	Void
*/
	public function disableKey(k:Number):Void {
		if (_oKeyMemory == undefined) _oKeyMemory = new Object();
		_oKeyMemory["k_"+k] = _oKeyPressed["k_"+k];
		delKeyAction(k);
	}
	
	
/**
* Enable the key refered by the keycode passed in the argument
* @param	k Keycode fo the key
* @return	Void
*/
	public function enableKey(k:Number):Void {
		_oKeyPressed["k_"+k] = _oKeyMemory["k_"+k];
		delMemory(k);
	}
	
	
/**
* Disable all the Key. If you don't want certain key to be disabled 
* you can pass an array of keycode as an argument
* @param	exception Array holding all the keycode number for exception
* @return	Void
*/
	public function disableAllKey(Void):Void {
		if (arguments[0] != undefined && arguments[0] instanceof Array) var exception:Array = arguments[0];
		if (_oKeyMemory == undefined) _oKeyMemory = new Object();
		for (var prop:String in _oKeyPressed) {
			var exc:Boolean = false;
			if (exception.length > 0) {
				for (var i:Number = 0; i<exception.length; ++i) {
					if (prop == "k_"+exception*) {
						exc = true;
						exception.splice(i,1);
						break;
					}
				}
			}
			if (!exc) {
				_oKeyMemory[prop] = _oKeyPressed[prop];
				delete _oKeyPressed[prop];
			}
		}
	}
	
	
/**
* Enable all the Key. If you don't want certain key to be enabled
* you can pass an array of keycode as an argument
* @param	exception Array holding all the keycode number for exception
* @return	Void
*/
	public function enableAllKey(Void):Void {
		if (arguments[0] != undefined && arguments[0] instanceof Array) var exception:Array = arguments[0];
		for (var prop:String in _oKeyMemory) {
			var exc:Boolean = false;
			if (exception.length > 0) {
				for (var i:Number = 0; i<exception.length; ++i) {
					if (prop == "k_"+exception*) {
						exc = true;
						exception.splice(i,1);
						break;
					}
				}
			}
			if (!exc) {
				_oKeyPressed[prop] = _oKeyMemory[prop];
				delete _oKeyMemory[prop];
			}
		}
	}
	
/* ****************************************************************************
* GET & SET
**************************************************************************** */

}

Read the comment in the class for the help.
Please gimme some feedbacks on this one, and/or if you see any features that could be added to it…
Anyway I hope it will help some.

C ya

Beauty, I prefer something along the lines of this:

//Key class broadcasting
Key.addListener(Key);
Key["onKeyDown"] = function ():Void {
 this.broadcastMessage("onKey" + Key.getCode() + "Down");
};
//
//example usage for listening to key 65 (A)
Key.addListener(this);
this.onKey65Down = function():Void  {
 trace("key 65 pressed");
};
//

I guess it’s just personal preference - really nice work :thumb:

Oh and I think this would be better suited in the Source/Experiments section :slight_smile:

Oh sorry btw I didn’t tell how to use it.


     _kmKey = new KeyManager();
//	Define the action Key
	_kmKey.addKeyAction(37, this, "keyLeftPressed", []);
	_kmKey.addKeyAction(39, this, "keyRightPressed", []);
	_kmKey.addKeyAction(80, this, "pauseEngine", []);

     public function keyLeftPressed() {}
     public function keyRightPressed() {}
     public function pauseEngine() {}

Ok, I will put it there (double post sorry then)
Otherwise the class is doing basically doing the same as your exemple.

Anyway thx for the feedbacks.

Oh I know how to use it I was just giving another example, sorry if I’m intruding in your thread. Like I said it’s a really useful class :slight_smile:

In fact I’ll delete the post to avoid confusion :beer:

Lol no worries mate. I just add a reply to add the eg I forgot to put in the first one. Oh man you shouldn’t. People maybe will prefer your way of doing it. You shoul drepost it lol … :slight_smile:

Anyway thx for the feedbacks (if you ahve time check the other thread I’ve started as well for the XClassEventListener. I need feedbacks for this one as well :slight_smile: )

Cheers