文档库 最新最全的文档下载
当前位置:文档库 › flashbookrps

flashbookrps

flashbookrps
flashbookrps

Chapter 2: Rock-paper-scissors

Concepts, skills and tools

In this chapter, you will create a computer version of the childhood playground game "rock, paper, scissors"—a game played by two people using hand gestures. In this version, a human player plays against the computer. The player selects a choice using picture buttons on the screen. The program you will write makes the choice for the computer using functions built into Flash (and common in many computer languages) that produce random results, that is, results showing no particular pattern.

Building this application will give you experience creating graphical buttons, programming random responses for the computer and the implementation of the rules of a game, and invoking animation to display the results.

You will use the following general programming concepts, skills and tools for Rock, Paper, Scissors:

?Writing code to handle an event

?Use of built-in function for generating random results (the Flash function Math.Random)

?Assigning numerical values for discrete choices

?Logical tests (the Flash statement is the if statement)

The Flash features used to construct this game include:

?Button symbols

?Object actions

?goToAndPlay statement

?labels for frames

?frame-by-frame animation

?Text fields

Description of the game

In the playground game, each player makes one of three choices: rock, paper or scissors using hand gestures. The rules of the game are:

?Rock breaks scissors – rock wins

?Scissors cuts paper – scissors wins

?Paper covers rock – paper wins

?If both players make the same move, it is a tie.

How this version of Rock, Paper, Scissors works

The version you will program matches a human player against the computer. The player makes a move by selecting one of the three choices. The opening screen is

The rock, paper and scissors graphics are actually buttons. When the player uses the mouse and clicks on one of these symbols, the program responds. The following screen shows a possible outcome when the player selects the rock. The text will guide you to program two forms of display to the player: text only, as indicated here and text plus animated sequences. You will see some snapshots from an animated sequence of a scissors cutting paper later on.

Key Design Issues

The role of the designer and programmer of a game is to produce the interface to accept player moves, generate computer moves, apply the rules of the game, and display the results. The key design tasks for rock, paper, scissors are

?Design the user interface to allow the player to input a choice.

?Generate a choice for the computer

?Determine the result

?Display the results

Solutions to each of these design and programming tasks are presented next. Use these suggestions as guidelines when building your own version of rock, paper, scissors. Task: Design the user interface to allow the player to input a choice.

Logic: The player must choose between the three options: rock, paper, or scissors and do so without knowing the computer's move. The design must make this easy for the player to do and for the programming system to recognize that it has taken place.

Solution: Put three buttons, that is, clickable images on the screen representing a rock, a piece of paper and a scissors. The player makes his choice by clicking on one of the images. Flash has a feature for programmers to specify what is termed an object action that takes place when an event such as clicking on a button occurs. Another name for this is an event handler. You will specify code to handle each of the three events: the player clicking on the rock; the player clicking on the paper; and the player clicking on the scissors.

Task: Generate a choice for the computer.

Logic: The computer, acting as the second player in the game, must also make a choice. Computers do not act on their own. You, the programmer, will generate the choice: rock, paper, or scissors. To be fair, you must do this independent of the player's choice. Solution: You will use the random facilities in Flash to generate a number and then map that number to one of the three choices.

Task: Determine the result.

Logic: Once both player move and computer move are known, the program must apply the rules of the game.

Solution: In each of the three places where you specify the code to handle the button release, you will use switch, Flash's version of the case statement, to check for the different conditions. Your logic will refer to the player's move and the generated computer move.

Task: Display the results.

Logic: After your code determines the winner and the specific rule that applies, you must display this result to the player.

Solution: Flash has facilities to generate animation. You will create 3 sequences for the 3 distinct winning conditions: rock breaks scissors; scissors cuts paper; and paper covers rock. Your code will invoke the appropriate animation by using the goToAndPlay command. In addition, your code will display in words what happened using what Flash terms a dynamic text field.

Preparing to program

