0% found this document useful (0 votes)
110 views15 pages

Tic Tac Toe

This document describes a Tic Tac Toe game project created by 3 students. It includes the code for the game which is written in Java and uses Swing components like JTextField and JPanels to create the graphical user interface. The code implements the core gameplay logic of Tic Tac Toe including tracking turns, detecting wins, and allowing both 2 player and 1 player vs computer modes.

Uploaded by

Navin Gurnani
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views15 pages

Tic Tac Toe

This document describes a Tic Tac Toe game project created by 3 students. It includes the code for the game which is written in Java and uses Swing components like JTextField and JPanels to create the graphical user interface. The code implements the core gameplay logic of Tic Tac Toe including tracking turns, detecting wins, and allowing both 2 player and 1 player vs computer modes.

Uploaded by

Navin Gurnani
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

TIC TAC TOE

Project by:

1. NAVINKUMAR GURNANI(66)

2. KUNAL MULWANI(67)

3. APURVA SANDBHOR(68)

CODE:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.net.URL;
import java.applet.*;
public class TicTacToe extends JFrame
{
JTextField messageTextField = new JTextField();
JPanel gamePanel = new JPanel();
JTextField[] boxTextField = new JTextField[9];
JLabel[] gridLabel = new JLabel[4];
JPanel playersPanel = new JPanel();
ButtonGroup playersButtonGroup = new ButtonGroup();
JRadioButton twoPlayersRadioButton = new JRadioButton();
JRadioButton onePlayerRadioButton = new JRadioButton();
JPanel firstPanel = new JPanel();
ButtonGroup firstButtonGroup = new ButtonGroup();
JRadioButton youFirstRadioButton = new JRadioButton();
JRadioButton computerFirstRadioButton = new JRadioButton();
JPanel computerPanel = new JPanel();
ButtonGroup computerButtonGroup = new ButtonGroup();
JRadioButton randomRadioButton = new JRadioButton();
JRadioButton smartRadioButton = new JRadioButton();
JPanel buttonsPanel = new JPanel();
JButton startStopButton = new JButton();
JButton exitButton = new JButton();

boolean xTurn;
boolean canClick = false;
int numberClicks;
String[] possibleWins = new String[8];
boolean gameOver;
Random myRandom = new Random();

AudioClip drawSound;
AudioClip winSound;

public static void main(String args[])


{
// create frame
new TicTacToe().show();
}

public TicTacToe()
{
// frame constructor
setTitle("Tic Tac Toe");
getContentPane().setBackground(Color.WHITE);
setResizable(false);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
exitForm(evt);
}
});
getContentPane().setLayout(new GridBagLayout());

messageTextField = new JTextField();


messageTextField.setPreferredSize(new Dimension(280, 50));
messageTextField.setEditable(false);
messageTextField.setBackground(Color.YELLOW);
messageTextField.setForeground(Color.BLUE);
messageTextField.setText("X's Move");
messageTextField.setHorizontalAlignment(SwingConstants.CENTER);
messageTextField.setFont(new Font("Arial", Font.BOLD, 24));
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 10, 10, 10);
getContentPane().add(messageTextField, gridConstraints);

gamePanel.setPreferredSize(new Dimension(280, 280));


gamePanel.setBackground(Color.WHITE);
gamePanel.setLayout(new GridBagLayout());
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.gridheight = 3;
gridConstraints.insets = new Insets(10, 10, 10, 10);
getContentPane().add(gamePanel, gridConstraints);

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


{
boxTextField[i] = new JTextField();
boxTextField[i].setPreferredSize(new Dimension(80, 80));
boxTextField[i].setEditable(false);
boxTextField[i].setBackground(Color.WHITE);
boxTextField[i].setHorizontalAlignment(SwingConstants.CENTER);
boxTextField[i].setFont(new Font("Arial", Font.BOLD, 48));
boxTextField[i].setBorder(null);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 2 * (i % 3);
gridConstraints.gridy = 2 * (i / 3);
gamePanel.add(boxTextField[i], gridConstraints);
boxTextField[i].addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
boxTextFieldMousePressed(e);
}
});
}

