Create a stack of cards similar to a Solitaire stack in as3
I am creating a card game everything is fine but I am not able to create a sta开发者_如何学运维ck of cards as follows:
If I have 4 cards that are represented in an array such as 4,5,6,7 of Spades then I want the card with the least priority to be placed on top and the highest priority card placed behind the first one.
How can one achieve this?
I assume you know how to create the DisplayObjects (your visual cards) so I will not mention that in my answer.
I would create a holder sprite and add my cards to that to get control over the card depth order. The you add the cards to the stack sprite either by using addChild (adds the displayObject in front) or addChildAt (adds the displayObject at your wanted position). If you use addChildAt and use 0 as your index it will add it below all other displayObjects and push the one index up. If you already have the cards in the displaylist you can change the index by using setChildIndex.
var cardList : Array;
var cardStack : Sprite = new Sprite();
addChild(cardStack);
for(var i : int = 0 ; i < cardList.length ; i++)
{
// adds it at below all displayObject in "cardStack"
cardStack.addChildAt(cardList[i], 0);
// adds it on top of all displayObject in "cardStack"
cardStack.addChild(cardList[i]);
}
The easiest way would be to remove all the cards from the stage using removeChildAt(...) and add them again (in the right order) using addChildAt(...).
Usign Mattias example:
var sortedCardArray:Array = [];
while (cardContainer.numChildren)
{
sortedCardArray.push(cardContainer.removeChildAt(0));
}
/*
/ This assumes that all the values of the cards
/ are numeric (2, 3, 4, 5, 6, 7, 8, 9, 10, Jack=11, Queen=12, King=13, Ace=14)
*/
sortedCardArray.sortOn("variableWithTheCardNumber", Array.NUMERIC | Array.DESCENDING);
var n:int = sortedCardArray.length;
for(var i:int = 0 ; i < n ; i++)
{
cardContainer.addChild(sortedCardArray[i]);
}
精彩评论