# Building the Rock, Scissors, and Paper Game

 Way Cool Okay, boys and girls, it’s time for something really fun! Now that you know how to work with if statements, we can create an interactive computer game.

Do you remember the Rock, Scissors, and Paper game from when you were little? Here’s how it works: There are two players. Each player selects rock, scissors, or paper. Then the two players simultaneously “show” the other their selection.

If both players have selected the same thing, it’s a tie. Otherwise, the winner is determined as follows:

• Rock wins over scissors (because a rock “smashes” scissors).

• Paper wins over rock (because paper “covers” a rock).

• Scissors win over paper (because scissors “cut” paper).

In our case, one of the players is the computer, and the other is the user of the computer program. The user will make a choice between rock, scissors, and paper. The computer’s choice will be made at random.

Here are the steps we’ll need to build into this program to make the game work:

• A method of capturing —another word for determining —the user’s choice of rock, scissors, or paper

• A way to generate a random choice for the computer

• A way to compare choices and determine the winner (or if it’s a tie)

• Finally, a way to display text that indicates the choices and the result

Figure 3-5 shows these steps in a simple flow chart —a diagram intended to show the “flow” of execution of statements in a computer program. The flow chart shown in Figure 3-5 is high level, meaning that it doesn’t “drill down” to the level of individual conditional statements. In many circumstances, it may be a helpful part of planning a program to create a flow chart that’s more detailed than this one.

Figure 3-5: A high-level flow chart of the Rock, Scissors, and Paper game

I’ll show you each of these steps in detail, but before we get there, we need to discuss a few preliminary programming concepts that I haven’t explained yet.

### Understanding Some Necessary Preliminaries

 Advanced To follow the Rock, Scissors, and Paper program, you need to know about some things that are only fully explained later in Learn How to Program.

#### Interacting with HTML Form Elements

You’ll need to know how to interact in a simple fashion with HTML form elements and the events fired by an element (Chapter 8, “ Understanding Events and Event-Driven Programming,” discusses these things). You’ve already seen in the age check example (Listing 3-3) that you can add code to the onClick event of a form button. The Rock, Scissors, and Paper example uses a similar mechanism to start a play of the game.

In addition, HTML form elements can be referred to by name in JavaScript code. We’ll need to know what the user selected—rock, scissors, or paper—which the user sets using option buttons (also referred to as radio buttons).

These are HTML <INPUT> elements of type=radio.

In JavaScript code, the value stored in a radio button—a Boolean true if it has been selected and a Boolean false if it hasn’t—can be evaluated using the following construction:

` document.formName.inputElementName.checked `

In the example, the form is named gameForm, and the radio button input elements are an array (I discuss arrays in a second) named game. The first radio button on the form is named game[0]. So, if it’s checked (selected), this expression:

` document.gameForm.game[0].checked `

will evaluate to true, and if the radio button hasn’t been selected, the expression is false.

#### Introducing Arrays

Chapter 6, “ Programming with Arrays,” fully explains arrays. In the meantime, you need to know that an array stores values that are of the same type, and they can be accessed using an index.

The index is notated using square brackets. In JavaScript it starts at zero (not as you might expect at one).

So whether (or not) the three radio buttons on the HTML form— one representing the user choice of rock, the next scissors, and the final one paper—are checked can be determined by Boolean evaluation of the expressions:

` document.gameForm.game[0].checked  document.gameForm.game[1].checked  document.gameForm.game[2].checked `

You may be curious to know why I used an array to name these buttons. If they’re named this way, the browser knows the radio buttons are related—and only one can be selected (checked) at a time.

#### Introducing Functions

A function is a piece of JavaScript code—in other words, a series of statements—that’s defined once in a program but can be executed many times. Functions (which are explained in detail in Chapter 5, “ Understanding Functions ”) can be passed values, also called parameters, to operate on, and they can return a value.

In the Rock, Scissors, and Paper application, functions are used to clarify the organization of the program—and to provide a mechanism so that the program code need not be assigned as a single string to the onClick event.

Listing 3-3 in contrast shows an example of assigning the entire program code as a quoted string to an onClick event. You can readily see why this would get out of hand (and be hard to read) if there were more than one or two lines of code.

#### Introducing the Random Method

The JavaScript Math object makes available a number of mathematical constants and functions. The Rock, Scissors, and Paper application uses the Random function of the Math object—which returns a pseudorandom number between zero and one.

I say “pseudorandom” because this number isn’t really random if you’re going to be picky—but it’s certainly random enough for playing a game of Rock, Scissors, and Paper.

But it’s not necessary to flip ahead. Now that you have been introduced to the preliminaries, we’re ready to forge full speed ahead with Rock, Scissors, and Paper.

### Building the User Interface

The first thing we’re going to do is build the user interface—or computer screen such as the Web page in which the user enters a choice and starts a play of the game—for Rock, Scissors, and Paper.