Flash has a special symbol type called button. Symbols such as buttons cannot be drawn directly on the Stage. You either create a symbol with button behavior or acquire one from the Common Library. In the first chapter, you could use a standard button from the Common Library. However, for this application, you should create your own buttons. Unlike movie symbols, buttons have just 4 frames and these relate to the position of the mouse, not the passing of time. The frames are up, over, down and hit. The up frame will indicate the look of the button when the mouse cursor is not over it. The over frame refers to just that: the look of the button when the cursor is over it. The down frame specifies the button when the player is pressing down. The graphic in the hit frame specifies what area is to be considered a hit. By specifying them, you can make the button change in response to the user's action. Flash buttons can be any shape and you do not have to change the graphics for the different frames, though many people it is good to provide feedback to users for any actions. For this game, you will draw a rock, a paper, and a scissors for the up frames, respectively. You can decide what to do for the other frames. The design of a button is distinct from programming any events relating to the button. You design the button after clicking on Insert/New Symbol. This opens up a new editing window. After designing each of the 4 frames of each button, you will return to editing the main movie. At this point, there are no buttons in the main movie. You have two more tasks to perform for each button. You must place each button on the stage. Next, when one of these buttons is selected, say the rock, you open the Actions panel and program the action for responding to the player clicking on the rock. For this application, you will use the release event. The template for this is the following:

on (release) {

}

The event indicated by 'release' is the player releasing, letting up, the mouse button over your drawing of the rock. (See Related Flash features below). The code in-between the two brackets.

Other programming systems have facilities for implementing buttons, though they vary widely in terminology and exact usage. Visual Basic, for example, has command button controls and several event procedures already identified for you the write the code. In JavaScript, you can specify onClick=string indicating the action within an anchor tag. Libraries exist for Java and Java applets that set up interfaces for you to write the code. Similarly, libraries exist for C++ that provide facilities for buttons.

The next task is generating a choice for the computer move. One approach is to cheat! That is, you can program the computer to win always or lose always by choosing a move based on the player's choice. That is not what is recommended here. Instead, use the built-in Flash facility for producing random numbers. This is Math.random, the random method of the Math object. (Method is the name for a function associated with an object.

You will learn about defining your own objects in later chapters.) A call to Math.random will return a value from zero to less than one. Flash uses an algorithm that produces results with no apparent pattern. Most computer languages have similar facilities and you can accept that the results will be random. (Actually, in certain circumstances, it is important to evaluate the randomness of the results. Several years ago, a state lottery system was found to not produce random results.)

You need to work a little more to get what you need for this game. The Math.random produces a value greater than or equal to zero and less than one. You need to make a selection from among 3 things. The solution is to multiply this value by 3, getting a value we can call value3, and then determine the biggest integer (whole number) that is not bigger than the value3. This can be done in one line of code:

computermove = Math.floor(3*Math.random());

Math.floor is another method associated with the Math object. It does exactly what we need here. The floor method is defined as the biggest whole number not bigger than its argument. Other computer languages have a similar built-in function, but it may be called something different. For example, in Visual Basic, the name is Int. The equal sign signifies an assignment; the value of the expression on the right of the equal sign is placed in the variable named at the left of the equal sign. You read this line of code starting at the right, from inside the parenthesis out. The result will be either 0, 1 or 2 in the variable computermove. We will say arbitrarily that 0 corresponds to a choice of rock, 1 to a choice of paper, and 2 to a choice of scissors. This works as long as we are consistent. This assignment of numbers to choices is used in the coding for each event handler for the buttons. It is also used to set up an array called moves.

var moves = new Array("rock","paper","scissors");

You use arrays in programming when you need to refer to a set of things. The individual elements are referenced using index values. The var statement above defines moves as an array in which moves[0] is the string "rock";moves[1] is the string "paper"; and moves[2] is the string "scissors". Note the use of square brackets for array elements. You can now combine the last two programming techniques to realize that moves[computermove] will produce a string telling the computer's choice.

Since the moves array will be used by all 3 of the button event handlers, the var statement will be defined elsewhere, namely as a frame action. This corresponds to what are termed global variables in other languages. You could define an array in each event handler, but this is more efficient. The issue is called scope. The Flash terminology is that the scope of moves is to the main movie timeline.

Now it is time to discuss how to apply the rules of the game. You will be writing 3 distinct pieces of code according to what button the player has clicked. Assume here that the player has clicked on the scissors. Using the ideas just described, you know how to get a number 0, 1 or 2 and also a string indicating the computer move. You must write

code that compares these choices against the player's choice of scissors. The Flash code for this is a switch statement. JavaScript, Java and C++ all have switch statements. The terminology of Visual Basic is somewhat more evocative: it is Select Case. It is best explained by going right to the code needed. Here is the entire code for the scissors button.

