Friday, 25 July 2014

Tic Tac Toe without graphics

                                                                          CODE

import java.util.Scanner;

public class TicTacToeBasic {

   // Name-constants to represent the seeds and cell contents

   public static final int EMPTY = 0;
   public static final int CROSS = 1;
   public static final int NOUGHT = 2;

   // Name-constants to represent the various states of the game

   public static final int PLAYING = 0;
   public static final int DRAW = 1;
   public static final int CROSS_WON = 2;
   public static final int NOUGHT_WON = 3;

   // The game board and the game status

   public static final int ROWS = 3, COLS = 3; // number of rows and columns

   public static int[][] board = new int[ROWS][COLS]; // game board in 2D array
                                                      //  containing (EMPTY, CROSS, NOUGHT)

   public static int currentState;  // the current state of the game
                                    // (PLAYING, DRAW, CROSS_WON, NOUGHT_WON)

   public static int currentPlayer; // the current player (CROSS or NOUGHT)
   public static int currntRow, currentCol; // current seed's row and column

   public static Scanner in = new Scanner(System.in); // the input Scanner

   /** The entry main method (the program starts here)
     * @param args */

   public static void main(String[] args) {

      // Initialize the game-board and current status

      initGame();

      // Play the game once
      do {

         playerMove(currentPlayer); // update currentRow and currentCol
         updateGame(currentPlayer, currntRow, currentCol); // update currentState
         printBoard();

         // Print message if game-over
         if (currentState == CROSS_WON) {
            System.out.println("'X' won! Bye!");
         } else if (currentState == NOUGHT_WON) {
            System.out.println("'O' won! Bye!");
         } else if (currentState == DRAW) {
            System.out.println("It's a Draw! Bye!");
         }

         // Switch player
         currentPlayer = (currentPlayer == CROSS) ? NOUGHT : CROSS;
      } while (currentState == PLAYING); // repeat if not game-over
   }

   /** Initialize the game-board contents and the current states */

   public static void initGame() {
      for (int row = 0; row < ROWS; ++row) {
         for (int col = 0; col < COLS; ++col) {
            board[row][col] = EMPTY;  // all cells empty
         }
      }
      currentState = PLAYING; // ready to play
      currentPlayer = CROSS;  // cross plays first
   }

   /** Player with the "theSeed" makes one move, with input validation.
       Update global variables "currentRow" and "currentCol".
     * @param theSeed */

   public static void playerMove(int theSeed) {

      boolean validInput = false;  // for input validation

      do {
         if (theSeed == CROSS) {
            System.out.print("Player 'X', enter your move (row[1-3] column[1-3]): ");
         } else {
            System.out.print("Player 'O', enter your move (row[1-3] column[1-3]): ");
         }
         int row = in.nextInt() - 1;  // array index starts at 0 instead of 1
         int col = in.nextInt() - 1;
         if (row >= 0 && row < ROWS && col >= 0 && col < COLS && board[row][col] == EMPTY) {
            currntRow = row;
            currentCol = col;
            board[currntRow][currentCol] = theSeed;  // update game-board content
            validInput = true;  // input okay, exit loop
         } else {
            System.out.println("This move at (" + (row + 1) + "," + (col + 1)
                  + ") is not valid. Try again...");
         }
      } while (!validInput);  // repeat until input is valid
   }

   /** Update the "currentState" after the player with "theSeed" has placed on
       (currentRow, currentCol).
     * @param theSeed
     * @param currentRow
     * @param currentCol */

   public static void updateGame(int theSeed, int currentRow, int currentCol) {
      if (hasWon(theSeed, currentRow, currentCol)) {
       // check if winning move
         currentState = (theSeed == CROSS) ? CROSS_WON : NOUGHT_WON;
      }
      else if (isDraw()) {  
       // check for draw
         currentState = DRAW;
      }
      // Otherwise, no change to currentState (still PLAYING).
   }

   /** Return true if it is a draw (no more empty cell)
     * @return  */

   public static boolean isDraw() {
      for (int row = 0; row < ROWS; ++row) {
         for (int col = 0; col < COLS; ++col) {
            if (board[row][col] == EMPTY) {
               return false;  // an empty cell found, not draw, exit
            }
         }
      }
      return true;  // no empty cell, it's a draw
   }

   /** Return true if the player with "theSeed" has won after placing at
       (currentRow, currentCol)
     * @param theSeed
     * @param currentRow
     * @param currentCol
     * @return  */

