Create an XML file from a script AS3 - actionscript-3

I can not figure out how I get more XML file from the language images,
In the image here you will look at setupItems how it is built
Here it explains how I build the missing XML file but I do not understand how I build it properly that will work for me on the site
public function init(param1:int) : void
{
var _loc2_:String = null;
this.itemHolder.addChild(this.hairHolder);
this.itemHolder.addChild(this.shirtHolder);
this.shirtHolder.visible = false;
this.itemHolder.addChild(this.pantsHolder);
this.pantsHolder.visible = false;
this.itemHolder.addChild(this.shoesHolder);
this.shoesHolder.visible = false;
this.activeHolder = this.hairHolder;
this.initButtons();
this.randomTimer = new Timer(this.randomTimerInitDelay,this.randomTimerCount);
this.randomTimer.addEventListener(TimerEvent.TIMER,this.changeRandomClothes,false,0,true);
this.xml = new XML();
if(param1 == 1)
{
_loc2_ = "boyItems.xml";
}
else if(param1 == 2)
{
_loc2_ = "girlItems.xml";
}
this.xmlLoader = new URLLoader(new URLRequest("./website/common/register/xmls/" + _loc2_));
this.xmlLoader.addEventListener(Event.COMPLETE,this.xmlLoaded);
this.xmlLoader.addEventListener(IOErrorEvent.IO_ERROR,this.errorLoadingXml);
}
another code
private function xmlLoaded(param1:Event) : void
{
this.xmlLoader.removeEventListener(Event.COMPLETE,this.xmlLoaded);
this.xmlLoader.removeEventListener(IOErrorEvent.IO_ERROR,this.errorLoadingXml);
this.xml = XML(this.xmlLoader.data);
Register.AVATAR_HAIR = this.xml.hair.child(0).#id;
var _loc2_:int = Math.random() * 2 + 1;
this.bubble.gotoAndStop("hair_" + Register.language + _loc2_);
this.setupItems(this.xml.hair,this.hairItems,this.hairHolder);
this.setupItems(this.xml.shirt,this.shirtItems,this.shirtHolder);
this.setupItems(this.xml.pants,this.pantsItems,this.pantsHolder);
this.setupItems(this.xml.shoes,this.shoesItems,this.shoesHolder);}
private function setupItems(param1:*, param2:Array, param3:Sprite) : void
{
var _loc9_:* = undefined;
var _loc10_:Item = null;
var _loc4_:int = 54.5;
var _loc5_:Number = 64.5;
var _loc6_:*;
var _loc7_:int = (_loc6_ = param1).children().length();
var _loc8_:int = 0;
while(_loc8_ < _loc7_)
{
_loc9_ = _loc6_.child(_loc8_);
(_loc10_ = new Item()).x = _loc4_;
_loc4_ += this.itemSpacing;
_loc10_.y = _loc5_;
_loc10_.loadItem(_loc9_.#type,_loc9_.#ordinal,_loc9_.#id,_loc9_.#inventoryType,Register.pathToItemsFolder);
param2.push(_loc10_);
param3.addChild(_loc10_);
_loc8_++;
}
}
This is the loadItem file:
(Maybe here you can see how I build the XML files)
public function loadItem(param1:int, param2:int, param3:int, param4:int, param5:String) : void
{
this.type = param1;
this.ordinal = param2;
this.id = param3;
this.itemImage = new ImageItemNoCache(param1,param2,param3,param4,null,null,param5);
this.itemImage.mouseEnabled = false;
this.itemImage.mouseChildren = false;
this.itemImage.addEventListener(ImageItem.DATA_LOADED,this.positionImage,false,0,true);
addChild(this.itemImage);
addEventListener(MouseEvent.CLICK,this.clickedMe,false,0,true);
}
Code for ImageItemNoCache:
public class ImageItemNoCache extends ImageItem
{
private var textData:Object;
private var itemData:Object;
private var pathToItemsFolder:String;
public function ImageItemNoCache(param1:int, param2:int, param3:int, param4:int, param5:Object = null, param6:Object = null, param7:String = ".")
{
this.textData = param5;
this.itemData = param6;
this.pathToItemsFolder = param7;
super(param1,param2,param3,param4);
}
override protected function getImageItemData(param1:int, param2:int = -1, param3:int = -1, param4:int = -1) : ImageItemData
{
return new ImageItemDataNoCache(param1,param2,param3,param4,this.textData,this.itemData,this.pathToItemsFolder);
}
override public function clone() : DisplayItem
{
return new ImageItemNoCache(getType(),getOrdinal(),getId(),getInventoryType(),this.textData,this.itemData,this.pathToItemsFolder);
}
}

Related

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.

Multiple arrays, private static function

I have an array list which is connected with a private static function and would like to make another array list on a different view (Flex builder, Action script) so I copied the private static function edited the name and the "Select" parts but I get an error saying:
"1061: call to a possibly undefined method members through a reference with static type class."
Here is the code of the AS:
package model
{
import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.events.SQLEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import model.Dish;
import mx.collections.ArrayCollection;
public class SQLiteDatabase
{
private static var _sqlConnection:SQLConnection;
public static function get sqlConnection():SQLConnection
{
if (_sqlConnection)
return _sqlConnection;
openDatabase(File.desktopDirectory.resolvePath("test.db"));
return _sqlConnection;
}
public function getNote(id:int):Dish
{
var sql:String = "SELECT id, title, time, message FROM notes WHERE id=?";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = id;
stmt.execute();
var result:Array = stmt.getResult().data;
if (result && result.length == 1)
return processRow(result[0]);
else
return null;
}
public function getmember(id:int):Dish
{
var sql:String = "SELECT id, title, time, message FROM notes WHERE id=?";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = id;
stmt.execute();
var result:Array = stmt.getResult().data;
if (result && result.length == 1)
return processRow(result[0]);
else
return null;
}
public function getMYBlist(id:int):Dish
{
var sql:String = "SELECT id, title, time, message FROM notes WHERE id=?";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = id;
stmt.execute();
var result:Array = stmt.getResult().data;
if (result && result.length == 1)
return processRow(result[0]);
else
return null;
}
public static function notes():ArrayCollection
{
var noteList:ArrayCollection = new ArrayCollection();
var sql:String = "SELECT id, title, time, message FROM notes";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
var sqlResult:SQLResult = stmt.getResult();
if (sqlResult) {
var result:Array = sqlResult.data;
if (result) {
for (var index:Number = 0; index < result.length; index++) {
noteList.addItem(processRow(result[index]));
}
}
}
return noteList;
}
public static function members():ArrayCollection
{
var memberslist:ArrayCollection = new ArrayCollection();
var sql:String = "SELECT id, name FROM members";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
var sqlResult:SQLResult = stmt.getResult();
if (sqlResult) {
var result:Array = sqlResult.data;
if (result) {
for (var index:Number = 0; index < result.length; index++) {
memberslist.addItem(processRow(result[index]));
}
}
}
return memberslist;
}
public static function addNote(note:Dish):void
{
var sql:String =
"INSERT INTO notes (title, time, message) " +
"VALUES (?,?,?)";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = note.title;
stmt.parameters[1] = note.time;
stmt.parameters[2] = note.message;
stmt.execute();
}
public static function addMember(note:Dish):void
{
var sql:String =
"INSERT INTO notes (title, time, message) " +
"VALUES (?,?,?)";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = note.title;
stmt.parameters[1] = note.time;
stmt.parameters[2] = note.message;
stmt.execute();
}
public static function deleteNote(note:Dish):void
{
var sql:String = "DELETE FROM notes WHERE id=?";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = note.id;
stmt.execute();
}
public static function updateNote(note:Dish):void
{
var sql:String = "UPDATE notes SET title=?, time=?, message=? WHERE id=?";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = note.title;
stmt.parameters[1] = note.time;
stmt.parameters[2] = note.message;
stmt.parameters[3] = note.id;
stmt.execute();
}
protected static function processRow(o:Object):Dish
{
var note:Dish = new Dish();
note.id = o.id;
note.title = o.title == null ? "" : o.title;
note.time = o.time == null ? "" :o.time;
note.message = o.message == null ? "" : o.message;
return note;
}
public static function openDatabase(file:File):void
{
var newDB:Boolean = true;
if (file.exists)
newDB = false;
_sqlConnection = new SQLConnection();
_sqlConnection.open(file);
if (newDB)
{
createDatabase();
populateDatabase();
}
}
protected static function createDatabase():void
{
var sql:String =
"CREATE TABLE IF NOT EXISTS notes ( "+
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title VARCHAR(50), " +
"time VARCHAR(50), " +
"message VARCHAR(200))";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
}
protected static function populateDatabase():void
{
var file:File = File.applicationDirectory.resolvePath("assets/notes.xml");
if (!file.exists) return;
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ);
var xml:XML = XML(stream.readUTFBytes(stream.bytesAvailable));
stream.close();
for each (var n:XML in xml.note)
{
var note:Dish = new Dish();
note.id = n.id;
note.title = n.title;
note.time = n.time;
note.message = n.message;
addNote(note);
}
}
}
}
and the code of the MXML file:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="Profile">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import model.Dish;
import model.SQLiteDatabase;
import spark.events.IndexChangeEvent;
protected function onNote2Selected(event:IndexChangeEvent):void {
var selectedNote:Dish = event.currentTarget.dataProvider[event.newIndex];
navigator.pushView(MemberDetailsView, selectedNote);
}
protected function onAddButtonClicked(event:MouseEvent):void {
navigator.pushView(AddMemberView);
}
]]>
</fx:Script>
<s:VGroup gap="-1">
</s:VGroup>
**<s:List dataProvider="{SQLiteDatabase.members()}" change="onNoteSelected(event)"**
left="0" right="0" top="0" bottom="0">
<s:itemRenderer>
<fx:Component>
<s:IconItemRenderer labelField="title" messageField="message"/>
</fx:Component>
</s:itemRenderer>
</s:List>
</s:View>
The error is because you are accessing a static method to a non-static class. The meaning is that the instance has not been created yet, so while the linker should be able to locate the static member function, there is no way to resolve which instance of the object. If you declare the class static, it should solve this problem.
public static function notes():ArrayCollection
{
var noteList:ArrayCollection = new ArrayCollection();
var sql:String = "SELECT id, title, time, message FROM notes";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
var sqlResult:SQLResult = stmt.getResult();
if (sqlResult) {
var result:Array = sqlResult.data;
if (result) {
for (var index:Number = 0; index < result.length; index++) {
noteList.addItem(processRow(result[index]));
}
}
}
return noteList;
}
public static function members():ArrayCollection
{
var noteList:ArrayCollection = new ArrayCollection();
var sql:String = "SELECT testid, Dish_Name FROM DishInventory";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
var sqlResult:SQLResult = stmt.getResult();
if (sqlResult) {
var result:Array = sqlResult.data;
if (result) {
for (var index:Number = 0; index < result.length; index++) {
noteList.addItem(processRow2(result[index]));
}
}
}
return noteList;
}
protected static function processRow(o:Object):Dish
{
var note:Dish = new Dish();
note.id = o.id;
note.title = o.title == null ? "" : o.title;
note.time = o.time == null ? "" :o.time;
note.message = o.message == null ? "" : o.message;
return note;
}
protected static function processRow2(o:Object):Dish
{
var note:Dish = new Dish();
note.id = o.testID;
note.title = o.Dish_Name == null ? "" : o.Dish_Name;
return note;
}
Still got to clean my coding though
The solution is:
private function sqlResult(res:SQLEvent):void {
var sqlResult:SQLResult = stmt.getResult();
if (sqlResult) {
var data:Array = sqlResult.data;
contactList = new ArrayCollection();
for each(var item:Object in data){
contact = new Contact(item);
contactList.addItem(contact);
}
}
}

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.

