code by Michael Avila,
written by Kirupa | 3 April 2006
We started to go through the hefty parts of the code on
the previous page.
In this page, we will chug on and trace how our key
detection actually maps what you type to what you specified
as a trigger in your FLA.
- private
function
onKeyDown
()
- {
- var
key
:
Number =
Key.getCode
();
- cleanKeysPressed
();
- if
(key
!=
keys_pressed [keys_pressed.length
-
1])
- {
- keys_pressed.push
(key);
- }
- checkCombinations
();
- }
This function is responsible for checking which keys you
have pressed and adding them to your keys_pressed array.
First you call the cleanKeysPressed() function to clear your
past history of key presses, and then you cycle through your
keys_pressed array to make sure the key you just pressed
hasn't been pressed consecutively.
In other words, you can press Ctrl + Z + N + Z
continuously, but you will not be allowed to press Ctrl + Z
+ Z. Also, your keys_pressed array stores only the letters
that you press in a combination. Pressing the Ctrl key,
releasing the Ctrl key, and pressing the Z key again will
not cause your keys_pressed array to store the keycode for
both your Ctrl and Z key presses.
- private
function
checkCombinations
()
- {
- for
(var
j
: Number
=
0; j
<
key_combinations.length;
j
++)
- {
- for
(var
i
:
Number
=
0;
i
<
keys_pressed.length;
i
++)
- {
- if
(keys_pressed
[i]
==
key_combinations
[j][i
+
1])
- {
- if
(i
==
key_combinations
[j].length
-
2)
- {
-
invokeOnKeyCombination
(key_combinations
[j][0]);
- return;
- }
- }
else
- {
- break;
- }
- }
- }
- }
This function is where a lot of the action takes place!
The checkCombinations function uses two nested for loops to
compare whether the key combinations you specified match the
keys you pressed.
The best way to explain this is via an, albeit long,
example:
Trial 0.0
Let's say that you pressed the key combination Ctrl + Z
for Undo. Your key_combinations array, for example, contains
the following data:
key_combinations -> [[redo, 17,
89], [undo, 17, 90], [paste, 17, 86]];
Because you pressed Ctrl + Z, your keys_pressed array
will contain the codes for your Ctrl and Z keys:
keys_pressed -> [17, 90];
The code's goal is to realize that you pressing Ctrl + Z
(Key 17 + Key 89) maps to your key_combination for [undo,
17, 90]. So, let's try to see how the above lines of code
help you to interpret the key presses as Undo.
This is a pretty involved function, so take a quick break
and let's continue on the
next page!
|