on (release) {

var computermove;

computermove = Math.floor(3*Math.random());

computer = "Computer move: " + moves[computermove];

switch (computermove) {

case 0: result="Computer wins: rock breaks scissors";

break;

case 1: result="Player wins: scissors cuts paper";

break;

case 2: result="TIE";

}

}

The switch statement is what is termed a compound statement. It has format

switch (selectionvalue) {

case casevalue:

case casevalue:

}

You put the statements that you want executed under the appropriate case. You may have any number of cases and any number of statements for each case. Flash evaluates the selectionvalue and then jumps to the first case that fits the value. It will then continue to the following case unless you code a break; statement. The function of break is to break out of the compound statement. For the situation in rock, paper, scissors, you want to use the break. The switch statement will specify cases according to the 3 possible computer moves. The statements within each case will produce the feedback to the player on the outcome of the game.

The variables computer and result are used to display the results of the game. They are each associated with dynamic text fields.

The arrows show the text field, the designation of it as a dynamic text field, which means that it can be changed by programming, and the reference to result as the associated

Var[iable]. The assignment statements will change the contents of the text fields.

If you want to give the player more dramatic feedback than simply text, you can build three sequences of frames on the Timeline that show a rock breaking a scissors, a scissors cutting paper, and a paper covering a rock. The statements within the switch statement will change the value of the text fields AND cause the program to jump to the appropriate frame for the animated sequence. This will be done using the goToAndPlay procedure.

Frames are labeled using the Properties panel. If it is not present, click on Window and then Properties to make it appear. The following screen shot shows the Properties window:

You type the name you want for the frame where it says . You will also need to put stop(); statements to stop the flow of frames from continuing into the animated sequences.

Final Timeline, Stage, Library

Since we suggest a two-phase approach to building this application, we describe two final settings. For the project that just has text output, this screen shot shows the Timeline, part of the Stage, and the Object Action for the Rock button:

Notice that there is just one frame, with two layers. The board layer contains 3 buttons and two text fields (only one showing). The selected object, the rock button, has actions specified for the on (release) event. Here is another screen shot, with the actions layer,

first and only frame selected:

The next screen shot shows the Library, with its 3 symbols: the 3 buttons.

To summarize the text version of rock, paper, scissors: 1 frame, 2 layers, 3 button symbols, 2 text fields, object action code for each of the three buttons, frame action code for the first frame.

The animated display version of the application builds on the text version. What is added are more frames, a new layer holding the frame labels, and additions to the object action code for each of the buttons.

The Timeline for the animated display version is shown in this screen shot:

Here are some partial screen snaps showing some individual frames from the rock breaks scissors sequence:

From the scissors cuts paper sequence:

Note: we inserted a keyframe on the labels layer at the last frame in order to make the label "scissorscuts" be displayed on the panel.

The successive frames are created by making minor modifications of parts of the three original drawings for the rock, paper and scissors using erasing, paint bucket, selection, movement and transformation.

The modification you must make to the code is to add the goToAndPlay statement to the appropriate case, with the appropriate argument. Here is the complete event handler for the scissors button:

on (release) {

var computermove;

computermove = Math.floor(3*Math.random());

computer = "Computer move: " + moves[computermove];

switch (computermove) {

case 0: result="Computer wins: rock breaks scissors";

goToAndPlay("rockbreaks");

break;

case 1: result="Player wins: scissors cuts paper";

goToAndPlay("scissorscuts");

break;

case 2: result="TIE";

}

}

The rock and the paper button are changed in a similar manner. You should make these changes first and then add the frames for the animation. This is because adding keyframes copies the contents of the Stage, including any object actions. If you then go back and add to the object actions in the first frame, it will NOT be copied over to the buttons in later frames. The result of not making the change first is that the animation will not work for subsequent moves.

One more important coding task remains. You need to add keyframes and put in the code for stopping the animation at the end of each sequence. Otherwise, the animation continues. This is shown in the following screen shot:

To summarize the animated display version of rock, paper, scissors: there are 40 frames (the exact number will vary) and 3 layers. The layers are board, actions, and labels. There are 3 labels. Code is in the actions layer in the first frame and the frame corresponding to the end of each animated sequence. There is also code for the button event handlers. The Stage contains the 3 button symbols, 2 text fields, and graphics drawn directly on the stage.

Construction plan

