ActionScript3 : Argument Error on constructor - actionscript-3

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.

Related

Does bitmapdata.copyPixels reduce image quality?

I am using a pair of classes to process and use Sprite Sheets but i have a slight problem, in comparison to the Bitmap class my SpriteSheetClips look very ugly, I scale both, Bitmap and SpriteSheetClip up and down using exactly the same image loaded and they look very different Bitmap looks smooth and nice while my SpriteSheetClips look pixelated with white borders, what is wrong with my classes that is causing this problem?
SpriteSheet (contains the cut bitmapDatas to be used for the clip):
package src {
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.Point;
public class SpriteSheet {
private var frames:Array = new Array();
public function SpriteSheet(spriteSheet:BitmapData, spriteSheetXML:XML)
{
var tileAmount:int = spriteSheetXML.SubTexture.length();
var rect:Rectangle;
var point:Point = new Point(0, 0);
var frame:BitmapData;
for (var a:int = 0; a < tileAmount ; a++)
{
frame = new BitmapData(spriteSheetXML.SubTexture[a].#width, spriteSheetXML.SubTexture[a].#height);
rect = new Rectangle(spriteSheetXML.SubTexture[a].#x, spriteSheetXML.SubTexture[a].#y, spriteSheetXML.SubTexture[a].#width, spriteSheetXML.SubTexture[a].#height);
frame.copyPixels(spriteSheet, rect, point);
frames.push(frame);
}
}
public function getTile(tileNum:int):BitmapData
{
return frames[tileNum-1];
}
public function get length():int
{
return frames.length;
}
}
}
SpriteSheetClip:
package src {
import flash.display.Sprite;
import flash.display.Bitmap;
import flash.events.Event;
public class SpriteSheetClip extends Sprite{
private var spriteSheet:SpriteSheet;
public var frame:Bitmap;
private var _currentFrame:int = 1;
private var _isPlaying:Boolean = true;
public var isLooping:Boolean = true;
private var frames:Array = new Array();
public function SpriteSheetClip(spriteSheetUsed:SpriteSheet)
{
spriteSheet = spriteSheetUsed;
frame = new Bitmap(spriteSheet.getTile(1), "auto", true);
this.addChild(frame);
for (var a:int = 0; a < totalFrames; a++)
{
frames.push({labelName:"", action:""});
}
this.addEventListener(Event.ENTER_FRAME, onFrameLoop, false, 0, true);
}
public function get currentFrame():int
{
return _currentFrame;
}
public function get totalFrames():int
{
return spriteSheet.length;
}
public function get isPlaying():Boolean
{
return _isPlaying;
}
public function start()
{
_isPlaying = true;
}
public function stop()
{
_isPlaying = false;
}
public function addFrameLabel(frameNum:int, labelName:String)
{
if (frameNum == 0)
{
return;
}
frames[frameNum-1].frameLabel = labelName;
}
public function addConnection(frameLabel:*, connectedFrameLabel:*)
{
var frameNum:int = frameNumber(frameLabel);
if (frameNum == 0)
{
return;
}
frames[frameNum-1].action = connectedFrameLabel;
}
private function frameNumber(frameLabel:*):int
{
if (int(frameLabel) <= totalFrames && int(frameLabel) > 0)
{
return int(frameLabel);
}
for (var a:int = 0; a < frames.length; a++)
{
if (frames[a].frameLabel == frameLabel)
{
return (a+1);
}
}
return 0;
}
public function gotoAndStop(frameLabel:*)
{
var frameNum:int = frameNumber(frameLabel);
if (frameNum > 0 && frameNum <= totalFrames)
{
_currentFrame = frameNum;
}
updateFrame();
stop();
}
public function gotoAndPlay(frameLabel:*)
{
var frameNum:int = frameNumber(frameLabel);
if (frameNum > 0 && frameNum <= totalFrames)
{
_currentFrame = frameNum;
}
updateFrame();
start();
}
private function updateFrame()
{
frame.bitmapData = spriteSheet.getTile(currentFrame);
}
public function nextFrame()
{
frame.bitmapData = spriteSheet.getTile(currentFrame);
if (frames[currentFrame-1].action != "")
{
this.gotoAndPlay(frames[currentFrame-1].action);
return;
}
_currentFrame++;
if (currentFrame > totalFrames)
{
if (isLooping)
{
_currentFrame = 1;
}
else
{
_currentFrame = totalFrames;
_isPlaying = false;
}
}
}
private function onFrameLoop(e:Event)
{
if (isPlaying)
{
nextFrame();
}
}
}
}

FLEX - BitmapImage not updated after filters assigned

I've a flex mobile project and a component (as-Class) inside of it with an BitmapImage, a Button and a Graphic sign.
When a boolean is false the button is disabled, the image gets gray through a ColorMatrixFilter (bitmapImage.filters = [myCMFilter]) and the sign appers, else button is enabled, the image has no filters (bitmapImage.filters = []).
The problem is that the image doesn't switch to grey -> but the sign appears and the button gets disabled.
If call the setting of the filters one frame later (callLater -> a function setting the filters) everything works.
I have extracted the code to a sample project and everything works... without callLater
Anyone an idea what can happpen in my case???
Christian
Code:
package de.xxx.yyy.app.view.componentsV2.widgets
{
import de.assets.header.HeaderBGDarkGray;
import de.assets.miscellaneous.StarGrey;
import de.assets.miscellaneous.StarYellow;
import de.assets.miscellaneous.UnderConstruction;
import de.assets.ImageAssets;
import de.xxx.yyy.app.view.componentsV2.buttons.BasicButton;
import de.xxx.yyy.app.view.pools.UserInterfaceComponentsPool;
import flash.debugger.enterDebugger;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.ColorMatrixFilter;
import mx.core.IVisualElement;
import mx.core.UIComponent;
import spark.components.Button;
import spark.components.Group;
import spark.core.SpriteVisualElement;
import spark.primitives.BitmapImage;
public class StadiumWidget extends Group{
private static var STADION_LEVELS:int = 7;
private static var SIDE_SPACING:int = 7;
private static var BUTTON_WIDTH:int = 150;
private static var BUTTON_HEIGHT:int = 33;
////////////////////////////////////////////////////////////////////////////
// USER INTERFACE COMPONENTS
////////////////////////////////////////////////////////////////////////////
private var underConstructionImage:UnderConstruction;
private var currentImage:BitmapImage;
private var footerBackground:HeaderBGDarkGray;
private var developButton:BasicButton;
private var manageButton:BasicButton;
private var displayedlevel:int;
////////////////////////////////////////////////////////////////////////////
// FIELDS
////////////////////////////////////////////////////////////////////////////
private var createdStars:Array = [];
////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////
private var _grayscaleFilter:ColorMatrixFilter;
public function get grayscaleFilter():ColorMatrixFilter
{
if(!_grayscaleFilter)
{
var matrix:Array = [0.3, 0.59, 0.11, 0, 0,
0.3, 0.59, 0.11, 0, 0,
0.3, 0.59, 0.11, 0, 0,
0, 0, 0, 1, 0];
_grayscaleFilter = new ColorMatrixFilter(matrix);
}
return _grayscaleFilter;
}
public function set grayscaleFilter(value:ColorMatrixFilter):void
{
_grayscaleFilter = value;
}
////////////////////////////////////////////////////////////////////////////
// GETTER AND SETTER WITH DIRTY FLAG
////////////////////////////////////////////////////////////////////////////
private var levelChanged:Boolean;
private var _level:int;
public function set level(value:int):void
{
_level = value;
levelChanged = true;
invalidateProperties();
invalidateDisplayList()
}
public function get level():int
{
return _level;
}
//
private var isUnderConstructionChanged:Boolean;
private var _isUnderConstruction:Boolean;
public function set isUnderConstruction(value:Boolean):void
{
_isUnderConstruction = value;
isUnderConstructionChanged = true;
invalidateProperties();
invalidateDisplayList()
}
public function get isUnderConstruction():Boolean
{
return _isUnderConstruction;
}
////////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
////////////////////////////////////////////////////////////////////////////
public function Stadium()
{
super();
}
////////////////////////////////////////////////////////////////////////////
// LIFECYCLE STANDARD METHODS
////////////////////////////////////////////////////////////////////////////
var testSprite:UIComponent;
override protected function createChildren():void
{
super.createChildren();
currentImage = new BitmapImage();
currentImage.smooth = true;
currentImage.percentWidth = 100;
currentImage.scaleMode = "letterbox";
addElement(currentImage);
// FOOTER
footerBackground = new HeaderBGDarkGray();
addElement(footerBackground);
developButton = new BasicButton();
developButton.width = BUTTON_WIDTH;
developButton.height = 38;
developButton.x = SIDE_SPACING;
developButton.label = resourceManager.getString("FlexApp", "stadium.developButtonLabel");
developButton.addEventListener(MouseEvent.CLICK, handleDevelopButtonClicked);
addElement(developButton);
manageButton = new BasicButton();
manageButton.width = BUTTON_WIDTH;
manageButton.height = 38;
manageButton.label = resourceManager.getString("FlexApp", "stadium.manageButtonLabel");
manageButton.addEventListener(MouseEvent.CLICK, handleManageButtonClicked);
addElement(manageButton);
}
override protected function commitProperties():void
{
super.commitProperties();
if(currentImage && levelChanged)
{
setcurrentImage();
setStars();
levelChanged = false;
}
if(isUnderConstructionChanged)
{
setUnderConstruction();
isUnderConstructionChanged = false;
}
}
override protected function measure():void
{
super.measure();
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
var FOOTER_HEIGHT:int = footerBackground.getPreferredBoundsHeight();
var STAR_X_STEP:int = 25;
footerBackground.y = unscaledHeight - FOOTER_HEIGHT;
footerBackground.width = unscaledWidth;
manageButton.x = unscaledWidth - (BUTTON_WIDTH + SIDE_SPACING);
manageButton.y = developButton.y = footerBackground.y + ((FOOTER_HEIGHT - BUTTON_HEIGHT) / 2);
if(currentImage.height > unscaledHeight - footerBackground.height)
{
currentImage.height = unscaledHeight - footerBackground.height;
}
if(underConstructionImage)
{
underConstructionImage.x = (unscaledWidth - underConstructionImage.width) / 2;
}
var starStartX:int = unscaledWidth / 2 - (STADION_LEVELS * STAR_X_STEP) / 2;
var starY:int = createdStars.length > 0 ? unscaledHeight - FOOTER_HEIGHT + (FOOTER_HEIGHT - createdStars[0].height) / 2 : 0;
for(var i:int = 0; i < createdStars.length; i++)
{
createdStars[i].y = starY;
createdStars[i].x = starStartX + i * STAR_X_STEP;
}
}
////////////////////////////////////////////////////////////////////////////
// HELPER METHODS
////////////////////////////////////////////////////////////////////////////
private function setStars():void
{
var pool:UserInterfaceComponentsPool = UserInterfaceComponentsPool.getInstance();
var star:IVisualElement;
while(createdStars.length > 0)
{
star = createdStars.pop() as IVisualElement;
if(containsElement(star))
{
removeElement(star);
}
pool.disposeUserInterfaceComponent(star);
}
// POOL THE STARS!!!
for(var i:int = 1; i <= STADION_LEVELS; i++)
{
if(i <= level)
{
star = pool.getYellowStar();
}
else
{
star = pool.getGreyStar();
}
addElement(star)
createdStars.push(star);
}
}
private function setcurrentImage():void
{
if(level != displayedlevel)
{
currentImage.source = currentImages["LEVEL_" + level + "_NAME"];
displayedlevel = level;
}
setUnderConstruction();
}
private function setUnderConstruction():void
{
developButton.enabled = isUnderConstruction == false;
if(isUnderConstruction)
{
if(!underConstructionImage)
{
underConstructionImage = new UnderConstruction();
underConstructionImage.y = 30;
underConstructionImage.width = 330;
underConstructionImage.height = 330;
addElement(underConstructionImage);
}
callLater(setFilters, [true]);
}
else
{
callLater(setFilters, [false]);
if(underConstructionImage && containsElement(underConstructionImage))
{
removeElement(underConstructionImage);
}
underConstructionImage = null;
}
}
private function setFilters(value:Boolean):void
{
if(value && (!currentImage.filters || currentImage.filters.length == 0))
{
currentImage.filters = [grayscaleFilter];
}
else if(!value && currentImage.filters && currentImage.filters.length > 0)
{
currentImage.filters = [];
}
}
////////////////////////////////////////////////////////////////////////////
// EVENT HANDLER
////////////////////////////////////////////////////////////////////////////
private function handleDevelopButtonClicked(event:MouseEvent):void
{
dispatchEvent(new Event("openlevelPopup", true));
}
private function handleManageButtonClicked(event:MouseEvent):void
{
dispatchEvent(new Event("openManagePopup", true));
}
////////////////////////////////////////////////////////////////////////////
// DISPOSE
////////////////////////////////////////////////////////////////////////////
public function dispose():void
{
developButton.removeEventListener(MouseEvent.CLICK, handleDevelopButtonClicked);
manageButton.removeEventListener(MouseEvent.CLICK, handleManageButtonClicked);
}
}
}

Move actionscript from external .as to timeline

I want to ask how can I make an external script .as can be moved to the timeline??
i dont understand about as3..
plis help me :(
this is the script that i want to move to timeline
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.net.URLRequest;
//import fl.display.ProLoader;
dynamic public class bismillah extends MovieClip
{
public var ba:MovieClip;
public var scorebox:TextField;
public var alif:MovieClip;
public var dal:MovieClip;
public var tong:MovieClip;
public var book:MovieClip;
public var objArray:Array;
public var targetArray:Array;
public var objek:MovieClip;
public var original_x:Number;
public var original_y:Number;
public var score:int;
public var i:int;
public var tombol1:MovieClip;
var singleLoader:Loader = new Loader();
public function bismillah()
{
stop();
addFrameScript(0, frame1);
tombol1 = Object(root).tombol1 as MovieClip;
tombol1.addEventListener(MouseEvent.MOUSE_UP, tes);
return;
}// end function
public function tes(param : MouseEvent) : void
{
var req:URLRequest = new URLRequest("dragdragon.swf");
//singleLoader.unload();
singleLoader.load(req);
addChild(singleLoader);
}
public function down(param1:MouseEvent) : void
{
objek = MovieClip(param1.target);
original_x = objek.x;
original_y = objek.y;
addChild(objek);
objek.startDrag();
stage.addEventListener(MouseEvent.MOUSE_UP, stageUp);
return;
}// end function
public function stageUp(param1:MouseEvent) : void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, stageUp);
objek.stopDrag();
if (objek.dropTarget)
{
if (objek.dropTarget.parent.name == "book")
{
if ((objek == alif) || (objek == ba)){ //yg perlu diganti
objek.x = objek.dropTarget.parent.x;
objek.y = objek.dropTarget.parent.y + 50;
objek.removeEventListener(MouseEvent.MOUSE_DOWN, down);
objek.buttonMode = false;
var _loc_2:Number;
objek.scaleY = 0.4;
objek.scaleX = _loc_2;
objek.alpha = 0.6;
score+=5;
scorebox.text = "Score: " + score;
}
else {
objek.x = objek.dropTarget.parent.x;
objek.y = objek.dropTarget.parent.y + 50;
objek.removeEventListener(MouseEvent.MOUSE_DOWN, down);
objek.buttonMode = false;
var _loc_2:Number;
objek.scaleY = 0.4;
objek.scaleX = _loc_2;
objek.alpha = 0.6;
score-=2;
scorebox.text = "Score: " + score;}
}
else if (objek.dropTarget.parent.name == "tong")
{
if (objek == dal) { //yg perlu diganti
objek.x = objek.dropTarget.parent.x;
objek.y = objek.dropTarget.parent.y + 50;
objek.removeEventListener(MouseEvent.MOUSE_DOWN, down);
objek.buttonMode = false;
var _loc_2:Number;
objek.scaleY = 0.4;
objek.scaleX = _loc_2;
objek.alpha = 0.6;
score+=5;
scorebox.text = "Score: " + score;
}
else {
objek.x = objek.dropTarget.parent.x;
objek.y = objek.dropTarget.parent.y + 50;
objek.removeEventListener(MouseEvent.MOUSE_DOWN, down);
objek.buttonMode = false;
var _loc_2:Number;
objek.scaleY = 0.4;
objek.scaleX = _loc_2;
objek.alpha = 0.6;
score-=2;
scorebox.text = "Score: " + score;
}
}
}
else
{
objek.x = original_x;
objek.y = original_y;
}
return;
}// end function
public function returnToOriginalPosition() : void
{
return;
}// end function
function frame1()
{
objArray = [alif, dal, ba]; //yg perlu diganti
targetArray = [book, tong];
score = 0;
scorebox.text = "Score: " + score;
i = 0;
while (i < objArray.length)
{
objArray[i].buttonMode = true;
objArray[i].addEventListener(MouseEvent.MOUSE_DOWN, down);
i++;
}
return;
}// end function
}
}
Please is it possible someone to help me to move the code to timeline??
Create new MovieClip in the fla library
Select "Export for ActionScript" check box
Enter the name of your as file in the input field "Class"
put the *.as files in the same folder as fla file.
Don't forget to create all nested clips in your new MovieClip - ba, scorebox, etc.