   public static boolean hasWon(int theSeed, int currentRow, int currentCol) {
      return (board[currentRow][0] == theSeed         // 3-in-the-row
                   && board[currentRow][1] == theSeed
                   && board[currentRow][2] == theSeed
              || board[0][currentCol] == theSeed      // 3-in-the-column
                   && board[1][currentCol] == theSeed
                   && board[2][currentCol] == theSeed
              || currentRow == currentCol            // 3-in-the-diagonal
                   && board[0][0] == theSeed
                   && board[1][1] == theSeed
                   && board[2][2] == theSeed
              || currentRow + currentCol == 2  // 3-in-the-opposite-diagonal
                   && board[0][2] == theSeed
                   && board[1][1] == theSeed
                   && board[2][0] == theSeed);
   }

   /** Print the game board */

   public static void printBoard() {
      for (int row = 0; row < ROWS; ++row) {
         for (int col = 0; col < COLS; ++col) {
            printCell(board[row][col]); // print each of the cells
            if (col != COLS - 1) {
               System.out.print("|");   // print vertical partition
            }
         }
         System.out.println();
         if (row != ROWS - 1) {
            System.out.println("-----------"); // print horizontal partition
         }
      }
      System.out.println();
   }

   /** Print a cell with the specified "content"
     * @param content */

   public static void printCell(int content) {
      switch (content) {
         case EMPTY:  System.out.print("   "); break;
         case NOUGHT: System.out.print(" O "); break;
         case CROSS:  System.out.print(" X "); break;
      }
   }
}

                                             OUTPUT



Thursday, 24 July 2014

Tic Tac Toe

