Development environment



Chapter 6: Functions and parameters

This chapter will continue the study of programmer-defined functions started in previous chapters, with focus on function parameters. The chapter also addresses the topic of how to encode features of the application such as the rules of a game. After studying this chapter, you will

• understand the role of function parameters

• learn how different programming languages provide the function parameter feature and some of the different terminology used

• understand what is meant by program state and how variables are used to represent the state

• appreciate how aspects of a representation or encoding can be arbitrary

• acquire experience using function parameters, arrays, global and local variables, and cel animation in Flash with ActionScript.

Motivating Example

The examples for this chapter are computer versions of the playground game, rock-paper-scissors. Two versions will be described: one with text results and the other with animated results, taking advantages of the facilities of Flash.

An opening screen for the game is shown in Figure 1.

[pic]

Figure 1. Opening screen shot for rock-paper-scissors.

The 3 pictures on the screen are actually buttons. When the player clicks on one, say rock, the program makes a choice for 'the computer'. In Figure 2, the program indicates a tie because both player and computer have chosen the same thing, the rock.

[pic]

Figure 2. Screen shot showing a tie.

In Figure 3, the screen displays that the computer has won, since the player clicked on paper and the computer selected scissors. This design does depend on the player remembering his or her choice and having the faith that the program is fair. In this instance, 'fair' means that the computer's choice is based on a random calculation and not knowledge of the player's move.

[pic]

Figure 3. Screen shot indicating computer win.

A fancier version of the game makes use of the animation features of Flash. In this version, the player's moves and the implementation of the rules of the games are the same. However, depending on which of the 3 non-tie results happens, the player is treated to a short (very short) animation illustrating the result. The next set of screen shots show this for the rock breaks scissors situation. In Figure 4, the rock is partially off the Stage (above the stage). When the published version is shown, the rock will appear to fall from above onto the scissors.

[pic]

Figure 4. Screen shot of start of animation for rock breaks scissors.

In Figure 5, the rock is falling towards the scissors:

[pic]

Figure 5. The rock nears the scissors.

In Figure 6, the rock hits the scissors:

[pic]

Figure 6. The rock is on top of the scissors.

Next, Figure 7 shows the rock on top of the scissors.

[pic]

Figure 7. The rock has crushed the scissors.

In the last frame of the animation, shown in Figure 8, pieces of the scissors are shown flying off.

[pic]

Figure 8. Pieces of the scissors fly off.

A similar sequence is created for the two other situations: paper covering rock and scissors cutting paper.

The critical features required by this application include

• a mechanism for the player to indicate his or her move

• pseudo-random facilities to produce the computer move

• ways for the program to display the results

• incorporating the rules of the game into the program

• animation: techniques to produce changing displays so that the player sees movement

Introduction to concepts

As was described in previous chapters, all programming languages provide programmers a way to extend the language by defining their own procedures, pieces of code that can be invoked by name. One reason to do this is to avoid writing the same code multiple times. When a procedure is defined, it can be called (invoked) from multiple places. Programming languages have built-in procedures and also provide a way for programmers to define their own procedures.

TECHNICAL NOTE: The terminology varies. In some languages, a function is a procedure that returns a value so that the function call can occur within an expression or wherever an expression can occur, for example, the right side of an assignment statement. In some languages, subroutines are procedures that do not return values. The strongly-typed languages require definition of the datatype of the returned value in the definition of the procedure.

Methods are procedures defined as part of the definition of a class. A class defines code (the methods) and data (called properties or attributes that the methods act on). Strings are implemented in JavaScript and ActionScript as instances of a String class. If a variable is assigned a string literal, as in

title = "Logic";

then you can write code making use of String properties

title.length

and String methods

title.substring(a,b)

There are many other String methods.

NOTE: JavaScript and ActionScript use the term 'function' for any procedure, returning a value or not, so, for the most part, that is the terminology of this book. However, here and elsewhere, you will find some examples of other languages.

Procedures can be called with extra information, a folksy way of describing what you have seen go in-between the parentheses after the function name as part of the call. Here again, terminology differs. Some languages refer to the values in the call as arguments and the values in the procedure definition as parameters.

Games and other applications often require aspects of the application to be encoded in some way in the program. This encoding can take different forms and you will read about strategies in this and other chapters. One subtle point is that often the encodings are arbitrary, that is, totally up to you, the programmer. Many different ways would work. This arbitrariness can be unsettling. Every application has its own distinct set of representation issues, but we hope the rock-paper-scissors example and then the others in this text will contribute to your programming education.

EXAMPLE: The examples will feature calling one procedure with different parameters. The parameter will indicate the player move. The rules of the game will be encoded in logical statements: a sequence of if statements. The animated rock-paper-scissors example will demonstrate a basic facility of the Flash system: cel or frame by frame animation. The Flash-specific mechanism of control passing from frame to next frame or to a specified frame can be compared to flow of control in procedures.

Description: procedure definition header line

A programmer-defined procedure is defined in different programming languages by a header or prototype line with a mixture of keywords; sometimes called modifiers, that specify attributes of the procedure; the programmer-given name of the procedure; and names and, with some languages, datatype information for the parameters. If the procedure returns a value, the strongly-typed languages require datatype information on the returned value. In JavaScript and ActionScript, the header takes the following format:

function functionname (parametername1, parametername2…)

The keyword function is required and must be spelled correctly! What is indicated here as functionname is up to the programmer. Generally, names need to start with a letter and cannot have blanks.

TIP: Make function names, variable names, and parameter names meaningful even if that means making them longer. We refer to this as not economizing on typing. You will spend more time examining your code than typing it.

If there are no parameters, then the functionname is followed by opening and closing parentheses. If there are parameters, then when the function is invoked, the values specified in the call are given the parameter names for use 'in' the function. Using the rock-paper-scissors example, if the function starts with the header statement

function computerturn (player)

and the function is called with the statement

computerturn("rock");

the technical jargon is that "rock" is passed as the parameter. In the function computerturn, whenever code refers to player, as in

if (computer==player)

player will have the value "rock" unless player has been assigned a different value earlier in the function. The parameter player is treated as a local variable with the value set by the call. When computerturn completes, the variable is no longer accessible.

TECHNICAL NOTE: In the implementation of most programming languages, space for the local variables is assigned in the memory circuitry of the computer when a function is invoked. When the function completes, the association between the locations in memory and the variable names goes away and the memory is available for other purposes.

Examples in Java

The general notion of parameters applies to other programming languages, but some of them have other mechanisms concerning parameters. As you may guess if you think about what have been described as strongly-typed languages, the parameter definitions also must contain datatype information. In Java[1], a class is a way of specifying a combination of procedures and variables. An object or object instance can be declared to be of the class. The procedures are called methods. Without going into too much detail at this time on the definition of classes, the definition of a method for building a rectangle object could start with

public Rectangle (float x1, float y1, float x2, float y2)

This method would be part of a class definition for objects of type Rectangle. The modifier public means that statements in other classes in other files can invoke this method. This method builds the rectangle. It accepts 4 parameters, indicating two opposing corners of the rectangle, each as floating point numbers. It is assumed that the other two corners are at (x1, y2) and (x2, y1). Specifying the datatype of the parameters means that the compiler can do type checking for all uses of the parameters inside the function. It also means the compiler does type checking for the calls of the function. This last leads to a feature of Java called method overloading. Programmers can specify different versions of a method with the same name, the versions differing based on different definitions for the parameters. These are sometimes called different signatures or prototypes. For example, for rectangles, a programmer may decide that it is useful to think of default situations. The method starting off (with prototype)

public Rectangle (float x, float y)

will build the rectangle with corners at (0,0), (x, 0), (0,y), and (x, y).

The method starting off

public Rectangle (float side)

will build the rectangle, which happens to be a square, with corners (0,0), (0,side), (side,0) and (side, side).

The compiler examines each call of the method and chooses the one with the corresponding signature.

There is one more feature of procedures that is specified in Java and certain other languages: the return value. You may have seen the following as the prototype of the method required for any Java program:

public static void main(String args[])

The void modifier indicates that this method does not return any value. If a programmer wanted to specify a method that returned a value of a certain datatype then the prototype would follow the format

modifiers datatype functionname (parameter types and names)

