Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Example: Game of Chance - JavaScript(JS)

Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Functions

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Example: Game of Chance - JavaScript(JS)

One of the most popular games of chance is a dice game known as craps, which is played in casinos and back alleys throughout the world.

Example: Game of Chance


One of the most popular games of chance is a dice game known as craps, which is played in casinos and back alleys throughout the world. The rules of the game are straightforward:


A player rolls two dice. Each die has six faces. These faces contain one, two, three, four, five and six spots, respectively. After the dice have come to rest, the sum of the spots on the two upward faces is calculated. If the sum is 7 or 11 on the first throw, the player wins. If the sum is 2, 3 or 12 on the first throw (called “craps”), the player loses (i.e., the “house” wins). If the sum is 4, 5, 6, 8, 9 or 10 on the first throw, that sum becomes the player’s “point.” To win, you must continue rolling the dice until you “make your point” (i.e., roll your point value). You lose by rolling a 7 before making the point.


The script in Fig. 9.6 simulates the game of craps.


Note that the player must roll two dice on the first and all subsequent rolls. When you execute the script, click the Roll Dice button to play the game. A message below the Roll Dice button displays the status of the game after each roll.


Until now, all user interactions with scripts have been through either a prompt dialog (in which the user types an input value for the program) or an alert dialog (in which a message is displayed to the user, and the user can click OK to dismiss the dialog). Although these dialogs are valid ways to receive input from a user and to display messages, they are fairly limited in their capabilities. A prompt dialog can obtain only one value at a time from the user, and a message dialog can display only one message.


More frequently, multiple inputs are received from the user at once via an XHTML form (such as one in which the user enters name and address information) or to display many pieces of data at once (e.g., the values of the dice, the sum of the dice and the point in this example). To begin our introduction to more elaborate user interfaces, this program uses an XHTML form (discussed in Chapter 4) and a new graphical user interface con-cept—GUI event handling. This is our first example in which the JavaScript executes in response to the user’s interaction with a GUI component in an XHTML form. This inter-action causes an event. Scripts are often used to respond to events.


      <?xml version = "1.0" encoding = "utf-8"?>


      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"




      <!-- Fig. 9.6: Craps.html -->


      <!-- Craps game simulation. -->


      <html xmlns = "http://www.w3.org/1999/xhtml">




      <title>Program that Simulates the Game of Craps</title>


<style type = "text/css">

table {        text-align: right }

body {        font-family: arial, sans-serif }

        div.red { color: red }




        <script type = "text/javascript">



        // variables used to test the state of the game

        var WON = 0;

        var LOST = 1;


        var CONTINUE_ROLLING = 2;

        // other variables used in program


        var firstRoll = true; // true if current roll is first


        var sumOfDice = 0; // sum of the dice


        var myPoint = 0; // point if no win/loss on first roll


        var gameStatus = CONTINUE_ROLLING; // game not over yet


        // process one roll of the dice


        function play()


// get the point field on the page

var point = document.getElementById( "pointfield" );


// get the status div on the page

var statusDiv = document.getElementById( "status" );

if ( firstRoll ) // first roll of the dice


sumOfDice = rollDice();     


switch ( sumOfDice )          


case 7: case 11: // win on first roll

            gameStatus = WON;           

            // clear point field     

            point.value = "";       


case 2: case 3: case 12: // lose on first roll

            gameStatus = LOST;          

            // clear point field     

            point.value = "";       


default:           // remember point

            gameStatus = CONTINUE_ROLLING;

            myPoint = sumOfDice;       

            point.value = myPoint;       

            firstRoll = false;       

} // end switch          

} // end            if         



sumOfDice = rollDice();     


if ( sumOfDice == myPoint ) // win by making point

gameStatus = WON;           


if          ( sumOfDice == 7 )   // lose by rolling 7

            gameStatus = LOST;          

} // end            else    


if ( gameStatus == CONTINUE_ROLLING )

statusDiv.innerHTML = "Roll again";



