How to "restart" my as3 code - actionscript-3

I've got some AS3 codes on my 4th frame.
var words:Array = new Array; //a mini database to hold the words
var current_word:String; //used to hold the current word being tested
var ques_num:int; //used to track the question number
var tileArray:Array = new Array; //array of tile objects
var targetArray:Array = new Array; //array of target areas
var scramble_Array:Array = new Array; //array used to scramble the word
getword();
function getword() {
words=["screen"];
current_word=words[ques_num];
setTiles(current_word.length);
ques_num++;
}//getword
function setTiles(a) {tileArray=[ ];
for(i=0;i<a;i++){
var tempclip:Tile =new Tile;addChild(tempclip);
tempclip.x=150+(i*120);tempclip.y=500;tempclip.tag=i;
tempclip.original_posx=tempclip.x;
tempclip.original_posy=tempclip.y;
tileArray[i]=tempclip;
var tempclip2:Placeholder =new Placeholder;addChild(tempclip2);
tempclip2.x=150+(i*120);tempclip2.y=620;
targetArray[i]=tempclip2;
}//for i
scramble_word(a);
}//setTiles
I wanted to put a button where the user can click in order to go back to frame 1.
goBack1.addEventListener(MouseEvent.CLICK, gotoOne, false, 0, true);
function gotoOne(event:MouseEvent):void{
gotoAndStop(1);
}
When I do so, we can still see the child of the 4th frame..
So I removed them.
trace("clear_board");
removeChild(checker);
pauser=false;
for(i=0;i<tileArray.length;i++){
removeChild(tileArray[i]);
removeChild(targetArray[i]);
}
}
But now, when the user is going back to the 4th frame, an error is displayed :
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at RECUPERE_jeumuseev1_fla::Jules_108/getword()[RECUPERE_jeumuseev1_fla.Jules_108::frame4:95]
The line 95 is this :
setTiles(current_word.length);
I suppose that the error come from the fact that I've "removed" tileArray[i] but I'm not sure..
What do you suggest I could do to simply "restart" the all code from this frame, like the first time the user is coming to the 4th code ?

Related

how to print a large size sprite by as3

I've an app in which users first insert some data and then print the data in an aligned and table form. But I have a problem with printing the final document when I print this with a custom class FilePrinter which takes only one non-optional parameter "Sprite". I clearly and rightly follow through the codes but when I print, the printed document is nothing but a clear page. I'm not understanding why this so?
But one thing that should be noted is that the sprite is consisted of an image (with resolution not normal) and the size of printed Document becomes much (Round About 12mb to 15mb) when it is ready to print.
If any one knows about the issue so please help me...
Thanks...!
var rslt:MovieClip = new MAIN_DOC();
rslt.box1.text = arr[0].toString();
rslt.box2.text = arr[1].toString();
rslt.box3.text = arr[2].toString();
rslt.box4.text = arr[3].toString();
rslt.box5.text = arr[4].toString();
rslt.box6.text = arr[5].toString();
var BackM:MovieClip = new BackGround();
BackM.PIcont.addChild(picData);
var sprite:Sprite = new Sprite();
sprite.addChild(BackM);
sprite.addChild(rslt);
var print:FilePrinter = new FilePrinter(sprite);
function printBtnClick(e:MouseEvent):void
{
print.print();
}
FilePrinter Class
public class FilePrinter {
private var pJob:PrintJob;
private var opt:PrintJobOptions = new PrintJobOptions(true);
private var sp:Sprite;
public function FilePrinter(sprite:Sprite) {
sp = new Sprite();
sp = sprite;
pJob = new PrintJob();
if (pJob.start())
{
pJob.addPage(sp, null, opt);
}
}
public function startPrint():void {
pJob.send();
}
}
From the Actionscript documentation:
Additionally, a 15 second script timeout limit applies to the following intervals:
PrintJob.start() and the first PrintJob.addPage()
PrintJob.addPage() and the next PrintJob.addPage()
The last PrintJob.addPage() and PrintJob.send()
If any of the above intervals span more than 15 seconds, the next call to PrintJob.start() on the PrintJob instance returns false, and the next PrintJob.addPage() on the PrintJob instance causes the Flash Player or Adobe AIR to throw a runtime exception.
I'd recommend not initalising your FilePrinter class until the button press event triggers, also you seem to be calling print() in your button click listener, but there is no such function in your FilePrinter class, only startPrint()
var print:FilePrinter;
function printBtnClick(e:MouseEvent):void
{
print = new FilePrinter(sprite);
print.startPrint();
}

