Change handler not triggering the first time in Flex - actionscript-3

I use a multiple-check Drop-Down which does not trigger the first Change event. Subsequent events trigger properly. When I select Select All or any other option the first time it does not trigger the event either.
use namespace mx_internal;
[Style(name="selectAllBorderAlpha", type="Number", inherit="no", theme="spark, mobile", minValue="0.0", maxValue="1.0")]
[Style(name="selectAllBorderColor", type="uint", format="Color", inherit="no", theme="spark, mobile")]
[Style(name="selectAllBorderVisible", type="Boolean", inherit="no", theme="spark, mobile")]
[Style(name="selectAllBackgroundColor", type="uint", format="Color", inherit="no", theme="spark, mobile")]
[Style(name="selectAllBackgroundAlpha", type="Number", inherit="no", theme="spark, mobile", minValue="0.0", maxValue="1.0")]
[IconFile("DropDownList.png")]
[DiscouragedForProfile("mobileDevice")]
public class CheckBoxDropDownList extends CheckBoxDropDownListBase
{
public function CheckBoxDropDownList()
{
super();
addEventListener(IndexChangeEvent.CHANGE, indexChangeHandler);
}
protected function indexChangeHandler(event:IndexChangeEvent):void
{
selectedAll = false;
}
[SkinPart(required="false")]
public var selectAllCheckBox:CheckBox;
[SkinPart(required="false")]
public var selectAllHitArea:UIComponent;
[SkinPart(required="false")]
public var labelDisplay:IDisplayText;
private var labelChanged:Boolean = false;
private var labelDisplayExplicitWidth:Number;
private var labelDisplayExplicitHeight:Number;
private var sizeSetByTypicalItem:Boolean;
override public function get baselinePosition():Number
{
return getBaselinePositionForPart(labelDisplay as IVisualElement);
}
private var _prompt:String = "";
[Inspectable(category="General", defaultValue="")]
public function get prompt():String
{
return _prompt;
}
public function set prompt(value:String):void
{
if (_prompt == value)
return;
_prompt = value;
labelChanged = true;
invalidateProperties();
}
[Inspectable(category="Data")]
override public function set typicalItem(value:Object):void
{
super.typicalItem = value;
invalidateSize();
}
override protected function commitProperties():void
{
super.commitProperties();
if (labelChanged)
{
labelChanged = false;
updateLabelDisplay();
}
if (selectedAllChanged)
{
selectedAllChanged = false;
if (selectAllCheckBox)
{
selectAllCheckBox.selected = _selectedAll;
this.dispatchEvent(new Event("selectAllChanged"));
}
invalidateList();
}
}
override protected function partAdded(partName:String, instance:Object):void
{
super.partAdded(partName, instance);
if (instance == labelDisplay)
{
labelChanged = true;
invalidateProperties();
}
if (instance == selectAllCheckBox)
{
selectedAllChanged = true;
invalidateProperties();
}
if (instance == selectAllHitArea)
{
selectAllHitArea.addEventListener(MouseEvent.CLICK, selectAllHitArea_clickHandler);
}
}
override protected function partRemoved(partName:String, instance:Object):void
{
super.partRemoved(partName, instance);
if (instance == selectAllHitArea)
{
selectAllHitArea.removeEventListener(MouseEvent.CLICK, selectAllHitArea_clickHandler);
}
}
protected function selectAllHitArea_clickHandler(event:MouseEvent):void
{
if (selectAllCheckBox)
selectedAll = !selectAllCheckBox.selected;
}
private var _selectedAll:Boolean = false;
private var selectedAllChanged:Boolean;
public function get selectedAll():Boolean
{
return _selectedAll;
}
public function set selectedAll(value:Boolean):void
{
if (value == _selectedAll)
return;
_selectedAll = value;
selectedAllChanged = true;
labelChanged = true;
selectedIndices = Vector.<int>([]);
//setSelectedItem(undefined, false);
invalidateProperties();
}
public function setSelectedIndices(selValues:Array):void
{
if (this.dataProvider == null) {
return;
}
var selIndices:Vector.<int> = new Vector.<int>();
if (selValues == null || selValues.length == 0)
{
this.selectedAll = true;
return;
}
for(var i:int=0; i < this.dataProvider.length; i++)
{
for(var j:int=0; j < selValues.length; j++)
{
var obj:Object = this.dataProvider.getItemAt(i);
if(selValues[j] == obj.value || selValues[j] == obj.label)
{
selIndices.push(i);
break;
}
}
}
if (selIndices.length == 0)
{
this.selectedAll = true;
}
else
{
this.selectedAll = false;
this.selectedIndices = selIndices;
}
}
override protected function item_mouseDownHandler(event:MouseEvent):void
{
if (selectedAll)
{
selectedAll = false;
var newIndex:int
if (event.currentTarget is IItemRenderer)
newIndex = IItemRenderer(event.currentTarget).itemIndex;
else
newIndex = dataGroup.getElementIndex(event.currentTarget as IVisualElement);
var arr:Array = dataProvider.toArray()
arr.splice(newIndex, 1);
selectedItems = Vector.<Object>(arr);
return;
}
super.item_mouseDownHandler(event);
// if all items are selected, then unselect them and check the "Select All" checkbox.
if (selectedItems.length == dataProvider.length)
{
selectedAll = true;
selectedIndex = -1;
}
}
override protected function dropDownController_closeHandler(event:DropDownEvent):void
{
super.dropDownController_closeHandler(event);
// Automatically selected all items if no items are selected when closing the dropDown.
if (selectedItems.length == 0 && !selectedAll)
selectedAll = true;
}
override protected function measure():void
{
var labelComp:TextBase = labelDisplay as TextBase;
// If typicalItem is set, then use it for measurement
if (labelComp && typicalItem != null)
{
// Save the labelDisplay's dimensions in case we clear out typicalItem
if (!sizeSetByTypicalItem)
{
labelDisplayExplicitWidth = labelComp.explicitWidth;
labelDisplayExplicitHeight = labelComp.explicitHeight;
sizeSetByTypicalItem = true;
}
labelComp.explicitWidth = NaN;
labelComp.explicitHeight = NaN;
// Swap in the typicalItem into the labelDisplay
updateLabelDisplay(typicalItem);
UIComponentGlobals.layoutManager.validateClient(skin, true);
// Force the labelDisplay to be sized to the measured size
labelComp.width = labelComp.measuredWidth;
labelComp.height = labelComp.measuredHeight;
// Set the labelDisplay back to selectedItem
updateLabelDisplay();
}
else if (labelComp && sizeSetByTypicalItem && typicalItem == null)
{
// Restore the labelDisplay to its original size
labelComp.width = labelDisplayExplicitWidth;
labelComp.height = labelDisplayExplicitHeight;
sizeSetByTypicalItem = false;
}
super.measure();
}
override mx_internal function updateLabelDisplay(displayItem:* = undefined):void
{
if (labelDisplay)
{
if (displayItem == undefined)
{
if (selectedItems != null && selectedItems.length > 1)
displayItem = VectorUtils.vectorToArray(selectedItems, Object);
else
displayItem = selectedItem;
}
if (displayItem != null && displayItem != undefined)
if (displayItem is Array)
{
this.toolTip = selectedItemsToLabel(displayItem, labelField, labelFunction);
labelDisplay.text = (displayItem as Array).length + " selected";
}
else
{
this.toolTip = null;
labelDisplay.text = selectedItemsToLabel(displayItem, labelField, labelFunction);
}
else if (selectedAll)
labelDisplay.text = "All";
else
labelDisplay.text = prompt;
}
}
private function invalidateList():void
{
if (dataGroup == null)
return;
for each (var itemIndex:int in dataGroup.getItemIndicesInView())
{
var renderer:UIComponent = dataGroup.getElementAt(itemIndex) as UIComponent;
if (renderer)
renderer.invalidateDisplayList();
}
}
private function selectedItemsToLabel(item:Object, labelField:String=null, labelFunction:Function=null):String
{
if (labelFunction != null)
return labelFunction(item);
var collection:ICollectionView = null;
if (item is Array)
{
collection = new ArrayCollection(item as Array);
}
else if (item is ICollectionView)
{
collection = ICollectionView(item);
}
else if (item is IList)
{
collection = new ListCollectionView(IList(item));
}
if (collection != null)
{
var itemLabels:Array = [];
for each (var obj:Object in collection)
{
itemLabels.push(obj[labelField]);
}
return itemLabels.join(", ");
}
return LabelUtil.itemToLabel(item, labelField, labelFunction);
}
public function get selectedValues():Array
{
var arr:Array = [];
if(selectedItems != null && selectedItems.length > 0)
{
for each (var obj:Object in selectedItems)
arr.push(obj.value);
}
return arr;
}
public function get selectedLabels():Array
{
var arr:Array = [];
if(selectedItems != null && selectedItems.length > 0)
{
for each (var obj:Object in selectedItems)
arr.push(obj.label);
}
return arr;
}
}

