AS3 stack overflow? - actionscript-3

Working with Arrays. I create objects on a Class base, push them into an Array, I have 2 buttons: one adds a Child and pushes it into the Array, second one Shifts Array and removes the Child. Also a function on my mouse, if I click an object, I define it's Array number, remove the Child and... well, not sure if successful but "delete Array[i];" where i is target's Array number. I can see Array.length in a text field every time I do something. Second button actually does remove an object from Array, the number decreases. But deleting a specified object from the Array, as well as Array.slice(i,1), doesn't reduce the Array length. So I'm afraid it may cause overflow. It's only Array, not sure, maybe it's fine to have over a million cells in an Array? Like if I make a game with meteor shower, meteors are removed from the screen, but the Array still has their cells. And if they appear like 30-50 per sec, it's obvious I may get memory problems in 20 minutes of running it. Well it's 60k so maybe I shouldn't worry as only graphics take much memory?
Still, I could use an advice on how to shift an object in a middle of an Array. Chosen one. How do I delete it as if it never was created, same as Shift does? (it does, right?)

Array.splice() will do most of the tricks. As you remove the meteor off screen, you can splice it out of the array, do like this:
var i:int=meteorArray.indexOf(meteorToRemove);
if (i>=0) meteorArray.splice(i,1);

You should not create a new object as a good practice if you are deleting other. Try recycling, or better said 'object pools'
You should figure out the number max of elements you may use at once. create a property 'active' on each and set it to true or false instead of creating/deleting. Then you can run the update on each object and update it only if necessary
For example:
var meteors:Array = [];
// create 500 meteors
for ( var i:int = 0; i < 500; i++ ) {
var meteor:Meteor = new Meteor();
meteor.active = false;
meteors.push(meteor);
}
// enable one meteor
meteors[0].active = true;
// in your update method:
for each (var meteor in meteors )
if ( meteor.active )
meteor.update();
Hope that helps.
Also you can add a helper method to get a meteor available:
function getMeteorAvailable():Meteor
{
for each (var meteor in meteors )
if ( !meteor.active )
return meteor;
}

Related

Is there any direct function to get indices of all possible matches in an array

I generally find indexOf very useful, to get an index directly, and not writing 3-4 lines of for loop to get a match.
Is there any similar function, say like indicesOf , to get an array of all possible matches ?
Or may be having a different name, but acts as a shortcut as beautifully as "indexOf" ?
As you don't mind creating a new Array, you can use the filter() function - it executes a function on each item of the array, then returns a new Array with the items that return true:
// our comparison function
function myCompFunction( element:*, index:int, array:Array ):Boolean
{
return ( element > 10 );
}
var ar:Array = [5,10,15,20];
var ar2:Array = ar.filter( myCompFunction ); // ar2 is now [15,20]
It's not exactly indicies, but then again, you don't need to dereference your objects.
NOTE: because it's calling a function on each element, looping through the array yourself will still be quicker
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#filter()
Unfortunately, there is not such shortcut. indexOf works for only one item, and there is no alternative for multiple items.
The solutions are obvious - iterate over the entire array or use some kind of sort on the array. Maybe there are other methods, but they are almost the same - loop through everything and check. Sorry to say it, but that's the way it is :)

getting a random element from an array of movieclips(or labels in a timeline) in Flash CC . Actionscript 3

