How do you make buttons that have a specific length? - arrays

I'm having difficulty using a customlistrenderer class and homescreen class.
Here's my Homescreen class that contains the function generateData(), which is supposed to display a scroller of 22 buttons.
private function generateData(): void{
var list: List = new List();
list.width = 235;
list.height = 380;
list.name = "HomeScreenList";
this.addChild(list);
var rows:int = 6;
var iterator:int = 0;
var num:int = 22;
var counter:int = 0;
var obj:Object;
var heroName:Array = ["ana", "bastion", "d.va", "genji", "hanzo", "junkrat", "lucio",
"mccree", "mei", "mercy", "pharah", "reaper", "reinhardt", "roadhog", "soldier76", "symmetra",
"torbjorn", "tracer", "widowmaker", "winston", "zarya", "zenyatta"];
var temp:Array = []
obj = new Object();
while(iterator < rows){
obj.name1 = heroName[counter];
obj.image1 = myResource.getImage(heroName[counter]);
obj.name2 = heroName[counter+1];
obj.image2 = myResource.getImage(heroName[counter+1]);
obj.name3 = heroName[counter+2];
obj.image3 = myResource.getImage(heroName[counter+2]);
obj.name4 = heroName[counter+3];
obj.image4 = myResource.getImage(heroName[counter+3]);
temp.push(obj);
counter+4;
iterator++;
}
var collection:ListCollection = new ListCollection(temp);
//assign the renderer
list.itemRendererType = CustomMenuListRenderer;
list.dataProvider = collection;
list.addEventListener(Event.CHANGE, onChange);
this.addChild(list);
list.validate();
}
and the CustomMenuListRenderer class, under the initialize() function
super.initialize();
firstButton = new Button();
this.addChild(firstButton);
firstButton.x = 20;
firstButton.y = 100;
firstButton.scale = 0.60;
secondButton = new Button();
secondButton.x = 92;
secondButton.y = 100;
secondButton.scale = 0.60;
thirdButton = new Button();
thirdButton.x = 163;
thirdButton.y = 100;
thirdButton.scale = 0.60;
fourthButton = new Button();
fourthButton.x = 235;
fourthButton.y = 100;
fourthButton.scale = 0.60;
firstButton.addEventListener(Event.TRIGGERED, onTrigger);
secondButton.addEventListener(Event.TRIGGERED, onTrigger);
thirdButton.addEventListener(Event.TRIGGERED, onTrigger);
fourthButton.addEventListener(Event.TRIGGERED, onTrigger);
The problem is since the loop displays the 4 buttons each loop, an error occurs at the 23rd button(since I only specified 22 buttons but I declared 4 buttons on the CustomMenuListRenderer class) in the 6th row.
My question is how do I fix this issue?

First question, why define num manually and not use heroName.lenght? Is more secure
var heroName:Array = ["ana", "bastion", "d.va", "genji", "hanzo", "junkrat", "lucio",
"mccree", "mei", "mercy", "pharah", "reaper", "reinhardt", "roadhog", "soldier76", "symmetra",
"torbjorn", "tracer", "widowmaker", "winston", "zarya", "zenyatta"];
var num:int = heroName.lenght;
To fix your error, you have to check is heroName index exists before to get it.
Something like :
obj = new Object();
while(iterator < rows){
var objCounter:int = 1;
while(objCounter <= 4 )
{
if( counter < heroName.lenght )
{
obj["name"+objCounter] = heroName[counter];
obj["image"+objCounter] = myResource.getImage(heroName[counter]);
}
objCounter++;
counter++;
}
temp.push(obj);
iterator++;
}

Related

Trying to access the first instance of an array in Actionscript 3