It is always beneficial to divide a programming task into phases. For rock, paper, scissors, first implement the basic logic and display the results using text by itself. When you know that that works, modify the switch statements to add jumps to named labels. By using named labels, you do not need to know the frame number for each of the animated sequences. Construct the animated sequences (inserting the keyframes and drawing). You can do this using the original drawings of the rock, paper, and scissors. Insert the labels by inserting the keyframes on the labels layer at the appropriate places.

Version 1.

Rename the first layer to be diagrams (double click on Layer 1 and type in diagrams). Add and rename two more layers: code and labels.

Prepare symbols

You need to prepare rock, paper and scissors buttons. For each one, do the following: Click on Insert/New Symbol. Select the behavior type of button. Give it an appropriate name. You will get what looks like a new, bare Stage. The Timeline has only 4 frames. Make your drawings. To simplify things if you do not want to spend time now on drawing, make one drawing. Click on the next frame (the over frame) and Insert keyframe. The same graphic will be copied over. Click on the next frame (the down frame) and Insert keyframe. Click on the next frame (the hit frame) and repeat.

To go back to the main movie, click on Scene 1 and repeat for the next button.

Content to the Stage/Timeline

With the Library open (Window/Library), select and drag each of the 3 buttons to the Stage, diagrams layer, frame 1.

Program frame and object actions

Select the first frame, code layer. In the Actions panel (Window/Actions), type in:

var moves = new Array("rock","paper","scissors");

var computer;

var result;

computer="Make your choice.";

result="";

stop();

To set the handling of the button events, click on the first frame, diagrams layer. The scissors code is given above (use the first example). Select the scissors and enter that

code (you may need to click on the Stage where there is not content and then click on the scissors). Then select the rock button In the Actions panel, using the scissors code as a model, program the rock and then the paper button.

Try the program by clicking on Control/Test the movie. Once it works, you can go on and add the animated responses.

Version 2.

Prepare symbols

Use what you have already.

Program frame and object actions

The code in frame 1 is the same as before.

To set button actions, proceed as before, using the second scissors example as the model. Notice: you will enter this code before you have created the new frames, including the keyframes with the labels.

Add to the Stage

Create 3 sequences, denoting a rock breaking a scissors, a paper covering a rock and a scissors cutting paper. One way to do this is to re-use the graphics for the rock, paper, and scissor buttons.

Assume we are working on rock breaks scissors. Open up the Library (Window/Library) and click on the rock symbol to edit it. Copy (using the button) the image you want, most likely the image in the up frame. Then return to Scene 1, that is, the main movie. Select a new frame on the diagrams layer. We chose frame 5, but you could actually chose frame 2 or any other frame. Insert a keyframe. Everything will be copied over from frame 1 (or, more correctly, the last keyframe). Click on Edit/Paste and then move the image where you want it to be. Now go to the Library and copy the scissors symbol. Paste and then move it where you want, presumably under the rock. Select frame 6 and insert a keyframe. Select the rock using the arrow to draw a rectangle around it or the lasso. Move the rock down. Select frame 7 and insert a keyframe. Again, select and move the rock down. Continue until the rock is on top of the scissors. You make a small change in the graphics and then move on to the next frame. For the last one or two frames, you can depict the scissors breaking by using the lasso to select parts of the scissors and moving them away.

After you create the animated sequences, you must do the coding to make the application work. In the first frame of each of the 3 sequences, select the frame in the labels layer. Insert a keyframe. Give the frames the labels rockbreaks, scissorscuts, and papercovers.

Tips and warnings

A very common error is to neglect to insert a keyframe before trying to place code or create a label.

You may see strange things happening because you unintentionally have selected more content on the Stage than you wanted. Click outside of any content to deselect and then try again.

Related Flash features

Flash provides an If statement as another way to handle conditional logic. The If statement (common to most programming languages) has the format:

If (condition) {

}

The curly braces can contain any number of statements, which are executed only if the condition is true. You can also have an else clause:

If (condition) {

}

else {

}

Other applications in this text will make use of the If statement.

Ideas for enhancements & other applications

The playground game rock, paper, scissors does not use text. How would you make a computer version without text? Remember: you need to display the computer's move back to the player and also show the results.

You can make a Flash application that would be part of an on-line store by making the customer click on a picture of an item indicating a product or a service. The code would do something different for each selection.

Exercises & discussion questions

1.Explain how a button is created (hint: what are the 4 frames) and how event

handlers for the button are programmed.

2.How does a switch statement work?

3.

相关文档