How to skew a Textfield in Actionscript 3.0?

How can I skew a Textfield in order to set a ascending space for each line.
Following image should illustrate my intention:
Got it:
adobe
public class TextBlock_createTextLineExample extends Sprite {
public function TextBlock_createTextLineExample():void {
var str:String = "I am a TextElement, created from a String and assigned " +
"to the content property of a TextBlock. The createTextLine() method " +
"then created these lines, 300 pixels wide, for display." ;
var fontDescription:FontDescription = new FontDescription("Arial");
var format:ElementFormat = new ElementFormat(fontDescription);
format.fontSize = 16;
var textElement:TextElement = new TextElement(str, format);
var textBlock:TextBlock = new TextBlock();
textBlock.content = textElement;
createLines(textBlock);
}
private function createLines(textBlock:TextBlock):void
{
var lineWidth:Number = 300;
var xPos:Number = 15.0;
var yPos:Number = 20.0;
var textLine:TextLine = textBlock.createTextLine (null, lineWidth);
while (textLine)
{
//increase textLine every Line 10 px to get an offset
textLine.x += 10
textLine.y = yPos;
yPos += textLine.height + 2;
addChild (textLine);
textLine = textBlock.createTextLine (textLine, lineWidth);
}
}
}
}
private static const _DEG2RAD:Number = Math.PI/180;
public static function skew(target:DisplayObject, skewXDegree:Number, skewYDegree:Number):void
{
var m:Matrix = target.transform.matrix.clone();
m.b = Math.tan(skewYDegree*_DEG2RAD);
m.c = Math.tan(skewXDegree*_DEG2RAD);
target.transform.matrix = m;
}
public static function skewY(target:DisplayObject, skewDegree:Number):void
{
var m:Matrix = target.transform.matrix.clone();
m.b = Math.tan(skewDegree*_DEG2RAD);
target.transform.matrix = m;
}
public static function skewX(target:DisplayObject, skewDegree:Number):void
{
var m:Matrix = target.transform.matrix.clone();
m.c = Math.tan(skewDegree*_DEG2RAD);
target.transform.matrix = m;
}