if ( gameStatus == WON )  

statusDiv.innerHTML = "Player wins. " +

            "Click Roll Dice to play again.";


statusDiv.innerHTML = "Player loses. " +

            "Click Roll Dice to play again.";


firstRoll = true;         

        } // end else


        } // end function play


        // roll the dice


        function rollDice()


var die1;

var       die2;

var       workSum;

die1 = Math.floor( 1 + Math.random() * 6 );         

die2 = Math.floor( 1 + Math.random() * 6 );         

workSum = die1 + die2;     


document.getElementById( "die1field" ).value = die1; 

document.getElementById( "die2field" ).value = die2; 

document.getElementById( "sumfield" ).value = workSum;   


        return workSum;


        } // end function rollDice

        // -->






        <form action = "">






        <tr><td>Die 1</td>


        <td><input id = "die1field" type = "text" />




        <tr><td>Die 2</td>


        <td><input id = "die2field" type = "text" />






        <td><input id = "sumfield" type = "text" />






        <td><input id = "pointfield" type = "text" />




        <tr><td /><td><input type = "button" value = "Roll Dice"


        onclick = "play()" /></td></tr>




        <div id = "status" class = "red">


        Click the Roll Dice button to play</div>







Fig. 9.6 | Craps game simulation.

In this example, we have decided to place the form’s GUI components in an XHTML table element, so line 107 begins the definition of the XHTML table. Lines 109–120 create four table rows. Each row contains a left cell with a text label and an input element in the right cell.


Four input fields (lines 110, 113, 116 and 119) are created to display the value of the first die, the second die, the sum of the dice and the current point value, if any. Their id attributes are set to die1field, die2field, sumfield, and pointfield, respectively. The id attribute can be used to apply CSS styles and to enable script code to refer to an element in an XHTML document. Because the id attribute, if specified, must have a unique value, JavaScript can reliably refer to any single element via its id attribute. We see how this is done in a moment.


Lines 121–122 create a fifth row with an empty cell in the left column before the Roll Dice button. The button’s onclick attribute indicates the action to take when the user of the XHTML document clicks the Roll Dice button. In this example, clicking the button causes a call to function play.


This style of programming is known as event-driven programming—the user interacts with a GUI component, the script is notified of the event and the script processes the event. The user’s interaction with the GUI “drives” the program. The button click is known as the event. The function that is called when an event occurs is known as an event-handling function or event handler. When a GUI event occurs in a form, the browser calls the spec-ified event-handling function. Before any event can be processed, each GUI component must know which event-handling function will be called when a particular event occurs. Most XHTML GUI components have several different event types. The event model is dis-cussed in detail in Chapter 13, JavaScript: Events. By specifying onclick = "play()" for the Roll Dice button, we instruct the browser to listen for events (button-click events in par-ticular). This registers the event handler for the GUI component, causing the browser to begin listening for the click event on the component. If no event handler is specified for the Roll Dice button, the script will not respond when the user presses the button.


Lines 123–125 end the table and form elements, respectively. After the table, a div element is created with an id attribute of "status". This element will be updated by the script to display the result of each roll to the user. A style declaration in line 13 colors the text contained in this div red.


The game is reasonably involved. The player may win or lose on the first roll, or may win or lose on any subsequent roll. Lines 18–20 create variables that define the three game states—game won, game lost and continue rolling the dice. Unlike many other program-ming languages, JavaScript does not provide a mechanism to define a constant (i.e., a vari-able whose value cannot be modified). For this reason, we use all capital letters for these variable names, to indicate that we do not intend to modify their values and to make them stand out in the code—a common industry practice for genuine constants.

Lines 23–26 declare several variables that are used throughout the script. Variable firstRoll indicates whether the next roll of the dice is the first roll in the current game. Variable sumOfDice maintains the sum of the dice from the last roll. Variable myPoint stores the point if the player does not win or lose on the first roll. Variable gameStatus keeps track of the current state of the game (WON, LOST or CONTINUE_ROLLING).


