Monday, October 29, 2012

Creating EasyKeyboard class: Part 11

In this tutorial we'll fix a bug with addEasyComboListener method and add an addEasySequenceListener method.

The addEasyComboListener function right now doesn't work exactly as it is supposed to. It's actually missing an important line, which adds keyCodes to listeners. I don't know how I left this unnoticed (sorry), but the code is fixed by adding a simple line, which adds each key code to the keyCodes array, which is then applied to the ComboListener.

/**
 * Add event listener for a combination of keys using key names.
 * @paramkeyNames Array of key names for the combination.
 * @paramhandler Function to execute when the combination is held.
 */

public function addEasyComboListener(keyNames:Array, handler:Function):void {
var flags:Array = [];
var keyCodes:Array = [];
var u:int;
var i:int;
var code:int = -1;
var keyName:String;

for (u = 0; u < keyNames.length; u++) {
flags.push(false);
code = -1;
keyName = keyNames[u];
for (i = 0; i < keyLabels.length; i++) {
if (keyLabels[i] == keyName) {
code = i;
keyCodes.push(code);
break;
}
}
if (code == -1) {
throw new Error('Incorrect key string value specified - no "' + keyName + '" key found.');
return;
}
}

listeners.push(new ComboListener(keyCodes, handler, flags));
}

The addEasySequenceListener() method is a mix between addSequenceListener() and addEasyComboListener() functions:

/**
 * Add event listener for a sequence of keys to be pressed using key names.
 * @paramkeyNames Array of key names in the sequence.
 * @paramhandler Function to execute when the keys are pressed in the specific order.
 */

public function addEasySequenceListener(keyNames:Array, handler:Function):void {
var keyCodes:Array = [];
var u:int;
var i:int;
var code:int = -1;
var keyName:String;

for (u = 0; u < keyNames.length; u++) {
code = -1;
keyName = keyNames[u];
for (i = 0; i < keyLabels.length; i++) {
if (keyLabels[i] == keyName) {
code = i;
keyCodes.push(code);
break;
}
}
if (code == -1) {
throw new Error('Incorrect key string value specified - no "' + keyName + '" key found.');
return;
}
}
listeners.push(new SequenceListener(keyCodes, handler));
}

Back in main.as you can now use these 2 listener types like this:

keyboard = new EasyKeyboard(stage);
keyboard.addEasySequenceListener(["A", "S", "D"], function() { trace("Sequence A+S+D registered!") } );
keyboard.addEasyComboListener(["G", "H"], function () { trace("G+H combination registered!"); } );

This was a rather short tutorial, but the methods needed wrapping up.

We will work on removing individual listeners in the next parts.

Thanks for reading!

No comments:

Post a Comment