The user interface, as you can see in Listing 3-5, is almost entirely HTML (as opposed to JavaScript).

Listing 3.5: The Rock, Scissors, and Paper User Interface

` <BODY> <H2>  Play "Rock, Scissors, and Paper" the JavaScript way!  </H2> <UL> <LI>Rock smashes scissors!     <LI>Scissors cut paper!     <LI>Paper covers rock!  </UL> <FORM name="gameForm"> <P>Make a choice:  <BR> <INPUT type="radio" name="game" value="Rock" checked> Rock<BR> <INPUT type="radio" name="game" value="Paper">Paper<BR> <INPUT type="radio" name="game" value="Scissors">Scissors<BR> <INPUT type="button" name="play" value="Play" onClick="shakeIt();"> </FORM> </BODY> `

 Note I’m not going to take much time in this book explaining HTML tags because creating HTML isn’t really programming, and it would distract from the subject matter of this book. If you need to better understand the HTML tags used to create user interfaces in the examples, you should pick up one of the many books available that describe HTML in detail, such as HTML & XHTML: The Definitive Guide, Fifth Edition, by Chuck Musciano and Bill Kennedy (O’Reilly, 2002).

The HTML shown in Listing 3-5 creates the Web page shown in Figure 3-6.

Figure 3-6: The Web page (user interface) for Rock, Scissors, and Paper

If you look at the HTML that makes up the Web page, you’ll see that there only a few things you need to know from the viewpoint of the JavaScript program. First, the HTML form has a name— gameForm — that we’ll need in order to refer to input elements on the form.

Second, the three radio button input elements are all named game and can be referred to using array notation, as I explained a little while ago.

Finally, the user starts a round of the game by clicking the Play button. Clicking this button causes the button’s onClick event to fire. The code assigned to the button’s onClick event is a single JavaScript function, shakeIt:

` <INPUT type="button" name="play" value="Play" onClick="shakeIt();"> `

You can tell from this that program execution passes immediately to the shakeIt function when the user starts a round of the game.

### Understanding the Organization of the Code

 Do It Right! In contrast to the previous examples in Learn How to Program, you can find the program code for the Rock, Scissors, and Paper game in two JavaScript functions, shakeIt and whoWon. This is done for clarity—code organized into conceptual modules is easier to read and, in the long run, easier to maintain.

The function shakeIt is named to suggest the shaking of dice. It performs the following tasks:

• Randomly generates a choice for the computer

• Determines the choice made by the user

• Displays a message box showing both choices and calls the function whoWon with the choices as values

The function whoWon determines the winner and passes back an appropriate message to complete the message box display initiated by shakeIt.

Both functions are placed in the <HEAD> section of the HTML document. One reason for doing this is that everything in the <HEAD> section of an HTML document is loaded—or read by the computer—first. If you put a JavaScript function in the <HEAD> section of an HTML document, then you know it will be available—and the computer will know what you’re talking about—when you call it from the body of the document.

Listing 3-6 shows the general structure used for code placement in the Rock, Scissors, and Paper application.

Listing 3.6: Placement of Code in Rock, Scissors, and Paper

` <HTML> <HEAD> <TITLE>        JavaScript "Rock, Scissors, Paper" Game        </TITLE> <SCRIPT>     function whoWon (iplay, uplay) {     ...     }     function shakeIt(){     ...     }  </SCRIPT> </HEAD> <BODY>       ...       </BODY> </HTML> `

### Generating a Choice for the Computer

The first thing that the shakeIt function does is to obtain a random number between zero and one using the Math object’s random number generator that I talked about a little while ago:

` var randGen = Math.random(); `

Next, a choice of rock, scissors, or paper is assigned to the computer using if statements and the random number:

` if (randGen <= .33)     var computerPlay = "rock";  if ((randGen >.33) & & (randGen <= .66))     var computerPlay = "scissors";  if (randGen > .66)     var computerPlay = "paper"; `

### Determining the User’s Choice

To determine the user’s choice, the program uses another series of if statements—combined with the array notation I explained earlier:

` if (document.gameForm.game[0].checked)      var personPlay = "rock";  if (document.gameForm.game[1].checked)      var personPlay = "paper";  if (document.gameForm.game[2].checked)      var personPlay = "scissors"; `

The value selected by the user is now stored in the variable personPlay, and the value chosen for the computer is stored in the variable computerPlay.

### Finding the Winner

The last line in the shakeIt function does a couple of things at the same time:

` alert ("The computer played: " + computerPlay +      ". You played: " + personPlay + ".  " + whoWon(computerPlay,  personPlay)); `

The alert keyword tells the computer to display a message box. The string that will be displayed in the message box starts with the value of the choice randomly selected for the computer, computerPlay, followed by the user’s selection, personPlay. Next, the whoWon function is called with both values.