Modify stage size cause error - Flash CC

I have an application with 2 scene, the first scene contains 4 movieclips which are placed manually into the scene, every movieClip had an instance name (mc1,mc2..mc4), and I create an array with this objects var arr:Array = [mc1..mc4];
I add them an mouse event listener , for each (var i in arr){ i.addEvent...mouse.click)};
In this scene I also have an button "next scene" which have this code : nextScene();
In the second scene I have one button "back" which have this code : prevScene();
My app is 1200 x 720 px size, and I want it 800 x 600, so when I'm changing this manually .
When I'm running the application, everything is good, a go to next scene, and when I press back, it gives me an error at first scene
for each(var i in arr){
i.addEvent...mouse.click)
};
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main/frame2()
at flash.display::MovieClip/prevScene()
at Main/onBack()
When I trace mc1 , at first run scene1 the output is //movieclip
when I'm pressing back the output is // null
and if I trace arr, the output is // ,movieclip,movieclip,movieclip (first only comma)
what can be the problem? thank you
Scene 1 code:
stop();
trace(mc1); // first run -> object [MovieClip]
// when back pressd -> null
var selectedIm:MovieClip = mc1;
var selectedD = d1;
var difficulty:uint = 3;
var imgs:Array = [mc1,mc2,mc3,mc4];
var diff:Array = [d1,d2,d3,d4];
goBtn.addEventListener(MouseEvent.CLICK, onGo);
for each(var i in imgs){
i.addEventListener(MouseEvent.CLICK, onImage); //here is the error, NULL OBJECT
}
function onGo(e:MouseEvent):void{ //next button
new Clk().play();
nextScene();
}
function onImage(e:MouseEvent):void{
new Clk().play();
if(selectedIm) selectedIm.filters = [];
selectedIm = e.target as MovieClip;
addOutline(selectedIm,0xFFFFFF,6);
}
...
Scene 2 code:
...
function onBack(e:MouseEvent):void{
new Clk().play();
removeChild(pz);
timer.reset();
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, numara);
prevScene();
....
}

AS3 Remove items in an ENTER_FRAME

I have generated random bubbles, I used a code I found in the net. Now I want a click event that will hide a random bubble.
Here is exactly the code I used,
http://good-tutorials-4u.blogspot.com/2009/04/flash-bubbles-with-actionscript-3.html
I got the bubbles running good...
I have tried this, and so far no luck..
addEventListener(MouseEvent.CLICK, eventListener);
function eventListener(eventObject:MouseEvent) {
bubbles[i].splice(i,1,bubbles[i]);
}
I tried using an array but it returns me this output
TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/removeChild()
at Function/()
TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/removeChild()
at Function/()
If you have the bubbles in an array this should work.
var randomIndex:int = int(Math.random() * bubbles.length);
parent.removeChild(bubbles[randomIndex]);
bubbles.splice(randomIndex, 1);
Notice that you have to remove the bubble from the display list too.
You can try creating a new array without a random element from the original array. Then just reassign the old array to the new one, e.g.
// get the random index to remove element at
var randomIndex:int = 0 + bubbles.length * Math.random();
var index:int = 0;
// create new array containing all apart from the chosen one
var newBubbles:Array = [];
for each (var item:Object in bubbles) {
if (index != randomIndex) {
newBubbles.push(item);
}
index++;
}
// here you go new array without one random item
bubbles = newBubbles;
Or something like these.
Just a minor revision on Baris Usakli's code here, this is if you want the one that was clicked on to be removed.
var bubbles:Array = [];
function makeBubbles()
{
for(var i:int=0;i<100;i++)
{
var bubble:Bubble = new Bubble();
bubbles.push(bubble);
addChild(bubble);
bubble.addEventListener(MouseEvent.CLICK, eventListener);
}
}
function eventListener(eventObject:MouseEvent) {
var clickedBubbleIndex:int = bubbles.indexOf(eventObject.currentTarget);
parent.removeChild(eventObject.currentTarget);
bubbles.splice(clickedBubbleIndex:int, 1);
}
try this
bubbles.addEventListener(MouseEvent.CLICK, eventListener); // place this listener in moveBubbles function.
function eventListener(eventObject:MouseEvent):void {
eventObject.currentTarget.visible = false;
}

