-2

I copy some code and want to use it but I don't understand. this code is about How to randomly swap shapes' positions in specific locations. anyone can explain in simple how this code works?

function randomSort(a:*, b:*):Number
{
    if (Math.random() < 0.5) return -1;
    else return 1;
}

// Push 12 positions as new Point() in an array.
var positions:Array = [ new Point(12, 42), new Point(43, 56), new Point(43,87) ]; // ...add 12 positions
var mcs:Array = [mc1, mc2, mc3]; // ...add 12 mcs

positions.sort(randomSort);

// link randomized position to MovieClips:
for (var i:int = 0, l:int = positions.length; i < l, i++ ) {
    var mc:MovieClip = mcs[i];
    var point:Point = positions[i];
    mc.x = point.x;
    mc.y = point.y;
}
Tamara
  • 23
  • 7

1 Answers1

0

There are two lists: MovieClips and Points. The provided script randomizes one of the lists, so each MovieClip get a random Point out of the given ones.

The idea of random-sorting could be confusing a bit. The Array.sort() method is intended to organize Array's elements on given criteria, but if you give a random-based criteria instead, the elements are mixed with no predefined order.

The other (and probably more understandable) way to do the thing is to match a fixed MovieClip to a random Point, then remove matched pair from the respective lists, then proceed until there are items left.

var P:Array = [new Point(12, 42), new Point(43, 56), new Point(43,87)];
var M:Array = [mc1, mc2, mc3];

// Do while there are items to process.
while (M.length)
{
    // Get the last MovieClip and remove it from the list.
    var aMC:MovieClip = M.pop();

    // Produce a random Point.
    var anIndex:int = Math.random() * P.length;
    var aPo:Point = P[anIndex];

    // Remove the selected Point from its list.
    P.splice(anIndex, 1);

    // Move the selected MovieClip to the selected Point coordinates.
    aMC.x = aPo.x;
    aMC.y = aPo.y;
}
Organis
  • 7,243
  • 2
  • 12
  • 14
  • what's the function of ````P.splice();```` and ````M.pop();````? @Organis – Tamara Sep 14 '19 at 03:19
  • They are inbuilt functionality of an Array you can find it here: https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html# – user1234567 Sep 16 '19 at 04:03