Move actionscript from external .as to timeline - actionscript-3

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.

Related

TypeError: Error #1006: addEventListener is not a function

New to flash, just trying to complete an assignment.
A simple nav interface with start and end screens. I have that working. the code is simple.
Now I'm trying to insert this tutorial into one of my frames/pages.
at the moment I'm getting the error in the title, but anyway, here is the code.
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.utils.setTimeout;
import flash.utils.getTimer;
public class MathGameFinal extends MovieClip
{
private var buttonsArray:Array = new Array();
private var num1Array:Array = new Array();
private var num2Array:Array = new Array();
private var answersArray:Array = new Array();
private var count:uint = 0;
private var numOfQuestions:uint = 20;
private var numRange:uint = 20;
private var startTime:uint;
private var currentTime:uint;
public function MathGameFinal()
{
// constructor code
buttonsArray = new Array(oneBtn,twoBtn,threeBtn,fourBtn,
fiveBtn,sixBtn,sevenBtn,eightBtn, nineBtn, zeroBtn, clearBtn);
for (var i:uint = 0; i < buttonsArray.length; i++)
{
buttonsArray[i].buttonMode = true;
buttonsArray[i].addEventListener(MouseEvent.CLICK, buttonClicked);
}
mgEnd_Screen.visible = false;
mgStart_Screen.mgStart_Btn.addEventListener(MouseEvent.CLICK, startGame);
}
private function startGame(e:MouseEvent):void{
mgStart_Screen.visible = false;
init();
}
private function init():void {
startTime = getTimer();
currentTime = 0;
for(var j:uint = 0; j < numOfQuestions; j++){
num1Array.push( uint(Math.random() * numRange)+1 );
num2Array.push( uint(Math.random() * numRange)+1 );
answersArray.push( num1Array[j] + num2Array[j] );
}
Input_Txt.text = num1Array[count] + ' + ' + num2Array[count];
}
private function buttonClicked(e:MouseEvent):void{
switch(e.target){
case zeroBtn: Output_Txt.appendText('0'); break;
case oneBtn: Output_Txt.appendText('1'); break;
case twoBtn: Output_Txt.appendText('2'); break;
case threeBtn: Output_Txt.appendText('3'); break;
case fourBtn: Output_Txt.appendText('4'); break;
case fiveBtn: Output_Txt.appendText('5'); break;
case sixBtn: Output_Txt.appendText('6'); break;
case sevenBtn: Output_Txt.appendText('7'); break;
case eightBtn: Output_Txt.appendText('8'); break;
case nineBtn: Output_Txt.appendText('9'); break;
case clearBtn: Output_Txt.text =''; break;
}
setTimeout(checkResult,400);
}
private function checkResult():void{
if(Output_Txt.text == answersArray[count]){
Output_Txt.text = ''};
count++;
Input_Txt.text = num1Array[count] + ' + ' + num2Array[count];
}
}
}

Action Script 3.0 The public attribute can only be used inside a package