Try to call super() after the addEventListener() in the constructor function

Related

Hovering off DPAD sometimes makes character move infinitely in one direction

I have a DPAD in my game when the player holds down let's say the Left DPAD, if he moves his touch to the Up DPAD and let's go, the player continues going in the left direction.
It also works if you hold the a direction, lets say Up continue holding but move off the Up DPAD, sometimes you may continue going in that direction.
What I've tried to prevent this:
On direction clicks, trigger checks on whether your in motion, or
already going a different direction
Setting collisions to force these variables to become false; aka,
you hit something, inMotion = false, etc
That's about all I can think of on how to fix this.
Also, I use a lot of variables for my checks, is it better to change my functions to return booleans, or is this way fine? Just curious.
Game Class
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Game extends MovieClip
{
public var area1:Boolean = true;
public var area2:Boolean = false;
public var area3:Boolean = false;
public var player1:Boolean = true;
public var player2:Boolean = false;
public var upWalkspeed:Number = -5;
public var downWalkspeed:Number = 5;
public var leftWalkspeed:Number = -5;
public var rightWalkspeed:Number = 5;
public var inMotion:Boolean = false;
public var goingUp:Boolean = false;
public var goingDown:Boolean = false;
public var goingLeft:Boolean = false;
public var goingRight:Boolean = false;
public var playerPosKeeper_mc:MovieClip = new mc_PlayerPosKeeper();
public var up_dpad:MovieClip = new dpad_Up();
public var down_dpad:MovieClip = new dpad_Down();
public var left_dpad:MovieClip = new dpad_Left();
public var right_dpad:MovieClip = new dpad_Right();
public var menu_dpad:MovieClip = new dpad_Menu();
public var run_dpad:MovieClip = new dpad_Menu();
public var barrierRoof1_game:MovieClip = new game_BarrierRoof();
public var barrierRoof2_game:MovieClip = new game_BarrierRoof();
public var barrierSide1_game:MovieClip = new game_BarrierSide();
public var barrierSide2_game:MovieClip = new game_BarrierSide();
public var StageCollisions:Array = new Array(barrierRoof1_game, barrierRoof2_game, barrierSide1_game, barrierSide2_game);
// fix MC goes after not before ||| public var player1States:Array = new Array(mc_P1D1,mc_P1D2,"mc_P1L1","mc_P1L2","mc_P1R1","mc_P1R2","mc_P1U1","mc_P1U2");
public function Game()
{
trace("SUCCESS | Constructed Game Class");
var aMove:Movement = new Movement(this);
addChild(aMove);
}
}
}
Movement Class
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.TouchEvent;
import flash.net.dns.AAAARecord;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class Movement extends MovieClip
{
public function Movement(main:Game)
{
trace("SUCCESS | Constructed Movement Class");
addChild(main.playerPosKeeper_mc);
main.playerPosKeeper_mc.x = 384;
main.playerPosKeeper_mc.y = 46;
addChild(main.up_dpad);
main.up_dpad.x = 55;
main.up_dpad.y = 336;
addChild(main.down_dpad);
main.down_dpad.x = 57;
main.down_dpad.y = 432;
addChild(main.left_dpad);
main.left_dpad.x = 19;
main.left_dpad.y = 372;
addChild(main.right_dpad);
main.right_dpad.x = 118;
main.right_dpad.y = 372;
addChild(main.menu_dpad);
main.menu_dpad.x = 61;
main.menu_dpad.y = 377;
addChild(main.run_dpad);
main.run_dpad.x = 684;
main.run_dpad.y = 369;
addChild(main.barrierRoof1_game);
main.barrierRoof1_game.x = 0;
main.barrierRoof1_game.y = 0;
addChild(main.barrierRoof2_game);
main.barrierRoof2_game.x = 0;
main.barrierRoof2_game.y = 470;
addChild(main.barrierSide1_game);
main.barrierSide1_game.x = 0;
main.barrierSide1_game.y = 0;
addChild(main.barrierSide2_game);
main.barrierSide2_game.x = 790;
main.barrierSide2_game.y = 0;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
main.up_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, upBeginInput);
main.down_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, downBeginInput);
main.left_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, leftBeginInput);
main.right_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, rightBeginInput);
// Maybe add diagnol direction buttons in the future?;
// !! NOTE !!
// Use some sort of value, maybe a return or a variable to sync up animations
// to if the player is moving, in the future
// Movement Directions
// Start of UP Movement
function upBeginInput(e:TouchEvent):void
{
main.inMotion = true;
main.goingUp = true;
main.goingDown = false;
main.goingLeft = false;
main.goingRight = false;
main.up_dpad.addEventListener(TouchEvent.TOUCH_END, upEndInput);
addEventListener(Event.ENTER_FRAME,sendUpMovement);
}
function upEndInput(e:TouchEvent):void
{
main.inMotion = false;
main.goingUp = false;
main.up_dpad.removeEventListener(TouchEvent.TOUCH_END, upEndInput);
removeEventListener(Event.ENTER_FRAME,sendUpMovement);
}
function sendUpMovement():void
{
if (main.inMotion == true && main.goingUp == true && main.goingDown == false && main.goingLeft == false && main.goingRight == false)
{
movePlayer(0, main.upWalkspeed);
}
else
{
}
}
// End of UP Movement
// Start of DOWN Movement
function downBeginInput(e:TouchEvent):void
{
main.inMotion = true;
main.goingUp = false;
main.goingDown = true;
main.goingLeft = false;
main.goingRight = false;
main.down_dpad.addEventListener(TouchEvent.TOUCH_END, downEndInput);
addEventListener(Event.ENTER_FRAME,sendDownMovement);
}
function downEndInput(e:TouchEvent):void
{
main.inMotion = false;
main.goingDown = false;
main.down_dpad.removeEventListener(TouchEvent.TOUCH_END, downEndInput);
removeEventListener(Event.ENTER_FRAME,sendDownMovement);
}
function sendDownMovement():void
{
if (main.inMotion == true && main.goingUp == false && main.goingDown == true && main.goingLeft == false && main.goingRight == false)
{
movePlayer(0, main.downWalkspeed);
}
else
{
}
}
// End of DOWN Movement
// Start of LEFT Movement
function leftBeginInput(e:TouchEvent):void
{
main.inMotion = true;
main.goingUp = false;
main.goingDown = false;
main.goingLeft = true;
main.goingRight = false;
main.left_dpad.addEventListener(TouchEvent.TOUCH_END, leftEndInput);
addEventListener(Event.ENTER_FRAME,sendLeftMovement);
}
function leftEndInput(e:TouchEvent):void
{
main.inMotion = false;
main.goingLeft = false;
main.left_dpad.removeEventListener(TouchEvent.TOUCH_END, leftEndInput);
removeEventListener(Event.ENTER_FRAME,sendLeftMovement);
}
function sendLeftMovement():void
{
if (main.inMotion == true && main.goingUp == false && main.goingDown == false && main.goingLeft == true && main.goingRight == false)
{
movePlayer(main.leftWalkspeed, 0);
}
else
{
}
}
// End of LEFT Movement
// Start of RIGHT Movement
function rightBeginInput(e:TouchEvent):void
{
main.inMotion = true;
main.goingUp = false;
main.goingDown = false;
main.goingLeft = false;
main.goingRight = true;
main.right_dpad.addEventListener(TouchEvent.TOUCH_END, rightEndInput);
addEventListener(Event.ENTER_FRAME,sendRightMovement);
}
function rightEndInput(e:TouchEvent):void
{
main.inMotion = false;
main.goingRight = false;
main.right_dpad.removeEventListener(TouchEvent.TOUCH_END, rightEndInput);
removeEventListener(Event.ENTER_FRAME,sendRightMovement);
}
function sendRightMovement():void
{
if (main.inMotion == true && main.goingUp == false && main.goingDown == false && main.goingLeft == false && main.goingRight == true)
{
movePlayer(main.rightWalkspeed, 0);
}
else
{
}
}
// End of RIGHT Movement
function movePlayer(movementX:Number, movementY:Number):void
{
var originalX:Number = main.playerPosKeeper_mc.x;
var originalY:Number = main.playerPosKeeper_mc.y;
main.playerPosKeeper_mc.x += movementX;
if (checkCollision())
{
main.playerPosKeeper_mc.x = originalX;
}
main.playerPosKeeper_mc.y += movementY;
if (checkCollision())
{
main.playerPosKeeper_mc.y = originalY;
}
}
function checkCollision():Boolean
{
for each (var StageCollisions:MovieClip in main.StageCollisions)
{
if (main.playerPosKeeper_mc.hitTestObject(StageCollisions))
{
return true;
main.inMotion = false;
main.goingUp = false;
main.goingDown = false;
main.goingLeft = false;
main.goingRight = false;
}
}
return false;
}
}
}
}
Before you even start to debug behaviors, you need to understand what algorithmic approach is. You have 4 similar pieces of code which differ in minor details and make your whole script too long and unreadable and hard to manage. Here's the guideline:
var isMoving:Boolean;
var Direction:Point = new Point;
var Buttons:Array = [Up, Down, Left, Right];
// Subscribe all buttons for the same handlers and behaviors.
for each (var aButton:InteractiveObject in Buttons)
{
aButton.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
aButton.addEventListener(MouseEvent.MOUSE_OUT, onUp);
aButton.addEventListener(MouseEvent.MOUSE_UP, onUp);
}
function onDown(e:MouseEvent):void
{
// Figure which button was pressed.
switch (e.currentTarget)
{
case Up:
Direction.x = 0;
Direction.y = -1;
break;
case Down:
Direction.x = 0;
Direction.y = 1;
break;
case Left:
Direction.x = -1;
Direction.y = 0;
break;
case Up:
Direction.x = 1;
Direction.y = 0;
break;
}
// Now start moving Hero into the Direction.
if (!isMoving)
{
isMoving = true;
addEventListener(Event.ENTER_FRAME, onFrame);
}
}
function onFrame(e:Event):void
{
Hero.x += Direction.x;
Hero.y += Direction.y;
}
function onUp(e:MouseEvent):void
{
// If any of buttons is released or mouse out, stop moving Hero.
removeEventListener(Event.ENTER_FRAME, onFrame);
Direction.x = 0;
Direction.y = 0;
isMoving = false;
}
As you can see, the beauty of algorithmic approach is that you need to handle differently only things that need to be handled differently, in the example case (which is pretty similar to what you want to create) it is the block to set the movement direction. The rest of the code is identical for all the buttons and that's why the whole script is short and readable, easy to understand and manageable.

