Next page | Contents page |

Cards, suits and values

As seen earlier, we define the type Card with a function that sets property values:


function Card (suit, value)
{
  this.suit = suit;
  this.value = value;
}

But what are the types of the 2 parameters, suit and value?

Some programming languages have a construct called enum (short for enumeration). JS does not have that (unless it has been added to the language recently and I have not noticed). Instead we can do this:


const SUITS = {CLUB:1, DIAMOND:2, HEART:3, SPADE:4};

Then we can use the (constant) names for the suits instead of having to remember numbers and possibly getting then wrong. The suits are now very clear. (Some languages hide the numbers in the enum so you are forced to use the names, which is a good thing.)

Card values can just be numerical, from 1 for Ace up to 13 for King. We will see later that there is a possible reason for using 13 and 14 for Queen and King but we will cross that bridge when we come to it.

Now we are in a position to write a first version of a new file called cardA.js, to hold everything about type Card. It will be loaded into the HTML by a new script element which I would put before the one for gameA.js though the order is not crucial, just logical to me.

With a method for getting the name of a card, file cardA.js starts like this:


const SUITS = {CLUB:1, DIAMOND:2, HEART:3, SPADE:4};

function Card (suit, value)// (null, 0) for Joker
{ this.suit = suit;
  this.value = value;
}

Card.prototype.getName = function ()
{ var s;
  switch (this.value)
  { case 0: return "Joker"; 
    case 1: s = "Ace"; break;
    case 11: s = "Jack"; break;
    case 12: s = "Queen"; break;
    case 13: s = "King"; break;
    default: s = this.value;
  }
  s += " of ";
  switch (this.suit)
  { case SUITS.CLUB: s += "Clubs"; break;
    case SUITS.DIAMOND: s += "Diamonds"; break;
    case SUITS.HEART: s += "Hearts"; break;
    case SUITS.SPADE: s += "Spades"; break;
  }
  return s;
};

You may notice that I have put a comment about how I might handle jokers. I now think a better idea would be to have an additional suit called JOKERS and then use values to distinguish red or black. Spider does not require jokers so I will not develop this further in these pages.

There will be more properties and methods to be added to Card later, as we need them.

For beginners: semicolons are optional in JS but I strongly recommend using them for ending every statement. If you don't do that you will sometimes get errors that can be very hard to find (the browser can become confused about whether a statement continues on the next line and some browsers may behave differently from others in such cases).

Next page | Contents page |