Playing cards: Difference between revisions

Added Easylang
(Added Easylang)
 
(116 intermediate revisions by 54 users not shown)
Line 1:
{{task|Games}} [[Category:Cards]]
[[Category:Cards]]
Create a data structure and the associated methods to define and manipulate a deck of [[wp:Playing-cards#Anglo-American-French|playing cards]].
 
;Task:
Create a data structure and the associated methods to define and manipulate a deck of   [[wp:Playing-cards#Anglo-American-French|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, and print the current contents of a deck. :
:::*   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]]
 
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun remove-nth (i xs)
(if (or (zp i) (endp (rest xs)))
(rest xs)
Line 61 ⟶ 76:
(defun draw-from-deck (deck)
(mv (first deck) (rest deck)))
</syntaxhighlight>
</lang>
 
Example (first 4 cards of a shuffled deck):
Line 71 ⟶ 86:
4 of DIAMONDS
(NIL <state>)</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE PTR="CARD"
DEFINE MAXDECKSIZE="52"
 
TYPE Deck=[
PTR cards ;BYTE ARRAY
BYTE first,count]
 
BYTE FUNC IsEmpty(Deck POINTER d)
IF d.count=0 THEN
RETURN (1)
FI
RETURN (0)
 
BYTE FUNC IsFull(Deck POINTER d)
IF d.count=MAXDECKSIZE THEN
RETURN (1)
FI
RETURN (0)
 
BYTE FUNC Index(Deck POINTER d BYTE i)
RETURN ((d.first+i) MOD MAXDECKSIZE)
 
PROC InitEmpty(Deck POINTER d BYTE ARRAY crds)
d.cards=crds
d.first=0
d.count=0
RETURN
 
PROC InitFull(Deck POINTER d BYTE ARRAY crds)
BYTE i
 
d.cards=crds
d.first=0
d.count=MAXDECKSIZE
FOR i=0 TO MAXDECKSIZE-1
DO
crds(i)=i
OD
RETURN
 
PROC Shuffle(Deck POINTER d)
BYTE i,j,i2,j2,tmp
BYTE ARRAY crds
 
crds=d.cards
i=d.count-1
WHILE i>0
DO
j=Rand(i)
i2=Index(d,i)
j2=Index(d,j)
tmp=crds(i2)
crds(i2)=crds(j2)
crds(j2)=tmp
i==-1
OD
RETURN
 
BYTE FUNC Deal(Deck POINTER d)
BYTE ARRAY crds
BYTE c
 
IF IsEmpty(d) THEN
PrintE("Error: deck is empty!")
Break()
FI
 
crds=d.cards
c=crds(d.first)
d.count==-1
d.first==+1
IF d.first=MAXDECKSIZE THEN
d.first=0
FI
RETURN (c)
 
PROC Add(Deck POINTER d BYTE c)
BYTE ARRAY crds
BYTE i
 
IF IsFull(d) THEN
PrintE("Error: deck is full!")
Break()
FI
 
crds=d.cards
i=Index(d,d.count)
crds(i)=c
d.count==+1
RETURN
 
PROC PrintCard(BYTE c)
BYTE s,v
BYTE ARRAY fig=['J 'Q 'K 'A]
BYTE ARRAY suit=[16 96 0 123]
 
s=c/13 v=c MOD 13
IF v<=8 THEN
PrintB(v+2)
ELSE
Put(fig(v-9))
FI
Put(suit(s))
RETURN
 
PROC PrintDeck(Deck POINTER d)
BYTE i,i2
BYTE ARRAY crds
 
crds=d.cards
IF IsEmpty(d) THEN
Print("Empty")
ELSE
FOR i=0 TO d.count-1
DO
i2=Index(d,i)
PrintCard(crds(i2))
IF i<d.count-1 THEN
Put(' )
FI
OD
FI
RETURN
 
PROC Main()
BYTE LMARGIN=$52,oldLMARGIN,i,c
BYTE ARRAY crds(MAXDECKSIZE),crds1(MAXDECKSIZE),crds2(MAXDECKSIZE)
Deck d,d1,d2
 
oldLMARGIN=LMARGIN
LMARGIN=0 ;remove left margin on the screen
Put(125) PutE() ;clear the screen
 
PrintE("New deck:")
InitFull(d,crds)
PrintDeck(d) PutE() PutE()
 
PrintE("Shuffle:")
Shuffle(d)
PrintDeck(d) PutE() PutE()
 
PrintE("Deal cards:")
InitEmpty(d1,crds1) InitEmpty(d2,crds2)
FOR i=1 TO 5
DO
c=Deal(d) Add(d1,c)
c=Deal(d) Add(d2,c)
OD
Print(" Player 1: ") PrintDeck(d1) PutE()
Print(" Player 2: ") PrintDeck(d2) PutE() PutE()
 
PrintE("Deck after dealing:")
PrintDeck(d)
 
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Playing_cards.png Screenshot from Atari 8-bit computer]
<pre>
New deck:
2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣ Q♣ K♣ A♣
2♦ 3♦ 4♦ 5♦ 6♦ 7♦ 8♦ 9♦ 10♦ J♦ Q♦ K♦ A♦
2♥ 3♥ 4♥ 5♥ 6♥ 7♥ 8♥ 9♥ 10♥ J♥ Q♥ K♥ A♥
2♠ 3♠ 4♠ 5♠ 6♠ 7♠ 8♠ 9♠ 10♠ J♠ Q♠ K♠ A♠
 
Shuffle:
5♥ K♦ 2♣ 3♠ 4♣ 5♣ 9♦ J♣ 10♠ K♣ K♠ 8♦ 5♦
3♦ 4♠ 4♥ 10♦ 8♥ 3♣ A♦ 7♣ 10♥ Q♣ 6♦ 2♦ 3♥
4♦ 7♥ 7♦ J♥ 9♣ A♥ 2♠ 10♣ J♠ Q♥ 2♥ A♣ Q♦
8♣ 9♥ 9♠ 6♥ K♥ Q♠ 6♣ 5♠ A♠ 8♠ J♦ 6♠ 7♠
 
Deal cards:
Player 1: 5♥ 2♣ 4♣ 9♦ 10♠
Player 2: K♦ 3♠ 5♣ J♣ K♣
 
Deck after dealing:
K♠ 8♦ 5♦ 3♦ 4♠ 4♥ 10♦ 8♥ 3♣ A♦ 7♣ 10♥ Q♣
6♦ 2♦ 3♥ 4♦ 7♥ 7♦ J♥ 9♣ A♥ 2♠ 10♣ J♠ Q♥
2♥ A♣ Q♦ 8♣ 9♥ 9♠ 6♥ K♥ Q♠ 6♣ 5♠ A♠ 8♠
J♦ 6♠ 7♠
</pre>
 
=={{header|Ada}}==
Line 86 ⟶ 284:
* [http://www.csail.mit.edu/timeline/timeline.php?query=event&id=93 LOC was essential; Algol 68's REF was a mistake.]
 
<langsyntaxhighlight lang="algol68">MODE CARD = STRUCT(STRING pip, suit); # instance attributes #
 
# class members & attributes #
Line 160 ⟶ 358:
(init OF class deck)(deck);
(shuffle OF class deck)(deck);
print (((repr OF class deck)(deck), new line))</langsyntaxhighlight>
 
{{Out|Example output}}
<pre>((King OF Clubs), (6 OF Hearts), (7 OF Diamonds), (Ace OF Hearts), (9 OF Spades), (10 OF Clubs), (Ace OF Spades), (8 OF Clubs), (4 OF Spades), (8 OF Hearts), (Jack OF Hearts), (3 OF Clubs), (7 OF Hearts), (10 OF Hearts), (Jack OF Clubs), (Ace OF Clubs), (King OF Spades), (9 OF Clubs), (7 OF Spades), (5 OF Spades), (7 OF Clubs), (Queen OF Clubs), (9 OF Diamonds), (2 OF Spades), (6 OF Diamonds), (Ace OF Diamonds), (Queen OF Diamonds), (5 OF Hearts), (4 OF Clubs), (5 OF Clubs), (4 OF Hearts), (3 OF Diamonds), (4 OF Diamonds), (3 OF Hearts), (King OF Diamonds), (2 OF Clubs), (Jack OF Spades), (2 OF Diamonds), (5 OF Diamonds), (Queen OF Spades), (10 OF Diamonds), (King OF Hearts), (Jack OF Diamonds), (Queen OF Hearts), (8 OF Spades), (2 OF Hearts), (8 OF Diamonds), (10 OF Spades), (9 OF Hearts), (6 OF Clubs), (3 OF Spades), (6 OF Spades))</pre>
 
=={{header|APL}}==
 
<syntaxhighlight lang="apl">
deck←,'23456789TJQKA'∘.,'CDSH'
shuffle←{⍵[?⍨⍴⍵]}
</syntaxhighlight>
 
{{out}}
<pre>
deck
2C 2D 2S 2H 3C 3D 3S 3H 4C ..
shuffle deck
7H 3D 2H 9D KS 7C JH TC JS ..
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">ranks: 1..13
suits: [`♣`, `♦`, `♥`, `♠`]
 
define :card [rank, suit][
init: [
ensure ->
and? -> contains? ranks this\rank
-> contains? suits this\suit
]
 
print: [
R: ø
case [this\rank=]
when? [1] -> R: `A`
when? [11]-> R: `J`
when? [12]-> R: `Q`
when? [13]-> R: `K`
else -> R: this\rank
~{|R||this\suit|}
]
]
 
define :deck [][
init: [
this\cards: []
loop ranks 'rank ->
loop suits 'suit ->
this\cards: this\cards ++ to :card @[rank, suit]
]
]
 
shuffleUp: function [this :deck][
this\cards: shuffle this\cards
]
 
deal: function [this :deck, cnt :integer][
if cnt > size this\cards ->
panic "Not enough cards in deck"
 
cards: []
do.times: cnt [
dealt: sample this\cards
'cards ++ dealt
this\cards: remove this\cards dealt
]
return cards
]
 
; create a new deck
Deck: to :deck []
 
; and shuffle it
shuffleUp Deck
 
; deal 5 cards
print deal Deck 5</syntaxhighlight>
 
{{out}}
 
<pre>A♥ 6♣ 7♣ Q♦ K♥</pre>
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
#include
"share/HATS/atspre_staload_libats_ML.hats"
//
(* ****** ****** *)
//
abst@ype
pip_type = int
abst@ype
suit_type = int
//
abst@ype
card_type = int
//
(* ****** ****** *)
 
typedef pip = pip_type
typedef suit = suit_type
 
(* ****** ****** *)
 
typedef card = card_type
 
(* ****** ****** *)
//
extern
fun
pip_make: natLt(13) -> pip
extern
fun
pip_get_name: pip -> string
extern
fun
pip_get_value: pip -> intBtwe(1, 13)
//
extern
fun
suit_make: natLt(4) -> suit
extern
fun
suit_get_name: suit -> string
extern
fun
suit_get_value: suit -> intBtwe(1, 4)
//
overload .name with pip_get_name
overload .name with suit_get_name
overload .value with pip_get_value
overload .value with suit_get_value
//
(* ****** ****** *)
//
(*
| Two | Three | Four | Five
| Six | Seven | Eight | Nine
| Ten | Jack | Queen | King | Ace
*)
//
(*
| Spade | Heart | Diamond | Club
*)
//
(* ****** ****** *)
 
local
 
assume
pip_type = natLt(13)
 
in (* in-of-local *)
 
implement
pip_make(x) = x
implement
pip_get_value(x) = x + 1
 
end // end of [local]
 
(* ****** ****** *)
 
local
 
assume
suit_type = natLt(4)
 
in (* in-of-local *)
 
implement
suit_make(x) = x
implement
suit_get_value(x) = x + 1
 
end // end of [local]
 
(* ****** ****** *)
 
implement
pip_get_name
(x) =
(
case+
x.value()
of // case+
| 1 => "Ace"
| 2 => "Two"
| 3 => "Three"
| 4 => "Four"
| 5 => "Five"
| 6 => "Six"
| 7 => "Seven"
| 8 => "Eight"
| 9 => "Nine"
| 10 => "Ten"
| 11 => "Jack"
| 12 => "Queen"
| 13 => "King"
)
 
(* ****** ****** *)
//
implement
suit_get_name
(x) =
(
case+
x.value()
of // case+
| 1 => "S" | 2 => "H" | 3 => "D" | 4 => "C"
) (* end of [suit_get_name] *)
//
(* ****** ****** *)
//
extern
fun
card_get_pip: card -> pip
extern
fun
card_get_suit: card -> suit
//
extern
fun
card_make: natLt(52) -> card
extern
fun
card_make_suit_pip: (suit, pip) -> card
//
(* ****** ****** *)
 
extern
fun
fprint_pip : fprint_type(pip)
extern
fun
fprint_suit : fprint_type(suit)
extern
fun
fprint_card : fprint_type(card)
 
(* ****** ****** *)
 
overload .pip with card_get_pip
overload .suit with card_get_suit
 
(* ****** ****** *)
 
implement
fprint_val<card> = fprint_card
 
(* ****** ****** *)
 
overload fprint with fprint_pip
overload fprint with fprint_suit
overload fprint with fprint_card
 
(* ****** ****** *)
 
local
 
assume
card_type = natLt(52)
 
in (* in-of-local *)
//
implement
card_get_pip
(x) = pip_make(nmod(x, 13))
implement
card_get_suit
(x) = suit_make(ndiv(x, 13))
//
implement
card_make(xy) = xy
//
implement
card_make_suit_pip(x, y) =
(x.value()-1) * 13 + (y.value()-1)
//
end // end of [local]
 
(* ****** ****** *)
//
implement
fprint_pip(out, x) =
fprint!(out, x.name())
implement
fprint_suit(out, x) =
fprint!(out, x.name())
//
implement
fprint_card(out, c) =
fprint!(out, c.suit(), "(", c.pip(), ")")
//
(* ****** ****** *)
//
absvtype
deck_vtype(n:int) = ptr
//
vtypedef deck(n:int) = deck_vtype(n)
//
(* ****** ****** *)
//
extern
fun
deck_get_size
{n:nat}(!deck(n)): int(n)
//
extern
fun
deck_is_empty
{n:nat}(!deck(n)): bool(n==0)
//
overload iseqz with deck_is_empty
//
(* ****** ****** *)
//
extern
fun
deck_free{n:int}(deck(n)): void
//
overload .free with deck_free
//
(* ****** ****** *)
//
extern
fun
deck_make_full((*void*)): deck(52)
//
(* ****** ****** *)
//
extern
fun
fprint_deck
{n:nat}(FILEref, !deck(n)): void
//
overload fprint with fprint_deck
//
(* ****** ****** *)
//
extern
fun
deck_shuffle
{n:nat}(!deck(n) >> _): void
//
overload .shuffle with deck_shuffle
//
(* ****** ****** *)
//
extern
fun
deck_takeout_top
{n:pos}(!deck(n) >> deck(n-1)): card
//
(* ****** ****** *)
 
local
//
datavtype
deck(int) =
| {n:nat}
Deck(n) of
(
int(n)
, list_vt(card, n)
) // end of [Deck]
//
assume
deck_vtype(n:int) = deck(n)
//
in (* in-of-local *)
 
implement
deck_get_size
(deck) =
(
let val+Deck(n, _) = deck in n end
)
 
implement
deck_is_empty
(deck) =
(
let val+Deck(n, _) = deck in n = 0 end
)
 
(* ****** ****** *)
//
implement
deck_free(deck) =
(
let val+~Deck(n, xs) = deck in free(xs) end
) (* end of [deck_free] *)
//
(* ****** ****** *)
 
implement
deck_make_full
((*void*)) = let
//
val xys =
list_make_intrange(0, 52)
//
val cards =
list_vt_mapfree_fun<natLt(52)><card>(xys, lam xy => card_make(xy))
//
in
Deck(52, cards)
end // end of [deck_make_full]
 
(* ****** ****** *)
 
implement
fprint_deck
(out, deck) = let
//
val+Deck(n, xs) = deck
//
in
//
fprint_list_vt(out, xs)
//
end // end of [fprint_deck]
 
(* ****** ****** *)
 
implement
deck_shuffle
(deck) =
fold@(deck) where
{
//
val+@Deck(n, xs) = deck
//
implement
list_vt_permute$randint<>
(n) = randint(n)
//
val ((*void*)) =
(xs := list_vt_permute(xs))
//
} (* end of [deck_shuffle] *)
 
(* ****** ****** *)
 
implement
deck_takeout_top
(deck) = let
//
val+@Deck(n, xs) = deck
//
val+
~list_vt_cons(x0, xs_tl) = xs
//
val ((*void*)) = n := n - 1
val ((*void*)) = (xs := xs_tl)
//
in
fold@(deck); x0(*top*)
end // end of [deck_takeout_top]
 
end // end of [local]
 
(* ****** ****** *)
 
implement
main0((*void*)) =
{
//
val () =
println!
(
"Hello from [Playing_cards]!"
) (* println! *)
//
val out = stdout_ref
//
val theDeck =
deck_make_full((*void*))
//
val ((*void*)) =
fprintln!(out, "theDeck = ", theDeck)
//
val ((*void*)) =
theDeck.shuffle((*void*))
//
val ((*void*)) =
fprintln!(out, "theDeck = ", theDeck)
//
val ((*void*)) =
loop_deal(theDeck) where
{
//
fun
loop_deal{n:nat}
(
deck: !deck(n) >> deck(0)
) : void =
(
if (
iseqz(deck)
) then ((*void*))
else
let
val card =
deck_takeout_top(deck)
in
fprintln!(out, card); loop_deal(deck)
end // end of [let]
// end of [else]
)
//
} (* end of [val] *)
//
val ((*freed*)) = theDeck.free()
//
} (* end of [main0] *)
 
(* ****** ****** *)
</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">suits := ["♠", "♦", "♥", "♣"]
===Pseudo-arrays===
values := [2,3,4,5,6,7,8,9,10,"J","Q","K","A"]
<lang AutoHotkey>Loop, 52
Gui, font, s14
Gui, add, button, w190 gNewDeck, New Deck
Gui, add, button, x+10 wp gShuffle, Shuffle
Gui, add, button, x+10 wp gDeal, Deal
Gui, add, text, xs w600 , Current Deck:
Gui, add, Edit, xs wp r4 vDeck
Gui, add, text, xs , Hands:
Gui, add, Edit, x+10 w60 vHands gHands
Gui, add, UpDown,, 1
Edits := 0
 
Hands:
Gui, Submit, NoHide
loop, % Edits
GuiControl,Hide, Hand%A_Index%
 
loop, % Hands
GuiControl,Show, % "Hand" A_Index
 
loop, % Hands - Edits
{
Edits++
Random, card%A_Index%, 1, 52
Gui, add, ListBox, % "x" (Edits=1?"s":"+10") " w60 r13 vHand" Edits
While card%A_Index%
Random, card%A_Index%, 1, 52
card%A_Index% := Mod(card%A_Index%, 12) . " of " . ((card%A_Index% <= 12)
? "diamonds" : ((card%A_Index%) <= 24)
? "hearts" : ((card%A_Index% <= 36)
? "clubs"
: "spades"))
allcards .= card%A_Index% . "`n"
}
Gui, show, AutoSize
currentcard = 1
return
Gui, Add, Text, vcard w500
;-----------------------------------------------
Gui, Add, Button, w500 gNew, New Deck (Shuffle)
Gui, Add, Button, w500 gDeal, Deal Next Card
Gui, Add, Button, w500 gReveal, Reveal Entire Deck
Gui, Show,, Playing Cards
Return
New:
Reload
GuiClose:
ExitApp
return
Deal:
;-----------------------------------------------
GuiControl,, card, % card%currentcard%
NewDeck:
currentcard++
cards := [], deck := Dealt:= ""
Return
Reveal:
GuiControl,, card, % allcards
Return</lang>
===Classes===
{{works with|AutoHotkey L}}
<lang ahk>Deck:=new Deck
Deck.Shuffle()
msgbox % Deck.Show()
loop, 2
msgbox % Deck.Deal().Show()
msgbox % Deck.Show()
Return ;-------------------------------------------------------------------
 
loop, % Hands
class Card
GuiControl,, Hand%A_Index%, |
 
for each, suit in suits
for each, value in values
cards.Insert(value suit)
 
for each, card in cards
deck .= card (mod(A_Index, 13) ? " " : "`n")
GuiControl,, Deck, % deck
GuiControl,, Dealt
GuiControl, Enable, Button2
GuiControl, Enable, Hands
return
;-----------------------------------------------
shuffle:
gosub, NewDeck
shuffled := [], deck := ""
loop, 52 {
Random, rnd, 1, % cards.MaxIndex()
shuffled[A_Index] := cards.RemoveAt(rnd)
}
for each, card in shuffled
{
deck .= card (mod(A_Index, 13) ? " " : "`n")
__New(Pip, Suit) {
cards.Insert(card)
this.Pip:=Pip, this.Suit:=Suit
}
Show() {
Return this.Pip . this.Suit
}
}
GuiControl,, Deck, % deck
return
;-----------------------------------------------
Deal:
Gui, Submit, NoHide
if ( Hands > cards.MaxIndex())
return
 
deck := ""
class Deck
loop, % Hands
{
GuiControl,, Hand%A_Index%, % cards.RemoveAt(1)
Suits:={1:"♣",2:"♦",3:"♠",4:"♥"}
 
Pips:={13:"A",1:"2",2:"3",3:"4",4:"5",5:"6",6:"7",7:"8",8:"9",9:"T",10:"J",11:"Q",12:"K"}
GuiControl, Disable, Button2
GuiControl, Disable, Hands
__New() {
GuiControl,, Dealt, % Dealt
this.Deck:=[]
 
For i, Pip in this.Pips
Forfor jeach, Suitcard in this.Suitscards
deck .= card (mod(A_Index, 13) ? " " : "`n")
this.Deck.Insert(new Card(Pip,Suit))
GuiControl,, Deck, % deck
}
return
Shuffle() { ; Knuth Shuffle from http://rosettacode.org/wiki/Knuth_Shuffle#AutoHotkey
;-----------------------------------------------</syntaxhighlight>
Loop % this.Deck.MaxIndex()-1 {
 
Random, i, A_Index, this.Deck.MaxIndex() ; swap item 1,2... with a random item to the right of it
=={{header|AutoIt}}==
temp := this.Deck[i], this.Deck[i] := this.Deck[A_Index], this.Deck[A_Index] := temp
<syntaxhighlight lang="autoit">
}
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
}
#AutoIt3Wrapper_Change2CUI=y
Deal() {
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
Return this.Deck.Remove() ; to deal from bottom, use Remove(1)
#include <Array.au3>
}
 
Show() {
; ## GLOBALS ##
For i, Card in this.Deck
Global $SUIT = ["D", "H", "S", "C"]
s .= Card.Show() " "
Global $FACE = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]
Return s
Global $DECK[52]
}
 
}</lang>
; ## CREATES A NEW DECK
Func NewDeck()
 
For $i = 0 To 3
For $x = 0 To 12
_ArrayPush($DECK, $FACE[$x] & $SUIT[$i])
Next
Next
 
EndFunc ;==>NewDeck
 
; ## SHUFFLE DECK
Func Shuffle()
 
_ArrayShuffle($DECK)
 
EndFunc ;==>Shuffle
 
; ## DEAL A CARD
Func Deal()
 
Return _ArrayPop($DECK)
 
EndFunc ;==>Deal
 
; ## PRINT DECK
Func Print()
 
ConsoleWrite(_ArrayToString($DECK) & @CRLF)
 
EndFunc ;==>Print
 
 
#Region ;#### USAGE ####
NewDeck()
Print()
Shuffle()
Print()
ConsoleWrite("DEALT: " & Deal() & @CRLF)
Print()
#EndRegion ;#### USAGE ####
</syntaxhighlight>
{{Out|Example output}}
<pre>
2D|3D|4D|5D|6D|7D|8D|9D|10D|JD|QD|KD|AD|2H|3H|4H|5H|6H|7H|8H|9H|10H|JH|QH|KH|AH|2S|3S|4S|5S|6S|7S|8S|9S|10S|JS|QS|KS|AS|2C|3C|4C|5C|6C|7C|8C|9C|10C|JC|QC|KC|AC
2C|4D|6H|AC|KC|6S|3C|AS|KS|3H|4S|10D|AD|8D|7C|QH|4C|5H|5S|3D|2D|7D|9C|2S|QD|6C|KH|7S|3S|7H|8H|JH|QC|JC|10H|JD|KD|5D|5C|9H|8S|9D|QS|8C|10C|2H|6D|10S|9S|JS|AH|4H
DEALT: 4H
2C|4D|6H|AC|KC|6S|3C|AS|KS|3H|4S|10D|AD|8D|7C|QH|4C|5H|5S|3D|2D|7D|9C|2S|QD|6C|KH|7S|3S|7H|8H|JH|QC|JC|10H|JD|KD|5D|5C|9H|8S|9D|QS|8C|10C|2H|6D|10S|9S|JS|AH
</pre>
 
=={{header|BASIC}}==
==={{header|QuickBASIC}}===
{{works with|QuickBASIC|QBX 7.1}}
 
Most BASICs aren't object-oriented (or anything even resembling such) and can't do a deck of cards as a single cohesive unit -- but we can fake it.
 
<langsyntaxhighlight lang="qbasic">DECLARE SUB setInitialValues (deck() AS STRING * 2)
DECLARE SUB shuffle (deck() AS STRING * 2)
DECLARE SUB showDeck (deck() AS STRING * 2)
Line 312 ⟶ 1,102:
deck(L0) = shuffled(L0)
NEXT
END SUB</langsyntaxhighlight>
 
{{out}}
Sample output:
<pre>
Dealt: 7D
Dealt: 6D
Line 323 ⟶ 1,115:
AS 2S 3S 4S 5S 6S 7S 8S 9S TS JS QS KS AH 2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KH AC
2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KC AD 2D 3D 4D 5D 6D 7D 8D 9D TD JD QD KD
</pre>
 
=={{header|BASIC256}}==
{{trans|Run BASIC}}
<syntaxhighlight lang="vb">suite$ = "CDHS" #Club, Diamond, Heart, Spade
card$ = "A23456789TJQK" #Cards Ace to King
card = 0
 
dim n(55) #make ordered deck
for i = 1 to 52 # of 52 cards
n[i] = i
next i
 
for i = 1 to 52 * 3 #shuffle deck 3 times
i1 = int(rand * 52) + 1
i2 = int(rand * 52) + 1
h2 = n[i1]
n[i1] = n[i2]
n[i2] = h2
next i
 
for hand = 1 to 4 #4 hands
for deal = 1 to 13 #deal each 13 cards
card += 1 #next card in deck
s = (n[card] mod 4) + 1 #determine suite
c = (n[card] mod 13) + 1 #determine card
print mid(card$,c,1);mid(suite$,s,1);" "; #show the card
next deal
print
next hand
end
 
function word$(sr$, wn, delim$)
j = wn
if j = 0 then j += 1
res$ = "" : s$ = sr$ : d$ = delim$
if d$ = "" then d$ = " "
sd = length(d$) : sl = length(s$)
while true
n = instr(s$,d$) : j -= 1
if j = 0 then
if n=0 then res$=s$ else res$=mid(s$,1,n-1)
return res$
end if
if n = 0 then return res$
if n = sl - sd then res$ = "" : return res$
sl2 = sl-n : s$ = mid(s$,n+1,sl2) : sl = sl2
end while
return res$
end function</syntaxhighlight>
{{out}}
<pre>Same as Run BASIC entry.</pre>
 
=={{header|Batch File}}==
The data structure is a simple string with 3 characters per card, one char for the suit, a char for the pip (T) means ten and a last char not printed that would allow to sort a hand.
<syntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
call:newdeck deck
echo new deck:
echo.
call:showcards deck
echo.
echo shuffling:
echo.
call:shuffle deck
call:showcards deck
echo.
echo dealing 5 cards to 4 players
call:deal deck 5 hand1 hand2 hand3 hand4
echo.
echo player 1 & call:showcards hand1
echo.
echo player 2 & call:showcards hand2
echo.
echo player 3 & call:showcards hand3
echo.
echo player 4 & call:showcards hand4
echo.
call:count %deck% cnt
echo %cnt% cards remaining in the deck
echo.
call:showcards deck
echo.
exit /b
 
:getcard deck hand :: deals 1 card to a player
set "loc1=!%~1!"
set "%~2=!%~2!!loc1:~0,3!"
set "%~1=!loc1:~3!"
exit /b
 
:deal deck n player1 player2...up to 7
set "loc=!%~1!"
set "cards=%~2"
set players=%3 %4 %5 %6 %7 %8 %9
for /L %%j in (1,1,!cards!) do (
for %%k in (!players!) do call:getcard loc %%k)
set "%~1=!loc!"
exit /b
 
:newdeck [deck] ::creates a deck of cards
:: in the parentheses below there are ascii chars 3,4,5 and 6 representing the suits
for %%i in ( ♠ ♦ ♥ ♣ ) do (
for %%j in (20 31 42 53 64 75 86 97 T8 J9 QA KB AC) do set loc=!loc!%%i%%j
)
set "%~1=!loc!"
exit /b
 
:showcards [deck] :: prints a deck or a hand
set "loc=!%~1!"
for /L %%j in (0,39,117) do (
set s=
for /L %%i in (0,3,36) do (
set /a n=%%i+%%j
call set s=%%s%% %%loc:~!n!,2%%
)
if "!s: =!" neq "" echo(!s!
set /a n+=1
if "%loc:~!n!,!%" equ "" goto endloop
)
:endloop
exit /b
:count deck count
set "loc1=%1"
set /a cnt1=0
for %%i in (96 48 24 12 6 3 ) do if "!loc1:~%%i,1!" neq "" set /a cnt1+=%%i & set loc1=!loc1:~%%i!
set /a cnt1=cnt1/3+1
set "%~2=!cnt1!"
exit /b
 
:shuffle (deck) :: shuffles a deck
set "loc=!%~1!"
call:count %loc%, cnt
set /a cnt-=1
for /L %%i in (%cnt%,-1,0) do (
SET /A "from=%%i,to=(!RANDOM!*(%%i-1)/32768)"
call:swap loc from to
)
set "%~1=!loc!"
exit /b
:swap deck from to :: swaps two cards
set "arr=!%~1!"
set /a "from=!%~2!*3,to=!%~3!*3"
set temp1=!arr:~%from%,3!
set temp2=!arr:~%to%,3!
set arr=!arr:%temp1%=@@@!
set arr=!arr:%temp2%=%temp1%!
set arr=!arr:@@@=%temp2%!
set "%~1=!arr!"
exit /b</syntaxhighlight>
{{Out}}
<pre>
new deck:
 
♠2 ♠3 ♠4 ♠5 ♠6 ♠7 ♠8 ♠9 ♠T ♠J ♠Q ♠K ♠A
♦2 ♦3 ♦4 ♦5 ♦6 ♦7 ♦8 ♦9 ♦T ♦J ♦Q ♦K ♦A
♥2 ♥3 ♥4 ♥5 ♥6 ♥7 ♥8 ♥9 ♥T ♥J ♥Q ♥K ♥A
♣2 ♣3 ♣4 ♣5 ♣6 ♣7 ♣8 ♣9 ♣T ♣J ♣Q ♣K ♣A
 
shuffling:
 
♥8 ♥7 ♦K ♠K ♥2 ♥5 ♥A ♠7 ♣8 ♠A ♦7 ♠9 ♠3
♠J ♣J ♦9 ♠8 ♦A ♣Q ♦2 ♦5 ♣K ♥9 ♦4 ♣2 ♣6
♦6 ♥Q ♦8 ♥6 ♣5 ♥T ♦3 ♠6 ♣7 ♠5 ♣T ♣3 ♠T
♠2 ♦Q ♠Q ♦T ♥3 ♥K ♦J ♥4 ♠4 ♣4 ♥J ♣A ♣9
 
dealing 5 cards to 4 players
 
player 1
♥8 ♥2 ♣8 ♠3 ♠8
 
player 2
♥7 ♥5 ♠A ♠J ♦A
 
player 3
♦K ♥A ♦7 ♣J ♣Q
 
player 4
♠K ♠7 ♠9 ♦9 ♦2
 
32 cards remaining in the deck
 
♦5 ♣K ♥9 ♦4 ♣2 ♣6 ♦6 ♥Q ♦8 ♥6 ♣5 ♥T ♦3
♠6 ♣7 ♠5 ♣T ♣3 ♠T ♠2 ♦Q ♠Q ♦T ♥3 ♥K ♦J
♥4 ♠4 ♣4 ♥J ♣A ♣9
</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM Deck{ncards%, card&(51)}, Suit$(3), Rank$(12)
Suit$() = "Clubs", "Diamonds", "Hearts", "Spades"
Rank$() = "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", \
Line 372 ⟶ 1,354:
REM Return the name of a card:
DEF FNcardname(card&)
= Rank$(card& >> 2) + " of " + Suit$(card& AND 3)</langsyntaxhighlight>
Output:
<pre>Creating a new deck...
Line 392 ⟶ 1,374:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
Line 485 ⟶ 1,467:
//free(d);
return 0;
}</langsyntaxhighlight>output
<pre>
New deck, 52 cards: ♠A ♠2 ♠3 ♠4 ♠5 ♠6 ♠7 ♠8 ♠9 ♠10 ♠J ♠Q ♠K ♥A ♥2 ...
Line 497 ⟶ 1,479:
See also [[Playing Cards/C]]
 
=={{header|C++ sharp|C#}}==
{{works with|g++|4.1.2 20061115 (prerelease) (SUSE Linux)}}
 
<syntaxhighlight lang="csharp">using System;
Since all the functions are quite simple, they are all defined inline
using System.Linq;
<lang cpp>#ifndef CARDS_H_INC
using System.Collections.Generic;
#define CARDS_H_INC
 
public struct Card
#include <deque>
{
public Card(string rank, string suit) : this()
{
Rank = rank;
Suit = suit;
}
 
public string Rank { get; }
public string Suit { get; }
 
public override string ToString() => $"{Rank} of {Suit}";
}
 
public class Deck : IEnumerable<Card>
{
static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" };
static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
readonly List<Card> cards;
public Deck() {
cards = (from suit in suits
from rank in ranks
select new Card(rank, suit)).ToList();
}
 
public int Count => cards.Count;
 
public void Shuffle() {
// using Knuth Shuffle (see at http://rosettacode.org/wiki/Knuth_shuffle)
var random = new Random();
for (int i = 0; i < cards.Count; i++) {
int r = random.Next(i, cards.Count);
var temp = cards[i];
cards[i] = cards[r];
cards[r] = temp;
}
}
 
public Card Deal() {
int last = cards.Count - 1;
Card card = cards[last];
//Removing from the front will shift the other items back 1 spot,
//so that would be an O(n) operation. Removing from the back is O(1).
cards.RemoveAt(last);
return card;
}
 
public IEnumerator<Card> GetEnumerator() {
//Reverse enumeration of the list so that they are returned in the order they would be dealt.
//LINQ's Reverse() copies the entire list. Let's avoid that.
for (int i = cards.Count - 1; i >= 0; i--)
yield return cards[i];
}
 
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}</syntaxhighlight>
 
=={{header|C++}}==
=== Text version ===
<syntaxhighlight lang="cpp">#include <deque>
#include <algorithm>
#include <ostream>
Line 511 ⟶ 1,553:
namespace cards
{
class card
{
public:
enum pip_type { two, three, four, five, six, seven, eight, nine, ten,
jack, queen, king, ace, pip_count };
enum suite_type { hearts, spades, diamonds, clubs, suite_count };
enum { unique_count = pip_count * suite_count };
 
card(suite_type s, pip_type p): value(s + suite_count * p) {}
// construct a card of a given suite and pip
card(suite_type s, pip_type p): value(s + 4*p) {}
 
// construct aexplicit card(unsigned directlychar fromv its= 0): value(v) {}
card(unsigned char v = 0): value(v) {}
 
pip_type pip() { return pip_type(value / suite_count); }
// return the pip of the card
pip_type pip() { return pip_type(value/4); }
 
suite_type suite() { return suite_type(value % suite_count); }
// return the suit of the card
suite_type suite() { return suite_type(value%4); }
 
private:
// there are only 52 cards, therefore unsigned char suffices
unsigned char value;
};
 
const char const* const pip_names[] =
{ "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"jack", "queen", "king", "ace" };
 
std::ostream& operator<<(std::ostream& os, card::pip_type pip)
// output a pip
{
std::ostream& operator<<(std::ostream& os, card::pip_type pip)
{
return os << pip_names[pip];
};
 
const char const* const suite_names[] =
{ "hearts", "spades", "diamonds", "clubs" };
 
std::ostream& operator<<(std::ostream& os, card::suite_type suite)
// output a suite
{
std::ostream& operator<<(std::ostream& os, card::suite_type suite)
{
return os << suite_names[suite];
}
 
std::ostream& operator<<(std::ostream& os, card c)
// output a card
{
std::ostream& operator<<(std::ostream& os, card c)
{
return os << c.pip() << " of " << c.suite();
}
 
class deck
{
public:
// default constructor: construct a default-ordered deck
deck()
{
for (int i = 0; i < 52card::unique_count; ++i) {
cards.push_back(card(i));
}
}
 
// shuffle the deck
void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }
 
// deal a card from the top
card deal() { card c = cards.front(); cards.pop_front(); return c; }
 
// iterators (only reading access is allowed)
typedef std::deque<card>::const_iterator const_iterator;
const_iterator begin() const { return cards.begincbegin(); }
const_iterator end() const { return cards.endcend(); }
private:
// the cards
std::deque<card> cards;
};
 
inline std::ostream& operator<<(std::ostream& os, const deck& d)
// output the deck
{
inline std::ostream& operator<<(std::ostream& os, deck const& d)
{
std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n"));
return os;
}
}
}</syntaxhighlight>
 
main.cpp:
#endif</lang>
<syntaxhighlight lang="cpp">#include <iostream>
 
int main(int argc, const char** args) {
=={{header|C sharp|C#}}==
cards::deck d;
d.shuffle();
std::cout << d;
 
return 0;
<lang csharp>using System;
}</syntaxhighlight>
using System.Linq;
using System.Text;
using System.Collections.Generic;
 
=== Unicode version ===
class Card {
{{Works with|Unicode|6 and above}}
string pip;
<syntaxhighlight lang="cpp">#include <algorithm>
string suit;
#include <iostream>
#include <string>
#include <vector>
 
const public static std::vector<std::string[]> pipscards = { "Two🂡", "Three🂱", "Four","Five","Six","Seven🃁", "Eight🃑",
"Nine🂢", "Ten🂲", "Jack🃂", "Queen🃒","King","Ace"};
"🂣", "🂳", "🃃", "🃓",
 
public static string[] suits = { "Diamonds🂤", "Spades🂴", "Hearts🃄", "Clubs🃔" };,
"🂥", "🂵", "🃅", "🃕",
"🂦", "🂶", "🃆", "🃖",
"🂧", "🂷", "🃇", "🃗",
"🂨", "🂸", "🂸", "🂸",
"🂩", "🂩", "🃉", "🃙",
"🂪", "🂺", "🃊", "🃚",
"🂫", "🂻", "🃋", "🃛",
"🂭", "🂽", "🃍", "🃝",
"🂮", "🂾", "🃎", "🃞"
};
 
int main(int argc, const char* args[]) {
public Card(string pip, string suit) {
auto this.pip = pipdeck(cards);
std::random_shuffle(deck.begin(), deck.end());
this.suit = suit;
uint i = 1;
for (auto &card: deck) {
std::cout << card;
if (i++ % 13 == 0)
std::cout << std::endl;
}
 
return 0;
public override string ToString() {
}</syntaxhighlight>
return String.Format("{0} of {1}", pip, suit);
{{out}}
<pre>🂢🃞🃓🃔🂧🃙🂵🂪🃇🃎🂩🃚🃕
🃁🃝🂾🂷🃅🂩🂫🂲🂶🃒🂤🃄🃋
🃗🃂🂽🂭🂸🃊🂴🂺🃑🂥🂸🃛🂳
🃆🂣🃖🂦🃉🂱🃃🂸🂡🃍🂻🂮🂨</pre>
 
=={{header|Ceylon}}==
<syntaxhighlight lang="ceylon">import com.vasileff.ceylon.random.api { ... }
 
"""Run the example code for Rosetta Code ["Playing cards" task] (http://rosettacode.org/wiki/Playing_cards)."""
shared void run() {
variable value deck = Deck();
print("New deck (``deck.size`` cards): ``deck``
");
deck = deck.shuffle();
print("Shuffeled deck (``deck.size`` cards): ``deck``
");
print("Deal three hands: ");
for (i in 1..3) {
value [hand, _deck] = deck.deal();
print("- Dealt ``hand.size`` cards to hand ``i`` : ``join(hand)``");
deck = _deck;
}
print("
Deck (``deck.size`` cards) after dealing three hands: ``deck``");
}
 
abstract class Suit() of clubs | hearts | spades | diamonds {}
class Deck {
public List<Card> deck = new List<Card>();
 
object clubs extends Suit() { string = "♣"; }
public Deck() {
object hearts extends Suit() { foreach (string pip= in"♥"; Card.pips) {}
object spades extends Suit() { string = "♠"; }
foreach (string suits in Card.suits) {
object diamonds extends Suit() { string = "♦"; }
deck.Add(new Card(pip, suits));
 
}
abstract class Pip() of two | three | four | five | six | seven | eight | nine | ten | jack | queen | king | ace {}
object two extends Pip() { string = "2"; }
object three extends Pip() { string = "3"; }
object four extends Pip() { string = "4"; }
object five extends Pip() { string = "5"; }
object six extends Pip() { string = "6"; }
object seven extends Pip() { string = "7"; }
object eight extends Pip() { string = "8"; }
object nine extends Pip() { string = "9"; }
object ten extends Pip() { string = "10"; }
object jack extends Pip() { string = "J"; }
object queen extends Pip() { string = "Q"; }
object king extends Pip() { string = "K"; }
object ace extends Pip() { string = "A"; }
 
class Card(shared Pip pip, shared Suit suit) {
string = "``pip`` of ``suit``";
}
 
 
String join(Card[] cards) => ", ".join { *cards };
 
class Deck (cards = [ for (suit in `Suit`.caseValues) for (pip in `Pip`.caseValues) Card(pip, suit) ]) {
shared Card[] cards;
shared Deck shuffle(Random rnd = platformRandom())
=> if (nonempty cards)
then Deck( [*randomize(cards, rnd)] )
else this;
shared Integer size => cards.size;
shared Boolean empty => cards.empty;
string => if (size > 13)
then "\n " + "\n ". join { *cards.partition(13).map((cards) => join(cards)) }
else join(cards);
shared [Card[], Deck] deal(Integer handSize = 5) {
if (handSize >= cards.size) {
return [cards, Deck([])];
}
else {
return [
cards.initial(handSize),
Deck(cards.skip(handSize).sequence())
];
}
}
}</syntaxhighlight>
 
Output:
public void Shuffle() {
<pre>New deck (52 cards):
// using Knuth Shuffle (see at http://rosettacode.org/wiki/Knuth_shuffle)
2 of ♣, 3 of ♣, 4 of ♣, 5 of ♣, 6 of ♣, 7 of ♣, 8 of ♣, 9 of ♣, 10 of ♣, J of ♣, Q of ♣, K of ♣, A of ♣
Random random = new System.Random();
2 of ♥, 3 of ♥, 4 of ♥, 5 of ♥, 6 of ♥, 7 of ♥, 8 of ♥, 9 of ♥, 10 of ♥, J of ♥, Q of ♥, K of ♥, A of ♥
Card temp;
2 of ♠, 3 of ♠, 4 of ♠, 5 of ♠, 6 of ♠, 7 of ♠, 8 of ♠, 9 of ♠, 10 of ♠, J of ♠, Q of ♠, K of ♠, A of ♠
int j;
2 of ♦, 3 of ♦, 4 of ♦, 5 of ♦, 6 of ♦, 7 of ♦, 8 of ♦, 9 of ♦, 10 of ♦, J of ♦, Q of ♦, K of ♦, A of ♦
for (int i = 0; i < deck.Count; i++){
j = random.Next(deck.Count);
temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}
 
Shuffeled deck (52 cards):
public Card Deal() {
4 of ♠, 2 of ♦, 5 of ♣, 9 of ♠, 4 of ♥, 7 of ♥, 10 of ♦, 5 of ♠, 3 of ♥, K of ♥, 6 of ♣, 9 of ♦, 6 of ♦
Card r = this.deck[0];
4 of ♣, 8 of ♣, 4 of ♦, Q of ♥, 6 of ♥, J of ♥, 8 of ♦, 5 of ♥, 5 of ♦, J of ♣, A of ♥, J of ♦, 2 of ♣
this.deck.RemoveAt(0);
7 of ♠, Q of ♦, A of ♣, Q of ♣, 6 of ♠, Q of ♠, K of ♠, 7 of ♦, 7 of ♣, 3 of ♦, 2 of ♠, 8 of ♥, A of ♦
return r;
2 of ♥, 9 of ♣, 8 of ♠, 10 of ♥, 3 of ♠, 10 of ♣, 9 of ♥, 10 of ♠, 3 of ♣, J of ♠, K of ♣, K of ♦, A of ♠
}
 
Deal three hands:
public override string ToString() {
- Dealt 5 cards to hand 1 : 4 of ♠, 2 of ♦, 5 of ♣, 9 of ♠, 4 of ♥
return String.Join(Environment.NewLine, this.deck.Select(x => x.ToString()).ToArray());
- Dealt 5 cards to hand 2 : 7 of ♥, 10 of ♦, 5 of ♠, 3 of ♥, K of ♥
}
- Dealt 5 cards to hand 3 : 6 of ♣, 9 of ♦, 6 of ♦, 4 of ♣, 8 of ♣
}</lang>
 
Deck (37 cards) after dealing three hands:
=={{Header|Clojure}}==
4 of ♦, Q of ♥, 6 of ♥, J of ♥, 8 of ♦, 5 of ♥, 5 of ♦, J of ♣, A of ♥, J of ♦, 2 of ♣, 7 of ♠, Q of ♦
<lang Clojure>(defrecord Card [pip suit]
A of ♣, Q of ♣, 6 of ♠, Q of ♠, K of ♠, 7 of ♦, 7 of ♣, 3 of ♦, 2 of ♠, 8 of ♥, A of ♦, 2 of ♥, 9 of ♣
Object
8 of ♠, 10 of ♥, 3 of ♠, 10 of ♣, 9 of ♥, 10 of ♠, 3 of ♣, J of ♠, K of ♣, K of ♦, A of ♠</pre>
(toString [this] (str pip " of " suit)))
 
=={{header|Clojure}}==
(defprotocol pDeck
<syntaxhighlight lang="clojure">(def suits [:club :diamond :heart :spade])
(deal [this n])
(def pips [:ace 2 3 4 5 6 7 8 9 10 :jack :queen :king])
(shuffle [this])
(newDeck [this])
(print [this]))
 
(defn deck [] (for [s suits p pips] [s p]))
(deftype Deck [cards]
pDeck
(deal [this n] [(take n cards) (Deck. (drop n cards))])
(shuffle [this] (Deck. (shuffle cards)))
(newDeck [this] (Deck. (for [suit ["Clubs" "Hearts" "Spades" "Diamonds"]
pip ["2" "3" "4" "5" "6" "7" "8" "9" "10" "Jack" "Queen" "King" "Ace"]]
(Card. pip suit))))
(print [this] (dorun (map (comp println str) cards)) this))
 
(def shuffle clojure.core/shuffle)
(defn new-deck []
(def deal first)
(.newDeck (Deck. nil)))</lang>
(defn output [deck]
(doseq [[suit pip] deck]
(println (format "%s of %ss"
(if (keyword? pip) (name pip) pip)
(name suit)))))</syntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% Represents one playing card.
card = cluster is make, parse, unparse, equal, all_cards
rep = struct[pip: int, suit: char]
own suits: string := "CHSD";
own pips: sequence[string] := sequence[string]$
["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
find_pip = proc (pip: string) returns (int) signals (bad_format)
for i: int in int$from_to(1, sequence[string]$size(pips)) do
if pips[i] = pip then return(i) end
end
signal bad_format
end find_pip
make = proc (pip: int, suit: char) returns (cvt) signals (bad_format)
if string$indexc(suit, suits) = 0
cor ~(pip >= 1 cand pip <= 13)
then signal bad_format
end
return(rep${pip: pip, suit: suit})
end make
parse = proc (s: string) returns (cvt) signals (bad_format)
size: int := string$size(s)
if size<2 cor size>3 then signal bad_format end
pip: string := string$substr(s, 1, size-1)
suit: char := string$rest(s, size-1)[1]
return(down(make(find_pip(pip), suit))) resignal bad_format
end parse
unparse = proc (c: cvt) returns (string)
return( pips[c.pip] || string$c2s(c.suit) )
end unparse
equal = proc (a, b: cvt) returns (bool)
return( a.pip = b.pip cand a.suit = b.suit )
end equal
% Yield all cards in the canonical order
all_cards = iter () yields (cvt)
for suit: char in string$chars(suits) do
for pip: int in int$from_to(1,sequence[string]$size(pips)) do
yield(down(make(pip, suit)))
end
end
end all_cards
end card
 
% Represents a deck
=={{Header|CoffeeScript}}==
deck = cluster is new, shuffle, cards, deal, unparse
rep = array[card]
new = proc () returns (cvt)
d: rep := rep$new()
for c: card in card$all_cards() do rep$addh(d, c) end
return(d)
end new
shuffle = proc (d: cvt)
lo: int := rep$low(d)
hi: int := rep$high(d)
for i: int in int$from_to_by(hi, lo+1, -1) do
j: int := lo + random$next(i-lo)
c: card := d[i]
d[i] := d[j]
d[j] := c
end
end shuffle
cards = iter (d: cvt) yields (card)
for c: card in rep$elements(d) do yield(c) end
end cards
deal = proc (d: cvt) returns (card) signals (empty)
if rep$empty(d) then signal empty end
return(rep$reml(d))
end deal
unparse = proc (d: cvt) returns (string)
ss: stream := stream$create_output()
n: int := 0
for c: card in cards(up(d)) do
if n~=0 cand n//13=0 then stream$putc(ss, '\n')
elseif n~=0 then stream$putc(ss, ' ')
end
stream$puts(ss, card$unparse(c))
n := n+1
end
return(stream$get_contents(ss))
end unparse
end deck
 
start_up = proc ()
<lang coffeescript>#translated from JavaScript example
po: stream := stream$primary_output()
% seed the RNG
d_: date := now()
random$seed(d_.second + 60*(d_.minute + 60*d_.hour))
% make a new deck
d: deck := deck$new()
stream$putl(po, "New deck: ")
stream$putl(po, deck$unparse(d))
% shuffle the deck
deck$shuffle(d)
stream$putl(po, "\nShuffled deck: ")
stream$putl(po, deck$unparse(d))
% deal some cards
stream$puts(po, "\nDealing 10 cards:")
for i: int in int$from_to(1, 10) do
stream$puts(po, " " || card$unparse(deck$deal(d)))
end
% show remaining deck
stream$putl(po, "\n\nRemaining cards in deck:")
stream$putl(po, deck$unparse(d))
end start_up</syntaxhighlight>
{{out}}
<pre>New deck:
AC 2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC
AH 2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH
AS 2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS
AD 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD
 
Shuffled deck:
QS 5D 5C 3H 8D 8C 2D 4H 3S QH 8H JS 9H
9C AH 4S 7S 8S 9S 2H AD QC 9D 5S 7C 10S
5H 4C KC 6S 4D 3C KS 6C JC 2C QD 7H AC
AS 10H 6H 3D KD 10D JD 7D JH KH 6D 2S 10C
 
Dealing 10 cards: QS 5D 5C 3H 8D 8C 2D 4H 3S QH
 
Remaining cards in deck:
8H JS 9H 9C AH 4S 7S 8S 9S 2H AD QC 9D
5S 7C 10S 5H 4C KC 6S 4D 3C KS 6C JC 2C
QD 7H AC AS 10H 6H 3D KD 10D JD 7D JH KH
6D 2S 10C</pre>
 
=={{header|COBOL}}==
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol"> identification division.
program-id. playing-cards.
 
environment division.
configuration section.
repository.
function all intrinsic.
 
data division.
working-storage section.
77 card usage index.
01 deck.
05 cards occurs 52 times ascending key slot indexed by card.
10 slot pic 99.
10 hand pic 99.
10 suit pic 9.
10 symbol pic x(4).
10 rank pic 99.
 
01 filler.
05 suit-name pic x(8) occurs 4 times.
 
*> Unicode U+1F0Ax, Bx, Cx, Dx "f09f82a0" "82b0" "8380" "8390"
01 base-s constant as 4036985504.
01 base-h constant as 4036985520.
01 base-d constant as 4036985728.
01 base-c constant as 4036985744.
 
01 sym pic x(4) comp-x.
01 symx redefines sym pic x(4).
77 s pic 9.
77 r pic 99.
77 c pic 99.
77 hit pic 9.
77 limiter pic 9(6).
 
01 spades constant as 1.
01 hearts constant as 2.
01 diamonds constant as 3.
01 clubs constant as 4.
 
01 players constant as 3.
01 cards-per constant as 5.
01 deal pic 99.
01 player pic 99.
 
01 show-tally pic zz.
01 show-rank pic z(5).
01 arg pic 9(10).
procedure division.
cards-main.
perform seed
perform initialize-deck
perform shuffle-deck
perform deal-deck
perform display-hands
goback.
*> ********
seed.
accept arg from command-line
if arg not equal 0 then
move random(arg) to c
end-if
.
 
initialize-deck.
move "spades" to suit-name(spades)
move "hearts" to suit-name(hearts)
move "diamonds" to suit-name(diamonds)
move "clubs" to suit-name(clubs)
 
perform varying s from 1 by 1 until s > 4
after r from 1 by 1 until r > 13
compute c = (s - 1) * 13 + r
evaluate s
when spades compute sym = base-s + r
when hearts compute sym = base-h + r
when diamonds compute sym = base-d + r
when clubs compute sym = base-c + r
end-evaluate
if r > 11 then compute sym = sym + 1 end-if
move s to suit(c)
move r to rank(c)
move symx to symbol(c)
move zero to slot(c)
move zero to hand(c)
end-perform
.
 
shuffle-deck.
move zero to limiter
perform until exit
compute c = random() * 52.0 + 1.0
move zero to hit
perform varying tally from 1 by 1 until tally > 52
if slot(tally) equal c then
move 1 to hit
exit perform
end-if
if slot(tally) equal 0 then
if tally < 52 then move 1 to hit end-if
move c to slot(tally)
exit perform
end-if
end-perform
if hit equal zero then exit perform end-if
if limiter > 999999 then
display "too many shuffles, deck invalid" upon syserr
exit perform
end-if
add 1 to limiter
end-perform
sort cards ascending key slot
.
 
display-card.
>>IF ENGLISH IS DEFINED
move rank(tally) to show-rank
evaluate rank(tally)
when 1 display " ace" with no advancing
when 2 thru 10 display show-rank with no advancing
when 11 display " jack" with no advancing
when 12 display "queen" with no advancing
when 13 display " king" with no advancing
end-evaluate
display " of " suit-name(suit(tally)) with no advancing
>>ELSE
display symbol(tally) with no advancing
>>END-IF
.
 
display-deck.
perform varying tally from 1 by 1 until tally > 52
move tally to show-tally
display "Card: " show-tally
" currently in hand " hand(tally)
" is " with no advancing
perform display-card
display space
end-perform
.
 
display-hands.
perform varying player from 1 by 1 until player > players
move player to tally
display "Player " player ": " with no advancing
perform varying deal from 1 by 1 until deal > cards-per
perform display-card
add players to tally
end-perform
display space
end-perform
display "Stock: " with no advancing
subtract players from tally
add 1 to tally
perform varying tally from tally by 1 until tally > 52
perform display-card
>>IF ENGLISH IS DEFINED
display space
>>END-IF
end-perform
display space
.
 
deal-deck.
display "Dealing " cards-per " cards to " players " players"
move 1 to tally
perform varying deal from 1 by 1 until deal > cards-per
after player from 1 by 1 until player > players
move player to hand(tally)
add 1 to tally
end-perform
.
 
end program playing-cards.
</syntaxhighlight>
 
{{out}}
<pre>prompt$ cobc -xjd playing-cards.cob
Dealing 5 cards to 3 players
Player 01: 🂷🃇🂺🃉🂸
Player 02: 🃋🃈🂵🂦🃑
Player 03: 🃓🂻🂹🂾🂩
Stock: 🃁🃞🂧🂮🃒🂢🃚🃔🃍🂫🃃🂱🃂🂪🃛🃙🂶🂭🂳🃊🃗🃝🂴🃖🂨🂣🂤🃆🂡🃎🃘🃅🂥🃕🂲🃄🂽
</pre>
Or in English
<pre>prompt$ cobc -xjd playing-cards.cob -DENGLISH
Dealing 5 cards to 3 players
Player 01: 7 of hearts 7 of diamonds 10 of hearts 9 of diamonds 8 of hearts
Player 02: jack of diamonds 8 of diamonds 5 of hearts 6 of spades ace of clubs
Player 03: 3 of clubs jack of hearts 9 of hearts king of hearts 9 of spades
Stock: ace of diamonds
king of clubs
7 of spades
king of spades
2 of clubs
2 of spades
10 of clubs
4 of clubs
queen of diamonds
jack of spades
3 of diamonds
ace of hearts
2 of diamonds
10 of spades
jack of clubs
9 of clubs
6 of hearts
queen of spades
3 of hearts
10 of diamonds
7 of clubs
queen of clubs
4 of hearts
6 of clubs
8 of spades
3 of spades
4 of spades
6 of diamonds
ace of spades
king of diamonds
8 of clubs
5 of diamonds
5 of spades
5 of clubs
2 of hearts
4 of diamonds
queen of hearts</pre>
 
GnuCOBOL pseudo-random number sequences are reproducible. A command line argument can be used to pass an initial seed value.
 
=={{header|CoffeeScript}}==
 
<syntaxhighlight lang="coffeescript">#translated from JavaScript example
class Card
constructor: (@pip, @suit) ->
Line 707 ⟶ 2,195:
@cards[i] = @cards.splice(randomCard, 1, card)[0]
deal: -> @cards.shift()</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 713 ⟶ 2,201:
A card is a cons of a suit and a pip. A deck is a list of cards, and so dealing is simply popping off of a deck. Shuffling is naïve, just a sort with a random predicate. Printing is built in.
 
<langsyntaxhighlight lang="lisp">(defconstant +suits+
'(club diamond heart spade)
"Card suits are the symbols club, diamond, heart, and spade.")
Line 734 ⟶ 2,222:
(sort list #'(lambda (x y)
(declare (ignore x y))
(zerop (random 2)))))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.typecons, std.algorithm, std.traits, std.array,
std.range, std.random;
 
Line 745 ⟶ 2,232:
alias Card = Tuple!(Pip, Suit);
 
auto newDeck() pure nothrow @safe @nogc {
return cartesianProduct([EnumMembers!Pip], [EnumMembers!Suit]);
}
Line 757 ⟶ 2,244:
}
 
void show(in Card[] deck) @safe {
writefln("Deck:\n%(%s\n%)\n", deck);
}
 
void main() /*@safe*/ {
auto d = newDeck.array;
d.show;
Line 767 ⟶ 2,254:
while (!d.empty)
d.dealCard.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>Deck:
Line 877 ⟶ 2,364:
 
===More Refined Version===
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.algorithm, std.string, std.range;
 
struct Card {
Line 987 ⟶ 2,474:
g.sortDeck.showDeck;
}
}</langsyntaxhighlight>
{{out}}
<pre>Host
Line 1,025 ⟶ 2,512:
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">program Cards;
 
{$APPTYPE CONSOLE}
Line 1,149 ⟶ 2,636:
 
Readln;
end.</langsyntaxhighlight>
 
=={{header|E}}==
See [[Playing Cards/E]]
 
=={{header|EasyLang}}==
<syntaxhighlight>
global deck[] top .
proc new . .
deck[] = [ ]
for i to 52
deck[] &= i
.
top = 52
.
suit$[] = [ "♠" "♦" "♥" "♣" ]
val$[] = [ 2 3 4 5 6 7 8 9 10 "J" "Q" "K" "A" ]
func$ name card .
return suit$[card mod1 4] & val$[card div1 4]
.
proc show . .
for i to top
write name deck[i] & " "
.
print ""
print ""
.
proc shuffle . .
for i = 52 downto 2
r = randint i
swap deck[i] deck[r]
.
top = 52
.
func deal .
top -= 1
return deck[top + 1]
.
new
show
shuffle
show
for i to 10
write name deal & " "
.
print ""
print ""
show
</syntaxhighlight>
 
{{out}}
<pre>
♠2 ♦2 ♥2 ♣2 ♠3 ♦3 ♥3 ♣3 ♠4 ♦4 ♥4 ♣4 ♠5 ♦5 ♥5 ♣5 ♠6 ♦6 ♥6 ♣6 ♠7 ♦7 ♥7 ♣7 ♠8 ♦8 ♥8 ♣8 ♠9 ♦9 ♥9 ♣9 ♠10 ♦10 ♥10 ♣10 ♠J ♦J ♥J ♣J ♠Q ♦Q ♥Q ♣Q ♠K ♦K ♥K ♣K ♠A ♦A ♥A ♣A
 
♦2 ♣2 ♦6 ♠10 ♦5 ♥3 ♣4 ♦7 ♣9 ♥2 ♣7 ♣K ♦K ♠Q ♠2 ♦Q ♥7 ♥8 ♣8 ♥A ♠3 ♥10 ♥Q ♣10 ♠K ♠5 ♦8 ♠9 ♠4 ♣5 ♣J ♥5 ♠J ♠7 ♦4 ♦3 ♦10 ♥6 ♣Q ♥4 ♠6 ♣3 ♥K ♦J ♠A ♠8 ♥J ♥9 ♣A ♦9 ♣6 ♦A
 
♦A ♣6 ♦9 ♣A ♥9 ♥J ♠8 ♠A ♦J ♥K
 
♦2 ♣2 ♦6 ♠10 ♦5 ♥3 ♣4 ♦7 ♣9 ♥2 ♣7 ♣K ♦K ♠Q ♠2 ♦Q ♥7 ♥8 ♣8 ♥A ♠3 ♥10 ♥Q ♣10 ♠K ♠5 ♦8 ♠9 ♠4 ♣5 ♣J ♥5 ♠J ♠7 ♦4 ♦3 ♦10 ♥6 ♣Q ♥4 ♠6 ♣3
</pre>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<syntaxhighlight lang="elixir">defmodule Card do
defstruct pip: nil, suit: nil
end
 
defmodule Playing_cards do
@pips ~w[2 3 4 5 6 7 8 9 10 Jack Queen King Ace]a
@suits ~w[Clubs Hearts Spades Diamonds]a
@pip_value Enum.with_index(@pips)
@suit_value Enum.with_index(@suits)
def deal( n_cards, deck ), do: Enum.split( deck, n_cards )
def deal( n_hands, n_cards, deck ) do
Enum.reduce(1..n_hands, {[], deck}, fn _,{acc,d} ->
{hand, new_d} = deal(n_cards, d)
{[hand | acc], new_d}
end)
end
def deck, do: (for x <- @suits, y <- @pips, do: %Card{suit: x, pip: y})
def print( cards ), do: IO.puts (for x <- cards, do: "\t#{inspect x}")
def shuffle( deck ), do: Enum.shuffle( deck )
def sort_pips( cards ), do: Enum.sort_by( cards, &@pip_value[&1.pip] )
def sort_suits( cards ), do: Enum.sort_by( cards, &(@suit_value[&1.suit]) )
def task do
shuffled = shuffle( deck )
{hand, new_deck} = deal( 3, shuffled )
{hands, _deck} = deal( 2, 3, new_deck )
IO.write "Hand:"
print( hand )
IO.puts "Hands:"
for x <- hands, do: print(x)
end
end
 
Playing_cards.task</syntaxhighlight>
 
{{out}}
<pre>
Hand: %Card{pip: :Ace, suit: :Spades} %Card{pip: :"5", suit: :Hearts} %Card{pip: :"7", suit: :Clubs}
Hands:
%Card{pip: :"7", suit: :Hearts} %Card{pip: :"4", suit: :Spades} %Card{pip: :"9", suit: :Spades}
%Card{pip: :"6", suit: :Spades} %Card{pip: :Ace, suit: :Hearts} %Card{pip: :"2", suit: :Diamonds}
</pre>
 
=={{header|Erlang}}==
Line 1,158 ⟶ 2,753:
 
This module is used by [[Go_Fish]].
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( playing_cards ).
 
Line 1,197 ⟶ 2,792:
 
suites() -> ["Clubs", "Hearts", "Spades", "Diamonds"].
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,205 ⟶ 2,800:
{card,"6","Hearts"} {card,"3","Diamonds"} {card,"Queen","Spades"}
{card,"10","Hearts"} {card,"2","Hearts"} {card,"6","Diamonds"}
</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.98}}
Since our data structure is both a sequence and a stack, we can leverage the existing <code>randomize</code> word for shuffling and <code>pop</code> word for dealing.
 
<syntaxhighlight lang="factor">USING: formatting grouping io kernel math qw random sequences
vectors ;
IN: rosetta-code.playing-cards
 
CONSTANT: pips qw{ A 2 3 4 5 6 7 8 9 10 J Q K }
CONSTANT: suits qw{ ♥ ♣ ♦ ♠ }
 
: <deck> ( -- vec ) 52 <iota> >vector ;
 
: card>str ( n -- str )
13 /mod [ suits nth ] [ pips nth ] bi* prepend ;
: print-deck ( seq -- )
13 group [ [ card>str "%-4s" printf ] each nl ] each ;
<deck> ! make new deck
randomize ! shuffle the deck
dup pop drop ! deal from the deck (and discard)
print-deck ! print the deck</syntaxhighlight>
{{out}}
<pre>
J♣ 10♥ 3♥ 10♠ 7♥ 7♦ 4♦ 4♥ K♣ 9♠ 8♠ A♠ 6♥
K♠ 10♣ 8♦ 10♦ 3♦ Q♥ 9♥ 5♦ 7♣ 6♦ 3♣ 4♣ J♥
5♣ 6♣ 7♠ J♠ 3♠ 2♣ 2♥ 5♠ Q♠ 6♠ 4♠ 2♠ 5♥
K♥ 2♦ 8♣ A♥ 9♦ 9♣ 8♥ J♦ K♦ A♣ Q♦ A♦
</pre>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">
enum class Suit { clubs, diamonds, hearts, spades }
enum class Pips { ace, two, three, four, five,
Line 1,275 ⟶ 2,901:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
{{works with|GNU Forth}}
<langsyntaxhighlight lang="forth">require random.fs \ RANDOM ( n -- 0..n-1 ) is called CHOOSE in other Forths
 
create pips s" A23456789TJQK" mem,
Line 1,310 ⟶ 2,936:
new-deck shuffle .deck
5 .hand
cards-left . \ 47</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">MODULE Cards
 
IMPLICIT NONE
Line 1,379 ⟶ 3,005:
END SUBROUTINE Print_deck
 
END MODULE Cards</langsyntaxhighlight>
Example use:
<langsyntaxhighlight lang="fortran">PROGRAM Playing_Cards
USE Cards
Line 1,391 ⟶ 3,017:
CALL Print_deck
END PROGRAM</langsyntaxhighlight>
This creates a new deck, shuffles it, deals five cards to hand, prints the cards in hand and then prints the cards remaining in the deck.
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">#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</syntaxhighlight>
{{out}}<pre>Dealing a card: King of Diamonds
Ace of Spades
Eight of Spades
Nine of Spades
Two of Spades
Ten of Spades
Six of Spades
Five of Spades
Three of Spades
Four of Spades
Seven of Spades</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package cards
 
import (
Line 1,567 ⟶ 3,266:
}
return hands, true
}</langsyntaxhighlight>
Example use:
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,613 ⟶ 3,312:
fmt.Println("\nReturning the cards to the deck")
fmt.Println(d)
}</langsyntaxhighlight>
Output:
<pre>
Line 1,658 ⟶ 3,357:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">import groovy.transform.TupleConstructor
 
enum Pip {
Line 1,694 ⟶ 3,393:
 
String toString() { cards.isEmpty() ? "Empty Deck" : "Deck $cards" }
}</langsyntaxhighlight>
Test Code
<langsyntaxhighlight lang="groovy">Deck deck = new Deck()
deck.shuffle()
(0..<5).each { println deck.deal() }</langsyntaxhighlight>
Output:
<pre>TWO of DIAMONDS
Line 1,709 ⟶ 3,408:
 
Straightforward implementation with explicit names for pips and suits. A deck is just a list of cards. Dealing consists of splitting off cards from the beginning of the list by the usual pattern matching (not shown). Printing is automatic. Purely functional shuffling is a bit tricky, so here we just do the naive quadratic version. This also works for other than full decks.
<langsyntaxhighlight lang="haskell">import System.Random
 
data Pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten |
Line 1,735 ⟶ 3,434:
shuffle' g [] _ ys = ys
shuffle' g (x:xs) n ys = shuffle' g' xs (n+1) (insertAt k x ys) where
(k,g') = randomR (0,n) g</langsyntaxhighlight>
 
=={{header|Hy}}==
{{works with|Hy|0.17.0+}}
 
A simple program that deals out two five card hands.
 
<syntaxhighlight lang="hy">(import [random [shuffle]])
(setv pips (.split "2 3 4 5 6 7 8 9 10 J Q K A"))
(setv suits (.split "♥ ♦ ♣ ♠"))
(setv cards_per_hand 5)
 
(defn make_deck [pips suits]
(lfor
x pips
y suits
(+ x y)))
 
(defn deal_hand [num_cards deck]
(setv delt (cut deck None num_cards))
(setv new_deck (lfor
x deck
:if (not (in x delt))
x))
[delt new_deck])
 
 
(if (= __name__ "__main__")
(do
(setv deck (make_deck pips suits))
(shuffle deck)
(setv [first_hand deck] (deal_hand cards_per_hand deck))
(setv [second_hand deck] (deal_hand cards_per_hand deck))
(print "\nThe first hand delt was:" (.join " " (map str first_hand)))
(print "\nThe second hand delt was:" (.join " " (map str second_hand)))
(print "\nThe remaining cards in the deck are...\n" (.join " " (map str deck)))))</syntaxhighlight>
 
Sample Output:
 
The first hand delt was: 5♠ 3♣ 4♥ 10♦ 6♣
 
The second hand delt was: J♣ 8♣ 9♣ K♠ 2♦
 
The remaining cards in the deck are...
3♦ 6♥ 10♠ Q♦ 7♥ 2♠ 5♥ K♥ A♦ A♥ J♥ 4♣ 3♥ A♣ 8♦ 5♦ 10♥ 7♠ A♠ J♠ 5♣ 2♥ 9♥ 4♦ 8♠ 9♦ 6♠ 7♣ 10♣ 2♣ Q♥ Q♠ 9♠ 7♦ 8♥ Q♣ 3♠ 6♦ K♣ 4♠ K♦ J♦
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
 
cards := 2 # cards per hand
Line 1,790 ⟶ 3,533:
procedure card2string(x) #: return a string version of a card
return x.pip || x.suit
end</langsyntaxhighlight>
Sample output:
<pre>New deck : 2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH AH 2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS AS 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AD 2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC AC
Line 1,803 ⟶ 3,546:
=={{header|J}}==
'''Solution:'''<br>
<langsyntaxhighlight lang="j">NB. playingcards.ijs
NB. Defines a Rosetta Code playing cards class
NB. Multiple decks may be used, one for each instance of this class.
Line 1,844 ⟶ 3,587:
)
 
newDeck_z_=: conew&'rcpc'</langsyntaxhighlight>
 
'''Example use:'''
<langsyntaxhighlight lang="j"> load '~user/playingcards.ijs'
coinsert 'rcpc' NB. insert rcpc class in the path of current locale
pc=: newDeck ''
Line 1,869 ⟶ 3,612:
42 2
destroy__pc ''
1</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
 
<langsyntaxhighlight lang="java">public enum Pip { Two, Three, Four, Five, Six, Seven,
Eight, Nine, Ten, Jack, Queen, King, Ace }</langsyntaxhighlight>
<langsyntaxhighlight lang="java">public enum Suit { Diamonds, Spades, Hearts, Clubs }</langsyntaxhighlight>
 
The card:
<langsyntaxhighlight lang="java">public class Card {
private final Suit suit;
private final Pip value;
Line 1,891 ⟶ 3,634:
return value + " of " + suit;
}
}</langsyntaxhighlight>
The deck:
<langsyntaxhighlight lang="java">import java.util.Collections;
import java.util.LinkedList;
 
Line 1,916 ⟶ 3,659:
return deck.toString();
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">function Card(pip, suit) {
this.pip = pip;
this.suit = suit;
Line 1,949 ⟶ 3,692:
return this.deck.shift();
};
}</langsyntaxhighlight>
 
=={{header|jq}}==
In the following, dealing of cards is accomplished in the conventional manner,
that is in a round-robin fashion whereby in each round, each player is dealt one card from the top of the deck in turn.
 
Since neither the C nor the Go implementation of jq currently has a built-in
PRNG,
this program assumes an invocation such as:
<pre>
< /dev/urandom tr -cd '0-9' | fold -w 1 | $JQ -MRcnr -f playing-cards.jq
</pre>
where $JQ can be either jq or gojq. If gojq is used, the def of
`_nwise` given below should be uncommented.
 
<syntaxhighlight lang=jq>
# Uncomment for gojq:
# def _nwise($n):
# def nw: if length <= $n then . else .[0:$n] , (.[$n:] | nw) end;
# nw;
 
# Output: a prn in range(0;$n) where $n is .
def prn:
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
 
def knuthShuffle:
length as $n
| if $n <= 1 then .
else {i: $n, a: .}
| until(.i == 0;
.i += -1
| (.i + 1 | prn) as $j
| .a[.i] as $t
| .a[.i] = .a[$j]
| .a[$j] = $t)
| .a
end;
 
def Pip: ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
 
def Suit: ["♦", "♣", "♥", "♠"];
 
def Card(pip; suit): pip + suit;
 
def Deck: Card(Pip[]; Suit[]);
 
# Deal one round of the cards in .deck to the players
# represented by .hands,
# but if there are not enough cards, do nothing except add .error to the input
# Input {deck, hands}
def deal:
(.hands | length) as $nplayers
| if $nplayers > (.deck|length) then .error = "not enough cards"
else reduce range(0;$nplayers) as $i (.; .hands[$i] += [.deck[$i]])
| .deck |= .[$nplayers:]
 
# Deal $n cards to $nplayers players if there are enough cards in the input deck
# Input: a deck
# Output: {deck, hands}
def deal($n; $nplayers):
if $n * $nplayers > length then "deal/2: not enough cards" | error
else {deck: ., hands: [range(0; $nplayers)|[]]}
| until( .hands[0]|length == $n; deal)
end ;
 
# display an entire deck or else just the cards
def display:
if length == 52 then _nwise(13) | join(" ")
else join(" ")
end;
 
def task:
Deck
| "After creation, the deck consists of:", display, "",
(knuthShuffle
| "After shuffling:", display, "",
( deal(5; 4)
| "After dealing 5 cards each to 4 players, the hands are:",
(.hands[] | display), "", "... leaving \(.deck|length) cards") ) ;
 
task
</syntaxhighlight>
{{output}}
An example.
<pre>
After creation, the deck consists of:
A♦ 2♦ 3♦ 4♦ 5♦ 6♦ 7♦ 8♦ 9♦ 10♦ J♦ Q♦ K♦
A♣ 2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣ Q♣ K♣
A♥ 2♥ 3♥ 4♥ 5♥ 6♥ 7♥ 8♥ 9♥ 10♥ J♥ Q♥ K♥
A♠ 2♠ 3♠ 4♠ 5♠ 6♠ 7♠ 8♠ 9♠ 10♠ J♠ Q♠ K♠
 
After shuffling:
9♦ 7♦ J♥ 7♥ 4♥ 3♠ 4♣ 2♦ 2♠ 6♦ Q♠ 8♦ A♣
8♥ 4♦ J♣ 5♠ 3♣ Q♣ 3♥ 7♠ 9♥ 8♣ 10♠ 2♥ A♠
Q♦ 5♦ 10♦ J♠ K♥ 5♣ A♦ 10♥ 10♣ A♥ 2♣ 9♣ 7♣
K♣ 6♠ K♦ 9♠ J♦ 5♥ Q♥ 4♠ K♠ 8♠ 6♣ 6♥ 3♦
 
After dealing 5 cards each to 4 players, the hands are:
9♦ 4♥ 2♠ A♣ 5♠
7♦ 3♠ 6♦ 8♥ 3♣
J♥ 4♣ Q♠ 4♦ Q♣
7♥ 2♦ 8♦ J♣ 3♥
 
... leaving 32 cards
</pre>
 
=={{header|Julia}}==
'''Deck Types and Constructors'''
 
A deck consists of an array of integers and a <tt>DeckDesign</tt> type, which defines the meanings of the cards. This is a somewhat simplified implementation. While strictly speaking, a deck should be an array of cards, it is sufficient here to use integers. Indeed, cards and hands are just decks with smaller numbers of cards.
 
<syntaxhighlight lang="julia">
type DeckDesign{T<:Integer,U<:String}
rlen::T
slen::T
ranks::Array{U,1}
suits::Array{U,1}
hlen::T
end
 
type Deck{T<:Integer}
cards::Array{T,1}
design::DeckDesign
end
 
Deck(n::Integer, des::DeckDesign) = Deck([n], des)
 
function pokerlayout()
r = [map(string, 2:10), "J", "Q", "K", "A"]
r = map(utf8, r)
s = ["\u2663", "\u2666", "\u2665", "\u2660"]
DeckDesign(13, 4, r, s, 5)
end
 
function fresh(des::DeckDesign)
Deck(collect(1:des.rlen*des.slen), des)
end
</syntaxhighlight>
 
'''Define a Few of the Standard Methods'''
 
Many of these definitions are simply passed through to the card array component of the deck. But note that <tt>size</tt> returns parameters appropriate to a complete deck. This behavior is helpful when assigning meaning to any list of cards.
<syntaxhighlight lang="julia">
Base.isempty(d::Deck) = isempty(d.cards)
Base.empty!(d::Deck) = empty!(d.cards)
Base.length(d::Deck) = length(d.cards)
Base.endof(d::Deck) = endof(d.cards)
Base.shuffle!(d::Deck) = shuffle!(d.cards)
Base.sort!(d::Deck) = sort!(d.cards)
Base.getindex(d::Deck, r) = Deck(getindex(d.cards, r), d.design)
Base.size(d::Deck) = (d.design.rlen, d.design.slen)
function Base.print(d::Deck)
sz = size(d)
r = map(x->d.design.ranks[ind2sub(sz, x)[1]], d.cards)
s = map(x->d.design.suits[ind2sub(sz, x)[2]], d.cards)
join(r.*s, " ")
end
</syntaxhighlight>
 
'''Define Some Special Methods'''
 
<tt>deal!</tt> is the only deck specific method required to complete the essentials for this task.
 
<syntaxhighlight lang="julia">
function deal!{T<:Integer}(d::Deck, hlen::T)
if hlen < length(d)
hand = Deck(d.cards[1:hlen], d.design)
d.cards = d.cards[hlen+1:end]
else
hand = d
empty!(d)
end
return hand
end
 
function deal!(d::Deck)
deal!(d, d.design.hlen)
end
 
function pretty(d::Deck)
s = ""
llen = d.design.rlen
dlen = length(d)
for i in 1:llen:dlen
j = min(i+llen-1, dlen)
s *= print(d[i:j])*"\n"
end
chop(s)
end
</syntaxhighlight>
 
'''Main'''
<syntaxhighlight lang="julia">
d = fresh(pokerlayout())
println("A new poker deck:")
println(pretty(d))
 
shuffle!(d)
println()
println("The deck shuffled:")
println(pretty(d))
 
n = 4
println()
println("Deal ", n, " hands:")
for i in 1:n
h = deal!(d)
println(pretty(h))
end
 
println()
println("And now the deck contains:")
println(pretty(d))
</syntaxhighlight>
 
{{out}}
<pre>
A new poker deck:
2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣ Q♣ K♣ A♣
2♦ 3♦ 4♦ 5♦ 6♦ 7♦ 8♦ 9♦ 10♦ J♦ Q♦ K♦ A♦
2♥ 3♥ 4♥ 5♥ 6♥ 7♥ 8♥ 9♥ 10♥ J♥ Q♥ K♥ A♥
2♠ 3♠ 4♠ 5♠ 6♠ 7♠ 8♠ 9♠ 10♠ J♠ Q♠ K♠ A♠
 
The deck shuffled:
Q♥ 6♠ 4♣ 2♠ 5♣ 10♣ 9♠ K♥ 7♠ 3♠ 2♥ 4♥ A♣
6♥ A♥ 3♥ 3♦ K♦ 10♦ 10♠ 8♣ 4♦ 8♦ K♣ 5♦ 6♣
7♦ 9♦ 6♦ 8♥ 10♥ 5♥ J♠ 9♣ 8♠ Q♦ 2♦ K♠ Q♣
J♣ J♥ 7♥ J♦ 2♣ 4♠ 5♠ 9♥ A♦ 3♣ 7♣ A♠ Q♠
 
Deal 4 hands:
Q♥ 6♠ 4♣ 2♠ 5♣
10♣ 9♠ K♥ 7♠ 3♠
2♥ 4♥ A♣ 6♥ A♥
3♥ 3♦ K♦ 10♦ 10♠
 
And now the deck contains:
8♣ 4♦ 8♦ K♣ 5♦ 6♣ 7♦ 9♦ 6♦ 8♥ 10♥ 5♥ J♠
9♣ 8♠ Q♦ 2♦ K♠ Q♣ J♣ J♥ 7♥ J♦ 2♣ 4♠ 5♠
9♥ A♦ 3♣ 7♣ A♠ Q♠
</pre>
 
=={{header|K}}==
Line 1,955 ⟶ 3,943:
 
Create the deck.
<langsyntaxhighlight Klang="k"> v:"A23456789TJQK" / values
s:"SHCD" / suites
 
/ create a new deck
newdeck:{deck::,/s,'\:v}
newdeck();</langsyntaxhighlight>
 
Show the deck.
<langsyntaxhighlight Klang="k"> show:{`0:$,/-3$$deck}
 
show()
SA S2 S3 S4 S5 S6 S7 S8 S9 ST SJ SQ SK HA H2 H3 H4 H5 H6 H7 H8 H9 HT HJ HQ HK CA C2 C3 C4 C5 C6 C7 C8 C9 CT CJ CQ CK DA D2 D3 D4 D5 D6 D7 D8 D9 DT DJ DQ DK </langsyntaxhighlight>
 
Shuffle the deck.
<langsyntaxhighlight Klang="k"> shuffle:{deck::(-#deck)?deck}
 
shuffle();show()
S8 CA D5 D2 SJ D6 DJ H7 S4 S9 SQ SK S5 D8 C4 HT DA H3 S6 S2 DT HA C2 C5 D9 ST C7 DK S3 HQ D7 DQ C8 D3 SA CJ CQ CT H4 H2 CK H9 H5 C3 C6 H6 D4 HJ C9 S7 HK H8 </langsyntaxhighlight>
 
Deal: Get the N top cards and remove them from the deck.
Deal 5 cards.
<langsyntaxhighlight Klang="k"> deal1:{|((#deck)-x)_|deck}
deal:{c:deal1[x];deck::(deck _dvl c);c}
 
Line 1,987 ⟶ 3,975:
 
#deck / 5 cards are removed
47</langsyntaxhighlight>
 
Deal 3 more hands.
<langsyntaxhighlight Klang="k"> {deal@5}'!3
(("D6"
"DJ"
Line 2,005 ⟶ 3,993:
"H3"
"S6"
"S2"))</langsyntaxhighlight>
 
We now have 32 cards left.
<langsyntaxhighlight Klang="k"> #deck
32
show()
DT HA C2 C5 D9 ST C7 DK S3 HQ D7 DQ C8 D3 SA CJ CQ CT H4 H2 CK H9 H5 C3 C6 H6 D4 HJ C9 S7 HK H8</langsyntaxhighlight>
 
=={{header|Kotlin}}==
=== procedural style ===
{{Works with|Kotlin|1.3.50}}
<syntaxhighlight lang="scala">const val FACES = "23456789TJQKA"
const val SUITS = "shdc"
 
fun createDeck(): List<String> {
val cards = mutableListOf<String>()
FACES.forEach { face -> SUITS.forEach { suit -> cards.add("$face$suit") } }
return cards
}
 
fun dealTopDeck(deck: List<String>, n: Int) = deck.take(n)
 
fun dealBottomDeck(deck: List<String>, n: Int) = deck.takeLast(n).reversed()
 
fun printDeck(deck: List<String>) {
for (i in deck.indices) {
print("${deck[i]} ")
if ((i + 1) % 13 == 0 || i == deck.size - 1) println()
}
}
 
fun main(args: Array<String>) {
var deck = createDeck()
println("After creation, deck consists of:")
printDeck(deck)
deck = deck.shuffled()
println("\nAfter shuffling, deck consists of:")
printDeck(deck)
val dealtTop = dealTopDeck(deck, 10)
println("\nThe 10 cards dealt from the top of the deck are:")
printDeck(dealtTop)
val dealtBottom = dealBottomDeck(deck, 10)
println("\nThe 10 cards dealt from the bottom of the deck are:")
printDeck(dealtBottom)
}</syntaxhighlight>
Sample output:
{{out}}
<pre>
After creation, deck consists of:
2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As
2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah
2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad
2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac
 
After shuffling, deck consists of:
2h 6h 5s 9s Td Kh Jc 4s Ac Tc 7s 8s 9c
Js 3s Th Kd 2d Qd 8h 3c 6d Qc 2c Ks Ad
9d 5c 6s 4h Qh 4d Ah 3d As 5h Ts 7d Jh
Jd 4c 8d 7h 6c 2s Qs 7c Kc 9h 8c 3h 5d
 
The 10 cards dealt from the top of the deck are:
2h 6h 5s 9s Td Kh Jc 4s Ac Tc
 
The 10 cards dealt from the bottom of the deck are:
5d 3h 8c 9h Kc 7c Qs 2s 6c 7h</pre>
 
=== object-oriented ===
{{Works with|Kotlin|1.4.10}}
<syntaxhighlight lang="scala">class Deck : ArrayList<String> {
constructor() { FACES.forEach { face -> SUITS.forEach { add("$face$it") } } }
constructor(c: Collection<String>) { addAll(c) }
 
fun dealTop(n: Int) = Deck(take(n))
fun dealBottom(n: Int) = Deck(takeLast(n).reversed())
 
fun print() {
forEachIndexed { i, s ->
print("$s ")
if ((i + 1) % 13 == 0 || i == size - 1) println()
}
}
 
private companion object {
const val FACES = "23456789TJQKA"
const val SUITS = "shdc"
}
}
 
fun main(args: Array<String>) {
val deck = Deck()
println("After creation, deck consists of:")
deck.print()
deck.shuffle()
println("\nAfter shuffling, deck consists of:")
deck.print()
println("\nThe 10 cards dealt from the top of the deck are:")
deck.dealTop(10).print()
println("\nThe 10 cards dealt from the bottom of the deck are:")
deck.dealBottom(10).print()
}</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb"> Dim deckCards(52)
Dim holdCards(1, 1)
Print "The Sorted Deck"
Line 2,105 ⟶ 4,186:
pipLabel$ = "Ace Deuce Three Four Five Six Seven Eight Nine Ten Jack Queen King"
pip$ = Word$(pipLabel$, faceValue)
End Function</langsyntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">make "suits {Diamonds Hearts Clubs Spades}
make "pips {Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King}
 
Line 2,141 ⟶ 4,222:
new.deck
shuffle.deck
repeat 5 [deal.card]</langsyntaxhighlight>
 
=={{header|Lua}}==
===Version 1===
<lang Lua>
<syntaxhighlight lang="lua">
suits = {"Clubs", "Diamonds", "Hearts", "Spades"}
faces = {2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"}
Line 2,209 ⟶ 4,291:
print(d - 4 .. "")
print(-b .. "")
</syntaxhighlight>
</lang>
 
===Version 2===
<syntaxhighlight lang="lua">local tPlayers = {} -- cards of players
local tBoard = {} -- cards in a board
local nPlayers = 5 -- number of players
 
local tDeck = {
'2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', 'Td', 'Jd', 'Qd', 'Kd', 'Ad', -- DIAMONDS
'2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', 'Ts', 'Js', 'Qs', 'Ks', 'As', -- SPADES
'2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', 'Th', 'Jh', 'Qh', 'Kh', 'Ah', -- HEARTS
'2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', 'Tc', 'Jc', 'Qc', 'Kc', 'Ac'} -- CLUBS
 
local function shuffle() -- Fisher–Yates shuffle
i = #tDeck
while i > 1 do
i = i - 1
j = math.random(1, i)
tDeck[j], tDeck[i] = tDeck[i], tDeck[j]
end
return tDeck
end
 
local function cardTransfer(to, amount, from)
for f = 1, amount do
table.insert(to, #to+1, from[#from])
from[#from] = nil
end
end
 
----||EXAMPLE OF USE||----
print('FRESH DECK \n', table.concat(tDeck, ' '), '\n')
 
shuffle()
 
print('SHUFFLED DECK \n', table.concat(tDeck, ' '), '\n')
 
for a = 1, nPlayers do
tPlayers[a] = {}
cardTransfer(tPlayers[a], 2, tDeck)
end
 
cardTransfer(tBoard, 5, tDeck)
 
print('BOARD\n', table.concat(tBoard, ' '), '\n')
 
for b = 1, nPlayers do
print('PLAYER #'..b..': ', table.concat(tPlayers[b], ' '))
end
 
print('\nREMAINING\n', table.concat(tDeck, ' '), '\n')
 
for c = 1, #tPlayers do
for d = 1, #tPlayers[c] do
cardTransfer(tDeck, d, tPlayers[c])
end
end
 
cardTransfer(tDeck, 5, tBoard)
 
print('ALL CARDS IN THE DECK\n', table.concat(tDeck, ' '), '\n')
</syntaxhighlight>
 
Output:
<syntaxhighlight lang="lua">FRESH DECK
2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac
 
SHUFFLED DECK
7c 3d 8h 7h 7s 9c 8c Ks 8s 2s 5s 8d 2h 3h Jc 6h Td Ts Jh Tc 6s Kd 7d 4h 4d 5d Qd 5h 5c Kh 9d 2d Ah 6d 3c Js 9h Qh 4c 3s As Kc Qs Ad Th 4s Jd Ac Qc 2c 9s 6c
 
BOARD
Kc As 3s 4c Qh
 
PLAYER #1: 6c 9s
PLAYER #2: 2c Qc
PLAYER #3: Ac Jd
PLAYER #4: 4s Th
PLAYER #5: Ad Qs
 
REMAINING
7c 3d 8h 7h 7s 9c 8c Ks 8s 2s 5s 8d 2h 3h Jc 6h Td Ts Jh Tc 6s Kd 7d 4h 4d 5d Qd 5h 5c Kh 9d 2d Ah 6d 3c Js 9h
 
ALL CARDS IN THE DECK
7c 3d 8h 7h 7s 9c 8c Ks 8s 2s 5s 8d 2h 3h Jc 6h Td Ts Jh Tc 6s Kd 7d 4h 4d 5d Qd 5h 5c Kh 9d 2d Ah 6d 3c Js 9h 9s 6c Qc 2c Jd Ac Th 4s Qs Ad Qh 4c 3s As Kc
</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
We can use one or more packs. When we need a card and deck has no card then a new pack inserted (automatic drop some random cards)
<syntaxhighlight lang="m2000 interpreter">
Module PlayCards {
Font "Arial" ' Ensure characters exist for Suits
Cls 15,0
Pen 0
Inventory Suits = "♠":=0, "♥":=4, "♦":=4, "♣":=0 'suit -> color
Inventory Cards = "two":=2, "three":=3, "four":=4, "five":=5
Append Cards, "six":=6, "seven":=7, "eight":=8, "nine":=9
Append Cards, "ten":=10, "jack":=10, "queen":=10, "king":=10, "ace":=1
DealerMoney=0
PrintCardOnly = Lambda Suits, Cards (k, nl=True)-> {
For k {
Pen Suits(.suit!) {
If nl then {
Print Part @(10), Eval$(Suits, .suit)+Eval$(Cards, .card)
Print
} Else Print Eval$(Suits, .suit)+Eval$(Cards, .card),
}
}
}
' Using a stack object
StackPack = Stack
Module AppendArray (N, A) {
Stack N {Data !A}
}
Class OneCard {
suit=-1, Card
Class:
Module OneCard {
\\ ? for optional reading
read ? .suit, .card
}
}
Decks=1
Dim Pack(Len(Cards)*Len(Suits)*Decks)
k=0
\\ fill cards to Pack()
For times=1 To Decks {
N=each(Suits)
While N {
M=each(Cards)
While M {
Pack(k)=OneCard(N^, M^)
k++
}
}
}
DisplayAll() ' in order
Suffle()
DisplayAll() ' at random positions
Print
Card=OneCard()
Print "Cards in Deck:";Len(StackPack)
For i=1 to 60 {
NextCard()
Print "Get Card:";
Call PrintCardOnly(Card)
Print
Print "Cards in Deck:";Len(StackPack)
DisplayDeck()
Print
}
Sub Suffle()
Print
Local N=Len(Pack())-1, N2, i, j, total=N*4+4, cur=1
For j=1 To 4 {
For i=0 To N {
If cur Mod 4=3 Then Print Over format$("Suffle {0:0}%",cur/total*100)
N2=random(0, N)
While N2=i {N2=random(0, N)}
Swap Pack(i), Pack(N2)
cur++
}
}
AppendArray StackPack, Pack()
Print
End Sub
Sub DisplayDeck()
local m=each(StackPack)
While m {
Call PrintCardOnly(StackItem(m), False)
}
End Sub
Sub DisplayAll()
For k=0 To Len(Pack())-1 {
PrintCard(k)
}
End Sub
Sub PrintCard(k)
For Pack(k) {
Pen Suits(.suit!) {
Print Eval$(Suits, .suit)+Eval$(Cards, .card),
}
}
End Sub
Sub NextCard()
If Len(StackPack)=0 Then {
Suffle()
Stack StackPack {
Drop Random(0, 51)
}
}
Stack StackPack {
Read Card
}
End Sub
}
PlayCards
</syntaxhighlight>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">define(`randSeed',141592653)dnl
define(`setRand',
`define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))')dnl
Line 2,251 ⟶ 4,530:
deal deal(`b')
deal deal(`b')
show(`b')</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">MakeDeck[] := Tuples[{{"Ace ", 2, 3 , 4 , 5, 6 , 7 , 8 , 9 , 10, "Jack" , "Queen", "King"}, {♦ , ♣, ♥ , ♠}}]
DeckShuffle[deck_] := RandomSample[deck, Length@deck]
DealFromDeck[] := (Print@First@deck; deck = deck[[2 ;; All]];)</langsyntaxhighlight>
Example usage:
<pre>deck = DeckShuffle@MakeDeck[]; Print[deck]
Line 2,279 ⟶ 4,558:
{8,♥},{Jack,♠},{5,♥},{7,♣},{8,♠},{King,♣},{Queen,♦},{9,♥},{Ace ,♥},{3,♦},{7,♥},{Queen,♣},{10,♣},
{3,♥},{2,♥},{Jack,♥},{7,♦},{6,♠},{6,♥},{Ace ,♠},{9,♣}}</pre>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">suits = ["Spades", "Clubs", "Hearts", "Diamonds"]
pips = ["Ace","Two","Three","Four","Five","Six","Seven",
"Eight","Nine","Ten","Jack","Queen","King"]
 
Card = {}
Card.str = function()
return self.pip + " of " + self.suit + " (value: " + self.value + ")"
end function
 
//Build Deck
deck = []
for s in suits.indexes
for p in pips.indexes
card = new Card
card.suit = suits[s]
card.pip = pips[p]
card.value = s * 100 + p
deck.push card
end for
end for
draw = function(count=7)
hand = []
for i in range(1, count)
hand.push deck.pop
end for
return hand
end function
display = function(stack)
for card in stack
print card.str
end for
end function
print "Deck created. Cards in Deck: " + deck.len
deck.shuffle
print "Deck Shuffled"
hand = draw
print "First hand: "
display hand
 
print
print deck.len + " cards left in deck:"
display deck</syntaxhighlight>
{{out}}
<pre>Deck created. Cards in Deck: 52
Deck Shuffled
First hand:
Nine of Diamonds (value: 308)
Queen of Spades (value: 11)
Seven of Clubs (value: 106)
Ten of Diamonds (value: 309)
Seven of Hearts (value: 206)
Eight of Spades (value: 7)
King of Diamonds (value: 312)
45 cards left in deck:
Nine of Spades (value: 8)
Four of Spades (value: 3)
Queen of Hearts (value: 211)
(etc.)</pre>
 
=={{header|MUMPS}}==
See [[Playing Cards/MUMPS]]
 
=={{header|NimrodNim}}==
<syntaxhighlight lang="nim">import random, strutils
<lang nimrod>import math
randomize()
 
proc shuffle[T](x: var seq[T]) =
for i in countdown(x.high, 0):
let j = random(i + 1)
swap(x[i], x[j])
 
type
Suit* = enum ♥, ♦, ♣, ♠
 
Rank* {.pure.} = enum
Pip = enum c02, c03, c04, c05, c06, c07, c08, c09, c10, cQu, cKi, cAs
Ace = (1, "A")
Two = (2, "2")
Three = (3, "3")
Four = (4, "4")
Five = (5, "5")
Six = (6, "6")
Seven = (7, "7")
Eight = (8, "8")
Nine = (9, "9")
Ten = (10, "10")
Jack = (11, "J")
Queen = (12, "Q")
King = (13, "K")
 
Card* = objecttuple[rank: Rank; suit: Suit]
pip: Pip
suit: Suit
 
# Sequences of cards: synonyms for seq[Card].
Deck = object
Deck* cards:= seq[Card]
Hand* = seq[Card]
 
var initRandom = false # True if "randomize" has been called.
proc `$`(c: Card): string = $c.pip & $c.suit
 
 
proc initDeck(): Deck =
proc `$`*(c: Card): string =
result = Deck(cards: @[])
## Return the representation of a card.
$c.rank & $c.suit
 
 
proc initDeck*(): Deck =
## Initialize a deck.
for suit in Suit:
for piprank in PipRank:
result.cards.add Card(pip: piprank, suit: suit)
 
proc `$`(d: Deck): string = $d.cards
 
proc shuffle*(dcards: var Deckseq[Card]) = shuffle(d.cards)
## Shuffle a list of cards (deck or hand).
if not initRandom:
randomize()
initRandom = true
random.shuffle(cards)
 
proc deal(d: var Deck): Card =
d.shuffle()
d.cards.pop()
 
func `$`*(cards: seq[Card]): string =
var d = initDeck()
## Return the representation of a list o cards.
echo "40 cards from a deck:"
cards.join(" ")
for i in 0..4:
 
for j in 0..7:
 
stdout.write($d.deal(), " ")
func dealOne*(cards: var seq[Card]): Card =
echo ""
## Deal one card from a list of cards.
echo "The remaining cards are: ", $d</lang>
assert cards.len > 0
Output:
<pre>40 cards from a deck:.pop()
 
c10♦ c06♥ cKi♠ c09♥ c06♣ c02♦ c10♣ c08♣
 
c03♥ cQu♠ c07♠ c02♣ c04♦ c09♠ c07♦ c09♦
## Draw one card from a list of cards.
c02♠ c06♠ cKi♥ cAs♦ cAs♥ c04♥ c05♣ c02♥
let draw* = dealOne
cQu♥ c03♠ cQu♣ c05♦ c08♥ c04♠ c10♥ cQu♦
 
c04♣ c03♣ c03♦ cAs♠ c10♠ cKi♣ cKi♦ c05♠
 
The remaining cards are: @[c07♣, cAs♣, c05♥, c06♦, c08♦, c08♠, c09♣, c07♥]</pre>
func deal*(deck: var Deck; nPlayers: Positive; nCards: Positive): seq[Hand] =
## Deal "nCards" cards to "nPlayers" players.
assert deck.len >= nCards * nPlayers
result.setLen(nPlayers)
for n in 1..nCards:
for p in 0..<nPlayers:
result[p].add deck.pop()
 
 
when isMainModule:
import strformat
 
var deck = initDeck()
deck.shuffle()
echo "Initial deck after shuffling: "
for i in 0..2: echo deck[(i * 13)..(i * 13 + 12)], " ..."
echo deck[^13..^1]
 
echo "\nDeal eight cards for five players from the deck:"
var hands = deck.deal(5, 8)
for i, hand in hands: echo &"Player {i + 1} hand: ", hand
echo "Remaining cards: ", deck
 
echo "\nAfter player 1 drew a card from the deck: "
hands[0].add deck.draw()
echo "Player 1 hand: ", hands[0]
echo "Remaining cards: ", deck</syntaxhighlight>
 
{{out}}
<pre>Initial deck after shuffling:
A♦ Q♣ 2♣ A♥ 10♣ 3♠ Q♦ 7♦ A♣ 4♠ 9♥ 4♦ 7♠ ...
6♣ J♦ 7♥ 6♦ 9♠ 2♥ 8♥ 8♣ 8♦ 8♠ 4♣ 5♠ 2♦ ...
3♣ 9♦ 6♠ K♦ K♣ 5♦ 3♦ 10♠ J♠ 9♣ Q♥ 10♦ Q♠ ...
6♥ 5♣ 2♠ J♣ 3♥ K♠ A♠ 4♥ J♥ K♥ 10♥ 7♣ 5♥
 
Deal eight cards for five players from the deck:
Player 1 hand: 5♥ 4♥ 2♠ Q♥ 5♦ 3♣ 8♦ 6♦
Player 2 hand: 7♣ A♠ 5♣ 9♣ K♣ 2♦ 8♣ 7♥
Player 3 hand: 10♥ K♠ 6♥ J♠ K♦ 5♠ 8♥ J♦
Player 4 hand: K♥ 3♥ Q♠ 10♠ 6♠ 4♣ 2♥ 6♣
Player 5 hand: J♥ J♣ 10♦ 3♦ 9♦ 8♠ 9♠ 7♠
Remaining cards: A♦ Q♣ 2♣ A♥ 10♣ 3♠ Q♦ 7♦ A♣ 4♠ 9♥ 4♦
 
After player 1 drew a card from the deck:
Player 1 hand: 5♥ 4♥ 2♠ Q♥ 5♦ 3♣ 8♦ 6♦ 4♦
Remaining cards: A♦ Q♣ 2♣ A♥ 10♣ 3♠ Q♦ 7♦ A♣ 4♠ 9♥</pre>
 
=={{header|OCaml}}==
Straightforward implementation with algebraic types for the pips and suits, and lists of their values. A deck is an array of cards.
<langsyntaxhighlight lang="ocaml">type pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten |
Jack | Queen | King | Ace
let pips = [Two; Three; Four; Five; Six; Seven; Eight; Nine; Ten;
Jack; Queen; King; Ace]
 
type suit = Diamonds | Spades | Hearts | Clubs
let suits = [Diamonds; Spades; Hearts; Clubs]
 
type card = pip * suit
 
let full_deck = Array.of_list (List.concat (List.map (fun pip -> List.map (fun suit -> (pip, suit)) suits) pips))
 
(* Fisher-Yates shuffle *)
let shuffle deck =
for i = Array.length deck - 1 downto 1 do
let j = Random.int (i+1) in
(* swap deck.(i) and deck.(j) *)
let temp = deck.(i) in
deck.(i) <- deck.(j);
deck.(j) <- temp
done</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Uses a global variable v to pass around the remaining cards in the deck. If used inside a function this would be a good case for a dynamically-scoped variable (<code>local</code>) rather than the typically-preferred lexical scoping of <code>my</code>.
<langsyntaxhighlight lang="parigp">name(n)=Str(["A",2,3,4,5,6,7,8,9,10,"J","Q","K"][(n+3)>>2],["h","d","s","c"][n%4+1]);
newdeck()={
v=vector(52,i,i);
Line 2,381 ⟶ 4,779:
);
v
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 2,387 ⟶ 4,785:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">package Playing_Card_Deck;
 
use strict;
use warnings;
 
@Playing_Card_Deck::suits = qw
Line 2,405 ⟶ 4,804:
{my $invocant = shift;
my $class = ref($invocant) || $invocant;
my @cards = ();
foreach my $suit (@Playing_Card_Deck::suits)
{foreach my $pip (@Playing_Card_Deck::pips)
Line 2,414 ⟶ 4,813:
# Removes the top card of the given deck and returns it as a hash
# with the keys "suit" and "pip".
{return %{ shift( @{shift(@_)} ) };}
 
sub shuffle
Line 2,428 ⟶ 4,827:
sub print_cards
# Prints out a description of every card in the deck, in order.
{print "$_->{pip} of $_->{suit}\n" foreach @{shift(@_)};}</langsyntaxhighlight>
Some examples of use:
<langsyntaxhighlight lang="perl">my $deck = new Playing_Card_Deck->new;
$deck->shuffle;
my %card = $deck->deal;
print uc("$card{pip} OF $card{suit}\n");
$deck->print_cards;</langsyntaxhighlight>
This creates a new deck, shuffles it, removes the top card, prints out that card's name in all caps, and then prints the rest of the deck.
 
=={{header|Perl 6Phix}}==
Includes both ascii/console and unicode/gui displays
<lang perl6>enum Pip <A 2 3 4 5 6 7 8 9 10 J Q K>;
{{libheader|Phix/pGUI}}
enum Suit <♦ ♣ ♥ ♠>;
<!--<syntaxhighlight lang="phix">-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Playing_cards.exw</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">deal</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">deck</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">nhands</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">ncards</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">hands</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">({},</span><span style="color: #000000;">nhands</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">ncards</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">nhands</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">hands</span><span style="color: #0000FF;">[</span><span style="color: #000000;">h</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">deck</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">deck</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">deck</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..$]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">deck</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hands</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #000080;font-style:italic;">--console:</span>
class Card {
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show_cards</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
has Pip $.pip;
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
has Suit $.suit;
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">1</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">sep</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)?</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"23456789TJQKA"</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]&</span><span style="color: #008000;">"SHDC"</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">/</span><span style="color: #000000;">13</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]&</span><span style="color: #000000;">sep</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">deck</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hands</span>
method Str { $!pip ~ $!suit }
}
<span style="color: #008080;">procedure</span> <span style="color: #000000;">console_show</span><span style="color: #0000FF;">()</span>
class Deck {
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hands</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
has Card @.cards = pick *,
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"hand%d:\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">})</span>
map { Card.new(:$^pip, :$^suit) }, (Pip.pick(*) X Suit.pick(*));
<span style="color: #000000;">show_cards</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hands</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"remaining cards(%d):\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">deck</span><span style="color: #0000FF;">)})</span>
<span style="color: #000000;">show_cards</span><span style="color: #0000FF;">(</span><span style="color: #000000;">deck</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000080;font-style:italic;">--GUI:</span>
method shuffle { @!cards .= pick: * }
<span style="color: #008080;">function</span> <span style="color: #000000;">cards_to_utf8</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">utf32</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">pip</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">utf32</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">0x1F0A1</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">pip</span><span style="color: #0000FF;">+(</span><span style="color: #000000;">pip</span><span style="color: #0000FF;">></span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">+</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">c</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">13</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">#10</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #000000;">i</span><span style="color: #0000FF;"><</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">utf32</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">'\n'</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">utf32_to_utf8</span><span style="color: #0000FF;">(</span><span style="color: #000000;">utf32</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
method deal { shift @!cards }
<span style="color: #008080;">constant</span> <span style="color: #000000;">FONT</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">`FONT="Arial, %d"`</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">92</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">gui_show</span><span style="color: #0000FF;">()</span>
method Str { ~@!cards }
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
method gist { ~@!cards }
<span style="color: #7060A8;">IupSetGlobal</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"UTF8MODE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"YES"</span><span style="color: #0000FF;">)</span>
}
 
<span style="color: #004080;">Ihandles</span> <span style="color: #000000;">lh</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
my Deck $d = Deck.new;
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hands</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
say "Deck: $d";
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"hand%d:"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">}))</span>
 
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">h</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cards_to_utf8</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hands</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])),</span><span style="color: #000000;">FONT</span><span style="color: #0000FF;">)</span>
my $top = $d.deal;
<span style="color: #000000;">lh</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">&</span><span style="color: #000000;">h</span>
say "Top card: $top";
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #000000;">lh</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"remaining cards:"</span><span style="color: #0000FF;">)</span>
$d.shuffle;
<span style="color: #000000;">lh</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cards_to_utf8</span><span style="color: #0000FF;">(</span><span style="color: #000000;">deck</span><span style="color: #0000FF;">),</span><span style="color: #000000;">FONT</span><span style="color: #0000FF;">)</span>
say "Deck, re-shuffled: ", $d;</lang>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lh</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">DECKSIZE</span><span style="color: #0000FF;">=</span><span style="color: #000000;">52</span>
<span style="color: #000000;">deck</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">DECKSIZE</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">show_cards</span><span style="color: #0000FF;">(</span><span style="color: #000000;">deck</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">deck</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hands</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">deal</span><span style="color: #0000FF;">(</span><span style="color: #000000;">deck</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">console_show</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">gui_show</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
(console)
<pre>Deck: 3♦ J♦ 4♥ 7♠ 7♣ 7♥ 9♣ K♥ 6♠ 2♦ 3♠ Q♥ 8♥ 2♥ J♥ 5♥ 8♦ 8♣ 6♦ 7♦ 5♦ 2♣ 4♦ 8♠ 9♥ 4♣ 3♥ K♠ 2♠ 5♣ Q♣ Q♦ K♦ 4♠ 9♦ Q♠ 5♠ 6♥ J♣ J♠ K♣ 9♠ 3♣ 6♣
<pre>
Top card: 3♦
JC QC 6C 3D QS 7C 7D KS 2S AH TD TS 3C
Deck, re-shuffled: K♦ 4♣ J♠ 2♥ J♥ K♣ 6♣ 5♠ 3♥ 6♦ 5♦ 4♠ J♣ 4♦ 6♥ K♥ 7♥ 7♦ 2♦ 4♥ 6♠ 7♣ 9♦ 3♣ 3♠ 2♣ 2♠ 8♦ 5♣ 9♠ 5♥ J♦ 9♥ Q♦ Q♣ Q♥ Q♠ 8♥ 8♠ K♠ 9♣ 8♣ 7♠</pre>
QH 5H 4S KD 9S 8H QD 3S TC 2H 6S 9C 3H
7S 5S 8C 2D 5D 2C 4H 8S 9D JS 4D 8D JD
KH AS 6D AC JH 4C 6H KC TH 9H 5C AD 7H
hand1:
2S 3S QS KD 3C 9C JC
hand2:
9S 3H QH AH 7C TC QC
hand3:
7S 2H 5H 8H 7D TD 6C
hand4:
4S 5S 6S TS KS 3D QD
remaining cards(24):
8C 2D 5D 2C 4H 8S 9D JS 4D 8D JD KH AS
6D AC JH 4C 6H KC TH 9H 5C AD 7H
</pre>
 
=={{header|PHP}}==
{{works with|PHP|5.3+}}
Implementation:
<langsyntaxhighlight lang="php">class Card
{
// if unable to save as UTF-8, use other, non-UTF-8, symbols here
Line 2,751 ⟶ 5,216:
return $result[ 0 ];
}
}</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight lang="php">// if viewing in a browser, lets output a text/plain header with utf-8 charset
header( 'Content-Type: text/plain; charset=utf-8' );
 
Line 2,810 ⟶ 5,275:
 
// show the remaining cards in the deck
echo PHP_EOL . count( $deck ) . ' cards remaining in the deck: ' . PHP_EOL . $deck . PHP_EOL;</langsyntaxhighlight>
 
This will output something like:
Line 2,832 ⟶ 5,297:
24 cards remaining in the deck:
♥A ♥6 ♦2 ♦5 ♥J ♣T ♦3 ♠5 ♠A ♣8 ♥8 ♥7 ♥K ♦7 ♥T ♦6 ♦T ♣6 ♣3 ♣A ♦4 ♥4 ♠6 ♣9</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
% Create and print the deck
deck(Deck),
print_deck(Deck),
nl,
% Shuffle the deck
print_deck(shuffle(Deck)),
nl,
 
% Deal 3 cards
Deck := deal(Deck,Card1),
Deck := deal(Deck,Card2),
Deck := deal(Deck,Card3),
 
println(deal1=Card1),
println(deal2=Card2),
println(deal3=Card3),
% The remaining deck
print_deck(Deck),
nl,
 
% Deal 5 cards
Deck := deal(Deck,Card4),
Deck := deal(Deck,Card5),
Deck := deal(Deck,Card6),
Deck := deal(Deck,Card7),
Deck := deal(Deck,Card8),
 
println(cards4_to_8=[Card4,Card5,Card6,Card7,Card8]),
nl,
 
% Deal 5 cards
Deck := deal_n(Deck,5,FiveCards),
println(fiveCards=FiveCards),
print_deck(Deck),
nl,
 
% And deal some more cards
% This chaining works since deal/1 returns the remaining deck
Deck := Deck.deal(Card9).deal(Card10).deal(Card11).deal(Card12),
println("4_more_cards"=[Card9,Card10,Card11,Card12]),
print_deck(Deck),
 
nl.
 
% suits(Suits) => Suits = ["♠","♥","♦","♣"].
suits(Suits) => Suits = ["C","H","S","D"].
values(Values) => Values = ["A","2","3","4","5","6","7","8","9","T","J","Q","K"].
 
% Create a (sorted) deck.
deck(Deck) =>
suits(Suits),
values(Values),
Deck =[S++V :V in Values, S in Suits].sort().
 
% Shuffle a deck
shuffle(Deck) = Deck2 =>
Deck2 = Deck,
Len = Deck2.length,
foreach(I in 1..Len)
R2 = random(1,Len),
Deck2 := swap(Deck2,I,R2)
end.
 
% Swap position I <=> J in list L
swap(L,I,J) = L2, list(L) =>
L2 = L,
T = L2[I],
L2[I] := L2[J],
L2[J] := T.
 
 
% The first card is returned as the out parameter Card.
% The deck is returned as the function value.
deal(Deck, Card) = Deck.tail() => Card = Deck.first().
 
% Deal N cards
deal_n(Deck, N, Cards) = [Deck[I] : I in Len+1..Deck.length] =>
Len = min(N,Deck.length),
Cards = [Deck[I] : I in 1..Len].
 
% Print deck
print_deck(Deck) =>
println("Deck:"),
foreach({Card,I} in zip(Deck,1..Deck.len))
printf("%w ", Card),
if I mod 10 == 0 then
nl
end
end,
nl.</syntaxhighlight>
 
{{out}}
<pre>Deck:
C2 C3 C4 C5 C6 C7 C8 C9 CA CJ
CK CQ CT D2 D3 D4 D5 D6 D7 D8
D9 DA DJ DK DQ DT H2 H3 H4 H5
H6 H7 H8 H9 HA HJ HK HQ HT S2
S3 S4 S5 S6 S7 S8 S9 SA SJ SK
SQ ST
 
Deck:
SA C2 D7 C7 C4 S8 HT D9 DA H6
D6 S6 H2 C5 H8 ST SJ HQ S9 DQ
D5 C6 CJ H4 S5 HK CK HJ H5 D8
H9 C8 D4 CQ H3 H7 SK S4 DK SQ
CA S7 D2 C9 DJ HA DT S2 C3 CT
D3 S3
 
deal1 = SA
deal2 = C2
deal3 = D7
Deck:
C7 C4 S8 HT D9 DA H6 D6 S6 H2
C5 H8 ST SJ HQ S9 DQ D5 C6 CJ
H4 S5 HK CK HJ H5 D8 H9 C8 D4
CQ H3 H7 SK S4 DK SQ CA S7 D2
C9 DJ HA DT S2 C3 CT D3 S3
 
cards4_to_8 = [C7,C4,S8,HT,D9]
 
fiveCards = [DA,H6,D6,S6,H2]
Deck:
C5 H8 ST SJ HQ S9 DQ D5 C6 CJ
H4 S5 HK CK HJ H5 D8 H9 C8 D4
CQ H3 H7 SK S4 DK SQ CA S7 D2
C9 DJ HA DT S2 C3 CT D3 S3
 
4_more_cards = [C5,H8,ST,SJ]
Deck:
HQ S9 DQ D5 C6 CJ H4 S5 HK CK
HJ H5 D8 H9 C8 D4 CQ H3 H7 SK
S4 DK SQ CA S7 D2 C9 DJ HA DT
S2 C3 CT D3 S3 </pre>
 
 
=={{header|PicoLisp}}==
{{trans|Common Lisp}}
<langsyntaxhighlight PicoLisplang="picolisp">(de *Suits
Club Diamond Heart Spade )
 
Line 2,847 ⟶ 5,450:
 
(de shuffle (Lst)
(by '(NIL (rand)) sort Lst) )</langsyntaxhighlight>
 
=={{header|PowerShell}}==
This implementation was designed as a pre-requisite to other cards games. For this reason, this has the ability to have more than one persistent deck, more than one persistent hand, and shuffle the ''same deck'' over and over again or after some cards have been dealt out. There is also a full help file accessed by typing
''Get-Help Any-Function -full''
<syntaxhighlight lang="powershell">
<#
.Synopsis
Creates a new "Deck" which is a hashtable converted to a dictionary
This is only used for creating the deck, to view/list the deck contents use Get-Deck.
.DESCRIPTION
Casts the string value that the user inputs to the name of the variable that holds the "deck"
Creates a global variable, allowing you to use the name you choose in other functions and allows you to create
multiple decks under different names.
.EXAMPLE
PS C:\WINDOWS\system32> New-Deck
cmdlet New-Deck at command pipeline position 1
Supply values for the following parameters:
YourDeckName: Deck1
 
PS C:\WINDOWS\system32>
 
.EXAMPLE
PS C:\WINDOWS\system32> New-Deck -YourDeckName Deck2
 
PS C:\WINDOWS\system32>
.EXAMPLE
PS C:\WINDOWS\system32> New-Deck -YourDeckName Deck2
 
PS C:\WINDOWS\system32> New-Deck -YourDeckName Deck3
 
PS C:\WINDOWS\system32>
#>
function New-Deck
{
[CmdletBinding()]
[OutputType([int])]
Param
(
# Name your Deck, this will be the name of the variable that holds your deck
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$False,
Position=0)]$YourDeckName
)
 
Begin
{
$Suit = @(' of Hearts', ' of Spades', ' of Diamonds', ' of Clubs')
$Pip = @('Ace', 'King', 'Queen', 'Jack', '10', '9', '8', '7', '6', '5', '4', '3', '2')
 
#Creates the hash table that will hold the suit and pip variables
$Deck = @{}
#creates counters for the loop below to make 52 total cards with 13 cards per suit
[int]$SuitCounter = 0
[int]$PipCounter = 0
[int]$CardValue = 0
 
}
Process
{
#Creates the initial deck
do
{
#card2add is the rows in the hashtable
$Card2Add = ($Pip[$PipCounter]+$Suit[$SuitCounter])
 
#Addes the row to the hashtable
$Deck.Add($CardValue, $Card2Add)
 
#Used to create the Keys
$CardValue++
 
#Counts the amount of cards per suit
$PipCounter ++
if ($PipCounter -eq 13)
{
#once reached the suit is changed
$SuitCounter++
#and the per-suit counter is reset
$PipCounter = 0
}
else
{
continue
}
}
#52 cards in a deck
until ($Deck.count -eq 52)
 
}
End
{
#sets the name of a variable that is unknown
#Then converts the hash table to a dictionary and pipes it to the Get-Random cmdlet with the arguments to randomize the contents
Set-Variable -Name "$YourDeckName" -Value ($Deck.GetEnumerator() | Get-Random -Count ([int]::MaxValue)) -Scope Global
}
}
 
<#
.Synopsis
Lists the cards in your selected deck
.DESCRIPTION
Contains a Try-Catch-Finally block in case the deck requested has not been created
.EXAMPLE
PS C:\WINDOWS\system32> Get-Deck -YourDeckName deck1
 
8 of Clubs
5 of Hearts
--Shortened--
King of Clubs
Jack of Diamonds
 
PS C:\WINDOWS\system32>
 
 
.EXAMPLE
PS C:\WINDOWS\system32> Get-Deck -YourDeckName deck2
 
deck2 does not exist...
Creating Deck deck2...
 
Ace of Spades
10 of Hearts
--Shortened--
5 of Clubs
4 of Clubs
 
PS C:\WINDOWS\system32>
 
.EXAMPLE
PS C:\WINDOWS\system32> deck deck2
 
Ace of Spades
10 of Hearts
--Shortened--
4 of Spades
6 of Spades
Queen of Spades
 
PS C:\WINDOWS\system32>
#>
function Get-Deck
{
[CmdletBinding()]
[Alias('Deck')]
[OutputType([int])]
Param
(
#Brings the Vairiable in from Get-Deck
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]$YourDeckName
)
 
Begin
{
}
Process
{
# Will return a terminal error if the deck has not been created
try
{
$temp = Get-Variable -name "$YourDeckName" -ValueOnly -ErrorAction stop
}
catch
{
Write-Host
Write-Host "$YourDeckName does not exist..."
Write-Host "Creating Deck $YourDeckName..."
New-Deck -YourDeckName $YourDeckName
$temp = Get-Variable -name "$YourDeckName" -ValueOnly
}
 
finally
{
$temp | select Value | ft -HideTableHeaders
}
 
}
End
{
Write-Verbose "End of show-deck function"
}
}
 
<#
.Synopsis
Shuffles a deck of your selection with Get-Random
.DESCRIPTION
This function can be used to Shuffle any deck that has been created.
This can be used on a deck that has less than 52 cards
Contains a Try-Catch-Finally block in case the deck requested has not been created
Does NOT output the value of the deck being shuffled (You wouldn't look at the cards you shuffled, would you?)
 
.EXAMPLE
PS C:\WINDOWS\system32> Shuffle-Deck -YourDeckName Deck1
Your Deck was shuffled
 
PS C:\WINDOWS\system32>
 
.EXAMPLE
PS C:\WINDOWS\system32> Shuffle NotMadeYet
 
NotMadeYet does not exist...
Creating and shuffling NotMadeYet...
Your Deck was shuffled
 
PS C:\WINDOWS\system32>
#>
function Shuffle-Deck
{
[CmdletBinding()]
[Alias('Shuffle')]
[OutputType([int])]
Param
(
#The Deck you want to shuffle
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]$YourDeckName)
Begin
{
Write-Verbose 'Shuffles your deck with Get-Random'
}
Process
{
# Will return a missing variable error if the deck has net been created
try
{
#These two commands could be on one line using the pipeline, but look cleaner on two
$temp1 = Get-Variable -name "$YourDeckName" -ValueOnly -ErrorAction stop
$temp1 = $temp1 | Get-Random -Count ([int]::MaxValue)
}
catch
{
Write-Host
Write-Host "$YourDeckName does not exist..."
Write-Host "Creating and shuffling $YourDeckName..."
New-Deck -YourDeckName $YourDeckName
$temp1 = Get-Variable -name "$YourDeckName" -ValueOnly
$temp1 = $temp1 | Get-Random -Count ([int]::MaxValue)
 
}
 
finally
{
#Gets the actual value of variable $YourDeckName from the New-Deck function and uses that string value
#to set the variables name
Set-Variable -Name "$YourDeckName" -value ($temp1) -Scope Global
}
}
End
{
Write-Host "Your Deck was shuffled"
}
}
 
<#
.Synopsis
Creates a new "Hand" which is a hashtable converted to a dictionary
This is only used for creating the hand, to view/list the deck contents use Get-Hand.
.DESCRIPTION
Casts the string value that the user inputs to the name of the variable that holds the "hand"
Creates a global variable, allowing you to use the name you choose in other functions and allows you to create
multiple hands under different names.
.EXAMPLE
PS C:\WINDOWS\system32> New-Hand -YourHandName JohnDoe
 
PS C:\WINDOWS\system32>
.EXAMPLE
PS C:\WINDOWS\system32> New-Hand JaneDoe
 
PS C:\WINDOWS\system32>
>
#>
function New-Hand
{
[CmdletBinding()]
[OutputType([int])]
Param
(
# Name your Deck, this will be the name of the variable that holds your deck
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$False,
Position=0)]$YourHandName
)
 
Begin
{
$Hand = @{}
}
Process
{
}
End
{
Set-Variable -Name "$YourHandName" -Value ($Hand.GetEnumerator()) -Scope Global
}
}
 
<#
.Synopsis
Lists the cards in the selected Hand
.DESCRIPTION
Contains a Try-Catch-Finally block in case the hand requested has not been created
.EXAMPLE
#create a new hand
PS C:\WINDOWS\system32> New-Hand -YourHandName Hand1
 
PS C:\WINDOWS\system32> Get-Hand -YourHandName Hand1
Hand1's hand contains cards, they are...
 
PS C:\WINDOWS\system32>
#This hand is empty
.EXAMPLE
PS C:\WINDOWS\system32> Get-Hand -YourHandName Hand2
 
Hand2 does not exist...
Creating Hand Hand2...
Hand2's hand contains cards, they are...
 
PS C:\WINDOWS\system32>
 
.EXAMPLE
PS C:\WINDOWS\system32> hand hand3
hand3's hand contains 4 cards, they are...
 
5 of Spades
4 of Spades
6 of Spades
Queen of Diamonds
#>
function Get-Hand
{
[CmdletBinding()]
[Alias('Hand')]
[OutputType([int])]
Param
(
#Brings the Vairiable in from Get-Deck
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]$YourHandName
)
Begin
{
}
Process
{
# Will return a missing variable error if the deck has net been created
try
{
$temp = Get-Variable -name "$YourHandName" -ValueOnly -ErrorAction stop
}
catch
{
Write-Host
Write-Host "$YourHandName does not exist..."
Write-Host "Creating Hand $YourHandName..."
New-Hand -YourHandName $YourHandName
$temp = Get-Variable -name "$YourHandName" -ValueOnly
}
 
finally
{
$count = $temp.count
Write-Host "$YourHandName's hand contains $count cards, they are..."
$temp | select Value | ft -HideTableHeaders
}
 
}
End
{
Write-Verbose "End of show-deck function"
}
}
 
<#
.Synopsis
Draws/returns cards
.DESCRIPTION
Draws/returns cards from your chosen deck , to your chosen hand
Can be used without creating a deck or hand first
.EXAMPLE
PS C:\WINDOWS\system32> DrawFrom-Deck -YourDeckName Deck1 -YourHandName test1 -HowManyCardsToDraw 10
 
 
PS C:\WINDOWS\system32>
.EXAMPLE
DrawFrom-Deck -YourDeckName Deck2 -YourHandName test2 -HowManyCardsToDraw 10
Deck2 does not exist...
Creating Deck Deck2...
 
test2 does not exist...
Creating Hand test2...
test2's hand contains cards, they are...
 
 
.EXAMPLE
PS C:\WINDOWS\system32> draw -YourDeckName deck1 -YourHandName test1 -HowManyCardsToDraw 5
 
 
 
#>
function Draw-Deck
{
[CmdletBinding()]
[Alias('Draw')]
[OutputType([int])]
Param
(
# The Deck in which you want to draw cards out of
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]$YourDeckName,
#The hand in which you want to draw cards to
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]$YourHandName,
 
 
#Quanity of cards being drawn
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]$HowManyCardsToDraw
 
)
Begin
{
Write-Verbose "Draws a chosen amount of cards from the chosen deck"
 
#try-catch-finally blocks so the user does not have to use New-Deck and New-Hand beforehand.
try
{
$temp = Get-Variable -name "$YourDeckName" -ValueOnly -ErrorAction Stop
}
catch
{
Get-Deck -YourDeckName $YourDeckName
$temp = Get-Variable -name "$YourDeckName" -ValueOnly -ErrorAction Stop
}
finally
{
Write-Host
}
 
try
{
$temp2 = Get-Variable -name "$YourHandName" -ValueOnly -ErrorAction Stop
}
catch
{
Get-Hand -YourHandName $YourHandName
$temp2 = Get-Variable -name "$YourHandName" -ValueOnly -ErrorAction Stop
}
finally
{
Write-Host
}
}
 
Process
{
Write-Host "you drew $HowManyCardsToDraw cards, they are..."
 
$handValues = Get-Variable -name "$YourDeckName" -ValueOnly
$handValues = $handValues[0..(($HowManyCardsToDraw -1))] | select value | ft -HideTableHeaders
$handValues
 
}
End
{
#sets the new values for the deck and the hand selected
Set-Variable -Name "$YourDeckName" -value ($temp[$HowManyCardsToDraw..($temp.count)]) -Scope Global
Set-Variable -Name "$YourHandName" -value ($temp2 + $handValues) -Scope Global
}
}
</syntaxhighlight>
Results of using ''Draw-Deck'' without creating a hand or deck beforehand.
Note: Due to length I've shortened some of the results, however when run it returns everything:
<pre>
PS C:\WINDOWS\system32> Draw-Deck -YourDeckName TestDeck -YourHandName TestHand -HowManyCardsToDraw 5
 
TestDeck does not exist...
Creating Deck TestDeck...
 
2 of Spades
7 of Hearts
--Shortened--
6 of Spades
10 of Diamonds
 
 
TestHand does not exist...
Creating Hand TestHand...
TestHand's hand contains cards, they are...
 
you drew 5 cards, they are...
 
2 of Spades
Jack of Hearts
King of Clubs
Queen of Diamonds
4 of Spades
 
</pre>
 
Results of ''Get-Hand'':
<pre>
PS C:\WINDOWS\system32> Get-Hand -YourHandName TestHand
TestHand's hand contains 5 cards, they are...
 
King of Spades
King of Clubs
10 of Clubs
2 of Clubs
Ace of Spades
 
PS C:\WINDOWS\system32>
 
</pre>
Results of dealing all but 10 cards out of a deck and then shuffling the remaining cards in the deck:
<pre>
PS C:\WINDOWS\system32> draw -YourDeckName Deck -YourHandName MyHand -HowManyCardsToDraw 42
 
Deck does not exist...
Creating Deck Deck...
 
8 of Spades
2 of Diamonds
--Shortened--
6 of Hearts
5 of Spades
 
MyHand does not exist...
Creating Hand MyHand...
MyHand's hand contains cards, they are...
 
you drew 42 cards, they are...
 
8 of Spades
--Shortened--
2 of Clubs
 
PS C:\WINDOWS\system32> Get-Deck deck
 
6 of Diamonds
Ace of Diamonds
6 of Clubs
5 of Diamonds
9 of Hearts
Queen of Diamonds
9 of Diamonds
4 of Hearts
6 of Hearts
5 of Spades
 
PS C:\WINDOWS\system32> $deck.count
10
 
PS C:\WINDOWS\system32> Shuffle-Deck deck
Your Deck was shuffled
 
PS C:\WINDOWS\system32> Get-Deck deck
 
5 of Diamonds
Ace of Diamonds
9 of Hearts
6 of Hearts
6 of Diamonds
4 of Hearts
9 of Diamonds
6 of Clubs
Queen of Diamonds
5 of Spades
 
PS C:\WINDOWS\system32>
 
</pre>
 
=={{header|Prolog}}==
Line 2,853 ⟶ 6,043:
{{works with|SWI Prolog|4.8.0}}
 
<langsyntaxhighlight Prologlang="prolog">/** <module> Cards
 
A card is represented by the term "card(Pip, Suit)".
Line 2,891 ⟶ 6,081:
print_card(card(Pip, Suit)) :-
format('~a of ~a~n', [Pip, Suit]).
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
This approach keeps track of the cards in an abbrieviated form but allows them to be expanded to a more wordy form when they are dealt or shown.
<langsyntaxhighlight PureBasiclang="purebasic">#MaxCards = 52 ;Max Cards in a deck
Structure card
pip.s
Line 3,027 ⟶ 6,218:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>Dealt: Queen of Hearts
Line 3,042 ⟶ 6,233:
=={{header|Python}}==
===Python 2.x, standalone===
<langsyntaxhighlight lang="python">import random
 
class Card(object):
Line 3,067 ⟶ 6,258:
def deal(self):
self.shuffle() # Can't tell what is next from self.deck
return self.deck.pop(0)</langsyntaxhighlight>
 
===Python 3: extending [[Poker hand analyser#Python]]===
Assume the code from [[Poker hand analyser#Python]] is in a file pokerhand.py and importable.
<langsyntaxhighlight lang="python">from pokerhand import Card, suit, face
from itertools import product
from random import randrange
Line 3,095 ⟶ 6,286:
print(deck.deal(), end=' ')
print()
print('\nThe remaining cards are a', deck)</langsyntaxhighlight>
 
{{out}}
Line 3,107 ⟶ 6,298:
 
The remaining cards are a Deck of 2♦ 2♠ 4♦ 4♠ 5♦ 6♦ 8♦ 8♣ j♥ j♠ q♦ a♦</pre>
 
=={{header|Quackery}}==
 
This task is the subject of the chapter Dealing With Quackery in the book The Book of Quackery, which can be found at the GitHub Quackery repository, here: [https://github.com/GordonCharlton/Quackery]. Code presented here is done so with the permission of the author (me).
 
First, a demonstration in the Quackery shell of sufficient of the code to fulfil the requirements of this task:
 
<pre>/O> newpack +jokers 3 riffles 4 players 7 deal
... say "The player's hands..." cr cr
... witheach [ echohand cr ]
... say "Cards left in the pack (the talon)..." cr cr
... echohand
...
The player's hands...
 
eight of hearts
seven of clubs
nine of hearts
two of diamonds
three of diamonds
three of hearts
seven of spades
 
low joker
ace of hearts
ace of clubs
queen of diamonds
nine of clubs
six of spades
six of diamonds
 
ten of diamonds
five of spades
jack of diamonds
two of hearts
two of clubs
five of diamonds
ten of clubs
 
ace of diamonds
ace of spades
eight of clubs
king of diamonds
four of diamonds
ten of hearts
three of clubs
 
Cards left in the pack (the talon)...
 
eight of spades
four of hearts
jack of hearts
four of clubs
nine of spades
ten of spades
two of spades
five of hearts
seven of diamonds
five of clubs
jack of clubs
eight of diamonds
six of hearts
queen of hearts
three of spades
nine of diamonds
six of clubs
queen of clubs
four of spades
seven of hearts
jack of spades
queen of spades
king of hearts
king of spades
king of clubs
high joker
</pre>
 
A listing of the code accompanying the chapter, which does the above and more:
 
<syntaxhighlight lang="quackery"> [ /mod if 1+ ] is /up ( n n --> n )
 
[ [] 52 times [ i^ join ] ] is newpack ( --> [ )
 
[ -13 swap join ] is +lowjoker ( [ --> [ )
 
[ 64 join ] is +highjoker ( [ --> [ )
 
[ +lowjoker +highjoker ] is +jokers ( [ --> [ )
 
[ [ table
$ 'ace' $ 'two' $ 'three'
$ 'four' $ 'five' $ 'six'
$ 'seven' $ 'eight' $ 'nine'
$ 'ten' $ 'jack' $ 'queen'
$ 'king' ] do ] is rank ( n --> $ )
 
[ [ table
$ 'clubs' $ 'diamonds'
$ 'hearts' $ 'spades' ]
do ] is suit ( n --> $ )
 
[ dup -13 = iff
[ drop $ 'low joker' ] done
dup 64 = iff
[ drop $ 'high joker' ] done
13 /mod rank
$ ' of ' join
swap suit join ] is card ( n --> $ )
 
[ [] swap
witheach
[ card join
carriage join ] ] is hand ( [ --> $ )
 
[ card echo$ ] is echocard ( n --> )
 
[ hand echo$ ] is echohand ( [ --> )
 
[ > ] is bysuit ( n n --> b )
 
[ 13 /mod 4 * + ] is rankfirst ( n --> n )
 
[ rankfirst
swap rankfirst < ] is byrank ( n n --> b )
 
[ dup [] != while
dup size random split
swap join ] is cut ( [ --> [ )
 
[ dup [] != while
dup size 2 * 3 /up
random split
dup size dup iff
[ random split
dip swap join ]
else drop join ] is scarne ( [ --> [ )
 
[ [] nested swap of ] is players ( n --> [ )
 
[ temp put
over size * times
[ over [] = iff
[ 1 split swap join ]
else
[ swap temp share split
swap rot behead
rot join
nested join ] ]
temp release ] is dealby ( [ [ n n --> [ [ )
 
[ 1 dealby ] is deal ( [ [ n --> [ [ )
 
[ 1 swap dealby ] is dealeach ( [ [ n --> [ [ )
 
[ over size deal ] is dealall ( [ [ --> [ [ )
 
[ [] swap
[ behead 1 split
dip [ swap dip join ]
dup [] = iff
drop
else
[ nested join ]
dup [] = until ]
drop swap join ] is undeal ( [ [ --> [ )
 
[ over size over size
tuck /mod
rot over -
dip [ over 1+ swap of ]
rot swap of join
swap []
2swap
witheach
[ split unrot nested join
swap ]
unrot witheach
[ dip behead join
nested join ] ] is divvy ( [ [ --> [ [ )
 
[ newpack
4 players divvy
witheach
[ 1 split 7 split
nip join join ]
+highjoker ] is euchrepack ( --> [ )
 
[ [] swap witheach join
swap join ] is gather ( [ [ --> [ )
 
[ 2 players divvy undeal ] is faro-out ( [ --> [ )
 
[ 2 players divvy
1 split swap join undeal ] is faro-in ( [ --> [ )
 
[ unrot times
[ over i bit & iff
faro-in else faro-out ]
nip ] is faro ( [ n n --> [ )
 
[ players dealall gather ] is piles ( [ n --> [ )
 
[ players dealall
shuffle gather ] is mixpiles ( [ --> [ )
 
[ stack 5 ] is riffskill ( --> [ )
 
[ [] swap
dup size 2 /up split
2 random if swap
[ dup [] != while
behead nested
dip rot join unrot
riffskill share 1+ random
1 != if swap
again ] drop join ] is riffle ( [ --> [ )
 
[ times riffle ] is riffles ( [ n --> [ )</syntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">pips <- c("2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace")
suit <- c("Clubs", "Diamonds", "Hearts", "Spades")
# Create a deck
Line 3,133 ⟶ 6,542:
deck <- deal(deck)
# While no-one is looking, sneakily deal a card from the bottom of the pack
deck <- deal(deck, FALSE)</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight Racketlang="racket">#lang racket
 
;; suits:
Line 3,158 ⟶ 6,567:
(set-box! deck (shuffle (unbox deck))))
 
;; deal a card from tAthe 2 3 4 5 6 7 8 9 10 J Q K>;deck:
enum Suit he deck:
(define (deck-deal deck)
(begin0 (first (unbox deck))
Line 3,170 ⟶ 6,578:
(deck-deal my-deck)
(deck-deal my-deck)
(length (unbox my-deck))</langsyntaxhighlight>
 
{{out}}
Line 3,180 ⟶ 6,588:
> </pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2016.08}}
<syntaxhighlight lang="raku" line>enum Pip <A 2 3 4 5 6 7 8 9 10 J Q K>;
enum Suit <♦ ♣ ♥ ♠>;
class Card {
has Pip $.pip;
has Suit $.suit;
method Str { $!pip ~ $!suit }
}
class Deck {
has Card @.cards = pick *,
map { Card.new(:$^pip, :$^suit) }, flat (Pip.pick(*) X Suit.pick(*));
method shuffle { @!cards .= pick: * }
method deal { shift @!cards }
method Str { ~@!cards }
method gist { ~@!cards }
}
 
my Deck $d = Deck.new;
say "Deck: $d";
 
my $top = $d.deal;
say "Top card: $top";
 
$d.shuffle;
say "Deck, re-shuffled: ", $d;</syntaxhighlight>
{{out}}
<pre>Deck: 3♦ J♦ 4♥ 7♠ 7♣ 7♥ 9♣ K♥ 6♠ 2♦ 3♠ Q♥ 8♥ 2♥ J♥ 5♥ 8♦ 8♣ 6♦ 7♦ 5♦ 2♣ 4♦ 8♠ 9♥ 4♣ 3♥ K♠ 2♠ 5♣ Q♣ Q♦ K♦ 4♠ 9♦ Q♠ 5♠ 6♥ J♣ J♠ K♣ 9♠ 3♣ 6♣
Top card: 3♦
Deck, re-shuffled: K♦ 4♣ J♠ 2♥ J♥ K♣ 6♣ 5♠ 3♥ 6♦ 5♦ 4♠ J♣ 4♦ 6♥ K♥ 7♥ 7♦ 2♦ 4♥ 6♠ 7♣ 9♦ 3♣ 3♠ 2♣ 2♠ 8♦ 5♣ 9♠ 5♥ J♦ 9♥ Q♦ Q♣ Q♥ Q♠ 8♥ 8♠ K♠ 9♣ 8♣ 7♠</pre>
 
=={{header|Red}}==
<syntaxhighlight lang="rebol">
Red [Title: "Playing Cards"]
 
pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"]
suit: ["♣" "♦" "♥" "♠"]
 
make-deck: function [] [
new-deck: make block! 52
foreach s suit [foreach p pip [append/only new-deck reduce [p s]]]
return new-deck
]
 
shuffle: function [deck [block!]] [deck: random deck]
 
deal: function [other-deck [block!] deck [block!]] [unless empty? deck [append/only other-deck take deck]]
 
contents: function [deck [block!]] [
line: 0
repeat i length? deck [
prin [trim/all form deck/:i " "]
if (to-integer i / 13) > line [line: line + 1 print ""]
]]
 
deck: shuffle make-deck
print "40 cards from a deck:"
loop 5 [ print "" loop 8 [prin [trim/all form take deck " "]]]
prin "^/^/remaining: "
contents deck
</syntaxhighlight>
{{out}}
<pre>
40 cards from a deck:
 
a♣ 3♠ 6♦ 9♦ 8♦ q♣ a♥ 8♣
10♥ 3♥ a♦ k♦ 6♣ 9♣ k♥ 4♥
j♠ j♣ 5♦ q♦ 9♠ 2♥ 10♦ k♣
4♦ k♠ j♥ 5♠ q♠ 8♠ 2♣ 7♥
3♣ 2♦ 5♥ 7♦ 6♠ 6♥ q♥ 9♥
 
remaining: 3♦ 10♠ a♠ 7♠ 8♥ 4♣ j♦ 5♣ 2♠ 7♣ 4♠ 10♣
</pre>
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 1) Build ordered Card deck
* 2) Create shuffled stack
Line 3,231 ⟶ 6,719:
Say 'Left on shuffled stack:'
Say ' 'subword(ss,1,26) /* and what's left on stack */
Say ' 'subword(ss,27,6)</langsyntaxhighlight>
Output:
<pre>
Line 3,250 ⟶ 6,738:
 
===version 2===
A check is made to see if ASCII characters can be used to display the suits &nbsp; (if using an ASCII machine).
<lang rexx>/*REXX pgm shows methods (subroutines) to build/shuffle/deal a card deck*/
<syntaxhighlight lang="rexx">/*REXX pgm shows a method to build/shuffle/deal 5 cards (using a 52─card deck)──►4 hands*/
call buildDeck ; say ' new deck:' newDeck /*new 52-card deck*/
callbox shuffleDeck= build(); say 'shuffled deckbox of cards:' theDeck box /*shuffleda deck.brand new standard box of 52 cards.*/
calldeck= dealHandsmix(); 5,4 say 'shuffled deck:' deck /*obtain a randomly shuffled deck. /*5 cards, 4 hands*/
call deal 5, 4 /* ◄───────────────── 5 cards, 4 hands.*/
say; say; say right('[north]' hand.1,50)
say; say; say '[west]' hand.4 say right('[eastnorth]' hand.21, 60)
say; say ' [west]' hand.4 right('[southeast]' hand.32,50 60)
say; say; say; say right('[south]'remainder of deck:' hand.3, theDeck60)
exitsay; say; say; say 'remainder of deck: ' /*stick a fork in it, we're done.*/deck
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────BUILDDECK subroutine────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
buildDeck: _=''; ranks='A 2 3 4 5 6 7 8 9 10 J Q K' /*ranks. */
ifbuild: 1_=='f1'x; then suitsranks='h d"A c2 s'3 4 5 6 7 8 9 10 J Q K" /*EBCDIC?ranks. */
if 5=='f5'x elsethen suits='♥ "h d c s" ♠' /*ASCII.EBCDIC? */
else suits= "♥ ♠" do s=1 for words(suits) /*ASCII. */
do s=1 for words(suits); do r$=1 for wordsword(rankssuits, s)
do r=1 for words(ranks); _= _ word(ranks, r)$ /*append a suit to _=_ word(ranks,r)word(suits,s)rank*/
end /*dealRr*/
end /*s*/; return _ end; /*dealS*/ /*jokers newDeck=_are not used. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
return
deal: parse arg #cards, hands; hand.= /*initially, nullify all hands. */
/*──────────────────────────────────SHUFFLEDECK subroutine──────────────*/
do #cards /*deal a hand to all the players. */
shuffleDeck: theDeck=''; _=newDeck; #cards=words(_)
do shufflerplayer=1 for #cardshands /*shuffledeal all thesome cards into the deckplayers. */
r hand.player=random hand.player word(1deck,#cards+ 1-shuffler) /*randomdeal #the top decreasescard eachto timea player. */
theDeck=theDeck word deck= subword(_deck,r 2) /*sufffleddiminish deck, 1elide one card. at-a-time*/
_=delword(_,r,1) end /*delete the just-chosen card. player*/
end /*shuffler#cards*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
return
mix: @=; _=box; #cards= words(_) /*define three REXX variables. */
/*──────────────────────────────────DEALHANDS subroutine────────────────*/
do mixer=1 for #cards /*shuffle all the cards in deck. */
dealHands: parse arg numberOfCards,hands; hand.=''
do numberOfCards ?= random(1, #cards + 1 - mixer) /*deal the hand to the/*each players.shuffle, random# decreases.*/
do player@=1 @ for handsword(_, ?) /*deal a card to the players. /*shuffled deck, 1 card at a time.*/
hand.player_=hand.player subworddelword(theDeck_,1 ?, 1) /*dealelide topjust─chosen card. from deck*/
end /*mixer*/; return @</syntaxhighlight>
theDeck=subword(theDeck,2 ) /*diminish deck, remove one card.*/
{{out|output|text=&nbsp; when using the internal default values of four hands holding five cards:}}
end /*player*/
end /*numberOfCards*/
return</lang>
'''output'''
<pre>
box of new deckcards: A♥ 2♥ 3♥ 4♥ 5♥ 6♥ 7♥ 8♥ 9♥ 10♥ J♥ Q♥ K♥ A♦ 2♦ 3♦ 4♦ 5♦ 6♦ 7♦ 8♦ 9♦ 10♦ J♦ Q♦ K♦ A♣ 2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣ Q♣ K♣ A♠ 2♠ 3♠ 4♠ 5♠ 6♠ 7♠ 8♠ 9♠ 10♠ J♠ Q♠ K♠
shuffled deck: A♣2♠ 3♠4♣ 5♥K♠ J♣3♠ K♦3♥ 10♥ 9♣ Q♥ 2♣7♠ 3♦ Q♠10♦ A♠8♥ 4♥5♥ 8♠8♦ K♠5♠ 10♣6♠ 8♦10♠ 6♥A♣ 7♦ 3♥ 3♣ Q♣ 9♦ 9♥J♠ J♠J♣ A♥ Q♦10♣ 4♦2♣ J♦A♠ 5♠5♦ 10♠9♥ 4♠10♥ Q♠ 6♦ 9♠ A♦K♣ 2♦6♣ 2♥A♦ 6♠4♥ 7♣ K♥4♠ 8♥3♣ 6♦Q♥ 8♣K♥ 4♣J♦ 5♦8♠ 7♥ 6♣ 7♠ K♣K♦ 5♣ 2♠9♣ 10♦4♦ Q♣ J♥ 2♦ 8♣ Q♦ 6♥ 2♥
 
 
[north] A♣2♠ K♦3♥ 2♣8♥ 4♥6♠ 8♦9♦
 
[west] J♣3♠ Q♥10♦ A♠5♠ 10♣7♦ 3♥A♥ [east] 3♠4♣ 10♥7♠ 3♦5♥ 8♠10♠ 6♥J♠
 
[south] 5♥K♠ 9♣3♦ Q♠8♦ K♠A♣ 7♦J♣
 
 
 
remainder of deck: 3♣ Q♣ 9♦ 9♥ J♠ A♥ Q♦ 4♦ J♦ 5♠ 10♠ 4♠ 9♠ A♦ 2♦ 2♥ 6♠ 7♣ K♥ 8♥ 6♦ 8♣ 4♣ 5♦ 7♥ 6♣ 7♠ K♣ 5♣ 2♠ 10♦ J♥
remainder of deck: 10♣ 2♣ A♠ 5♦ 9♥ 10♥ Q♠ 6♦ 9♠ K♣ 6♣ A♦ 4♥ 7♣ 4♠ 3♣ Q♥ K♥ J♦ 8♠ 7♥ K♦ 5♣ 9♣ 4♦ Q♣ J♥ 2♦ 8♣ Q♦ 6♥ 2♥
</pre>
 
=={{header|Ring}}==
 
The Cards game, Screen shot : http://ring-lang.sourceforge.net/doc/_images/ringqt_shot48.jpg
 
<syntaxhighlight lang="ring">
Load "guilib.ring"
 
nScale = 1
 
app1 = new qApp
 
mypic = new QPixmap("cards.jpg")
 
mypic2 = mypic.copy(0,(124*4)+1,79,124)
Player1EatPic = mypic.copy(80,(124*4)+1,79,124)
Player2EatPic= mypic.copy(160,(124*4)+1,79,124)
 
aMyCards = []
aMyValues = []
for x1 = 0 to 3
for y1 = 0 to 12
temppic = mypic.copy((79*y1)+1,(124*x1)+1,79,124)
aMyCards + temppic
aMyValues + (y1+1)
next
next
 
nPlayer1Score = 0 nPlayer2Score=0
 
do
Page1 = new Game
Page1.Start()
again Page1.lnewgame
 
mypic.delete()
mypic2.delete()
Player1EatPic.delete()
Player2EatPic.delete()
 
for t in aMyCards
t.delete()
next
 
func gui_setbtnpixmap pBtn,pPixmap
pBtn {
setIcon(new qicon(pPixmap.scaled(width(),height(),0,0)))
setIconSize(new QSize(width(),height()))
}
 
Class Game
 
nCardsCount = 10
win1 layout1 label1 label2 layout2 layout3 aBtns aBtns2
aCards nRole=1 aStatus = list(nCardsCount) aStatus2 = aStatus
aValues aStatusValues = aStatus aStatusValues2 = aStatus
Player1EatPic Player2EatPic
lnewgame = false
nDelayEat = 0.5
nDelayNewGame = 1
 
func start
 
win1 = new qWidget() {
setwindowtitle("Five")
setstylesheet("background-color: White")
showfullscreen()
}
 
layout1 = new qvboxlayout()
 
label1 = new qlabel(win1) {
settext("Player (1) - Score : " + nPlayer1Score)
setalignment(Qt_AlignHCenter | Qt_AlignVCenter)
setstylesheet("color: White; background-color: Purple;
font-size:20pt")
setfixedheight(200)
}
 
closebtn = new qpushbutton(win1) {
settext("Close Application")
setstylesheet("font-size: 18px ; color : white ;
background-color: black ;")
setclickevent("Page1.win1.close()")
}
 
aCards = aMyCards
aValues = aMyValues
 
layout2 = new qhboxlayout()
 
aBtns = []
 
for x = 1 to nCardsCount
aBtns + new qpushbutton(win1)
aBtns[x].setfixedwidth(79*nScale)
aBtns[x].setfixedheight(124*nScale)
gui_setbtnpixmap(aBtns[x],mypic2)
layout2.addwidget(aBtns[x])
aBtns[x].setclickevent("Page1.Player1click("+x+")")
next
 
layout1.addwidget(label1)
layout1.addlayout(layout2)
 
label2 = new qlabel(win1) {
settext("Player (2) - Score : " + nPlayer2Score)
setalignment(Qt_AlignHCenter | Qt_AlignVCenter)
setstylesheet("color: white; background-color: red;
font-size:20pt")
setfixedheight(200)
}
 
layout3 = new qhboxlayout()
 
aBtns2 = []
for x = 1 to nCardsCount
aBtns2 + new qpushbutton(win1)
aBtns2[x].setfixedwidth(79*nScale)
aBtns2[x].setfixedheight(124*nScale)
gui_setbtnpixmap(aBtns2[x],mypic2)
layout3.addwidget(aBtns2[x])
aBtns2[x].setclickevent("Page1.Player2click("+x+")")
next
 
layout1.addwidget(label2)
layout1.addlayout(layout3)
layout1.addwidget(closebtn)
 
win1.setlayout(layout1)
 
app1.exec()
 
Func Player1Click x
if nRole = 1 and aStatus[x] = 0
nPos = ((random(100)+clock())%(len(aCards)-1)) + 1
gui_setbtnpixmap(aBtns[x],aCards[nPos])
del(aCards,nPos)
nRole = 2
aStatus[x] = 1
aStatusValues[x] = aValues[nPos]
del(aValues,nPos)
Player1Eat(x,aStatusValues[x])
checknewgame()
ok
 
Func Player2Click x
if nRole = 2 and aStatus2[x] = 0
nPos = ((random(100)+clock())%(len(aCards)-1)) + 1
gui_setbtnpixmap(aBtns2[x],aCards[nPos])
del(aCards,nPos)
nRole = 1
aStatus2[x] = 1
aStatusValues2[x] = aValues[nPos]
del(aValues,nPos)
Player2Eat(x,aStatusValues2[x])
checknewgame()
ok
 
Func Player1Eat nPos,nValue
 
app1.processEvents()
 
delay(nDelayEat)
lEat = false
for x = 1 to nCardsCount
if aStatus2[x] = 1 and (aStatusValues2[x] = nValue or nValue=5)
aStatus2[x] = 2
gui_setbtnpixmap(aBtns2[x],Player1EatPic)
lEat = True
nPlayer1Score++
ok
if (x != nPos) and (aStatus[x] = 1) and
(aStatusValues[x] = nValue or nValue=5)
aStatus[x] = 2
gui_setbtnpixmap(aBtns[x],Player1EatPic)
lEat = True
nPlayer1Score++
ok
next
if lEat
nPlayer1Score++
gui_setbtnpixmap(aBtns[nPos],Player1EatPic)
aStatus[nPos] = 2
label1.settext("Player (1) - Score : " + nPlayer1Score)
ok
 
Func Player2Eat nPos,nValue
 
app1.processEvents()
 
delay(nDelayEat)
lEat = false
for x = 1 to nCardsCount
if aStatus[x] = 1 and (aStatusValues[x] = nValue or nValue = 5)
aStatus[x] = 2
gui_setbtnpixmap(aBtns[x],Player2EatPic)
lEat = True
nPlayer2Score++
ok
 
if (x != nPos) and (aStatus2[x] = 1) and
(aStatusValues2[x] = nValue or nValue=5 )
aStatus2[x] = 2
gui_setbtnpixmap(aBtns2[x],Player2EatPic)
lEat = True
nPlayer2Score++
ok
next
if lEat
nPlayer2Score++
gui_setbtnpixmap(aBtns2[nPos],Player2EatPic)
aStatus2[nPos] = 2
label2.settext("Player (2) - Score : " + nPlayer2Score)
ok
 
Func checknewgame
if isnewgame()
lnewgame = true
 
if nPlayer1Score > nPlayer2Score
label1.settext("Player (1) Wins!!!")
ok
if nPlayer2Score > nPlayer1Score
label2.settext("Player (2) Wins!!!")
ok
 
app1.processEvents()
delay(nDelayNewGame)
 
win1.delete()
app1.quit()
ok
 
Func isnewgame
for t in aStatus
if t = 0
return false
ok
next
for t in aStatus2
if t = 0
return false
ok
next
return true
 
Func delay x
nTime = x * 1000
oTest = new qTest
oTest.qsleep(nTime)
</syntaxhighlight>
 
=={{header|Ruby}}==
{{trans|Python}}
 
{{works with|Ruby|12.80.70+}}
<langsyntaxhighlight lang="ruby">class Card
# class constants
SuitsSUITS = %i[" Clubs"," Hearts"," Spades"," Diamonds" ]
PIPS Pips = %i[" 2"," 3"," 4"," 5"," 6"," 7"," 8"," 9"," 10"," Jack"," Queen"," King"," Ace" ]
# class variables (private)
@@suit_value = Hash[ SuitsSUITS.each_with_index.to_a ]
@@pip_value = Hash[ PipsPIPS.each_with_index.to_a ]
attr_reader :pip, :suit
def initialize(pip,suit)
@pip = pip
@suit = suit
end
def to_s
"#{@pip} #{@suit}"
end
# allow sorting an array of Cards: first by suit, then by value
def <=>(cardother)
(@@suit_value[@suit] <=> @@suit_value[cardother.suit]).nonzero? or \
@@pip_value[@pip] <=> @@pip_value[cardother.pip]
end
end
 
class Deck
def initialize
@deck = Card::SUITS.product(Card::PIPS).map{|suit,pip| Card.new(pip,suit)}
@deck = []
end
for suit in Card::Suits
for pip in Card::Pips
def to_s
@deck << Card.new(pip,suit)
end@deck.inspect
end
end
def shuffle!
def to_s@deck.shuffle!
self
"[#{@deck.join(", ")}]"
end
def shuffle!deal(*args)
@deck.shuffle!shift(*args)
end
self
end
def deal(*args)
@deck.shift(*args)
end
end
 
Line 3,361 ⟶ 7,094:
hand = deck.deal(5)
puts hand.join(", ")
puts hand.sort.join(", ")</langsyntaxhighlight>
 
{{out}}
<pre>10 Clubs
8 Diamonds, Queen Clubs, 10 Hearts, 6 Diamonds, 4 Clubs
Line 3,367 ⟶ 7,102:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">suite$ = "C,D,H,S" ' Club, Diamond,Hart Heart,Spaces Spade
card$ = "A,2,3,4,5,6,7,8,9,T,J,Q,K" ' Cards Ace to King
 
Line 3,391 ⟶ 7,126:
next deal
print
next hand</langsyntaxhighlight>
<pre>TD 7S JD 7C 3H AS 6D QD KH 5H 2C QH 8C
8H 5S 7D 2D 2H 4D KS JS 7H QC KC 9S TH
Line 3,398 ⟶ 7,133:
 
=={{header|Rust}}==
{{libheader|rand}}
<lang rust>use std::fmt;
<syntaxhighlight lang="rust">extern crate rand;
use std::rand::{task_rng, Rng};
 
use std::fmt;
#[deriving(Clone)]
use rand::Rng;
enum Pip {
use Pip::*;
Ace,
use Suit::*;
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King
}
 
#[derive(Copy, Clone, Debug)]
impl fmt::Show for Pip {
enum Pip { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let name = match *self {
Ace => "Ace",
Two => "Two",
Three => "Three",
Four => "Four",
Five => "Five",
Six => "Six",
Seven => "Seven",
Eight => "Eight",
Nine => "Nine",
Ten => "Ten",
Jack => "Jack",
Queen => "Queen",
King => "King"
};
 
#[derive(Copy, Clone, Debug)]
write!(f, "{}", name)
enum Suit { Spades, Hearts, Diamonds, Clubs }
}
}
 
#[deriving(Clone)]
enum Suit {
Spades,
Hearts,
Diamonds,
Clubs
}
 
impl fmt::Show for Suit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let name = match *self {
Spades => "Spades",
Hearts => "Hearts",
Diamonds => "Diamonds",
Clubs => "Clubs"
};
 
write!(f, "{}", name)
}
}
 
#[deriving(Clone)]
struct Card {
pip: Pip,
Line 3,467 ⟶ 7,152:
}
 
impl fmt::Display for Card {
fn new(pip: Pip, suit: Suit) -> Card {
Card {pip: pip, suit: suit}
}
}
 
impl fmt::Show for Card {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?} of {:?}", self.pip, self.suit)
}
}
 
#[deriving(Clone)]
struct Deck(Vec<Card>);
 
Line 3,485 ⟶ 7,163:
fn new() -> Deck {
let mut cards:Vec<Card> = Vec::with_capacity(52);
for &suit in &[Spades, Hearts, Diamonds, Clubs].iter() {
for &pip in &[Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King].iter() {
cards.push( Card{pip::new(* pip, *suit): suit} );
}
}
Line 3,494 ⟶ 7,172:
 
fn deal(&mut self) -> Option<Card> {
let &Deckself.0.pop(ref mut cards) = self;
cards.pop()
}
 
fn shuffle(&mut self) {
let rand::thread_rng().shuffle(&Deck(ref mut cardsself.0) = self;
let mut rng = task_rng();
 
rng.shuffle(cards.as_mut_slice());
}
}
 
impl fmt::ShowDisplay for Deck {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
letfor &Deck(refcard cards) =in self;.0.iter() {
writeln!(f, "{}", card);
 
let mut text = String::new();
let mut i = 0;
for card in cards.iter() {
text.push_str(format!("{}", card).as_slice());
i += 1;
if i < cards.capacity() {
text.push_str("\n");
}
}
write!(f, "")
}
}
 
fn main() {
write!(f, "{}", text)
let mut deck = Deck::new();
deck.shuffle();
//println!("{}", deck);
for _ in 0..5 {
println!("{}", deck.deal().unwrap());
}
}</langsyntaxhighlight>
'''Sample output: 5 random cards'''
<pre>Jack of Diamonds
Nine of Hearts
Queen of Hearts
Six of Clubs
Five of Clubs</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import scala.annotation.tailrec
import scala.util.Random
 
Line 3,559 ⟶ 7,239:
}
override def toString():String="Deck: " + (cards mkString ", ")
}</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="scala">val deck=new Deck()
val deckShuffled:Deck=deck.shuffle
 
Line 3,575 ⟶ 7,255:
val (cards, rest3) =deckShuffled deal 6
println(cards)
println(rest3)</langsyntaxhighlight>
Output:
<pre>Deck: Four of Diamonds, Two of Diamonds, Queen of Diamonds, Jack of Diamonds, Nine of Diamonds, Five of Diamonds, Seven of Diamonds, Ten of Diamonds, Six of Diamonds, Ace of Diamonds, King of Diamonds, Three of Diamonds, Eight of Diamonds, Ten of Spades, Seven of Spades, Eight of Spades, King of Spades, Ace of Spades, Three of Spades, Queen of Spades, Jack of Spades, Six of Spades, Five of Spades, Nine of Spades, Four of Spades, Two of Spades, Seven of Hearts, Queen of Hearts, Two of Hearts, Ten of Hearts, Eight of Hearts, Jack of Hearts, Four of Hearts, Nine of Hearts, Six of Hearts, King of Hearts, Five of Hearts, Three of Hearts, Ace of Hearts, King of Clubs, Jack of Clubs, Queen of Clubs, Six of Clubs, Three of Clubs, Two of Clubs, Eight of Clubs, Seven of Clubs, Ace of Clubs, Four of Clubs, Nine of Clubs, Five of Clubs, Ten of Clubs
Line 3,590 ⟶ 7,270:
The procedure <code>shuffle</code> requires an appropriate procedure <code>random</code> to be
defined. Some Scheme implementations provide this as an extension.
<langsyntaxhighlight lang="scheme">(define ranks
(quote (ace 2 3 4 5 6 7 8 9 10 jack queen king)))
 
Line 3,617 ⟶ 7,297:
(syntax-rules ()
((deal! deck hand)
(begin (set! hand (cons (car deck) hand)) (set! deck (cdr deck))))))</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="scheme">(define deck
(shuffle new-deck))
 
Line 3,632 ⟶ 7,312:
 
(display hand)
(newline)</langsyntaxhighlight>
Sample output:
<pre>((jack . hearts) (5 . clubs) (9 . hearts) (7 . clubs) (6 . spades))</pre>
 
=={{header|SenseTalk}}==
Using Object-Oriented Programming in SenseTalk, the object below is defined in a script titled, DeckOfCards. A second script would then be used to call the DeckOfCards and its methods.
 
DeckOfCards:
<syntaxhighlight lang="sensetalk">properties
cards: []
end properties
to initialize
set pips to (2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace")
set suits to ("Clubs", "Spades", "Diamonds", "Hearts")
repeat for each suit in suits
repeat for each pip in pips
set card to pip && "of" && suit
insert card into my cards
end repeat
end repeat
put "New deck created, number of cards in deck:" && the number of items in my cards
end initialize
to shuffle
sort my cards by random of a million
put "Deck shuffled"
end shuffle
to deal
pull from my cards into card
put "Card dealt:" && card
put "Cards in deck remaining:" && the number of items in my cards
end deal
to handle asText
return my cards joined by return
end asText</syntaxhighlight>
Run:
<syntaxhighlight lang="sensetalk">put a new DeckOfCards into deck1
get deck1.shuffle
get deck1.deal
put deck1</syntaxhighlight>
Output:
<pre>New deck created, number of cards in deck: 52
Deck shuffled
Card dealt: 10 of Hearts
Cards in deck remaining: 51
9 of Spades
3 of Hearts
Ace of Hearts
9 of Clubs
5 of Clubs
5 of Diamonds
10 of Clubs
4 of Diamonds
King of Spades
6 of Hearts
5 of Spades
2 of Clubs
9 of Diamonds
4 of Clubs
King of Hearts
8 of Diamonds
Queen of Hearts
5 of Hearts
King of Diamonds
Queen of Diamonds
6 of Diamonds
10 of Diamonds
Ace of Diamonds
2 of Spades
3 of Diamonds
Queen of Spades
Jack of Hearts
Jack of Spades
Ace of Clubs
2 of Hearts
7 of Spades
6 of Clubs
4 of Spades
10 of Spades
7 of Clubs
3 of Clubs
6 of Spades
Jack of Clubs
Queen of Clubs
8 of Spades
9 of Hearts
4 of Hearts
King of Clubs
7 of Hearts
2 of Diamonds
8 of Hearts
7 of Diamonds
Jack of Diamonds
8 of Clubs
3 of Spades
Ace of Spades</pre>
 
=={{header|Sidef}}==
{{trans|Raku}}
<syntaxhighlight lang="ruby">define Pip = <A 2 3 4 5 6 7 8 9 10 J Q K>;
define Suit = <♦ ♣ ♥ ♠>;
 
class Card(pip, suit) {
method to_s { pip + suit }
}
 
class Deck(cards=[]) {
 
method init {
cards = gather {
Pip.each { |p| Suit.each { |s| take(Card(p, s)) } }
}
}
 
method shuffle {
cards.shuffle!;
}
 
method deal { cards.shift };
method to_s { cards.join(" ") };
}
 
var d = Deck();
say "Deck: #{d}";
 
var top = d.deal;
say "Top card: #{top}";
 
d.shuffle;
say "Deck, shuffled: #{d}";</syntaxhighlight>
{{out}}
<pre>
Deck: A♦ A♣ A♥ A♠ 2♦ 2♣ 2♥ 2♠ 3♦ 3♣ 3♥ 3♠ 4♦ 4♣ 4♥ 4♠ 5♦ 5♣ 5♥ 5♠ 6♦ 6♣ 6♥ 6♠ 7♦ 7♣ 7♥ 7♠ 8♦ 8♣ 8♥ 8♠ 9♦ 9♣ 9♥ 9♠ 10♦ 10♣ 10♥ 10♠ J♦ J♣ J♥ J♠ Q♦ Q♣ Q♥ Q♠ K♦ K♣ K♥ K♠
Top card: A♦
Deck, shuffled: 10♠ 2♠ 3♠ Q♥ 3♣ A♠ 6♠ 6♣ 9♣ 6♦ Q♦ 8♣ 4♦ 7♠ 10♦ 3♥ 4♠ 7♥ 8♠ 10♥ 10♣ 9♦ 5♠ Q♠ A♥ 4♥ J♥ Q♣ 7♣ 2♥ 6♥ 8♥ 5♥ 7♦ J♠ 5♦ K♦ 3♦ J♣ 2♦ 5♣ K♥ 9♥ 2♣ 8♦ A♣ K♣ 9♠ K♠ J♦ 4♣
</pre>
 
=={{header|Smalltalk}}==
===Version 1===
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">Object subclass: #Card
instanceVariableNames: 'thePip theSuit'
classVariableNames: 'pips suits'
Line 3,740 ⟶ 7,553:
 
"create a deck, shuffle it, remove the first card and display it"
Deck new shuffle deal displayNl.</langsyntaxhighlight>
 
'''Note''': there's something odd with the class method for getting pips and suits; it's because I've not understood how to initialize class variables to certain values without the need to explicitly call a method to do so.
 
===Version 2===
{{works with|GNU Smalltalk}}
<syntaxhighlight lang="smalltalk">Object subclass: Deck [
 
| cards |
 
Deck class >> of: aCardClass
[^self new
initializeWith: aCardClass;
yourself]
 
initializeWith: aCardClass
[cards := OrderedCollection from: aCardClass standardSet]
 
displayOn: aStream
[cards
do: [:each | each displayOn: aStream]
separatedBy: [aStream space]]
 
shuffle
[1 to: cards size - 1 do:
[:a || b |
b := Random between: a and: cards size.
cards swap: a with: b]]
 
deal
[^cards removeLast]
]
 
Object subclass: Card [
 
Card class >> standardSet
[^#(
'2d' '3d' '4d' '5d' '6d' '7d' '8d' '9d' 'Td' 'Jd' 'Qd' 'Kd' 'Ad'
'2s' '3s' '4s' '5s' '6s' '7s' '8s' '9s' 'Ts' 'Js' 'Qs' 'Ks' 'As'
'2h' '3h' '4h' '5h' '6h' '7h' '8h' '9h' 'Th' 'Jh' 'Qh' 'Kh' 'Ah'
'2c' '3c' '4c' '5c' '6c' '7c' '8c' '9c' 'Tc' 'Jc' 'Qc' 'Kc' 'Ac'
) deepCopy]
]</syntaxhighlight>
 
The Card class should obviously be more intricate to fulfil the needs of a CardGame class. :-)
 
Use example:
<syntaxhighlight lang="smalltalk">st> myDeck := Deck of: Card
a Deck
st> myDeck displayNl
2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac
st> myDeck shuffle
a Deck
st> myDeck displayNl
6c 7d Ac 4c 9s 2s Tc 9c Jh 3h Kh 7h 3s 5s 3d Kd Jc Qs As Qd 3c Kc Qh 2d 9h 4h 8c 7s Ah 9d Js 6h 8s 8h 5c 2c 4s 8d 5d Ts 4d Qc Td 7c 2h 5h 6s 6d Th Ks Jd Ad
st> myHand := OrderedCollection new
OrderedCollection ()
st> 5 timesRepeat: [myHand add: myDeck deal]
5
st> myHand
OrderedCollection ('Ad' 'Jd' 'Ks' 'Th' '6d' )</syntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift|5}}
<syntaxhighlight lang="swift">
struct Card: CustomStringConvertible
{
enum Suit: String, CaseIterable, CustomStringConvertible
{
case clubs = "♣️"
case diamonds = "♦️"
case hearts = "♥️"
case spades = "♠️"
 
var description: String { rawValue }
}
 
let suit: Suit
let value: Int
 
var description: String
{
let valueAsString: String
switch value
{
case 1:
valueAsString = "A"
case 11:
valueAsString = "J"
case 12:
valueAsString = "Q"
case 13:
valueAsString = "K"
default:
valueAsString = "\(value)"
}
return valueAsString + suit.description
}
}
 
struct Deck: CustomStringConvertible
{
var cards: [Card] = []
 
init()
{
for suit in Card.Suit.allCases
{
for faceValue in 1 ... 13
{
cards.append(Card(suit: suit, value: faceValue))
}
}
}
 
var description: String
{
String(cards.map{ $0.description }.joined(separator: ", "))
}
 
mutating func shuffle()
{
cards.shuffle()
}
 
mutating func dealCard() -> Card?
{
guard !cards.isEmpty else { return nil }
return cards.removeLast()
}
}
 
var deck = Deck()
print("New deck:")
print(deck)
deck.shuffle()
print("Shuffled deck:")
print(deck)
 
var hands: [[Card]] = [[], [], [], []]
 
var handIndex = 0
 
while let card = deck.dealCard()
{
hands[handIndex].append(card)
handIndex = (handIndex + 1) % hands.count
}
 
print ("Hands:")
print(hands.map({ $0.description }).joined(separator: "\n"))
print("Remaining deck (should be empty):")
print(deck)
</syntaxhighlight>
{{out}}
<pre>
New deck:
A♣️, 2♣️, 3♣️, 4♣️, 5♣️, 6♣️, 7♣️, 8♣️, 9♣️, 10♣️, J♣️, Q♣️, K♣️, A♦️, 2♦️, 3♦️, 4♦️, 5♦️, 6♦️, 7♦️, 8♦️, 9♦️, 10♦️, J♦️, Q♦️, K♦️, A♥️, 2♥️, 3♥️, 4♥️, 5♥️, 6♥️, 7♥️, 8♥️, 9♥️, 10♥️, J♥️, Q♥️, K♥️, A♠️, 2♠️, 3♠️, 4♠️, 5♠️, 6♠️, 7♠️, 8♠️, 9♠️, 10♠️, J♠️, Q♠️, K♠️
Shuffled deck:
2♣️, 2♠️, 8♠️, K♣️, 7♥️, Q♠️, 3♥️, 5♦️, 7♣️, 6♥️, J♥️, 10♣️, 6♠️, 8♥️, A♦️, 6♣️, 10♠️, 9♠️, 2♥️, 7♠️, 3♠️, 6♦️, A♥️, 5♥️, 9♣️, 5♣️, A♣️, 3♣️, 3♦️, 9♥️, Q♥️, 4♣️, 8♣️, K♦️, 10♥️, 4♦️, J♦️, 7♦️, 8♦️, J♣️, Q♦️, 5♠️, 2♦️, 4♥️, 10♦️, 9♦️, K♥️, 4♠️, J♠️, K♠️, Q♣️, A♠️
Hands:
[A♠️, 4♠️, 4♥️, J♣️, 4♦️, 4♣️, 3♣️, 5♥️, 7♠️, 6♣️, 10♣️, 5♦️, K♣️]
[Q♣️, K♥️, 2♦️, 8♦️, 10♥️, Q♥️, A♣️, A♥️, 2♥️, A♦️, J♥️, 3♥️, 8♠️]
[K♠️, 9♦️, 5♠️, 7♦️, K♦️, 9♥️, 5♣️, 6♦️, 9♠️, 8♥️, 6♥️, Q♠️, 2♠️]
[J♠️, 10♦️, Q♦️, J♦️, 8♣️, 3♦️, 9♣️, 3♠️, 10♠️, 6♠️, 7♣️, 7♥️, 2♣️]
Remaining deck (should be empty):
 
</pre>
 
{{works with|Swift 2.0}}
 
Enter this into a playground to see results
<syntaxhighlight lang="swift">
import Foundation
 
// extend any Indexed collection to be able to shuffle (see http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift)
extension CollectionType where Index == Int {
/// Return a copy of `self` with its elements shuffled
func shuffle() -> [Generator.Element] {
var list = Array(self)
list.shuffleInPlace()
return list
}
}
 
extension MutableCollectionType where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffleInPlace() {
// empty and single-element collections don't shuffle
if count < 2 { return }
for i in 0..<count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
 
// now the model structs
enum CardColor : Int {
case Red
case Black
}
extension CardColor : CustomStringConvertible {
var description : String {
switch self {
case .Red:
return "Red"
case .Black:
return "Black"
}
}
}
 
enum Suit : Int {
case Hearts = 1
case Diamonds
case Spades
case Clubs
var color : CardColor {
switch self {
case .Hearts, .Diamonds:
return .Red
case .Spades, .Clubs:
return .Black
}
}
}
 
enum Pip : Int {
case Ace = 1
case Two = 2
case Three = 3
case Four = 4
case Five = 5
case Six = 6
case Seven = 7
case Eight = 8
case Nine = 9
case Ten = 10
case Jack = 11
case Queen = 12
case King = 13
}
 
struct Card {
let pip : Pip
let suit : Suit
var isFaceCard : Bool {
return pip.rawValue > 10
}
var color : CardColor {
return suit.color
}
}
extension Card : Equatable {}
func == (l:Card, r:Card) -> Bool {
return l.pip == r.pip &&
l.suit == r.suit
}
extension Card : CustomStringConvertible {
var description : String {
return "\(pip) of \(suit)"
}
}
 
 
struct Deck {
var cards : [Card]
var count : Int {
return cards.count
}
init(shuffling:Bool=true) {
var startcards = [Card]()
for suit in (Suit.Hearts.rawValue...Suit.Clubs.rawValue) {
for pip in (Pip.Ace.rawValue...Pip.King.rawValue) {
startcards.append(Card(pip: Pip(rawValue: pip)!, suit: Suit(rawValue: suit)!))
}
}
cards = startcards
if shuffling {
shuffle()
}
}
mutating func shuffle() {
cards.shuffleInPlace()
}
mutating func deal() -> Card {
let out = cards.removeFirst()
return out
}
}
extension Deck : CustomStringConvertible {
var description : String {
return "\(count) cards: \(cards.description)"
}
}
 
 
 
// test some cards
let kh = Card(pip: .King, suit: .Hearts)
let ad = Card(pip: .Ace, suit: .Diamonds)
let tc = Card(pip: .Two, suit: .Clubs)
let fc = Card(pip: Pip(rawValue:4)!, suit: .Spades)
 
 
// create an unshuffled deck
var efg = Deck(shuffling: false)
 
 
// create a shuffled deck and print its contents
var d = Deck()
print(d)
 
// deal three cards
d.deal()
d.deal()
d.deal()
d
 
// deal a couple more cards and check their color
let c = d.deal()
c.color
 
let cc = d.deal()
cc.color
 
// deal out the rest of the deck, leaving just one card
while d.count > 1 {
d.deal()
}
d
 
// test equality of a couple cards
if kh == Card(pip: Pip.King, suit: Suit.Clubs) {
let a = true
}
else {
let a = false
}
 
kh != Card(pip: Pip.King, suit: Suit.Clubs)
kh.isFaceCard
fc.isFaceCard
 
 
</syntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
namespace eval playing_cards {
Line 3,810 ⟶ 7,978:
playing_cards::print $hand -sort true
puts "\nthe deck:"
playing_cards::print_deck</langsyntaxhighlight>
 
=={{header|VBScript}}==
=====Implementation=====
<syntaxhighlight lang="vb">
<lang vb>
class playingcard
dim suit
Line 3,881 ⟶ 8,049:
end sub
end class
</syntaxhighlight>
</lang>
 
=====Invocation=====
<syntaxhighlight lang="vb">
<lang vb>
dim pack
set pack = new carddeck
Line 3,903 ⟶ 8,071:
end if
 
</syntaxhighlight>
</lang>
 
=====Output=====
Line 3,919 ⟶ 8,087:
Each users hand is another edit buffer.
There is no need for any routines to display the deck or a hand, since each of them is displayed in an edit window.
<langsyntaxhighlight lang="vedit">// Playing Cards, main program
 
Call("CREATE_DECK")
Line 4,001 ⟶ 8,169:
Buf_Switch(#11) // players hand
Reg_ins(9) // insert the cards here
Return</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="wren">import "random" for Random
 
var FACES = "23456789TJQKA"
var SUITS = "shdc"
 
var createDeck = Fn.new {
var cards = []
SUITS.each { |suit| FACES.each { |face| cards.add("%(face)%(suit)") } }
return cards
}
 
var dealTopDeck = Fn.new { |deck, n| deck.take(n).toList }
 
var dealBottomDeck = Fn.new { |deck, n| deck[-n..-1][-1..0] }
 
var printDeck = Fn.new { |deck|
for (i in 0...deck.count) {
System.write("%(deck[i]) ")
if ((i + 1) % 13 == 0 || i == deck.count - 1) System.print()
}
}
 
var deck = createDeck.call()
System.print("After creation, deck consists of:")
printDeck.call(deck)
Random.new().shuffle(deck)
System.print("\nAfter shuffling, deck consists of:")
printDeck.call(deck)
var dealtTop = dealTopDeck.call(deck, 10)
System.print("\nThe 10 cards dealt from the top of the deck are:")
printDeck.call(dealtTop)
var dealtBottom = dealBottomDeck.call(deck, 10)
System.print("\nThe 10 cards dealt from the bottom of the deck are:")
printDeck.call(dealtBottom)</syntaxhighlight>
 
{{out}}
<pre>
After creation, deck consists of:
2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As
2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah
2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad
2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac
 
After shuffling, deck consists of:
Qs 9c 3c Qd 2h 5h As 5c 7s 7d 6s Qh Jc
Td 9s 6h Ad 5d 2d 4c 8d Kh Kc 8s Tc 7c
Ts 9h 3d 9d 7h 2s 3s 4d 5s Ac Kd 4s Ks
4h 8c Qc 6d Th 6c Jh 8h 2c 3h Ah Js Jd
 
The 10 cards dealt from the top of the deck are:
Qs 9c 3c Qd 2h 5h As 5c 7s 7d
 
The 10 cards dealt from the bottom of the deck are:
Jd Js Ah 3h 2c 8h Jh 6c Th 6d
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">char Deck(52); \card structure (low 2 bits = suit)
def Players = 4; \number of players to deal to
char Hand(Players, 52); \each player's hand
int Card, N, I, J, T;
char Suit, Royal;
[for Card:= 0 to 52-1 do \make a new deck
Deck(Card):= Card;
for N:= 0 to 10000 do \shuffle the deck
[I:= Ran(52); J:= Ran(52);
T:= Deck(I); Deck(I):= Deck(J); Deck(J):= T;
];
for N:= 0 to 52-1 do \deal from the deck
[Card:= Deck(N);
I:= N/Players;
J:= rem(0);
Hand(J, I):= Card;
];
Suit:= "HDCS "; \print each player's hand
Royal:= "JQK "; \ (= contents of the deck)
for J:= 0 to Players-1 do \e.g: 2D 3C 10C AS KD
[for I:= 0 to 52/Players -1 do
[Card:= Hand(J, I);
N:= Card>>2 + 1; \pip value
if N = 1 then ChOut(0, ^A)
else if N >= 11 then ChOut(0, Royal(N-11))
else IntOut(0, N);
ChOut(0, Suit(Card&3));
ChOut(0, ^ );
];
CrLf(0);
];
]</syntaxhighlight>
 
{{out}}
<pre>
3S 9C 4C 5D KC 9H QS 4H 5C 6H 2C 3C 5S
8D 4S 3H 8C 2D 7C 2S 8H 8S 10D 9S AH JC
6C 10C KH 9D 3D 5H JS 10S 2H 4D 10H 7H JH
QD KS 7S QH 6S JD QC 6D KD AC 7D AS AD
</pre>
 
=={{header|Yabasic}}==
{{trans|Run BASIC}}
<syntaxhighlight lang="vb">suite$ = "CDHS" //Club, Diamond, Heart, Spade
card$ = "A23456789TJQK" //Cards Ace to King
 
dim n(55) //make ordered deck
for i = 1 to 52 // of 52 cards
n(i) = i
next i
 
for i = 1 to 52 * 3 //shuffle deck 3 times
i1 = int(ran(52)) + 1
i2 = int(ran(52)) + 1
h2 = n(i1)
n(i1) = n(i2)
n(i2) = h2
next i
 
for hand = 1 to 4 //4 hands
for deal = 1 to 13 //deal each 13 cards
card = card + 1 //next card in deck
s = mod(n(card), 4) + 1 //determine suite
c = mod(n(card), 13) + 1 //determine card
print mid$(card$,c,1),mid$(suite$,s,1)," "; //show the card
next deal
print
next hand
end</syntaxhighlight>
{{out}}
<pre>Same as Run BASIC entry.</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">const Diamonds=1, Spades=3, Clubs=0, Hearts=2, Ace=1; // informational
var suits=T(0x1F0D1,0x1F0C1,0x1F0B1,0x1F0A1); //unicode 🃑,🃁,🂱,🂡
 
Line 4,028 ⟶ 8,327:
fcn deal(cards=5){ deck.pop(0,cards); }
fcn toString{ deck.pump(String,"toString"); }
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">d:=Deck();
d.println(d.deck.len());
d.deal().println();
d.println();</langsyntaxhighlight>
{{out}}
<pre>
Line 4,039 ⟶ 8,338:
🃄🂷🂤🃉🂡🂽🂥🂶🃃🃇🂳🂫🃍🃅🂭🃚🃞🃋🃘🂹🃛🂩🂺🃁🂮🂣🃖🂨🃙🃝🃒🂪🃂🃊🂲🃈🂧🃑🃆🂵🂴🃔🂾🂦🃓🂻🃕
</pre>
 
=={{header|ZX Spectrum Basic}}==
The deck is just a basic index from 1 to 52, with 1-13 representing the A-K of hearts, 14-26 the A-K of spades, etc. This makes it easier to sort a hand later, if so desired.
<syntaxhighlight lang="zxbasic">10 GOSUB 5000
20 CLS
30 PRINT "Options:"
40 PRINT "1: Shuffle deck"
50 PRINT "2: Deal cards"
60 PRINT "3: Display deck"
70 INPUT o
80 IF o<1 OR o>3 OR o<>INT o THEN GOTO 70
90 GO SUB (o+1)*1000
100 GO TO 20
 
999 REM convert index to card
1000 LET s=INT ((x-1)/13)+1
1010 LET p=x-13*(s-1)
1020 LET n=s-2*INT (s/2)+1
1030 LET c$=p$(p)+CHR$ 16+CHR$ (n AND n>1)+s$(s): REM colour codes to force red or black
1040 RETURN
 
1999 REM shuffle - only a naive shuffle algorithm but it'll do; the modularity of the program means this is easy enough to modify
2000 CLS : PRINT FLASH 1;"Shuffling..."
2010 LET s=1: REM changing s allows shuffling the remainder of an undealt deck, say
2020 FOR x=1 TO 100
2030 LET a=INT (RND*53-s)+s
2040 LET b=INT (RND*53-s)+s
2050 LET n=d(a)
2060 LET d(a)=d(b)
2070 LET d(b)=n
2080 NEXT x
2090 RETURN
 
2999 REM deal
3000 INPUT "How many players? ";p
3010 INPUT "How many cards? ";c
3020 IF c<1 OR p<1 OR c<>INT c OR p<>INT p THEN PRINT "Don't be silly!": GO TO 3000
3030 IF c*p>52 THEN PRINT "Not enough cards for that!": GO TO 3000
3040 CLS : DIM h(p,c)
3050 LET k=1
3060 FOR f=1 TO c
3070 FOR e=1 TO p
3080 LET h(e,f)=d(k)
3090 LET k=k+1
3100 NEXT e
3110 NEXT f
3120 FOR e=1 TO p
3130 PRINT "Player ";e;"'s hand:"
3140 FOR f=1 TO c
3150 LET x=h(e,f)
3160 GO SUB 1000
3170 PRINT c$;" ";
3180 NEXT e
3190 PRINT
3200 NEXT f
3210 PRINT
3220 PRINT "Remaining deck:"
3230 IF c*p=52 THEN PRINT "none"
3240 GO SUB 4010
3250 RETURN
 
3999 REM display deck
4000 CLS : LET k=1
4010 FOR y=k TO 52: REM enter here with k>1 to show the rest of an undealt deck
4020 LET x=d(y)
4030 GO SUB 1000
4040 PRINT c$
4050 NEXT y
4060 FOR y=0 TO 1000
4070 NEXT y
4080 RETURN
 
4999 REM initialise
5000 DIM d(52)
5010 GO SUB 6000
5020 LET s$=CHR$ 144+CHR$ 145+CHR$ 146+CHR$ 147: REM or LET s$="HSDC" if you don't want symbols
5030 LET p$="A23456789TJQK"
5040 FOR x=1 TO 52
5050 LET d(x)=x
5060 NEXT x
5070 RETURN
 
5999 REM characters - the ZX Spectrum character set doesn't contain suit symbols
6000 RESTORE 7000
6010 FOR x=65368 TO 65399
6020 READ a
6030 POKE x,a
6040 NEXT x
6050 RETURN
 
7000 DATA BIN 01101100: REM 108
7010 DATA BIN 11111110: REM 254
7020 DATA BIN 11111110: REM 254
7030 DATA BIN 11111110: REM 254
7040 DATA BIN 01111100: REM 124
7050 DATA BIN 00111000: REM 56
7060 DATA BIN 00010000: REM 16
7070 DATA BIN 00000000: REM 0
 
7080 DATA BIN 00010000: REM 16
7090 DATA BIN 00111000: REM 56
7100 DATA BIN 01111100: REM 124
7110 DATA BIN 11111110: REM 254
7120 DATA BIN 01010100: REM 84
7130 DATA BIN 00010000: REM 16
7140 DATA BIN 01111100: REM 124
7150 DATA BIN 00000000: REM 0
 
7160 DATA BIN 00010000: REM 16
7170 DATA BIN 00111000: REM 56
7180 DATA BIN 01111100: REM 124
7190 DATA BIN 11111110: REM 254
7200 DATA BIN 01111100: REM 124
7210 DATA BIN 00111000: REM 56
7220 DATA BIN 00010000: REM 16
7230 DATA BIN 00000000: REM 0
 
7240 DATA BIN 00010000: REM 16
7250 DATA BIN 00111000: REM 56
7260 DATA BIN 01010100: REM 84
7270 DATA BIN 11111110: REM 254
7280 DATA BIN 01010100: REM 84
7290 DATA BIN 00010000: REM 16
7300 DATA BIN 01111100: REM 124
7310 DATA BIN 00000000: REM 0</syntaxhighlight>
{{out}}
Using the HSDC mod from line 5020 to make it easier here. H and D would appear in colour.
<pre>
Player 1's hand:
QD 8D 6S 7D JS 8C 9S QH
 
Player 2's hand:
5C 7H 7C 4D 8H 3H 2H AD
 
Player 3's hand:
3C 5S QC AS 2D TS JH 6H
 
Player 4's hand:
9C 4C 7S TC 2C 6D AH 9D
Player 5's hand:
KH 6C JC 8S KD TD TH 5H
 
Player 6's hand:
AC JD QS KC 5D 3D 4H 4S
 
Remaining deck:
2S
KS
9H
3S</pre>
2,063

edits