Flash - Pause Game ActionScript 3

I'm only a beginner and this code is somewhere in the internet that I just want to learn
This is a snake game, I want to pause a game using spacebar keyboard
I don't know how to pause a game someone please help
import flash.ui.*;
public class Snake extends MovieClip
{
private var _Paused:Boolean = false
private var score, life, framesElapsed:Number;
private var p1speedX, p1speedY:Number;
private var spacePressed, readyToMove, gotoWin, gotoLose:Boolean;
private var left,right,up,down:Boolean;
private var snakes:Array;
private var mcFood:Food;
public function Snake()
{
}
//All Start Functions
public function startMenu()
{
stop();
btnStartGame.addEventListener(MouseEvent.CLICK, gotoStartGame);
btnHowToPlay.addEventListener(MouseEvent.CLICK, gotoHowToPlay);
}
public function startHowToPlay()
{
btnBack.addEventListener(MouseEvent.CLICK, gotoMenu);
}
public function startWin()
{
btnBack.addEventListener(MouseEvent.CLICK, gotoMenu);
}
public function startLose()
{
btnBack.addEventListener(MouseEvent.CLICK, gotoMenu);
}
public function startGame()
{
score = 0;
life = 3;
framesElapsed = 0;
p1speedX = 1; //snakek starts moving right
p1speedY = 0;
up = false;
down = false;
left = false;
right = false;
spacePressed = false;
readyToMove = false;
gotoWin = false;
gotoLose = false;
snakes = new Array();
//Create 1st body part of snake and push it into the array
var snakeHead = new SnakePart();
snakeHead.x = 400;
snakeHead.y = 300;
snakes.push(snakeHead);
addChild(snakeHead);
addEventListener(Event.ENTER_FRAME,update);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
stage.focus = this;
}
//All Goto Functions
private function gotoStartGame(evt:MouseEvent)
{
btnStartGame.removeEventListener(MouseEvent.CLICK, gotoStartGame);
btnHowToPlay.removeEventListener(MouseEvent.CLICK, gotoHowToPlay);
gotoAndStop("game");
}
private function gotoHowToPlay(evt:MouseEvent)
{
btnStartGame.removeEventListener(MouseEvent.CLICK, gotoStartGame);
btnHowToPlay.removeEventListener(MouseEvent.CLICK, gotoHowToPlay);
gotoAndStop("howtoplay");
}
private function gotoMenu(evt:MouseEvent)
{
btnBack.removeEventListener(MouseEvent.CLICK, gotoMenu);
gotoAndStop("menu");
}
private function keyDownHandler(evt:KeyboardEvent)
{
if (evt.keyCode == Keyboard.A)
{
//1st Player Left Key
left = true;
}
else if (evt.keyCode == Keyboard.D)
{
//1st Player Right Key
right = true;
}
if (evt.keyCode == Keyboard.W)
{
//1st Player Up Key
up = true;
}
else if (evt.keyCode == Keyboard.S)
{
//1st Player Down Key
down = true;
}
if (evt.keyCode == Keyboard.SPACE)
{
spacePressed = true;
}
}
private function keyUpHandler(evt:KeyboardEvent)
{
if (evt.keyCode == Keyboard.A)
{
left = false;
}
else if (evt.keyCode == Keyboard.D)
{
right = false;
}
else if (evt.keyCode == Keyboard.W)
{
up = false;
}
else if (evt.keyCode == Keyboard.S)
{
down = false;
}
if (evt.keyCode == Keyboard.SPACE)
{
spacePressed = false;
}
}
public function update(evt:Event)
{
handleUserInput();
handleGameLogic();
handleDraw();
if (gotoWin)
triggerGoToWin();
else if (gotoLose)
triggerGoToLose();
}
private function handleUserInput()
{
//Handle player 1 position
//if player wants to move left but snake is not
//already moving right
if (left && (p1speedX != 1))
{
p1speedX = -1;
p1speedY = 0;
}
//if player wants to move right but snake is not
//already moving left
else if (right && (p1speedX != -1 ))
{
p1speedX = 1;
p1speedY = 0;
}
//if player wants to move up but snake is not
//already moving down
else if (up && (p1speedY != 1))
{
p1speedY = -1;
p1speedX = 0;
}
else if (down && (p1speedY != -1))
{
p1speedY = 1;
p1speedX = 0;
}
if (spacePressed)
readyToMove = true;
}
private function handleGameLogic()
{
if (!readyToMove)
return;
framesElapsed++;
//Update the new position of the snake's head
if (framesElapsed % 2 == 0)
{
//Update motion of the snake's body
for (var i = snakes.length - 1; i >= 1; i--)
{
snakes[i].x = snakes[i-1].x;
snakes[i].y = snakes[i-1].y;
}
if (p1speedX > 0)
{
snakes[0].x += 20;
}
else if (p1speedX < 0)
{
snakes[0].x -= 20;
}
else if (p1speedY > 0)
{
snakes[0].y += 20;
}
else if (p1speedY < 0)
{
snakes[0].y -= 20;
}
//Check for collisions between the snake and its own body
for (var i = snakes.length - 1; i >= 1; i--)
{
if ((snakes[0].x == snakes[i].x) &&
(snakes[0].y == snakes[i].y))
{
collided();
break;
}
}
}
//Check for collisions between the snake and the walls
if (snakes[0].y < 0)
{
collided();
}
else if (snakes[0].x > 800)
{
collided();
}
else if (snakes[0].x < 0)
{
collided();
}
else if (snakes[0].y > 600)
{
collided();
}
//Add new food items
if (mcFood == null)
{
//Create a new food item
mcFood = new Food();
mcFood.x = Math.random() * 700 + 50;
mcFood.y = Math.random() * 500 + 50;
addChild(mcFood);
}
//Check for collisions between food item and Snake
if (mcFood != null)
{
if (snakes[0].hitTestObject(mcFood))
{
//Add score
score += 100;
if (score >= 5000)
gotoWin = true;
removeChild(mcFood);
mcFood = null;
//Add a body
var newPart = new SnakePart();
newPart.x = snakes[snakes.length-1].x;
newPart.y = snakes[snakes.length-1].y;
snakes.push(newPart);
addChild(newPart);
}
}
}
private function handleDraw()
{
//Handle display
if (!readyToMove)
txtHitSpaceBar.visible = true;
else
txtHitSpaceBar.visible = false;
txtScoreP1.text = String(score);
txtLife.text = String(life);
}
private function triggerGoToWin()
{
clearGame();
removeEventListener(Event.ENTER_FRAME, update);
gotoAndStop("win");
}
private function triggerGoToLose()
{
clearGame();
removeEventListener(Event.ENTER_FRAME, update);
gotoAndStop("lose");
}
//Misc Functions
private function resetGame()
{
//remove all food
removeChild(mcFood);
mcFood = null;
//remove all of snake body except first
for (var i = snakes.length - 1; i >= 1; i--)
{
removeChild(snakes[i]);
snakes.splice(i,1);
}
//Center the snake's head
snakes[0].x = 400;
snakes[0].y = 300;
readyToMove = false;
}
private function clearGame()
{
//remove all food
if (mcFood != null)
{
removeChild(mcFood);
mcFood = null;
}
//remove all of snake body
for (var i = snakes.length - 1; i >= 0; i--)
{
removeChild(snakes[i]);
snakes.splice(i,1);
}
}
private function collided()
{
life -= 1;
if (life > 0)
resetGame();
else
gotoLose = true;
}
}
}//end class
//end package
There are a few possibilities how to pause a game.
You already have a boolean variable called _Paused, this will help us to determine when to pause the execution of the game.
Change the contents of keyDownHandler(evt) to the following:
private function keyDownHandler(evt:KeyboardEvent)
{
...
//leave the if conditionals for movement as they are
if (evt.keyCode == Keyboard.SPACE)
{
if(_Pause == true){
_Pause = false;
}else{
_Pause = true;
}
}
}
The above code will toggle between a Paused state and the Game state. When the game first starts, the _Paused variable is false. Once you press Space on your keyboard, the if condition will check what state you need to be in. So at the very first time, _Paused will be set to true. if you press space again, it will set it to false again. Simple, right?
Now, you have an EventListener for ENTER_FRAME called update that executes for every frame. This function is responsible that things, well, work. You can see that it calls different functions that draw stuff on the screen or handle game logic. So, what would happen if you don't call this function? The game would stop. So we need a way to not call those functions when you are in your pause state. Again, this is very simple.
Change the contents of update(evt) to the following:
public function update(evt:Event)
{
if(_Paused == false){
handleUserInput();
handleGameLogic();
handleDraw();
if (gotoWin)
triggerGoToWin();
else if (gotoLose)
triggerGoToLose();
}
}
Now the functions will only be called when your _Paused variable is set to false.
I hope this helped you with your studying, although this is very basic stuff. Maybe you should try smaller steps first? Programming games can be pretty complex for beginner who have no experience with coding whatsoever.

