Tic Tac Toe
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
/**
*
* @author MBC
*/
public class TicTacToe extends JApplet
{
//Determine who goes first; Default is X.
private char whoseTurn = 'X';
//Create and intialize cells
private Cell[][] cells = new Cell[3][3];
////Create Status Label and initialize
private JLabel jlblStatus = new JLabel("X's turn to play");
//start UI
public TicTacToe()
{
//Create panel to hold cells.
JPanel p = new JPanel(new GridLayout(3, 3, 0, 0));
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
p.add(cells[i][j] = new Cell());
//set line borderes on the panel and status label.
p.setBorder(new LineBorder(Color.red, 1));
jlblStatus.setBorder((new LineBorder(Color.yellow, 1)));
//set panel and label to applet.
add(p, BorderLayout.CENTER);
add(jlblStatus, BorderLayout.SOUTH);
}
//Determine if cells are occupied.
public boolean isFull()
{
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
if (cells[i][j].getToken() == ' ')
return false;
return true;
}
//Determine if player has specific token to win.
public boolean isWon(char token)
{
for(int i = 0; i < 3; i++)
if ((cells[i][0].getToken() == token)
&& (cells[i][1].getToken() == token)
&& (cells[i][2].getToken() == token))
{
return true;
}
for(int j = 0; j < 3; j++)
if ((cells[0][j].getToken() == token)
&& (cells[1][j].getToken() == token)
&& (cells[2][j].getToken() == token))
{
return true;
}
if ((cells[0][0].getToken() == token)
&& (cells[1][1].getToken() == token)
&& (cells[2][2].getToken() == token))
{
return true;
}
if ((cells[0][2].getToken() == token)
&& (cells[1][1].getToken() == token)
&& (cells[2][0].getToken() == token))
{
return true;
}
return false;
}
//An inner class of cell
public class Cell extends JPanel
{
// token used for this cell
private char token = ' ';
public Cell()
{
setBorder(new LineBorder(Color.black, 1));
addMouseListener(new MyMouseListener());
}
//return token.
public char getToken()
{
return token;
}
//set token.
public void setToken(char c)
{
token = c;
repaint();
}
//paint cell
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (token == 'X')
{
g.drawLine(10, 10, getWidth() - 10, getHeight() - 10);
g.drawLine(getWidth() - 10, 10, 10, getHeight() - 10);
}
else if (token == '0')
{
g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);
}
}
//handle action event
private class MyMouseListener extends MouseAdapter
{
//handle mouse click.
public void mouseClicked(MouseEvent e)
{
//if cell is empty and game isnt over
if (token == ' ' && whoseTurn != ' ')
{
//set token in cell
setToken(whoseTurn);
if(isWon(whoseTurn))
{
jlblStatus.setText(whoseTurn + " won! Game Over");
//game over
whoseTurn = ' ';
}
else if (isFull())
{
jlblStatus.setText("Draw! Game Over");
//game over
whoseTurn = ' ';
}
else
{
//switch turn
whoseTurn = (whoseTurn == 'X') ? '0' : 'X';
//display who's turn.
jlblStatus.setText(whoseTurn + "'s turn");
}
}
}
}
}
}