Java Basics for Game Programming

Lecture #1 Java Basics for Game Programming Java Basics The source code of a generic Java application consists of three primary components: the cla...
Author: Eric Anderson
0 downloads 1 Views 1MB Size
Lecture #1

Java Basics for Game Programming

Java Basics

The source code of a generic Java application consists of three primary components: the class definition, a main() function, and the statements that define behaviors of the application. The following is a simple code that creates an application for the command-line interface (not a Windows desktop application). It demonstrates how these three basic components are used to build a Java application. A Java source code must be compiled by the compiler ( javac.exe) before being execution in the Java Virtual Machine (JVM). The line numbers, 01, 02, …, and 11, are not part of the source code. They are used by the instructor to indicate the sequence of statements. It is necessary to note that all Java source files must have extentsion “.java”. 01 02 03 04 05 06 07 08 09 10 11

// Filename: MyJava.java import javax.swing.JOptionPane; public class MyJava { public static void main(String args[]) { JOptionPane.showMessageDialog(null, "Java Game"); System.exit(0); // terminate the app immediately } }

Java has a very special convention that needs programmers’ attention. The “identifier” (name of the file) of the Java source file must be exactly the same as the identifier of the the class that has the main() function. In the above example, the identifier of the class is “MyJava”; therefore, the identifier of the source file must be “MyJava.java”, where “.java” is the file extension. By the way, a java source file can contain one or more classes, yet only one can contain the “main” function. In Java, the main function is the entry point of the program which is called at program startup to determine how to initialize the entire program. The output is a GUI dialog box as shown below.

The first line (line led by 01) is a “comment” and is used to provide reference to the programmer only. In terms of programming, comments are the placing of human readable descriptions inside a computer programs detailing what the Code is doing. Comments are ignored by the compiler and have no effect on the program but are useful to other programmers as coding references. // Filename: MyJava.java

The second line (02) “imports” the javax.swing.JOptionPane class which provides tools to create simple dialog box as GUI applications. In Java, the “import” keyword is used to access tools provided by Java (particularly classes and interfaces) and make their members available and accessible to the current source code, without specifying fully qualified package names. The above code uses the showMessageDialog() method to display a string in a message dialog box. import javax.swing.JOptionPane;

1 Java Game Programming - Penn P. Wu, PhD

The program begins with the class definition statement. A “class”, in any generic Java program, is a container of specification that describes how the Java program would be executed. A class is a block code enclosed by a pair of “{“ and “}” signs. A Java source file may contains two or more classes; however, only one of them is the primary class (the one that has a main() function), while others are supportive classes. The following illustrates the basic form of a class definition in Java. AccessModifier class Name { statements }

The keyword class begins the class definition for a class followed by the identifier (name) of the class. The statements (Java code) for each class reside between the opening and closing curly braces. The identifier (name) of class must be the exactly same as the name of source file. For example, if the class name is “MyJava”, the source file must be named “MyJava.java”. Java has three access modifiers: public, private, and protected. They control access to a member of a given class. The private acsess is most restricted, it allows only the class objects in which it is declared can access it. The protected access is typically used for a super-class to allow readonly access from an object of sub-class. The public access does not enforce any restriction. By the way, public is the default; therefore, the following are technically the same code. Specify to use public

Defaulted to use public

public class MyJava { }

class MyJava { }

Each Java program must have a main() function, which is the starting point of the program, meaning it is where the execution of entire application starts. This main() function typically describes how to subsequently execute all the other codes of the Java program. It is a linguistic requirement to declare the main() function as public in Java; therefore, JVM can easily access and execute it. In the case that a Java program does not contain at least one main() function, the JVM will throw a NoSuchMethodException:main message if it does not find the main() function of in any class of a given Java program. public static void main(String[] args){ ..... }