We define a function rollDice (lines 86–101) to roll the dice and to compute and display their sum. Function rollDice is defined once, but is called from two places in the program (lines 38 and 61). Function rollDice takes no arguments, so it has an empty parameter list. Function rollDice returns the sum of the two dice.


The user clicks the Roll Dice button to roll the dice. This action invokes function play (lines 29–83) of the script. Lines 32 and 35 create two new variables with objects repre-senting elements in the XHTML document using the document object’s getElementById method. The getElementById method, given an id as an argument, finds the XHTML element with a matching id attribute and returns a JavaScript object representing the ele-ment. Line 32 stores an object representing the pointfield input element (line 119) in the variable point. Line 35 gets an object representing the status div from line 124. In a moment, we show how you can use these objects to manipulate the XHTML document.


Function play checks the variable firstRoll (line 36) to determine whether it is true or false. If true, the roll is the first roll of the game. Line 38 calls rollDice, which picks two random values from 1 to 6, displays the value of the first die, the value of the second die and the sum of the dice in the first three text fields and returns the sum of the dice. (We discuss function rollDice in detail shortly.) After the first roll (if firstRoll is false), the nested switch statement in lines 40–57 determines whether the game is won or lost, or whether it should continue with another roll. After the first roll, if the game is not over, sumOfDice is saved in myPoint and displayed in the text field point in the XHTML form.


Note how the text field’s value is changed in lines 45, 50 and 55. The object stored in the variable point allows access to the pointfield text field’s contents. The expression point.value accesses the value property of the text field referred to by point. The value property specifies the text to display in the text field. To access this property, we specify the object representing the text field (point), followed by a dot (.) and the name of the property to access (value). This technique for accessing properties of an object (also used to access methods as in Math.pow) is called dot notation. We discuss using scripts to access elements in an XHTML page in more detail in Chapter 13.


The program proceeds to the nested ifelse statement in lines 70–82, which uses the statusDiv variable to update the div that displays the game status. Using the object’s innerHTML property, we set the text inside the div to reflect the most recent status. In lines 71, 75–76 and 78–79, we set the div’s innerHTML to


Roll again.


if gameStatus is equal to CONTINUE_ROLLING, to Player wins. Click Roll Dice to play again. if gameStatus is equal to WON and to Player loses. Click Roll Dice to play again.


if gameStatus is equal to LOST. If the game is won or lost, line 81 sets firstRoll to true to indicate that the next roll of the dice begins the next game.

The program then waits for the user to click the button Roll Dice again. Each time the user clicks Roll Dice, the program calls function play, which, in turn, calls the rollDice function to produce a new  value for  sumOfDice. If sumOfDice matches  myPoint, gameStatus is set to WON, the ifelse statement in lines 70–82 executes and the game is complete. If sum is equal to 7, gameStatus is set to LOST, the ifelse statement in lines 70–82 executes and the game is complete. Clicking the Roll Dice button starts a new game. The program updates the four text fields in the XHTML form with the new values of the dice and the sum on each roll, and updates the text field point each time a new game begins.


Function rollDice (lines 86–101) defines its own local variables die1, die2 and workSum (lines 88–90). Because they are defined inside the rollDice function, these vari-ables are accessible only inside that function. Lines 92–93 pick two random values in the range 1 to 6 and assign them to variables die1 and die2, respectively. Lines 96–98 once again use the document’s getElementById method to find and update the correct input elements with the values of die1, die2 and workSum. Note that the integer values are con-verted automatically to strings when they are assigned to each text field’s value property. Line 100 returns the value of workSum for use in function play.

Note the use of the various program-control mechanisms. The craps program uses two functionsplay and rollDiceand the switch, ifelse and nested if statements.

Note also the use of multiple case labels in the switch statement to execute the same state-ments (lines 42 and 47). In the exercises at the end of this chapter, we investigate various interesting characteristics of the game of craps.

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.