Implicit coercion of a value of type flash.events:KeyboardEvent to an unrelated type flash.events:MouseEvent

how can I call a function of flash events : MouseEvent in flash events keyboardEvent function
I am a biggner in as3 please help
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
function keyPressed(event:KeyboardEvent){
if (event.keyCode == Keyboard.ENTER)
{
if (keyMode == 0)
{
keyMode = 1;
**startFun(event);**
}
else if (keyMode == 1)
{
**checkfun(event);**
}
else if (keyMode == 2)
{
keyMode = 1;
**anotherPro(event);**
}
}
}
There is several ways, dispatch events, etc. I'll give you a simple example:
// or should be KEY_UP?
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedHandler, false, 0, true);
stage.addEventListener(MouseEvent.CLICK, exampleMouseClickHandler, false, 0, true);
function exampleMouseClickHandler(event:MouseEvent):void
{
//if necessary to pass any parameter, just need to change these mouseClickLogic() / keyPressLogic() methods
mouseClickLogic();
keyPressLogic();
}
function mouseClickLogic():void
{
//do something...
}
function keyPressedHandler(event:KeyboardEvent):void
{
//if necessary to pass any parameter, just need to change these mouseClickLogic() / keyPressLogic() methods
keyPressLogic();
mouseClickLogic();
}
function keyPressLogic():void
{
//to something...
}
You can use like that:
MouseEvent in flash events:
import flash.events.MouseEvent;
stage.addEventListener(MouseEvent.CLICK,clickStage);
stage.addEventListener(MouseEvent.MOUSE_UP,upStage);
stage.addEventListener(Event.MOUSE_LEAVE,leaveStage);
stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownStage);
function clickStage(e:MouseEvent):void
{
trace("click Stage");
}
function upStage(e:MouseEvent):void
{
trace("up Stage");
}
function leaveStage(e:Event):void
{
trace("leave Stage");
}
function mouseDownStage(e:MouseEvent):void
{
trace("mouse Down Stage");
}
keyboardEvent function:
function reportKeyDown(event:KeyboardEvent):void
{
trace("Key Pressed: " + String.fromCharCode(event.charCode) + " (character code: " + event.charCode + ")");
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
I thank all those who tried to help me
this is my program without any error the error which I made before is in this code instead of Event
I typed MousEvent
function startFun(evt:Event):void
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.Event;
var elapsedTime:Number;
var NumOfProplem:Number;
var PropSolved:Number;
var completeSet:Boolean;
answerbox.restrict = "0-9";
ProplemBox.restrict = "0-9";
mult2.restrict = "?";
mult1.restrict = "?";
var keyMode:Number = 0;
stage.focus = ProplemBox;
bt1.visible = false;
bt2.visible = false;
//////////////////////////////
btnstart.addEventListener(MouseEvent.CLICK, startFun);
function startFun(evt:Event):void {
if (ProplemBox.text == "") {
stage.focus = ProplemBox;
return;
}
bt1.visible = true;
bt2.visible = true;
NumOfProplem = Number(ProplemBox.text);
PropSolved = 0;
completeSet = false;
elapsedTime = getTimer();
keyMode = 1;
anotherPro(evt);
}
///////////////////////////////
stage.focus = answerbox;
answerbox.setSelection(0,3);
}
/////////////////
bt1.addEventListener(MouseEvent.CLICK,checkfun);
function checkfun(evt:Event):void
{
var x:Number = parseInt(mult1.text);
var y:Number = parseInt(mult2.text);
var z:Number = parseInt(answerbox.text);
if ((x*y )== z){
messagebox.text = "Right";
PropSolved++;
if (PropSolved >= NumOfProplem ){
keyMode = 3;
endGameReport();
}
else{
keyMode = 2;
}
}
else
{
messagebox.text = "Wrong";
stage.focus = answerbox;
answerbox.setSelection(0,3);
}
}
function endGameReport():void{
elapsedTime = (getTimer() - elapsedTime);
stage.focus = ProplemBox;
ProplemBox.setSelection(0,2);
bt1.visible = false;
bt2.visible = false;
messagebox.text = "You completed" + NumOfProplem + "Proplems in"
+ Math.floor(elapsedTime/1000) + "Second";
}
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
function keyPressed(evt:KeyboardEvent){
if (evt.keyCode == Keyboard.ENTER)
{
if (keyMode == 0)
{
keyMode = 1;
startFun(evt);
}
else if (keyMode == 1)
{
checkfun(evt);
}
else if (keyMode == 2)
{
keyMode = 1;
anotherPro(evt);
}
}
}