adding a object to another object in as3

Ok so i have a character on the screen and when it moves the camera follows(thanks to manifest222 on youtube) i have a wall where the player cant go through. I also have boxes adding to the stage but i want it so that the box adds to onto another object hers the code.
package {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.display.Stage;
public class Main extends MovieClip {
// player
public var characterEndMC:MovieClip = new charEndMC();
public var arrayOfBarrier:Array = new Array();
//box
private var boxAmount:Number=0;
private var boxLimit:Number=20;
private var _root:Object;
//$txt
public var money:int=0;
public var gold:int=0;
public var my_scrollbar:MakeScrollBar;
//$$
public var testnumber:Number=1;
//enemy1
private var e01Amount:Number=0;
private var e01Limit:Number=2;
public function Main() {
$box.click$.move$.buttonMode=true;
$box.click$.clickmini$.buttonMode=true;
backgroundpic.visible = false;
character_mc["charAngle"]=0;
character_mc["moveX"]=0;
character_mc["moveY"]=0;
character_mc["walkSpeed"]=5;
stage.addEventListener(MouseEvent.CLICK, charMove);
//box add listener
addEventListener(Event.ENTER_FRAME, eFrame);
//moneybox
$box.click$.move$.addEventListener(MouseEvent.MOUSE_DOWN, startmoving$);
$box.click$.move$.addEventListener(MouseEvent.MOUSE_UP, stopmoving$);
$box.click$.clickmini$.addEventListener(MouseEvent.CLICK, c$mini);
my_scrollbar=new MakeScrollBar(scroll_mc,scroll_text);
}
public function charLoop(event:Event) {
if (character_mc.hitTestPoint(character_mc["charEnd"].x,character_mc["charEnd"].y,true)) {
character_mc["moveX"]=0;
character_mc["moveY"]=0;
this.removeChild(character_mc["charEnd"]);
character_mc.removeEventListener(Event.ENTER_FRAME, charLoop);
}
for (var j:int = 0; j < arrayOfBarrier.length; j++) {
if (character_mc.hitTestObject(arrayOfBarrier[j])) {
character_mc.x-=character_mc["moveX"];
character_mc.y-=character_mc["moveY"];
character_mc["moveX"]=0;
character_mc["moveY"]=0;
this.removeChild(character_mc["charEnd"]);
character_mc.removeEventListener(Event.ENTER_FRAME, charLoop);
}
}
for (var i:int = 0; i < this.numChildren; i++) {
this.getChildAt(i).x-=character_mc["moveX"];
this.getChildAt(i).y-=character_mc["moveY"];
}
character_mc.x+=character_mc["moveX"]+.05;
character_mc.y+=character_mc["moveY"]+.05;
}
public function lookAtMouse() {
var characterMC:MovieClip=character_mc;
characterMC["charAngle"] = Math.atan2(this.mouseY - characterMC.y, this.mouseX - characterMC.x) / (Math.PI / 180);
characterMC.rotation=characterMC["charAngle"];
}
public function charMove(event:MouseEvent) {
lookAtMouse();
this.addChild(characterEndMC);
characterEndMC.x=this.mouseX;
characterEndMC.y=this.mouseY;
character_mc["charEnd"]=characterEndMC;
character_mc["charEnd"].visible = false;
character_mc["moveX"]=Math.cos(character_mc["charAngle"]*Math.PI/180)*character_mc["walkSpeed"];
character_mc["moveY"]=Math.sin(character_mc["charAngle"]*Math.PI/180)*character_mc["walkSpeed"];
character_mc.addEventListener(Event.ENTER_FRAME, charLoop);
}
//boxadding
private function eFrame(event:Event):void {
if (boxAmount<boxLimit) {
boxAmount++;
var _box:Box=new Box ;
_box.addEventListener(MouseEvent.CLICK,boxclick);
_box.buttonMode=true;
_box.y=Math.random()* backgroundpic.height;
_box.x=Math.random()* backgroundpic.width;
addChild(_box);
}
if (e01Amount<e01Limit) {
e01Amount++;
var Enemy1: enemy01=new enemy01 ;
Enemy1.addEventListener(MouseEvent.CLICK, en01click);
Enemy1.buttonMode=true;
Enemy1.y=Math.random()*stage.stageHeight;
Enemy1.x=Math.random()*stage.stageWidth;
addChild(Enemy1);
}
}
public function boxclick(event:MouseEvent):void {
var _box:Box=event.currentTarget as Box;
logtxt.appendText("You collected " + testnumber + " boxes" + "\n" );
character_mc["moveX"] = _box.y + 40 + (character_mc.height / 2);
character_mc["moveY"]=_box.x;
logtxt.scrollV=logtxt.maxScrollV;
var randVal$:Number=Math.random();
if (randVal$>=0.49) {
money+=100;
} else if (randVal$ <= 0.50 && randVal$ >= 0.15) {
money+=200;
} else if (randVal$ <= 0.14 && randVal$ >= 0.02) {
gold+=10;
} else if (randVal$ == 0.01) {
money+=200;
gold+=20;
}
testnumber++;
boxAmount--;
$box.box$in.box$insins.Moneytxt.text=String(money);
$box.box$in.box$insins.Goldtxt.text=String(gold);
removeChild(_box);
}
private function startmoving$(event:MouseEvent):void {
$box.startDrag();
}
private function stopmoving$(event:MouseEvent):void {
$box.stopDrag();
}
private function c$mini(event:MouseEvent):void {
$box.click$.move$.visible=false;
$box.box$in.visible=false;
$box.y=200;
$box.x=100;
$box.click$.clickmini$.addEventListener(MouseEvent.CLICK, reclickbox$);
$box.click$.clickmini$.removeEventListener(MouseEvent.CLICK, c$mini);
}
private function reclickbox$(event:MouseEvent):void {
$box.click$.clickmini$.addEventListener(MouseEvent.CLICK, c$mini);
$box.click$.clickmini$.removeEventListener(MouseEvent.CLICK, reclickbox$);
$box.y=70;
$box.x=250;
$box.click$.move$.visible=true;
$box.box$in.visible=true;
}
public function scroll_text( n:Number ) {
logtxt.scrollV = Math.round( ( logtxt.maxScrollV - 1 ) * n ) + 1;
}
public function en01click (event:MouseEvent){
}
}
}
That's:
var _box:Box = new Box();
receivingDisplayObjectInstanceName.addChild(_box);