Let us assume there was a method in the rectangle class named contains that accepted two values of datatype double representing the x and y coordinates of a point and returned true if this point was in the rectangle and false otherwise. The prototype would be

public Boolean contains(double x, double y)

This indicates that the method returns a value of true or false. The compiler can check that contains is invoked in places that require Boolean values, such as the condition expression of if statements.

END OF JAVA EXAMPLES

Description: call by value versus call by reference

The discussion so far has focused on use of the parameter values. What if the code changes the parameter value, that is, the variable in the procedure holding the parameter that was passed? When local variables are changed, the change lasts as long as the variable last, only until the procedure ends. If a procedure is called with a variable A as one of the parameters, and that parameter is changed in the procedure, will the variable A be changed when the procedure is complete and control returns to the point of the call? The answer is: it depends. In JavaScript, the parameters are called by value. This means that the value of the parameter is calculated and passed to the called procedure. The opposite of this is call by reference. In this case, what is passed to the procedure is a reference to the variable and so the variable itself will be changed if it is changed within the called procedure. In some languages, the programmer has a choice and can specify which of the two it is to be for each parameter.

An exception to the 'call by value' rule in JavaScript concerns arrays. Recall that an array is a sequence of values. In the rock-paper-scissors example, an array will be used to hold the three strings "rock", "paper", and "scissors". The JavaScript processor passes a copy of header type information about an array when an array variable is named in the function call. This information allows the called program to make some changes to the original array, such as changing one of the elements. The following HTML/JavaScript file demonstrates this:

var origa = [1, 2, 3];

testparms(origa);

alert("This is origa after the call: "+origa);

function testparms (a) {

a[1] = "Hello";

}

nothing

The sequence of operations, also referred to as the flow of control, is as follows:

load script element

execute var statement setting up the variable origa as an array

set up definition of the testparms function

execute call of testparms, using origa as the parameter

execute the statements in testparms, with a set to be origa

return from testparms

execute alert statement

load body element

[The purpose of this exercise is to see what appears in the alert box. After clicking on the OK for the alert box, the element is loaded and the word nothing appears on the screen.]

The alert box shown in Figure 9 indicates that the element with index 1 in the array has, indeed, been changed.[2]

[pic]

Figure 9. Alert box showing value of array variable after function call.

However, if the code changes the variable a to be a string or a number or a different array, these changes will not persist. Try it! This behavior is repeated in some other languages.

The alert (very alert) reader may now ask what happens to strings. Will a string defined outside of a function be changed by code inside a function? The exact analog to the array example, changing one character in the string in place, cannot be done. If the code in the function assigns a new string to the parameter value, the original string remains the same. Given the file,

var origs = "This is the original string.";

testparms(origs);

alert("This is origs after the call: "+origs);

function testparms (a) {

a = "Now this is a new string";

}

nothing

The alert box shown in Figure 10 shows that the variable still holds the original string.

[pic]

Figure 10. Alert box showing string variable after function call.

TECHNICAL NOTE: In what has been discussed, the correspondence between values in the call and values in the procedure were based on the order of the values: the first value in the call is assigned to the first parameter in the definition of the function, the second to the second, and so on. There are languages supporting the technique in which parameters are indicated by name. This is similar to the use of attributes in HTML tags:

is the same as

Description: flow of control and cel animation

In programming, flow of control refers to the order of execution. The execution of an if statement uses the evaluation of the condition to determine whether flow of control goes to the if-true clause or not. Whenever a procedure is invoked, the flow of control changes from the calling procedure to the called procedure. When the procedure is complete, control generally returns to the called procedure. Event programming allows the programmer to specify execution of code if and when events occur. In some programming systems, it is possible to specify the invoking of multiple processes. That is, a so-called child process starts and the parent process continues at the same time.

Flash has a flow of control from frame to frame along in addition to the flow of control indicated by event handling. Each frame has its own material on the Stage and its own ActionScript. Flash also allows multiple movie clips to be present 'on the Stage' and each movie clip has its own flow of control.

In Flash, you can specify ActionScript in each frame. If a command occurs in a function in one frame such as

goToAndPlay(frame_name or frame_number)