I am making a pretty neat quiz-game in flashCC right now and I definitely need your help.
My skills are more on the design then the programming side. So to many of you this might seem a baby question (and asked many times before) but from all the answers I saw so far, I couldn't get any results for my project.
So here is the thing :
I need the EXACT script for creating an array (with movieclips inside? or instance names of mcs? How does this even work?)
and a method, to pick a random element of this array without repeats until the "game is over".
Paul
The easiest way to pick a random element from an array without repeating is to first sort the array with a "random" function, then pop or shift items out of it until the array is empty.
Let's say you have an array of items which can be filled with either instances or instance names, you've chosen instance names: :
var FirstArray:Array = ["blau", "orange", "green"];
Now, you'll need a random sort function:
// you do not need to modify this function in any way.
// the Array.sort method accepts a function that takes in 2 objects and returns an int
// this function has been written to comply with that
function randomSort(a:Object, b:Object):int
{
return Math.random() > .5 ? -1 : 1;
}
The way a sort function normally works is it compares two objects and returns -1 if the first item precedes the second item, 1 if the opposite is true, and 0 if they are the same.
So what we're doing in the function above is returning -1 or 1 randomly. This should get the array all jumbled up when you call:
FirstArray.sort(randomSort);
Now that the array is randomly sorted, you can begin pulling items from it like so:
if(FirstArray.length) // make sure there's at least one item in there
{
// since you are using instance names, you'll need to use that to grab a reference to the actual instance:
var currentQuizItem:MovieClip = this[FirstArray.pop()];
// if you had filled your array with the actual instances instead, you would just be assigning FirstArray.pop() to currentQuizItem
// every time you call pop on an array, you're removing the last item
// this will ensure that you won't repeat any items
// do what you need to do with your MovieClip here
}
else
{
// if there aren't any items left, the game is over
}
When strung together, the above code should be enough to get you up and running.
You could try something like:
var array:Array = [1, 2, 3, 4, 5];
var shuffledArray:Array = [];
while (array.length > 0)
{
shuffledArray.push(array.splice(Math.round(Math.random() * (array.length - 1)), 1)[0]);
}
trace('shuffledArray: ', shuffledArray, '\nrandom item: ', shuffledArray[0]);

How do i populate an Array in one class based on a textfield in another class?(Actionscript 3.0)

i have a class (TheList.as). in which i have an array "Data" and it has a couple of values. Then i have a loop through which i am creating a scrollable list which uses the values from "Data" array. [I am trying make a unit converter]
Then i have another class "Units.as". In that class i have created three instances of "TheList". A main list ("myList"), and to sublists "ListFrom" and "ListTo". They are using values from "Data" array. Now i have text field whose value changes to whatever item is clicked. When i click "Angle" in the main list, i want the sublists to get populated with ("Degree", "Radian" etc)..
Here is what i tried
if(myList._TextLabel.text == "Angle")
{
ListFrom.Data = ["Degree", "Radian"];
}
But nothing happens, i do not get any error either. When i do this in an "ENTER_FRAME" event and trace (ListFrom.Data), i can see that the values change, but they do not get assigned to the list items in the list. I would really appreciate the help. Thanks!
Here are complete Classes for understanding the situation better(the code is pretty messy, as i am a newbie to OOP)
TheList.as: http://pastebin.com/FLy5QV9i
Units.as : http://pastebin.com/z2CcHZzC
where you call ListFrom.Data = ["Degree","Radian"], make sure when the data changed, the renders in the ListFrom have been set new data. for example, you may use MyRender in ListFrom for show, you should debug in the set data method in MyRender.
you should call the code below after you call ListFrom.Data = ["Degree","Radian"];
for (var i:int = 0; i < Data.legnth;i++) {
var render:MyRender = ListFrom[i] as MyRender;
if (render) {
render.data = Data[i];
} else {
var render:MyRender = new MyRender();
render.data = Data[i];
ListFrom.addChild(render);
}
}
You can use event listeners, singleton classes or reference one class to another, depending on the style you want. All are equally valid and fast / efficient.

Splice then re-index array in ActionScript 3