The whoWon function, shown in Listing 3-7, compares two variables, iplay and uplay, that are passed to the function. The variable iplay corresponds to the variable computerPlay, and uplay corresponds to personPlay.

Listing 3.7: The whoWon Function

` function whoWon (iplay, uplay) {     // "I" am the computer     if (iplay == uplay)        return "IT'S A TIE! TRY AGAIN, FRAIL HUMAN ENTITY?";     if (iplay == "rock") {        if (uplay == "scissors")           return "I WIN! ROCK SMASHES SCISSORS! COMPUTERS FOREVER!"        else           return "YOU WIN. Paper covers rock. Paltry human, how did you        beat me?";     }     if (iplay == "scissors") {        if (uplay == "paper")           return "I WIN! SCISSORS CUT PAPER! CHIPS BEAT BRAINS!"       else     return "YOU WIN. Rock smashes scissors. iconid=parrow       Frail human, would you like to try again?";    }    if (iplay == "paper") {        if (uplay == "rock")              return "I WIN! PAPER COVERS ROCK! ROCK AND ROLL, BABY!"        else   return "YOU WIN. Scissors cut paper. Oh, vain flesh and bone entity, iconid=parrow      I'll get you next time!";    }  } `

The function whoWon first checks to see if the two plays are the same, in which case the game is a tie. Next, it uses if statements to check each possible computer play (for example, rock). If the computer played rock, then the human user loses if the user selected scissors—and wins otherwise.

Each possible combination is checked using conditional statements, and the results are passed back to the shakeIt function as a string using the return keyword.

 Note As a reminder, the comparison operator (==) is used to compare two values for equality. On the other hand, the assignment operator (=) is used to assign a value to a variable.

### Playing the Game

It’s time to have some fun and play Rock, Scissors, and Paper against the computer. The computer, of course, is on the honor system.

Way Cool

You’ll find the complete program code for Rock, Scissors, and Paper in Listing 3-8. But before you go ahead and read it, let’s play against the computer a few times (see Figures 3-7, 3-8, and 3-9).

Listing 3.8: Rock, Scissors, and Paper—the JavaScript Way

` <HTML> <HEAD> <TITLE>   JavaScript "Rock, Scissors, Paper" Game  </TITLE> <SCRIPT>  function whoWon (iplay, uplay) {        // "I" am the computer        if (iplay == uplay)           return "IT'S A TIE! TRY AGAIN, FRAIL HUMAN ENTITY?";        if (iplay == "rock") {           if (uplay == "scissors")     return "I WIN! ROCK SMASHES SCISSORS! COMPUTERS FOREVER!"           else     return "YOU WIN. Paper covers rock. Paltry human, how did you beat        me?";        }        if (iplay == "scissors") {           if (uplay == "paper")     return "I WIN! SCISSORS CUT PAPER! CHIPS BEAT BRAINS!"           else     return "YOU WIN. Rock smashes scissors. iconid=parrow         Frail human, would you like to try again?";        }        if (iplay == "paper") {           if (uplay == "rock")     return "I WIN! PAPER COVERS ROCK! ROCK AND ROLL, BABY!"           else     return "YOU WIN. Scissors cut paper. Oh, vain flesh and bone entity, iconid=parrow        I'll get you next time!";        }     }     function shakeIt(){        var randGen = Math.random();        if (randGen <= .33)           var computerPlay = "rock";        if ((randGen >.33) & & (randGen <= .66))           var computerPlay = "scissors";        if (randGen > .66)            var computerPlay = "paper";        if (document.gameForm.game[0].checked)            var personPlay = "rock";        if (document.gameForm.game[1].checked)            var personPlay = "paper";        if (document.gameForm.game[2].checked)            var personPlay = "scissors";        alert ("The computer played: " + computerPlay +               ". You played: " + personPlay + ".  " +               whoWon(computerPlay,personPlay));     }     </SCRIPT> </HEAD> <BODY> <H2>     Play "Rock, Scissors and Paper" the JavaScript way!     </H2> <UL> <Li>Rock smashes scissors!      <Li>Scissors cut paper!      <Li>Paper covers rock!     </UL> <FORM name="gameForm"> <P>Make a choice:     <BR> <input type="radio" name="game" value="Rock"  checked> <STRONG>Rock</STRONG> <BR> <input type="radio" name="game"  value="Paper"> <STRONG>Paper</STRONG> <BR> <input type="radio" name="game"  value="Scissors"> <STRONG>Scissors</STRONG> <P> <BR> <BR> <INPUT type="button" name="play" value="Play" onClick="shakeIt();"> </FORM> </BODY> </HTML> `

 Try This at Home Figure 3-7: The computer played rock and the human played scissors—a win for the computer! Figure 3-8: Both players chose rock; it’s a tie. Figure 3-9: The computer played paper, and the human chose scissors and wins!

Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis