user2072135
user2072135

Reputation: 59

Using keyboard events in AS3

I'm trying to write a simple program in AS3 Non- OOP (I'm coding directly to the timeline) but my function "choices" isn't being called like it should. In fact it's not being called at all and I receive no compiler error. Here's my code:

//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);
}

Upvotes: 0

Views: 450

Answers (2)

Pevi
Pevi

Reputation: 55

In addition Pan says:

stage.addEventListener(KeyboardEvent.KEY_DOWN,choices);

Is important to know that you can lose the focus of your main window. I have some similar in my project (too in the timeline), and i have to call regularly this (when i know that the focus can be lost):

stage.focus = stage;

Upvotes: 0

Pan
Pan

Reputation: 2101

Try to add eventListener on stage.

stage.addEventListener(KeyboardEvent.KEY_DOWN,choices);

Upvotes: 3

Related Questions