CODE

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TicTacToe extends JFrame {

   // Named-constants for the game board

   public static final int ROWS = 3;  // ROWS by COLS cells
   public static final int COLS = 3;

   // Named-constants of the various dimensions used for graphics drawing

   public static final int CELL_SIZE = 100; // cell width and height (square)
   public static final int CANVAS_WIDTH = CELL_SIZE * COLS;  // the drawing canvas
   public static final int CANVAS_HEIGHT = CELL_SIZE * ROWS;
   public static final int GRID_WIDTH = 8;                   // Grid-line's width
   public static final int GRID_WIDHT_HALF = GRID_WIDTH / 2; // Grid-line's half-width

   // Symbols (cross/nought) are displayed inside a cell, with padding from border

   public static final int CELL_PADDING = CELL_SIZE / 6;
   public static final int SYMBOL_SIZE = CELL_SIZE - CELL_PADDING * 2; // width/height
   public static final int SYMBOL_STROKE_WIDTH = 8; // pen's stroke width

   // Use an enumeration (inner class) to represent the various states of the game

   public enum GameState {
      PLAYING, DRAW, CROSS_WON, NOUGHT_WON
   }
   private GameState currentState;  // the current game state

   // Use an enumeration (inner class) to represent the seeds and cell contents

   public enum Seed {
      EMPTY, CROSS, NOUGHT
   }
   private Seed currentPlayer;  // the current player

   private Seed[][] board   ; // Game board of ROWS-by-COLS cells
   private final DrawCanvas canvas; // Drawing canvas (JPanel) for the game board
   private final JLabel statusBar;  // Status Bar

   /** Constructor to setup the game and the GUI components */

   public TicTacToe() {
      canvas = new DrawCanvas();  // Construct a drawing canvas (a JPanel)
      canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));

      // The canvas (JPanel) fires a MouseEvent upon mouse-click

      canvas.addMouseListener(new MouseAdapter() {
         @Override
         public void mouseClicked(MouseEvent e) {  // mouse-clicked handler
            int mouseX = e.getX();
            int mouseY = e.getY();

            // Get the row and column clicked
            int rowSelected = mouseY / CELL_SIZE;
            int colSelected = mouseX / CELL_SIZE;

            if (currentState == GameState.PLAYING) {
               if (rowSelected >= 0 && rowSelected < ROWS && colSelected >= 0
                     && colSelected < COLS && board[rowSelected][colSelected] == Seed.EMPTY) {
                  board[rowSelected][colSelected] = currentPlayer; // Make a move
                  updateGame(currentPlayer, rowSelected, colSelected); // update state
                  // Switch player
                  currentPlayer = (currentPlayer == Seed.CROSS) ? Seed.NOUGHT : Seed.CROSS;
               }
            } else {       // game over
               initGame(); // restart the game
            }
            // Refresh the drawing canvas
            repaint();  // Call-back paintComponent().
         }
      });

      // Setup the status bar (JLabel) to display status message

      statusBar = new JLabel("  ");
      statusBar.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 15));
      statusBar.setBorder(BorderFactory.createEmptyBorder(2, 5, 4, 5));

      Container cp = getContentPane();
      cp.setLayout(new BorderLayout());
      cp.add(canvas, BorderLayout.CENTER);
      cp.add(statusBar, BorderLayout.PAGE_END); // same as SOUTH

      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      pack();  // pack all the components in this JFrame
      setTitle("Tic Tac Toe");
      setVisible(true);  // show this JFrame

      board = new Seed[ROWS][COLS]; // allocate array
      initGame(); // initialize the game board contents and game variables
   }

   /** Initialize the game-board contents and the status */

   public void initGame() {
      for (int row = 0; row < ROWS; ++row) {
         for (int col = 0; col < COLS; ++col) {
            board[row][col] = Seed.EMPTY; // all cells empty
         }
      }
      currentState = GameState.PLAYING; // ready to play
      currentPlayer = Seed.CROSS;       // cross plays first
   }

   /** Update the currentState after the player with "theSeed" has placed on
       (rowSelected, colSelected).
     * @param theSeed
     * @param rowSelected
     * @param colSelected */

   public void updateGame(Seed theSeed, int rowSelected, int colSelected) {
      if (hasWon(theSeed, rowSelected, colSelected)) {  // check for win
         currentState = (theSeed == Seed.CROSS) ? GameState.CROSS_WON : GameState.NOUGHT_WON;
      } else if (isDraw()) {  // check for draw
         currentState = GameState.DRAW;
      }
      // Otherwise, no change to current state (still GameState.PLAYING).
   }

   /** Return true if it is a draw (i.e., no more empty cell)
     * @return  */

   public boolean isDraw() {
      for (int row = 0; row < ROWS; ++row) {
         for (int col = 0; col < COLS; ++col) {
            if (board[row][col] == Seed.EMPTY) {
               return false; // an empty cell found, not draw, exit
            }
         }
      }
      return true;  // no more empty cell, it's a draw
   }

   /** Return true if the player with "theSeed" has won after placing at
       (rowSelected, colSelected)
     * @param theSeed
     * @param rowSelected
     * @param colSelected
     * @return  */

   public boolean hasWon(Seed theSeed, int rowSelected, int colSelected) {
      return (board[rowSelected][0] == theSeed  // 3-in-the-row
            && board[rowSelected][1] == theSeed
            && board[rowSelected][2] == theSeed
       || board[0][colSelected] == theSeed      // 3-in-the-column
            && board[1][colSelected] == theSeed
            && board[2][colSelected] == theSeed
       || rowSelected == colSelected            // 3-in-the-diagonal
            && board[0][0] == theSeed
            && board[1][1] == theSeed
            && board[2][2] == theSeed
       || rowSelected + colSelected == 2  // 3-in-the-opposite-diagonal
            && board[0][2] == theSeed
            && board[1][1] == theSeed
            && board[2][0] == theSeed);
   }

   /**
    *  Inner class DrawCanvas (extends JPanel) used for custom graphics drawing.
    */

   class DrawCanvas extends JPanel {
      @Override
      public void paintComponent(Graphics g) {  // invoke via repaint()
         super.paintComponent(g);    // fill background
         setBackground(Color.WHITE); // set its background color

         // Draw the grid-lines
         g.setColor(Color.LIGHT_GRAY);
         for (int row = 1; row < ROWS; ++row) {
            g.fillRoundRect(0, CELL_SIZE * row - GRID_WIDHT_HALF,
                  CANVAS_WIDTH-1, GRID_WIDTH, GRID_WIDTH, GRID_WIDTH);
         }
         for (int col = 1; col < COLS; ++col) {
            g.fillRoundRect(CELL_SIZE * col - GRID_WIDHT_HALF, 0,
                  GRID_WIDTH, CANVAS_HEIGHT-1, GRID_WIDTH, GRID_WIDTH);
         }

         // Draw the Seeds of all the cells if they are not empty
         // Use Graphics2D which allows us to set the pen's stroke

         Graphics2D g2d = (Graphics2D)g;
         g2d.setStroke(new BasicStroke(SYMBOL_STROKE_WIDTH, BasicStroke.CAP_ROUND,
               BasicStroke.JOIN_ROUND));  // Graphics2D only
         for (int row = 0; row < ROWS; ++row) {
            for (int col = 0; col < COLS; ++col) {
               int x1 = col * CELL_SIZE + CELL_PADDING;
               int y1 = row * CELL_SIZE + CELL_PADDING;
               if (board[row][col] == Seed.CROSS) {
                  g2d.setColor(Color.RED);
                  int x2 = (col + 1) * CELL_SIZE - CELL_PADDING;
                  int y2 = (row + 1) * CELL_SIZE - CELL_PADDING;
                  g2d.drawLine(x1, y1, x2, y2);
                  g2d.drawLine(x2, y1, x1, y2);
               } else if (board[row][col] == Seed.NOUGHT) {
                  g2d.setColor(Color.BLUE);
                  g2d.drawOval(x1, y1, SYMBOL_SIZE, SYMBOL_SIZE);
               }
            }
         }

         // Print status-bar message

         if (currentState == GameState.PLAYING) {
            statusBar.setForeground(Color.BLACK);
            if (currentPlayer == Seed.CROSS) {
               statusBar.setText("X's Turn");
            } else {
               statusBar.setText("O's Turn");
            }
         } else if (currentState == GameState.DRAW) {
            statusBar.setForeground(Color.RED);
            statusBar.setText("It's a Draw! Click to play again.");
         } else if (currentState == GameState.CROSS_WON) {
            statusBar.setForeground(Color.RED);
            statusBar.setText("'X' Won! Click to play again.");
         } else if (currentState == GameState.NOUGHT_WON) {
            statusBar.setForeground(Color.RED);
            statusBar.setText("'O' Won! Click to play again.");
         }
      }
   }

   /** The entry main() method
     * @param args */

   public static void main(String[] args) {
      // Run GUI codes in the Event-Dispatching thread for thread safety
      SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
             TicTacToe ticTacToe = new TicTacToe(); // Let the constructor do the job
         }
      });
   }
}

    OUTPUT 





