Question

how to disable keyboard keys in Action Script?

I'm creating Flash "memory" game, Idea to discover 2 equal cards. When 2nd card is discovered it is shown for 750 milliseconds, in that time player can't do any actions. When I use this mouseChildren = false; player can't click with mouse for this time, but he can use keyboard arrows/enter/space/tab buttons... I need to disable It for this time.

Here is part of my code:

            {
                    trace("Wrong");
                    _message = "Wrong";
                    message_txt.text = _message;
                     _secondCard = event.currentTarget;


                    var timer:Timer = new Timer(750, 1);
                    timer.addEventListener(TimerEvent.TIMER_COMPLETE, flipBack);
                    timer.start();

                stage.addEventListener(KeyboardEvent.KEY_DOWN, blindKeyboard);//added here
                stage.addEventListener(KeyboardEvent.KEY_UP, blindKeyboard);//added here


                    mouseChildren = false;


                }
            }

function blindKeyboard(e:KeyboardEvent):void{ //added here function
    e.preventDefault();
    e.stopPropagation();
}

            protected function flipBack(event:TimerEvent):void
    {
        _firstCard.gotoAndPlay("flipBack");
        _secondCard.gotoAndPlay("flipBack");
        _firstCard.addEventListener(MouseEvent.CLICK, checkCards);
        _secondCard.addEventListener(MouseEvent.CLICK, checkCards);
        _firstCard = _secondCard = undefined; 
        mouseChildren = true;
    }
Was it helpful?

Solution

You could just have functions for adding/removing listeners :

function addListeners():void
{
    // loop through and add the listeners for the cards
    // add keyboard listeners
}

function removeListeners():void
{
   // loop through and remove listeners from the cards
   // remove keyboard listeners
}

Before you set the timer, you remove your listeners :

removeListeners();

Then in your flipback timer handler you just call the addListeners :

addListeners();

OTHER TIPS

Try

stage.addEventListener(KeyboardEvent.KEY_DOWN, blindKeyboard);
stage.addEventListener(KeyboardEvent.KEY_UP, blindKeyboard);
function blindKeyboard(e:KeyboardEvent):void{
    e.preventDefault();
    e.stopPropagation();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top