ActionScript3 : Argument Error on constructor

I have a real problem on an ActionScript homework. I have to program a solitaire, and I'm now stuck on a bug that I don't understand.
When I launch my game object, it instanciates a CardDeck object, and fill its array with Card objects. But since my last edit, a "ArgumentError: Error #1063" is thrown every 2 seconds, and i just don't get why. I've looked and tried the few topics related to this Error, but I didn't manage to make it work ...
Here are my classes :
Card.as
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Card extends MovieClip
{
public static const COLOR_RED:int = 1;
public static const COLOR_BLACK:int = 2;
public static const SYMBOL_HEART:int = 1;
public static const SYMBOL_DIAMOND:int = 2;
public static const SYMBOL_SPADE:int = 3;
public static const SYMBOL_CLUB:int = 4;
public var game:Game;
private var t:Timer; // For click/double click fix
private var currentTarget:Card;
public var container:CardStack;
public var color:int;
public var symbol:int;
public var value:int;
public var isVisible:Boolean = false;
public function Card(type:int, value:int, g:Game)
{
game = g;
if (type == SYMBOL_HEART || type == SYMBOL_DIAMOND)
this.color = COLOR_RED;
else
this.color = COLOR_BLACK;
this.symbol = type;
this.value = value;
this.doubleClickEnabled = true;
this.addEventListener(MouseEvent.CLICK, Click);
this.addEventListener(MouseEvent.DOUBLE_CLICK, doubleClick);
}
private function doubleClick(e:MouseEvent):void
{
t.removeEventListener(TimerEvent.TIMER_COMPLETE, onCardClick);
if (t.running)
t.stop();
onCardDoubleClick(e);
}
private function Click(e:MouseEvent):void
{
currentTarget = (Card)(e.currentTarget);
t = new Timer(100,1);
t.addEventListener(TimerEvent.TIMER_COMPLETE, onCardClick);
t.start();
}
public function isSameColor(otherCard:Card):Boolean
{
if (this.color == otherCard.color)
return true;
else
return false;
}
public function setVisible(flipped:Boolean):void
{
if (flipped == true)
{
isVisible = true;
gotoAndStop(value);
}
else {
isVisible = false;
gotoAndStop(14);
}
game.pStage.addChild(this);
}
public function setInvisible():void
{
removeListeners();
game.pStage.removeChild(this);
}
public function removeListeners():void
{
this.removeEventListener(MouseEvent.CLICK, Click);
this.removeEventListener(MouseEvent.DOUBLE_CLICK, doubleClick);
}
private function onCardClick(e:TimerEvent):void
{
var card:Card = currentTarget;
if (this.isVisible == true) {
if (game.flagSelecting == false) {
if (!(card.container == game.deck && game.deck.isHeadCard(card) == false))
game.select.addToSelect(card);
}else{
if (card.container == game.deck)
game.deck.lastPickedCard--;
game.mvOutCard(game.select.tSelect, card.container);
}
}else {
if (((card.container.deckSize()) - 1) == (game.selCard(card, card.container)))
card.setVisible(true);
}
}
private function onCardDoubleClick(e:MouseEvent):void
{
var card:Card = (Card)(e.currentTarget);
// Acestack
if (game.aceStacks.canMoveTo(card) == true)
{
game.moveToAce(card);
}
//K sur place libre
if (card.value == 13) {
var freeStack:CardStack = (game.river.hasFreeStack());
if (freeStack != null){
game.select.addToSelect(card);
game.moveKing(game.select.tSelect, freeStack);
}
}
game.select.reinitSelection();
}
}
CardDeck.as
import Math;
import flash.events.MouseEvent;
import flash.events.Event;
public class CardDeck extends CardStack
{
// THIS IS ABOUT CARDDECK
public var lastPickedCard:int = 0;
public var isEmptyNow:Boolean = false;
// THIS IS ABOUT HANDSTACK
public var handStack:Array = new Array();
public static const X_FIRST_HANDCARD:int = 120;
public static const X_CARD_PADDING:int = 18;
public static const Y_HANDSTACK:int = 62;
public function CardDeck(g:Game)
{
trace("GAME" + g);
var a:Array = new Array();
var nGame:Game = g;
super(a,g);
trace("CONSTRUCTEUR2");
var i:int = 1;
while (i <= 52)
{
if (i < 14)
this.deck.push(new HeartCard(i,g));
else if (i >= 14 && i < 27)
this.deck.push(new DiamondCard(i - 13, g));
else if (i >= 27 && i < 40)
this.deck.push(new SpadeCard(i - 26, g));
else if (i >= 40)
this.deck.push(new ClubCard(i - 39, g));
i++;
}
trace("CONSTRUCTEUR3");
var nDeck:Array;
nDeck = new Array();
var idx:int;
while(this.deck.length > 0){
var r:int = Math.random()*(this.deck.length);
idx = (Math.floor(r));
//deck[idx].container = game.deck;
nDeck.push(deck.splice(idx, 1)[0]);
}
trace("CONSTRUCTEUR4");
this.deck = nDeck;
this.addEventListener(MouseEvent.CLICK, onDeckClick);
this.game.pStage.addChild(this);
this.x = 46;
this.y = 62;
trace("CONSTRUCTEUR5");
}
private function onDeckClick(e:MouseEvent):void
{
trace("LISTENER");
if (isEmptyNow == false)
fillHand();
else
setFilled();
}
public function setEmpty():void
{
this.alpha = .2;
this.isEmptyNow = true;
}
public function setFilled():void
{
this.alpha = 1;
this.isEmptyNow = false;
this.reinitHS();
}
// HANDSTACK
public function showHand():void
{
var i:int = 0;
while (i < (this.handStack.length)) {
trace("SHOW HAND");
handStack[i].setVisible(true);
handStack[i].y = Y_HANDSTACK;
handStack[i].x = X_FIRST_HANDCARD + (i * X_CARD_PADDING);
i++;
}
this.setDepth();
}
public function fillHand():void
{
trace("FILL");
if(lastPickedCard < (deck.length)-3)
this.handStack = this.deck.slice(deck.lastPickedCard, 3);
else {
this.handStack = this.deck.slice(game.deck.lastPickedCard);
this.setEmpty();
}
showHand();
}
public function reinitHS():void {
var i:int = 0;
while (i < (this.handStack.length)) {
handStack[i].setInvisible();
i++;
}
this.handStack = new Array();
}
public function isHeadCard(c:Card):Boolean
{
if (handStack.indexOf(c) == handStack.length -1)
return true;
else
return false;
}
}
CardStack.as
import flash.display.MovieClip;
public class CardStack extends MovieClip
{
public var deck:Array;
public var game:Game;
public function CardStack(newDeck:Array, g:Game)
{
game = g;
this.deck = newDeck;
}
public function isEmpty():Boolean {
if (this.deck.lenght == 0)
return true;
else
return false;
}
public function setDepth():void
{
var i:int = 0;
while (i < (this.deck.length))
{
if (i == 0)
this.deck[i].parent.setChildIndex(this.deck[i], 1);
else
this.deck[i].parent.setChildIndex(this.deck[i], 1 + i);
i++;
}
}
public function deckSize():int {return (this.deck.length);}
}
I call this here :
public function Game(pS:Stage)
{
pStage = pS;
select = new Selection(this);
trace("flag");
deck = new CardDeck(this);
trace("flag2");
aceStacks = new AceRiver(this);
river = new River(deck.deck, this);
}
And I get this exception :
ArgumentError: Error #1063: Argument count mismatch on CardDeck(). Expected 1, got 0
Any help would be really appreciated !
Stab in the dark; assuming that the only line that calls CardDeck() is:
deck = new CardDeck(this);
then I would ask, are you using more than one swf file in your project and loading one in at runtime? If so, try rebuilding all of your swfs that reference the CardDeck class.