Wednesday, 16 July 2014

Java EE

             Java Enterprise Edition is Oracles's enterprise Java computing platform. It was earlier called J2EE , Java 2 Platform, Enterprise Edition. But since the 5th edition , "2" has been dropped from its name.Some people have started to call it JEE .There is nothing named JEE ! Never use that name ! The correct name is Java EE.

             One of the big reasons that the name was changed is because we wanted to emphasize on the fact that all the platforms are "Java" . The old names J2EE, J2ME and J2SE don't do that .

INTRODUCTION

Java EE is an ongoing standard for producing scalable, highly-available and secure enterprise applications .The standard defines that "Services should be provided by Servers" that support Java EE. These servers supply Java EE containers in which Java EE components will execute.


DISTRIBUTED MULTI-TIERED APPLICATIONS

The Java EE platform uses a multitiered distributed application model for both enterprise applications. Application logic is divided into components according to function, and the various application components that make up a Java EE application are installed on different machines depending on the tier in the multitiered Java EE environment to which the application component belongs.
    
        - Client-tier components run on the client machine.

        - Web-tier components run on the Java EE server.

        - Business-tier components run on the Java EE server.

        - Enterprise information system (EIS)-tier software runs on the EIS server.


MULTI-TIERED APPLICATIONS


Java EE COMPONENTS


Java EE applications are made up of components. A Java EE component is a self-contained functional software unit that is assembled into a Java EE application with its related classes and files and that communicates with other components. The Java EE specification defines the following components:

         - Application clients and applets are components that run on the client.
        
         - Java Servlet and JavaServer Pages (JSP) technology components are Web components that run on the server.

         - Enterprise JavaBeans (EJB) components (enterprise beans) are Business components that run on the server.


          J2EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between J2EE components and "standard" Java classes is that J2EE components are assembled into a J2EE application, verified to be well formed and in compliance with the J2EE specification, and deployed to production, where they are run and managed by the J2EE server.


CLIENT COMPONENTS

It is of two types : web client and application client 

Web Client : 

A Web client consists of two parts:

- Dynamic Web pages containing various types of markup language (HTML, XML, and so on), which are generated by Web components running in the Web tier, and a

- Web browser, which renders the pages received from the server.


A Web client is sometimes called a thin client. Thin clients usually do not do things like query databases, execute complex business rules, or connect to legacy applications. 

Application Client :

A Java EE application client runs on a client machine and provides a way for users to handle tasks that require a richer user interface than can be provided by a markup language. 

