HTML and CSS Reference
In-Depth Information
Note: The three statements in the nested for loops could be combined into
deck[i++]=new MCard(n+1,suitnames[si], suitnames[si]+"-"+nums[n]+"-75.png"); .
This is because the ++ iteration operator takes place after the value has been generated for indexing
the deck array. However, I recommend that in this learning example you don't do it! Using three
statements is much easier to write and to understand.
Creating the programmer-defined object for the cards
JavaScript provides a way for programmers to create programmer-defined objects to group together data;
the different pieces of data called attributes or properties , and we use dot notation to get at the
different attributes. It is also possible to bundle together code into methods , but we dont need to do that
in this example (recall that we did do this in other applications, such as cannonball and slingshot in
Chapter 4). The function setting up the new object is called the constructor function. For cards, I defined
MCard , which was shown in use in the previous section in the builddeck function. The definition of this
function follows:
function MCard(n, s, picname){
this.num = n;
if (n>10) n = 10;
this.value = n;
this.suit = s;
this.picture = new Image();
this.picture.src = picname;
this.dealt = 0;
}
The line of the function
if (n>10) n = 10;
will be triggered by the face cards (jack, queen, king); remember, the value of each is 10. This line
corrects the value to be 10 in these cases.
Notice that this if statement is structurally different from previous if statements. There are not any
opening and closing curly brackets setting off the if-true clause. The single-statement clause is a
legitimate form of the if statement. I generally avoid this form because if I later decide to add another
statement, I will need to insert the curly brackets. However, it is OK in this situation. You will see both
variations when examining code. Notice that nothing special is done when n equals 1. The rule for two
possible values for an ace is handled elsewhere in the program.
The properties of MCard objects include a newly created Image object with its src attribute set to the
picname passed in. The last attribute, dealt , initialized to 0, will be set to 1 or 2 depending on whether the
card goes to the player or the dealer.
Dealing the cards
The builddeck function constructs the deck array of MCard objects. The players hand is kept in an array
called playerhand with pi holding the index of the next position. Similarly, the dealers hand is kept in an
array called househand with hi holding the index of the next position. An example showing the syntax
 
Search WWH ::




Custom Search