You are on page 1of 22

1.

INTRODUCTION
This case study “Tic-tac-toe” it is a game was implemented using java awt, swings and java
applets.

Java programming language was originally developed by Sun Microsystems which was initiated
by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform
(Java 1.0 [J2SE]).

The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and
its widespread popularity, multiple configurations were built to suit various types of platforms.
For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.

The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is
guaranteed to be Write Once, Run Anywhere.

Java is −

 Object Oriented: In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.

 Platform Independent: unlike many other programming languages including C and


C++, when Java is compiled, it is not compiled into platform specific machine, rather
into platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.

 Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP
Java, it would be easy to master.

 Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.

 Architecture-neutral: Java compiler generates an architecture-neutral object file format,


which makes the compiled code executable on many processors, with the presence of
Java runtime system.
 Portable: Being architecture-neutral and having no implementation dependent aspects of
the specification makes Java portable. Compiler in Java is written in ANSI C with a
clean portability boundary, which is a POSIX subset.

 Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.

 Multithreaded: With Java's multithreaded feature it is possible to write programs that


can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly.

 Interpreted: Java byte code is translated on the fly to native machine instructions and is
not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light-weight process.

 High Performance: with the use of Just-In-Time compilers, Java enables high
performance.

 Distributed: Java is designed for the distributed environment of the internet.

 Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to


adapt to an evolving environment. Java programs can carry extensive amount of run-
time information that can be used to verify and resolve accesses to objects on run-time.

1. 1 Java AWT

AWT stands for Abstract Window Toolkit. It is a platform dependent API for creating
Graphical User Interface (GUI) for java programs.

Java AWT calls native platform (Operating systems) subroutine for creating components such as
textbox, checkbox, button etc. For example an AWT GUI having a button would have a different
look and feel across platforms like windows, Mac OS & Unix, this is because these platforms
have different look and feel for their native buttons and AWT directly calls their native
subroutine that creates the button. In simple, an application build on AWT would look like a
windows application when it runs on Windows, but the same application would look like a Mac
application when runs on Mac OS.

AWT is rarely used now days because of its platform dependent and heavy-weight nature. AWT
components are considered heavy weight because they are being generated by underlying
operating system (OS). For example if you are instantiating a text box in AWT that means you
are actually asking OS to create a text box for you.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

Components and containers

All the elements like buttons, text fields, scrollbars etc. are known as components. In AWT we
have classes for each component as shown in the above diagram. To have everything placed on a
screen to a particular position, we have to add them to a container. A container is like a screen
wherein we are placing components like buttons, text fields, checkbox etc. In short a container
contains and controls the layout of components. A container itself is a component (shown in the
above hierarchy diagram) thus we can add a container inside container.
Types of containers:

As explained above, a container is a place wherein we add components like text field, button,
checkbox etc. There are four types of containers available in AWT: Window, Frame, Dialog and
Panel. As shown in the hierarchy diagram above, Frame and Dialog are subclasses of Window
class.

Window: An instance of the Window class has no border and no title.


Dialog: Dialog class has border and title. An instance of the Dialog class cannot exist without an
associated instance of the Frame class.

Panel: Panel does not contain title bar, menu bar or border. It is a generic container for holding
components. An instance of the Panel class provides a container to which to add components.
Frame: A frame has title, border and menu bars. It can contain several components like buttons,
text fields, scrollbars etc. This is most widely used container while developing an application in
AWT.

1.2 Java Swing

Swing is a part of Java Foundation classes (JFC), the other parts of JFC are java2D and Abstract
window toolkit (AWT). AWT, Swing & Java 2D are used for building graphical user interfaces
(GUIs) in java. In this tutorial we will mainly discuss about Swing API which is used for
building GUIs on the top of AWT and are much more light-weight compared to AWT.

In the above example we have used several components.

JFrame – A frame is an instance of JFrame. Frame is a window that can have title, border,
menu, buttons, text fields and several other components. A Swing application must have a frame
to have the components added to it.

