Tuesday, November 27, 2007

How to shuffle deck of cards


When making some Flash game there is sometimes need for Arrays manipulation. For example if you make game with cards, you want to find a way how to shuffle set of 52 cards. Let's say your array is:

a = Array("1h", "2h", ..., "14h", ..., "14d");

now, you can use next function to shuffle your cards array:

1.function shuffle( b:Array ) : Array{
2.     var temp:Array = new Array();
3.     var templen:Number;
4.     var take:Number;
5.     while (b.length > 0) {
6.         take = Math.floor(Math.random()*b.length);
7.         templen = temp.push(b[take]);
8.         b.splice(take,1);
9.     }
10.   return temp;
11.}


What this code means? I hope it is clear I only have to explain lines in while loop, because everything else is easy to understand. So, while loop will work until there are elements in start array, and do remember that we take one element from that array in every pass. With line 6 we choose randomly one element of start array. Then in 7, we push that element in first empty place in result array and than in line 8, we exclude same element from start array. In every while loop pass, start array is shorter for 1 element and result array is longer for 1 element. Since we choose element randomly in the end function returns shuffled array. Simply as that.

You can test this function with this code:

trace(a);
trace(a.length);

function onMouseUp() {
    var c:Array = new Array();
    c = shuffle(a);
    trace(c);
}


Download this function and few more here.
Enjoy!

Posted by flanture at 03:21:34 | Permanent Link | Comments (0) |
Comments
Write a comment