Flex 4.6 Control timer in itemRenderer of TIleList

I am working with Flex 4.6 AIR application. I have a tile list and there is an image as an itemRenderer. When i search images, the data is not filtered but is selected the indices(selected items) of the tilelist and i set a custom property in arrayCollection(dataProvider) then updateDisplayList called and i start a timer in this function. Which perform play the inner images in the selected item.
Now the problem is when if i search the item and click the non selected item the timer is not stoped. How can i achieve that.
The code of itemRenderer is below
<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
autoDrawBackground="true" buttonMode="true"
click="itemrenderer2_clickHandler(event)"
doubleClick="itemrenderer1_doubleClickHandler(event)" doubleClickEnabled="true"
rightClick="itemrenderer1_rightClickHandler(event)"
rollOut="itemrenderer1_rollOutHandler(event)"
rollOver="itemrenderer1_rollOverHandler(event)" useHandCursor="true">
<fx:Script>
<![CDATA[
import customs.customcomponents.LibraryReDownloadComponent;
import customs.customcomponents.VideoUploadBox;
import dbconnection.Connection;
import globalData.DataModel;
import mx.collections.ArrayCollection;
import mx.core.FlexGlobals;
import mx.core.UIComponent;
import mx.events.ItemClickEvent;
import mx.managers.PopUpManager;
import mx.utils.ObjectProxy;
import mx.utils.UIDUtil;
private var isLoaded:Boolean = false;
private var timer:Timer;
private var rollOverFlag:Boolean = false;
private var countThumb:int = 0;
private var arrThumnail:ArrayCollection;
private var loaderThumb:Loader;
private var request:URLRequest;
private var requestThumb:URLRequest;
private var loader:Loader;
private var sqlStatStatus:SQLStatement;
private var downloadVideoPath:String = "";
private var videoUrlStream:URLStream;
private var videoFileStream:FileStream;
private var uploadvidbox:VideoUploadBox = new VideoUploadBox();
private var dtStartVideo:Date;
private var videoFileName:String = "";
private var videoFile:File;
private var IsRollOver:Boolean = false;
[Bindable]
private var modellocator:DataModel=DataModel.getInstance();
private var connection:Connection = Connection.getInstance();
override public function set data(value:Object):void
{
if(value != null)
{
super.data = value;
if(timer != null)
{
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, showFrame);
timer = null;
}
loaderThumb = new Loader();
rollOverFlag = false;
countThumb = 0;
if(flash.system.Capabilities.os.indexOf("Mac") > -1)
{
requestThumb = new URLRequest("file://" + data.Videothumbnail);
}
else
{
requestThumb = new URLRequest(data.Videothumbnail);
}
loaderThumb.contentLoaderInfo.addEventListener(Event.COMPLETE,onThumbComplete);
loaderThumb.load(requestThumb);
if(data.VideoBuyFlag == "yes")
{
if(data.VideoIsDeleted == "No")
{
bContain.setStyle("borderColor", "#00FF18");
bContain.alpha = 1;
}
else
{
bContain.setStyle("borderColor", "#888888");
bContain.alpha = 0.3;
}
}
else
{
if(data.VideoIsDeleted == "No")
{
bContain.setStyle("borderColor", "#C50000");
bContain.alpha = 1;
}
else
{
bContain.setStyle("borderColor", "#888888");
bContain.alpha = 0.3;
}
}
if(data.VideoStatus == "Active")
{
imgActive.source = "assets/btn_Active.jpg";
bContain.alpha = 1;
}
else
{
imgActive.source = "assets/btn_InActive.jpg";
bContain.alpha = 0.3;
}
arrThumnail = new ArrayCollection();
if(data.Videothumbdata.thumbimage != null)
{
if(data.Videothumbdata.thumbimage.source.item.length > 1)
{
for(var i:int = 0; i < data.Videothumbdata.thumbimage.source.item.length; i++)
{
arrThumnail.addItem(data.Videothumbdata.thumbimage.source.item[i]);
}
}
else
{
arrThumnail.addItem(data.Videothumbdata.thumbimage.source.item);
}
}
}
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
/* trace(data.Videoname);
trace("IsRollOver : " + IsRollOver.toString());
trace("IsSearching : " + data.IsSearching.toString());
trace("rollOverFlag : " + rollOverFlag.toString()); */
if(data.IsSearching == false)
{
if(IsRollOver == false)
{
if(timer != null)
{
trace("inner");
loaderThumb = new Loader();
rollOverFlag = false;
if(flash.system.Capabilities.os.indexOf("Mac") > -1)
{
requestThumb = new URLRequest("file://" + data.Videothumbnail);
}
else
{
requestThumb = new URLRequest(data.Videothumbnail);
}
loaderThumb.contentLoaderInfo.addEventListener(Event.COMPLETE,onThumbComplete);
loaderThumb.load(requestThumb);
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, showFrame);
countThumb= 0;
System.gc();
System.gc();
}
}
}
else
{
if(rollOverFlag == false)
{
rollOverFlag = true;
trace("Hi");
timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, showFrame);
timer.start();
}
else
{
if(timer != null)
{
trace("SecondInner");
loaderThumb = new Loader();
rollOverFlag = false;
if(flash.system.Capabilities.os.indexOf("Mac") > -1)
{
requestThumb = new URLRequest("file://" + data.Videothumbnail);
}
else
{
requestThumb = new URLRequest(data.Videothumbnail);
}
loaderThumb.contentLoaderInfo.addEventListener(Event.COMPLETE,onThumbComplete);
loaderThumb.load(requestThumb);
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, showFrame);
countThumb= 0;
System.gc();
System.gc();
}
}
}
}
protected function showFrame(event:TimerEvent):void
{
var file:File;
trace("hello");
if(countThumb < arrThumnail.length)
{
if(flash.system.Capabilities.os.indexOf("Mac") > -1)
{
file = new File("file://" + arrThumnail[countThumb]);
}
else
{
file = new File(arrThumnail[countThumb]);
}
if(file.exists)
{
loader = new Loader();
if(flash.system.Capabilities.os.indexOf("Mac") > -1)
{
request=new URLRequest("file://" + arrThumnail[countThumb]);
}
else
{
request=new URLRequest(arrThumnail[countThumb]);
}
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onComplete);
loader.load(request);
if(countThumb == (arrThumnail.length - 1))
{
countThumb = 0;
}
else
{
countThumb++;
}
}
else
{
countThumb++;
}
}
else
{
countThumb = 0;
}
}
protected function itemrenderer1_rollOverHandler(event:MouseEvent):void
{
if(data.IsSearching == false)
{
rollOverFlag = true;
IsRollOver = true;
if(arrThumnail != null && arrThumnail.length > 0)
{
timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, showFrame);
timer.start();
}
}
}
private function onComplete(event:Event):void
{
if(rollOverFlag)
{
imgThumb.source = loader;
}
}
private function onThumbComplete(event:Event):void
{
imgThumb.source = loaderThumb;
}
protected function itemrenderer1_rollOutHandler(event:MouseEvent):void
{
if(data.IsSearching == false)
{
rollOverFlag = false;
IsRollOver = false;
imgThumb.source = loaderThumb;
if(timer != null)
{
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, showFrame);
timer = null;
}
countThumb = 0;
System.gc();
System.gc();
}
}
protected function itemrenderer2_clickHandler(event:MouseEvent):void
{
for(var i:int=0; i < modellocator.libraryvideoac.length; i++)
{
modellocator.libraryvideoac[i].IsSearching = false;
}
parentDocument.parentDocument.txt_search.text = resourceManager.getString('languages','lblSearchText');
parentDocument.parentDocument.unCheckSelection();
if(data.VideoIsDeleted == "Yes")
{
var popupReDownload:LibraryReDownloadComponent = new LibraryReDownloadComponent();
popupReDownload = PopUpManager.createPopUp(UIComponent(this.parentApplication), LibraryReDownloadComponent, true) as LibraryReDownloadComponent;
popupReDownload.addEventListener("downloadMovie", redownloadMovie);
PopUpManager.centerPopUp(popupReDownload);
}
}
]]>
</fx:Script>
<fx:Declarations>
<mx:NumberFormatter id="numFormat" precision="2"/>
</fx:Declarations>
<s:BorderContainer id="bContain" left="2" top="2" width="92" height="67" backgroundAlpha="1"
backgroundColor="#000000" borderColor="#030304" borderWeight="3">
<s:Image id="imgThumb" width="86" height="61" fillMode="scale" scaleMode="stretch"/>
<s:Image id="imgActive" right="0" bottom="0" width="15" height="15" buttonMode="true"
useHandCursor="true"/>
</s:BorderContainer>
</s:ItemRenderer>
You have timer instantiation at different places in the code. I can't be sure of the actual program flow, but maybe you instantiate the timer two times? In that case program would overwrite the timer variable, and lose reference to the first timer. So, when you call timer.stop() you actually only stop one timer, while the other keeps running in the background.
You didn't set weak reference attribute here:
timer.addEventListener(TimerEvent.TIMER, showFrame);
so the timer will not be garbage collected if you lose its reference (even if you call System.gc() twice :-)). Check that situation out, and try adding a listener with:
timer.addEventListener(TimerEvent.TIMER, showFrame, false, 0, true);