JPanel – A panel is an instance of JPanel. A frame can have more than one panels and each
panel can have several components. You can also call them parts of Frame. Panels are useful for
grouping components and placing them to appropriate locations in a frame.
JLabel – A label is an instance of JLabel class. A label is an unselectable text and images. If you
want to display a string or an image on a frame, you can do so by using labels.

JTextField – Used for capturing user inputs, these are the text boxes where user enters the data.

JPasswordField – Similar to text fields but the entered data gets hidden and displayed as dots on
GUI.

JButton – A button is an instance of JButton class.

Java swing Hierarchy

The hierarchy of Java swing classes are given below.

1.3 Java applet

Applets are small Java applications that can be accessed on an Internet server, transported over
Internet, and can be automatically installed and run as a part of a web document. After a user
receives an applet, the applet can produce a graphical user interface. It has limited access to
resources so that it can run complex computations without introducing the risk of viruses or
breaching data integrity. Any applet in Java is a class that extends the java.applet.Applet class.
An Applet class does not have any main () method. It is viewed using JVM. The JVM can use
either a plug-in of the Web browser or a separate runtime environment to run an applet
application. JVM creates an instance of the applet class and invokes init() method to initialize an
Applet.

Applet class
Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet. It also provide methods that load and display images and methods that load
and play audio clips.

An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.

 init() : init() is the first method to be called. This is where variable are initialized. This
method is called only once during the runtime of applet.
 start() : start() method is called after init(). This method is called to restart an applet after
it has been stopped.
 stop() : stop() method is called to suspend thread that does not need to run when applet is
not visible.
 destroy() : destroy() method is called when your applet needs to be removed completely
from memory.

The hierarchy of Java applet classes


1.1ABOUT THE CASE STUDY

Tic-tac-toe is a simple, two-player game that, if played optimally by both players, will always
result in a tie. The game is also called noughts and crosses or Xs and Os.

Tic-tac-toe is a game that is traditionally played by being drawn on paper, and it can be played
on a computer or on a variety of media. Other games, such as Connect 4, are based on this
classic.

History of Tic-Tac-Toe

An early variation of the game was played in the Roman Empire, around the 1st century B.C. It
was called "Terni lapilli," which means "three pebbles at a time." The game's grid markings have
been found chalked all over Roman ruins. Evidence of the game was also found in ancient
Egyptian ruins. The first print reference to "noughts and crosses," the British name for the game,
appeared in 1864. The first print reference to a game called "tick-tack-toe" occurred in 1884 but
referred to a children's game played on a slate.

More Advanced Tic-Tac-Toe

A relatively simple game usually played on a grid of 3-by-3 squares, tic-tac-toe is mainly
enjoyed by children. Tic-tac-toe can be made significantly more complex by increasing the size
of the board to 4-by-4, 5-by-5, or even up to a 20-by-20 grid.

Gameplay

The goal of tic-tac-toe is to be the first player to get three in a row on a 3-by-3 grid or four in a
row in a 4-by-4 grid.

To start, one player draws a board, creating a grid of squares, usually 3-by-3 or 4-by-4.In a 3-by-
3 grid game, the player who is playing "X" always goes first. Players alternate placing Xs and Os
on the board until either player has three in a row, horizontally, vertically, or diagonally or until
all squares on the grid are filled. If a player is able to draw three Xs or three Os in a row, then
that player wins. If all squares are filled and neither player has made a complete row of Xs or Os,
then the game is a draw.
One of the game's best strategies involves creating a "fork," which is placing your mark in such a
way that you have the opportunity to win two ways on your next turn. Your opponent can only
block one, thereby, you can win after that. The gameplay is the same if you are playing on a 4-
by-4 grid. The "X" player goes first. And, players alternate placing Xs and Os on the board until
a row is completed horizontally, vertically, or diagonally, or all 16 squares are filled. If all 16
squares are filled and neither player has four in a row, the game is a draw.

Other Variants