AS3 Error 1009 - Where am i going wrong?

This is the error I'm getting:
TypeError: Error #1009: Cannot access a property or method of a null object reference. at ICA_v7_fla::MainTimeline/addEgg()
at Function/http://adobe.com/AS3/2006/builtin::apply()
at SetIntervalTimer/onTimer()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
Cannot see where I am going wrong - could someone point out where I'm trying to refer to a null object reference please :)
The rest of my AS reads:
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
//Set as a variable so that it can be changed at a later
//date so that the user level can change (if necessary).
var eggMoveSpeed=6;
var Score=0;
var ScoreValue=10;
var Level=1;
var NextLevel=100;
var EggCount=0;
var EggMax=15;
btn.addEventListener(MouseEvent.CLICK, scorer);
function scorer(e:Event):void{
//Add to the score.
Score=Score+10;
//Display score in text box.
scoreText.text=Score;
}
var eggAdd = setInterval(addEgg,2000);
function addEgg(){
//Add to the egg count (to ensure maximum is not exceeded).
EggCount=EggCount+1;
if (EggCount<=EggMax){
//Create an object of the egg_mc from the egg class.
var egg:egg_mc = new egg_mc();
//Set the Max and Min WIDTH positions.
var maxWidth = 452;
var minWidth = 98;
//Randomize the position of the egg on the screen - with thanks to http://www.kirupa.com/developer/actionscript/tricks/random.htm
var positionX = Math.floor(Math.random()*(1+maxWidth-minWidth))+minWidth;
//Position the egg on the stage, and add it to the screen
egg.y=400;
egg.x=positionX;
//Add the egg to the stage.
stage.addChild(egg);
//Add a moving loop to the egg.
egg.addEventListener(Event.ENTER_FRAME, loop);
}else{
clearInterval(eggAdd);
}
function loop(e:Event):void{
//Move the egg up the screen.
egg.y-=eggMoveSpeed;
//Check to see if egg has got to the top of the screen - if so, then move the object to the bottom.
if (egg.y<-100){
egg.y=400;
}
}
//Add an event listener to the egg, to see if it has been clicked.
egg.addEventListener(MouseEvent.CLICK, clickedEgg);
function clickedEgg(e:Event):void{
//http://asgamer.com/2009/flash-game-design-basics-adding-library-objects-to-stage-with-as3
//Create an object of the brokenEgg_mc from the broken egg class.
var brokenEgg:brokenEgg_mc = new brokenEgg_mc();
//Position the brokenEgg image wherever the egg Image was.
brokenEgg.y=egg.y;
brokenEgg.x=egg.x;
//Add brokenEgg to stage, and remove the egg image.
stage.addChild(brokenEgg);
stage.removeChild(egg);
//Add to the score.
Score=Score+ScoreValue;
//Display score in text box.
scoreText.text=Score;
//Set LevelCheck Variable to 0 - to recalculate correctly.
var LevelCheck = 0;
//Check the level that the user is currently on by dividing the score by the next level required score.
LevelCheck=Score/NextLevel;
//Setup a variable to use for the actual level to display.
var ActualLevel=0;
//Check to see if the LevelCheck variable has come back less than 1 (i.e. 0.1 or a score of 10).
if (LevelCheck < 1){
//If yes, then set the level to 1, as user is still on level 1.
ActualLevel=0;
} else {
//If not, then round down to the lowest level (1.9 is still level 1!).
ActualLevel=Math.floor(LevelCheck);
}
//Display the Lowest Level to the user.
levelText.text=ActualLevel;
}}
Obviously, the timer event loops until there are 15 eggs on the stage, where the interval should then stop running - but this produces the error.
Your egg variable is function-wide, namely it's defined in addEgg() function, but you refer to egg inside clickedEgg and loop, which don't have actual access to egg's value. Also, if there is more than a single egg, how do you plan on tracking which egg was clicked, etc? At the very least, use e.target in clickedEgg function to find out what egg was clicked, and don't forget clearing the event listener.
function addEgg():void {
if (EggCounter>=EggMax) return; // why adding eggs if there are too many?
var egg:egg_mc=new egg_mc();
// rest of code intact
}
function loop(e:Event):void {
var egg:egg_mc=(e.target as egg_mc);
if (!egg) return; // loop is for eggs only
// rest of function intact
}
function clickedEgg(e:MouseEvent):void {
var egg:egg_mc=(e.target as egg_mc);
if (!egg) return;
// rest of function intact, as we now have a valid egg link
egg.removeEventListener(Event.ENTER_FRAME,loop);
egg.removeEventListener(MouseEvent.CLICK,clickedEgg);
// clear listeners. These are persistent until removed manually!
}

