KeyDemo.as
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
public class KeyDemo extends Sprite {
var t : TextField = new TextField;
public function KeyDemo() {
key.initKey(stage);
t.autoSize = TextFieldAutoSize.LEFT;
addChild(t);
stage.addEventListener(Event.ENTER_FRAME, showKeys);
}
public function showKeys(e : Event) {
var s : String = "";
var i : int;
for (i = 0; i < key.MAXKEY; i++) {
if (key.k[i]) { s = s + "Key[" + i.toString() + "] pressed "; }
}
t.text = s;
}
}
}
key.as
package {
import flash.events.KeyboardEvent;
public class key {
static const MAXKEY = 128;
// keycode declarations
static const RIGHT = 39;
static const LEFT = 37;
static const UP = 38;
static const DOWN = 40;
static const PLUS = 107;
static const EQUAL = 187;
static const MINUS = 109;
static const UNDERSCORE = 189;
static const SPACE = 32;
static const ENTER = 13;
public static var k : Array = new Array(MAXKEY); // stores all key states as boolean
// adds keyboard handler to provided object
public static function initKey(o : Object) {
var i : int;
for (i = 0; i < MAXKEY; i++) {
k[i] = false; }
o.addEventListener(KeyboardEvent.KEY_DOWN, keyDownListener);
o.addEventListener(KeyboardEvent.KEY_UP, keyUpListener);
}
public static function keyDownListener(e : KeyboardEvent) {
k[e.keyCode] = true;
}
public static function keyUpListener(e : KeyboardEvent) {
k[e.keyCode] = false;
}
}
}