Tic-tac-toe can be also be played on a 5-by-5 grid with each player trying to get five in a row.
The game can also be played on larger grids, such as 10-by-10 or even 20-by-20. For any grid of
6-by-6 or greater, it might be best to make your goal to get five in a row. This turns the basic
game of tic-tac-toe into a much more complex game with similarities to the board game Pente,
meaning "five" in Greek. Similarly, the goal of Pente is for a player to score five marks in a row.
2. HARDWARE AND SOFTWARE SPECIFICATION

HARDWARE SPECIFICATIONS

The selection of hardware configuration is very important task related to the software
development. Insufficient RAM may affect adversely on the speed and efficiency of the entire
system. The processor should be powerful to handle the entire operations. The hard disk should
have sufficient capacity to store the file applications.

Processor : Intel Pentium Processor

RAM : 2 GB

Hard disk capacity : 40 GB

Monitor : SVGA color monitor

Keyboard : 108 keys and above

Mouse : 3 Buttons

SOFTWARE SPECIFICATIONS

The software is desired for JAVA version 7 or later. It can also work in Windows 7 or later
version.

Front end : JAVA

OS : Windows 7

Back end : NETBEANS


3. SCREENLAYOUT
4. CODING
import java.awt.*;

import java.awt.event.*;

import java.awt.geom.*;

import javax.swing.*;

import javax.swing.event.*;

import java.util.Random;

import java.applet.*;