Stopping a function to run more than once in a period of time

I have this MouseEvent function that I have totally no idea why it fired twice. Is there a way I can disable the function in a period of time? I tried disabling the button, but seems like it directly called the function and does not trigger from the button.
Addition info:When I add in more object to the array, the function fired more time
The Class the handles the button
package classes
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import classes.playVideo;
import classes.playList;
import classes.viewType;
public class controlMenu extends MovieClip
{
private var playV:playVideo=new playVideo();
private var list:playList=new playList();
private var viewT:viewType = new viewType();
private static var con:controls = new controls();
private static var _buttonStatus:Boolean;
public function controlMenu()
{
}
//-------------------------------------------------------------
public function loadControlMenu():void
{
this.addEventListener(Event.ADDED_TO_STAGE,add2Stage);
}
private function add2Stage(e:Event):void
{
if (stage.numChildren == 1)
{
con.x=(stage.stageWidth-230)/2;
con.y=stage.stageHeight-(con.height+9);
addChild(con);
playButtonStatus();
con.soundBtn.addEventListener(MouseEvent.MOUSE_OVER, soundOver);
con.soundBtn.addEventListener(MouseEvent.MOUSE_OUT, soundOut);
con.soundBtn.addEventListener(MouseEvent.MOUSE_DOWN, soundDown);
stage.addEventListener(MouseEvent.MOUSE_UP, soundUp);
con.prev.addEventListener(MouseEvent.CLICK,prevClick);
con.next.addEventListener(MouseEvent.CLICK,nextClick);
}
}
private function playClick(e:MouseEvent):void
{
if (e.currentTarget.currentFrameLabel == "play" && playV.currentVideoStatus == "play")
{
e.currentTarget.gotoAndStop("pause");
playV.pauseStatus();
}
else if (e.currentTarget.currentFrameLabel=="pause" && playV.currentVideoStatus == "pause")
{
e.currentTarget.gotoAndStop("play");
playV.playStatus();
}
else if (e.currentTarget.currentFrameLabel == "play"&& playV.currentVideoStatus == "end")
{
playV.newVideo = "video/video" + list.currentIndex + ".flv";
}
}
private function playOver(e:MouseEvent):void
{
e.currentTarget.btn.gotoAndStop("over");
}
private function playOut(e:MouseEvent):void
{
e.currentTarget.btn.gotoAndStop("out");
}
//-------------------------------------------------------------
private function soundOver(e:MouseEvent):void
{
e.currentTarget.gotoAndStop("over");
}
private function soundOut(e:MouseEvent):void
{
if (e.buttonDown == false)
{
e.currentTarget.gotoAndStop("out");
}
}
private function soundDown(e:MouseEvent):void
{
var volumeBound:Rectangle = new Rectangle(-93,35,80,0);
e.currentTarget.startDrag(false, volumeBound);
stage.addEventListener(MouseEvent.MOUSE_MOVE,soundAdjust);
}
private function soundUp(e:MouseEvent):void
{
con.soundBtn.stopDrag();
con.soundBtn.gotoAndStop("out");
stage.removeEventListener(MouseEvent.MOUSE_MOVE,soundAdjust);
}
private function soundAdjust(e:MouseEvent):void
{
playV.adjustSound = ((con.soundBtn.x+93)*100)/80;
}
public function set adjustSoundBtnPos(a:Number):void
{
var newPos:Number = ((80*a)/100);
con.soundBtn.x = newPos - 93;
}
private function prevClick(e:MouseEvent):void
{
if (viewT.viewIn == "stream" && list.currentIndex > 1)
{
var goBack = list.currentIndex - 1;
list.currentIndex = goBack;
playV.newVideo = "video/video" + goBack + ".flv";
list.currentVideoLink = goBack;
}
}
private function nextClick(e:MouseEvent):void
{
if (viewT.viewIn == "stream" && list.currentIndex < list.vDataLength)
{
var goNext = list.currentIndex + 1;
list.currentIndex = goNext;
playV.newVideo = "video/video" + goNext + ".flv";
list.currentVideoLink = goNext;
}
}
//-------------------------------------------------------------
public function get currentStatus():String
{
return con.playBtn.currentFrameLabel;
}
public function resetPlayStatus():void
{
con.playBtn.gotoAndStop("play");
}
//-------------------------------------------------------------
public function set buttonStatus(s:Boolean):void
{
_buttonStatus = s;
playButtonStatus();
}
public function playButtonStatus():void
{
if (_buttonStatus == true)
{
con.playBtn.buttonMode = true;
con.playBtn.addEventListener(MouseEvent.CLICK, playClick);
con.playBtn.addEventListener(MouseEvent.MOUSE_OVER, playOver);
con.playBtn.addEventListener(MouseEvent.MOUSE_OUT, playOut);
con.soundBtn.buttonMode = true;
con.soundBtn.mouseEnabled = true;
}
else
{
con.playBtn.buttonMode = false;
con.playBtn.removeEventListener(MouseEvent.CLICK, playClick);
con.playBtn.removeEventListener(MouseEvent.MOUSE_OVER, playOver);
con.playBtn.removeEventListener(MouseEvent.MOUSE_OUT, playOut);
con.soundBtn.buttonMode = false;
con.soundBtn.mouseEnabled = false;
}
}
}
}
The Class that cause the extra loop on mouseevent function
package classes
{
import flash.media.Video;
import flash.display.MovieClip;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.events.AsyncErrorEvent;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.utils.Timer;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.media.SoundTransform;
import flash.media.SoundMixer;
import flash.net.URLLoader;
import flash.net.URLRequest;
import classes.Playing;
import classes.progressBar;
import classes.controlMenu;
import classes.viewType;
import classes.downloadVideo;
import classes.playList;
import classes.playVideo;
public class playVideo extends MovieClip
{
private var Play:Playing = new Playing();
private var progressB:progressBar = new progressBar();
private var conM:controlMenu;
private var viewT:viewType=new viewType();
private var downloadV:downloadVideo;
private var list:playList;
private var vBox:MovieClip = new MovieClip();
private var nc:NetConnection;
private static var ns:NetStream;
private const buffer:Number = 2;
private static var videoURL:String;
private static var vid:Video = new Video();
private static var meta:Object = new Object();
private var durationSecs:Number;
private var durationMins:Number;
private var durSecsDisplay:String;
private var durMinsDisplay:String;
private static var videoDuration:String;
private static var t:Timer = new Timer(100);
private static var videoSound:SoundTransform = new SoundTransform();
private var arial:Arial = new Arial();
private static var durationTxt:TextField=new TextField();
private var durationTxtF:TextFormat=new TextFormat();
private var scrubForward:Boolean;
private static var currentStatus;
private static var nsArray:Array= new Array();
private var dummyArray:Array = new Array();
//--------------------------------------------------------------------------
private var videoLoader:URLLoader;
public function playVideo()
{
}
public function set newVideo(v:String):void
{
currentStatus = "play";
videoURL = v;
if (viewT.viewIn == "stream")
{
addVideo();
}
else if (viewT.viewIn=="download")
{
for (var i:uint=0; i<nsArray.length; i++)
{
if (nsArray[i] != null)
{
nsArray[i].close();
}
}
videoProperties();
soundF();
}
conM.resetPlayStatus();
}
public function videoFunction():void
{
vBox.graphics.beginFill(0x000000);
vBox.graphics.drawRect(0,36,668,410);
vBox.graphics.endFill();
addChild(vBox);
// Add the instance of vid to the stage
vid.width = vid.width * 2;
vid.height = vid.height * 1.5;
vid.x = vBox.width / 2 - vid.width / 2;
vid.y = vBox.height / 2 - vid.height / 2 + 36;
vBox.addChild(vid);
if (viewT.viewIn == "stream")
{
videoProperties();
}
soundF();
durationText();
}
public function videoProperties():void
{
nc=new NetConnection();
// Assign variable name for Net Connection
nc.connect(null);
// Assign Var for the NetStream Object using NetConnection
ns = new NetStream(nc);
// Add the buffer time to the video Net Stream
ns.bufferTime = buffer;
// Set client for Meta Data Function
ns.client = {};
ns.client.onMetaData = onMetaData;
// Attach netStream to our new Video Object
if (viewT.viewIn == "stream")
{
vid.attachNetStream(ns);
}
else if (viewT.viewIn == "download")
{
nsArray[list.currentIndex - 1] = ns;
dummyArray.push(ns);
vid.attachNetStream(ns);
}
addVideo();
}
private function addVideo():void
{
// Assign NetStream to start play automatically by default
if (viewT.viewIn == "stream" && videoURL == null)
{
videoURL = "video/video1.flv";
}
ns.play(videoURL);
conM= new controlMenu();
conM.buttonStatus = true;
progressB.progressBarStatus();
// Add Error listener and listeners for all of our buttons
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR,asyncErrorHandler);
currentStatus = "play";
t.addEventListener(TimerEvent.TIMER,onTick);
t.start();
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
// Do whatever you want if an error arises
}
private function onMetaData(info:Object):void
{
meta = info;
/*for (meta in info)
{
trace(meta + ":" + info[meta]);
}*/
durationSecs = Math.floor(meta.duration);
durationMins = Math.floor(durationSecs / 60);
durationMins %= 60;
durationSecs %= 60;
if (durationMins < 10)
{
durMinsDisplay = "0" + durationMins;
}
else
{
durMinsDisplay = "" + durationMins;
}
if (durationSecs < 10)
{
durSecsDisplay = "0" + durationSecs;
}
else
{
durSecsDisplay = "" + durationSecs;
}
videoDuration = durMinsDisplay + ":" + durSecsDisplay;
Play.vDuration = videoDuration;
}
//--------------------------------------------------------------------------
public function prepareArray():void
{
list = new playList();
for (var i:uint=0; i<list.vDataLength; i++)
{
nsArray.push(null);
}
}
//--------------------------------------------------------------------------
private function onTick(event:TimerEvent):void
{
if (viewT.viewIn == "stream" || ns.bytesLoaded == ns.bytesTotal)
{
var nsSecs:Number = Math.floor(ns.time);
var nsMins:Number = Math.floor(nsSecs / 60);
nsMins %= 60;
nsSecs %= 60;
var nsSecsDisplay:String = "";
var nsMinsDisplay:String = "";
if (nsMins < 10)
{
nsMinsDisplay = "0" + nsMins;
}
else
{
nsMinsDisplay = "" + nsMins;
}
if (nsSecs < 10)
{
nsSecsDisplay = "0" + nsSecs;
}
else
{
nsSecsDisplay = "" + nsSecs;
}
durationTxt.text = nsMinsDisplay + ":" + nsSecsDisplay;
progressB.progressing = ns.time / meta.duration * 668;
}
else if (viewT.viewIn=="download" && ns.bytesLoaded!=ns.bytesTotal)
{
list.preloadFlv();
}
if (durationTxt.text == videoDuration)
{
currentStatus = "end";
t.stop();
t.removeEventListener(TimerEvent.TIMER,onTick);
ns.pause();
ns.seek(0);
}
}
//--------------------------------------------------------------------------
private function soundF():void
{
var soundAmount:Number = 7;
if (viewT.viewIn == "stream")
{
ns.soundTransform = videoSound;
videoSound.volume = soundAmount / 10;
conM.adjustSoundBtnPos = soundAmount * 10;
}
else if (viewT.viewIn=="download")
{
if (dummyArray.length == 1 && ns != null)
{
ns.soundTransform = videoSound;
videoSound.volume = soundAmount / 10;
conM.adjustSoundBtnPos = soundAmount * 10;
}
else if (dummyArray.length> 1 && ns!=null)
{
ns.soundTransform = videoSound;
}
}
}
public function set adjustSound(s:Number):void
{
videoSound.volume = s / 100;
ns.soundTransform = videoSound;
}
//--------------------------------------------------------------------------
private function durationText():void
{
durationTxtF = new TextFormat();
durationTxtF.size = 12;
durationTxtF.leftMargin = 5;
durationTxtF.font = arial.fontName;
durationTxt.defaultTextFormat = durationTxtF;
durationTxt.selectable = false;
durationTxt.textColor = 0x999999;
durationTxt.width = 50;
durationTxt.height = 22;
durationTxt.x = 476;
durationTxt.y = 477;
durationTxt.text = "00:00";
addChild(durationTxt);
}
//--------------------------------------------------------------------------
public function get Duration():String
{
return videoDuration;
}
public function playStatus():void
{
conM=new controlMenu();
if (conM.currentStatus == "play")
{
ns.resume();
updateProgress();
}
if (currentStatus == "pause")
{
currentStatus = "play";
t.start();
}
}
public function pauseStatus():void
{
ns.pause();
t.stop();
trace("pause");
if (currentStatus == "play")
{
currentStatus = "pause";
}
}
public function get currentVideoStatus():String
{
return currentStatus;
}
public function restartVideo():void
{
ns.resume();
}
//--------------------------------------------------------------------------
public function updateProgress():void
{
ns.seek((progressB.currentProgress / 668) *meta.duration);
}
public function get nsBytesTotal():Number
{
return ns.bytesTotal;
}
public function get nsBytesLoaded():Number
{
return ns.bytesLoaded;
}
public function get getVideoURL():String
{
return videoURL;
}
}
}
I strongly, strongly recommend against doing some sort of flag or timer hack to get around an unexplained behavior - that leads to code bloat and down the line it'll cause you more problems in the long run.
It's much, much, much better to understand why it's calling your function twice. Invest the time in figuring that out (do you have listeners set on multiple display objects? Is this some sort of bubbling issue? Could it be your mouse? Try a clean flash project with just a handler and see if that calls twice, etc), and not only will your code be better and faster but you'll also learn a lot in the process.
You could make a variable so it only runs once. Something like...
var runOnce:Boolean = false;
button.addEventListener(MouseEvent.CLICK, testEvent);
function testEvent(e:Event):void{
if(runOnce == false){
//do stuff here
runOnce = true;
}
It's a bit lazy, but you get the idea.