Up Up Down Down Left Right Left Right B A

by Martin on 29/03/2008

While showering last night (this is usually when ideas and / or solutions present themselves) I came up with this idea.

Basically it’s a simple class that allows you to listen for specific sequences of keystrokes. So if the user was to press the sequence in the title, in the correct order naturally, you might react to it in any way you might deem funny. Code beneath the cut.

(BTW: I’m not all that familiar with the Text package in AS3 yet, so if there is some kind of method that does this for you please let me know.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package{

import flash.display.*;
import flash.events.*;

public class CheatCode extends EventDispatcher {

  //Create an array to keep our key sequence
  var aKeys:Array;
  // Counter to keep track of keystrokes
  var count: int;

public function CheatCode (stage:Stage){ 

  trace("I'm here baby")

  stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
  // Start at zero
  count = 0;
  // Keycodes for "Up Up Down Down Left Right Left Right B A"
  aKeys = new Array(38,38,40,40,37,39,37,39,66,65);

  }

private function onKeyUp(ke:KeyboardEvent) : void {  

for (var i:int = 0; i < aKeys.length; i++) {
  if (count == i) {
    if (ke.keyCode != aKeys[i]) {
      /*If the keystroke DOESN'T match the
        keyCode at the array position
        set the counter back to zero
        and start over*/

      count = 0;
      return;
    } else {
      /*If, however, it DOES match
      advance the counter
      and keep listening*/


      trace(count + " correct. Keep going")
      count++;

    if (count != aKeys.length) {
      /*If the keystrokes so far are
      correct but we're not yet at the
      end of the sequence; Carry on.*/

      return;
      }
    }
  }
  /*And, finally; When we're at the
  end of the sequence and all is well
  reset count and dispach an event to
  which one might want to react.*/

  if (count == aKeys.length) {
  count = 0;
  dispatchEvent(new Event("CodeEntered",true,false));
  }

  }

}
}

}

The class + Usage example file here.

There is 1 comment in this article:

  1. 6/06/2009Control Option Command » Capture key sequences in ActionScript 3. AKA The Konami Comeback. says:

    [...] I wrote a (crappy but working) class to implement such functionality in ActionScript about a year ago here. [...]

Write a comment: