Creating, Randomising and Dealing a Pack of Cards
- Tutorial 014
This very clever algorithm by Alan Thomas, which I have here made more explicit,
repays study to see how it works :
REM: Hand of Cards
REM: After Alan Thomas
REM: Shows explicitly how the nos 1 TO 52
REM: are converted to 4 suits of 13 cards
REM: shuffled and dealt
MODE8
INPUTTAB(1,1)"How many cards : "n
@%=6
VDU14
A$="diamondsclubs...hearts..spades.."
DIM A(52)
PRINT'"Unshuffled pack :"'
REM: Show unshuffled pack
FOR i=1 TO 52
A(i)=i
PRINTA(i);
PROCdecode(A(i))
NEXT i
PRINT'"Shuffled Pack :"'
REM: Shuffle the pack
FOR j=52 TO 2 STEP -1
r=RND(j)
temp=A(r)
A(r)=A(j)
A(j)=temp
NEXT j
REM: Display shuffled pack
FOR m=1 TO 52
PRINTSTR$(m),A(m);
PROCdecode(A(m))
NEXT m
PRINT'
REM: Deal out n cards
PRINT'"Here's your hand :"'
FOR k=52 TO (53-n) STEP -1
cardno=A(k)
PROCdecode(cardno)
NEXT k
END
:
DEF PROCdecode(cardno)
suit=cardno MOD 4
facevalue=1 + (cardno MOD 13)
PRINTfacevalue;SPC(2);" of ";
PRINTMID$(A$,(8*suit)+1,8)
ENDPROC
Annotated Listing
REM: Hand of Cards
REM: After Alan Thomas
REM: Shows explicitly how the nos 1 TO 52
REM: are converted to 4 suits of 13 cards
REM: shuffled and dealt
MODE8
INPUTTAB(1,1)"How many cards : "n
@%=6 *** Print formatting
VDU14 *** Paged Mode on - press the shift
key to make the screen scroll ***
A$="diamondsclubs...hearts..spades.." *****
See penutimate line of the program to see how this is used ****
DIM A(52) **** an Array of 52 memory locations
to store the "numbers" of the cards (1 to 52)
PRINT'"Unshuffled pack :"'
REM: Show unshuffled pack
FOR i=1 TO 52
A(i)=i *** each card number is
later converted into "1-13" of a suit - e.g. 13 is a King, 12 a Queen, 11
aJack
PRINTA(i);
PROCdecode(A(i)) *** converts
the card's "number" eg 45 into a particular card"
NEXT i
PRINT'"Shuffled Pack :"'
REM: Shuffle the pack
FOR j=52 TO 2 STEP -1
r=RND(j) *** This is the clever
bit which does the shuffling ***
temp=A(r)
A(r)=A(j)
A(j)=temp *** Can you see how
it works? ***
NEXT j
REM: Display shuffled pack
FOR m=1 TO 52
PRINT STR$(m),A(m); ***STR$(m)
converts the number m into a string which facilatates formatting ***
PROCdecode(A(m))
NEXT m
PRINT'
REM: Deal out n cards
PRINT'"Here's your hand :"'
FOR k=52 TO (53-n) STEP -1
cardno=A(k)
PROCdecode(cardno)
NEXT k
END
:
DEF PROCdecode(cardno) *** Look at the display
when you run the program to see how this works out ***
suit=cardno MOD 4 *** Rem 4 suits ***
facevalue=1 + (cardno MOD 13) ***Rem 13 cards
per suit ***
PRINTfacevalue;SPC(2);" of ";
PRINT MID$(A$,(8*suit)+1,8) *** The a
part of the string, A$, starting ((8*suit)+1) letters along and 8 letters
long ***
ENDPROC
Next
Tutorial
Richard Weston's Homepage