It typically has a graphical user interface (GUI) created from Swing or Abstract Window Toolkit (AWT) APIs, but a command-line interface is certainly possible.

Application clients directly access enterprise beans running in the business tier. However, if application requirements warrant it, a Java EE application client can open an HTTP connection to establish communication with a servlet running in the Web tier.
























WEB COMPONENTS

Java EE Web components can be either servlets or JSP pages.

-  Servlets are Java programming language classes that dynamically process requests and construct responses.

-  JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.

NOTE : Static HTML pages and applets are bundled with Web components during application assembly, but are not considered Web components by the Java EE specification. Server-side utility classes can also be bundled with Web components and, like HTML pages, are not considered Web components.




BUSINESS COMPONENTS

Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. 

                          Enterprise bean receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.




There are three kinds of enterprise beans: 

-  Session beans :
     It represents a transient conversation with a client. When the client finishes executing, the session bean and its data are gone. 

-  Entity beans :
    It represents persistent data stored in one row of a database table. If the client terminates or if the server shuts down, the underlying services ensure that the entity bean data is saved.

-  Message-driven beans :
   It combines features of a session bean and a Java Message Service ("JMS") message listener, allowing a business component to receive JMS messages asynchronously.


 For information on message-driven beans


ENTERPRISE INFORMATION SYSTEM TIER

It handles Java EE architecture connectivity to the resources that are not a part of Java EE .These include variety of services such as :

- Enterprise Resource Planning (ERP)
- Database Systems
- Legacy Information Systems

Java EE application components might need access to enterprise information systems for database connectivity.


We have used a lot of new terms in this post but as you will read more thing will become clearer.
Here are some links that I found useful :

http://docs.oracle.com/javaee/6/tutorial/doc/
http://www.deknight.com/java/jee-architecture-java-enterprise-edition-architecture.html
http://www.slideshare.net/keshabnath/j2-ee-container-components

Wednesday, 9 July 2014

Inner Class in Java

In the previous posts we have seen how to put a button on a JFrame. Today we will see how to put two buttons on a frame . This could be easily done . But how to get action events for two different buttons when each button needs to do something different ?


POSSIBLE OPTIONS :

(1) Implement two actionPerformed() methods

     class MyGui implements ActionListener{
               // coding goes here

              public void actionPerformed(ActionEvent event){
                 frame.repaint ( ) ;
             }
            public void actionPerformed(ActionEvent event){
                 label.setText("Hello !!") ;
            }
        }

                         There's flaw in it !! We can't do this. The same method cannot be implemented twice in a Java class.It will not compile and secondly, how would the event source (button) know which of the methods to call.

(2) Creating two separate ActionListener classes

     class MyGui {
       
            JFrame frame ;
            Jlabel label ;
            void gui ( ) {
              // code to instantiate the two listeners and register one with the color button
              // and the other with label button .
           }
     }
   class ColorButtonListener implements ActionListener {
       public static void main ( String args [ ] ){
          frame.repaint() ;
       }
   }
  class LabelButtonListener implements ActionListener {
       public static void main ( String args [ ] ){
          label.setText("Hello !!") ;
       }
   }

         These classes won't have access to the variables they need to act on 'frame' and 'label' .


SOLUTION : INNER CLASS :

Simple inner class :

class MyOuterClass {

     private int x ;
     class MyInnerClass {
         void go( ){
            x = 42 ;           // uses 'x' as if it were a variable of the inner class
         }
      }
 }

An inner class gets access to use the outer class's variables and methods even if they are private. We will be continuing with the example which we used in the last post.



OUTPUT :











WHEN WE CLICK THE CHANGE COLOR BUTTON THE COLOR CHANGES !!






WHEN WE CLICK THE CHANGE LABEL BUTTON THE LABEL ON THE LEFT SIDE CHANGES ALONG WITH THE CHANGE IN CIRCLE COLOR (this is because the circle changes color every time a button gets clicked)

Monday, 7 July 2014

Graphics using Swing Package

In the previous post we saw how to use JFrame . What if you want to add your own graphics on the screen?? The best way is to make a paintable widget and then we just need to add that button to our frame just like a button . The widget can have moving images or make color change every time you click a button and much more.....


EXAMPLE :




OUTPUT:




Now let's make a program that causes the figure to change its color every time it is clicked by the user !! We will be using Graphics2D class because we want the color of the figure to be decided at compile time and such things can be performed by using Graphics2D object.




OUTPUT :








You might be still confused about JPanel and JFrame. I found the following links to be quite helpful :D