Errors when loading random movie clips from an array as3 - actionscript-3

I am getting closer to finding a solution for the errors being generated when running the code below.
I have three boxes on the stage. The goal is to load one random item from the array without any one item being duplicated in more than one of the three boxes.
Yasuyuki Uno has been very helpful. We are currently trying to solve the following:
Code:
var animalArray: Array = [animal1, animal2, animal3, animal4, animal5, animal6, animal7, animal8, animal9, animal10];
var randArr: Array = [];
var rand: int;
// Get random value for 3 times.
for(var i:int=0,len:int=animalArray.length;i<3;i++,len--){
rand = Math.floor( Math.random() * len); // Generate random integer between 0 and len-1.
randArr.push(animalArray.splice(rand,1)); // Delete a value from original array and add that value to new array.
}
box1.addChild(randArr[0]);
box2.addChild(randArr[1]);
box3.addChild(randArr[2]);
Error Message: Incorrect number of arguments. Expected no more than 0
Any help would be greatly appreciated. Thnx!

Assuming that animal1, animal2, etc are linkage IDs in your library, they are class references so they need to be instantiated using the new operator.
There are a few other non-critical issues with your code that made it hard to understand from my point of view:
Using animal1 instead of Animal1 and so on for class names. Uncapitalized names look like properties or functions, not classes.
Using Array instead of Vector. Vectors give you better errors; had you been using Vectors from the start your problem would be obvious.
Example:
var animalTypes:Vector.<Class> = new <Class>[Animal1, Animal2, Animal3, Animal4, Animal5, Animal6, Animal7, Animal8, Animal9, Animal10];
var randomAnimals:Vector.<DisplayObject> = new <DisplayObject>[];
// Get random value for 3 times.
for (var i:int = 0; i < 3; i++){
// Generate random integer between 0 and length-1.
var randomIndex:int = Math.random() * animalTypes.length;
// Remove a class from original vector.
var randomAnimalType:Class = animalTypes.splice(randomIndex, 1)[0];
// Create an instance of the animal class.
var randomAnimal:DisplayObject = new randomAnimalType();
// Add the instance to the random vector.
randomAnimals.push(randomAnimal);
}
box1.addChild(randomAnimals[0]);
box2.addChild(randomAnimals[1]);
box3.addChild(randomAnimals[2]);

As you check length of animalArray in for expression, it's no need to change variable len.
Also if you want to fill with 3 random items new array, you need to use this code:
const arr: Array = [animal1, animal2, animal3, animal4, animal5, animal6, animal7];
const genArr: Array = [];
var len: int = arr.length;
var n: int = 3;
while(n--) {
const randIndex: int = Math.floor(Math.random()*len); // get random index
genArr.push(arr.splice(randIndex, 1)[0]); // splice returns array, so we need first and exist item
len--; // decrement length as optimized solution of no-read length of array each cycle
}
trace(genArr);

Related

AS3 - Using a For Loop to Update Multiple Points and Their Values in an Array

I'm a bit new with AS3 (but not really with coding) so please forgive my ignorance. I'm creating a small function that will be called by a Main Function to update the position of 52 Pointers that have the x and y position of multiple point objects (empty movie clips). It will also then update two global arrays with those values (one array for the x and one for the y).
The problem is, as there are 52 of them, and they will probably grow in quantity, I'd like to be able to use a FOR function to do it, but I can't seem to be able to figure it out.
I get this error: Access of undefined property _point.
Here is a piece of the code that dream about:
function happyFunc():void
{
var avpointers:int = 52;
var vpointx:Array = new Array();
var vpointy:Array = new Array();
for (aa=0; aa<vpointers; aa++)
{
vpointx[aa] = _point[aa].x;
vpointy[aa] = _point[aa].y;
}
}
And this is the code that I'm stuck with...
function reallySadFunc():void
{
_point1 = localToGlobal(new Point(point1.x,point1.y));
//...
_point52 = localToGlobal(new Point(point52.x,point1.y));
vpointx[0] = _point1.x;
vpointx[1] = _point2.x;
//...
//oh god there are 104 lines of this why do I have to suffer
}
Thank you!
If I read your question correctly, I think this is what you need:
public static const CLIP_COUNT:int = 52;
// ...
private function happyFunc(parentClip:DisplayObjectContainer):void
{
var vpointx:Vector.<Number> = new Vector.<Number>(CLIP_COUNT, true);
var vpointy:Vector.<Number> = new Vector.<Number>(CLIP_COUNT, true);
var clipPoint:Point = new Point ();
var globalPoint:Point;
for (var i:int = 0; i < CLIP_COUNT; i++)
{
var childClip:DisplayObject = parentClip.getChildByName("point" +
(i + 1).toString());
clipPoint.x = childClip.x;
clipPoint.y = childClip.y;
globalPoint = parentClip.localToGlobal(clipPoint);
vpointx[i] = globalPoint.x;
vpointy[i] = globalPoint.y;
}
// do something with vpointx and vpointy - they're local variables
// and will go out of scope unless you declare them as class members
// or somehow return them from this function.
}
This function works by taking the parent display object (the one that contains the 52 movie clips - this could be the Stage) and iterates through them by getting each movie clip by name. The code assumes that your movie clips are called point1, point2, ..., point52.
To speed up the local-to-global coordinate conversion, two Point objects are created and then reused during the for loop to avoid creating many temporary Point instances.
Instead of using Array, use Vector.<Number> - this class has better performance than Array does.