gridLabel[0] = new JLabel();


gridLabel[0].setPreferredSize(new Dimension(280, 10));
gridLabel[0].setOpaque(true);
gridLabel[0].setBackground(Color.BLUE);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.gridwidth = 5;
gridConstraints.insets = new Insets(5, 0, 5, 0);
gamePanel.add(gridLabel[0], gridConstraints);

gridLabel[1] = new JLabel();


gridLabel[1].setPreferredSize(new Dimension(280, 10));
gridLabel[1].setOpaque(true);
gridLabel[1].setBackground(Color.BLUE);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 3;
gridConstraints.gridwidth = 5;
gridConstraints.insets = new Insets(5, 0, 5, 0);
gamePanel.add(gridLabel[1], gridConstraints);

gridLabel[2] = new JLabel();


gridLabel[2].setPreferredSize(new Dimension(10, 280));
gridLabel[2].setOpaque(true);
gridLabel[2].setBackground(Color.BLUE);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 0;
gridConstraints.gridheight = 5;
gridConstraints.insets = new Insets(0, 5, 0, 5);
gamePanel.add(gridLabel[2], gridConstraints);
gridLabel[3] = new JLabel();
gridLabel[3].setPreferredSize(new Dimension(10, 280));
gridLabel[3].setOpaque(true);
gridLabel[3].setBackground(Color.BLUE);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 3;
gridConstraints.gridy = 0;
gridConstraints.gridheight = 5;
gridConstraints.insets = new Insets(0, 5, 0, 5);
gamePanel.add(gridLabel[3], gridConstraints);

playersPanel.setPreferredSize(new Dimension(160, 75));


playersPanel.setBackground(Color.WHITE);
playersPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
playersPanel.setLayout(new GridBagLayout());
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(5, 10, 5, 10);
getContentPane().add(playersPanel, gridConstraints);

twoPlayersRadioButton.setText("Two Players");
twoPlayersRadioButton.setBackground(Color.WHITE);
twoPlayersRadioButton.setSelected(true);
playersButtonGroup.add(twoPlayersRadioButton);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.anchor = GridBagConstraints.WEST;
playersPanel.add(twoPlayersRadioButton, gridConstraints);
twoPlayersRadioButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
twoPlayersRadioButtonActionPerformed(e);
}
});

onePlayerRadioButton.setText("One Player");
onePlayerRadioButton.setBackground(Color.WHITE);
playersButtonGroup.add(onePlayerRadioButton);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.anchor = GridBagConstraints.WEST;
playersPanel.add(onePlayerRadioButton, gridConstraints);
onePlayerRadioButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
onePlayerRadioButtonActionPerformed(e);
}
});

firstPanel.setPreferredSize(new Dimension(160, 75));


firstPanel.setBackground(Color.WHITE);
firstPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
firstPanel.setLayout(new GridBagLayout());
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(5, 10, 5, 10);
getContentPane().add(firstPanel, gridConstraints);

youFirstRadioButton.setText("You First");
youFirstRadioButton.setBackground(Color.WHITE);
youFirstRadioButton.setSelected(true);
firstButtonGroup.add(youFirstRadioButton);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.anchor = GridBagConstraints.WEST;
firstPanel.add(youFirstRadioButton, gridConstraints);

computerFirstRadioButton.setText("Computer First");
computerFirstRadioButton.setBackground(Color.WHITE);
firstButtonGroup.add(computerFirstRadioButton);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.anchor = GridBagConstraints.WEST;
firstPanel.add(computerFirstRadioButton, gridConstraints);

computerPanel.setPreferredSize(new Dimension(160, 75));


computerPanel.setBackground(Color.WHITE);
computerPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
computerPanel.setLayout(new GridBagLayout());
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 2;
gridConstraints.insets = new Insets(5, 10, 5, 10);
getContentPane().add(computerPanel, gridConstraints);

randomRadioButton.setText("Random Computer");
randomRadioButton.setBackground(Color.WHITE);
randomRadioButton.setSelected(true);
computerButtonGroup.add(randomRadioButton);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.anchor = GridBagConstraints.WEST;
computerPanel.add(randomRadioButton, gridConstraints);

