PDA

View Full Version : Shuffle routine



Kim Friis
16-01-2003, 02:55 PM
I'm creating a small (webbased) card game where I need a shuffle routine for my cards. I have made a small one that works if when I only have to have 1 deck, but I need to make one that can take care of x decks.
What I need as an output is a stringlist with the card id's in a random order. (0..54 (3 jokers)) So depending on how many decks, the stringlist will be count=55 or count=110 or ... (you get the meaning?)
Anybody have a simple shuffle routine for me? It would be nice if I only need to create that one stringlist that I need for the cards.

Stevie56
16-01-2003, 09:41 PM
Well, in my card routine library I have never used a stringlist for a card deck, so you’ll have to modify the following code to suit your needs.

First we have to fill the deck…..I use an array of integers (could optimise to bytes, of course, but memory in card games is not usually a problem)


procedure filldeck(var mydeck:array of integer;decksize:integer);
var t:integer;
begin
for t:=0 to decksize-1 do mydeck[t]:=t;
end;

Each card in the deck has a numbered ID from 0 to decksize-1; Thus 0=Ace of Clubs, 1= 2 of Clubs, …. and so forth.

If I wanted to have 2 decks in a single pile (maybe for a double-decked patience game), I would use the following….


procedure filldecks(var mydeck:array of integer; decksize,deckcount:integer);
var s,t:integer;
begin
for s:=0 to deckcount-1 do
for t:=0 to decksize-1 do mydeck[(decksize*s)+t]:=t;
end;


to shuffle the deck (of any size) we swap each entry in the array with another element chosen at random….


procedure shuffledeck(var mydeck:array of integer; cardcount:integer);
var s,t,u:integer;
begin
for s:=0 to cardcount-1 do //we swap each element at least once
begin
t:=random(cardcount);
u:=mydeck[s];
mydeck[s]:=mydeck[t];
mydeck[t]:=u;
end;
end;


Hope this helps a little.

Kim Friis
20-01-2003, 03:15 PM
Thanks Stevie, that looks exactly what I need. And the reason I use Stringlists is because I need to insert the values into SQL for later use so it is no problem to use an integet array.

Alimonster
20-01-2003, 03:26 PM
You might want to have a look at Dr. John Stockton's pages, specifically here (http://www.merlyn.demon.co.uk/pas-rand.htm#SDD).

Kim Friis
21-01-2003, 08:33 AM
Arh, examples with pascal code. Just what I like.