The code below are inside a file called Script_1.as
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.*;
import flash.geom.Rectangle;
import flash.media.Sound;
import flash.text.*;
public class Game extends flash.display.MovieClip{
public static const STATE_INIT:int = 10;
public static const STATE_PLAY:int = 20;
public static const STATE_END_GAME:int = 30;
public var gameState:int = 0;
public var score:int = 0;
public var chances:int = 5;
public var bg:MovieClip;
public var enemies:Array;
public var paly:MovieClip;
public var level:Number = 0;
public var scoreLable:TextField = newTextField
public var levelLable:TextField = newTextField
public var chancesLable:TextField = newTextField
public var scoreText:TextField = newTextField
public var levelText:TextField = newTextField
public var chancesText:TextField = newTextField
public const SCOREBOARD_Y:Number = 380
public function Game(){
addEventListener(Event.ENTER_FRAME, gameLoop);
bg = new BackImage();
addChild(bg);
scoreLable.text = "Score:";
levelLable.text = "level:";
chancesLable.text = "Misses:";
scoreText.text = "0";
levelText.text = "1";
chancesText.text = "5";
scoreLable.y = SCOREBOARD_Y;
levelLablel.y = SCOREBOARD_Y;
chancesLabel.y = SCOREBOARD_;
scoreText.y = SCOREBOARD_Y;
levelText.y = SCOREBOARD_Y;
chancesText.y = SCOREBOARD_Y;
scoreLabel.x = 5;
scoreText.x = 50;
chancesLabel.x = 105;
chancesText.x = 155;
levelLabel.x = 205;
levelText.x = 260
addChild(scoreLabel);
addChild(levelLabel);
addChild(chancesLabel);
addChild(scoreText);
addChild(levelText);
addChild(chancesText);
gameState = STATE_INIT;
}
public function gameLoop(e:Event):void{
switch(gameState){
case STATE_INIT:
initGame();
break;
case STATE_PLAY:
playGame();
break;
case STATE_END_GAME:
endGame();
break;
}
//public function initGame():void{
score = 0;
chances = 5;
player = new playerImage();
enemies = newArray();
level = 1;
levelText.text = leveltoString();
addChild(player);
player.startDrag(true,newRectangle(0,0,550,400))
gameState = STATE_PLAY
}
//public function playGame():void{
player.rotation += 15;
makeEnemies();
moveEnemies();
testCollisions();
testForEnd();
}
//public function makeEnemies():void{
var chance:Number = Math.floor(Math.random()*100);
var tempEnemy:MovieClip;
if (chance < 2 + level) {
tempEnemy = new EnemyImage()
tempEnemy.speed = 3 + level;
tempEnemy.gotoAndStop(Math.floor(Math.randome()*5)+1);
tempEnemy.y = 435;
tempEnemy.x = Math.floor(Math.randome()*515)
addChild(tempEnemy);
enemies.push(tempEnemy);
}
}
//public function moveEnemies():void{
/var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
tempEnemy.y -= tempEnemy.speed;
if (tempEnemy.y < -35){
chances -= 1;
chancesText.text = chances.toString();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testCollisions();void {
var sound:Sound = new Pop();
var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
if(tempEnemy.hitTestObject(player)){
score++;
scoreText.text = score.toString();
sound.play();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testForEnd():void{
if(chances == 5){
gameState = STATE_END_GAME;
}else if(score > level*20) {
level++;
levelText.text = level.toString();
}
}
public function endGame():void{
for(var i:int = 0; i< enemies.length; i++) {
removeChild(enemies[i]);
}
enemies = [];
player.stopDrag()
}
}
}
The Error Reports are:
The Public Attribute Can Only Be Used In A Package
(I put // before these Error Lines to mark them. They are not in the original code.)
Syntax error: expecting identifier before var.
Syntax error: expecting rightbrace before semicolon.
(I put / before these Errors. they are on the same line and the / is not in the original code either.)
Try rename your file to Game.as.
try to add a } after your switch case to close the function gameLoop().
PS:
Is it really your code ? Math.randome() ? newTextField ? newArray() ? public function testCollisions();void ? (;void)

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.

How to jump to next frame actionscript 3

I have a memory game here. And each time a card is removed from the gameboard I have "cardCount -2", when this cardCount gets to zero, I want the program to jump to the next frame which is like a "game over" page. I've tried using gotoAndStop(); as well as nextFrame(); but it doesn't seem to be working!
On my frame 1 I have the game, and on frame 2 I have the gameover page.
Any help would be GREATLY appreciated! Thank you!
Here is my code!
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.display.MovieClip;
public class MemoryGame extends Sprite{
private var firstTile:cards;
private var secondTile:cards;
private var pauseTimer:Timer;
private var levelTimer:Timer;
private var score:int;
private var cardCount:int;
var numberDeck:Array = new Array(1,1,2,2,3,3,4,4,5,5,6,6);
public function MemoryGame(){
score = 0;
txtScore.text=": "+score;
for(x=1; x<=4; x++) {
for (y=1; y<=3; y++){
var randomCard = Math.floor(Math.random()*numberDeck.length);
var tile:cards = new cards();
tile.card = numberDeck[randomCard];
numberDeck.splice(randomCard,1);
tile.gotoAndStop(9);
tile.x = (x-1) * 150;
tile.y = (y-1) * 200;
tile.addEventListener(MouseEvent.CLICK,tileClicked);
addChild(tile);
cardCount = cardCount + 1
if (cardCount == 0){
trace("GAME OVER!")
trace("SCORE:" +score);
}
}
}
trace("Cardcount: "+cardCount);
}
public function tileClicked(event:MouseEvent) {
var clicked:cards = (event.currentTarget as cards);
if (firstTile == null){
firstTile = clicked;
firstTile.gotoAndStop(clicked.card);
}
else if (secondTile == null && firstTile != clicked){
secondTile = clicked;
secondTile.gotoAndStop(clicked.card);
if (firstTile.card == secondTile.card){
pauseTimer = new Timer(1000, 1);
pauseTimer.addEventListener(TimerEvent.TIMER_COMPLETE,removeCards);
pauseTimer.start();
}
else {
pauseTimer = new Timer(1000, 1);
pauseTimer.addEventListener(TimerEvent.TIMER_COMPLETE,resetCards);
pauseTimer.start();
}
}
}
public function resetCards(event:TimerEvent) {
firstTile.gotoAndStop(9);
secondTile.gotoAndStop(9);
firstTile = null;
secondTile = null;
pauseTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,resetCards);
score = score - 2;
txtScore.text=": "+score;
}
public function removeCards(event:TimerEvent){
removeChild(firstTile);
removeChild(secondTile);
firstTile = null;
secondTile = null;
pauseTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,removeCards);
score = score + 10;
txtScore.text=": "+score;
cardCount = cardCount - 2;
trace("Cardcount: " + cardCount);
if (cardCount == 0){
//NEXT FRAME CODE HERE!
trace("GAME OVER!")
trace("SCORE:" +score);
}
}
}
}
Try to extend MemoryGame from MovieClip , not from Sprite.
If your frame is on the main timeline, you need to call stage.gotoAndStop(2);.

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.