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


-- demo\rosetta\Playing_cards.exw
function deal(sequence deck, integer nhands, integer ncards)
sequence hands = repeat({},nhands)
    for n=1 to ncards do
        for h=1 to nhands do
            hands[h] &= deck[1]
            deck = deck[2..$]
        end for
    end for
    return {deck,hands}
end function

--console:
procedure show_cards(sequence s)
    for i=1 to length(s) do
        integer c = s[i]-1
        string sep = iff(mod(i,13)=0 or i=length(s)?"\n":" ")
        puts(1,"23456789TJQKA"[mod(c,13)+1]&"SHDC"[floor(c/13)+1]&sep)
    end for
end procedure

sequence deck, hands

procedure console_show()
    for i=1 to length(hands) do
        printf(1,"hand%d:\n",{i})
        show_cards(sort(hands[i]))
    end for
    printf(1,"remaining cards(%d):\n",{length(deck)})
    show_cards(deck)
end procedure

--GUI:
function cards_to_utf8(sequence s)
sequence utf32 = {}
    for i=1 to length(s) do
        integer c = s[i]
        integer pip = mod(c,13)
        utf32 &= 0x1F0A1 + pip+(pip>10) + floor((c-1)/13)*#10
        if mod(i,12)=0 and i<length(s) then
            utf32 &= '\n'
        end if
    end for
    return utf32_to_utf8(utf32)
end function

include pGUI.e

constant FONT = sprintf(`FONT="Arial, %d"`,{92})

procedure gui_show()
    IupOpen()
    IupSetGlobal("UTF8MODE","YES")

    Ihandles lh = {}
    for i=1 to length(hands) do
        Ihandle l = IupLabel(sprintf("hand%d:",{i}))
        Ihandle h = IupLabel(cards_to_utf8(sort(hands[i])),FONT)
        lh &= l&h
    end for
    lh &= IupLabel("remaining cards:")
    lh &= IupLabel(cards_to_utf8(deck),FONT)

    Ihandle dlg = IupDialog(IupVbox(lh))
    IupShow(dlg)
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure

constant DECKSIZE=52
deck = shuffle(tagset(DECKSIZE))
show_cards(deck)
{deck,hands} = deal(deck,2,9)
console_show()
gui_show()