AS3 Best way to declare variables inside loop

Is it possible better to declare variables without having to write one by one?
I need 200 but... no way.
My code i have:
var var0:Array = new Array();
var var01:Sprite = new Sprite();
var var02:Sprite = new Sprite();
var var03:Sprite = new Sprite();
etc to 200...
And inside for loop:
for( var i:Number = 0; i < arrayBig.length; i++ ){
var0[i] = new Sprite();
...
}
But Why cant I write var var0[i]:Sprite = new Sprite(); in the statments?
The error is Error #1086 Syntax error: expecting semicolon before
Thank you very much!!
You cannot index independent variables and you cannot concatenate variable names to form names of other variables (well, not the way you attempted).
You need to create an array of Sprite objects. An array is a data structure that stores several things at once. (A one-dimensional array is called a vector.)
To store sprites in a vector, you'd write:
var sprites:Vector.<Sprite> = new Vector.<Sprite> ();
for ( var i:int = 0; i < 200; i++ )
{
sprites.push ( new Sprite () );
}
This loop creates 200 Sprite instances and stores all of them in the sprites array (really, Vector). You can then access individual sprites by simply indexing them:
sprites[n]....
where n goes from 0 to N-1 if the Vector has N total elements.
i will answer for your question.
"But Why cant I write var var0[i]:Sprite = new Sprite(); in the statements?"
we cant override one object with that of the other same object in the class. thats the reason, we are declaring as "var0[i] = new Sprite();". spl case for sprite object in flex.

Two dimensional array of objects in as3

Is it possible to make array in as3 like this :
countdowns[bodyID][powerupName] = { time: powerup.getTime(), onRemove: onRemove };
I have been trying for hours but no luck..
Thanks
Sure, but you have to declare each object separately and you have to call index number instead of variable name
Say I have an array of colors with a sub array of types of that color filled with objects describing RGB
var colors:Array = [];
var red:Array = [];
var darkRed:Object = { r : 256, g : 100, b : 100 }
red.push( darkRed ); //darkRed is now part of red
colors.push( red ); //red is now part of colors
To access darkRed, you would do this:
colors[0][0]; //that is darkRed
I believe this is what you are trying to accomplish :
var countdowns:Array = new Array;
countdowns[bodyID] = new Array;
countdowns[bodyID][powerupName] = { time: powerup.getTime(), onRemove: onRemove };
The second dimension of the countdowns Array is achieved by inserting an array into each element of the first dimension.
While this certainly can be done, but it's possible you're overcomplicating things. Perhaps a single-dimensional Array ob tailored Objects will suit better.
var ob:Object=new Object();
ob.bodyId=bodyId;
ob.powerup=powerup; // direct link to powerup might serve you better!
ob.onRemove=onRemove;
countdowns.push(ob);

actionscript removing movieclip children