I am trying to do deat detection in actionscript 3. My idea is to create an array of dots (MovieClips) on the x axis which represents the frequency spectrum, SoundMixer.computeSpectrum(bytes, true, 0); is set to true. How do I access the first dot instance of my array. I then want to check it's highest value on each current frame and and measure it against the last value. I think I need to set a threshold and when the value is within the threshold call that a beat....I'm lost, can anybody point me in the right direction..
Thanks in advance.
var snd: Sound = new Sound();
var req: URLRequest = new URLRequest("mySong.mp3");
snd.load(req);
var channel: SoundChannel;
channel = snd.play();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
snd.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
const CHANNEL_LENGTH: int = 256;
const BUFFER_LENGTH: int = 512;
var dot:Dot;
dot.cacheAsBitmap = true;
var myArray:Array = new Array();
var bytes:ByteArray = new ByteArray();
function onEnterFrame(event: Event): void
{
SoundMixer.computeSpectrum(bytes, true, 0);
for (var i:int = 0; i < CHANNEL_LENGTH; i+=8) // channel_length = 256
{
var sampleValue:Number = bytes.readFloat();
dot = new Dot();
dot.x = i * 2;
dot.y = sampleValue * 250; //50 + (i * 30)
addChild(dot);
myArray.push(dot);
}
}
I am not sure what excetly you are going to do.
But if you want to do a sound spectrum visualizer, I think your direction is right.
I follow what you do and get result like this: (http://www.imageupload.co.uk/5M3n) Those dots will dance with the music
just move dot.cacheAsBitmap = true; after dot = new Dot(); or you can remove it.
and in Dot class, don't forget to dispose itself after some time.
But actually I dont need to use myArray at all.
Here is my code:
import flash.events.Event;
var snd: Sound = new Sound();
var req: URLRequest = new URLRequest("mySong.mp3");
snd.load(req);
var channel: SoundChannel;
channel = snd.play();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
snd.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
const CHANNEL_LENGTH: int = 256;
const BUFFER_LENGTH: int = 512;
var dot:Dot;
var myArray:Array;
var bytes:ByteArray = new ByteArray();
function onEnterFrame(event: Event): void
{
SoundMixer.computeSpectrum(bytes, true, 0);
myArray = [];
for (var i:int = 0; i < CHANNEL_LENGTH; i+=8) // channel_length = 256
{
var sampleValue:Number = bytes.readFloat();
dot = new Dot();
dot.cacheAsBitmap = true;
dot.x = i * 2;
dot.y = sampleValue * stage.StageHeight;
addChild(dot);
myArray.push(dot);
}
var firstElement:Dot = myArray.length>0?myArray[0]:null;
if(firstElement)
{
handleWithFirstElement(firstElement);
}
}
function onPlaybackComplete(e:Event):void
{
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}
function handleWithFirstElement(ele:Dot):void
{
//your code
}
And in Dot class:
flash.utils.setTimeout(this.parent.removeChild, 100, this);
// Run this just after added on Stage

Flash CS3 Deleting objects on stage

Ok so I have this minigame inside my main timeline. The minigame creates a bunch of objects dynamically inside an array using addChild(new a0), new a1, new a2 etc... Anyways at the end of the game, there's an option to either restart (resets scores and goes back to starting frame) or finished (goes back a few frames to the "main screen" which is on a different layer and back a few frames. If I choose either options, any of the objects that werent deleted from playing the game (getting a match) are left on the stage even when restarting or going back to the main frame. I've tried various methods of calling removeChild, setting arrays to empty and what not and I can't seem to figure out how to remove them. With the code that I will display here, I get this error:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at mousiesDay_fla::MainTimeline/clearGame()[mousiesDay_fla.MainTimeline::frame258:11]
at mousiesDay_fla::MainTimeline/tryAgain()[mousiesDay_fla.MainTimeline::frame258:29]
Here is the code
stop();
scoreWindow.visible = false;
scoreWindowText.visible = false;
finBtn.visible = false;
tryBtn.visible = false;
finBtn.removeEventListener(MouseEvent.CLICK, finished);
tryBtn.removeEventListener(MouseEvent.CLICK, tryAgain);
function clearGame() {
for( var i:int = 0; i < numClips; i++ ) {
removeChild( myClip[i] );
}
myClip.length = 0;
scoreWindow.visible = false;
scoreWindowText.visible = false;
finBtn.visible = false;
tryBtn.visible = false;
finBtn.removeEventListener(MouseEvent.CLICK, finished);
tryBtn.removeEventListener(MouseEvent.CLICK, tryAgain);
}
function finished(evt:MouseEvent) {
clearGame();
gotoAndPlay(256);
}
function tryAgain(evt:MouseEvent) {
clearGame();
gotoAndPlay(257);
}
backBtn.addEventListener(MouseEvent.CLICK, goBack);
function goBack(evt:MouseEvent) {
gotoAndPlay(256);
}
import flash.utils.*;
var myTimer:Timer = new Timer(1000);
myTimer.addEventListener("timer", timedFunction);
myTimer.start();
function timedFunction(eventArgs:TimerEvent) {
var tc:int= 31 - myTimer.currentCount;
pTime.text = tc.toString();
if (myTimer.currentCount > 30) {
for (var k:Number = 0; k < numClips; k++) {
myClip[k].removeEventListener("mouseDown", pieceMove);
myClip[k].removeEventListener("mouseUp", pieceMove);
}
myTimer.reset();
myTimer.stop();
scoreWindow.visible = true;
scoreWindowText.visible = true;
addChild(scoreWindow);
addChild(scoreWindowText);
scoreWindowText.text = "Congratulations. You got " + upgameScore + " / 10. \nClick FINISHED to go back or TRY AGAIN to restart.";
finBtn.visible = true;
finBtn.addEventListener(MouseEvent.CLICK, finished);
addChild(finBtn);
tryBtn.visible = true;
tryBtn.addEventListener(MouseEvent.CLICK, tryAgain);
addChild(tryBtn);
}
}
var mySound:Sound = new correctSound();
upgameScore = 0;
var numClips:Number = 7;
var myClip = new Array(numClips);
myClip[0] = addChild(new a0());
myClip[1] = addChild(new a1());
myClip[2] = addChild(new a2());
myClip[3] = addChild(new a3());
myClip[4] = addChild(new a4());
myClip[5] = addChild(new a5());
myClip[6] = addChild(new a6());
//myClip[7] = addChild(new a7());
//myClip[8] = addChild(new a8());
//myClip[9] = addChild(new a9());
myClip[0].name = "piece0";
myClip[1].name = "piece1";
myClip[2].name = "piece2";
myClip[3].name = "piece3";
myClip[4].name = "piece4";
myClip[5].name = "piece5";
myClip[6].name = "piece6";
//myClip[7].name = "piece7";
//myClip[8].name = "piece8";
//myClip[9].name = "piece9";
var nph = new Array(numClips);
nph[0] = nph0_mc;
nph[1] = nph1_mc;
nph[2] = nph2_mc;
nph[3] = nph3_mc;
nph[4] = nph4_mc;
nph[5] = nph5_mc;
nph[6] = nph6_mc;
//nph[7] = nph7_mc;
//nph[8] = nph8_mc;
//nph[9] = nph9_mc;
var tpg = new Array(numClips);
tpg[0] = tpg0_mc;
tpg[1] = tpg1_mc;
tpg[2] = tpg2_mc;
tpg[3] = tpg3_mc;
tpg[4] = tpg4_mc;
tpg[5] = tpg5_mc;
tpg[6] = tpg6_mc;
//tpg[7] = tpg7_mc;
//tpg[8] = tpg8_mc;
//tpg[9] = tpg9_mc;
var x0 = myClip[0].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y0 = myClip[0].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x1 = myClip[1].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y1 = myClip[1].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x2 = myClip[2].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y2 = myClip[2].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x3 = myClip[3].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y3 = myClip[3].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x4 = myClip[4].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y4 = myClip[4].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x5 = myClip[5].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y5 = myClip[5].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x6 = myClip[6].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y6 = myClip[6].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
/*var x7 = myClip[7].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y7 = myClip[7].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x8 = myClip[8].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y8 = myClip[8].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
var x9 = myClip[9].x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
var y9 = myClip[9].y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;*/
var j:Number;
for (var k:Number = 0; k < numClips; k++) {
myClip[k].addEventListener("mouseDown", pieceMove);
myClip[k].addEventListener("mouseUp", pieceMove);
}
function pieceMove(evt:Event):void {
if (evt.type == "mouseDown") {
//mySound.play();
evt.target.startDrag();
}
else if (evt.type == "mouseUp") {
//mySound.play();
evt.target.stopDrag();
for (j = 0; j < numClips; j++) {
if (evt.target.name == "piece" + j &&
evt.target.hitTestObject(nph[j]) == true) {
removeChild(myClip[j]);
nph[j].alpha = 0;
tpg[j].alpha = 100;
if (j == 2) {
setChildIndex(tpg[j], 1);
}
upgameScore++;
}
else if (evt.target.name == "piece" + j) {
evt.target.x = Math.floor(Math.random()*(1+530-20))+20;//Math.random()*400+50;
evt.target.y = Math.floor(Math.random()*(1+380-20))+20;//Math.random()*50+50;
}
}
scor.text = upgameScore.toString();
if (upgameScore == 10) {
msgbox.text = "Congratulations !";
for (var k:Number = 0; k < numClips; k++) {
myClip[k].removeEventListener("mouseDown", pieceMove);
myClip[k].removeEventListener("mouseUp", pieceMove);
}
myTimer.reset();
myTimer.stop();
scoreWindow.visible = true;
scoreWindowText.visible = true;
addChild(scoreWindow);
addChild(scoreWindowText);
scoreWindowText.text = "Congratulations. You got " + upgameScore + " / 10. \nClick FINISHED to go back or TRY AGAIN to restart.";
}
}
}
I should mention that if you look near the end of the code where I do the testHitObject and then call removeChild after that, THAT particular delete works and removes the object from the frame.
Solved this one too. I should probably spend a bit more time before I post these.
As it turns out, when objects were being matched they were being removed as per the removeChild() function that was working. What I was doing then was iterating through the array and attempting to remove some objects that were already removed. So what i did was kept an array that matched the objects and when they were removed, changed a flag to 0. Then at the end, iterate through the new array and if there's a 1, remove the child object from the array with the same index. If there's a 0, ignore it. Now it works.

as3 how to remove/ move position of graphics from reset array

I am trying to reset a scene an move every thing to its original position the reset function resets the array adds the nape bodies back to the stage and attaches the graphics but the original graphics still are on the stage in whatever position they were in when reset was called
private var brickGraphic:MovieClip = new Brick();
private var brick:Body;
private var brickArray:Array;
private function setUp():void
{
brickArray = new Array ;
for (var i:int = 0; i < 10; i++)
{
var brick:Body = new Body(BodyType.DYNAMIC);
var brickShape:Polygon = new Polygon(Polygon.box(10,25));
var brickGraphic = new Brick();
brickGraphic.width = 10;
brickGraphic.height = 25;
addChild(brickGraphic);
brickGraphic.cacheAsBitmap = true;
brick.shapes.add(brickShape);
brick.position.setxy(450, ((ag ) - 30 * (i + 0.5)));
brick.angularVel = 0;
brick.shapes.at(0).material.elasticity = .5;
brick.shapes.at(0).material.density = 150;
brick.cbTypes.add(brickType);
brick.space = space;
brickGraphic.stop();
brick.userData.sprite = brickGraphic;
brick.userData.sprite.x = brick.position.x;
this.brickArray.push(brick);
}
private function reset():void
{
if (contains(brickGraphic)) removeChild(brickGraphic);
space.clear();
setUp();
}
}
this is the final issue i am having on this app and your help would be greatly appreciated
That's because you are not removing them with removeChild.
You need to call removeChild for each brickGraphic object you add to the stage.
Something like :
private function setUp():void
{
brickArray = [];
for (var i:int = 0; i < 10; i++)
{
var brick:Body = new Body(BodyType.DYNAMIC);
var brickShape:Polygon = new Polygon(Polygon.box(10,25));
var brickGraphic = new Brick();
brickGraphic.width = 10;
brickGraphic.height = 25;
addChild(brickGraphic);
brickGraphic.cacheAsBitmap = true;
brick.shapes.add(brickShape);
brick.position.setxy(450, ((ag ) - 30 * (i + 0.5)));
brick.angularVel = 0;
brick.shapes.at(0).material.elasticity = .5;
brick.shapes.at(0).material.density = 150;
brick.cbTypes.add(brickType);
brick.space = space;
brickGraphic.stop();
brick.userData.sprite = brickGraphic;
brick.userData.sprite.x = brick.position.x;
this.brickArray.push(brick);
}
}
private function removeAllBricks():void
{
for(var i:int=0; i<brickArray.length; i++)
{
var dp:DisplayObject = brickArray[i].userData.sprite as DisplayObject;
if(dp && dp.parent)
dp.parent.removeChild(dp);
}
}
private function reset():void
{
removeAllBricks();
space.clear();
setUp();
}

as3 how to remove graphics from removed nape bodies

i have attached multiple instances of a moviecCip to multiple nape bodies and have a reset button to restore them to their original position. when the reset function is called the bodies are reset and have the mc attached to them. the problem is the original mc are still on the stage frozen in the position thy were when reset was called.
private var brickGraphic:MovieClip = new Brick();
private var brickArray:Array;
private function setUp():void
{
var brickType:CbType = new CbType();
var w:int = stage.stageWidth;
var h:int = stage.stageHeight;
var ag:int = stage.stageHeight - 58;// height ofarea above ground
brickArray = new Array ;
//wall
for (var i:int = 0; i < 10; i++)
{
var brick:Body = new Body(BodyType.DYNAMIC);
var brickShape:Polygon = new Polygon(Polygon.box(10,25));
var brickGraphic:MovieClip = new Brick();
brickGraphic.width = 10;
brickGraphic.height = 25;
addChild(brickGraphic);
brickGraphic.cacheAsBitmap = true;
brick.shapes.add(brickShape);
brick.position.setxy(450, ((ag ) - 30 * (i + 0.5)));
brick.angularVel = 0;
brick.shapes.at(0).material.elasticity = .5;
brick.shapes.at(0).material.density = 150;
brick.cbTypes.add(brickType);
brick.space = space;
brickGraphic.stop();
brick.userData.sprite = brickGraphic;
brick.userData.sprite.x = brick.position.x;
brick.userData.sprite.y = brick.position.y;
this.brickArray.push(brick);
}
}
private function reset():void
{
space.clear();
setUp();
}
any help would be greatly appreciated
Add a statement that will remove that linked MovieClip from those nape bodies into your reset() function. I expect this is what you need:
private function reset():void
{
if (contains(brick.userData.sprite)) removeChild(brick.userData.sprite);
space.clear();
setUp();
}

Actionscript 3: Trying to create a randomized array

im trying to create a randomized array that will change the position of my pictures(in the tilelist) each time the application is launched. Hope you understand what im looking for, and i dont really understand how to link code correctly here :/
I think its easier simply copying into flash and view from there
thanks :)
Here's my code:
flash.events.MouseEvent;
btn_back.addEventListener(MouseEvent.CLICK, ftilbake);
function ftilbake(evt:MouseEvent)
{
gotoAndStop(1);
}
var heroArray:Array = new Array();
var randomizeArray:Array = new Array();
createArrays()
function createArrays()
{
heroArray[0] = new Array("Rumble","Garen","Lulu","Corki","Warwick");
heroArray[1] = new Array("Bilder/Champions/Rumble.jpg","Bilder/Champions/Garen.jpg","Bilder/Champions/Lulu.jpg","Bilder/Champions/Corki.jpg","Bilder/Champions/Warwick.jpg");
heroArray[2] = new Array("Bilder/Champions/Rumble1.jpg","Bilder/Champions/Garen1.jpg","Bilder/Champions/Lulu1.jpg","Bilder/Champions/Corki1.jpg","Bilder/Champions/Warwick1.jpg");
heroArray[3] = new Array("the Mechanized Menace","the Might of Demacia","the Fae Sorceress","the Daring Bombardier","the Blood Hunter");
heroArray[4] = new Array(0,0,0,0,0);
heroArray[5] = new Array("Rumble.wav","Garen.wav","Lulu.wav","Corki.wav","Warwick.wav");
randomizeArray[0] = new Array();
randomizeArray[1] = new Array();
randomizeArray[2] = new Array();
randomizeArray[3] = new Array();
randomizeArray[4] = new Array();
//randomizing the positions in the array(?)
var randomPos:int = 0;
for (var i:int = 0; i < heroArray.length; i++)
{
randomPos = int(Math.random() * heroArray[0].length);
while (randomizeArray[randomPos][0] != null)
{
randomPos = int(Math.random() * heroArray.length);
}
}
}
var totalKlikk:int = 0;
for (var teller1:int = 0; teller1 <heroArray[0].length; teller1++)
{
leagueChamps.addItem({label:heroArray[0][teller1], source:heroArray[1][teller1]});
}
leagueChamps.columnWidth = 80;
leagueChamps.rowHeight = 80;
leagueChamps.columnCount = 5;
leagueChamps.rowCount = 1;
leagueChamps.direction = "horizontal";
leagueChamps.addEventListener(MouseEvent.CLICK, bildeKlikk);
function bildeKlikk(evt:MouseEvent)
{
var element:Object = leagueChamps.selectedItem;
var fil:String = element.source;
txtChHero.visible = false;
totalKlikk++;
if (totalKlikk <11)
{
for (teller1 = 0; teller1 <heroArray[0].length; teller1++)
{
if (heroArray[1][teller1] == fil)
{
heroArray[4][teller1]++;
if (heroArray[4][teller1] == 1)
{
txtBox1.visible = true;
txtBox2.visible = true;
leagueShow.source = heroArray[2][teller1];
txtBox1.text = heroArray[0][teller1];
txtBox2.text = heroArray[3][teller1];
}
if (heroArray[4][teller1] == 2)
{
txtBox1.visible = true;
txtBox2.visible = true;
leagueShow.source = heroArray[2][teller1];
txtBox1.text = heroArray[0][teller1];
txtBox2.text = heroArray[3][teller1];
heroArray[5][teller1].play();
}
if (heroArray[4][teller1] == 3)
{
bildeKlikk3();
}
}
}
}
else
{
txtChHero.visible = true;
txtChHero.text = "Du har klikket følgende mange ganger på de forskjellige bildene:";
txtH1.text = heroArray[4][0]
txtH2.text = heroArray[4][1]
txtH3.text = heroArray[4][2]
txtH4.text = heroArray[4][3]
txtH5.text = heroArray[4][4]
txtBox1.visible = false;
txtBox2.visible = false;
leagueShow.visible = false;
}
}
function bildeKlikk3()
{
txtBox1.visible = true;
txtBox2.visible = true;
leagueShow.source = heroArray[2][teller1];
txtBox2.text = "Ikke mer informasjon";
}
txtBox2.visible = false;
txtBox1.visible = false;
Array randomization is something which comes up very frequently in all my projects so I ended up creating a static method in my Array utility class for it.
It uses the Fisher–Yates shuffle which is supposed to be the most unbiased (and efficient?) algorithm for shuffling the content of an array. There could be faster ways of doing it (like using the array.sortOn() method, but I am not sure how unbiased a result they get compared to this one.)
The shuffle method:
/**
* shuffle the given array
* #param array
* #return
*/
public static function shuffle(array:Array):Array
{
var index :int;
var item :*;
var limit :int = array.length as int;
for (var i:int = limit-1; i >= 0 ; --i)
{
index = Math.floor(Math.random() * (i + 1));
item = array[index];
array[index] = array[i];
array[i] = item;
}
return array;
}
Example:
var myArray:Array = new Array("Red","Orange","Yellow","Green","Blue");
myArray = ArrayUtils.shuffle(myArray);
where ArrayUtils is the name of the Array Utility class I use. You can simply use the function directly if you don't want to use a utility class of course.
Try this
while (heroArray.length > 0) {
randomizeArray.push(heroArray.splice(Math.round(Math.random() * (heroArray.length - 1)), 1)[0]);
}
Just instatiate randomizeArray though, and don't fill it with empty Arrays like in ur source!
I recommend creating a single object to hold related data, and using a single Array/Vector of that object type.
To answer your question, randomizing an array is fairly easy to do with array.sort() and a random selection function. This method can also be used to randomize any array. you don't need to splice arrays or iterate either.
function sortOnRandom(a:Object, b:Object):Number{
if(Math.random() > 0.5){
return 1;
}else{
return -1;
}
}
myArray.sort(sortOnRandom);

Resources