Sams Teach Yourself JavaScript in 24 Hours
- Table of Contents
- Copyright
- About the Author
- Acknowledgments
- We Want to Hear from You!
- Reader Services
- Introduction
- Part I: Getting Started
- Hour 1. Understanding JavaScript
- Hour 2. Creating a Simple Script
- Hour 3. How JavaScript Programs Work
- Part II: Learning JavaScript Basics
- Hour 4. Using Functions and Variables
- Hour 5. Using Strings and Arrays
- Hour 6. Testing and Comparing Values
- Hour 7. Repeating Yourself: Using Loops
- Hour 8. Using Math and Date Functions
- Part III: The Document Object Model (DOM)
- Hour 9. Working with the Document Object Model
- Hour 10. Responding to Events
- Hour 11. Using Windows and Frames
- Hour 12. Getting Data with Forms
- Hour 13. Using Graphics and Animation
- Part IV: Moving on to Advanced JavaScript Features
- Hour 14. Creating Cross-Browser Scripts
- Hour 15. Creating Custom Objects
- Hour 16. Working with Sounds and Plug-Ins
- Hour 17. Debugging JavaScript Applications
- Part V: Working with Dynamic HTML (DHTML)
- Hour 18. Working with Style Sheets
- Hour 19. Using Dynamic HTML (DHTML)
- Hour 20. Using Advanced DOM Features
- Part VI: Putting It All Together
- Hour 21. Improving a Web Page with JavaScript
- Hour 22. Creating a JavaScript Game
- Planning the Program
- Writing the Program
- Workshop: Putting It All Together
- Summary
- Q&A
- Quiz
- Exercises
- Hour 23. Creating DHTML Applications
- Hour 24. JavaScript Tips and Tricks
- Part VII: Appendices
- Appendix A. Other JavaScript Resources
- Appendix B. Tools for JavaScript Developers
- Appendix C. Glossary
- Appendix D. JavaScript Quick Reference
- Appendix E. DOM Quick Reference
Writing the Program
You're now ready to write the actual script to play the game. Because this is a game, the script will be entirely controlled by the user. Each of the functions is called by an event handler in the HTML document.
Handling the Deal/Draw Button
Because the Deal and Draw buttons are the same button, you will need a function that determines which action should be performed. The DealDraw function will be called by the button's event handler:
function DealDraw() {
if (dealt == true) Draw();
else Deal();
}
This function checks whether the cards have been dealt. If they have, it calls the Draw function; otherwise, it calls the Deal function.
Shuffling the Deck
The Deal function deals five cards into the five spaces in your HTML document. To begin, you first need a shuffled deck of cards. The first half of the Deal function fills the deck array with cards and then shuffles them:
function Deal() {
// fill the deck (in order, for now)
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");
}
// shuffle the deck
var n = Math.floor(400 * Math.random() + 500);
for (i=1; i<n; i++) {
card1 = Math.floor(52*Math.random() + 1);
card2 = Math.floor(52*Math.random() + 1);
temp = deck[card2];
deck[card2] = deck[card1];
deck[card1] = temp;
}
Here's a breakdown of the actions performed by this function:
- The statements within the first for loop fill the deck with cards. To begin with, the cards are in order by number and then by suit.
- The second for loop shuffles the deck. This is accomplished by picking a random number and starting a loop based on that number. In each loop iteration, two random cards are chosen and swapped.
Dealing the Cards
The second half of the Deal function will actually deal the cards:
// Deal and Display cards
for (i=1; i<6; i++) {
hand[i] = deck[i];
document.images[i].src = hand[i].fname();
document.images[i+5].src = "hold.gif";
held[i] = false;
}
dealt = true;
score = score - 1; //deduct one for bet amount
document.form1.total.value = score;
document.images[11].src="draw.gif";
Addscore();
}
This half includes the following actions:
- The for keyword begins a loop that will range from 1 to 5, using the variable i.
- The next card in the shuffled deck is assigned to the next position in the hand array.
- The document.images array is used to display the dealt card and to change the button below the card to the standard hold.gif. (An alternate version will be loaded when the user presses the button.)
- The held flag is set to false for the current card.
- After the loop is completed, the function sets the dealt flag and subtracts the bet from the total score.
- The current score is displayed in the text field.
- Now that the cards have been dealt, the function uses document.images to change the Deal button to the Draw button.
- Finally, the function calls the Addscore function to calculate the score so far for the dealt hand. We'll examine this function later.
Holding and Discarding Cards
Next, you will need a function that is called when the user presses the Hold button below a card:
//Hold or discard a card
function Hold(num) {
if (!dealt) return;
if (!held[num]) {
held[num]=true;
document.images[5+num].src="hold2.gif";
}
else {
held[num]=false;
document.images[5+num].src="hold.gif";
}
}
This function accepts a parameter indicating the card to hold. The if statement returns from the function if the cards have not yet been dealt. The rest of the function toggles the held flag for the card and displays either a highlighted or plain version of the Hold button to tell the user the card's status.
Drawing New Cards
Next is the Draw function, which is called when the Draw button is clicked. It draws more cards from the deck to replace the cards that the user wants to discard (those that aren't set to Hold). The following JavaScript code defines the Draw function:
//Draw new cards
function Draw() {
var curcard = 6;
for (i=1; i<6; i++) {
if (!held[i]) {
hand[i] = deck[curcard++];
document.images[i].src = hand[i].fname();
}
}
dealt = false;
document.images[11].src="deal.gif";
score += Addscore();
document.form1.total.value = score;
}
Here's how the Draw function works:
- A local variable called curcard is used to indicate the next card to be drawn from the deck. Because five cards have already been drawn, it starts at card number 6.
- The for loop checks each card's status in the held array. If the card is not held, it is replaced with the next card from the deck and the image on the page is updated.
- Because this hand is finished, the dealt variable is set back to false, and the Deal button replaces the Draw button.
- Finally, the Addscore function is called to calculate the score. Unlike the Deal function, this time the score is added to the total score and redisplayed.
Calculating the Score
Last but not least, the Addscore function calculates the score for the current poker hand. The score is one of the following values, loosely based on the odds of different hands:
- One pair (Jacks or better): 1 point
- Two pair: 2 points
- Three of a kind: 3 points
- Straight: 4 points
- Flush: 5 points
- Full house: 10 points
- Four of a kind: 25 points
- Straight flush: 50 points
- Royal flush: 100 points
The following is the complete Addscore function:
// Calculate Score
function Addscore() {
var straight = false;
var flush = false;
var pairs = 0;
var three = false;
var tally = new Array(14);
// sorted array for convenience
var nums = new Array(5);
for (i=0; i<5; i++) {
nums[i] = hand[i+1].num;
}
nums.sort(Numsort);
// flush
if (hand[1].suit == hand[2].suit &&
hand[2].suit == hand[3].suit &&
hand[3].suit == hand[4].suit &&
hand[4].suit == hand[5].suit) flush = true;
// straight (Ace low)
if (nums[0] == nums[1] - 1 &&
nums[1] == nums[2] - 1 &&
nums[2] == nums[3] - 1 &&
nums[3] == nums[4] - 1) straight = true;
// straight (Ace high)
if (nums[0] == 1 && nums[1] == 10 && nums[2] == 11
&& nums[3] == 12 && nums[4] == 13)
straight = true;
// royal flush, straight flush, straight, flush
if (straight && flush && nums[4] == 13 && nums[0] == 1) {
document.form1.message.value="Royal Flush";
return 100;
}
if (straight && flush) {
document.form1.message.value="Straight Flush";
return 50;
}
if (straight) {
document.form1.message.value="Straight";
return 4;
}
if (flush) {
document.form1.message.value="Flush";
return 5;
}
// tally array is a count for each card value
for (i=1; i<14; i++) {
tally[i] = 0;
}
for (i=0; i<5; i++) {
tally[nums[i]] += 1;
}
for (i=1; i<14; i++) {
if (tally[i] == 4) {
document.form1.message.value = "Four of a Kind";
return 25;
}
if (tally[i] == 3) three = true;
if (tally[i] == 2) pairs += 1;
}
if (three && pairs == 1) {
document.form1.message.value="Full House";
return 10;
}
if (pairs == 2) {
document.form1.message.value="Two Pair";
return 2;
}
if (three) {
document.form1.message.value="Three of a Kind";
return 3;
}
if (pairs == 1) {
if (tally[1] == 2 || tally[11]==2
|| tally[12] == 2 || tally[13]==2) {
document.form1.message.value="Jacks or Better";
return 1;
}
}
document.form1.message.value="No Score";
return 0;
}
This function includes some complex calculations, but it isn't too difficult to understand. Here's a breakdown of how it works:
- The var keywords initialize variables, including flags for the various types of poker hands.
- The first for loop creates the nums array, which stores a sorted version of the list of card values in the hand. This makes it easier to detect some hands (such as straights).
- The next if detects a flush (all cards have the same suit).
- Two if statements are used to detect a straight (all cards in a sequence). Because Aces can represent either 1 or 13, straights ending in Ace are checked separately.
- An if statement detects a royal flush (10, J, Q, K, A) and returns the score.
- Several more if statements return the scores for straight flush, straight, and flush hands.
- A for loop creates an array called tally. This is used to count the number of cards of each value in the hand.
- Several if statements use the tally array to detect four of a kind, full house, two pair, three of a kind, and pair hands.
- If the previous code detected a pair of cards, a further if statement checks whether it's a pair of Jacks or better and return the appropriate score.
- If no scoring hand was detected, the final lines return from the Addscore function with no score.
Workshop: Putting It All Together | Next Section

Account Sign In
View your cart