Development environment
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.
Figure 1 shows the logic of play in flow chart format.
[pic]
Figure 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 Figure 2.
[pic]
Figure 2. Starting screen in HTML/JavaScript craps game.
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.
[pic]
Figure 3. Snapshot of screen after a throw of 9.
After a couple of more throws, the game was lost when a 7 was thrown.
[pic]
Figure 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. Figure 5 shows a game.
[pic]
Figure 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 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
1. Describe what is meant by the state-of-the-game in general.
2. 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.
3. What is the difference between global variables and local variables?
4. What is a class and what is an object of that class?
5. 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:
|Value |Number of combinations |
|2 |1 |
|3 |2 |
|4 |3 |
|5 |4 |
|6 |5 |
|7 |6 |
|8 |5 |
|9 |4 |
|10 |3 |
|11 |2 |
|12 |1 |
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
element
faces array holding image files
global variable firstturn
global variable pointvalue
function definition for dthrow.
It will include if and switch statements
section
elements for each die
element to invoke dthrow
element to hold elements for display
This book will not cover how to set up a Java development environment. At a minimum, you need to download from the Web the Java classes. It is possible to use TextPad to create and test applications, but other development environments are available. The two files required for this Java implementation of craps will be shown in their entirety. Java source files define classes. One file defines the Game class. It is of type .java.
In outline, it is
class Game
private data for the first turn status and the point value
public Game method (the constructor)
public inplay method (used to see if game is still in process)
public play method (the rough equivalent of dthow)
contains ifs and switch statement
A member variable of the instance keeps track of whether the game is in first turn status or not. There are three methods. The Game method is the one the initializes the instance variables. The play method outputs a line with the results: what value was thrown and, as appropriate, report on winning or losing. The play method makes use of if statements and a switch statement. The inplay method returns true if the game is still in process and false otherwise.
The other file, with the main method required for Java applications, is called Crapstest.java. After creating an object instance of class Game, it keeps invoking the play method of the instance. Its outline is
class Crapstest
standard main method
create Game instance
loop until back in first turn status (use inplay method)
call play method
The two files must each be compiled successfully with no syntax errors. Then the Crapstest class is run.
Use of concepts in implementation
Now it is time to go into detail on the implementations for the two versions of the craps game.
HTML with JavaScript
For the HTML with JavaScript implementation, it is assumed that by this time you know the basic organization of an HTML document. At some point, you will need to create image files showing die faces: 6 images, showing 1 dot, 2 dots, and so on. Following the outline given in the previous section, the first critical step is to create the faces array. This could be an array of strings. However, a slightly more effective approach is to create HTML image objects of a specified width and height and then set the src attributes to be the appropriate string value. The tactic here is make the 0th element correspond to the die face with 1 dot, the 1st element correspond to 2 dots, and so on. The following coding sets up the array.
var faces = new Array;
faces[0] = new Image(50,50);
faces[0].src = "dice1.gif";
faces[1] = new Image(50,50);
faces[1].src = "dice2.gif";
faces[2] = new Image(50,50);
faces[2].src = "dice3.gif";
faces[3] = new Image(50,50);
faces[3].src = "dice4.gif";
faces[4] = new Image(50,50);
faces[4].src = "dice5.gif";
faces[5] = new Image(50,50);
faces[5].src = "dice6.gif";
TECHNICAL NOTE: It turns out that the approach of using Image objects forces the browser to load the images at the start so there will not be delays later on.
The next step is to set up the two variables holding the state information. The one indicating first turn status requires a var statement with initialization. The variable that will hold the point value just needs a var statement.
var firstturn = true;
var pointvalue;
The definition of the function that does all the work follows with line by line explanation. Certain lines require you to know or have faith in the coding that will appear in the element. For example, you need to decide on the names of the images and the form elements. The point value will be displayed in the input element named point in the form element named f.
|function dthrow() { |function header |
|var choice; |will hold random choice (0 to |
| |5) |
|var die1v; |will hold one die value |
|var die2v; |will hold one die value |
|var sum; |will hold the sum |
|choice=Math.floor(Math.random()*6); |Acquire random value 0 to 5 |
|die1v = choice+1; |Increment to get the die value |
| |to use in sum |
|document.dieimagea.src=faces[choice].src; |Use choice to set one visible |
| |die image |
|choice=Math.floor(Math.random()*6); |Acquire (another) random value |
| |0 to 5 |
|die2v = choice+1; |Increment to get the die value |
| |to use in sum |
|document.dieimageb.src=faces[choice].src; |Use choice to set the other |
| |visible die image |
|sum = die1v + die2v; |Calculate (add up the values) |
| |to get value of throw |
|if (firstturn) { |Is this a first turn |
| document.f.point.value = ""; |Wipe out any point value |
| |information from a prior game |
| switch (sum) { |Start of switch based on sum |
| case 7: |If it is 7… |
| case 11: |… or 11 |
| document.f.status.value = "You win!"; |Indicate a win |
| break; |Break out of switch |
| case 2: |If it is a 2… |
| case 3: |… or a 3… |
| case 12: |….or a 12 |
| document.f.status.value = "You lose."; |Indicate a loss |
| break; |Break out of switch |
| default: |Anything else: |
| firstturn = false; |Change status |
| pointvalue = sum; |Save sum to be the point value |
| document.f.point.value = pointvalue; |Display the point value |
| document.f.status.value ="Throw again for your point."; |Display message to throw again |
| } |End switch |
|} |End if-true |
|else { |Start else. This is a |
| |follow-up situation |
| switch (sum) { |Start switch |
| case 7: |If 7 |
| document.f.status.value = "You lose."; |Indicate a loss |
| firstturn = true; |Reset firstturn back to true |
| break; |Break out of switch |
| case pointvalue: |If the value is pointvalue |
| document.f.status.value = "You win."; |Indicate a win |
| firstturn = true; |Reset firstturn back to true |
| } |End switch |
| } |End else clause |
|} |End dthrow function |
Notice that if a follow-up throw was something other than 7 or the point value, nothing needs to be done.
Following the outline given previously, the element contains two elements that each will have the src attribute modified to display the appropriate image.
The actual call to the dthrow function is accomplished by setting the onClick handler in an a tag.
Click to throw dice.
Lastly, elements in a element are used for display, that is, for output.
Status
Point value
If you build this or any other application, you do need to test it thoroughly. This means testing for each of the winning and the losing situations and also testing that the game can start again after a win or a loss.
Java
The Java version, as indicated previously, consists of two files. The file defining the class called Game starts with an import statement letting the compiler know to make use of a built-in java class called Random.
import java.util.Random;
The variables must be declared with datatypes. The one indicating first turn status will be Boolean, that is, true if it is a first turn and false otherwise. When a new game object instance is created, this is set to true. The variable holding the point value will have datatype int.
The statement by statement exposition follows.
|public class Game { |Prototype for a class definition |
| Random generator = new Random(); |Declare and create a variable called generator of|
| |type Random object. |
| private boolean firstturn; |Declare firstturn as a variable of type boolean. |
| |It can only be accessed by code in the class |
| private int point; |Declare point as a variable of type int. It can |
| |only be accessed by code in the class. |
| public Game() { |Constructor method. This sets up an object |
| |instance. |
| firstturn = true; |firstturn is set to true. |
| } |Close Game method |
| public boolean inplay() { |Method that returns a value of type Boolean. |
| return firstturn; |Returns the value of firstturn |
| } |Close inplay method |
| public void play () { |Method that plays a turn. It does not return |
| |anything. |
| int die1 = generator.nextInt(6)+1; |A local variable named die1 gets value calculated|
| |using generator. It is a random value 1 to 6. |
| int die2 = generator.nextInt(6)+1; |A local variable named die2 gets value calculated|
| |using generator. It is a random value 1 to 6. |
| int throwvalue; |Declare a variable named throwvalue. |
| throwvalue = die1 + die2; |Set throwvalue to be the sum. |
| System.out.println("You threw "+throwvalue); |Print it out on the command/run console. |
| if (firstturn) { |Is it a first turn? |
| switch (throwvalue) { |Start switch based on throwvalue |
| case 7: |If it is 7…. |
| case 11: |…or 11 |
| System.out.println("You won!"); |Print out message |
| break; |Break out of switch |
| case 2: |Is it a 2… |
| case 3: |… or a 3… |
| case 12: |… or a 12 |
| System.out.println("You lost!"); |Print out message |
| break; |Break out of switch |
| default: |Default case |
| point = throwvalue; |Store throwvalue in one of the object variables |
| |where it will persist. |
| firstturn = false; |Set firstturn to false. It is also one of the |
| |object variables and will persist |
| } |End switch |
| } |End if first throw clause |
| else { |Must be follow-up |
| if (throwvalue==point) { |Does throwvalue equal the point |
| System.out.println("You won!"); |Output message |
| firstturn = true; |Reset firstturn to true |
| } |End if-true clause |
| else if (throwvalue == 7) { |Check if throwvalue equals 7 |
| System.out.println("You lost!"); |Output message |
| firstturn = true; |Reset firstturn |
| } |End this if-true clause |
| } |End else clause |
| } |End play method |
|} |End Game class definition |
Notice that the Java version used one and not two switch statements. The follow-up situation was handled by another if test.
The second file creates and then uses the other class to implement this simple, command line craps in Java. It is a class definition for a class named CrapsTest. It has a single method, the main method, required for Java applications and always with the same prototype. The heart of the main method is a do/while loop. The body of this loop is always executed at least once. A test is made after the first and any subsequent iteration. In this case, the test will succeed for another iteration if the game is in follow-up mode. It will fail when the game is back in first turn status.
|public class CrapsTest { |Prototype of class CrapsTest |
| public static void main (String args[]) { |Standard prototype for main method, what is invoked |
| |from the command line. |
| Game myGame = new Game(); |Create a Game instance. |
| do { |Start do |
| myGame.play();} |Invoke play method (equivalent to throwing the dice) |
| while (!myGame.inplay()); |Check using inplay method. |
| } |Close do/while |
|} |Close CrapsTest class. |
Notice that this testing program does not really test if myGame can be started again. See the Exercises for a challenge.
Reading checks
1. What are the roles of the CrapsTest class and the Game class in the Java implementation?
2. Write the logic using if statements in place of the switch statements (in either JavaScript or Java). Compare the two versions.
What can go wrong
The HTML with JavaScript version does require that the image files representing the die faces be prepared in the image format referenced in the code, named to correspond with the names used in the code, and stored in the same folder as the HTML file. Alternatively, the image files can be in another folder and the appropriate reference used. For example,
A way to confirm this is to change the initial src value of the two img tags systematically to check for each of the 6 files.
Both the HTML and the Java versions have bracketing, that is, { and } symbols, to define the clauses of if statements and switch statements. The JavaScript console in the Mozilla or Netscape browsers will be helpful sometimes, but for the most part, you are on your own in HTML and JavaScript. In the Java situation, the compiler will indicate a problem if the symbols do not occur in pairs. The compiler will not necessarily detect a bracket in the wrong place. A good practice is to type in the opening bracket, skip a line and type in a closing bracket and then go back and fill in what goes in-between.
A deeper issue is to make sure you really understand the rules of the game of craps. Then be patient when testing. Your application can be working perfectly and it can still take many turns before winning or losing.
Chapter Summary and Reflection
This chapter described ways to maintain information on the state of an application. The global variable feature demonstrated in the JavaScript application can be compared with the object data feature demonstrated in the Java application.
The variables in the JavaScript example were accessible everywhere. The variables in the Game instance were defined as private, meaning they were not accessible outside code in the Game methods. This meant that the inplay method was required. Why not simply make firstturn public and not private? The answer is that this approach ensures that firstturn and point will be handled properly. If firstturn is set to false, then point needs to have a value.
The fact that the users of the class do not need to know the details of the implementation is called information hiding. In this context 'users' refers to programmers building programs using the class. The information hiding feature of object oriented programming gives developers the power to change details of the implementation without needing to change all the other programs. The issue is not keeping secrets but making it unnecessary for review all the code for all changes.
At this point, you may say that there is exactly one use, the file CrapsTest, and, more importantly, you are the author of both CrapsTest and Game, so nothing is hidden! Our answer is that the benefits of information hiding and object orientation in general really occurs in large applications involving many programmers and, also, long maintenance cycles. However, even in these tiny textbook examples, the object orientation, along with strong typing, can mean that compiler catches errors that would take longer to catch otherwise.
The Java implementation of a Game class means that multiple games can be created by creating objects of the class. Each such object would have its own set of data. This would support a multi-user game. A Game class could make use of two die objects of a Die class. A throw method of the Die class could do the display work.
TECHNICAL NOTE: Do not judge all of Java by this pure text example. Java has many classes supporting graphical applications. However, it is the case the many applications involving Java are built using combinations of programming languages and the interface code is not done in Java. For example, e-commerce applications may implement the customer interface using HTML and JavaScript. The code would specify implementation a program written in Java running on the server. This program performs calculations and makes calls to a database engine using the Structured Query Language. The results of these operations are used by the Java program to generate a new HTML page to display to the customer.
If you were a programmer
In industrial applications involving events that do not happen according to a fixed schedule or pattern, testing is a challenge. There are many such applications. In addition to games, consider networks of ATM machines; control of the steering, braking and gear shifting in cars; and operating banks of elevators. The first stages of testing may consist of specifying occurrences and only later make use of facilities such as random number generators to simulate what would happen in the real world. Building the testing system is itself a considerable undertaking.
What's next
The next chapter, Chapter 8, demonstrates more use of arrays, including another example of parallel structures and for-loops. The featured example is a JavaScript version of the game of Memory, also known as concentration. Chapter 9 describes the use of programmer defined objects in ActionScript. The featured example is again Memory, but this time implemented in Flash with ActionScript.
Exercises
1. Describe the difference between global and local variables.
2. True or false: these JavaScript examples implement images and text differently.
3. What is the code for changing the image displayed using the HTML
to "car.gif"?
4. What is the code for changing the text displayed using the HTML
to "ALL"?
5. Describe the private and public modifier in Java.
6. What does void mean in a definition of a Java method?
Projects
7. Using features of earlier chapters, enhance the game to include betting. Use a form for inputting an initial stake (amount of money) and an amount to bet on each game.
8. Do research into casino craps table betting and incorporate your findings into an application.
9. If you have the facility to build and run Java programs, enhance the CrapsTest program to repeat the game, thereby testing how the Game class is defined.
10. Using features of earlier chapters, enhance the HTML/JavaScript game to keep score: games won and games lost.
11. Modify the CrapsTest program to keep playing and displaying the results until 3 games have been won.
12. Write down the names and email addresses of three people. Write a JavaScript switch statement based on a value name that will set the variable email to the email for the person indicated by the value of name. If the value of name is not on your list, set email to the empty string.
13. If you have access to , do the previous question in this language.
14. This is a big challenge: implement blackjack (also known as 21). The phases of your implementation would include: the deck of cards, drawing or dealing cards to make a hand, computing the possible values of the hand (with face cards valued at 10 and the ace valued at 1 or 11), shuffling the deck, the two person game (dealer plus player), official strategy for the dealer (dealer gets a new card if and only if the total is under 16).
For teachers only: Tips for Teachers
Students like this application. However, you do need to make sure they understand the logic before starting implementation. A throw of 7 wins on a first throw and loses on a follow-up throw and some students do not grasp this fact immediately.
Some students will test the program until they win, as opposed to testing for all situations. This is a good opportunity to remind them that they are the game application builders, not the players. Remind them that this advice holds for all applications, not just games: they are the builders preparing applications for customers or clients or end-users with some other title. They need to approach the application interface with the end-users in mind and test for all possibilities.
If the course is to serve as a pre-requisite for a course using Java, you may opt for a fairly simple development environment or even demonstrate the Java example without requiring student work. Alternatively, you may choose to skip over the Java and 'other languages' sections entirely. These sections to serve to show students that common features do exist across different languages.
-----------------------
No
Yes
Player loses!
V = 7
No
Yes
Player wins!
V = P
Follow-up throw: Player throws dice for a value of V.
Player loses!
Yes
No
P=2,3 or 12
No
Yes
Player wins!
P = 7 or 11
First throw: Player throws dice for a value P.
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- work environment descriptions
- job description work environment examples
- ideal work environment answer
- articles about the environment 2019
- environment articles
- job description work environment statement
- job descriptions work environment samples
- samples of work environment descriptions
- work environment for job description
- office work environment description
- environment projects for students
- maryland department of the environment mde