PDA

View Full Version : how would YOU code a deck of cards then shuffle them?



Elbudster
November 30th, 2004, 08:08 PM
I've been wondering that the past few days. This is how I thought of doint it...

here is how I would make the deck...



cards = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king", "ace"];
types = ["hearts", "diamonds", "clubs", "spades"];
deck = new Array();

function buildDeck() {
for (var i=0; i<cards.length; i++) {
for (var k=0; k<types.length; k++) {
var curCard = cards[i] + " of " + types[k];
deck.push(curCard);
}
}
}
buildDeck();


And here is how i would shuffle the deck



function shuffleDeck() {
var cardPos = new Array(52);
tempDeck = new Array(52);
var i=0;
while (i<deck.length) {
var ind = random(52);
if (cardPos[ind] == undefined) {
cardPos[ind] = i;
tempDeck[ind] = deck[i];
i++;
}
}
deck = tempDeck;
}
shuffleDeck();


Just curious as to how you would all go about doing it :)

Dr Warm
November 30th, 2004, 10:08 PM
won't this bit: <code>var ind = random(52);

make it so that cards will possible have the same position as each other in the array? ie card one now has position 25, then card two could (possible) have that as well?

As for the build deck, i would do it how you did :D
</code>

Elbudster
November 30th, 2004, 10:12 PM
i have a while loop run through and it checks first to see if that number position in the array is not used yet, and if it isn't then itll move that card to that number position, and if that index is already used then it reruns the loop again until it finds a location that has not yet been used

Dr Warm
November 30th, 2004, 11:21 PM
ah yep i see it know, <code>if (cardPos[ind] == undefined) {

sorry i don't really use while loops but i guess you have to for this one (well they'res other ways, such as having a position array which you remove elements from as you've selected them), yeah i tested your code now, works fine!! I haven't seen many card games in flash, keep it up!
</code>