Java


CLICK HERE TO DOWNLOAD THIS ANSWER  INSTANTLY $35 Only

 

We endeavor to set up some classes that involve playing card games with a human or simulating card games entirely by a computer.  There are two basic classes we'll need :

Card:  A class like the one presented in the modules, but with a few changes.

Hand:  A class that represents the cards held by a single player.

Here are eight cards, each of which contains both a value ('A', '2', '3', ... 'T', 'J', 'Q',' K') and a suit (spades ♠, hearts ♥, diamonds ♦, clubs ♣)
Notice that I am using the char 'T' to describe the value 10.  (Ignore the Joker, which we will not need.)

The dealer uses a Deck object to deal Hand objects to the players.  The dealer may or may not be a player who gets a hand of his own (poker dealers in casinos don't receive a hand, but most other games involve the dealer getting a hand).

Card: The Card class has two obvious members:  value (a char)  and suit (an enum).  But we add a new boolean, errorFlag, which can inform a client that a card is in an illegal state. We'll want the usual constructors, mutators, accessors and toString() methods for the class.  We only allow standard cards, like ('A', clubs), ('9', hearts) and ('T', diamonds), no jokers or other special cards.

Hand:  As you can see, a Hand object usually contains several cards, so we'll need an array of Card objects (myCards) as the principal member of the Hand class.  Since each game deals a different number of cards into its players hands, and even within a game the number of cards in a hand will increase or decrease, we must keep track of this with an int value (numCards).  We'll need constructors, mutators, etc., of course.  We'll also want a way for the hand to receive a card (from the deck or somewhere else), and play a card (to the table or to another player).  These two methods will be called takeCard() and playCard(), respectively.  Since this class has no information about the game being played, it always puts new cards received by takeCard() into the next available location of the array (index position numCards) and plays a card via playCard() from the highest occupied location (index position numCards - 1).  The client game application would somehow prepare this highest position with the correct card to be played before calling Hand's playCard() method.  This detail is not our concern.

 

We continue to work on the card game effort, now adding the source of all cards for the various players, the Deck.

Deck:  A class that represents the source of the cards for dealing and, as the game progresses, the place from which players can receive new cards (say, as they pick cards "from the deck" or when future hands are to be dealt from the same deck).  Recall this picture, which relates the Deck to the various Hands that it creates through the process called "dealing":

 

Let's deconstruct the meaning of this important class.

Deck: A Deck object is the source of all cards.  It's where the dealer gets cards to deal, and if a player takes an individual card after the deal, he takes it from the Deck object.  Naturally, the primary member here is an array of Card objects, much like Hand.  We'll call this member cards[].  A deck normally consists of a single pack of cards: 52 cards (four suits of 13 values each).  However, some games use two, three or more packs.  If a card game requires two packs, then the deck will consist of two full 52-card packs:  104 cards.  (Many games throw away some cards before beginning.  For example Pinochle wants all cards with values 8-and-below to be taken out of the deck, but we will not trouble ourselves with this complexity.)  A newly instantiated deck will have a multiple of 52 cards and will contain all the standard cards, so the number of cards in a newly instantiated deck will be 52, 104, 156, ..., i.e., numPacks × 52.

Clearly, we need an int like Hand's numCards, to keep track of how many cards are actually in the cards[] array.  To this end, we'll use topCard (not numCards), since a deck typically removes and delivers cards to players from the top-of-the-deck, and this is a convenient variable to use for the number of cards as well as the position of the top of the deck.

There are a few other useful members (numPacks, for example).  In addition to the the usual constructors and accessors, we'll want a dealCard() to return and remove the card at the top of the deck (which may be received by a client and added to some player's hand), and a shuffle() to re-order the cards in a random fashion.  Also, we'll need to restock the deck (init()) to the original full condition in preparation for a fresh deal (we would certainly not want to re-instantiate a new deck when we have a perfectly good one available:  garbage collection, done by us or by the operating system, is a resource we do not abuse).

Phase 1: The Deck Class

Private Static Class Constants

Define a private  final int value like MAX_PACKS = 6 , NUM_CARDS_PER_PACK = 52 , and MAX_CARDS_PER_DECK = MAX_PACKS * NUM_CARDS_PER_PACK.  Use them to their full benefit in the class code.

Private Static Member Data

Card[] masterPack

This is a private static Card array, masterPack[], containing exactly 52 card references, which point to all the standard cards.   It will enable us to avoid capriciously and repeatedly declaring the same 52 cards which are needed as the game proceeds.  In other words, once we have, say, a ('6', spades) Card constructed and stored (inside this masterPack[]), we use that same instance whenever we need it as a source to copy in various places, notably during a re-initialization of the Deck object;  it will always be in the masterPack[] array for us to copy.

Private Member Data

Card[] cards;

int topCard;

int numPacks;

Public Methods