smartRadioButton.setText("Smart Computer");
smartRadioButton.setBackground(Color.WHITE);
computerButtonGroup.add(smartRadioButton);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.anchor = GridBagConstraints.WEST;
computerPanel.add(smartRadioButton, gridConstraints);

buttonsPanel.setPreferredSize(new Dimension(160, 70));


buttonsPanel.setBackground(Color.WHITE);
buttonsPanel.setLayout(new GridBagLayout());
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 3;
getContentPane().add(buttonsPanel, gridConstraints);

startStopButton.setText("Start Game");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
buttonsPanel.add(startStopButton, gridConstraints);
startStopButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
startStopButtonActionPerformed(e);
}
});

exitButton.setText("Exit");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(10, 0, 0, 0);
buttonsPanel.add(exitButton, gridConstraints);
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
exitButtonActionPerformed(e);
}
});

pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((int) (0.5 * (screenSize.width - getWidth())), (int) (0.5 * (screenSize.height -
getHeight())), getWidth(), getHeight());

messageTextField.setText("Game Stopped");
youFirstRadioButton.setEnabled(false);
computerFirstRadioButton.setEnabled(false);
randomRadioButton.setEnabled(false);
smartRadioButton.setEnabled(false);
// possible wins
possibleWins[0] = "012";
possibleWins[1] = "345";
possibleWins[2] = "678";
possibleWins[3] = "036";
possibleWins[4] = "147";
possibleWins[5] = "258";
possibleWins[6] = "048";
possibleWins[7] = "246";
try
{
drawSound = Applet.newAudioClip(new URL("file:" + "beep.wav"));
winSound = Applet.newAudioClip(new URL("file:" + "tada.wav"));
}
catch (Exception ex)
{
System.out.println("Error loading sound files");
}
}

private void exitForm(WindowEvent evt)


{
System.exit(0);
}

private void boxTextFieldMousePressed(MouseEvent e)


{
if (canClick)
{
int i;
// get upper left corner of clicked box
Point p = e.getComponent().getLocation();
// determine index based on p
for (i = 0; i < 9; i++)
{
if (p.x == boxTextField[i].getX() && p.y == boxTextField[i].getY())
break;
}
markClickedBox(i);
}
}

private void twoPlayersRadioButtonActionPerformed(ActionEvent e)


{
youFirstRadioButton.setEnabled(false);
computerFirstRadioButton.setEnabled(false);
randomRadioButton.setEnabled(false);
smartRadioButton.setEnabled(false);
}

private void onePlayerRadioButtonActionPerformed(ActionEvent e)


{
youFirstRadioButton.setEnabled(true);
computerFirstRadioButton.setEnabled(true);
randomRadioButton.setEnabled(true);
smartRadioButton.setEnabled(true);
}

private void startStopButtonActionPerformed(ActionEvent e)


{
if (startStopButton.getText().equals("Start Game"))
{
startStopButton.setText("Stop Game");
twoPlayersRadioButton.setEnabled(false);
onePlayerRadioButton.setEnabled(false);
youFirstRadioButton.setEnabled(false);
computerFirstRadioButton.setEnabled(false);
randomRadioButton.setEnabled(false);
smartRadioButton.setEnabled(false);
exitButton.setEnabled(false);
xTurn = true;
messageTextField.setText("X's Turn");
// reset boxes
for (int i = 0; i < 9; i++)
{
boxTextField[i].setText("");
boxTextField[i].setBackground(Color.WHITE);
}
canClick = true;
numberClicks = 0;
gameOver = false;
if (computerFirstRadioButton.isSelected())
computerTurn();
}
else
{
startStopButton.setText("Start Game");
if (!gameOver)
messageTextField.setText("Game Stopped");
twoPlayersRadioButton.setEnabled(true);
onePlayerRadioButton.setEnabled(true);
if (onePlayerRadioButton.isSelected())
{
youFirstRadioButton.setEnabled(true);
computerFirstRadioButton.setEnabled(true);
randomRadioButton.setEnabled(true);
smartRadioButton.setEnabled(true);
}
exitButton.setEnabled(true);
canClick = false;
}
}

