AS2 push to array outside of clip does nothing - arrays

was wondering if someone could show me what I'm doing wrong here.
I have some old AS2 flash code I'm trying to get working.
First I create a few arrays in frame 1 of the main timeline like so-
var typeArr:Array = new Array();
for (var i:Number = 1; i < 5; i++)
{
_root.typeArr[i] = "data goes here";
}
Then I have a movieclip dynamically attached on the main stage that when clicked appends one of the arrays we created by pushing the string 'foo' to it-
stop();
_root.myType=3;//this can be any of our array numbers
this.onPress=function(){
var foo:String="test";
_root.typeArr[_root.myType].push(foo);
trace(_root.typeArr[_root.myType]);
}
Where _root.typeArr[_root.myType] is the array name and number _root.typeArr3, but pushing the data does not work and returns nothing.
However, if I test it directly using-
_root.typeArr[_root.myType]=foo;
It will store the data once (_root.typeArr3=test), so I can't see why it won't push to that array as multiple elements each time like- "test,test,test"
It's driving me crazy.
Thanks! :)

_root.typeArr[_root.myType] is equal to "data goes here" so you are pushing string to a string, which doesn't work.
If you would like to append the new string, you should do something like:
_root.typeArr[_root.myType]+=foo;
and you will get: data goes heretest
If you have different data structure instead of "data goes here" the key may lie in the format of this data.

var typeArr:Array = new Array();
// 'i' must start from 0 because the first element is typeArr[0]
for (var i:Number = 0; i < 5; i++)
{
typeArr[i] = i;
// trace(typeArr[i]); // 0,1,2,3,4
}
// trace(typeArr); // 0,1,2,3,4
myType = 3;
bt.onPress = function()
{
var foo:String = "test";
// push method puts the element at the end of your array
// typeArr.push(foo);
// trace(typeArr); // 0,1,2,3,4,test
// splice method replace the 4e element (index 3) of your array
typeArr.splice(myType, 1, foo);
trace(typeArr); // 0,1,2,test,4
}

Related

Actionscript 3 and sorting incoming bytes from an arduino

im new to using action script so i apologies if this wont make sense, the issue iam having is that the incoming bytes from my arduino are not being stored properly in an array. The bytes come in one at a time from my arduino and will be stored in an array in as3.
i have two values SF-F8-001, SF-F8-002 and SF-F8-003 etc... when i trace the incoming bytes i get this:
S
F
-
F
8
-
0
0
1
so when i look at that i realized i needed an array to store the byte as they come in however i have tried many different things but it hasnt worked
however this code below seems to get me close to my desired result
import flash.events.*;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequestMethod;
var ary:Array = new Array();
var bar_grab:Array = new Array();
var array:Array = new Array();
trace("__AS3 Example__");
var socket:Socket = new Socket("localhost",5331);
socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
function socketDataHandler(event:ProgressEvent):void
{
var str:String = String(socket.readUTFBytes(socket.bytesAvailable));
var b:String;
bar_grab.push(str);
b = bar_grab.join("");
boxtwo.text = b;
}
this code gets me this
SF-F8-001SF-F8-002SF-F8-003 etc...
however the result iam looking for is this
SF-F8-001,SF-F8-002,SF-F8-003 etc....
so if anyone could help me sort this out i will be grateful
thank you
If you know a priori how many characters each item will consist of you could read everything to string and get each individual item like that:
//Main string containing all items
var allString:String = "123456789";
//Number of chars in of item
var charsInItem = 3;
var item:String;
var index:int;
var resultArray:Array = new Array();
for(var i:int = 0; i < allString.length/charsInItem; i++)
{
index= i*charsInItem;
//traces name of one item
item = allString.slice(index, index+charsInItem);
resultArray.push(item);
trace(item);
}
//Output:
//123
//456
//789
If you don't know a number of chars in one item or it varies, I would suggest tweaking Arduino code and putting some sort of a marker in between every item. Like say a comma (,). Then your string would look something like this: "item1,item2,longerItem3". And you could split that string into array like that:
var array:Array = new Array();
var allString:String = "item1,item2,longerItem3";
//This splts string into array items using comma (,) as a seperator
array = allString.split(",");
for(var i:int = 0; i < array.length; i++)
{
//trace every array element
trace(array[i]);
}
//Output:
//item1
//item2
//longerItem3
I should add that even if you know a number of chars in one item I would still suggest using method nr.2.

Array not resetting in Game