public class TicTacToeApplet extends JApplet implements ChangeListener, ActionListener {

private JSlider slider;

private JButton oButton, xButton;

private Board board;

private int lineThickness=4;

private Color oColor=Color.BLUE, xColor=Color.RED;

static final char BLANK=' ', O='O', X='X';

private char position[]={ // Board position (BLANK, O, or X)

BLANK, BLANK, BLANK,

BLANK, BLANK, BLANK,

BLANK, BLANK, BLANK};

private int wins=0, losses=0, draws=0; // game count by user

// Initialize

public void init() {

JPanel topPanel=new JPanel();

topPanel.setLayout(new FlowLayout());

topPanel.add(new JLabel("Line Thickness:"));


topPanel.add(slider=new JSlider(SwingConstants.HORIZONTAL, 1, 20, 4));

slider.setMajorTickSpacing(1);

slider.setPaintTicks(true);

slider.addChangeListener(this);

topPanel.add(oButton=new JButton("O Color"));

topPanel.add(xButton=new JButton("X Color"));

oButton.addActionListener(this);

xButton.addActionListener(this);

add(topPanel, BorderLayout.NORTH);

add(board=new Board(), BorderLayout.CENTER);

setVisible(true);

// Change line thickness

public void stateChanged(ChangeEvent e) {

lineThickness = slider.getValue();

board.repaint();

// Change color of O or X

public void actionPerformed(ActionEvent e) {

if (e.getSource()==oButton) {

Color newColor = JColorChooser.showDialog(this, "Choose a new color for O", oColor);

if (newColor!=null)

oColor=newColor;

else if (e.getSource()==xButton) {
Color newColor = JColorChooser.showDialog(this, "Choose a new color for X", xColor);

if (newColor!=null)

xColor=newColor;

board.repaint();

// Board is what actually plays and displays the game

private class Board extends JPanel implements MouseListener {

private Random random=new Random();

private int rows[][]={{0,2},{3,5},{6,8},{0,6},{1,7},{2,8},{0,8},{2,6}};

// Endpoints of the 8 rows in position[] (across, down, diagonally)

public Board() {

addMouseListener(this);

// Redraw the board

public void paintComponent(Graphics g) {

super.paintComponent(g);

int w=getWidth();

int h=getHeight();

Graphics2D g2d = (Graphics2D) g;

// Draw the grid

g2d.setPaint(Color.WHITE);

g2d.fill(new Rectangle2D.Double(0, 0, w, h));

g2d.setPaint(Color.BLACK);

g2d.setStroke(new BasicStroke(lineThickness));
g2d.draw(new Line2D.Double(0, h/3, w, h/3));

g2d.draw(new Line2D.Double(0, h*2/3, w, h*2/3));

g2d.draw(new Line2D.Double(w/3, 0, w/3, h));

g2d.draw(new Line2D.Double(w*2/3, 0, w*2/3, h));

// Draw the Os and Xs

for (int i=0; i<9; ++i) {

double xpos=(i%3+0.5)*w/3.0;

double ypos=(i/3+0.5)*h/3.0;

double xr=w/8.0;

double yr=h/8.0;

if (position[i]==O) {

g2d.setPaint(oColor);

g2d.draw(new Ellipse2D.Double(xpos-xr, ypos-yr, xr*2, yr*2));

else if (position[i]==X) {

g2d.setPaint(xColor);

g2d.draw(new Line2D.Double(xpos-xr, ypos-yr, xpos+xr, ypos+yr));

g2d.draw(new Line2D.Double(xpos-xr, ypos+yr, xpos+xr, ypos-yr));

// Draw an O where the mouse is clicked

public void mouseClicked(MouseEvent e) {


int xpos=e.getX()*3/getWidth();

int ypos=e.getY()*3/getHeight();

int pos=xpos+3*ypos;

if (pos>=0 && pos<9 && position[pos]==BLANK) {

position[pos]=O;

repaint();

putX(); // computer plays

repaint();

// Ignore other mouse events

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

// Computer plays X

void putX() {

// Check if game is over

if (won(O))

newGame(O);

else if (isDraw())

newGame(BLANK);
// Play X, possibly ending the game

else {

nextMove();

if (won(X))

newGame(X);

else if (isDraw())

newGame(BLANK);

// Return true if player has won

boolean won(char player) {

for (int i=0; i<8; ++i)

if (testRow(player, rows[i][0], rows[i][1]))

return true;

return false;

// Has player won in the row from position[a] to position[b]?

boolean testRow(char player, int a, int b) {

return position[a]==player && position[b]==player

&& position[(a+b)/2]==player;

// Play X in the best spot

void nextMove() {

int r=findRow(X); // complete a row of X and win if possible


if (r<0)

r=findRow(O); // or try to block O from winning

if (r<0) { // otherwise move randomly

do

r=random.nextInt(9);

while (position[r]!=BLANK);

position[r]=X;

// Return 0-8 for the position of a blank spot in a row if the

// other 2 spots are occupied by player, or -1 if no spot exists

int findRow(char player) {

for (int i=0; i<8; ++i) {

int result=find1Row(player, rows[i][0], rows[i][1]);

if (result>=0)

return result;

return -1;

// If 2 of 3 spots in the row from position[a] to position[b]

// are occupied by player and the third is blank, then return the

// index of the blank spot, else return -1.

int find1Row(char player, int a, int b) {

int c=(a+b)/2; // middle spot

if (position[a]==player && position[b]==player && position[c]==BLANK)


return c;

if (position[a]==player && position[c]==player && position[b]==BLANK)

return b;

if (position[b]==player && position[c]==player && position[a]==BLANK)

return a;

return -1;

// Are all 9 spots filled?

boolean isDraw() {

for (int i=0; i<9; ++i)

if (position[i]==BLANK)

return false;

return true;

// Start a new game

void newGame(char winner) {

repaint();

// Announce result of last game. Ask user to play again.

String result;

if (winner==O) {

++wins;

result = "You Win!";

else if (winner==X) {

++losses;
result = "I Win!";

else {

result = "Tie";

++draws;

if (JOptionPane.showConfirmDialog(null,

"You have "+wins+ " wins, "+losses+" losses, "+draws+" draws\n"

+"Play again?", result, JOptionPane.YES_NO_OPTION)

!=JOptionPane.YES_OPTION) {

wins=losses=draws=0;

// Clear the board to start a new game

for (int j=0; j<9; ++j)

position[j]=BLANK;

// Computer starts first every other game

if ((wins+losses+draws)%2 == 1)

nextMove();

} // end inner class Board

} // end class TicTacToe

/*<applet code="TicTacToeApplet.class" width=300 height=100>

</applet>*/

You might also like