then control leaves the original frame and goes to the frame indicated. The default flow is frame to frame. To change this, you need to put in calls to goToAndPlay or stop. Unlike function calls, the goToAndPlay does not set up any return to the place just after the call. Though this is certainly a complexity of Flash, the code in the frames and the event handling code can fit the problem and, in actual practice, be easy to understand.

TIP: There are practices that help address the problem of not knowing "where's the code?", a question asked by many a new Flash programmer. One practice is to put all function definitions in the first frame, in a layer containing only ActionScript. Other places, that is, event handling associated with buttons events or movie clips events or actions in the many frames can contain calls to the functions defined in the first frame.

Description: representation of application features

The last general topic is representation of application features. It is not easy to discuss in the abstract so most of the exposition will be in the Application and Reflection sections.

In games and other applications, it may be necessary to represent different choices. In rock-paper-scissors, the player indicates a choice by clicking on one of three buttons. To be fair, the computer or system move is calculated using the pseudo-random features. The tactic chosen here is to code a calculation that returns one of the three values 0, 1 or 2. These values, in turn, are used as index values for an array that has been set up to hold the strings "rock", "paper" and "scissors". This uses the order of choices as they appear in saying the name of the game, but it is really arbitrary. The player is not aware that the Math.random method returns a value that was then mapped to a number and used as an index. This type of representation is common in programming.

Now we move on to the implementation of the examples.

Reading Checks

1. Define and contrast the terms procedure, function, and method.

2. Give an example of a String method.

3. Give an example of a class method.

4. Write an example of a function definition header line in JavaScript (or ActionScript). What is the meaning of each term.

5. Write an example of a method definition header line in Java. What is the meaning of each term.

6. If x is the name of a parameter in a function fun, parameters are passed by value, and the function definition has the line: x = x +2; then what will be the value of the variable z after the following lines of code:

z = 10;

fun(z);

7. What is the function call to jump to a new frame in a Flash application?

8. What is the function call to stop the flow of control to the next frame in a Flash application?

Application

This section reviews the use of functions in previous chapters and then goes on to describe construction of two versions of rock-paper-scissors using Flash.

Review of previous examples

The previous uses of programmer-defined functions, with one exception, all took no parameters and did not return values. With regard to returning values, to use terminology for some programming languages other than JavaScript, they were procedures or subroutines, not functions. JavaScript uses the word function for all procedures, those returning values and those that do not.

TECHNICAL NOTE: A procedure that does something other than calculate or generate a value is said to have side-effects.

The money function, described in Chapter 3 as an alternative approach for the example in Chapter 2, was a true function. It returned a value, a string. The money function had one parameter, a number representing a cost. The function produced a string that represented the number in proper dollars-and-cents formatting. The call to the money function was on the right-hand side of an assignment statement. The target, indicated in the left-hand side of the assignment statement, was the value of the element in the HTML page.

The coding for this function, since it was in JavaScript, did not have any datatype declarations. However, the programmer needed to be aware of datatype. The parameter value was used in a concatenation operation with a string

formatteds = orig + "00";

to produce a string that was, in turn, manipulated to produce the final result.

In contrast to the programmer-defined functions, there have been many uses of built-in functions. For example, the Math.random method was used without any parameters to produce values used in several examples. The parseFloat function was used to take a string input by the player and produce a floating point number (a number with a fraction):

bias = parseFloat(document.b.sbias.value);

Plan of attack for rock-paper-scissors

TIP: The examples in this text increase with complexity with each chapter, as is appropriate. Do resist the urge to jump to the coding. The Plan of attack section in each chapter provides an overview. Read it before going on to study the detailed implementation. This will help prevent the tendency to copy code and put it in the wrong place. The What can go wrong section may be useful in identifying problems so it makes sense to read it ahead of time and also refer to it once you have started. Similarly, when you complete an application, take the time to read the Reflection section and do your own reflecting on the process.

Overview, focus on text game

The text only version of the game will consist of a single frame. Three buttons will be created as New Symbols. Instances of each of these symbols are moved to the Stage. Note that this is a situation in which is makes sense to create your own buttons. Flash comes with many different styles of buttons in the Common Library and also the Pushbutton component and these have their place. This application calls for a button that looks like a rock, a button that looks like a scissors and a button that looks like paper. You create a button by clicking on Insert/New Symbol. Click on button (as opposed to Movie Clip or Graphic) and give the button a name. To create buttons, you need to create 4 keyframes (the system starts with one so you need to Insert/Keyframe 3 more times) for the Up, Over, Down and Hit frames.

