Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA code Understand the Class and Problem We continue to work on the card game

ID: 3663049 • Letter: J

Question

JAVA code

Understand the Class and Problem

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 (foursuits 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. This variable will represent 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 getTopCard() 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 reorder() to shuffle the cards in a random fashion. Also, we'll need to restock the deck(restock()) 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.

Static Member Data

Card[] staticPack

This is a private static Card array, staticPack[], 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 staticPack[]), we use that same instance whenever we need it as a source to copy in various places, notably during a restock() of the Deck object; it will always be in the staticPack[] array for us to copy.

Private Member Data

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, allocateStaticPack() (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, restock(), to assign the master pack Cards to the various cards[] elements.

boolean restock(int numPacks) - re-populate cards[] with the standard 52 × numPacks cards. (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, staticPack[], since that was done once, in the (first-invoked) constructor and never changes. The elements of the cards[] array can reference the staticPack[] objects -- that's safe since we will never give the client any of those objects to modify (see getTopCard() on this issue). If numPacks is out-of-range, return false without changing the object; else return true and make the change.

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

Card getTopCard() - 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 actualreference to the object in the cards[] array, since that object is also the object in the staticPack[] array, which the client must not be allowed to change.

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

Card getCard(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 getTopCard()).

Private Methods

static void allocateStaticPack() - 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 staticPack[] 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 staticPack[] in a previous invocation.

Recommended test of Class Deck

Declare a deck containing one pack of cards. Do not re-order. 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 restocking it again (to the same single pack).   Re-order 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 three pack deck.

Here is an example Test Run of Card Class. To save space, the run below uses a two pack deck in the place where you will be using a three pack deck.

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 12). That's one question, one numeric answer, and no further user-interaction. Use a loop to ensure that you get a legal value. Once you have a legal value, instantiate a single-pack Deck object without re-ordering, 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 re-order 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().

Example of One of Possibly Many Test Runs of Deck + Card Classes

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.

Explanation / Answer

import java.util.Random;
class Deck
{

private final static int MAX_PACKS = 6;
private final static int NUM_CARDS_PER_PACK = 52;
private final static int MAX_CARDS_PER_DECK = MAX_PACKS
* NUM_CARDS_PER_PACK;
private int numPacks;
private int topCard = NUM_CARDS_PER_PACK * numPacks;
private Card[] cards;
public static Card[] masterPack = new Card[NUM_CARDS_PER_PACK];
Deck(int numPacks)
{
int theNumPacks = numPacks;
cards = new Card[topCard];
allocateMasterPack();
init(theNumPacks);
}
static void allocateMasterPack()
{
int count;
int j;
int suitCount;
char val;
Suit theSuit;
Card[] masterPack = new Card[52];
for (count = 0; count < masterPack.length; count++)
masterPack[count] = new Card();
for (suitCount = 0; suitCount<4; suitCount ++)
{
switch(suitCount)
{
case 0:
theSuit = Suit.clubs; break;
case 1:
theSuit = Suit.diamonds; break;
case 2:
theSuit = Suit.hearts; break;
case 3:
theSuit = Suit.spades; break;
default:
theSuit = Suit.spades; break;
}
masterPack[13*suitCount].set('A', theSuit);
for (val='2', j = 1; val<='9'; val++, j++)
masterPack[13*suitCount + j].set(val, theSuit);
masterPack[13*suitCount+9].set('T', theSuit);
masterPack[13*suitCount+10].set('J', theSuit);
masterPack[13*suitCount+11].set('Q', theSuit);
masterPack[13*suitCount+12].set('K', theSuit);
}
}
boolean init (int aNumPacks)
{
boolean validNumPacks;
int theNumPacks = aNumPacks;
Random aRandom = new Random(1L);
if (theNumPacks < 1 || theNumPacks > MAX_PACKS)
{
validNumPacks = false;
}
else
{
for (int packCount = 0; packCount < aNumPacks; packCount++)
for (int cardCount = 0; cardCount < topCard;
cardCount++)
cards[packCount * NUM_CARDS_PER_PACK + cardCount]
= masterPack[cardCount];
validNumPacks = true;
}
return validNumPacks;
}
public void shuffle()
{
Card myCard = new Card();
for (int i = topCard-1; i > 0; i--)
{
Random random = new Random();
int randInt = random.nextInt(i+1);
myCard = cards[i];
cards[i] = cards[randInt];
cards[randInt] = myCard;
}
}
public int getNumCards()
{
return topCard;
}
public String toString()
{
int count;
String myString = "{ ";
for (count = 0; count < topCard; count++)
{
if (count == 0) myString += ", ";
myString += cards[count].toString();
}
myString += " }";
return myString;
}
}