2

I'm dealing with this problem. I have 24 movieclips (called mc1, mc2, .., mc24) and they are placed on stage in some kind of grid (6x4). I need a function, which switches positions of these movieclips (something like shuffle but with known position of other's movieclips). For example mc1.x and mc1.y would be equal to mc4.x and mc4.y etc. Thank you very much for your time and ideas!

BenMorel
  • 34,448
  • 50
  • 182
  • 322
tomiteko
  • 49
  • 1
  • 8

2 Answers2

1

Use a XOR swap. It basically goes like this:

mc1.x ^= mc4.x;
mc4.x ^= mc1.x;
mc1.x ^= mc4.x;

mc1.y ^= mc4.y;
mc4.y ^= mc1.y;
mc1.y ^= mc4.y;

Then go from there.

David
  • 877
  • 1
  • 7
  • 18
0

Do you mean something like this:

function swap(mcA:MovieClip, mcB:MovieClip):void
{
    var tempPosition:Point = new Point(mcA.x, mcA.y);
    mcA.x = mcB.x;
    mcA.y = mcB.y;

    mcB.x = tempPosition.x;
    mcB.y = tempPosition.y;
}
swap(mc1, mc4);

This will swap the positions of mc1 and mc4.

var totalItems:int = 24; // total number of items
for(var i:int = 0; i < int(totalItems/2); i++)
{
    var randomItem:String = "mc"+(int(Math.random() * (int(totalItems/2)-1)) + (int(totalItems/2)+1));
    swap(this["mc"+(i+1)], this[randomItem]);
}

This will go through the first half of the items and swap them with a random item from the 2nd half of the items.

Marcela
  • 3,728
  • 1
  • 15
  • 21
  • yeah but I need to swap positions of more than 2 movieclips, in best case of all 24, something like pexeso game - the goal is, when I run app, movieclips can not be on the same place everytime, they have to swap positions everytime – tomiteko Mar 13 '13 at 17:57
  • Ok, I updated the code to show you how you can shuffle the entire board. Basically, it's swapping each item from the first half of the board with a random item from the second half of the board. Another way to do this would be to put all of your MovieClips in an `Array`, shuffle it using `array.sort(function(a:Object,b:Object):int{return Math.random() > .5 ? -1 : 1})` and THEN assign them `x` and `y` values in an orderly fashion. – Marcela Mar 13 '13 at 18:17
  • thank you very much, I will try it as soon as I can and let you know how it works for me – tomiteko Mar 13 '13 at 18:50
  • it works perfect! There is just one little thing - last item doesn't change its position, but that's not a problem at all.. I really appreciate your help – tomiteko Mar 13 '13 at 20:50
  • The math isn't perfect since it's using `Math.random` to do the swapping. You may be better off going the other route I suggested: randomizing an array of the objects and then assigning the `x` and `y` values. – Marcela Mar 13 '13 at 21:02