accordion menu error 1010

I'm trying to create an accordion menu off of an online tutorial. I followed every step (i think) on Original Tutorial but changed things according to my size, as well as make the instance names end with _mc or _txt accordingly. But for some reason it doesn't seem to be working.
I'm getting the #1010 error and it doesn't really clarify anything:
TypeError: Error #1010: A term is
undefined and has no properties.
at
tutorial_fla::MainTimeline/placeItemsOnStage()
at
tutorial_fla::MainTimeline/onComplete()
at
flash.events::EventDispatcher/dispatchEventFunction()
at
flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
I have my first xml file that has all the images to insert and that one hasn't been changed at all should work fine.
I know this is long, but I'm hoping someone can check it out anyhow. I'm extremely new to this and would pretty much have to abandon the whole project. Thanks so much!
my code:
//import tweenlite classes
import gs.TweenLite;
import gs.easing.*;
var MENU_ARRAY:Array; //used to save the items data
var OPENED_MENU:int; //to inform the menu that should be open at startup
var MOVE_ON_MOUSE_OVER:Boolean=false; //tha name says everything
var xmlLoader:URLLoader; //the xml loader
loadXML("menu2.xml"); //load the xml
function loadXML(Uri:String):void {
xmlLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, onComplete);
xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
xmlLoader.load(new URLRequest(Uri));
}
function onError(evt:ErrorEvent):void {
trace("cannot load xml file");
}
function onComplete(evt:Event):void {
//read and load xml into array, by parsing it using prepareMenu
MENU_ARRAY=prepareMenu(xmlLoader.data.toString());
placeItemsOnStage(); //place all required items on stage.
}
function placeItemsOnStage():void {
var pos:Number=0;
//define the container properties
menuContainer_mc.x=0;
menuContainer_mc.y=0;
for(var c:int=0; c<MENU_ARRAY.length; c++) {
var it:menuItem = new menuItem; //load out menuItem, because its exported to AS, we can use it here
it.x=c*51; //its the gray border width
it.y=0; //place on top
it.id="Item-"+c; //id the menuItem
it.name="Item-"+c; //name de menuItem
it.posX=pos; //actual pos, useful to open and know is position
it.itemLabel_txt.text=String(MENU_ARRAY[c].Ititle).toUpperCase(); //load the label in uppercase
it.addEventListener(MouseEvent.CLICK, onMouseClick); //add mouse click listener
if(MOVE_ON_MOUSE_OVER==true) it.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver); //if configured, load the mouse over event
it.useHandCursor=true; //use hand cursor
it.buttonMode=true; //buttonMode
it.itemText_txt.visible=false; //hide the textField
menuContainer_mc.addChild(it); //add the menu item as child
if(String(MENU_ARRAY[c].IcontentType)=="image/swf") { //check the content and load things accordint to it
var ldr:Loader = new Loader();
ldr.x=51;
ldr.y=0;
it.addChild(ldr);
ldr.load(new URLRequest(MENU_ARRAY[c].IcontentData.toString()));
}
else if(String(MENU_ARRAY[c].IcontentType)=="text") {
it.itemText_txt.visible=true;
it.itemText_txt.text=MENU_ARRAY[c].IcontentData.toString();
}
pos+=51; //the next menuItem x position
}
//put mask in place
masker_mc.width=(MENU_ARRAY.length*51+700)
masker_mc.height=menuContainer_mc.height;
masker_mc.x=0;
masker_mc.y=0;
moveItem(OPENED_MENU-1); //open menu confirured in XML
}
function onMouseOver(evt:MouseEvent):void {
if(evt.target.name.toString()=="buttonBack") prepareMove(evt)
}
function prepareMove(evt:MouseEvent):void {
var targetName:String = evt.currentTarget.name.toString(); //get the menuItem
var temp:Array = targetName.split("-"); //split his name: Item-x
var itemNumber:int=(temp[1]); //got item number
moveItem(itemNumber); //move it
}
function onMouseClick(evt:MouseEvent):void {
if(evt.target.name.toString()=="buttonBack") prepareMove(evt); //mouse action was done in buttonBack
else trace("Item "+evt.currentTarget.name+" clicked!"); //mouse action was made on accordion area
}
function moveItem(num:int):void {
var itemToMove:menuItem=menuContainer_mc.getChildByName("Item-"+String(num)) as menuItem;
//get the menuItem child
for(var m=0;m<MENU_ARRAY.length;m++) //move one-by-one to the new position
{
var tempMc = menuContainer_mc.getChildByName("Item-"+m);
if(tempMc.x > itemToMove.x) TweenLite.to(tempMc, 1, {x:((tempMc.posX) + itemToMove.width-51), ease:Quart.easeOut}); //see tweenLite for info about this.
else if(tempMc.x <= itemToMove.x) TweenLite.to(tempMc, 1, {x:(tempMc.posX), ease:Quart.easeOut});
}
}
function prepareMenu (XMLData:String):Array
{
//make sure it cames in XML
var menuXML:XML = new XML(XMLData);
//just in case
menuXML.ignoreWhitespace = true;
//get XML item's entrys
var XMLItems = menuXML.descendants("item");
//load all items into an array
var itemsArray:Array = new Array();
var itemObj:Object;
for(var i in XMLItems)
{
itemObj=new Object();
itemObj.Ititle=XMLItems[i].#Ititle;
itemObj.IcontentType=XMLItems[i].#IcontentType;
itemObj.IcontentData=XMLItems[i].#IcontentData;
itemObj.itemID="menu"+i;
itemsArray.push(itemObj);
}
OPENED_MENU=menuXML.#menuOpen; //get menu for open.
MOVE_ON_MOUSE_OVER=(menuXML.#moveOnMouseOver.toString()=="true" ? true : false); //get the option for load or not mouseOver open
return itemsArray;
}
//finish.
stop();
"term" refers to an identifier, "Error #1010: A term is undefined and has no properties" means you are using an expression which cannot be evaluated. This usually happens when you try to access and use an undefined object property via its string name as in myobject["property"].method(). Can you provide the exact line on which the exception is raised?