|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Creating the ScriptBecause this is the longest script in this book, it will be easier to understand if you look at some of its key functions before the entire script. The following sections discuss how the script will manage the game. Using Objects to Store CardsBecause JavaScript is designed to work with numbers but not specifically with playing cards, you can create a custom object to make it easier to manage the card game. The following code is the constructor for a Card object: // make a filename for an image, given Card object
function fname() {
return this.num + this.suit + ".gif";
}
// constructor for Card objects
function Card(num,suit) {
this.num = num;
this.suit = suit;
this.fname = fname;
}Each Card object will represent a space on the board. It has two properties, num and suit, and an fname() method that returns the filename for the graphic representing the card. Setting Up the BoardAlong with the graphics on the screen, the board array will represent the game board by storing 25 Card objects, one for each space. Here's the code that will set up the board: // array for board contents
board = new Array(26);
for (i=1; i<26; i++) {
board[i] = new Card(0,"x");
obj=document.getElementById("card"+i);
obj.src = "blank.gif";
obj.onclick = PlaceCard;
}The first line creates the board array. The for loop then sets up each space on the board. First, it places a blank card in the array. Next, it finds the object for the corresponding space on the screen. It makes sure blank.gif is displayed in each space, and sets an event handler for onClick events to call the PlaceCard() function, which will handle the user's clicks on the board. Shuffling the DeckThe deck array will be used to simulate a deck of cards. The following code fills the array with Card objects: deck = new Array(53);
for (i=1; i<14; i++) {
deck[i] = new Card(i,"c");
deck[i+13] = new Card(i,"h");
deck[i+26] = new Card(i,"s");
deck[i+39] = new Card(i,"d");
}To save time, the statements in the for loop insert cards of each of the four suits into the deck. At this point, the cards are in order. The next step is to shuffle the deck: n = Math.floor(100 * Math.random() + 200);
for (i=1; i<n; i++) {
c1 = Math.floor(52*Math.random() + 1);
c2 = Math.floor(52*Math.random() + 1);
temp = deck[c2];
deck[c2] = deck[c1];
deck[c1] = temp;
}This code starts by choosing a random number, n, ranging from 200 to 299. It then loops n times using a for loop. Each iteration of the loop chooses two random cards in the deck and swaps their positions. This ensures a reasonably random deck that still contains exactly 52 unique cards. Placing Cards on the BoardThe PlaceCard() function will be called by an event handler when the user clicks on a space on the board. This function begins by determining which space was clicked: function PlaceCard(e) {
if (!e) var e = window.event;
// which space on the board was clicked?
thiscard = (e.target) ? e.target: e.srcElement;
pos = thiscard.id.substring(4);
if (board[pos].suit != "x") {
return;
}These statements use the target or srcElement property to determine which space was clicked. The pos variable stores the numeric position on the board (125), calculated by removing "card" from the id value using the substring() method. The final if statement checks whether a card is already in place, and returns to prevent placing a card over an existing card. The next section of PlaceCard() does the actual card placement: drawcard=document.getElementById("dcard");
thiscard.src = deck[nextcard].fname();
drawcard.src = "blank.gif";
board[pos] = deck[nextcard];
nextcard++;
Score();The nextcard variable keeps track of the next card in the deck, starting at one for the top card. This function uses getElementById() to find the object for the "next card" display, and then uses the fname() method to assign the appropriate filename to the src property of the image object. The board array is updated with the new card, nextcard is incremented, and the Score() function is called to update the scores. The next task for PlaceCard() is to check whether the game is over: // Game over?
if (nextcard > 25) {
EndGame();
}
else {
drawcard.src = deck[nextcard].fname();
// cache next image for draw pile
nexti = new Image(53,68);
nexti.src = deck[nextcard+1].fname();
}
}If 25 cards have been placed, the EndGame() function is called to end the game. Otherwise, the next card is displayed in the display. The next card image (not yet displayed) is also preloaded so the game will respond quickly. Scoring Columns, Rows, and DiagonalsThe Score() function will update the scores for each column, row, and diagonal each time a card is placed. Here is the code for the Score() function: function Score() {
score=document.getElementById("totalscore");
totscore = 0;
// rows
for (x=0; x<5; x++) {
r = x * 5 + 1;
a =
AddScore(board[r],board[r+1],board[r+2],board[r+3],board[r+4],"row"+x);
totscore += a;
}
// columns
for (x=0; x<5; x++) {
r = x + 1;
a =
AddScore(board[r],board[r+5],board[r+10],board[r+15],board[r+20],"col"+x);
totscore += a;
}
// diagonals
a = AddScore(board[5],board[9],board[13],board[17],board[21],"diag1")
totscore += a;
a = AddScore(board[1],board[7],board[13],board[19],board[25],"diag2")
totscore += a;
score.firstChild.nodeValue = totscore;
}This function uses for loops to process each row and each column. It then handles the diagonals. A separate function, AddScore(), will handle the actual detection of poker hands in each of these. The totscore variable stores a total of all of the scores. Each time a card is placed, the updated total score is displayed in the left column. Adding Up ScoresThe AddScore() function is called by Score() for each column, row, and diagonal. This function determines which poker hand, if any, is represented by the cards passed to it. It then updates the appropriate score box on the board with the row's score, and returns the numeric value to be used by Score(). The AddScore() function begins by setting up some variables: function AddScore(c1,c2,c3,c4,c5,scorebox) {
obj=document.getElementById(scorebox);
straight = false;
flush = false;
royal = false;
pairs = 0;
three = false;
// sorted array for convenience
nums = new Array(5);
nums[0] = c1.num;
nums[1] = c2.num;
nums[2] = c3.num;
nums[3] = c4.num;
nums[4] = c5.num;
nums.sort(numsort);The function first sets up a number of flag variables, such as straight and flush, to keep track of which poker hand it finds. It then stores the five card values in an array and sorts it to make it easy to detect straights. The function continues by testing for each hand, one at a time. For example, this if statement tests for a flush by comparing card suits: // flush
if (c1.suit == c2.suit && c2.suit == c3.suit
&& c3.suit == c4.suit && c4.suit == c5.suit) {
flush = true;
}After doing each test, AddScore() updates the board with a description of the poker hand and score for the row and returns a numeric score: if (flush) {
obj.innerHTML="Flush<br>5"
return 5;
}Ending the GameThe game ends when all 25 spaces on the board have been filled with cards and the EndGame() function is called. Because the score is updated in real time and no moves can be made after all cards are placed, the only thing left for this function to do is to display a "Game Over" message: function EndGame() {
stat=document.getElementById("status");
stat.innerHTML="<b>Game Over</b>";
}This uses innerHTML to display a message in the status element, which normally displays "Next Card" to label the draw card. |
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |