在AS3中使用键盘事件

时间:2013-09-25 00:24:28

标签: actionscript-3 flash keyboard

我正在尝试在AS3 Non-OOP中编写一个简单的程序(我直接编写到时间轴上)但我的函数“选择”并没有被调用。实际上它根本没有被调用,我没有收到编译器错误。这是我的代码:

//Black jack game
import flash.events.Event;
import flash.ui.Mouse;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
addEventListener(Event.ENTER_FRAME,talk);

stop();
var yourHand1:Number = 0;
var cHand1:Number = 0;
var yourHand2:Number = 0;
var cHand2:Number = 0;

function talk(e:Event){

    if(yourHand1 < 3){
        yourHand1 +1;
    }
    if(cHand1 < 3){
        cHand1 +1;
    }
    cHand1 = 1+Math.floor(Math.random() * 11);
    yourHand1 = 1+Math.floor(Math.random()* 11);
    trace(cHand1);  
    trace(yourHand1);
    cHand.text = cHand1.toString();
    yourHand.text = yourHand1.toString();
    removeEventListener(Event.ENTER_FRAME, talk);
    //choices();
}

addEventListener(KeyboardEvent.KEY_DOWN,choices);

function choices(event:KeyboardEvent){
    trace("Would you like to hit or stay?");
    trace("Press left arrow to hit, space bar to stay");
    if(event.charCode == 65){
        trace("You have chosen to stay");
    }
    if(event.charCode == 66){
        letsDoItAllAgain();
    }
}


function letsDoItAllAgain(){

    if(yourHand2 <= 2){
        yourHand2 +2;
    }
    if(cHand2 <= 2){
        cHand2 +2;
    }
    cHand2 = 1+Math.floor(Math.random() * 11);
    yourHand2 = 1+Math.floor(Math.random()* 11);
    trace(cHand2);  
    trace(yourHand2);
    cHand.text = (cHand2 + cHand1).toString();
    yourHand.text = (yourHand1 + cHand2).toString();
    removeEventListener(Event.ENTER_FRAME, letsDoItAllAgain);
}

2 个答案:

答案 0 :(得分:3)

尝试在舞台上添加eventListener。

stage.addEventListener(KeyboardEvent.KEY_DOWN,choices);

答案 1 :(得分:0)

另外潘说:

stage.addEventListener(KeyboardEvent.KEY_DOWN,choices);

重要的是要知道您可能会失去主窗口的焦点。 我的项目中也有类似的东西(时间轴也是如此),我必须定期打电话(当我知道重点可能丢失时):

stage.focus = stage;