The Stage also holds 3 text fields: one Static and two Dynamic. Static text fields do not change. Typically they are used to label parts of the screen or to provide information to the player that will not change. Dynamic text fields can be changed by code. Flash provides a third type of text field: Input. These fields can be changed by the user/player. Dynamic and Input text fields require the programmer to specify a Var: name so the fields can be accessed by code. You create a text field by clicking on the A in the Tools panel in Flash and then click, press and dragging to create a rectangle on the Stage. You then change the type of text field using the dropdown menu near the upper left corner of the Properties panel.

PREVIEW: Input text fields will be used in the bouncing ball example in Chapter 10.

Figure 11 shows the Flash development environment with the 3 buttons and the text fields. One of the text fields is selected. Note that the name result has been placed in the field labeled Var:. This is necessary to give the field a variable name so that the ActionScript code can change it.

[pic]

Figure 11. Stage shown with text field selected.

The code in the text application is located in 4 places. Each button has event handling code.[3] Figure 12 shows this for the rock button. Notice the rectangle around it indicating that it is selected on the Stage. The coding

on (release) {

computerturn("rock");

}

means that if and when the player presses down and then releases the mouse button while the cursor is positioned over this button, a call is made to the function computerturn with a parameter value of "rock".

TIP: The screen shown in Figure 12 was constructed by setting the Stage to be at 50% and expanding the Actions panel. This is a useful trick to make the Stage and the Actions panel both visible on the screen. Of course, when you are drawing, you will want to set the Stage to be larger, 100% or larger to facilitate drawing details.

[pic]

Figure 12. Action specified for the rock button.

You will select and add the corresponding code for the paper button instance and the scissors paper button instance. There will be 3 calls to the computerturn function, each with a different parameter.

The function definition for computerturn and an array variable definition encoding how the random computer move is to be implemented are placed 'in' the frame. (The exact coding will be shown below.)

TIP: When using Flash, you need to distinguish between ActionScript in frames and ActionScript associated with buttons and movie clips. In this application, and many others, function definitions are in frames and calls to the functions are part of the Actions associated with buttons and movie clips.

Animated game overview

The animated version of the game is built on the text version. The difference is that the Timeline contains more frames. There are labels indicating the start of each of the three sequences: "rockbreaks", "papercovers" and "scissorscuts". There is action code in the frame corresponding to the end of each sequence with the single statement

stop();

This prevents one animation from flowing into the next. Figure 13 shows the timeline for the animated game.

[pic]

Figure 13. Timeline for animated rock-paper-scissors.

Using layers for organization purposes, that is, to hold the ActionScript and the labels is not necessary but considered a good practice. The labels layer shows 3 frames that have labels attached. The third one, shown only by a flag, is Scissorscuts. The actions layer shows the frames with code.

The first frame has the bulk of the code, including the definition of the function computerturn. This function definition will be similar to the one for the text game with the addition of gotoAndPlay statements.

Looking at Figure 13, you can see three frames after frame 1 with the small a indicating the presence of ActionScript. In each case, the ActionScript is a stop(); statement.

The frames in the board layer starting at the frame under Rockbreaks contain the frame-by-frame animation showing a rock falling on a scissors. Similarly, the frames starting with the one under Papercovers shows a paper falling on top of a rock. Lastly, the frames starting with the one under the flagged frame that does have the label Scissorscuts shows a scissors cutting into paper.

Use of concepts in implementation

Create the buttons and the text fields as described in the previous section. Bring instances of the buttons to the Stage. It is not necessary to give these instances names since you will not be creating any code that references the buttons.

This application makes use of functions and parameters, the focus of this chapter. As you can see from Figure 12, a function is called from the action associated with each button, the event handler for the release event. Each of the three calls makes use of a different parameter value, namely the one indicating the button pressed.

computerturn("rock");

computerturn("paper");

computerturn("scissors");