private void exitButtonActionPerformed(ActionEvent e)


{
System.exit(0);
}

private void markClickedBox(int i)


{
String whoWon = "";
// if already clicked then exit
if (!boxTextField[i].getText().equals(""))
return;
numberClicks++;
if (xTurn)
{
boxTextField[i].setText("X");
xTurn = false;
messageTextField.setText("O's Turn");
}
else
{
boxTextField[i].setText("O");
xTurn = true;
messageTextField.setText("X's Turn");
}
// check for win - will establish a value for WhoWon
whoWon = checkForWin();
if (!whoWon.equals(""))
{
winSound.play();
messageTextField.setText(whoWon + " wins!");
gameOver = true;
startStopButton.doClick();
return;
}
else if (numberClicks == 9)
{
// draw
drawSound.play();
messageTextField.setText("It's a draw!");
gameOver = true;
startStopButton.doClick();
return;
}
if (onePlayerRadioButton.isSelected())
if ((xTurn && computerFirstRadioButton.isSelected()) || (!xTurn &&
youFirstRadioButton.isSelected()))
computerTurn();
}

private String checkForWin()


{
String winner = "";
int[] boxNumber = new int[3];
String[] mark = new String[3];
// check all possible for wins
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 3; j++)
{
boxNumber[j] = Integer.valueOf(String.valueOf(possibleWins[i].charAt(j))).intValue();
mark[j] = boxTextField[boxNumber[j]].getText();
}
if (mark[0].equals(mark[1]) && mark[0].equals(mark[2]) && mark[1].equals(mark[2]) && !
mark[0].equals(""))
{
// we have a winner
winner = mark[0];
for (int j = 0; j < 3; j++)
boxTextField[boxNumber[j]].setBackground(Color.RED);
}
}
return (winner);
}

private void computerTurn()


{
int selectedBox;
int i, n;
int j, k;
String computerMark, playerMark, markToFind;
int[] boxNumber = new int[3];
String[] mark = new String[3];
int emptyBox;
int[] bestMoves = { 4, 0, 2, 6, 8, 1, 3, 5, 7 };

if (randomRadioButton.isSelected())
{
// random logic
// put mark in Nth available square
n = myRandom.nextInt(9 - numberClicks) + 1;
i = 0;
for (selectedBox = 0; selectedBox < 9; selectedBox++)
{
if (boxTextField[selectedBox].getText().equals(""))
i++;
if (i == n)
break;
}
// put mark in SelectedBox
markClickedBox(selectedBox);
}
else
{
// smart computer
// determine who has what mark
if (computerFirstRadioButton.isSelected())
{
computerMark = "X";
playerMark = "O";
}
else
{
computerMark = "O";
playerMark = "X";
}
// Step 1 (K = 1) - check for win - see if two boxes hold computer mark and one is empty
// Step 2 (K = 2) - check for block - see if two boxes hold player mark and one is empty
for (k = 1; k <= 2; k++)
{
if (k == 1)
markToFind = computerMark;
else
markToFind = playerMark;
for (i = 0; i < 8; i++)
{
n = 0;
emptyBox = 0;
for (j = 0; j < 3; j++)
{
boxNumber[j] = Integer.valueOf(String.valueOf(possibleWins[i].charAt(j))).intValue();
mark[j] = boxTextField[boxNumber[j]].getText();
if (mark[j].equals(markToFind))
n++;
else if (mark[j].equals(""))
emptyBox = boxNumber[j];
}
if (n == 2 && emptyBox != 0)
{
// mark empty box to win (K = 1) or block (K = 2)
markClickedBox(emptyBox);
return;
}
}
}
// Step 3 - find next best move
for (i = 0; i < 9; i++)
{
if (boxTextField[bestMoves[i]].getText().equals(""))
{
markClickedBox(bestMoves[i]);
return;
}
}
}
}

SCREEN SHOTS:

You might also like