I want to remove the first four indexes from the array using splice(), then rebuild the array starting at index 0. How do I do this?
Array.index[0] = 'one';
Array.index[1] = 'two';
Array.index[2] = 'three';
Array.index[3] = 'four';
Array.index[4] = 'five';
Array.index[5] = 'six';
Array.index[6] = 'seven';
Array.index[7] = 'eight';
Array.splice(0, 4);
Array.index[0] = 'five';
Array.index[1] = 'six';
Array.index[2] = 'seven';
Array.index[3] = 'eight';
I am accessing the array via a timer, on each iteration I want to remove the first four indexes of the array. I assumed splice() would remove the indexes then rebuild the array starting at 0 index. it doesn't, so instead what I have done is created a 'deleteIndex' variable, on each iteration a +4 is added to deleteIndex.
var deleteIndex:int = 4;
function updateTimer(event:TimerEvent):void
{
Array.splice(0,deleteIndex);
deleteIndex = deleteIndex + 4;
}
What type of object is "Array" in the code you have shown? The Flash Array object does not have a property named "index". The Array class is dynamic, which means that it let's you add random properties to it at run time (which seems to be what you are doing).
In any case, if you are using the standard Flash Array class, it's splice() method updates the array indexes automatically. Here is a code example that proves it:
var a:Array = [1,2,3,4,5];
trace("third element: ", a[2]); // output: 3
a.splice(2,1); // delete 3rd element
trace(a); // output: 1,2,4,5
trace(a.length); // ouput: 4
trace("third element: ", a[2]); // output: 4
If I am understanding what you want correctly, you need to use the unshift method of Array.
example :
var someArray:Array = new Array(0,1,2,3,4,5,6,7,8);
someArray.splice(0,4);
somearray.unshift(5,6,7,8);
Also, you are using the Array Class improperly, you need to create an instance of an array to work with first.
The question is confusing because you used Array class name instead of an instance of an array. But as the commenter on this post said, if you splice elements, it automatically re-indexes.
im not sure what you want to do, but Array=Array.splice(0,4) should fix somethin..

Re-stacking MovieClips in an Array

I was trying to make a similar thing with the game SameGame (ie. the block above the removed blocks fall downward). Before trying this with an Array that contains MovieClips, this code worked (tried it with int values). With MovieClips on the array, it seems not working the same way.
With int values, example:
popUp(0, 4): Before: 1,2,3,4,5,6,7,8,9,10; After: 1,2,3,4,6,7,8,9,10
But with MovieClips:
popUp(0, 4): Before: 1,2,3,4,5,6,7,8,9,10; After; 1,2,3,4
// Assume the numbers are movieclips XD
Basically, it strips everything else, rather than just the said block >_<
Here's the whole method. Basically, two extra arrays juggle the values above the soon-to-be removed value, remove the value, then re-stack it to the original array.
What could be wrong with this? And am I doing the right thing for what I really wanted to emulate?
function popUp(col:uint, row:uint)
{
var tempStack:Array = new Array();
var extraStack:Array = new Array();
tempStack = IndexArray[col];
removeChild(tempStack[0]);
for(var ctr:uint = tempStack.length-(row+1); ctr > 0; ctr--)
{
removeChild(tempStack[ctr]);
extraStack.push(tempStack.pop());
trace(extraStack);
}
tempStack.pop();
for(ctr = extraStack.length; ctr > 0; ctr--)
{
tempStack.push(extraStack.pop());
//addChild(tempStack[ctr]);
}
IndexArray[col] = tempStack;
}
PS: If it's not too much to ask, are there free step-by-step guides on making a SameGame in AS3 (I fear I might not be doing things right)? Thanks in advance =)
I think you just want to remove an element and have everything after that index shift down a place to fill what you removed. There's an inbuilt function for this called splice(start:uint, length:uint);
Parameters:
start - the index to start removing elements from
length - the amount of elements to remove
var ar:Array = ["hello","there","sir"];
ar.splice(1, 1);
ar is now -> ["hello", "sir"];
As per question:
Here's an example with different types of elements:
var ar:Array = [new MovieClip(), "some string", new Sprite(), 8];
ar.splice(2, 1);
trace(ar); // [object MovieClip], some string, 8
And further example to display the indexes being changed:
trace(ar[2]); // was [object Sprite], is now 8