17770121 Java Project XsieOsies

download 17770121 Java Project XsieOsies

of 153

Transcript of 17770121 Java Project XsieOsies

  • 8/14/2019 17770121 Java Project XsieOsies

    1/153

    Page | 1

    CENTRE FOR DEVELOPMENT OF ADVANCED COMPUTINGPLOT NO A-34, INDUSTRIAL AREA, PHASE-8, MOHALI PHONE NO: 2237052,53,54,55 Websitewww.cdacmohali.in

    Core JavaBatch iii

    Project Based on Java Applet Is Xsie-Osies GameSummer Training (June 2009)

    Team Members: guide:Tarun Bhalla Bikramjit Singh Vishal Dogra

    ProjectMs. Sippy

  • 8/14/2019 17770121 Java Project XsieOsies

    2/153

    Page | 2

    AcknowledgementHere, I found this golden chance to acknowledge all those people who had blessed,encouraged and supported me technically and morally gratitude to all those whohelped me in my training. First of all, I pay my immense gratitude to PrincipalDr. M.L. Ohri, Chairman Er. Rakesh Bajaj, Er. Bal krishnan Nangal, HOD ComputerScience Dept. for their valuable guidance. It is my proud to express my heartiestgratitude to my venerable guide Miss. Sippy( Lecturer, Center for Development ofAdvance Computing, Mohali)for her valuable guidance, proper advice and constantencouragementand Mrs. J.S Bhatia(Director, Center for Development of AdvanceComputing, Mohali) without whose expert guidance and support, this training periodwould have been compelling. I also express my deep thanks to the faculty and staffof Centre for Development of Advanced Computing, Mohali, for their help,inspiration and moral support, which helped me a lot in the successful completionof my training. I extend my fort right thanks to my family and friends for theirmoral support and encouragement throughout my training report.

  • 8/14/2019 17770121 Java Project XsieOsies

    3/153

    Page | 3

    INDEX

    Abstract Project Plan Hardware and Software Requirement History of Java BuildingApplet Features of java Phases of Compiler Xsie-Osies Game How to play the GameDesign of Game Steps of Initialization of Game

  • 8/14/2019 17770121 Java Project XsieOsies

    4/153

    Page | 4

    ABSTRACTProject Objectives:The Core Java course that we took this summer training after4th semester placed emphasis on the paradigm of Java Programming techniques. Javais a general purpose programming language with a number of features that make thelanguage well suited for use on the World Wide Web. Small Java applications arecalled Java applets and can be downloaded from a Web server and run on yourcomputer by a Java-compatible Web browser, such as Netscape Navigator or MicrosoftInternet Explorer. The objective of our project is to make a game Xsie-Osies.Xsie-Osies is a board game. It is an example to show basic GUI programming, and isnot intended for advanced GUI design or for optimal game playing.

    Approach:When we were first given this project, we met to determine how we were tocarry out the task assigned to us. We drew up a time-line, discussed about theprogramming concepts to use to carry out the task. Getting a GUI program workingis hard enough the first time without worrying about too many details! The user(player) has the magenta X's and makes the first move. The computer has the blueO's. If the board is too small, filled squares are substituted for X's and filledcircles for O's.

  • 8/14/2019 17770121 Java Project XsieOsies

    5/153

    Page | 5

    Achievement:Our task was to develop Xsie-Osies. It is a board game. Samealgorithms that are commonly used in more complex computer strategy games. We havebeen able to achieve these tasksto achieve this task we have implement my methodto make our work achievable. In this user may change the size of the board. Therange allowed is from 2 to 18 positions. Most of the bugs we found will becorrected by using object-oriented principles and finally made a attractive gameto utilize free time of the user in good and efficient manner.

    Project PlanAt the beginning of the project, we scheduled meeting time for the group todiscuss on the design and implementation of the software and what language to usein writing the software. We had several meetings to this effect. When thendeveloped a time-line for the projectwhen we would be released it. We alsopondered on a suitable name to give the project. We came up with the name X's andO's but it was later changed to Xsie-Osies after our meeting with our client.We are a team of three members that would work on the parts of source code. Wekept in touch with each other and whenever we had difficulties, we asked eachother questions. On some occasions, we had to pretend we were the customer so asto try to figure out some of the things that user would desire, such as thefriendliness of the user interface and ease of navigation through the software.Fortunately for the team, we were able to stick to the new time-line and theproject was completed in due time. After the major part of the code was completed,we went ahead to

  • 8/14/2019 17770121 Java Project XsieOsies

    6/153

    Page | 6

    lace the code, that is, adding exception handlers which will make the softwaremore robust. We avoided this at the beginning because we did not want to getconfused with too many lines of code.

  • 8/14/2019 17770121 Java Project XsieOsies

    7/153

    Page | 7

    Hardware Requirement:Minimum Recommended

    Processor or higher Memory Video adapter VGA And monitor

    233 MHz 64 MB RAM Super VGA (800 x 600)

    300 MHz 128 MB RAM Or higher Super

    (800 x 600) or Higher resolution 1.5 GB 1.5 GB or

    Hard drive disk free space higher

  • 8/14/2019 17770121 Java Project XsieOsies

    8/153

    Page | 8

    Devices and

    Keyboard and mouse

    Keyboard Mouse

    Software Requirement:Operating System: Platform Independent but recommended thatit should be windows XP or KDE 3 (when using Linux). Java Runtime environment(JRE): a software bundle from Sun Microsystems that allows a computer system torun a Java application. Java applications are in widespread use and necessary toview many Internet pages. The software bundle consists of the Java Virtual Machineand programming interface (API). The API provides a set of standard classlibraries. The virtual machine and API have to be consistent with each other andare therefore bundled together as the JRE. This can be considered a virtualcomputer in which the virtual machine is the processor and the API is the userinterface.

    Development Tools and Packages: JCreator (an IDE for programming in java). JDK (Java Development Kit) 4 or better. Sun Java Wireless Toolkit

    History of Java:Java was created in 1991by James Gosling et al. of Sun Microsystems Initiallycalled Oak, in honor of the tree outside Gosling's window, its name was changed toJava because there was already a language called Oak.

    Java Background: History

  • 8/14/2019 17770121 Java Project XsieOsies

    9/153

    Page | 9

    JavaThe original motivation for java. The need for platform independent language

    that could be embedded in various consumer electronic products like toasters andrefrigerators. One of the first projects developed using Java. A personal hand-held remote control named Star 7. At about the same time, the World Wide Web and the Internet were gaining popularity. Gosling et. al. realized that Java could beused for Internet programming.

    What is Java Technology?The Java technology is:1.

    A

    As a programming language, Java can create all kinds of applications that youcould create using any conventional programming language.

    programming

    language

    -

    2.

    A development environment - As a developmentenvironment, Java technology provides you with a large suite of tools: A compiler(javac) An interpreter (java) A documentation generator (javadoc) A class filepackaging tool and so on...

    3.

    Application

    Java technology applications are typically general-purpose programs that run onany machine where the Java runtime environment (JRE) is installed.

    environment

    -

    4.

    Deployment environment - There are two main

    deployment environments

  • 8/14/2019 17770121 Java Project XsieOsies

    10/153

    P a g e | 10

    The JRE supplied by the Java 2 Software Development Kit (SDK) contains thecomplete set of class files for all the Java technology packages, which includesbasic language classes, GUI component classes, and so on. The other maindeployment environment is on your web browser. Most commercial browsers supply aJava technology interpreter and run time environment.

    Why Java Is Important to the Internet?The Internet helped catapult Java to the forefront of programming, and Java, inturn, has had a profound effect on the Internet. The reason for this is quitesimple: Java expands the universe of objects that can move about freely incyberspace. In a network, two very broad categories of objects are transmittedbetween the server and your personal computer: passive information and dynamic,active programs.

    Java ProgramA Java program is mostly a collection of objects talking to other objects byinvoking each other's methods. Every object is of a certain type, and that type isdefined by a class or an interface. Most Java programs use a collection of objectsof many different types. Class A template that describes the kinds of state and behavior that objects of its type support. Object At runtime, when the Java Virtual Machine (JVM) encounters the new keyword, it will use the appropriateclass to make an object which is an instance of that class. That object will haveits own state, and access to all of the behaviors defined by its class.

  • 8/14/2019 17770121 Java Project XsieOsies

    11/153

    P a g e | 11

    State (instance variables) each object (instance of a class) will have its ownunique set of instance variables as defined in the class. Collectively, the valuesassigned to an object's instance variables make up the object's state. Behavior(methods) when a programmer creates a class, she creates methods for that class.Methods are where the class' logic is stored. Methods are where the real work getsdone. They are where algorithms get executed, and data gets manipulated.

    Building Applets:Like applications, applets are created from classes. However,applets do not have main method as an entry point, but instead, have severalmethods to control specific aspects of applet execution.Run the Applet: To see the applet in action, you need an HTML file with the Applettag as follows:

    The easiest way to run the applet is with appletViewer shown below wheresimpleApplet.html is a file that contains the above HTML code: appletViewersimpleApplet.html

  • 8/14/2019 17770121 Java Project XsieOsies

    12/153

  • 8/14/2019 17770121 Java Project XsieOsies

    13/153

    P a g e | 13

    Code security:

    Class Loader:

    Code security is attained in Java through the implementation of its Java RuntimeEnvironment (JRE). JRE runs code compiled for a JVM and performs class loading(through the class loader), code verification (through the byte code verifier) andfinally code execution responsible for loading all classes needed for the Javaprogram adds security by separating the namespaces for the classes of the localfile system from those that are imported from network sources After loading allthe classes, the memory layout of the executable is then determined. This addsprotection against unauthorized access to restricted areas of the code since thememory layout is determined during runtime

    Byte code verifier:

    tests the format of the code fragments and checks the code fragments for illegalcode that can violate access rights to objects

    Phases of compiler: The following figure describes the process of compiling andexecuting a Java program

  • 8/14/2019 17770121 Java Project XsieOsies

    14/153

    P a g e | 14

    Project Swing APIs U :A frame object is a top-level window that provides a title,banner, and methods to manage the appearance and behavior of the window. TheProject Swing code that follows builds this simple application. The window on theleft appears when you start the application, and the window on the right appearswhen you click the button. Click again and you are back to the original window onthe left.

  • 8/14/2019 17770121 Java Project XsieOsies

    15/153

    P a g e | 15

    Import Statements:Here is the SwingUI.java code. At the top, you have four linesof import statements. The lines indicate exactly which Java TM API classes theprogram uses. You could replace four of these lines with this one line: importjava.awt.*; to import the entire awt package, but doing that increases compilationoverhead than importing exactly the classes you need and no others.import java.awt.Color; import java.awt.BorderLayout; import java.awt.event.*;import javax.swing.*;

    Class Declaration:The class declaration comes next and indicates the top-levelframe for the application's user interface is a JFrame that implements theActionListener interface.class SwingUI extends JFrame implements ActionListener{

    The JFrame class extends the Frame class that is part of the Abstract WindowToolkit (AWT) APIs. Project Swing extends the AWT with a full set of GUIcomponents and services, pluggable look and feel capabilities, and assistivetechnology support. The Java APIs provide classes and interfaces for you to use.An interface defines a set of methods, but does not

  • 8/14/2019 17770121 Java Project XsieOsies

    16/153

    P a g e | 16

    implement them. The rest of the SwingUI class declaration indicates that thisclass will implement the ActionListener interface. This means the SwingUI classmust implement all methods defined in the ActionListener interface.

    Instance Variables:These next lines declare the Project Swing component classesthe SwingUI class uses. These are instance variables that can be accessed by anymethod in the instantiated class. In this example, they are built in the SwingUIconstructor and accessed in the actionPerformed method implementation. The privateBoolean instance variable is visible only to the SwingUI class and is used in theactionPerformedmethod to find out whether or not the button has been clicked.JLabel text, clicked; JButton button, clickButton; JPanel panel; private boolean_clickMeMode = true;

    Constructor:The constructor (shown below) creates the user interface componentsand JPanel object, adds the components to the JPanel object, adds the panel to theframe, and makes the JButton components event listeners. When the JPanel object iscreated, the layout manager and background color are specified. The layout managerin use determines how user interface components are arranged on the display area.The code uses the BorderLayout layout manager, which arranges user interfacecomponents in the five areas shown at left. To add a component, specify the area(north, south, east, west, or center).

  • 8/14/2019 17770121 Java Project XsieOsies

    17/153

    P a g e | 17

    The call to the getContentPane method of the JFrame class is for adding the Panelto the JFrame. Components are not added directly to a JFrame, but to its contentpane. Because the layout manager controls the layout of components, it is set onthe content pane where the components reside. A content pane providesfunctionality that allows different types of components to work together inProject Swing.

    Action Listening:In addition to implementing the ActionListener interface, youhave to add the event listener to the JButton components. An action listener isthe SwingUI object because it implements the ActionListener interface. In thisexample, when the end user clicks the button, the underlying Java platformservices pass the action (or event) to the actionPerformed method. In your code,you implement the actionPerformed method to take the appropriate action based onwhich button is clicked. The component classes have the appropriate add methods toadd action listeners to them. In the code the JButton class has anaddActionListener method. The parameter passed to addActionListener is this, whichmeans the SwingUI action listener is added to the button so button-generatedactions are passed to the actionPerformed method in the SwingUI object.

  • 8/14/2019 17770121 Java Project XsieOsies

    18/153

    P a g e | 18

    button = new JButton("Click Me"); //Add button as an event listenerbutton.addActionListener(this);

    Event Handling:- The actionPerformed method ispassed an event object that represents the action event that occurred. Next, ituses an if statement to find out which component had the event, and takes actionaccording to its findings.

    Main Method:The main method creates the top-level frame, sets the title, andincludescode that lets the end user close the window using the frame menu. Thecode for closing the window shows an easy way to add event handling functionalityto a program. If the event listener interface you need provides more functionalitythan the program actually uses, use an adapter class. The Java APIs provideadapter classes for all listener interfaces with more than one method. This way,you can use the adapter class instead of the listener interface and implement onlythe methods you need. In the example, the WindowListener interface has 7 methodsand this program needs only the windowClosing method so it makes sense to use theWindowAdapter class instead. This code extends the WindowAdapter class andoverrides the windowClosing method. The new keyword creates an anonymous instanceof the extended inner class. It is anonymous because you are not assigning a nameto the class and you cannot create another instance of the class without executingthe code again. It is an inner class because

  • 8/14/2019 17770121 Java Project XsieOsies

    19/153

    P a g e | 19

    the extended class definition is nested within the SwingUI class. This approachtakes only a few lines of code, while implementing the WindowListener interfacewould require 6 empty method implementations. Be sure to add the WindowAdapterobject to the frame object so the frame object will listen for window events.

    What is Xsie-Osies game?Xsie-Osies is a graphical Java 1.1 AWT (GUI) applet to play the child's game ofXsie-Osies, also known as Tic-tac-toe, X's and O's, Naughts and Crosses. Click themouse on a position of your choice. You are the magenta X's, and you move first.The computer has the blue O's. To win, you must have a complete horizontal line, acomplete vertical line, or a complete diagonal line. There can be severaldiagonals, because the number of rows and columns can be different. The evaluationof each move is where most of the opportunity for sophistication resides. Eachmove results in a list of moves available to the computer's opponent, and each ofthose moves then result in a move for the computer, and so on. This tree of everexpanding possibilities is called a game tree. For most strategy games, tocompletely traverse the entire game tree, so that each possible move is narroweddown to an eventual win or loss, would take a very long time because of theextreme number of possibilities. The game tree for the third move in an Othellogame could easily involve many millions of possibilities.

  • 8/14/2019 17770121 Java Project XsieOsies

    20/153

    P a g e | 20

    A common tactic when implementing strategy games is to not fully evaluate allmoves. Instead, for each board, only the best and worst positions are returned.The worst position is returned because it is worst for the player, therefore bestfor the player's opponent, and so the move that the opponent is most likely tomake. This approach is called alpha-beta pruning. Here's an example of a gametree, for three levels of a tic-tac toe game.

    A recursive evaluation function evaluates each move. The function creates a listof all available moves for a given player. If any of those moves results in a win,then the

  • 8/14/2019 17770121 Java Project XsieOsies

    21/153

    P a g e | 21

    function returns the count of moves necessary to achieve that win. Otherwise, itcalls itself to evaluate each move for the player's opponent. The end result is alist of available moves, with the count of moves necessary to achieve a win, lossor tie if that move is made. The list is then scanned for the move least likely toresult in a loss and that is the move that is made.

    How to play the Game?The user (player) has the magenta X's and makes the first move. The computer hasthe blue O's. If the board is too small, filled squares are substituted for X'sand filled circles for O's. The user may change the size of the board. The numberof rows and columns may be changed independently. The range allowed (from 2 to 18positions) is more than is practical for playing a fair game. The point is to havecorrect programming logic even with extreme values of the input. The program willredraw the game board to make the best use of the available window size. To winthe game, one player must have a complete horizontal line, a complete verticalline, or a complete diagonal line. In a regular game, the number of rows andcolumns are equal, so all complete lines are the same length. This program allowsthe number of rows to be different than the number of columns.

  • 8/14/2019 17770121 Java Project XsieOsies

    22/153

  • 8/14/2019 17770121 Java Project XsieOsies

    23/153

    P a g e | 23

    The following example game is won by the first player, X:

    Both options have their merits from a programming point of view, because bothoptions force the programmer to avoid assumptions about board size. This programimplements option (2). Option (1) could be implemented as an extra feature. Asinstructors are so often heard to declare, the necessary changes are left as anexercise to the reader!

    Number of possible games:Despite its apparent simplicity, it requires some complexmathematics to determine the number of possible games. This is further complicatedby the definitions used when setting the conditions. Simplistically, there are362,880 (i.e. 9!) ways of placing Xs and Os on the board, without regard towinning combinations. When winning combinations are considered, there are 255,168possible games. Assuming that X makes the first move every time:

    131,184 finished games are won by (X) 1,440 are won by (X) after 5 moves 47,952 are won by (X) after 7 moves 81,792 are won by (X) after 9 moves

  • 8/14/2019 17770121 Java Project XsieOsies

    24/153

    P a g e | 24

    77,904 finished games are won by (O) 5,328 are won by (O) after 6 moves 72,576 are won by (O) after 8 moves

    46,080 finished games are drawn

  • 8/14/2019 17770121 Java Project XsieOsies

    25/153

    P a g e | 25

    Ignoring the sequence of Xs and Os, and after eliminating symmetrical outcomes(i.e. rotations and/or reflections of other outcomes), there are only 138 uniqueoutcomes. Assuming once again that X makes the first move every time:

    91 unique outcomes are won by (X) 21 won by (X) after 5 moves 58 won by (X) after 7 moves 12 won by (X) after 9 moves 44 unique outcomes are won by (O) 21 won by (O) after 6 moves 23 won by (O) after 8 moves 3 unique outcomes are drawn 21 won by (O) after 6 moves 23 won by (O) after 8 moves

    Design of Applet:-

  • 8/14/2019 17770121 Java Project XsieOsies

    26/153

    P a g e | 26

    The design considerations for this applet are as follows: The applet should run on older browsers as-is, without needing any additional downloads and/or features.The minimum target is JDK1.1 which is Microsoft Internet Explorer 5.0 (Windows 98)and Netscape 4.7/4.8 (JDK 1.1.5 from 1997). The applet should contain only a single class, with no external images, so that it can be downloaded as one filewith an HTML web page.

    The default background in the Sun Java applet viewer is white, but most webbrowsers use light grey. To get the background color that you want, you mustsetBackground () on components or fillRect () with the color of your choice. Asmall main () method is included with a WindowAdapter subclass, so that thisprogram can be run as an application. The default window size and position won'tplease everyone.

    Applet Initialization and Termination:It is important to understand the order inwhich the various methods shown in the skeleton are called. When an applet begins,the AWT calls the following methods, in this sequence: init( ) start( ) paint( ) When an applet is terminated, the following sequence of method callstakes place:

  • 8/14/2019 17770121 Java Project XsieOsies

    27/153

    P a g e | 27

    stop( ) destroy( ) Lets look more closely at these methods.

    Init ( ) method:- The init( ) method is the first method tobe called. This is where you should initialize variables. This method is calledonly once during the run time of your applet. Initialize this applet (equivalentto the main () method in an application). Please note the following about writingapplets: 1. An Applet is an AWT Component just like a Button, Frame, or Panel. Ithas a width, a height, and you can draw on it (given a proper graphical context,as in the paint () method).2.

    Applets shouldn't attempt to exit, such as by calling the System.exit() method,because this isn't allowed on a web page.

    Start ( ) method: - The start ( ) method is called afterinit ( ). It is also called to restart an applet after it has been stopped.Whereas init ( ) is called oncethe first time an applet is loadedstart ( ) iscalled each time an applets HTML document is displayed onscreen. So, if a userleaves a web page and comes back, the applet resumes execution at start ( ).

    Paint ( ) method: -The paint ( ) method is called eachtime your applets output must be redrawn. This situation can occur for severalreasons. For example, the window in which the applet is running may be overwrittenby another window and then uncovered. Or the applet window may be minimized

  • 8/14/2019 17770121 Java Project XsieOsies

    28/153

    P a g e | 28

    and then restored. paint ( ) is also called when the apple begins execution.Whatever the cause, whenever the applet must redraw its output, paint ( ) iscalled. The paint ( ) method has one parameter of type Graphics. This parameterwill contain the graphics context, which describes the graphics environment inwhich the applet is running. This context is used whenever output to the applet isrequired.

    stop ( ) method:- The stop( ) method is called when aweb browser leaves the HTML document containing the appletwhen it goes to anotherpage, for example. When stop ( ) is called, the applet is probably running. Youshould use stop ( ) to suspend threads that dont need to run when the applet isnot visible. You can restart them when start ( ) is called if the user returns tothe page.

    destroy ( ) method:-The destroy( ) method is calledwhen the environment determines that your applet needs to be removed completelyfrom memory. At this point, you should free up any resources the applet may beusing. The stop( ) method is always called before destroy( ).

    Steps for Initialization of Project Game:

    ClearBoard ():- ClearBoard is a method to clear(create) the game board. Create the GUI interface as a series of little panelsinside bigger panels. The intermediate panel names (panel1, panel2, etc) are of noimportance and hence are only numbered. Make a horizontal panel to hold the rowand column counters. It also creates a new game board, or clears the existing gameboard to all empty positions. This method should not do any GUI calls such asrepaint (), because there are several methods that make changes to GUI objects

  • 8/14/2019 17770121 Java Project XsieOsies

    29/153

    P a g e | 29

    after calling clearBoard () and before they are ready to repaint. If clearBoard ()forced a repaint, then too many unnecessary paint operations would be performed.

    Canvas: - Although it is not part of the hierarchy forapplet or frame windows, there is one other type of window that you will findvaluable: Canvas. Canvas encapsulates a blank window upon which you can draw. Nowput all that on top of a canvas for the game board, giving the game board theremaining window space. Since we don't set a size for the board canvas, it isassigned some arbitrary width and zero height. The paint () method will calculatethe correct placement later. main ():- Main () is simply a starting place for yourprogram. A complex program will have dozens of classes, only one of which willneed to have main () method to get things started. Applets only need an init ()method to start execution. This main () method is a

  • 8/14/2019 17770121 Java Project XsieOsies

    30/153

    P a g e | 30

    wrapper that allows the same applet code to run as an application.actionPerformed() method:- This interface defines the actionPerformed() methodthat is invoked when an action event occurs. Its general form is shown here:void actionPerformed(ActionEvent ae)

    In our project this method is called when the user clicks on the "New Game" or"Skip Turn" button

  • 8/14/2019 17770121 Java Project XsieOsies

    31/153

    P a g e | 31

    CreatePathList ():-Create a list of paths representingthe possible winning lines in the game board. This method must be called when theboard is initialized or after the board size changes. Having a separate loop forhorizontal logic, for vertical logic, and for diagonal logic looks like an easy(if somewhat lengthy) solution, but is actually a harder way of traversing thegame board. A better way is to create an array with one entry for each possibleline through the game board. Each entry has:

    [0] = the starting row number (index) [1] = the starting column number (index) [2] = the row increment (-1, 0, +1) to the next board position [3] = the

    column increment The number of diagonal paths is two, if the number of rows andcolumns are equal, but increases as the two diverge.

    drawBig0 ():-Draw an "O" for a player symbol at thegiven coordinates and size. If the size is too small, then just draw a filledcircle. Note that this method usually returns with the drawing color set to thebackground color. We draw the "O" as a larger circle with a smaller center circleremoved.

  • 8/14/2019 17770121 Java Project XsieOsies

    32/153

    P a g e | 32

    drawBigX ():-Draw an "X" for a player symbol at thegiven coordinates and size. If the size is too small, then just draw a filledsquare. Unlike drawBigO (), this method does not change the drawing color. Wecould draw the "X" as a single polygon shape with 16 points. However, we get amore regular "X" if we draw two linear polygon shapes with 6 points each. A small,additional border is added around the "X" so that an "X" appears to be more inproportion with an "O".

    iteamStateChanged():-This method is called whenthe user changes a row or column counter. We assume that the value returned fromthe GUI is in the proper range. A new game is started.

  • 8/14/2019 17770121 Java Project XsieOsies

    33/153

    P a g e | 33

    markWinningPath ():-A path in the game board is awinning path. Mark this path so that it will be displayed differently the nexttime the board is redrawn. mouseClicked ():-This method is called when the userclicks the mouse on the game board. To be consistent with the (x, y) coordinatesin paint (), this mouse listener is for the whole applet window -- not just thedummy board canvas. We must determine: a. if the user is allowed to choose a boardposition (user's turn to move); b. which position the mouse is pointing at; c. ifthe position is empty (available); and d. if choosing the position ends the game

  • 8/14/2019 17770121 Java Project XsieOsies

    34/153

    P a g e | 34

    Our calculations make use of several global variables set by the paint () method. moveComputer ():-This method is called after the user makes a move (that is,chooses a board position), or passes (that is, skips his/her turn). We must domore than just make the computer's move. We must: a. do nothing if there is noactive game (a sensible precaution); b. check if the user has won; c. check if thegame is tied, because no empty positions remain; d. choose a move for thecomputer; e. check if the computer has won; and f. Check again if the game istied, because no empty positions remain. Most of those steps involve traversingthe game board horizontally, vertically, and diagonally in a similar fashion. Amore interesting approach is to traverse the board only once or twice, collectinginformation as we go along, and analyzing that information later to make adecision. In other words, hold onto your hats, because this is a multitasking kindof method! (Well, not literally, because there is no Java threads involved. Ishould be more careful with computer terms like "multi-tasking" even if they haveentered common speech with a slightly different meaning.) Note that this methoddoesn't need to know anything about the GUI interface (except maybe setting themessage text), and doesn't need to do any painting. Both places where moveComputer() is called will do a repaint later anyway.

  • 8/14/2019 17770121 Java Project XsieOsies

    35/153

    P a g e | 35

    Paint ():-Draw the game board directly onto the lower

    part of the applet window. After this method returns, other AWT components(buttons, counters, etc) will draw themselves on *top* of whatever we draw here.We estimate the starting position of the game board from the component. Several global variables are set for later use by the mouse listener todetermine where board positions are located. When an applet runs on a web page,the initial window size is chosen by the web page's HTML code and can't be changedby the applet. Applets running outside of a web page (such as with Sun's appletviewer) can change their window size at any time. The user may enlarge or reducethe window to make it fit better on his/her display. Hence, while this appletdoesn't attempt to change the window size, it must accept that the window size maybe different each time the paint () method is called. A good applet redraws itscomponents to fit the window size. scanBoard ():-This is a general method toscan the game board to determine: a. if there is a winner; b. if the game is tied(no moves possible); c. if the game is hopeless (empty positions but nobody canwin); or d. If the game should continue. The vscanBoard () method Thisis a general method to scan the game board to determine: ariable will be set to if the game should end. As an option, while this method is scanning theboard, it will also estimate

  • 8/14/2019 17770121 Java Project XsieOsies

    36/153

    P a g e | 36

    the value (to the computer) of each empty board position. This is an optionbecause we only need this information before the computer moves, not afterward.

    Source Code /* Java 1.1 AWT Applet - Tic-Tac-Toe, X's and O's, Naughts and CrossesWritten by: Keith Fenske, http://www.psc-consulting.ca/fenske/ Saturday, 3 January2004 Java class name: TicTacToe4

  • 8/14/2019 17770121 Java Project XsieOsies

    37/153

  • 8/14/2019 17770121 Java Project XsieOsies

    38/153

    P a g e | 38

    The user may change the size of the board. The number of rows and columns may bechanged independently. The range allowed (from 2 to 18 positions) is more than ispractical for playing a fair game. The point is to have correct programming logiceven with extreme values of the input. The program will redraw the game board tomake the best use of the available window size. To win the game, one player musthave a complete horizontal line, a complete vertical line, or a complete diagonalline. In a regular game, the number of

  • 8/14/2019 17770121 Java Project XsieOsies

    39/153

    P a g e | 39

    rows and columns are equal, so all complete lines are the same length. Thisprogram allows the number of rows to be different than the number of columns. Twopossible definitions of a winning line present themselves: (1) Choose the smallerof the number of rows and the number of columns. Then any straight line anywhereon the board, with that many positions belonging to the same player, is a winningline. If, for example, there are 6 rows and 10 columns, a winning line of 6positions might appear from coordinates (3,2) to (3,7).

  • 8/14/2019 17770121 Java Project XsieOsies

    40/153

    P a g e | 40

    (2) Ignore the fact that the rows and columns aren't equal, and still insist on acomplete row, a complete column, or a complete diagonal -- and there may beseveral diagonals! This is visually easier to see and understand. Both optionshave their merits from a programming point of view, because both options force theprogrammer to avoid assumptions about board size. This program implements option(2). Option (1) could be implemented as an extra feature. As instructors are sooften heard to declare, the necessary changes are left as an exercise to thereader!

  • 8/14/2019 17770121 Java Project XsieOsies

    41/153

    P a g e | 41

    GNU General Public License (GPL) -------------------------------TicTacToe4 is freesoftware: you can redistribute it and/or modify it under the terms of the GNUGeneral Public License as published by the Free Software Foundation, eitherversion 3 of the License or (at your option) any later version. This program isdistributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, withouteven the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public License for more details.

  • 8/14/2019 17770121 Java Project XsieOsies

    42/153

    P a g e | 42

    You should have received a copy of the GNU General Public License along with thisprogram. If not, see the http://www.gnu.org/licenses/ web page.---------------------------------------------------------------------------JavaApplet Notes: The recommended way of writing applets is to use Java Swing,according to Sun Microsystems, the creators and sponsors of Java. Unfortunately,most web browsers don't support Swing unless you download a recent copy of theJava

  • 8/14/2019 17770121 Java Project XsieOsies

    43/153

    P a g e | 43

    run-time environment from Sun. This leaves a Java programmer with two choices: (1)Write applets using only old features found in the AWT interface. The advantage,if you can see it this way, is that the programmer gets a detailed opportunity tointeract with the graphical interface. (Joke.) (2) Force users to visithttp://java.sun.com/downloads/ to download and install a newer version of Java.However, forcing anyone to download

  • 8/14/2019 17770121 Java Project XsieOsies

    44/153

    P a g e | 44

    something before they can visit your web page is a poor idea. A worse idea is newbrowsers that don't have any Java support at all, unless the user first downloadsSun Java. Microsoft stopped distributing their version of Java in 2003 startingwith Windows XP SP1a (February), then Windows 2000 SP4 (June). Until Microsoft andSun resolve their various lawsuits -- or until Microsoft agrees to distribute anunaltered version of Sun Java -- there will be an increasing number of internetusers that have *no* version of Java installed on their machines!

  • 8/14/2019 17770121 Java Project XsieOsies

    45/153

    P a g e | 45

    The design considerations for this applet are as follows: (1) The applet shouldrun on older browsers as-is, without needing any additional downloads and/orfeatures. The minimum target is JDK1.1 which is Microsoft Internet Explorer 5.0(Windows 98) and Netscape 4.7/4.8 (JDK 1.1.5 from 1997). (2) The applet shouldcontain only a single class, with no external images, so that it can be downloadedas one file with an HTML web page.

  • 8/14/2019 17770121 Java Project XsieOsies

    46/153

  • 8/14/2019 17770121 Java Project XsieOsies

    47/153

    P a g e | 47

    import java.awt.*; GUI support import java.awt.event.*; GUI event support publicclass Xsie_Osies extends Applet

    // older Java // older Java

    implements ActionListener, ItemListener, MouseListener { /* constants */ staticfinal String beginMessage = "Click the mouse on a position of your choice. You arethe magenta X's."; static final int canvasBorder = 10; // empty pixels around gameboard

  • 8/14/2019 17770121 Java Project XsieOsies

    48/153

    P a g e | 48

    static final int DefCOLS = 5; // default number of columns in game board staticfinal int DefROWS = 3; // default number of rows in game board static final StringnoMessage = " "; // message text when nothing to say static final String[]rowColumnCounters = {"2", "3", "4", "5", "6", "8", "12", "18"}; static final ColorBACKGROUND = new Color(255, 204, 204); // light pink static final ColorColorCOMPUTER = new Color(102, 102, 255); // light blue static final ColorColorGRIDLINE = new Color(204, 153, 153); // darker pink

  • 8/14/2019 17770121 Java Project XsieOsies

    49/153

    P a g e | 49

    static final Color ColorUSER = Color.magenta; static final Color ColorWINCOMP =Color.red; static final Color ColorWINUSER = Color.red; static final intPlayCOMPUTER = 1; // board position: computer (regular) static final int PlayNONE= 2; position: empty static final int PlayUSER = 3; position: user (regular) //board // board

    static final int PlayWINCOMP = 4; // board position: computer wins here staticfinal int PlayWINUSER = 5; // board position: user wins here

  • 8/14/2019 17770121 Java Project XsieOsies

    50/153

    P a g e | 50

    static final int ValueOPENCOMP = 5; // relative importance (to the computer) //... of an empty position on a path // ... that is still open (that is, has // ...no user positions) static final int ValueOPENUSER = 2; // relative importance ofan empty // ... position on a path that is still // ... open to the user (nocomputer) static final int ValueWINCOMP = 500; // relative importance of a singleempty

  • 8/14/2019 17770121 Java Project XsieOsies

    51/153

    P a g e | 51

    // ... position that will win the game // ... for the computer static final intValueWINUSER = 200; // relative importance of a single empty // ... position thatwill stop the user // ... from winning in the next move /* class variables */ /*instance variables, including shared GUI components */ Canvas boardCanvas; drawthe game board // where we

  • 8/14/2019 17770121 Java Project XsieOsies

    52/153

    P a g e | 52

    int[][] boardData; board (PlayXXX)

    // internal game

    int boardGridStep; // calculated size of each board position, // ... includinginner borders and one set of // ... grid lines int boardInnerBorder; // pixels ineach position's inner border int boardLeftMargin; // adjusted left margin tocenter game board int boardSymbolSize; // pixels for each position's player symbolint boardTopMargin; // adjusted top margin to center game board int[][]boardValues; // estimated value of each empty position

  • 8/14/2019 17770121 Java Project XsieOsies

    53/153

    P a g e | 53

    Choice columnCounter; // column counter (number of columns) int gameState; forcurrent game // state variable // information

    Label messageText; or status message for user

    int numCols = DefCOLS; // number of columns in current game board int[][]pathList; lines in game board int numPaths; for // list ofwinning // a better name

    int numRows = DefROWS; // number of rows in current game board Choice rowCounter;(number of rows) Button skipButton; button // row counter // "Skip Turn"

  • 8/14/2019 17770121 Java Project XsieOsies

    54/153

    P a g e | 54

    Button startButton; button

    // "New Game"

    /* init() method Initialize this applet (equivalent to the main() method in anapplication). Please note the following about writing applets: (1) An Applet is anAWT Component just like a Button, Frame, or Panel. It has a width, a height, andyou can draw on it (given a proper graphical context, as in the paint() method).

  • 8/14/2019 17770121 Java Project XsieOsies

    55/153

    P a g e | 55

    (2) Applets shouldn't attempt to exit, such as by calling the System.exit()method, because this isn't allowed on a web page. */ public void init() { /*Intialize our own data before creating the GUI interface. */ clearBoard(); thegame board // clear (create)

    /* Create the GUI interface as a series of little panels inside bigger

  • 8/14/2019 17770121 Java Project XsieOsies

    56/153

    P a g e | 56

    panels. The intermediate panel names (panel1, panel2, etc) are of no importanceand hence are only numbered. */ /* Make a horizontal panel to hold the row andcolumn counters. */ Panel panel1 = new Panel(new FlowLayout(FlowLayout.CENTER, 0,0)); Label label1 = new Label("Rows: ", Label.RIGHT);label1.setBackground(BACKGROUND); panel1.add(label1); rowCounter = new Choice();for (int i = 0; i < rowColumnCounters.length; i ++)

  • 8/14/2019 17770121 Java Project XsieOsies

    57/153

    P a g e | 57

    rowCounter.add(rowColumnCounters[i] ); rowCounter.select(String.valueOf(DefROWS)); rowCounter.addItemListener((ItemListe ner) this); panel1.add(rowCounter);Panel panel2 = new Panel(new FlowLayout(FlowLayout.CENTER, 0, 0)); Label label2 =new Label("Columns: ", Label.RIGHT); label2.setBackground(BACKGROUND);panel2.add(label2); columnCounter = new Choice(); for (int i = 0; i 15) // if size is big enough, remove center { width = (int) (size * 0.14); // makeline width proportional to size gr.setColor(BACKGROUND); // erase center bydrawing background color gr.fillOval((hz + width), (vt + width), (size - (2 *width)), (size - (2 * width))); } } // end of drawBigO() method

    /*

  • 8/14/2019 17770121 Java Project XsieOsies

    86/153

    P a g e | 86

    drawBigX() method Draw an "X" for a player symbol at the given coordinates andsize. If the size is too small, then just draw a filled square. Unlike drawBigO(),this method does not change the drawing color. We could draw the "X" as a singlepolygon shape with 16 points. However, we get a more regular "X" if we draw twolinear polygon shapes with 6 points each. A small, additional border is addedaround the "X" so that an "X" appears to be more in proportion with an "O".

  • 8/14/2019 17770121 Java Project XsieOsies

    87/153

    P a g e | 87

    */ void drawBigX( Graphics gr, int hz, left corner int vt, right corner int size)pixels { int border; // additional border to make "X" look smaller int width;forming the cross int[] xlist; polygon shape // width of line // x coordinates for// graphics context // x coordinate of top// y coordinate of top// size of symbolin

  • 8/14/2019 17770121 Java Project XsieOsies

    88/153

    P a g e | 88

    int[] ylist; polygon shape if (size > 15) draw an "X" (cross) {

    // y coordinates for

    // if big enough to

    border = (int) (size * 0.04); // extra border is proportional to size width =(int) (size * 0.10); // make line width proportional to size xlist = new int[6];// six points needed to describe one stroke ylist = new int[6]; /* Draw strokefrom top left to bottom right. */

  • 8/14/2019 17770121 Java Project XsieOsies

    89/153

    P a g e | 89

    xlist[0] = hz + border; coordinate, clockwise

    // first x

    xlist[1] = hz + border + width; xlist[2] = hz + size - border; xlist[3] = hz +size - border; xlist[4] = hz + size - border - width; xlist[5] = hz + border;ylist[0] = vt + border; coordinate, clockwise ylist[1] = vt + border; ylist[2] =vt + size - border - width; ylist[3] = vt + size - border; ylist[4] = vt + size -border; ylist[5] = vt + border + width; // first y

  • 8/14/2019 17770121 Java Project XsieOsies

    90/153

    P a g e | 90

    gr.fillPolygon(xlist, ylist, 6); // draw stroke as a filled polygon /* Drawoverlapping stroke from top right to bottom left. */ xlist[0] = hz + size -border; // first x coordinate, clockwise xlist[1] = hz + size - border; xlist[2] =hz + border + width; xlist[3] = hz + border; xlist[4] = hz + border; xlist[5] = hz+ size - border - width; ylist[0] = vt + border; coordinate, clockwise // first y

    ylist[1] = vt + border + width;

  • 8/14/2019 17770121 Java Project XsieOsies

    91/153

    P a g e | 91

    ylist[2] = vt + size - border; ylist[3] = vt + size - border; ylist[4] = vt + size- border - width; ylist[5] = vt + border; gr.fillPolygon(xlist, ylist, 6); // drawstroke as a filled polygon } else { gr.fillRect(hz, vt, size, size); // too small,just fill square } } // end of drawBigX() method

  • 8/14/2019 17770121 Java Project XsieOsies

    92/153

    P a g e | 92

    /* itemStateChanged() method This method is called when the user changes a row orcolumn counter. We assume that the value returned from the GUI is in the properrange. A new game is started. */ public void itemStateChanged(ItemEvent event){ Object source = event.getSource(); // where the event came from if (source ==columnCounter) // new number of columns? {

  • 8/14/2019 17770121 Java Project XsieOsies

    93/153

    P a g e | 93

    numCols = Integer.parseInt(columnCounter.getSelecte dItem()); clearBoard(); gameboard // start a new

    messageText.setText("New game board is " + numRows + " rows by " + numCols + "columns."); repaint(); } else if (source == rowCounter) // new number of rows?{ numRows = Integer.parseInt(rowCounter.getSelectedIte m());

  • 8/14/2019 17770121 Java Project XsieOsies

    94/153

    P a g e | 94

    clearBoard(); game board

    // start a new

    messageText.setText("New game board is " + numRows + " rows by " + numCols + "columns."); repaint(); } else { System.out.println("error in itemStateChanged():ItemEvent not recognized: " + event); } } // end of itemStateChanged() method

  • 8/14/2019 17770121 Java Project XsieOsies

    95/153

    P a g e | 95

    /* markWinningPath() method A path in the game board is a winning path. Mark thispath so that it will be displayed differently the next time the board is redrawn.*/ void markWinningPath( int startRow, number (index) int startCol, number (index)int rowIncr, int colIncr) increment { // starting row // starting column // rowincrement // column

  • 8/14/2019 17770121 Java Project XsieOsies

    96/153

    P a g e | 96

    int col; number (index) int row; number (index) row = startRow; with this row col= startCol; column

    // temporary column // temporary row

    // path starts // and with this

    while ((row >= 0) && (row < numRows) && (col >= 0) && (col < numCols)) { switch(boardData[row][col]) { case PlayCOMPUTER: computer's position //

  • 8/14/2019 17770121 Java Project XsieOsies

    97/153

    P a g e | 97

    boardData[row][col] = PlayWINCOMP; // change to winning position break; casePlayUSER: // user's position

    boardData[row][col] = PlayWINUSER; // change to winning position break; default:System.out.println("error in markWinningPath(): bad boardData[" + row + "][" + col+ "] = " + boardData[row][col]); }

  • 8/14/2019 17770121 Java Project XsieOsies

    98/153

    P a g e | 98

    row += rowIncr; next position col += colIncr; next position }

    // row index of // column index of

    } // end of markWinningPath() method

    /* mouseClicked() method This method is called when the user clicks the mouse onthe game board. To be consistent with the (x,y) coordinates in paint(), this mouselistener is for the whole applet window -- not just the dummy board canvas. Wemust

  • 8/14/2019 17770121 Java Project XsieOsies

    99/153

    P a g e | 99

    determine: (1) if the user is allowed to choose a board position (user's turn tomove); (2) which position the mouse is pointing at; (3) if the position is empty(available); and (4) if choosing the position ends the game. Our calculations makeuse of several global variables set by the paint() method. */ public voidmouseClicked(MouseEvent event) {

  • 8/14/2019 17770121 Java Project XsieOsies

    100/153

    P a g e | 100

    int col; number int colExtra; column calculation int row; number int rowExtra; rowcalculation

    // calculate column // remainder from // calculate row // remainder from

    /* Convert the (x,y) coordinates into row and column numbers, with a little extrainformation to tell us if the user was clicking on a board position, or if theclicks are on an inner or outer border. */

  • 8/14/2019 17770121 Java Project XsieOsies

    101/153

  • 8/14/2019 17770121 Java Project XsieOsies

    102/153

    P a g e | 102

    messageText.setText("This game is finished. You must start a new game before youcan move again."); } else if (gameState != PlayUSER) { /* It's the computer's turnto move, not the user's. */ messageText.setText("Sorry, it's not your turn tomove. The computer is thinking."); } else if ((col < 0) game board || (col >=numCols) // if click is outside

  • 8/14/2019 17770121 Java Project XsieOsies

    103/153

    P a g e | 103

    || (colExtra < boardInnerBorder) // or on inner border || (colExtra >(boardInnerBorder + boardSymbolSize)) || (row < 0) game board // if click isoutside

    || (row >= numRows) || (rowExtra < boardInnerBorder) // or on inner border ||(rowExtra > (boardInnerBorder + boardSymbolSize))) { /* Ignore clicks that are notdirectly on a board position. */ messageText.setText("Please click on a boardposition.");

  • 8/14/2019 17770121 Java Project XsieOsies

    104/153

    P a g e | 104

    } else if (boardData[row][col] != PlayNONE) { /* The user clicked on a positionthat is already occupied. */ messageText.setText("Sorry, that board position hasalready been chosen."); } else { boardData[row][col] = PlayUSER; // user nowoccupies this position messageText.setText("Your move is row " + (row + 1) + " andcolumn " + (col + 1) + ".");

  • 8/14/2019 17770121 Java Project XsieOsies

    105/153

    P a g e | 105

    gameState = PlayCOMPUTER; moveComputer(); // check for winner, make computer'smove } repaint(); } // end of mouseClicked() method public voidmouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { }public void mousePressed(MouseEvent event) { } public voidmouseReleased(MouseEvent event) { }

  • 8/14/2019 17770121 Java Project XsieOsies

    106/153

    P a g e | 106

    /* moveComputer() method This method is called after the user makes a move (thatis, chooses a board position), or passes (that is, skips his/her turn). We must domore than just make the computer's move. We must: (1) do nothing if there is noactive game (a sensible precaution); (2) check if the user has won; (3) check ifthe game is tied, because no empty positions remain; (4) choose a move for thecomputer; (5) check if the computer has won; and

  • 8/14/2019 17770121 Java Project XsieOsies

    107/153

    P a g e | 107

    (6) check again if the game is tied, because no empty positions remain. Most ofthose steps involve traversing the game board horizontally, vertically, anddiagonally in a similar fashion. A more interesting approach is to traverse theboard only once or twice, collecting information as we go along, and analyzingthat information later to make a decision. In other words, hold onto your hats,because this is a multi-tasking kind of method! (Well, not literally, becausethere are no Java threads involved. I should be more careful with computer termslike "multi-tasking" even if they have

  • 8/14/2019 17770121 Java Project XsieOsies

    108/153

    P a g e | 108

    entered common speech with a slightly different meaning.) Note that this methoddoesn't need to know anything about the GUI interface (except maybe setting themessage text), and doesn't need to do any painting. Both places wheremoveComputer() is called will do a repaint later anyway. */ void moveComputer(){ int col; number (index) // temporary column

    int maxOccurs; // how many times occurs in the

  • 8/14/2019 17770121 Java Project XsieOsies

    109/153

    P a g e | 109

    // ... array int maxValue; // maximum value found in int moveCol; computer's next move int moveRow; computer's next move int row;number (index) // column of // row of // temporary row

    /* Check if we shouldn't have been called. This won't happen when the program isfinished, but may happen during debugging. */ if (gameState != PlayCOMPUTER)

  • 8/14/2019 17770121 Java Project XsieOsies

    110/153

    P a g e | 110

    { System.out.println("error in moveComputer(): called with gameState = " +gameState); return; moveComputer() } /* Check if someone wins, the game is tied,or no useful moves remain. */ scanBoard(true); for winners and losers // checkboard // error ends

    if (gameState == PlayNONE) // nothing to do if game is now over return;

  • 8/14/2019 17770121 Java Project XsieOsies

    111/153

    P a g e | 111

    /* Somebody can still win this game. This may not be the computer.... Choose aboard position with the maximum value estimated by scanBoard(). If the computercan't win, then we can at least aggressively block the user and hasten the end ofthe game! */ maxOccurs = 0; // no occurrences of maximum found yet maxValue = -1;// default is less than any position's value moveCol = moveRow = -1; // bad valuejust to make compiler happy for (row = 0; row < numRows; row ++) { for (col = 0;col < numCols; col ++)

  • 8/14/2019 17770121 Java Project XsieOsies

    112/153

    P a g e | 112

    { if (boardValues[row][col] > maxValue) { maxValue = boardValues[row][col]; // setnew maximum maxOccurs = 1; occurrence // first

    moveRow = row; // remember first position with this maximum moveCol = col; } elseif (boardValues[row][col] == maxValue) maxOccurs ++; number of occurences } } //count the

  • 8/14/2019 17770121 Java Project XsieOsies

    113/153

    P a g e | 113

    /* If more than one position has the same maximum value, then make a randomselection because this is more interesting for the user. */ if (maxOccurs > 1) //make a selection if more than one choice { int looking = 1 + (int) (Math.random()* maxOccurs); // random number from 1 to int current = 0; occurencefound // current

    for (row = 0; row < numRows; row ++)

  • 8/14/2019 17770121 Java Project XsieOsies

    114/153

  • 8/14/2019 17770121 Java Project XsieOsies

    115/153

    P a g e | 115

    } } } if (current == looking) // did we find what we were looking for? break; forrow loop } if (current != looking) System.out.println("error in moveComputer():current " + current + " is not equal to looking " + looking); } /* The selectedempty position becomes the computer's move. */ // yes, break out of

  • 8/14/2019 17770121 Java Project XsieOsies

    116/153

    P a g e | 116

    boardData[moveRow][moveCol] = PlayCOMPUTER; gameState = PlayUSER; turn to movescanBoard(false); for winners and losers // user's // check board

    } // end of moveComputer() method

    /* paint() method Draw the game board directly onto the lower part of the appletwindow. After

  • 8/14/2019 17770121 Java Project XsieOsies

    117/153

    P a g e | 117

    this method returns, other AWT components (buttons, counters, etc) will drawthemselves on *top* of whatever we draw here. We estimate the starting position ofthe game board from the component. Several global variables are setfor later use by the mouse listener to determine where board positions arelocated. When an applet runs on a web page, the initial window size is chosen bythe web page's HTML code and can't be changed by the applet. Applets runningoutside of a web page (such as with Sun's applet viewer) can change their

  • 8/14/2019 17770121 Java Project XsieOsies

    118/153

  • 8/14/2019 17770121 Java Project XsieOsies

    119/153

    P a g e | 119

    int col; number (index)

    // temporary column

    int hz; // temporary number of horizontal pixels int lineWidth; lines (in pixels)int row; number (index) int vt; of vertical pixels // width of grid // temporaryrow // temporary number

    /* Clear the entire applet window to our own background color, not the default(which is sometimes white and sometimes grey). */ // gr.setColor(BACKGROUND);

  • 8/14/2019 17770121 Java Project XsieOsies

    120/153

    P a g e | 120

    // gr.fillRect(0, 0, getWidth(), getHeight()); /* If the current message field isa complaint from us about the applet window being too small, then clear themessage text. Should the window problem persist, we will regenerate the errormessage anyway. */ if (messageText.getText().startsWith("Applet window"))messageText.setText(noMessage); /* The component gets positionedbelow our buttons and the

  • 8/14/2019 17770121 Java Project XsieOsies

    121/153

    P a g e | 121

    message field. The assigned size of is not important; we only needto know the starting y coordinate, so that we can draw the board below all theother AWT components. We calculate the size of the board (in pixels) using theapplet's window size minus the starting y coordinate of , minus aborder. The border serves two purposes: to prevent the game board from touchingthe window's edge, and as a safety zone above the board where the other AWTcomponents will appear along with a lower border that is *not* accounted for inthe starting y coordinate for . */

  • 8/14/2019 17770121 Java Project XsieOsies

    122/153

  • 8/14/2019 17770121 Java Project XsieOsies

    123/153

    P a g e | 123

    // JDK1.1 note: replace this.getHeight() with this.getSize().height boardHeight =this.getSize().height boardTopMargin - canvasBorder; boardHeight = (boardHeight >0) ? boardHeight : 0; /* Estimate size of each board position, including innerborders and grid lines between positions. Inner borders and grid lines areproportional, with a minimum size of one pixel. Board squares (positions) must bekept ... square. */ hz = boardWidth / numCols; // possible pixels per column

  • 8/14/2019 17770121 Java Project XsieOsies

    124/153

    P a g e | 124

    vt = boardHeight / numRows; // possible pixels per row boardGridStep = (hz < vt) ?hz : vt; // choose smaller of the two sizes lineWidth = (int) (boardGridStep *0.03); // pixels for grid lines lineWidth = (lineWidth > 1) ? lineWidth : 1; //minimum of 1 pixel boardInnerBorder = (int) (boardGridStep * 0.06); // pixels forinner borders boardInnerBorder = (boardInnerBorder > 1) ? boardInnerBorder : 1; //minimum of 1 pixel

  • 8/14/2019 17770121 Java Project XsieOsies

    125/153

    P a g e | 125

    boardSymbolSize = boardGridStep lineWidth - (2 * boardInnerBorder); // pixels foreach position's player symbol boardSymbolSize = (boardSymbolSize > 10) ?boardSymbolSize : 10; // minimum of 10 pixels boardGridStep = boardSymbolSize + (2* boardInnerBorder) + lineWidth; // re-calculate: result will be positive /*Compute a new left margin and top margin so that our game board will be centeredon the panel. */

  • 8/14/2019 17770121 Java Project XsieOsies

    126/153

    P a g e | 126

    hz = (boardWidth - (numCols * boardGridStep) + lineWidth) / 2; if (hz < 0){ messageText.setText("Applet window is too narrow to display " + numCols + "columns."); hz = 0; } boardLeftMargin += hz; defined left border // plus // resetand continue

    vt = (boardHeight - (numRows * boardGridStep) + lineWidth) / 2; if (vt < 0) {

  • 8/14/2019 17770121 Java Project XsieOsies

    127/153

    P a g e | 127

    messageText.setText("Applet window is too short to display " + numRows + "rows."); vt = 0; } boardTopMargin += vt; defined top border // plus // reset andcontinue

    /* Draw vertical grid lines between columns. */ gr.setColor(ColorGRIDLINE); hz =boardLeftMargin + boardGridStep lineWidth; // x coordinate of first grid line

  • 8/14/2019 17770121 Java Project XsieOsies

    128/153

    P a g e | 128

    vt = (numRows * boardGridStep) lineWidth; // vertical pixels (constant) for (col =1; col < numCols; col ++) { gr.fillRect(hz, boardTopMargin, lineWidth, vt); hz +=boardGridStep; coordinate for next column } /* Draw horizontal grid lines betweenrows. */ vt = boardTopMargin + boardGridStep lineWidth; // y coordinate of firstgrid line // x

  • 8/14/2019 17770121 Java Project XsieOsies

    129/153

    P a g e | 129

    hz = (numCols * boardGridStep) lineWidth; // horizontal pixels (constant) for (row= 1; row < numRows; row ++) { gr.fillRect(boardLeftMargin, vt, hz, lineWidth); vt+= boardGridStep; coordinate for next row } /* Draw the board. */ vt =boardTopMargin + boardInnerBorder; // y coordinate of first position symbol in //y

  • 8/14/2019 17770121 Java Project XsieOsies

    130/153

    P a g e | 130

    // ... first column in first row for (row = 0; row < numRows; row ++) { hz =boardLeftMargin + boardInnerBorder; // x coordinate of first position symbol in //... first column in this row for (col = 0; col < numCols; col ++) { switch(boardData[row][col]) { case PlayCOMPUTER: has this position // computer

  • 8/14/2019 17770121 Java Project XsieOsies

    131/153

    P a g e | 131

    gr.setColor(ColorCOMPUTER); drawBigO(gr, hz, vt, boardSymbolSize); // draw "O"break; case PlayNONE: position // empty

    /* do nothing, paint nothing, keep background only */ break; case PlayUSER:position // user has this

    gr.setColor(ColorUSER); drawBigX(gr, hz, vt, boardSymbolSize); // draw "X" break;

  • 8/14/2019 17770121 Java Project XsieOsies

    132/153

  • 8/14/2019 17770121 Java Project XsieOsies

    133/153

    P a g e | 133

    System.out.println("error in paint(): bad boardData[" + row + "][" + col + "] = "+ boardData[row][col]); } hz += boardGridStep; coordinate for next column } vt +=boardGridStep; coordinate for next row } } // end of paint() method // y // x

    /* scanBoard() method

  • 8/14/2019 17770121 Java Project XsieOsies

    134/153

    P a g e | 134

    This is a general method to scan the game board to determine: (1) if there is awinner; (2) if the game is tied (no moves possible); (3) if the game is hopeless(empty positions but nobody can win); or (4) if the game should continue. The vscanBoard() method This is a general method to scan the game board todetermine: ariable will be set to if the game should end.

  • 8/14/2019 17770121 Java Project XsieOsies

    135/153

    P a g e | 135

    As an option, while this method is scanning the board, it will also estimate thevalue (to the computer) of each empty board position. This is an option because weonly need this information before the computer moves, not afterward. */ voidscanBoard( boolean valueFlag) estimate position values { int col; number (index)int colIncr; increment // temporary column // column // true if we

  • 8/14/2019 17770121 Java Project XsieOsies

    136/153

  • 8/14/2019 17770121 Java Project XsieOsies

    137/153

    P a g e | 137

    int row; number (index) int rowIncr; int value; estimated value

    // temporary row // row increment // temporary

    /* If there is no active game, then do nothing. */ if (gameState == PlayNONE)return; /* Clear our estimated values for each board position. */ if (valueFlag)estimated values // if caller wants

  • 8/14/2019 17770121 Java Project XsieOsies

    138/153

  • 8/14/2019 17770121 Java Project XsieOsies

    139/153

    P a g e | 139

    winning. (3) Third are empty paths, or paths with only computer positions. (4)Fourth are empty positions where the computer can block the user (that is, make apath useless to the user). This speeds up the end of the game, when the computercan no longer win. (5) Paths with at least one computer position and at least oneuser position are of no value to anyone. */ openComputerPaths = openUserPaths = 0;

  • 8/14/2019 17770121 Java Project XsieOsies

    140/153

    P a g e | 140

    for (path = 0; path < numPaths; path ++) { row = pathList[path][0]; // startingrow number (index) col = pathList[path][1]; // starting column number (index)rowIncr = pathList[path][2]; // row increment to next position colIncr =pathList[path][3]; // column increment to next position foundComputer = foundEmpty= foundTotal = foundUser = 0; while ((row >= 0) && (row < numRows) && (col >= 0)&& (col < numCols)) {

  • 8/14/2019 17770121 Java Project XsieOsies

    141/153

    P a g e | 141

    switch (boardData[row][col]) { case PlayCOMPUTER: computer's positionfoundComputer ++; break; case PlayNONE: position foundEmpty ++; break; casePlayUSER: foundUser ++; break; // user's position // empty //

  • 8/14/2019 17770121 Java Project XsieOsies

    142/153

    P a g e | 142

    default: (should not occur)

    // error checking

    System.out.println("error in scanBoard(): bad boardData[" + row + "][" + col + "]= " + boardData[row][col]); } foundTotal ++; total length of path row += rowIncr;next position col += colIncr; next position } /* A player wins if the number ofplayer positions is equal to the total // to compute // row index of // columnindex of

  • 8/14/2019 17770121 Java Project XsieOsies

    143/153

    P a g e | 143

    number of positions on this path. Check the user first, out of courtesy, eventhough both the computer and the user can't win at the same time ... unless thisprogram has a logic error. */ if (foundUser == foundTotal) // user wins{ gameState = PlayNONE; over // game is

    markWinningPath(pathList[path][0], pathList[path][1], rowIncr, colIncr);messageText.setText("You win! Congratulations!"); return; scanBoard() // losinggame ends

  • 8/14/2019 17770121 Java Project XsieOsies

    144/153

    P a g e | 144

    } if (foundComputer == foundTotal) // computer wins { gameState = PlayNONE; over// game is

    markWinningPath(pathList[path][0], pathList[path][1], rowIncr, colIncr);messageText.setText("The computer wins this game."); return; scanBoard() } /*Count how many paths are still available to each player (because the // winninggame ends

  • 8/14/2019 17770121 Java Project XsieOsies

    145/153

    P a g e | 145

    paths don't contain positions occupied by the other player). */ if (foundComputer== 0) computer is good for user openUserPaths ++; good path for user if (foundUser== 0) good for computer // no // one more

    // no user is // one

    openComputerPaths ++; more good path for computer

    /* Now do the optional work of estimating the value of each empty square on thispath. */

  • 8/14/2019 17770121 Java Project XsieOsies

    146/153

    P a g e | 146

    if (valueFlag) estimated values {

    // if caller wants

    value = 0; // assume empty position has no value /* Single empty squares that willend the game have greater value. */ if ((foundComputer + foundEmpty) ==foundTotal) value += (foundEmpty == 1) ? ValueWINCOMP : ValueOPENCOMP; if((foundUser + foundEmpty) == foundTotal) value += (foundEmpty == 1) ? ValueWINUSER: ValueOPENUSER;

  • 8/14/2019 17770121 Java Project XsieOsies

    147/153

    P a g e | 147

    /* Add the estimated value to each empty position on this path. */ if (value > 0)if something to add! { row = pathList[path][0]; // starting row number (index) col= pathList[path][1]; // starting column number (index) rowIncr =pathList[path][2]; // row increment to next position colIncr = pathList[path][3];// column increment to next position // do this work only

  • 8/14/2019 17770121 Java Project XsieOsies

    148/153

    P a g e | 148

    while ((row >= 0) && (row < numRows) && (col >= 0) && (col < numCols)) { if(boardData[row][col] == PlayNONE) boardValues[row][col] += value; row += rowIncr;next position col += colIncr; next position } } } } // end of for path loop // rowindex of // column index of

  • 8/14/2019 17770121 Java Project XsieOsies

    149/153

    P a g e | 149

    /* We looked once at every path. Nobody won. If there are no more empty positions,then the game is tied. We detect a tie game when all paths are "dead" becausenobody can win. */ if ((openComputerPaths == 0) && (openUserPaths == 0)){ gameState = PlayNONE; over // game is

    messageText.setText("Nobody can win this game. The game is tied."); // return;ends scanBoard() } // hopeless situation

  • 8/14/2019 17770121 Java Project XsieOsies

    150/153

    P a g e | 150

    } // end of scanBoard() method } // end of TicTacToe4 class //------------------------------------------------------------------------ // /*TicTacToe4Window class This applet can also be run as an application by callingthe main() method instead of the init() method. As an application, it must exitwhen its main window is closed. A window listener is necessary becauseEXIT_ON_CLOSE is a

  • 8/14/2019 17770121 Java Project XsieOsies

    151/153

  • 8/14/2019 17770121 Java Project XsieOsies

    152/153

    P a g e | 152

  • 8/14/2019 17770121 Java Project XsieOsies

    153/153