Hey guys so i am developing a Game and i have an Array that keeps track of my 5 movie clips that are added to the stage by the array. I have a Player movie clip as well so the Player movie clip is Hittesting with all the 5 diamond movie clips which are added to the stage like so:
private var nPoints:Number = 5;..........
public function addPointsToStage():void
{
for (var i = 0; i < nPoints; i++)
{
trace(aPointsArray.length);
points = new mcGainPoints();
stage.addChild(points);
points.x = startPoint.x + (xSpacing * i);
points.y = startPoint.y - (ySpacing * i);
aPointsArray.push(points);
}
}
Now when the Player comes in contact with all the 5 movie clips everything works fine and the output for the array looks like this:
0
1
2
3
4
Then it continues to the next level.
But say that my Player doesnt hit any of the 5 movie clips or only hits a couple of them, when the next level is started the output looks like this:
5
6
7
8
9
and when the next level is started weird things start happening like points start adding to the highscore by themselves.
I think the problem is that im not destroying the array holding the 5 movie clips correctly this is the code i use to start the next level and destroy the array:
if(player.hitTestObject(mcGoal_1))
{
//Remove all points from array/stage
for (var i:int = 0; i < aPointsArray.length; i++)
{
if (aPointsArray[i].parent)
{
parent.removeChild(aPointsArray[i]);
}
startNextLevel();
}
The mcGoal_1 is the object of the game so if the player hits the goal_1 then destroy all array objects on screen and start next level. This is the startnextlevel function.
private function startNextLevel():void
{
//add points to next stage
addPointsToStage();
}
So can you see why when the next level starts the array isnt reset back to 01234? I think thats why the game has that bug of randomly adding points. Please any help will be appreciated
//Remove all points from array/stage
for (var i:int = 0; i < aPointsArray.length; i++)
if (aPointsArray[i].parent)
parent.removeChild(aPointsArray[i]);
// just one statement, no braces
aPointsArray.length=0; // clear the array itself, not just
// points from display list!
startNextLevel(); // now start level
An incorrect order of correct statements leads to a disaster. Always check your code flow, what executes now and what then, and how many times.
It doesn't look like you're removing anything from the array.
You can use a combination of .indexOf() and .splice() to remove items from an array:
function removeMc(clip:MovieClip):void
{
if(clip.parent) clip.parent.removeChild(clip);
// Also remove from array.
var index:int = aPointsArray.indexOf(clip);
aPointsArray.splice(index, 1);
}
It might also be worth simply emptying the array when you startNextLevel():
private function startNextLevel():void
{
aPointsArray.length = 0;
//add points to next stage
addPointsToStage();
}
Just assign your array to null value. so that array will start from begining whenever you require. i hope the following code code would helps you.
var nPoints:Number = 5;
var points:poin;
var aPointsArray:Array;
var startPoint:Number = 0;
var xSpacing:Number = 20;
var ySpacing:Number = 20;
addPointsToStage();
function addPointsToStage():void
{
aPointsArray = null;
aPointsArray = new Array();
for (var i:int = 0; i < 6; i++)
{
trace(aPointsArray.length);
points = new poin();
addChild(points);
points.x = 100+ (xSpacing * i);
points.y = 200 - (ySpacing * i);
aPointsArray.push(points);
}
}

Array is being NULL, don't know how

trace (suallar); - is written 2 times
1st time - HERE IT SHOWS ALL THE ELEMENTS OF THE ARRAY suallar
2nd time - BUT HERE THIS ARRAY SEEMS TO BE EMPTY, EVEN THOUGH I DIDN'T MANIPULATE WITH IT OR MAKE IT EQUAL TO ANYTHING I MANIPULATE WITH IN BETWEEN
var suallar:Array = new Array();
var i:int;
var cavablar:Array=new Array();
suallar.push(["sual1", "duz1", "sehv11", "sevh12", "sevh13","sevh14"]);
suallar.push(["sual2", "duz2", "sehv21", "sevh22","sevh23","sevh24" ]);
suallar.push(["sual3", "duz3", "sehv31", "sevh32","sevh33","sevh34"]);
suallar.push(["sual4", "duz4", "sehv41", "sevh42","sevh43","sevh44"]);
suallar.push(["sual5", "duz5", "sehv51", "sevh52","sevh53","sevh54"]);
var cavablar_temp:Array = suallar.concat();
for (i=0; i<suallar.length; i++){
cavablar_temp[i].shift();
}
trace (suallar);
for (i=0; i<suallar.length;i++){
var number_array:Array = cavablar_temp[i];
var final_array:Array = [];
var count_selected:int = 5;
for (var u = 0; u < count_selected; u++)
{
if (number_array.length == 0)
{
break;
}
else
{
final_array.push(number_array.splice(Math.floor(Math.random() * number_array.length), 1)[0]);
}
}
cavablar.push(final_array);}
trace(cavablar.join("\n"));
trace (suallar);
As per the Array.splice() documentation:
Adds elements to and removes elements from an array. This method modifies the array without making a copy.
When you do number_array.splice() in the middle of your loop, you're modifying the original arrays you pushed to suallar.
Take a look at Array.slice(), which returns a new array without modifying the original.

Reordering an array in flash as3

I have an array of objects, each of which is assigned an ID when it is first created. I give the user the ability to visually reorder the objects, which changes their position in the array. They then have the option to save that order using a flash sharedObject or "cookie" and then later, if they reopen the flash file, I want them to be able to hit a button to restore that order. I'm just not sure what the syntax would be to set the object's index within the array. Here's my code:
VARIABLES:
var project_settings = SharedObject.getLocal("settings"); //saves all project settings for the next time the file is opened
var project_order:Array = []; //saves project order for the next time the file is opened
var project_display:Array = []; //saves whether each project should be displayed or hidden for the next time the file is opened
SAVE CODE:
function saveOrder(){
for (var i=0;i<project_array.length;i++){
project_order[i] = project_array[i].id;
project_display[i] = project_array[i].projectThumb.thumbActive;
}
project_settings.data.order = project_order;
project_settings.data.active = project_display;
//trace (project_settings.data.active[1]);
project_settings.flush(); //saves most recent "cookie"
}
RESTORE CODE:
function loadOrder(){
for (var i=0;i<project_array.length;i++){
/* NEED THE CODE THAT GOES HERE. BASICALLY, PROJECT_ARRAY[i] SHOULD BE THE ITEM WITH AN ID EQUAL TO PROJECT_SETTINGS.DATA.ORDER[i] */
}
}
Something like this should work:
function loadOrder()
{
var dict = new Dictionary();
for (var i = 0; i < project_array.length; i++)
dict[project_array[i].id] = project_array[i];
project_array = [];
for (var i = 0; i < project_settings.data.order.length; i++)
project_array[i] = dict[project_settings.data.order[i]];
}
Just load in your array and sort on the ID. Something like this should work:
private function _loadArray():void
{
// fill in your array
project_array.sort( this._sortFunc );
}
// replace the * by whatever your object type is
private function _sortFunc( a:*, b:* ):int
{
return a.id - b.id;
}
More info: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#sort()
Or even the sortOn() function (which might be easier) should work:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#sortOn()

pushing or adding arrays as values into a multi-dimensional array in actionscript 3.0

I am running into some trouble adding an array into another array to create a multi-dimensional array.
The code appears as below:
var slideDataArray:Array = new Array();
var slideShowDataArray:Array = new Array();
slideDataArray[0] = xmlData.SlideShowParameters.SlideShowImagesDirectory;
slideDataArray[1] = xmlData.SlideShowParameters.SlideShowTimeInterval.valueOf();
slideDataArray[2] = xmlData.SlideShowParameters.SlideShowWidth.valueOf();
slideDataArray[3] = xmlData.SlideShowParameters.SlideShowHeight.valueOf();
slideDataArray[4] = slides.length();
slideShowDataArray[0] = slideDataArray;
for (i = 0; i < slides.length(); i++) {
// Read data from Slides tag in the XML file into slideDataArray
slideDataArray[0] = slides[i].SlideImage.toString();
slideDataArray[1] = slides[i].SlideText.toString();
slideDataArray[2] = slides[i].SlideLink.toString();
// Input the data from slideDataArray into the array for the slideshow (slideShowDataArray)
slideShowDataArray[i + 1] = slideDataArray;
}
// end of FOR loop
I am looking for a means of placing the slideDataArray into a 'slot' or value of slideShowDataArray so that I can in the end pass the slideShowDataArray as a parameter to another function.
As of now, the last slideDataArray appears 11 times (the loop runs 11 times) in slideShowDataArray and the way the code is written the slideDataArray is unique every iteration of the loop.
Any help is appreciated.
Thanks in advance...
Remember you are not adding an array, but a reference to slideDataArray to your multidimensional array. Each reference points to the same array - which just contains different values on every iteration of the loop. In other words: Every time you add that reference, you "link" to the same address in memory.
To get around this, move the inner part of the loop to a separate function and create a new local array on every call:
function createDataArray ( slide:Object ) : Array {
var slideDataArray:Array = [];
slideDataArray[0] = slide.SlideImage.toString();
slideDataArray[1] = slide.SlideText.toString();
slideDataArray[2] = slide.SlideLink.toString();
return slideDataArray;
}
Then call it from your loop:
for (i = 0; i < slides.length(); i++) {
slideShowDataArray.push( createDataArray (slides[i]) );
}
You should end up with 11 unique arrays instead of one array that is overwritten 11 times.

Resources