doubt regarding carrying data in custom events using actionscript

I am working on actionscript to generate a SWF dynamically using JSON data coming from an HTTP request. I receive the data on creationComplete and try to generate a tree like structure. I don’t create the whole tree at the same time. I create 2 levels, level 1 and level 2. My goal is to attach custom events on the panels which represent tree nodes. When users click the panels, it dispatches custom events and try to generate the next level. So, it goes like this :
On creation complete -> get JSON-> create top tow levels -> click on level 2-> create the level 2 and level 3 -> click on level 3-> create level 3 and 4. …and so on and so on. I am attaching my code with this email. Please take a look at it and if you have any hints on how you would do this if you need to paint a tree having total level number = “n” where n = 0 to 100
Should I carry the data around in CustomPageClickEvent class.
[code]
import com.iwobanas.effects.*;
import flash.events.MouseEvent;
import flash.filters.BitmapFilterQuality;
import flash.filters.BitmapFilterType;
import flash.filters.GradientGlowFilter;
import mx.controls.Alert;
private var roundedMask:Sprite;
private var panel:NewPanel;
public var oldPanelIds:Array = new Array();
public var pages:Array = new Array();
public var delPages:Array = new Array();
public function DrawPlaybook(pos:Number,title:String,chld:Object):void {
panel = new NewPanel(chld);
panel.title = title;
panel.name=title;
panel.width = 100;
panel.height = 80;
panel.x=pos+5;
panel.y=40;
var gradientGlow:GradientGlowFilter = new GradientGlowFilter();
gradientGlow.distance = 0;
gradientGlow.angle = 45;
gradientGlow.colors = [0xFFFFF0, 0xFFFFFF];
gradientGlow.alphas = [0, 1];
gradientGlow.ratios = [0, 255];
gradientGlow.blurX = 10;
gradientGlow.blurY = 10;
gradientGlow.strength = 2;
gradientGlow.quality = BitmapFilterQuality.HIGH;
gradientGlow.type = BitmapFilterType.OUTER;
panel.filters =[gradientGlow];
this.rawChildren.addChild(panel);
pages.push(panel);
panel.addEventListener(MouseEvent.CLICK,
function(e:MouseEvent){onClickHandler(e,title,chld)});
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED,
function(e:CustomPageClickEvent){onCustomPanelClicked(e,title)});
}
public function onClickHandler(e:MouseEvent,title:String,chld:Object):void {
for each(var stp1:NewPanel in pages){
if(stp1.title==title){
var eventObj:CustomPageClickEvent = new CustomPageClickEvent("panelClicked");
eventObj.panelClicked = stp1;
dispatchEvent(eventObj);
}
}
}
private function onCustomPanelClicked(e:CustomPageClickEvent,title:String):void {
Alert.show("onCustomPanelClicked" + title);
var panel:NewPanel;
for each(var stp:NewPanel in pages){
startAnimation(e,stp);
}
if(title == e.panelClicked.title){
panel = new NewPanel(null);
panel.title = title;
panel.name=title;
panel.width = 150;
panel.height = 80;
panel.x=100;
panel.y=40;
this.rawChildren.addChild(panel);
var slideRight:SlideRight = new SlideRight();
slideRight.target=panel;
slideRight.duration=750;
slideRight.showTarget=true;
slideRight.play();
var jsonData = this.map.getValue(title);
var posX:Number = 50;
var posY:Number = 175;
for each ( var pnl:NewPanel in pages){
pages.pop();
}
for each ( var stp1:Object in jsonData.children){
panel = new NewPanel(null);
panel.title = stp1.text;
panel.name=stp1.id;
panel.width = 100;
panel.id=stp1.id;
panel.height = 80;
panel.x = posX;
panel.y=posY;
posX+=150;
var s:String="hi" + stp1.text;
panel.addEventListener(MouseEvent.CLICK,
function(e:MouseEvent){onChildClick(e,s);});
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED,
function(e:CustomPageClickEvent){onCustomPnlClicked(e)});
this.rawChildren.addChild(panel);
pages.push(panel);
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED,
function(e:CustomPageClickEvent){onCustomPanelClicked(e,title)});
var slide:SlideUp = new SlideUp();
slide.target=panel;
slide.duration=1500;
slide.showTarget=false;
slide.play();
}
}
}
public function onChildClick(e:MouseEvent,s:String):void {
for each(var stp1:NewPanel in pages){
if(stp1.title==e.currentTarget.title){
var eventObj:CustomPageClickEvent = new CustomPageClickEvent("panelClicked");
eventObj.panelClicked = stp1;
dispatchEvent(eventObj);
}
}
}
private function onCustomPnlClicked(e:CustomPageClickEvent):void {
for each ( var pnl:NewPanel in pages){
pages.pop();
}
}
private function fadePanel(event:Event,panel:NewPanel):void{
panel.alpha -= .005;
if (panel.alpha <= 0){
panel.removeEventListener(Event.ENTER_FRAME,
function(e:Event){fadePanel(e,panel);});
};
panel.title="";
}
private function startAnimation(event:CustomPageClickEvent,panel:NewPanel):void{
panel.addEventListener(Event.ENTER_FRAME,
function(e:Event){fadePanel(e,panel)});
}
[/code]
Thanks in advance.
Palash
completely forgot i don't have enough rep to edit...
import com.iwobanas.effects.*;
import flash.events.MouseEvent;
import flash.filters.BitmapFilterQuality;
import flash.filters.BitmapFilterType;
import flash.filters.GradientGlowFilter;
import mx.controls.Alert;
private var roundedMask:Sprite;
private var panel:NewPanel;
public var oldPanelIds:Array = new Array();
public var pages:Array = new Array();
public var delPages:Array = new Array();
public function DrawPlaybook(pos:Number,title:String,chld:Object):void {
panel = new NewPanel(chld);
panel.title = title;
panel.name=title;
panel.width = 100;
panel.height = 80;
panel.x=pos+5;
panel.y=40;
var gradientGlow:GradientGlowFilter = new GradientGlowFilter();
gradientGlow.distance = 0;
gradientGlow.angle = 45;
gradientGlow.colors = [0xFFFFF0, 0xFFFFFF];
gradientGlow.alphas = [0, 1];
gradientGlow.ratios = [0, 255];
gradientGlow.blurX = 10;
gradientGlow.blurY = 10;
gradientGlow.strength = 2;
gradientGlow.quality = BitmapFilterQuality.HIGH;
gradientGlow.type = BitmapFilterType.OUTER;
panel.filters = [gradientGlow];
this.rawChildren.addChild(panel);
pages.push(panel);
panel.addEventListener(MouseEvent.CLICK, function(e:MouseEvent){onClickHandler(e,title,chld)});
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED, function(e:CustomPageClickEvent){onCustomPanelClicked(e,title)});
}
public function onClickHandler(e:MouseEvent,title:String,chld:Object):void {
for each(var stp1:NewPanel in pages){
if(stp1.title==title){
var eventObj:CustomPageClickEvent = new CustomPageClickEvent("panelClicked");
eventObj.panelClicked = stp1;
dispatchEvent(eventObj);
}
}
}
private function onCustomPanelClicked(e:CustomPageClickEvent,title:String):void {
Alert.show("onCustomPanelClicked" + title);
var panel:NewPanel;
for each(var stp:NewPanel in pages){
startAnimation(e,stp);
}
if(title == e.panelClicked.title){
panel = new NewPanel(null);
panel.title = title;
panel.name=title;
panel.width = 150;
panel.height = 80;
panel.x=100;
panel.y=40;
this.rawChildren.addChild(panel);
var slideRight:SlideRight = new SlideRight();
slideRight.target=panel;
slideRight.duration=750;
slideRight.showTarget=true;
slideRight.play();
var jsonData = this.map.getValue(title);
var posX:Number = 50;
var posY:Number = 175;
for each ( var pnl:NewPanel in pages){
pages.pop();
}
for each ( var stp1:Object in jsonData.children){
panel = new NewPanel(null);
panel.title = stp1.text;
panel.name=stp1.id;
panel.width = 100;
panel.id=stp1.id;
panel.height = 80;
panel.x = posX;
panel.y=posY;
posX += 150;
var s:String="hi" + stp1.text;
panel.addEventListener(MouseEvent.CLICK, function(e:MouseEvent){onChildClick(e,s);});
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED, function(e:CustomPageClickEvent){onCustomPnlClicked(e)});
this.rawChildren.addChild(panel);
pages.push(panel);
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED, function(e:CustomPageClickEvent){onCustomPanelClicked(e,title)});
var slide:SlideUp = new SlideUp();
slide.target=panel;
slide.duration=1500;
slide.showTarget=false;
slide.play();
}
}
}
public function onChildClick(e:MouseEvent,s:String):void {
for each(var stp1:NewPanel in pages){
if(stp1.title==e.currentTarget.title){
var eventObj:CustomPageClickEvent = new CustomPageClickEvent("panelClicked");
eventObj.panelClicked = stp1;
dispatchEvent(eventObj);
}
}
}
private function onCustomPnlClicked(e:CustomPageClickEvent):void {
for each ( var pnl:NewPanel in pages){
pages.pop();
}
}
private function fadePanel(event:Event,panel:NewPanel):void{
panel.alpha -= .005;
if (panel.alpha <= 0){
panel.removeEventListener(Event.ENTER_FRAME,
function(e:Event){fadePanel(e,panel);});
};
panel.title="";
}
private function startAnimation(event:CustomPageClickEvent,panel:NewPanel):void{
panel.addEventListener(Event.ENTER_FRAME,
function(e:Event){fadePanel(e,panel)});
}