Deck(int numPacks) - a constructor that populates the arrays and assigns initial values to members.  Overload so that if no parameters are passed, one pack is assumed.  This constructor can call a helper, allocateMasterPack() (see below), but that helper would only do something the very first time it gets called per program (no need to allocate a static array more than once per program, right?).  It would then use another helper, init(), to assign the master pack Cards to the various cards[] elements.

boolean init(int numPacks) - re-populate cards[] with the standard 52 × numPackscards. (This also gives the client a chance to change the number of packs in the deck in preparation for a new game.)  We should not repopulate the static array, masterPack[], since that was done once, in the (first-invoked) constructor and  never changes. The elements of the cards[] array can reference the masterPack[] objects -- that's safe since we will never give the client any of those objects to modify (see dealCard() on this issue). If numPacks is out-of-range, return false without changing the object;  else return true and make the change.

void shuffle() - mixes up the cards with the help of the standard random number generator.

Card dealCard() - returns and removes  (effectively, not physically) the card in the top occupied position of cards[].  Here we have to return a copy of the card, not the actual reference to the object in the cards[] array, since that object is also the object in the masterPack[] array, which the client must not be allowed to change.

An accessor for the int, topCard (no mutator.)

Card inspectCard(int k) - Accessor for an individual card.  Returns a card with errorFlag = true if k is bad.  Otherwise returns a copy of the card (see admonition for dealCard()).

Private Methods

static void allocateMasterPack() - this is a method that will be called by the constructor.  However, it has to be done with a very simple twist:  even if many Deck objects are constructed in a given program, this static method will not allow itself to be executed more than once.  Since masterPack[] is a static, unchanging, entity, it need not be built every time a new Deck is instantiated.  So this method needs to be able to ask itself, "Have I been here before?", and if the answer is "yes", it will immediately return without doing anything;  it has already built masterPack[] in a previous invocation.

Recommended test of Class Deck

Declare a deck containing a single pack of cards. Do not shuffle.  Deal all the cards in a loop until the deck is empty (dealt directly to the display/screen, not to any Hand objects just yet).  Display each card as it comes off the deck.  Next, reset the deck by initializing it again (to the same single pack).  Shuffle the deck this time, and re-deal to the screen in a loop again. Notice that the cards are now coming off in a random order.

Repeat this double deal, unshuffled, then shuffled, but this time using a deck containing twopacks of cards.

Phase 2: The Deck and Hand Classes

For your second test client, allow your Deck class to interact with your Hand class.  Don't add anything to the two classes, but do everything in this phase from within your main() client.

Ask the user (interactively) to select the number of players (a number from 1 to 10).  That's one question, one numeric answer, and no further user-interaction.  Once you have a legal value, instantiate a single-pack Deck object without shuffling, deal a deck into that many Hand objects, dealing all cards until the deck is empty.  Since the number of players chosen by the user may not divide evenly into 52, the number of cards dealt into the various hands might differ, but only by, at most, one.  Display all the hands after the deal.

Reset the objects to their initial state, but this time shuffle the deck before a second deal (same # of players).

To be clear, dealing to hands means dealing a single card to each hand, until all hands have one card, then repeating to give all hands a second card, etc., until the cards are gone, and each hand has (nearly) the same number of cards.  It does not mean dealing x cards to one hand, then x to the next hand, etc.  This is very important.

You don't need any more classes than the ones we've already created, since there should not be that much to do in main().

You will be graded, in part, on how efficiently you put together these two classes.  Use what  you know about arrays, loops, the methods available in the Deck and Hand classes -- even testing user input for valid in-range response --  to give a clean, short and completely tested client that proves that your Deck can feed the number of Hands requested by the user.  There is some amount of creativity and variability allowed in this part, and any two correct solutions will look very different.  You can implement this in any way that interprets the instructions.  Yet, I can and will deduct when I see basic programming concepts misused, deduction amounts commensurate with the type of infraction.

Attention Please:

Always include both a source and (for console apps) a run.

Do not add or change any characters on the console output lines.

All mutators return boolean. Set methods or functions should return a boolean value, whether your client uses the return value or not.

Filter input. Any mutator, constructor, or other member method (function) that uses a passed parameter as a basis for setting private data, should test for the validity of that passed parameter - that means range checking, string length testing, or any other test that makes sense for the class and private member.

Use symbolic names, not literals. Never use a numeric literal like 1000, 3 or 52 for the size of an array, or the maximum value of some data member in your code.  Instead create a symbolic constant and use the constant.  In other words, use ARRAY_SIZE or MAX_CARDS, not 1000 or 52.

Avoid costly methods when simple operations can acheive the same result more efficiently. Examples: (i) Methods like Math.pow() should not be used for small integer powers (e.g. powers less than 4). (ii) recursion should be avoided if a simple loop can do the same thing.

Never use labels in loops . Although continue and break statements are usually fine, using them with labels to create spaghetti looping creates bad form and code maintenance issues.