Playing cards: Difference between revisions

Content deleted Content added
Tikkanz (talk | contribs)
m →‎{{header|J}}: <nowiki> tags no longer required
Tikkanz (talk | contribs)
→‎{{header|J}}: define sayCards and DeckPrototype in parent class, simplify creation of new deck.
Line 1,082: Line 1,082:


=={{header|J}}==
=={{header|J}}==
'''Solution:'''<br>
<lang j>Note 'playingcards.ijs'
<lang j>NB. playingcards.ijs
This is a class script.
NB. Defines a Rosetta Code playing cards class
Multiple decks may be used, one for each instance of this class.
NB. Multiple decks may be used, one for each instance of this class.
)


coclass 'rcpc' NB. Rosetta Code playing cards class
coclass 'rcpc' NB. Rosetta Code playing cards class


NB. Class objects
create=: 3 : 0
N0=: > ;:'Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King'
n0=. > ;:'Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King'
N1=: > ;:'Spades Hearts Diamonds Clubs'
n1=. > ;:'Spades Hearts Diamonds Clubs'
DeckPrototype=: |. ,/(i.#N0),."1 0 i.#N1
DeckPrototype=: |. ,/(i.#n0),."1 0 i.#n1
sayCards=: ((N0{~{.),' of ',(N1{~{:))"1
startNewDeck ''
)


NB. Class methods
create=: startNewDeck
destroy=: codestroy
destroy=: codestroy


sayCards=: ((n0{~{.),' of ',(n1{~{:))"1
startNewDeck=: 3 : 0

startNewDeck=: monad define
1: TheDeck=: DeckPrototype
1: TheDeck=: DeckPrototype
)
)


shuffle=: 3 : 0
shuffle=: monad define
1: TheDeck=: TheDeck {~ ?~ # TheDeck
1: TheDeck=: TheDeck {~ ?~ # TheDeck
)
)


dealCards=: 3 : 0
NB.*dealCards v Deals y cards [to x players]
NB. x is: optional number of players, defaults to one
NB. Used monadically, the player-axis is omitted from output.
dealCards=: verb define
{. 1 dealCards y
{. 1 dealCards y
:
:
Line 1,114: Line 1,118:
TheDeck =: ToBeDealt }. TheDeck
TheDeck =: ToBeDealt }. TheDeck
(1 0 2)|:(y,x)$ CardsOffTop
(1 0 2)|:(y,x)$ CardsOffTop
)
Note 'dealCards'
Left parameter (x) is number of players, with default to one.
Right parameter (y) is number of cards to be dealt to each player.
Used monadically, the player-axis is omitted from output.
)
)


pcc=: 3 : 0 NB. "Print" current contents of the deck.
NB.*pcc v "Print" current contents of the deck.
pcc=: monad define
sayCards TheDeck
sayCards TheDeck
)
)</lang>

Example use:
newDeck_z_=: conew&'rcpc'</lang>
<lang j> load 'coutil'

load 'c:\documents and settings\user_name\j602-user\playingcards.ijs'
'''Example use:'''
pc=: '' conew 'rcpc'
<lang j> load '~user/playingcards.ijs'
coinsert 'rcpc' NB. inserts rcpc class in the path of current locale
pc=: newDeck ''
$TheDeck__pc
$TheDeck__pc
52 2
52 2
shuffle__pc ''
shuffle__pc ''
1
1
sayCards__pc 2 dealCards__pc 5 NB. deal two hands of five cards
sayCards 2 dealCards__pc 5 NB. deal two hands of five cards
Nine of Hearts
Nine of Hearts
Three of Clubs
Three of Clubs