konami code in flex

A state machine is fun to write, but in this case I’d go with a signature pattern. Depending on where you want to put the handler (on the stage of the component), here’s some code that should work, though you can probably tighten it (and of course customize it to your specific need):

// up-up-down-down-left-right-left-right-B-A
public static const KONAMI_CODE:String = "UUDDLRLRBA";

// signature
private var signatureKeySequence:String = "";

private function onKeyDown(event:KeyboardEvent):void {
    var keyCode:int = event.keyCode;

    switch (keyCode) {
        case Keyboard.UP:
            signatureKeySequence += "U";
            break;

        case Keyboard.DOWN:
            signatureKeySequence += "D";
            break;

        case Keyboard.LEFT:
            signatureKeySequence += "L";
            break;

        case Keyboard.RIGHT:
            signatureKeySequence += "R";
            break;

        case Keyboard.B:
            signatureKeySequence += "B";
            break;

        case Keyboard.A:
            signatureKeySequence += "A";
            break;

        default:
            signatureKeySequence = "";
            break;
    }

    // crop sequence
    signatureKeySequence = signatureKeySequence.substr(0, KONAMI_CODE.length);

    // check for konami code
    if (signatureKeySequence == KONAMI_CODE) {
        // 30 lives!
    }
}

Leave a Comment

tech