Ive got a document class in this class I dynamically create movie clips, store them in an array and finally add it to the stage using addChild. That's all fine, the issue is though im trying to remove the movieClips through the array and it is throwing an error:
1034: Type Coercion failed: cannot convert []#26be1fb1 to flash.display.DisplayObject.
Here is my code:
// Note i have declared the array outside the function, so that's not an issue
function x (e:MouseEvent){
if (thumbnails.length !== 0){ // Determine if any movieclips have already been created on stage and delete them
for(var ctr:int = 0; ctr < thumbnails.length;ctr++ ){
removeChild(thumbnails[ctr]);
}
}
for (var i: int = 0;i < userIput; i++){ // Loop through and create instances of symbol
var thumb:Thumbnail = new Thumbnail();
thumb.y = 180; // Set y position
thumb.x = 30 + ((thumb.width + 10) * i);
addChild(thumb);
thumbnails[i] = [thumb]; // Add to array
}
}
When you retrieve the MovieClip from your Array, you need to cast it as a DisplayObject before attempting to remove it:
if (thumbnails.length !== 0){ // Determine if any movieclips have already been created on stage and delete them
for(var ctr:int = 0; ctr < thumbnails.length;ctr++ ){
removeChild(DisplayObject(thumbnails[ctr]));
}
}
Alternatively, you could consider using a Vector (a type-safe version of an Array) with the base-type set as DisplayObject:
var thumbnails:Vector.<DisplayObject> = new Vector.<DisplayObject>();
thumbnails.push(new MovieClip());
this.addChild(thumbnails[0]);
this.removeChild(thumbnails[0]);
For further reading, have a look at the Adobe documentation on type conversion and Vectors.
Update:
Instead of adding an instance of Thumbnail to your Array the following line is actually adding a further Array containing a single element to your thumbnails Array (in effect you are creating a multi-dimensional Array):
// You're assigning an array literal with a single element
// to this element of the the thumbnails array
thumbnails[i] = [thumb];
Try either of the following instead:
// What you meant
thumbnails[i] = thumb;
// Better
thumbnails.push(thumb);
The error that appears tells you that Flash Player cannot convert []#26be1fb1 to DisplayObject. The []#26be1fb1 gives you a hint what type of object at which address cannot be converted. [] is the type of object here that means the type Array so when removeChild() is called you try to pass an array to it, but the method expects DisplayObject.
Why this happens
Your code has a very simple but maybe unobstrusive problem, namely at this code line:
thumbnails[i] = [thumb]; // Add to array
You put your thumb into an array by using [] around thumb. So what your code actually is doing is that it adds an array with a single element (thumb) to the array thumbnails. After that you have an array of arrays with single elements.
Solution
Change the above line to:
thumbnails[i] = thumb; // Add to array
This should solve your issue.
For your perceived issue:
Use Vector instead of Array
or cast array item to Thumbnail class
But the main culprit will probably be the fact you never clear the items from the array, you remove them from the parent/stage, but you do not remove them from the array… together with adding the items at a specific place in the array will cause erratic behavior:
you add them:
t[0] = item0_0
t[1] = item0_1
t[2] = item0_2
t[3] = item0_3
then remove item0_0, item0_1, item0_2, item0_3 from stage, but leave them in the array
next you add e.g. 2 new ones
t[0] = item1_0
t[1] = item1_1
so you have:
on stage:
item1_0
item1_1
in array:
t[0] = item1_0
t[1] = item1_1
t[2] = item0_2
t[3] = item0_3
This should be working:
var thumbnails:Vector.<Thumbnail> = new Vector.<Thumbnail>();
function x (e:MouseEvent) {
var thumb:Thumbnail;
for each(thumb in thumbnails){
removeChild(thumb);
}
thumbnails = new Vector.<Thumbnail>(); // clear Vector by re-initiating it
for (var i: int = 0;i < userIput; i++){
thumb = new Thumbnail();
// ...
addChild(thumb);
thumbnails.push(thumb);
}
}

Array cascades its changed to secondary temp array in as3

I came across a unique (to me), and quite puzzling situation.
I have an array of three values.
focal[x,y,z]
these values change based on user input.
however when the change occurs, they are logged into a new array to test for valid changed
A simplified psuedo version of my code:
var temp:Array = focal; //I have even changed this to a const at times but to no avail
//changes to array are made like thus:
focal[1]++;
focal[0]--;
if(valid){
doStuff();
} else {
focal = temp;
}
However, when the focal[1]++; focal[0]--; ect, ect, code takes place. It also changed the temp array.
and since it changes my temp, it never resets me original code back to its previous nature.
I have never seen this behavior and its kinda throwin' me off. Suggestions?
when you are doing like this:
var temp:Array = focal; // Both array variables refer to the same array.
if you want to make a backup or temporary array you need to copy all the componetns from one to another:
var baseArray : Array = [0, 0, 0];
var tempArray : Array = baseArray.slice();
baseArray[0]++;
baseArray[1] += 2;
baseArray[2] += 3;
trace ( baseArray ); // output: 1,2,3
trace ( tempArray ); // output: 0,0,0
I add the deep copy method to the (very good) post by Jevgenij:
import flash.utils.ByteArray;
function clone(source:Object):*
{
var myBA:ByteArray = new ByteArray();
myBA.writeObject(source);
myBA.position = 0;
return(myBA.readObject());
}
More informations here: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7ee7.html