The main() function typically takes a single argument which is an array of elements of type String. The name of this array is “args”. This array is a communication mechanism through which the runtime system can pass information from the console (or the JVM) to the application. The three keywords in the above statement: public, static, and void. The keyword “public” is one of the three basic access modifiers in Java: private, protected, and public. Any method or variable declared as public can be accessed from objects outside of the class. By setting the main() function to public, JVM can easily access and execute it. The main() function in Java is declared as static; therefore, it can be invoked by the runtime engine without having to instantiate an instance of the parent class. According to Java API document, the main() function is better to have a void return type because a Java program is excuted in JVM and does not directly interact with the operating system. The System.exit(0) statement is optional, but useful. It forces the JVM to terminate the program immediately. With it, JVM can decide when and how it should terminate a program. Most of the Java programs presented in this course will elide this statement. Many books use console codes to teach Java programming. The following is the console version 2 Java Game Programming - Penn P. Wu, PhD

of the above code. It is necessary to note that, throughout this course, most sample codes are written as GUI (graphical user interface) application, not console applications. public class MyJava { public static void main(String args[]) { System.out.println("Welcome to Java Game Programming!"); System.exit(0); // terminate the app immediately } }

The following statement uses the println() method of the System class from the core library to output a string literal, the “Welcome to Java Game Programming!” message, to standard output. System.out.println("Welcome to Java Game Programming!");

Another method to display output on the console screen is the print() method. The difference between print() and println() method is that println() adds a new line to the end of message while print() does not insert a new line. These two methods are designed for console environment, this is probably the only lecture for students to use them throughout this course. System.out.print("Welcome to Java Game Programming!");

The above “MyJava.class” byte code constitutes an individual Java program; however, it is a console program. The term “console program” means that its output will only be display in a command-line interface, such as Microsoft Windows’ Command Prompt, the DOS Prompt, or the Linux terminal. Only GUI-based application can display output in a Window form (or similar GUI interfaces) in a Windows desktop. The following compares a console program with an GUI program. They both display a message “Java Game”. Console

GUI

C:\User>java MyJava Welcome to Java Game Programming!

C:\User>java MyJava

It is probably more enjoyable to write GUI-based Java game applications compared to console applications. Througout this course, the instructor will only use GUI codes as demonstrations to guide students to create Java game codes. Java GUI application can run either as stand-alone or as applets. Two later lectures will discuss how to create standalone- and applet-based Java games in details. The following is the GUI-version. import javax.swing.JOptionPane; public class MyJava { public static void main(String args[]) { JOptionPane.showMessageDialog(null, "Welecome to Java Game Programming!"); } }

The above example is very simple GUI application, which only uses a generic dialog box to display the results. Starting from the next section, the instructor will gradually gear towards 3 Java Game Programming - Penn P. Wu, PhD

more advanced GUI applications. In addition to the javax.swing.JOptionPane class, GUI components such as JLabel will be used to display the output. The following illustrates how to declare and create an empty instance, named “label1”, of the javax.swing.JLabel class. An “empty” instance means it does not have any default content. JLabel label1 = new JLabel();

In Java, the syntax to declare a GUI component is: GUIClass objectID;

The following is the syntax to create an instance of the GUI component, where “new” is a keyword. The actual creation of an instance is done by the constructor. A “constructor” is a special kind of class method which is only used to create an instance of a class. A class constructor typically has the same identifier as the class, but followed by a pair of parentheses. The constructor of the JLabel class, for example, is JLabel(). objectID = new GUIClass();

Programmers frequently combine the declaration and instantiation (creating an instance) into one single-line statement, as shown below. GUIClass objectID = new GUIClass();

Many classes of GUI components provide options of constructors. The following lists three popular forms of JLabel() constructor. They are used frequently in this course. By the way, another frequently used GUI component is JButton. Later sections will discuss how to use JButton. Options JLabel() JLabel(string) JLabel(image)

Description Creates a JLabel instance with no content (and no image). Creates a JLabel instance with the specified text. Creates a JLabel instance with the specified image.

A JLabel object can display either text, an image, or both. However, a label does not react to input events. Interestingly, JLable does not support new line “\n”. Instead, it requires the use of HTML tags to break lines. In the following, the strings are surrounded with .. and break the lines with
. The following is the GUI version of the above console code. It use a JLabel to display a multiple-line text within the showMessageDialog window. import javax.swing.JOptionPane; import javax.swing.JLabel; public class MyJava { public static void main(String args[]) { String str = ""; str += "This is an underlined line.
"; str += "This is an italicized line.
"; str += "This is a striked out line.
"; str += ""; JLabel label1 = new JLabel(str); JOptionPane.showMessageDialog( null, label1 ); }

4 Java Game Programming - Penn P. Wu, PhD

}

Conents in a JLabel can be formatted using HTML tags, such as for underline, for itacic, and for striked-out. A sample ouput looks:

Java Compiler, and using Java virtual machine to execute Java games

Java source codes must be named with an extension “.java” such as MyJava.java. A source file is where the programmer writes and saves the game codes. The Java compiler (javac.exe), available for downloading at Oracle’s web site (http://www.oracle.com), is what a Java programmer needs to use to compile the source code into Java byte codes (object codes). In Java, a bytecode is the computer object code that is processed by the Java virtual machine. The Java virtual machine then serves as the intermediary between the Java program and the hardware processor. The syntax to compile a source code to a byte code is: javac FileName.java

The following illustrates how to compile a source file named “MyJava.java” in a Windows Command Prompt. c:\Users\user>javac MyJava.java

All Java byte codes have an extension .class; therefore, they are also known as “class files”. The above compilation command, if succeeds, will produce a new class file (or byte code) named “MyJava.class”. A Java byte code can be executed by running the “java.exe” command in the Java Virtual Machine (JVM). The syntax is (.exe is optional): java.exe ClassFileName

The following illustrates how to execute a Java byte code named MyJava.class in a Windows Command Prompt. It is necessary to note that the “.class” file extension is not used. c:\Users\user>java MyJava

Throughout this course, be sure not to type the .class extension when testing Java byte codes. The following example is an incorrect statement, which will cause an arror message. java MyJava.class

With respect to the MyJava.java source file (above), the output of this “java MyJava” command should look:

Java Variable and primitive data types

Variables are objects that do not have a fixed value or somethings that continuously change their values. For example, the value of a digital clock, because its value may change every second. Game values are typically represented by variables, such as game score. Java has some fundamental rules to declare an object as variable and designate a name to represent it. The following is the generic form of syntax. dataType VariableName = value;

5 Java Game Programming - Penn P. Wu, PhD

Variable names are case-sensitive and must not be a keyword or reserved word. The convention, however, is to always begin your variable names with a letter, not “$” or “_”. Table: Java keywords/reserved words abstract assert boolean break byte case catch char class const

continue default do double else enum extends final finally float

for goto if implements import instanceof int interface long native

new package private protected public return short static strictfp super

switch synchronized this throw throws transient try void volatile while

The Java programming language is sensitive to data type, which means that all variables must first be declared with a data type before they can be used. The primary reason of declaring a variable’s data type is to let the computer know what size of physically memory it should reserved for the variable to use. When declaring a variable x as int type, the computer will find a 32-bit space in memory to be used by the variable. The following table illustrates commonly seen primitive data types. The term “primitive” means they are provided by the Java language core. Table: Primitive data type Type int float double char string Boolean

Description a 32-bit signed integer a single-precision 32-bit IEEE 754 floating point a double-precision 64-bit IEEE 754 floating point a single 16-bit Unicode character a combination of characters a data that can only have two possible values: true and false

Example 1, 457, -39 3.1415 3.1415 '\u0000' apple, jennifer boolean x = false;

The following declares a variable as the int type. int x;

Once declared, a variable can be assigned a value of the same type. The following assigns 1 to x. Both 1 and x are int type. x = 1;

In Java, variable declaration and the assignment of initial value can be organized into one single statement. The following declares an integer variable x with an initial value of 1, all in one single statement. int x = 1;

The following is a complete code that demonstrates how to actually declare numerical variables and assign value to them. public class MyJava { public static void main(String args[]) { int x; // declaration x = 1; // assign value

6 Java Game Programming - Penn P. Wu, PhD

int y = 4; // declare and assign } }

Generally speaking, any whole number, positive or negative, between -2,147,483,648 and 2,147,483,647 falls into the definition of the “int” type. Both short and long are two special subsets of int data type. The short data type is a 16-bit signed integer, which has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). The long data type is a 64-bit integer for representing a very large integer. Throughout this course, declare non-fractional value as int type is functionally sufficient. No need to use these two data types. Any numbers with fractional part, such as 3.1415, are the floating-point values, and should be declared as either “float” or “double” type. The term “double” is defined as “double of float”, which means if a float type takes 16 bits, a double type will take 32 bits. It is necessary to note that Java frequently require programmers to place a “F” or “f” mark next to a float value. Either “F” or “f” is the valid indicator of float value. The Java compiler will return an error message if either “F” or “f” is not present. Interestingly, Java does not require any suffix if a value is declared as double. public class MyJava { public static void main(String args[]) { double PI = 3.1415; float area = 6.25F; float circumference = 5.31f; } }

Java supports the use of “scientific notation” when a fractional value is too large or too small. In the following example, 6.22-e23 is 6.22×10-23 and 1.03e15 is 1.03×1015. By the way, the letter “e” represents the “natural logarithm”. double a = 6.22e-23 * 1.03e15;

Interestingly, Java supports both “E” and “e”. The following works exactly the same way as the above. double a = 6.22E-23 * 1.03e15;

The char data type is for declaring a single 16-bit Unicode character, as shown below. A single character, such as letter, must be enclosed by a pair of single quotes. char c = 'A';

The following causes a syntax error because the value of a char type must be enclosed by a pair of single quotes, not double quotes. char a = "A";

Java supports the strings type through the java.lang.String class, which requires programmers to enclose a string with a pair of double quotes, as illustrated below. String s = "this is a string";

The following also causes a syntax error because string literals must be enclosed by double quotes.

7 Java Game Programming - Penn P. Wu, PhD

String s = 'this is a string';

The Boolean data type has only two possible values: true and false (sometimes represents as 1 and 0). Use this data type for simple flags that track true/false conditions. The following declares a Boolean variable, named “IsTrue”, that holds the result of (3>5) which is false. Boolean IsTrue = (3>5);

Basic operators

An operator, in Java, is a special symbol that can call a pre-programmed tool to perform a specific operation (such as addition and multiplication) on one or more operands and then returning a result. The following is the generic syntax: operand1 operator operand2

Throughout this course, students will frequently use three basic categories of Java operators: arithmetic, relational (including equality), and logical operators. Arithmetic operators perform basic arithmetic operations that involve the calculation of

numeric values represented by literals, variables, other expressions, function and property calls, and constants. The following table list five basic arithmetic operators. By the way, a modulus operator (%) divides the value of one expression by the value of another, and returns the remainder. Operator + * / %

Description Addition Subtraction Multiplication Division Modulus

Examples x x x x x

+ * / %

y y y y y

Arithmetic operators can only work on int, double, or float types of data. In the following example, there are two variables, x and y, of int type. The instructor declares a string variable, str, to store the result of arithmetic operations. public class MyJava { public static void main(String args[]) { int x = 15; int y = 3; String str += str += str += str +=

str = (x-y) (x*y) (x/y) (x%y)

(x+y) + "\n"; + "\n"; + "\n"; + "\n"; + "\n";

System.out.print(str); } }

The following is the output. C:\Users>java Myjava 18 12 45 5

8 Java Game Programming - Penn P. Wu, PhD

The following is the GUI version. For this point on, the instructor will start to use only GUI applications for demonstrations. import javax.swing.JOptionPane; import javax.swing.JLabel; public class MyJava { public static void main(String args[]) { String str = ""; int x = 15; int y = 3; str str str str str

+= += += += +=

(x+y) (x-y) (x*y) (x/y) (x%y)

+ + + + +

"
"; "
"; "
"; "
"; "
";

// // // // //

18 12 45 5 0

str += ""; JLabel label1 = new JLabel(str); JOptionPane.showMessageDialog( null, label1 ); } }

The output looks:

The following is the JFrame version of the above code. The javax.swing.JFrame class provides tools to create a Windows form-like GUI application (known as a “frame”). A later lecture will discuss how to create a “frame” in details. This example code also uses the setText() method of JLabel to set the text of JLabel to the specified string. import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.Container; public class MyJava { public static void main(String[] args) { JFrame form1 = new JFrame(); form1.setSize(300, 200); form1.setVisible(true); form1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container cont = form1.getContentPane(); cont.setLayout(null); JLabel label1 = new JLabel(); label1.setBounds(10, 10, 100, 100);

9 Java Game Programming - Penn P. Wu, PhD

cont.add(label1); String str = ""; int x = 15; int y = 3; str str str str str

+= += += += +=

(x+y) (x-y) (x*y) (x/y) (x%y)

+ + + + +

"
"; // "
"; // "
"; // "
"; // "";

18 12 45 5 // 0

label1.setText(str); } }

The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Be sure to distinguish the difference between the “assignment” (=) and “equal to” (==”) signs. Be sure to use "==", not "=", when testing if two primitive values are equal. Operator == != > >= < y x >= y x < y x y) + "
"; // true (x>=y) + "
"; // true (x 4) && (y >4) (x > 4) || (y >4)

The following example demonstrates how to use the conditional operators. import javax.swing.JOptionPane; import javax.swing.JLabel; public class MyJava { public static void main(String args[]) { String str = ""; int x = 5; int y = 3; str += ((x > 4) && (y >4)) + "
"; str += ((x > 4) || (y >4)) + "
";

// false // true

str += ""; JLabel label1 = new JLabel(str); JOptionPane.showMessageDialog(null, label1); } }

Type casting in Java

Java is type-sensitive; therefore, type casting is often necessary in order to obtain expected results. Type casting means to change a data of one type into another temporarily. In the following example, the expression is (5/3). The expected result is 1.666666666666667; however, the division operator does not produce expected result, it actually returns 1. import javax.swing.JOptionPane; public class MyJava { public static void main(String args[]) { String str = (5/3) + ""; // why 1? JOptionPane.showMessageDialog(null, str); } }

How could 5/3=1? This is because both the x and y variables are declared as int type (integers, 11 Java Game Programming - Penn P. Wu, PhD

which means whole number or a numerical values that cannot have fractional part); therefore, the result of calculation is still an int type. The arithmetic calculation must ignore the fractional part because the “int” data type does not allow fractional part. A temporary type casting can solve this problem. In the following example, during executation both 5 and 3 will be temporarily converted to the double type (which is a numerical value that allows fractional values); therefore, the result is double type. import javax.swing.JOptionPane; public class MyJava { public static void main(String args[]) { String str = ((double) 5 / (double) 3) + ""; // 1.666666666666667 JOptionPane.showMessageDialog(null, str); } }

The following illustrates the syntax of type casting in Java. It is necessary to enclose the data type by a pair of parentheses. (newType) variable

Type casting only changes the data type temporarily. After calculation, all involved data return to their original types, as demonstrated in the following example. import javax.swing.JOptionPane; import javax.swing.JLabel; public class MyJava { public static void main( String args[] ) { String str = "Before casting:
"; str += (5/3) + "

"; //1 str += "Casting
"; str += ((double) 5 / (double) 3) + "

"; // 1.6... str += "After casting
"; str += (5/3) + "
"; // 1 str += ""; JLabel label1 = new JLabel(str); JOptionPane.showMessageDialog(null, label1); } }

The output looks:

12 Java Game Programming - Penn P. Wu, PhD

The Java API provide a set of parsing methods for convert a string to other data types. The following table lists commonly used methods for converting string to numerical values. By the way, both float and double allows numerical values to have fractional parts. The main differences is that float is a single precision floating-point value, which the double type doubles the single precision. In other words, float has less precision than double. Type-to-be int float double short long byte

Method Integer.parseInt(string) Float.parseFloat(string) Double.parseDouble(string) Short.parseShort(string) Long.parseLong(string) Byte.parseByte(string)

All use entries collected from the keyboards, regardless how they look to a human eye, are treated as strings by the computer. If a user enters three character 3, 5, and 2. It is not treated as a numerical value, 352, but a string “352” by the computer. The following demonstrates how to use the showInputDialog() method of the JOptionPane class to take string inputs from the user, convert the string to float type, perform an arithematic calculation, and then display the result of a division operation in a dialog window. import javax.swing.JOptionPane; public class MyJava { public static void main(String[] args) { String n1 = JOptionPane.showInputDialog("Enter 1st value: "); String n2 = JOptionPane.showInputDialog("Enter 2nd value: "); float result = Float.parseFloat(n1) / Float.parseFloat(n2); JOptionPane.showMessageDialog(null, result); } }

The output looks:

and

Java Control Flow Statements

and

Control flow statements (or conditional statements) can break up a sequential flow of execution with decision making based on pre-defined condition. The condition is typically a Boolean expression that can only be either false or true (cannot be both at the same time). The if structure is probably the most frequently used control structure. As shown below, the if statement decides what to respond based on evaluation result of the Boolean expression. The following illustrates the simplest form of an if structure in Java, where condition is a Boolean expression and statements are Java code to be excuted when the Boolean expression returns true. 13

Java Game Programming - Penn P. Wu, PhD

if (condition) { //statements }

In the following, the condition (x > 4) can yield boolean results: true or false. When the user enters 5, the expression (x > 4) is true, the dialog displays “Bravo”. import javax.swing.JOptionPane; public class MyJava { public static void main(String[] args) { String str = JOptionPane.showInputDialog("Enter a number [19]"); int x = Integer.parseInt(str); if (x > 4) { JOptionPane.showMessageDialog(null, "Bravo!"); } } }

The above code has a logical problem. When the user enters 3 which is less than 4, the expression (x>4) becomes is a false statement. Interestingly, the above code will not have any response because it does not specify what to do when the expression is evaluated to be false. A variation of the if statement, if..else, can solve this problem. The following illustrates the syntax. if (condition) { statements for true } else { statements for false }

The following is a complete code. The “else” part of code will be executed when the user enters 3, 2, or any value that makes the (x>4) expression false. import javax.swing.JOptionPane; public class MyJava { public static void main(String[] args) { String str = JOptionPane.showInputDialog("Enter a number [19]"); int x = Integer.parseInt(str); if (x > 4) { JOptionPane.showMessageDialog(null, "Bravo!"); } else { JOptionPane.showMessageDialog(null, "No!");

14 Java Game Programming - Penn P. Wu, PhD

} } }

When there are more than two possible conditions, it will take a series of if..then..else statements (known as “else if ladder”) to develop a good logic. In the following example, there are four else..if statements in the if structure. By the way, the statement (x = x%5) uses the modulus operator (%) to limits the possible outcomes to 0, 1, 2, 3, and 4. The modulus operator (also known as remainder operator) performs an integer division that divides n1 by n2 and returns only the remainder (r).The setBackground() method can set the background of a JLabel control. import javax.swing.JOptionPane; import javax.swing.JLabel; import java.awt.Color;

Why does 15%6 = 1?

public class MyJava { public static void main(String[] args) { JLabel label1 = new JLabel("Give me a background color."); label1.setOpaque(true); int x = Integer.parseInt(JOptionPane.showInputDialog("Enter a number")); x = x%5; if (x == 0) { else if (x == else if (x == else if (x == else if (x == else { }

label1.setBackground(Color.magenta); } 1) { label1.setBackground(Color.yellow); } 2) { label1.setBackground(Color.green); } 3) { label1.setBackground(Color.pink); } 4) { label1.setBackground(Color.orange); }

JOptionPane.showMessageDialog(null, label1); } }

The following are samples of outcomes. x = 25 x%5 = 0

x = 31 x%5 = 1

x = 47 x%5 = 2

x = 78 x%5 = 3

x = 64 x%5 = 4

The switch..case structure allows programmer to pre-defined conditions and dynamically decide the execution path. Java switch..case structures work with the char and int types. public void actionPerformed(ActionEvent e) { switch (x) { case 400: x=0; label1.setBackground(Color.magenta); break; case 300: label1.setBackground(Color.green); break; case 200: label1.setBackground(Color.yellow); break; case 100: label1.setBackground(Color.blue); break; } x++; label1.setBounds(x,10,10,10);

15 Java Game Programming - Penn P. Wu, PhD

}

The Chinese Zodiac is based on a twelve-year cycle, each year in that cycle relates to an animal sign. These animal signs are the rat, ox, tiger, rabbit, dragon, snake, horse, sheep, monkey, rooster, dog and pig. The following example uses the western solar calendar to determine the year of “sign”; however, in China, the zodiac is supposed to be calculated based on the Chinese lunar. Since the Chinese Zodiac only adopts twelve different animals, the instructor uses the expression y%12 for calculation. This is because a given year value (such as 1997), under the modulus calculation of (y%12), can only return twelve possible values (0, 1, 2, 3, …, 11). The coding logic, on the other hand, is based on a very simple inference and reasoning. For example, the year 2000 was a dragon year. Since 2000%12=8, then any given year y must be a dragon year if and only if y%12=8. Year 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007

y%12 1996%12=4 1996%12=5 1996%12=6 1996%12=7 2000%12=8 2001%12=9 2002%12=10 2003%12=11 2004%12=0 2005%12=1 2006%12=2 2006%12=3

Zodiac Sign Rat Ox Horse Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig

The complete code looks: import javax.swing.JOptionPane; public class MyZodiac { public static void main(String args[]) throws Exception { String zodiac = ""; int y = Integer.parseInt(JOptionPane.showInputDialog("What year were you born?")); switch (y%12) { case case case case case case case case case case case case

0: zodiac = "Monkey"; break; 1: zodiac = "Rooster"; break; 2: zodiac = "Dog"; break; 3: zodiac = "Pig"; break; 4: zodiac = "Rat"; break; 5: zodiac = "Ox"; break; 6: zodiac = "Horse"; break; 7: zodiac = "Rabbit"; break; 8: zodiac = "Dragon"; break; 9: zodiac = "Snake"; break; 10: zodiac = "Horse"; break; 11: zodiac = "Goat"; break;

}

16 Java Game Programming - Penn P. Wu, PhD

JOptionPane.showMessageDialog(null, zodiac); } }

The for statement provides a compact way to repetitively perform a number of similar tasks. The following illustrates a general form of the for structure in Java, where the initialValue is a variable (such as i) that is assigned the first possible value, the terminalValue is a Boolean expression (such as i2) is true. If true, the iteration continutes to display the current value of i, substract 1 from the current value of i, and then checks if the express (i>2) is true. The repetition continues till (i>2) is false. Apparently, a while loop also supports the three basic components: initialValue, terminalValue, and increment/decrement. i=15; while (i>2) { System.out.println(i); i--; }

The increment/decrement in a while loop may be omitted due to the programming logic. The following is a very simple number guessing game. It will continue to ask users to enter a number from 1 to 9 until the entry matches with the value of rn. The condition to test is (x != rn), where x is the value given by the user and rn is assigned by the JVM. The instructor ues the currentTimeMillis() method of the java.lang.System class to return the current time in milliseconds (e.g. 1349333576102). The modulus operator will limit the possible value of rn to 0, 1, 2, 3, 4, 5, 6, 7, and 8. The instructors then adds 1 to the value of rn to change its range to 1 ~ 9. import javax.swing.JOptionPane; public class MyJava { public static void main(String[] args) { long rn = (System.currentTimeMillis()%9) + 1; int x = Integer.parseInt(JOptionPane.showInputDialog("Enter a number [1-9]"));

18 Java Game Programming - Penn P. Wu, PhD

while (x != rn) { x = Integer.parseInt(JOptionPane.showInputDialog("Try another number [1-9]")); } JOptionPane.showMessageDialog(null, "Correct!"); } }

The following example uses a while loop to create eight JButton controls. The initial value of the counter variable i is 0 (as specified by int i=0), the terminal value is 7 (as specified by i