Task

Create a data structure and the associated methods to define and manipulate a deck of   playing cards.

The deck should contain 52 unique cards.

The methods must include the ability to:

   make a new deck
   shuffle (randomize) the deck
   deal from the deck
   print the current contents of a deck 
Each card must have a pip value and a suit value which constitute the unique value of the card.

Related tasks:

 Card shuffles
 Deal cards_for_FreeCell
 War Card_Game
 Poker hand_analyser
 Go Fish


#define NSWAPS 100
 
type card
    suit : 2 as ubyte
    face : 4 as ubyte
    'the remaining 2 bits are unused
end type
 
dim shared as string*8 Suits(0 to 3) = {"Spades", "Clubs", "Hearts", "Diamonds"}
dim shared as string*8 Faces(0 to 12) = {"Ace", "Two", "Three", "Four", "Five",_
     "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}
 
sub newdeck( deck() as card )
    'produces an unshuffled deck of 52 cards
    redim preserve deck(0 to 51) as card
    for s as ubyte = 0 to 3
        for f as ubyte = 0 to 12
            deck(13*s + f).suit = s
            deck(13*s + f).face = f
        next f
    next s 
end sub
 
function deal( deck() as card ) as card
    'deals one card from the top of the deck, returning that
    'card and removing it from the deck
    dim as card dealt = deck(ubound(deck))
    redim preserve deck(0 to ubound(deck) - 1)
    return dealt
end function
 
function card_name( c as card ) as string
    'returns the name of a single given card
    return Faces(c.face) + " of " + Suits(c.suit)
end function
 
sub print_deck( deck() as card )
    'displays the contents of the deck,
    'with the top card (next to be dealt) first
    for i as byte = ubound(deck) to 0 step -1
        print card_name( deck(i) )
    next i
end sub
 
sub shuffle_deck( deck() as card )
    dim as integer n = ubound(deck)+1
    for i as integer = 1 to NSWAPS
        swap deck( int(rnd*n) ), deck( int(rnd*n) )
    next i
end sub
 
redim as card deck(0 to 0)  'allocate a new deck
newdeck(deck())             'set up the new deck
print "Dealing a card: ", card_name( deal( deck() ) )
for j as integer = 1 to 41  'deal another 41 cards and discard them
    deal(deck())
next j
shuffle_deck(deck())        'shuffle the remaining cards
print_deck(deck())          'display the last ten cards