Playing cards: Difference between revisions

Content added Content deleted
m (→‎{{header|J}}: <nowiki> tags no longer required)
(→‎{{header|J}}: define sayCards and DeckPrototype in parent class, simplify creation of new deck.)
Line 1,082:
 
=={{header|J}}==
'''Solution:'''<br>
<lang j>NoteNB. 'playingcards.ijs'
This is a class script.
NB. Defines a Rosetta Code playing cards class
NB. Multiple decks may be used, one for each instance of this class.
 
coclass 'rcpc' NB. Rosetta Code playing cards class
 
NB. Class objects
create=: 3 : 0
N0n0=:. > ;:'Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King'
N1n1=:. > ;:'Spades Hearts Diamonds Clubs'
DeckPrototype=: |. ,/(i.#N0n0),."1 0 i.#N1n1
sayCards=: ((N0{~{.),' of ',(N1{~{:))"1
startNewDeck ''
)
 
NB. Class methods
create=: 3 : 0startNewDeck
destroy=: codestroy
 
sayCards=: ((N0n0{~{.),' of ',(N1n1{~{:))"1
startNewDeck=: 3 : 0
 
startNewDeck=: ''monad define
1: TheDeck=: DeckPrototype
)
 
shuffle=: 3monad : 0define
1: TheDeck=: TheDeck {~ ?~ # TheDeck
)
 
NB.*dealCards=: 3v :Deals 0y cards [to x players]
Left parameterNB. (x) is: optional number of players, with defaultdefaults to one.
NB. Used monadically, the player-axis is omitted from output.
dealCards=: verb define
{. 1 dealCards y
:
Line 1,114 ⟶ 1,118:
TheDeck =: ToBeDealt }. TheDeck
(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.
)
 
NB.*pcc=: 3 : 0 NB.v "Print" current contents of the deck.
pcc=: monad define
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 'coutil~user/playingcards.ijs'
coinsert 'rcpc' NB. inserts rcpc class in the path of current locale
pc=: '' conewnewDeck 'rcpc'
$TheDeck__pc
52 2
shuffle__pc ''
1
sayCards__pcsayCards 2 dealCards__pc 5 NB. deal two hands of five cards
Nine of Hearts
Three of Clubs