/* Playing cards (Rosetta code) in Picat. http://rosettacode.org/wiki/Playing_cards """ Create a data structure and the associated methods to define and manipulate a deck of playing cards. The deck should contain 52 unique cards. The methods must include the ability to make a new deck, shuffle (randomize) the deck, deal from the deck, and 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. """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ % import util. % import cp. main => go. go => deck(Deck), println(deck=Deck), nl, println(shuffle=shuffle(Deck)), nl, Deck := deal(Deck,Card1), Deck := deal(Deck,Card2), Deck := deal(Deck,Card3), println(deal1=Card1), println(deal2=Card2), println(deal3=Card3), println(deck=Deck), Deck := deal2(Deck,Card4), Deck := deal2(Deck,Card5), Deck := deal2(Deck,Card6), Deck := deal2(Deck,Card7), Deck := deal2(Deck,Card8), println([Card4,Card5,Card6,Card7,Card8]), Deck := deal(Deck,5,FiveCards), println(fiveCards=FiveCards), println(deck=Deck), Deck := Deck.deal(Card9).deal(Card10).deal(Card11).deal(Card12), println(card9To12=[Card9,Card10,Card11,Card12]), println(deck=Deck), nl. suits(Suits) => Suits = ["C","H","S","D"]. % suits(Suits) => Suits = ["♠","♥","♦","♣"]. values(Values) => Values = ["A","2","3","4","5","6","7","8","9","T","J","Q","K"]. deck(Deck) => suits(Suits), values(Values), Deck =[S++V :V in Values, S in Suits]. % shuffle a deck shuffle(Deck) = Deck2 => Deck2 = Deck, Len = Deck2.length, foreach(I in 1..Len) R2 = 1+(random2() mod 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 a out parameter, % the deck is returned as function value. deal(Deck, Card) = Deck.tail() => Card = Deck.first(). % deal N cards deal(Deck, N, Cards) = [Deck[I] : I in Len+1..Deck.length] => Len = min(N,Deck.length), Cards = [Deck[I] : I in 1..Len]. deal2([],Card) = [] => Card = "". deal2([Card|Deck], Card2) = Deck => Card2=Card. % Note: The following don't work since pattern matcher can match it... % deal2([Card|Deck], Card) = Deck => true.