Next page | Contents page |

A deck of cards

The usual pack of playing cards contains 52 cards, perhaps plus jokers. There are 13 cards in each of 4 suits. Spider uses 2 such packs but no jokers. I decided to use Deck as the type name for the set of cards we will be using. Trying to make it generic, the constructor for Deck takes parameters specifying the number of 52-card packs and the number of additional jokers to use.

So make a new file called deckA.js, add the script element (after cardA.js) to load it into the HTML. Initially the file will contain this:


function Deck (nPacks, nJokers)
{ this.cards = [];
  const CARDS_PER_SUIT = 13;
  for (var j = 0; j < nPacks; j++)
  { for (var i = 1; i <= CARDS_PER_SUIT; i++)
    { this.cards.push (new Card (SUITS.CLUB, i));
      this.cards.push (new Card (SUITS.DIAMOND, i));
      this.cards.push (new Card (SUITS.HEART, i));
      this.cards.push (new Card (SUITS.SPADE, i));
  } }
  for (var k = 0; k < nJokers; k++)
  { this.cards.push (new Card (null, 0));
  }
};

Deck.prototype.getCard = function (i)
{ return this.cards [i];
};

Deck.prototype.shuffle = function ()
{// TO DO
};

This shows that a Deck object will hold its cards in a simple array. The outside world does not want to know that, so we have a method to get the ith card in the deck. This illustrates a general principle for object-oriented programming: do not alter the properties of objects directly because it might be decided later to change the internal data structures. As long as there is a method for doing what we need and that method is updated when data structures change it means that code elsewhere in the program will not need to change. This principle is sometimes summarised as "Don't have a dog and bark yourself". In the present case, Deck, the example is rather trivial but it can be very important in more complicated objects. Other programming languages enable you to mark object properties as private so you are forced to use the relevant methods to change them. (Yes, I know that such a facility was added to JS a few years ago but that would take us into a different way of defining objects.)

Then we come to the shuffle() method. As discussed on a previous page this is a dummy method for now, until we work out how to do it. Perhaps think about how you would do it before going to the next page.

Next page | Contents page |