A string is used because this will ease the comparison with the computer move to be explained later in this section.

The ActionScript in the first, and for the text version, the only frame, starts with an assignment statement to one of the two dynamic text fields:

computermove="Make a move";

The next set of statements sets up an array of strings to be used in the generation of the computer's move. This is the encoding of game moves. Remember that the player never sees the 0, 1 or 2.

var options=new Array();

options[0] = "rock";

options[1] = "paper";

options[2] = "scissors";

The next piece of coding is the definition of the computerturn function. The first line specifies the name of the parameter.

function computerturn (player) {

When the function is invoked, the value specified in the call will be assigned to player, acting as a local variable.

The next line sets up computer as a local variable and assigns it a value from the options array. The specific value, that is, the index to the array, is the result of the expression that starts off with a call to Math.random.

var computer = options[Math.floor(Math.random()*3)];

The right-hand side of the assignment can be analyzed as follows:

Math.random() produces a number from 0 up to, but not including 1

… multiplying by 3 produces a number from 0 up to, but not including 3

…taking Math.floor produces a whole number, either 0, 1 or 2

…as an index into options produces either "rock" , "paper" , or "scissors"

The next statement shows the result to the player by placing a string into computermove. The string is a concatenation of the literal "Computer played " and the value of the variable computer.

computermove= "Computer played " + computer;

Now it is time for the code that carries out the rules of the game. This is a set of if statements that can be in any order. Note an alternative way of implementing the game logic would make use of nested ifs or the switch statement (see the Exercises).

Given that the plan is to use the individual if statements, how many should there be? There are 3 times 3 possibilities: 3 possible moves by the player and 3 moves by the computer. This yields a total of 9. However, the 3 distinct situations when the player's move and the computer's move are the same can be handled with one if statement. This leaves 6 more situations for a total of 7. It is good practice to do this type of checking on your coding.

The true clause of each if statement assigns a string to the dynamic text field named result.

TIP: Notice the double equal signs for the equality test. A single equals sign is the operator for assignment. Notice also the double ampersand, which is the logical AND operator.

********NOTE NOT FOR TEXT BUT FOR COPY-EDIT, make sure the double equal sign appears as such and not as a single big equal sign. This happens with font Courier New, Bold, on my computer*********************

if (computer == player) {

result="TIE"; }

if (computer=="rock" && player=="scissors") {

result= "Computer wins: rock breaks scissors"; }

if (computer=="paper" && player=="rock") {

result="Computer wins: paper covers rock"; }

if (computer=="scissors" && player=="paper") {

result="Computer wins: scissors cuts paper"; }

if (player=="rock" && computer=="scissors") {

result = "Player wins: rock breaks scissors";}

if (player=="scissors" && computer=="paper") {

result = "Player wins: scissors cuts paper"; }

if (player=="paper" && computer=="rock") {

result = "Player wins: paper covers rock"; }

}

The ActionScript for the first frame ends with

stop();

This stops the Flash system from looping, or, in the animated version, going on to subsequent frames.

To add animation to the application, you need to create new frames using the Insert/Keyframe command. You can follow the approach indicated by the timeline shown in Figure 13 and insert new keyframes at frame 5, 15 and 25 in the labels layer. Use the properties panel as shown in Figure 14 to give the frame a name.

[pic]

Figure 14. Properties panel after entering name for frame.

This is making the estimate that no animated sequence will take more than 10 frames.

TIP: You do not need to economize on frames nor do you need to guess exactly how many you will use for each animated sequence ahead of time.

Next, add keyframes in the board layer. Every time you add a new keyframe, Flash copies the contents of the last keyframe to the new keyframe. This allows you to use the graphics in the previous frame as a starting point for the new frame.

For the first animated sequence, you need to add graphics showing a rock falling on top of a scissors. To get these graphics, you can reuse the graphics from the buttons. Do this by editing each button (click on Windows/Library to get the Library and then double click on each button). Select and copy the graphics. Use Figure 4 through Figure 8 as a model.

You use the drawing features of Flash to select and move the graphical material. When you start the next animated sequence, under the frame labeled Papercovers, you will need to erase the rock and scissors debris and copy in the graphics for paper and rock. Similarly, when you start the third and last sequence, you will need to erase the paper and rock and start with the scissors and paper.

