ࡱ> 5@ bjbj22 "XXѕ6666 2n$)$R ,u",A$n ؂H6(f84 W0Tp=>{,$===,,YR`PR`Chapter 7: Application state This chapter will continue the study of encoding the rules of an application, such as the business logic or the rules of a game, into the programming. After studying this chapter, you will understand the role of state data, information that must stay accessible (persist) independent of events and function calls, and how to use global variables or object data to hold state data understand how to use a type of conditional statement called the switch or case statement and the variations in how it is defined in different languages have computed the probability and odds of winning and losing in a game of chance have gained practice in the use of arrays for holding information organized by index values have acquired experience using global variables, array variables and conditional logic in JavaScript and img, form and input elements in HTML and examined a simplified version of the application built in Java. Motivating Examples The examples in this chapter are implementations of the dice game called crap or craps. This is the game celebrated in the musical Guys and Dolls. It is an excellent vehicle for demonstrated many programming concepts so it is hoped that the readers will not find it offensive. The rules of the game are as follows: First throw: Player throws the dice. The sum of the faces is computed. If it is 7 or 11, the player wins; if it is 2, 3 or 12, the player loses. For anything else, the value becomes 'the point' and play continues. Follow-up throw: Player throws the dice. The sum of the faces is computed. If it is the same as 'the point', the player wins. If it is 7, the player loses. If it is anything else, play continues for another follow-up throw. Note that the only thing that matters is the sum of the dice. A throw of 4 and 2 and a throw of 3 and 3 both yield the same result.  REF _Ref88536663 \h Figure 1 shows the logic of play in flow chart format.  SHAPE \* MERGEFORMAT  Figure  SEQ Figure \* ARABIC 1. Flow chart for logic in craps game. This game requires data that persists to hold the state of the game: is it a first throw or a follow-up throw situation and, if it is a follow-up throw, what is the value of 'the point'. The HTML with JavaScript implementation will begin with the screen shown in  REF _Ref88565110 \h Figure 2.  Figure  SEQ Figure \* ARABIC 2. Starting screen in HTML/JavaScript craps game.  REF _Ref88565204 \h Figure 3 shows the screen after a throw of 9, a value that does not result in an immediate win or loss. The status message indicates this by telling the player to throw again.  Figure  SEQ Figure \* ARABIC 3. Snapshot of screen after a throw of 9. After a couple of more throws, the game was lost when a 7 was thrown.  Figure  SEQ Figure \* ARABIC 4. Snapshot of loss on a follow-up throw. The Java implementation described here uses the command line interface. It does not use buttons and graphics. The application produces a whole game. Better implementations are possible but would require much more time on the supporting Java classes.  REF _Ref88566281 \h Figure 5 shows a game.  Figure  SEQ Figure \* ARABIC 5. Screen of command line interface for Java craps game. The critical features required by this application include pseudo-random processing to generate the values of two 'thrown' dice a mechanism for maintaining the state of the game, namely if it is a first throw or a follow-up throw, and, in the case of a follow-up throw, the point value techniques for displaying results back to the player: the HTML and JavaScript version will have pictures of die faces and the Java version will have text. Introduction to concepts Building applications often requires representing what is called the state of the application. The state starts off in a defined way when the application begins and then is subject to changes based on user actions and other circumstances. REAL-LIFE NOTES: All games have game states. In a game such as chess, the state of the game is the position of the pieces on the board, an indication of whose turn it is, and, in competitive chess, the time remaining on each player's clock. Chess and similar games are games of perfect knowledge: everyone knows the state. In card games, the state of the game includes what is in each player's hand. This knowledge is not shared. The concept of application state is not limited to games. If you make an order in an on-line store or at an ATM machine, the process involves well-defined states. Think about this when next ordering on-line or making an ATM transaction. END OF REAL-LIFE NOTES What maintaining the state of the game means operationally is that certain variables are initialized, that is, set to the defined initial values these variables change based on the rules of the games the variables must persist and be accessible to procedures, including event handlers, and retain values if and when procedures complete. Some programming languages supply this facility through what are called global variables. These are variables defined outside of any procedure. The opposite of global variables are local variables: variables defined inside of procedures. These local variables are not accessible and, in fact, do not even exist after the procedure completes. WARNING: Using global variables is viewed as a sign of poor programming in many situations, most especially when using languages supporting objects, to be described next. Other programming languages use the approach of objects. Member variables defined as part of the objects hold the permanent data for each object. There are rules governing access to the member variables. For example, some are accessible only in code in methods of the object. Logic involving state variables frequently makes use of conditional statements. Informally, the logic is: if (application in state S) do this The if statement already demonstrated can handle this. However, most programming languages have another construct that may express the logic in certain situations in a way that is simpler to code and to read. This type of statement is called a switch or a case statement. Unfortunately, there are significant variations in the definition of this statement in different programming languages that go beyond superficial aspects such as the statement name. Three varieties will be described. EXAMPLES: The implementation of craps in HTML with JavaScript will make use of an array to hold the image files corresponding to pictures representing die faces. This is a typical use of arrays. The Java example will demonstrate a complete Java application, making use of objects. Description: Global variables Global variables are variables with a declaration statement outside of any procedures. The term can be used in a relative sense as well, as in "the variable V is defined globally to the procedure P", meaning defined outside of P. Some languages, though none that are described here, allow for procedures to be defined within procedures so a variable may be global to an internal procedure, but local to the contained procedure. The statements accessing and setting the variable, with the exception of initialization, probably will be inside of procedures. The declaration statement outside of the procedures lets the language processor 'know' to keep the variable around. The general structure is declaration of variable g procedure definition p1 { . set or use g } procedure definition p2 . set or use g } Making the variable g global means that it is the same variable in all the procedures. Now, if someone, perhaps you, perhaps not, has written a procedure pn with an internal declaration of a variable named g, then the code in pn will refer to that local g. You may think this is unlikely, but it could happen. This is a reason why the members of a team working on an application must confer with each other. It also is a justification for the object-oriented style of programming to be described next. EXAMPLE: The HTML with JavaScript version of the craps game will make use of one global variable to indicate if the current throw is a first throw or a follow-up throw and another global variable to store the point value. Description: Objects An object is an entity that holds data and procedures together. Formally, programmers define classes. A class definition contains specification of variables and procedures. The procedures is called methods. Methods can be utility methods, only called by other methods of the class and methods can be public, that is, callable by other code. TECHNICAL NOTE: Careful planning in the design of classes can mean that the language compiler catches errors at compile time that otherwise would be much more challenging to detect at run-time. One critical method is one defined to perform actions when an object, also called object instance, is first created. This method is called the constructor. The actions could include initializing the member variables and modifying class variables. Classes are ways to extend the language as defined by the developers. The developers knew people would need integers and floating point numbers and Strings. They could not know that people would want a class that set up a game of craps. Some methods are called class methods and some variables, class variables. These operate independent of any specific object instance. You already have seen the use of these in Math.floor() and Math.random(). You can imagine that a programming language would supply Math.PI, a class constant. Class variables and methods are indicated in Java code using the modifier static. If the application calls for state data, one approach is to define a class with definitions of variables for holding the data that must be kept and then have code to create an instance of the class. The variables can be designated as private: only accessible by code in the methods defined for the class or public: accessible elsewhere. There are other so-called modifiers. If a variable is designated as private, the programmer can choose to define a public method that shows its value. You may now be wondering how to begin. Java and other object-oriented languages have rules for defining a main method and this method is what is invoked to start the application. EXAMPLE: the Java version of the craps game will use an object of a class called Game to hold the state information. Member variables for this class include firstturn and point. Description: Switch style of conditional statement The general structure of a switch or case statement is header indicating the expression to be examined case 1 definition: code for case 1 case 2 definition: code for case 2 etc. optional specification of a default case: code for default Across the different languages, the variations that the programmer needs to know concern limitations on the definition of the cases and whether the flow of execution goes to the next case or jumps out of the statement. In JavaScript and ActionScript, the statement has the following structure switch (expression) { case expression1: code for case case expression2: code for case default: code for default case } The expression following the keyword switch is evaluated. Flow of execution goes to the first case with expression equal to expression. Flow continues, then, to the next line. If that is not what is wanted, the programmer must use the statement: break; to jump out of the switch statement. The implementation of the logic for determining the days in a month (using 3 letter abbreviations) would be: switch (month) { case "Sep": case "Apr": case: "Jun": case: "Nov": alert("This month has 30 days"); break; case "Feb" alert("This month has 28 or 29 days"); break; default: alert("This month has 31 days"); } This example shows the advantages of having one case flow into another and also the use of the break command to leave the switch statement. The Java structure is the same with one critical difference. The cases must be defined by constants. This difference will be demonstrated by the use of a switch statement for the follow-on turn in the JavaScript implementation but an if statement in the Java implementation. The following is an implementation of the days-of-the-month example using the facility for giving names to constants. It assumes an encoding of numbers for months. There are 12 statements such as the following: final int JAN = 1; final int FEB = 2; Note that there is a convention that the names of constants should be all capital letters. The variable month_num will be a number from 1 to 12. switch (month_num) { case SEP: case APR: case: JUN: case: NOV: System.out.println("This month has 30 days"); break; case FEB: System.out.println("This month has 28 or 29 days"); break; default: System.out.println("This month has 31 days"); } The System.out.println is the way to print a line. Formally, System is a class, out is a class variable of type PrintStream and println is a method of the PrintStream object. OTHER LANGUAGES NOTES: Visual Basic and vb.net have a switch type of statement but with differences. This construct allows multiple expressions, including conditions, to define a case. For example, CASE IS >50: is allowable. After each case is executed, flow of execution jumps out of the structure. The days-of-the-month example is: SELECT CASE (month) CASE "Sep", "Apr", "Jun", "Nov": print "This month has 30 days." CASE "Feb": print "This month has 28 or 29 days." CASE ELSE: print "This month has 31 days." END SELECT The VB format uses line breaks for bracketing. Only the code following each case definition is executed, so there is no need for a break statement. The language for transforming eXtended Markup Language (XML) documents, eXtended Stylesheet Language (XSL) has a form of switch statement available using , and elements. The intent in telling you about these different languages is to impress the point that the switch or case construct is widely available, but that there are significant features you must understand in order to use the facility in the particular language. END OF OTHER LANGUAGES NOTES EXAMPLES: the logic of the craps game in both versions will be programmed using a combination of if and switch statements. Description: Array use The HTML with JavaScript example will display images of the faces of dice by setting up an array of HTML image objects as elements of the array. A subtle point here is that it is up to the builder of the application to make sure that the file names assigned to the src attributes of the images hold pictures corresponding to the appropriate value. The image file for the die face with 2 dots must show a die face with 2 dots! EXAMPLE: For the HTML with JavaScript implementation, the nth element of the array of images needs to refer to an image file that shows a die face with n+1 dots. Note that we could ignore the 0th element and start with 1, but we chose not to do this. The pseudo-random calculation will produce a whole number from 0 to 5 and this will be used as an index to reference an element of the array. The element of the array will be an Image that has an image file with 1 to 6 dots. Reading checks Describe what is meant by the state-of-the-game in general. Describe what is meant by the state-of-the-game in a game of your choosing, such as Texas Hold-Em or another variant of poker. What is the difference between global variables and local variables? What is a class and what is an object of that class? Describe the workings of a switch statement. Application This section reviews the use of global variables and arrays in previous chapters and then goes on to present two versions of the dice game called craps. Review of previous examples The rock-paper-scissors example in Chapter 6 made use of global variables and arrays in the options variable var options=new Array(); options[0] = "rock"; options[1] = "paper"; options[2] = "scissors"; It is a subtle point that this is not state data but rather information required for the implementation. The values in this array variable do not change. In contrast, the coin toss example in Chapter 5 that kept track of the counts of heads and tails did make use of global variables, the values did change, and thus can be viewed as state-of-the-game information. In Chapter 4, the version of the Find Daniel game that enforced a time limit made use of a variable, tid, for use to turn off the timing event in the situation when the player clicked on the correct area of the photograph. As indicated in that chapter, this needed to be a global variable so that it could be accessed in code in different places. Application: the game of craps It is possible to determine the probability or odds of winning or losing at each stage. Probability and odds are different ways of expressing chances. The probability of an event is the chances of the event happening divided by the chances of anything happening. The odds for an event are the chances of it happening divided by the chances of it NOT happening. There are 6 times 6 different combinations of values for each throw of the dice. The following table gives the number of combinations for each value of throw, that is, sum of the dice: ValueNumber of combinations2132435465768594103112121 Please make sure you understand the entries in the table. For example, the value 7 occurs when the dice are 3 and 4 4 and 3 2 and 5 5 and 2 1 and 6 6 and 1 The symmetry of the table and the fact that the combinations do add up to 36 provide some confirmation that the table entries are correct. So what does this mean for the game? It means that the probability of winning on a first throw are: 6 + 2 chances out of 36 for a value of 2/9. odds of winning on a first throw are: (6+2) / (28) yielding a value of 2/7. The probability of losing are 4 out of 36 (1/9th). The odds 'against you' are 1/8. The chances of winning on any specific follow-up throw varies depending on the point value. The point values of 6 or 8 are the best; each of these has a probability of 5/36. The chance of losing on a follow-up throw is greater: 6/36. Plan of attack for both implementations The outline of the HTML with JavaScript implementation is section