After completing the frames in the board layer, insert a keyframe in the actions layer in the same frame as the last one in each sequence and put in stop(); statements. This ensures that the program does not advance to the next sequence after showing the results of a game.

Reading Checks

1. The code: Math.random()*3 produces a number in what range?

2. The code: 1+Math.floor(Math.random()*6) produces what set of integers? This is a preview for the game in the next chapter.

3. What is the result of Math.floor(2.5762)?

4. Describe how to add a new keyframe in Flash.

5. Where does the code go for making a call to a function the event procedure for clicking and releasing a button?

What can go wrong

Be sure to put the names of the dynamic text fields in the Var field in the Property panel. A common mistake is to put the name in the instance field.

You need to be careful to put the definition of the computerturn function as Actions for the first frame and the calls to the function as Actions for the buttons. These calls are in the on(release) action. You can experiment using other button actions, such as on(press) or on(rollover) or on(rollout).

There are two sorts of mistakes that students often make in this application when adding the animation. The first is to add the goToAndPlay statements outside the appropriate if-true clauses. The following fragment of code

if (computer=="rock" && player=="scissors") {

result= "Computer wins: rock breaks scissors"; }

gotoAndPlay("Rockbreaks");

if (computer=="paper" && player=="rock") {

will not cause the desired action. The goToAndPlay statement is outside of the if-true clause and will ALWAYS be executed. This will take control to the Rockbreaks frame in all cases.

This is a reason to not do what was shown here and always write an if clause with the closing bracket on its own line.

if (condition) {

statements

}

Adding a statement correctly is now easier to do. This practice applies to other constructs and other languages making use of brackets.

A second common mistake is to bring instances of the rock, paper, or scissors buttons to the Stage for the animation and not copies of graphics from the button. You need to double-click on the button as listed in the Library to make it appear on the screen. You will see the first frame, the UP frame. Select (using the arrow selection tool) and copy (using the Edit pull-down menu). Then return to the main movie (indicated as Scene 1). Find the appropriate frame and paste the graphics.

TIP: The specific problem of using a button instead of graphics from the button applies just to Flash, but the more general one, of distinguishing between a thing and parts of a thing applies to many situations in many programming languages. For example, there are objects and the internal data, also called properties or attributes, which are a part of the objects. In Flash and other programming languages, there are text fields that have names and have contents.

Chapter Summary and Reflection

This chapter continues the fundamental concept of procedure with a focus on parameters. Like the coin toss in a previous chapter, the motivating example of the rock-paper-scissors game required the use of pseudo-random processing and the necessity to encode choices as numbers. The application featured use of a static array (options), an array that does not change. Remember: the encoding of the rock, paper, and scissors options as 0, 1 and 2 is arbitrary.

The game was implemented first in a text only version and then with animation. This iterative process is typical of work in computing.

As indicated above, there are different ways to program this application. It was mentioned that a switch statement would be more efficient than the sequence of ifs because in the sequence, the values are tested and re-tested even after the result is determined. Yet another possibility is to put the coding in the button action and not use a function such as computerturn at all. The coding would be more efficient, that is, faster, because there would not be the overhead of a function call and only 3 checks would need to be done in each case. It must be admitted one motivation for using the computerturn function was to illustrate function calls with parameters. If you were not driven by having to illustrate this concept, it may still make sense to use a function and, by doing so, centralize, put in one place, the rules of the game. This would make changing the code much easier.

The interface could use some redesign. The Exercises section includes some suggestions.

If you were a programmer

Repeating what has already been suggested before, if you were a programmer working in an organization, in most cases, you would not be responsible for all the programming in the project. You may be given the descriptions of procedures that you would use, including the prototype or header statements. Your part of the project would include code with calls to procedures built by other people, often at other times. Program re-use is a slogan that is promoted as an answer to what is called the software problem. The software problem refers to the fact that software, that is, programming, generally takes a long time to produce, tends to cost more than anticipated, and often contains errors (bugs). Making use of procedures already written is an example of program re-use.

Though this is a game, and a simulation of a child's playground game at that, it does provide a challenge to design. When you tackle the exercises to re-design the game, you need to think about your end-user, the player. When you design an interface for another type of application, you need to plan what buttons would be intuitive to your users and what display would be meaningful.

What's next

The applications so far consisted of games with single moves by the player. The next chapter will address the issues of a more complicated application state involving persistent data and more complex testing of conditions. You will see one example in HTML with JavaScript and another in Java. The rock-paper-scissors example in this chapter and the directions in Chapter 1 made use of cel or frame-by-frame animation. In Chapter 10, you will learn about animation produced by computation. All of the applications will make use of functions and parameters.

Exercises

1. Describe the role of parameters in programming procedures.

2. Define and contrast 'call by value' and 'call by reference'.

3. True or False: JavaScript uses primarily 'call by value'.

4. Create a Java style procedure header for a procedure named add_in_tax, with one parameter, named total, of datatype float. The procedure returns a float value.

5. Create a JavaScript style procedure header for a procedure (function) similar to the one in #4. Hint: this is easier than it appears.

6. Create a Java style procedure header for a procedure named fix_up, with 2 parameters, each of type int that does not return a value; that is, it is invoked strictly for its side effects.

7. Create a JavaScript style procedure header for a function fix_up similar to that in #6.

Projects

8. Do research on-line to find out the format for defining procedures in the languages c, c++, and c#.

9. Change the application to give the results in the style: "You win. You played rock and the computer played scissors and rock breaks scissors."

10. Change the application to use less text (not more). Perhaps include pictures of what the player played and what the computer played in a fixed part of the stage. One way to do this is to create movie clips of each of the 3 symbols, bring instances to the Stage, name them but put them off-stage, use duplicateMovieClip to create copies and position them on-stage at set positions.

11. As part of a re-design of the interface, you also may create different animated sequences for the computer winning versus the player winning. One idea is to make the player's choices on the left side and animated sequences in which the player wins start from left to right and those in which the computer wins go from right to left.

12. Look over the previous chapters and add scoring to the application.

13. Build an application in which a customer selects clothes by clicking on one of several graphical buttons. The program computes and displays the costs.

14. Build an application in which a student clicks on graphical buttons showing grades (A, A-, B+, etc.) and the program computes and displays a running average.

15. Using functions and parameters, building on what you learned in the Directions example in the first chapter, and this chapter, build a make-your-own adventure story in which the reader makes choice of how to proceed.

For teachers only: Tips for Teachers

The purpose of the general sections of this chapter is to provide a practical description of function definition mechanics. This includes how a compiler would make use of the information in translating a program.

One approach for teaching the lessons associated with this chapter and rock-paper-scissors is to prepare or assign the text version first and, only when it is completed, assign the animated version. This is how most professionals would do the project and demonstrates working in stages. You need to model working in stages for students because they want to jump to the final project and tend to view any other approach as slowing them down.

A slightly amended way is to demonstrate the text-only version, explaining the logic, and then demonstrate the addition of one of the three animated sequences. I then allow students to copy (download from my web site) this partially complete version with the assignment to modify the code and add the frames for the other two animated sequences. This provides instruction in programming and in Flash drawing and provides opportunities for the more graphically talented students to shine and the other students to produce adequate work since all they need to do is copy-and-paste from my [crude] drawings. It is important to have a successful project early on and this one always works for me.

Flash provides built-in (on-line) lessons and tutorials, so I suggest that students try them. I also model doing simple drawing and encourage students to demonstrate drawing techniques for each other.

Representation of application features, especially when it is arbitrary, is a challenging aspect of programming for most students. This chapter, with the association of 0 to rock, 1 to paper and 2 to scissors, is intended as a start to help new programmers distinguish between what is forced by the application and what is up to them.

-----------------------

[1] The examples of Java are provided to show you how a strongly-typed language specifies parameters. You can choose to skip these sections to focus on JavaScript and ActionScript. A small but complete Java example is in Chapter 7.

[2] This is not the first element, since arrays are indexed starting from zero, not one.

[3] Putting code in different places was the standard practice in Flash. An alternative way is to specify event handling procedurally in frame code. This would be done by giving the button an instance name, say rockbtn, and including a statement: rockbtn.onRelease = function () {computerturn(“rock”);}

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download