Jump to content




Recent Status Updates

  • Photo
      30 Sep
    rhossis

    laptop hard disk seated beneath motherboard but with no access panel. 7 hours to replace :(

    Show comments (3)
  • Photo
      19 Sep
    Chall

    I love it when you go to write a help thread, then while writing, you reach an enlightenment, and figure it out yourself.

    Show comments (3)
View All Updates

Developed by Kemal Taskin
Photo
* * * * * 2 votes

Java Source Code: Tic-Tac-Toe Game

tic-tac-toe source code

  • Please log in to reply
80 replies to this topic

#1 Blmaster

Blmaster

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 52 posts

Posted 06 October 2008 - 05:02 PM

Here is the Tic-Tac-Toe Game i have made!
I am actually very impressed with the layout I have done and it looks pretty cool if i do say so myself lol.

I will be working further on this to add like a High Score thing and like asking the user for the names and the CPU and more when i think of some good ideas to add on to this.

CREDITS: I have used the tutorial made from John as a guide to making this. So thank you for that John

Here is the code and no .jar file this time:




/*
Title: Tic-Tac-Toe Game
Created: October 5, 2008
Last Edited: pending...
Author: Blmaster
Changes:
See Below...
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class TicTacToe implements ActionListener {
final String VERSION = "1.0";
//Setting up ALL the variables
JFrame window = new JFrame("Tic-Tac-Toe " + VERSION);

JMenuBar mnuMain = new JMenuBar();
JMenuItem mnuNewGame = new JMenuItem("New Game"),
mnuInstruction = new JMenuItem("Instructions"),
mnuExit = new JMenuItem("Exit"),
mnuAbout = new JMenuItem("About");

JButton btn1v1 = new JButton("Player vs Player"),
btn1vCPU = new JButton("Player vs CPU"),
btnBack = new JButton("<--back");
JButton btnEmpty[] = new JButton[10];

JPanel pnlNewGame = new JPanel(),
pnlNorth = new JPanel(),
pnlSouth = new JPanel(),
pnlTop = new JPanel(),
pnlBottom = new JPanel(),
pnlPlayingField = new JPanel();
JLabel lblTitle = new JLabel("Tic-Tac-Toe");
JTextArea txtMessage = new JTextArea();

final int winCombo[][] = new int[][] {
{1, 2, 3}, {1, 4, 7}, {1, 5, 9},
{4, 5, 6}, {2, 5, 8}, {3, 5, 7},
{7, 8, 9}, {3, 6, 9}
/*Horizontal Wins*/ /*Vertical Wins*/ /*Diagonal Wins*/
};
final int X = 412, Y = 268, color = 190;
boolean inGame = false;
boolean win = false;
boolean btnEmptyClicked = false;
String message;
int turn = 1;
int wonNumber1 = 1, wonNumber2 = 1, wonNumber3 = 1;

public TicTacToe() { //Setting game properties and layout and sytle...
//Setting window properties:
window.setSize(X, Y);
window.setLocation(450, 260);
window.setResizable(false);
window.setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Setting Panel layouts and properties
pnlNewGame.setLayout(new GridLayout(2, 1, 2, 10));
pnlNorth.setLayout(new FlowLayout(FlowLayout.CENTER));
pnlSouth.setLayout(new FlowLayout(FlowLayout.CENTER));

pnlNorth.setBackground(new Color(color-20, color-20, color-20));
pnlSouth.setBackground(new Color(color, color, color));

pnlTop.setBackground(new Color(color, color, color));
pnlBottom.setBackground(new Color(color, color, color));

pnlTop.setLayout(new FlowLayout(FlowLayout.CENTER));
pnlBottom.setLayout(new FlowLayout(FlowLayout.CENTER));
pnlNewGame.setBackground(Color.blue);

//Adding menu items to menu bar
mnuMain.add(mnuNewGame);
mnuMain.add(mnuInstruction);
mnuMain.add(mnuAbout);
mnuMain.add(mnuExit);//---->Menu Bar Complete

//Adding buttons to NewGame panel
pnlNewGame.add(btn1v1);
pnlNewGame.add(btn1vCPU);

//Adding Action Listener to all the Buttons and Menu Items
mnuNewGame.addActionListener(this);
mnuExit.addActionListener(this);
mnuInstruction.addActionListener(this);
mnuAbout.addActionListener(this);
btn1v1.addActionListener(this);
btn1vCPU.addActionListener(this);
btnBack.addActionListener(this);

//Setting up the playing field
pnlPlayingField.setLayout(new GridLayout(3, 3, 2, 2));
pnlPlayingField.setBackground(Color.black);
for(int i=1; i<=9; i++) {
btnEmpty[i] = new JButton();
btnEmpty[i].setBackground(new Color(220, 220, 220));
btnEmpty[i].addActionListener(this);
pnlPlayingField.add(btnEmpty[i]);
}
//Adding everything needed to pnlNorth and pnlSouth
pnlNorth.add(mnuMain);
pnlSouth.add(lblTitle);

//Adding to window and Showing window
window.add(pnlNorth, BorderLayout.NORTH);
window.add(pnlSouth, BorderLayout.CENTER);
window.setVisible(true);
}

//-------------------START OF ACTION PERFORMED CLASS-------------------------//
public void actionPerformed(ActionEvent click) {
Object source = click.getSource();
for(int i=1; i<=9; i++) {
if(source == btnEmpty[i] && turn < 10) {
btnEmptyClicked = true;
if(!(turn % 2 == 0))
btnEmpty[i].setText("X");
else
btnEmpty[i].setText("O");
btnEmpty[i].setEnabled(false);
pnlPlayingField.requestFocus();
turn++;
}
}
if(btnEmptyClicked) {
checkWin();
btnEmptyClicked = false;
}
if(source == mnuNewGame) {
clearPanelSouth();
pnlSouth.setLayout(new GridLayout(2, 1, 2, 5));
pnlTop.add(pnlNewGame);
pnlBottom.add(btnBack);
pnlSouth.add(pnlTop);
pnlSouth.add(pnlBottom);

}
else if(source == btn1v1) {
if(inGame) {
int option = JOptionPane.showConfirmDialog(null, "If you start a new game," +
"your current game will be lost..." + "\n" +
"Are you sure you want to continue?",
"Quit Game?" ,JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION) {
inGame = false;
}
}
if(!inGame) {
btnEmpty[wonNumber1].setBackground(new Color(220, 220, 220));
btnEmpty[wonNumber2].setBackground(new Color(220, 220, 220));
btnEmpty[wonNumber3].setBackground(new Color(220, 220, 220));
turn = 1;
for(int i=1; i<10; i++) {
btnEmpty[i].setText("");
btnEmpty[i].setEnabled(true);
}
win = false;
showGame();

}
}
else if(source == btn1vCPU) {
JOptionPane.showMessageDialog(null, "Coming Soon!!");
}
else if(source == mnuExit) {
int option = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?",
"Exit Game" ,JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION)
System.exit(0);
}
else if(source == mnuInstruction || source == mnuAbout) {
clearPanelSouth();
String message = "";
txtMessage.setBackground(new Color(color, color, color));
if(source == mnuInstruction) {
message = "Instructions:\n\n" +
"Your goal is to be the first player to get 3 X's or O's in a\n" +
"row. (horizontally, diagonally, or vertically)";
} else {
message = "About:\n\n" +
"Title: Tic-Tac-Toe\n" +
"Author: Blmaster\n" +
"Version: " + VERSION + "\n";
}
txtMessage.setEditable(false);
txtMessage.setText(message);
pnlSouth.setLayout(new GridLayout(2, 1, 2, 5));
pnlTop.add(txtMessage);
pnlBottom.add(btnBack);
pnlSouth.add(pnlTop);
pnlSouth.add(pnlBottom);
}
else if(source == btnBack) {
if(inGame)
showGame();
else {
clearPanelSouth();
pnlSouth.setLayout(new FlowLayout(FlowLayout.CENTER));
pnlNorth.setVisible(true);
pnlSouth.add(lblTitle);
}
}
pnlSouth.setVisible(false);
pnlSouth.setVisible(true);
}
//-------------------END OF ACTION PERFORMED CLASS-------------------------//

/*
----------------------------------
Start of all the other methods. |
----------------------------------
*/
public void showGame() { // Shows the Playing Field
// *IMPORTANT*- Does not start out brand new (meaning just shows what it had before)
clearPanelSouth();
inGame = true;
pnlSouth.setLayout(new BorderLayout());
pnlSouth.add(pnlPlayingField, BorderLayout.CENTER);
pnlPlayingField.requestFocus();
}

public void checkWin() { // checks if there are 3 symbols in a row vertically, diagonally, or horizontally.
// then shows a message and disables buttons.
for(int i=0; i<7; i++) {
if(
!btnEmpty[winCombo[i][0]].getText().equals("") &&
btnEmpty[winCombo[i][0]].getText().equals(btnEmpty[winCombo[i][1]].getText()) &&
// if {1 == 2 && 2 == 3}
btnEmpty[winCombo[i][1]].getText().equals(btnEmpty[winCombo[i][2]].getText())
/*
The way this checks the if someone won is:
First: it checks if the btnEmpty[x] is not equal to an empty string- x being the array number
inside the multi-dementional array winCombo[checks inside each of the 7 sets][the first number]
Secong: it checks if btnEmpty[x] is equal to btnEmpty[y]- x being winCombo[each set][the first number]
y being winCombo[each set the same as x][the second number] (So basically checks if the first and
second number in each set is equal to each other)
Third: it checks if btnEmtpy[y] is eual to btnEmpty[z]- y being the same y as last time and z being
winCombo[each set as y][the third number]
Conclusion: So basically it checks if it is equal to the btnEmpty is equal to each set of numbers
*/
) {
win = true;
wonNumber1 = winCombo[i][0];
wonNumber2 = winCombo[i][1];
wonNumber3 = winCombo[i][2];
btnEmpty[wonNumber1].setBackground(Color.white);
btnEmpty[wonNumber2].setBackground(Color.white);
btnEmpty[wonNumber3].setBackground(Color.white);
break;
}
}
if(win || (!win && turn>9)) {
if(win) {
if(turn % 2 == 0)
message = "X has won!";
else
message = "O has won!";
win = false;
} else if(!win && turn>9) {
message = "Both players have tied!\nBetter luck next time.";
}
JOptionPane.showMessageDialog(null, message);
for(int i=1; i<=9; i++) {
btnEmpty[i].setEnabled(false);
}
}
}

public void clearPanelSouth() { //Removes all the possible panels
//that pnlSouth, pnlTop, pnlBottom
//could have.
pnlSouth.remove(lblTitle);
pnlSouth.remove(pnlTop);
pnlSouth.remove(pnlBottom);
pnlSouth.remove(pnlPlayingField);
pnlTop.remove(pnlNewGame);
pnlTop.remove(txtMessage);
pnlBottom.remove(btnBack);
}

public static void main(String[] args) {
new TicTacToe();// Calling the class construtor.
}
}
/*
Changes:
1.0- changes below: Stable
0.9- added back button, added comments.
0.8- added dynamic win message.
0.7- added game function- game playable.
0.6- changed menu layout.
0.5- basic functions with menu and nice GUI.
*/
 

Besides this tic-tac-toe tutorial from John, definitely check out his Java tutorial series!

 


Edited by Roger, 29 September 2014 - 04:36 PM.

  • 0

#2 Blmaster

Blmaster

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 52 posts

Posted 11 October 2008 - 05:49 PM

Here is another Version of Tic-Tac-Toe.
I still haven't done the computer AI yet but that will come in next version!
Hope you like what I have done so far.

[Uploaded .jar file if you just want to see/play the game]

/*
Title: Tic-Tac-Toe Game
Created: October 5, 2008
Last Edited: October 11, 2008
Author: Blmaster
Changes:
See Below...
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

public cl*** TicTacToe implements ActionListener {
final String VERSION = "2.0";
//Setting up ALL the variables
JFrame window = new JFrame("Tic-Tac-Toe " + VERSION);

JMenuBar mnuMain = new JMenuBar();
JMenuItem mnuNewGame = new JMenuItem("New Game"),
mnuInstruction = new JMenuItem("Instructions"),
mnuExit = new JMenuItem("Exit"),
mnuAbout = new JMenuItem("About");

JButton btn1v1 = new JButton("Player vs Player"),
btn1vCPU = new JButton("Player vs Computer"),
btnQuit = new JButton("Quit"),
btnSetName = new JButton("Set Player Names"),
btnContinue = new JButton("Continue..."),
btnTryAgain = new JButton("Try Again?");
JButton btnEmpty[] = new JButton[10];

JPanel pnlNewGame = new JPanel(),
pnlMenu = new JPanel(),
pnlMain = new JPanel(),
pnlTop = new JPanel(),
pnlBottom = new JPanel(),
pnlQuitNTryAgain = new JPanel(),
pnlPlayingField = new JPanel();

JLabel lblTitle = new JLabel("Tic-Tac-Toe"),
lblTurn = new JLabel(),
lblStatus = new JLabel("", JLabel.CENTER);
JTextArea txtMessage = new JTextArea();

final int winCombo[][] = new int[][] {
{1, 2, 3}, {1, 4, 7}, {1, 5, 9},
{4, 5, 6}, {2, 5, 8}, {3, 5, 7},
{7, 8, 9}, {3, 6, 9}
/*Horizontal Wins*/ /*Vertical Wins*/ /*Diagonal Wins*/
};
final int X = 535, Y = 342,
mainColorR = 190, mainColorG = 50, mainColorB = 50,
btnColorR = 70, btnColorG = 70, btnColorB = 70;
Color clrBtnWonColor = new Color(190, 190, 190);
int turn = 1,
player1Won = 0,
player2Won = 0,
wonNumber1 = 1,
wonNumber2 = 1,
wonNumber3 = 1;
int option;
boolean inGame = false;
boolean win = false;
boolean btnEmptyClicked = false;
String message, whoTurn,
Player1 = "Player 1", Player2 = "Player 2";


public TicTacToe() { //Setting game properties and layout and sytle...
//Setting window properties:
window.setSize(X, Y);
window.setLocation(350, 260);
window.setResizable(false);
window.setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Setting Menu, Main, Top, Bottom Panel Layout/Backgrounds
pnlMenu.setLayout(new FlowLayout(FlowLayout.CENTER));
pnlTop.setLayout(new FlowLayout(FlowLayout.CENTER));
pnlBottom.setLayout(new FlowLayout(FlowLayout.CENTER));

pnlNewGame.setBackground(new Color(mainColorR - 50, mainColorG - 50, mainColorB- 50));
pnlMenu.setBackground(new Color((mainColorR - 50), (mainColorG - 50), (mainColorB- 50)));
pnlMain.setBackground(new Color(mainColorR, mainColorG, mainColorB));
pnlTop.setBackground(new Color(mainColorR, mainColorG, mainColorB));
pnlBottom.setBackground(new Color(mainColorR, mainColorG, mainColorB));

//Setting up Panel QuitNTryAgain
pnlQuitNTryAgain.setLayout(new GridLayout(1, 2, 2, 2));
pnlQuitNTryAgain.add(btnTryAgain);
pnlQuitNTryAgain.add(btnQuit);

//Adding menu items to menu bar
mnuMain.add(mnuNewGame);
mnuMain.add(mnuInstruction);
mnuMain.add(mnuAbout);
mnuMain.add(mnuExit);// Menu Bar is Complete

//Adding buttons to NewGame panel
pnlNewGame.setLayout(new GridLayout(4, 1, 2, 10));
pnlNewGame.add(btnContinue);
pnlNewGame.add(btn1v1);
pnlNewGame.add(btn1vCPU);
pnlNewGame.add(btnSetName);

//Setting Button propertied
btnTryAgain.setEnabled(false);
btnContinue.setEnabled(false);

//Setting txtMessage Properties
txtMessage.setBackground(new Color(mainColorR-30, mainColorG-30, mainColorB-30));
txtMessage.setForeground(Color.white);
txtMessage.setEditable(false);

//Adding Action Listener to all the Buttons and Menu Items
mnuNewGame.addActionListener(this);
mnuExit.addActionListener(this);
mnuInstruction.addActionListener(this);
mnuAbout.addActionListener(this);
btn1v1.addActionListener(this);
btn1vCPU.addActionListener(this);
btnQuit.addActionListener(this);
btnSetName.addActionListener(this);
btnContinue.addActionListener(this);
btnTryAgain.addActionListener(this);

//Setting up the playing field
pnlPlayingField.setLayout(new GridLayout(3, 3, 2, 2));
pnlPlayingField.setBackground(Color.black);
for(int i=1; i<=9; i++) {
btnEmpty[i] = new JButton();
btnEmpty[i].setBackground(new Color(btnColorR, btnColorG, btnColorB));
btnEmpty[i].addActionListener(this);
pnlPlayingField.add(btnEmpty[i]);// Playing Field is Compelte
}

//Adding everything needed to pnlMenu and pnlMain
pnlMenu.add(mnuMain);
pnlMain.add(lblTitle);

//Adding to window and Showing window
window.add(pnlMenu, BorderLayout.NORTH);
window.add(pnlMain, BorderLayout.CENTER);
window.setVisible(true);
}

public static void main(String[] args) {
new TicTacToe();// Calling the cl*** construtor.
// PROGRAM STARTS HERE!
}



/*
-------------------------
Start of all METHODS. |
-------------------------
*/
public void showGame() { // Shows the Playing Field
// *IMPORTANT*- Does not start out brand new (meaning just shows what it had before)
clearPanelSouth();
pnlMain.setLayout(new BorderLayout());
pnlTop.setLayout(new BorderLayout());
pnlBottom.setLayout(new BorderLayout());
pnlTop.add(pnlPlayingField);
pnlBottom.add(lblTurn, BorderLayout.WEST);
pnlBottom.add(lblStatus, BorderLayout.CENTER);
pnlBottom.add(pnlQuitNTryAgain, BorderLayout.EAST);
pnlMain.add(pnlTop, BorderLayout.CENTER);
pnlMain.add(pnlBottom, BorderLayout.SOUTH);
pnlPlayingField.requestFocus();
inGame = true;
checkTurn();
checkWinStatus();
}
//-----------------------------------------------------------------------------------------------------------------------------------
public void new1v1Game() { // Sets all the game required variables to default
// and then shows the playing field.
// (Basically: Starts a new 1v1 Game)
btnEmpty[wonNumber1].setBackground(new Color(btnColorR, btnColorG, btnColorB));
btnEmpty[wonNumber2].setBackground(new Color(btnColorR, btnColorG, btnColorB));
btnEmpty[wonNumber3].setBackground(new Color(btnColorR, btnColorG, btnColorB));
for(int i=1; i<10; i++) {
btnEmpty[i].setText("");
btnEmpty[i].setEnabled(true);
}
turn = 1;
win = false;
showGame();
}
//-----------------------------------------------------------------------------------------------------------------------------------
public void goBack() {
clearPanelSouth();
pnlMain.setLayout(new FlowLayout(FlowLayout.CENTER));
pnlMain.add(lblTitle);
}
//-----------------------------------------------------------------------------------------------------------------------------------
public void checkWin() { // checks if there are 3 symbols in a row vertically, diagonally, or horizontally.
// then shows a message and disables buttons. If the game is over then it asks
// if you want to play again.
for(int i=0; i<8; i++) {
if(
!btnEmpty[winCombo[i][0]].getText().equals("") &&
btnEmpty[winCombo[i][0]].getText().equals(btnEmpty[winCombo[i][1]].getText()) &&
// if {1 == 2 && 2 == 3}
btnEmpty[winCombo[i][1]].getText().equals(btnEmpty[winCombo[i][2]].getText())) {
/*
The way this checks the if someone won is:
First: it checks if the btnEmpty[x] is not equal to an empty string- x being the array number
inside the multi-dementional array winCombo[checks inside each of the 7 sets][the first number]
Secong: it checks if btnEmpty[x] is equal to btnEmpty[y]- x being winCombo[each set][the first number]
y being winCombo[each set the same as x][the second number] (So basically checks if the first and
second number in each set is equal to each other)
Third: it checks if btnEmtpy[y] is eual to btnEmpty[z]- y being the same y as last time and z being
winCombo[each set as y][the third number]
Conclusion: So basically it checks if it is equal to the btnEmpty is equal to each set of numbers
*/
win = true;
wonNumber1 = winCombo[i][0];
wonNumber2 = winCombo[i][1];
wonNumber3 = winCombo[i][2];
btnEmpty[wonNumber1].setBackground(clrBtnWonColor);
btnEmpty[wonNumber2].setBackground(clrBtnWonColor);
btnEmpty[wonNumber3].setBackground(clrBtnWonColor);
break;
}
}
if(win || (!win && turn>9)) {
if(win) {
if(turn % 2 == 0) {
message = Player1 + " has won";
player1Won++;
}
else {
message = Player2 + " has won";
player2Won++;
}
win = false;
} else if(!win && turn>9)
message = "Both players have tied!\nBetter luck next time.";
showMessage(message);
for(int i=1; i<=9; i++) {
btnEmpty[i].setEnabled(false);
}
btnTryAgain.setEnabled(true);
checkWinStatus();
} else
checkTurn();
}
//-----------------------------------------------------------------------------------------------------------------------------------
public void checkTurn() {
if(!(turn % 2 == 0)) {
whoTurn = Player1 + " [X]";
} else {
whoTurn = Player2 + " [O]";
}
lblTurn.setText("Turn: " + whoTurn);
}
//-----------------------------------------------------------------------------------------------------------------------------------
public void checkWinStatus() {
lblStatus.setText(Player1 + ": " + player1Won + " | " + Player2 + ": " + player2Won);
}
//-----------------------------------------------------------------------------------------------------------------------------------
public void askUserForPlayerNames() {
String temp = Player2;

temp = getInput("Enter player 1 name:", Player1);
if(temp == null) {/*Do Nothing*/}
else if(temp.equals(""))
showMessage("Invalid Name!");
else if(temp.equals(Player2)) {
option = askMessage("Player 1 name matches Player 2's\nDo you want to continue?", "Name Match", JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION)
Player1 = temp;
} else if(temp != null) {
Player1 = temp;
}

temp = getInput("Enter player 2 name:", Player2);
if(temp == null) {/*Do Nothing*/}
else if(temp.equals(""))
showMessage("Invalid Name!");
else if(temp.equals(Player1)) {
option = askMessage("Player 2 name matches Player 1's\nDo you want to continue?", "Name Match", JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION)
Player2 = temp;
} else if(temp != null) {
Player2 = temp;
}
}
//-----------------------------------------------------------------------------------------------------------------------------------
public void setDefaultLayout() {
pnlMain.setLayout(new GridLayout(2, 1, 2, 5));
pnlTop.setLayout(new FlowLayout(FlowLayout.CENTER));
pnlBottom.setLayout(new FlowLayout(FlowLayout.CENTER));
}
//-----------------------------------------------------------------------------------------------------------------------------------
public int askMessage(String message, String title, int option) {
return JOptionPane.showConfirmDialog(null, message, title, option);
}
//-----------------------------------------------------------------------------------------------------------------------------------
public String getInput(String message, String setText) {
return JOptionPane.showInputDialog(null, message, setText);
}
//-----------------------------------------------------------------------------------------------------------------------------------
public void showMessage(String message) {
JOptionPane.showMessageDialog(null, message);
}
//-----------------------------------------------------------------------------------------------------------------------------------
public void clearPanelSouth() { //Removes all the possible panels
//that pnlMain, pnlTop, pnlBottom
//could have.
pnlMain.remove(lblTitle);
pnlMain.remove(pnlTop);
pnlMain.remove(pnlBottom);
pnlTop.remove(pnlNewGame);
pnlTop.remove(txtMessage);
pnlTop.remove(pnlPlayingField);
pnlBottom.remove(lblTurn);
pnlBottom.remove(pnlQuitNTryAgain);
}
/*
-------------------------------------
End of all non-Abstract METHODS. |
-------------------------------------
*/

//-------------------ACTION PERFORMED METHOD (Button Click --> Action?)-------------------------//
public void actionPerformed(ActionEvent click) {
Object source = click.getSource();
for(int i=1; i<=9; i++) {
if(source == btnEmpty[i] && turn < 10) {
btnEmptyClicked = true;
if(!(turn % 2 == 0))
btnEmpty[i].setText("X");
else
btnEmpty[i].setText("O");
btnEmpty[i].setEnabled(false);
pnlPlayingField.requestFocus();
turn++;
}
}
if(btnEmptyClicked) {
checkWin();
btnEmptyClicked = false;
}
if(source == mnuNewGame || source == mnuInstruction || source == mnuAbout) {
clearPanelSouth();
setDefaultLayout();

if(source == mnuNewGame) {//NewGame
pnlTop.add(pnlNewGame);
}
else if(source == mnuInstruction || source == mnuAbout) {
if(source == mnuInstruction) {// Instructions
message = "Instructions:\n\n" +
"Your goal is to be the first player to get 3 X's or O's in a\n" +
"row. (horizontally, diagonally, or vertically)\n" +
Player1 + ": X\n" +
Player2 + ": O\n";
} else {//About
message = "About:\n\n" +
"Title: Tic-Tac-Toe\n" +
"Creator: Blmaster\n" +
"Version: " + VERSION + "\n";
}
txtMessage.setText(message);
pnlTop.add(txtMessage);
}
pnlMain.add(pnlTop);
}
else if(source == btn1v1 || source == btn1vCPU) {
if(inGame) {
option = askMessage("If you start a new game," +
"your current game will be lost..." + "\n" +
"Are you sure you want to continue?",
"Quit Game?" ,JOptionPane.YES_NO_OPTION
);
if(option == JOptionPane.YES_OPTION)
inGame = false;
}
if(!inGame) {
if(source == btn1v1) {// 1 v 1 Game
btnContinue.setEnabled(true);
new1v1Game();
} else {// 1 v CPU Game
showMessage("Coming Soon!");
}
}
}
else if(source == btnContinue) {
checkTurn();
showGame();
}
else if(source == btnSetName) {
askUserForPlayerNames();
}
else if(source == mnuExit) {
option = askMessage("Are you sure you want to exit?", "Exit Game", JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION)
System.exit(0);
}
else if(source == btnTryAgain) {
new1v1Game();
btnTryAgain.setEnabled(false);
}
else if(source == btnQuit) {
inGame = false;
btnContinue.setEnabled(false);
goBack();
}
pnlMain.setVisible(false);
pnlMain.setVisible(true);
}
//-------------------END OF ACTION PERFORMED METHOD-------------------------//
}
/* Future Plans:
-Add AI
*/
/* Changes:
2.0- changes below: bug fixes [Stable]
1.95- fixed bug: TryAgain Button takes over Status Label
1.9- added Label that shows Player 1 and Player 2 wins
1.8- removed Try Again pop-up. Added Try Again Button
1.7- removed Back Button. Added Continue Button
1.6- fixed bugs below...
fixed bug: Same name for both players.
fixed bug: Names updated in game if user changes.
fixed bug: Names are null if user presses cancel.
1.5- added function to set Player Names.
1.4- program more efficient/faster.
1.35- fixed bugs, added turn status to status bar.
1.3- added Status bar with quit button during gameplay.
1.2- changed theme.
1.15- fixed bug: one win combo not working.
1.1- added play again function.
1.0- changes below: (problems gone!) [Stable]
0.9- added back button, added comments.
0.8- added dynamic win message.
0.7- added game function- game playable.
0.6- changed menu layout.
0.5- basic functions with menu and nice GUI.
*/


/* LAYOUT OF THE GAME:

THE WINDOW: (pnlMenu/pnlMain)
pnlMenu: (THE MENU)
pnlMain: (pnlTop/pnlBottom)
pnlTop: (pnlPlayingField/INSTRUCTIONS/ABOUT/NEW GAME)
pnlBottom:(STATUS BAR/BACK BUTTON)

/////////////////////////////////////////////////--------------|
/ pnlMenu / |
/ / |
/////////////////////////////////////////////////-----| |
/ / | |
/ / | |
/ / | |
/ pnlTop / | |
/ / | |- MAIN WINDOW
/ / |- |
/ / |pnlMain |
/ / | |
/ / | |
/ / | |
/ / | |
/ / | |
///////////////////////////////////////////////// | |
/ pnlBottom / | |
/////////////////////////////////////////////////-----|--------|

*/

 

 

Besides this tic-tac-toe tutorial from John, definitely check out his Java tutorial series!

 

We have many implementation and topics on tic-tac-toe on the site. Check them out for some ideas!


uploaded .jar file here:

Attached Files


Edited by Roger, 25 February 2013 - 04:36 PM.

  • 0

#3 Blmaster

Blmaster

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 52 posts

Posted 13 October 2008 - 02:09 PM

I got the AI done!
Here is Version 3.0

/*
	Title: Tic-Tac-Toe Game
	Created: October 5, 2008
	Last Edited: October 13, 2008
	Author: Blmaster
	Changes:
		See Below...
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TicTacToe implements ActionListener	{
	final String VERSION = "3.0";
//Setting up ALL the variables
	JFrame window = new JFrame("Tic-Tac-Toe " + VERSION);
	
	JMenuBar mnuMain = new JMenuBar();
	JMenuItem 	mnuNewGame = new JMenuItem("New Game"),	
					mnuInstruction = new JMenuItem("Instructions"),
					mnuExit = new JMenuItem("Exit"), 
					mnuAbout = new JMenuItem("About");
	
	JButton 	btn1v1 = new JButton("Player vs Player"),
				btn1vCPU = new JButton("Player vs Computer"),
				btnQuit = new JButton("Quit"),
				btnSetName = new JButton("Set Player Names"),
				btnContinue = new JButton("Continue..."),
				btnTryAgain = new JButton("Try Again?");
	JButton btnEmpty[] = new JButton[10];
	
	JPanel 	pnlNewGame = new JPanel(),
				pnlMenu = new JPanel(),
				pnlMain = new JPanel(),
				pnlTop = new JPanel(),
				pnlBottom = new JPanel(),
				pnlQuitNTryAgain = new JPanel(),
				pnlPlayingField = new JPanel();
				
	JLabel 	lblTitle = new JLabel("Tic-Tac-Toe"),
				lblTurn = new JLabel(),
				lblStatus = new JLabel("", JLabel.CENTER),
				lblMode = new JLabel("", JLabel.LEFT);
	JTextArea txtMessage = new JTextArea();
	
	final int winCombo[][] = new int[][]	{
		{1, 2, 3}, 			{1, 4, 7}, 		{1, 5, 9},
		{4, 5, 6}, 			{2, 5, 8}, 		{3, 5, 7},
		{7, 8, 9}, 			{3, 6, 9}
/*Horizontal Wins*/	/*Vertical Wins*/ /*Diagonal Wins*/
	};
	final int X = 535, Y = 342,
		mainColorR = 190, mainColorG = 50, mainColorB = 50,
		btnColorR = 70, btnColorG = 70, btnColorB = 70;
	Color clrBtnWonColor = new Color(190, 190, 190);
	int 	turn = 1,
			player1Won = 0, player2Won = 0,
			wonNumber1 = 1, wonNumber2 = 1, wonNumber3 = 1,
			option;
	boolean 	inGame = false,
				CPUGame = false,
				win = false;
	String 	message,
				Player1 = "Player 1", Player2 = "Player 2",
				tempPlayer2 = "Player 2";
	

	public TicTacToe()	{	//Setting game properties and layout and sytle...
	//Setting window properties:
		window.setSize(X, Y);
		window.setLocation(350, 260);
		//window.setResizable(false);
		window.setLayout(new BorderLayout());
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	//Setting Menu, Main, Top, Bottom Panel Layout/Backgrounds
		pnlMenu.setLayout(new FlowLayout(FlowLayout.CENTER));
		pnlTop.setLayout(new FlowLayout(FlowLayout.CENTER));
		pnlBottom.setLayout(new FlowLayout(FlowLayout.CENTER));
		
		pnlNewGame.setBackground(new Color(mainColorR - 50, mainColorG - 50, mainColorB- 50));
		pnlMenu.setBackground(new Color((mainColorR - 50), (mainColorG - 50), (mainColorB- 50)));
		pnlMain.setBackground(new Color(mainColorR, mainColorG, mainColorB));
		pnlTop.setBackground(new Color(mainColorR, mainColorG, mainColorB));
		pnlBottom.setBackground(new Color(mainColorR, mainColorG, mainColorB));
		
	//Setting up Panel QuitNTryAgain
		pnlQuitNTryAgain.setLayout(new GridLayout(1, 2, 2, 2));
		pnlQuitNTryAgain.add(btnTryAgain);
		pnlQuitNTryAgain.add(btnQuit);
		
	//Adding menu items to menu bar
		mnuMain.add(mnuNewGame);
		mnuMain.add(mnuInstruction);
		mnuMain.add(mnuAbout);
		mnuMain.add(mnuExit);//	Menu Bar is Complete
		
	//Adding buttons to NewGame panel
		pnlNewGame.setLayout(new GridLayout(4, 1, 2, 10));
		pnlNewGame.add(btnContinue);
		pnlNewGame.add(btn1v1);
		pnlNewGame.add(btn1vCPU);
		pnlNewGame.add(btnSetName);
	
	//Setting Button propertied
		btnTryAgain.setEnabled(false);
		btnContinue.setEnabled(false);
	
	//Setting txtMessage Properties
		txtMessage.setBackground(new Color(mainColorR-30, mainColorG-30, mainColorB-30));
		txtMessage.setForeground(Color.white);
		txtMessage.setEditable(false);
		
	//Adding Action Listener to all the Buttons and Menu Items
		mnuNewGame.addActionListener(this);
		mnuExit.addActionListener(this);
		mnuInstruction.addActionListener(this);
		mnuAbout.addActionListener(this);
		btn1v1.addActionListener(this);
		btn1vCPU.addActionListener(this);
		btnQuit.addActionListener(this);
		btnSetName.addActionListener(this);
		btnContinue.addActionListener(this);
		btnTryAgain.addActionListener(this);
	
	//Setting up the playing field
		pnlPlayingField.setLayout(new GridLayout(3, 3, 2, 2));
		pnlPlayingField.setBackground(Color.black);
		for(int i=1; i<=9; i++)	{
			btnEmpty[i] = new JButton();
			btnEmpty[i].setBackground(new Color(btnColorR, btnColorG, btnColorB));
			btnEmpty[i].addActionListener(this);
			pnlPlayingField.add(btnEmpty[i]);//	Playing Field is Compelte
		}

	//Adding everything needed to pnlMenu and pnlMain
		lblMode.setForeground(Color.white);
		pnlMenu.add(lblMode);
		pnlMenu.add(mnuMain);
		pnlMain.add(lblTitle);
		
	//Adding to window and Showing window
		window.add(pnlMenu, BorderLayout.NORTH);
		window.add(pnlMain, BorderLayout.CENTER);
		window.setVisible(true);
	}
	
	public static void main(String[] args)	{
		new TicTacToe();//	Calling the class construtor.
							//		PROGRAM STARTS HERE!
	}



/*
		-------------------------
		Start of all METHODS.	|
		-------------------------
*/
	public void showGame()	{	//	Shows the Playing Field
										//	*IMPORTANT*- Does not start out brand new (meaning just shows what it had before)
		clearPanelSouth();
		pnlMain.setLayout(new BorderLayout());
		pnlTop.setLayout(new BorderLayout());
		pnlBottom.setLayout(new BorderLayout());
		pnlTop.add(pnlPlayingField);
		pnlBottom.add(lblTurn, BorderLayout.WEST);
		pnlBottom.add(lblStatus, BorderLayout.CENTER);
		pnlBottom.add(pnlQuitNTryAgain, BorderLayout.EAST);
		pnlMain.add(pnlTop, BorderLayout.CENTER);
		pnlMain.add(pnlBottom, BorderLayout.SOUTH);
		pnlPlayingField.requestFocus();
		inGame = true;
		checkTurn();
		checkWinStatus();
	}
//-----------------------------------------------------------------------------------------------------------------------------------	
	public void newGame()	{	//	Sets all the game required variables to default
											//	and then shows the playing field.
											//	(Basically: Starts a new 1v1 Game)
		btnEmpty[wonNumber1].setBackground(new Color(btnColorR, btnColorG, btnColorB));
		btnEmpty[wonNumber2].setBackground(new Color(btnColorR, btnColorG, btnColorB));
		btnEmpty[wonNumber3].setBackground(new Color(btnColorR, btnColorG, btnColorB));
		for(int i=1; i<10; i++)	{
			btnEmpty[i].setText("");
			btnEmpty[i].setEnabled(true);
		}
		turn = 1;
		win = false;
		showGame();
	}
//-----------------------------------------------------------------------------------------------------------------------------------	
	public void quit()	{
		inGame = false;
		lblMode.setText("");
		btnContinue.setEnabled(false);
		clearPanelSouth();
		setDefaultLayout();
		pnlTop.add(pnlNewGame);
		pnlMain.add(pnlTop);
	}
//-----------------------------------------------------------------------------------------------------------------------------------	
	public void checkWin()	{	//	checks if there are 3 symbols in a row vertically, diagonally, or horizontally.
										//	then shows a message and disables buttons. If the game is over then it asks
										//	if you want to play again.
		for(int i=0; i<8; i++)	{
			if(
				!btnEmpty[winCombo[i][0]].getText().equals("") &&
				btnEmpty[winCombo[i][0]].getText().equals(btnEmpty[winCombo[i][1]].getText()) &&
				//								if {1 == 2 && 2 == 3}
				btnEmpty[winCombo[i][1]].getText().equals(btnEmpty[winCombo[i][2]].getText()))	{
				/*
					The way this checks the if someone won is:
					First: it checks if the btnEmpty[x] is not equal to an empty string-	x being the array number 
						inside the multi-dementional array winCombo[checks inside each of the 7 sets][the first number]
					Secong: it checks if btnEmpty[x] is equal to btnEmpty[y]- x being winCombo[each set][the first number]
						y being winCombo[each set the same as x][the second number] (So basically checks if the first and
						second number in each set is equal to each other)
					Third: it checks if btnEmtpy[y] is eual to btnEmpty[z]- y being the same y as last time and z being
						winCombo[each set as y][the third number]
					Conclusion:	So basically it checks if it is equal to the btnEmpty is equal to each set of numbers
				*/
				win = true;
				wonNumber1 = winCombo[i][0];
				wonNumber2 = winCombo[i][1];
				wonNumber3 = winCombo[i][2];
				btnEmpty[wonNumber1].setBackground(clrBtnWonColor);
				btnEmpty[wonNumber2].setBackground(clrBtnWonColor);
				btnEmpty[wonNumber3].setBackground(clrBtnWonColor);
				break;
			}
		}
		if(win || (!win && turn>9))	{
			if(win)	{
				if(btnEmpty[wonNumber1].getText().equals("X"))	{
					message = Player1 + " has won";
					player1Won++;
				}
				else	{
					message = Player2 + " has won";
					player2Won++;
				}
		}	else if(!win && turn>9)
				message = "Both players have tied!\nBetter luck next time.";
			showMessage(message);
			for(int i=1; i<=9; i++)	{
				btnEmpty[i].setEnabled(false);
			}
			btnTryAgain.setEnabled(true);
			checkWinStatus();
		} else
			checkTurn();
	}
//-----------------------------------------------------------------------------------------------------------------------------------	
	public void AI()	{
		int computerButton;
		if(turn <= 9)	{
			turn++;
			computerButton = CPU.doMove(
				btnEmpty[1], btnEmpty[2], btnEmpty[3],
				btnEmpty[4], btnEmpty[5], btnEmpty[6],
				btnEmpty[7], btnEmpty[8], btnEmpty[9]);
			if(computerButton == 0)
				Random();
			else {
				btnEmpty[computerButton].setText("O");
				btnEmpty[computerButton].setEnabled(false);
			}
			checkWin();
		}
	}
//-----------------------------------------------------------------------------------------------------------------------------------	
	public void Random()	{
		int random;
		if(turn <= 9)	{
			random = 0;
			while(random == 0)	{
				random = (int)(Math.random() * 10);
			}
			if(CPU.doRandomMove(btnEmpty[random]))	{
				btnEmpty[random].setText("O");
				btnEmpty[random].setEnabled(false);
			} else {
				Random();
			}
		}
	}
//-----------------------------------------------------------------------------------------------------------------------------------	
	public void checkTurn()	{
		String whoTurn;
		if(!(turn % 2 == 0))	{
			whoTurn = Player1 + " [X]";
		}	else	{
			whoTurn = Player2 + " [O]";
		}
		lblTurn.setText("Turn: " + whoTurn);
	}
//-----------------------------------------------------------------------------------------------------------------------------------	
	public void askUserForPlayerNames()	{
		String temp;
		boolean tempIsValid = false;
		temp = getInput("Enter player 1 name:", Player1);
		if(temp == null)	{/*Do Nothing*/}
		else if(temp.equals(""))
			showMessage("Invalid Name!");
		else if(temp.equals(Player2))	{
			option = askMessage("Player 1 name matches Player 2's\nDo you want to continue?", "Name Match", JOptionPane.YES_NO_OPTION);
			if(option == JOptionPane.YES_OPTION)
				tempIsValid = true;
		} else if(temp != null)	{
			tempIsValid = true;
		}
		if(tempIsValid)	{
			Player1 = temp;
			tempIsValid = false;
		}
		
		temp = getInput("Enter player 2 name:", Player2);
		if(temp == null)	{/*Do Nothing*/}
		else if(temp.equals(""))
			showMessage("Invalid Name!");
		else if(temp.equals(Player1))	{
			option = askMessage("Player 2 name matches Player 1's\nDo you want to continue?", "Name Match", JOptionPane.YES_NO_OPTION);
			if(option == JOptionPane.YES_OPTION)
				tempIsValid = true;
		} else if(temp != null)	{
			tempIsValid = true;
		}
		if(tempIsValid)	{
			Player2 = temp;
			tempPlayer2 = temp;
			tempIsValid = false;
		}
	}
//-----------------------------------------------------------------------------------------------------------------------------------	
	public void setDefaultLayout()	{
		pnlMain.setLayout(new GridLayout(2, 1, 2, 5));
		pnlTop.setLayout(new FlowLayout(FlowLayout.CENTER));
		pnlBottom.setLayout(new FlowLayout(FlowLayout.CENTER));
	}
//-----------------------------------------------------------------------------------------------------------------------------------	
	public void checkWinStatus()	{
		lblStatus.setText(Player1 + ": " + player1Won + " | " + Player2 + ": " + player2Won);	
	}
//-----------------------------------------------------------------------------------------------------------------------------------	
	public int askMessage(String msg, String tle, int op)	{
		return JOptionPane.showConfirmDialog(null, msg, tle, op);
	}
//-----------------------------------------------------------------------------------------------------------------------------------
	public String getInput(String msg, String setText)	{
		return JOptionPane.showInputDialog(null, msg, setText);
	}
//-----------------------------------------------------------------------------------------------------------------------------------
	public void showMessage(String msg)	{
		JOptionPane.showMessageDialog(null, msg);
	}
//-----------------------------------------------------------------------------------------------------------------------------------	
	public void clearPanelSouth()	{	//Removes all the possible panels 
												//that pnlMain, pnlTop, pnlBottom
												//could have.
		pnlMain.remove(lblTitle);
		pnlMain.remove(pnlTop);
		pnlMain.remove(pnlBottom);
		pnlTop.remove(pnlNewGame);
		pnlTop.remove(txtMessage);
		pnlTop.remove(pnlPlayingField);
		pnlBottom.remove(lblTurn);
		pnlBottom.remove(pnlQuitNTryAgain);
	}
/*
		-------------------------------------
		End of all non-Abstract METHODS.		|
		-------------------------------------
*/

//-------------------ACTION PERFORMED METHOD (Button Click --> Action?)-------------------------//	
	public void actionPerformed(ActionEvent click)	{
		Object source = click.getSource();
		for(int i=1; i<=9; i++)	{
			if(source == btnEmpty[i] && turn <	10)	{
				if(!(turn % 2 == 0))
					btnEmpty[i].setText("X");
				else
					btnEmpty[i].setText("O");
				btnEmpty[i].setEnabled(false);
				pnlPlayingField.requestFocus();
				turn++;
				checkWin();
				if(CPUGame && win == false)
					AI();
			}
		}
		if(source == mnuNewGame || source == mnuInstruction || source == mnuAbout)	{
			clearPanelSouth();
			setDefaultLayout();
			
			if(source == mnuNewGame)	{//NewGame
				pnlTop.add(pnlNewGame);
			}	
			else if(source == mnuInstruction || source == mnuAbout)	{
				if(source == mnuInstruction)	{// Instructions
					message = 	"Instructions:\n\n" +
									"Your goal is to be the first player to get 3 X's or O's in a\n" +
									"row. (horizontally, diagonally, or vertically)\n" +
									Player1 + ": X\n" +
									Player2 + ": O\n";
				} else	{//About
					message = 	"About:\n\n" +
									"Title: Tic-Tac-Toe\n" +
									"Creator: Blmaster\n" +
									"Version: " + VERSION + "\n";
				}
				txtMessage.setText(message);
				pnlTop.add(txtMessage);
			}	
			pnlMain.add(pnlTop);
		}
		else if(source == btn1v1 || source == btn1vCPU)	{
			if(inGame)	{
				option = askMessage("If you start a new game," +
					"your current game will be lost..." + "\n" +
					"Are you sure you want to continue?", 
					"Quit Game?" ,JOptionPane.YES_NO_OPTION
				);
				if(option == JOptionPane.YES_OPTION)
					inGame = false;
			}
			if(!inGame)	{
				btnContinue.setEnabled(true);
				if(source == btn1v1)	{// 1 v 1 Game
					Player2 = tempPlayer2;
					player1Won = 0;
					player2Won = 0;
					lblMode.setText("1 v 1");
					CPUGame = false;	
					newGame();
				} else	{// 1 v CPU Game
					Player2 = "Computer";
					player1Won = 0;
					player2Won = 0;
					lblMode.setText("1 v CPU");
					CPUGame = true;
					newGame();
				}
			}
		}
		else if(source == btnContinue)	{
			checkTurn();
			showGame();
		}
		else if(source == btnSetName)	{
			askUserForPlayerNames();
		}
		else if(source == mnuExit)	{
			option = askMessage("Are you sure you want to exit?", "Exit Game", JOptionPane.YES_NO_OPTION);
			if(option == JOptionPane.YES_OPTION)
				System.exit(0);
		}
		else if(source == btnTryAgain)	{
			newGame();
			btnTryAgain.setEnabled(false);
		}
		else if(source == btnQuit)	{
			quit();
		}
		pnlMain.setVisible(false);
		pnlMain.setVisible(true);
	}
//-------------------END OF ACTION PERFORMED METHOD-------------------------//
}
/* Future Plans:
*/
/*	Changes:
	3.0- changes below: Added AI [Stable]
		2.9-	Added Label which shows waht game mode user is in.
		2.8-	Quit goes back to Gmae Options rather than Main Screen.
		2.79-	fixed bug: win count will not show 0 when New Game is started.
		2.75-	fixed bug: Players win count didnt change to 0 when New Game is started.
		2.7-	Player 2 name will change back from Computer in single player.
		2.6-	AI name is constant to Computer.
		2.55- fixed bug: Ad. AI clicks middle spot if available.
		2.5-	improved basic AI to Advanced AI.
		2.4-	fixed bugs below...
			fixed bug: AI crashes sometime.
			fixed bug: AI does checkWin twice.
			fixed bug: AI does not count as turn.
			fixed bug: AI does not check if won.
		2.3-	added basic AI (Artificial Intelligence).
		2.2-	Player vs CPU does random move.
		2.1-	removed unnessary code. more effienct.
	2.0- changes below: Changed Layout [Stable]
		1.95- fixed bug: TryAgain Button takes over Status Label
		1.9-	added Label that shows Player 1 and Player 2 wins
		1.8-	removed Try Again pop-up. Added Try Again Button
		1.7-	removed Back Button. Added Continue Button
		1.6-	fixed bugs below...
			fixed bug: Same name for both players.
			fixed bug: Names updated in game if user changes.
			fixed bug: Names are null if user presses cancel.
		1.5-	added function to set Player Names.
		1.4-	program more efficient/faster.
		1.35- fixed bugs, added turn status to status bar.
		1.3-	added Status bar with quit button during gameplay.
		1.2-	changed theme.
		1.15- fixed bug: one win combo not working.
		1.1-	added play again function.
	1.0- 	changes below: (problems gone!) [Stable]
		0.9-	added back button, added comments.
		0.8-	added dynamic win message.
		0.7-	added game function- game playable.
		0.6-	changed menu layout.
		0.5-	basic functions with menu and nice GUI.
*/


/*	LAYOUT OF THE GAME:
	
	THE WINDOW: (pnlMenu/pnlMain)
	pnlMenu: (THE MENU)
	pnlMain:	(pnlTop/pnlBottom)
	pnlTop:	(pnlPlayingField/INSTRUCTIONS/ABOUT/NEW GAME)
	pnlBottom:(STATUS BAR/BACK BUTTON)

	/////////////////////////////////////////////////--------------|
	/						pnlMenu								/					|
	/																/					|
	/////////////////////////////////////////////////-----|			|
	/																/		|			|
	/																/		|			|
	/																/		|			|
	/						pnlTop								/		|			|
	/																/		|			|- MAIN WINDOW
	/																/		|-			|
	/																/		|pnlMain	|
	/																/		|			|
	/																/		|			|
	/																/		|			|
	/																/		|			|
	/																/		|			|		
	/////////////////////////////////////////////////		|			|
	/						pnlBottom							/		|			|
	/////////////////////////////////////////////////-----|--------|
	
*/

The AI class
//Tic-Tac-Toe Artificial Intelligence
//Created: October 13, 2008
import javax.swing.JButton;

public class CPU	{
	public static int doMove(JButton btn1, JButton btn2, JButton btn3, JButton btn4, JButton btn5, JButton btn6, JButton btn7, JButton btn8, JButton btn9)	{
		if(btn1.getText().equals("O") && btn2.getText().equals("O") && btn3.getText().equals(""))
			return 3;
		else if(btn4.getText().equals("O") && btn5.getText().equals("O") && btn6.getText().equals(""))
			return 6;
		else if(btn7.getText().equals("O") && btn8.getText().equals("O") && btn9.getText().equals(""))
			return 9;
		
		else if(btn2.getText().equals("O") && btn3.getText().equals("O") && btn1.getText().equals(""))
			return 1;
		else if(btn5.getText().equals("O") && btn6.getText().equals("O") && btn4.getText().equals(""))
			return 4;
		else if(btn8.getText().equals("O") && btn9.getText().equals("O") && btn7.getText().equals(""))
			return 7;
		
		else if(btn1.getText().equals("O") && btn3.getText().equals("O") && btn2.getText().equals(""))
			return 2;
		else if(btn4.getText().equals("O") && btn6.getText().equals("O") && btn5.getText().equals(""))
			return 5;
		else if(btn7.getText().equals("O") && btn9.getText().equals("O") && btn8.getText().equals(""))
			return 8;
		
		else if(btn1.getText().equals("O") && btn4.getText().equals("O") && btn7.getText().equals(""))
			return 7;
		else if(btn2.getText().equals("O") && btn5.getText().equals("O") && btn8.getText().equals(""))
			return 8;
		else if(btn3.getText().equals("O") && btn6.getText().equals("O") && btn9.getText().equals(""))
			return 9;
		
		else if(btn4.getText().equals("O") && btn7.getText().equals("O") && btn1.getText().equals(""))
			return 1;
		else if(btn5.getText().equals("O") && btn8.getText().equals("O") && btn2.getText().equals(""))
			return 2;
		else if(btn6.getText().equals("O") && btn9.getText().equals("O") && btn3.getText().equals(""))
			return 3;
		
		else if(btn1.getText().equals("O") && btn7.getText().equals("O") && btn4.getText().equals(""))
			return 4;
		else if(btn2.getText().equals("O") && btn8.getText().equals("O") && btn5.getText().equals(""))
			return 5;
		else if(btn3.getText().equals("O") && btn9.getText().equals("O") && btn6.getText().equals(""))
			return 6;
		
		else if(btn1.getText().equals("O") && btn5.getText().equals("O") && btn9.getText().equals(""))
			return 9;
		else if(btn5.getText().equals("O") && btn9.getText().equals("O") && btn1.getText().equals(""))
			return 1;
		else if(btn1.getText().equals("O") && btn9.getText().equals("O") && btn5.getText().equals(""))
			return 5;
		
		else if(btn3.getText().equals("O") && btn5.getText().equals("O") && btn7.getText().equals(""))
			return 7;
		else if(btn7.getText().equals("O") && btn5.getText().equals("O") && btn3.getText().equals(""))
			return 3;
		else if(btn7.getText().equals("O") && btn3.getText().equals("O") && btn5.getText().equals(""))
			return 5;
		
		else if(btn1.getText().equals("X") && btn2.getText().equals("X") && btn3.getText().equals(""))
			return 3;
		else if(btn4.getText().equals("X") && btn5.getText().equals("X") && btn6.getText().equals(""))
			return 6;
		else if(btn7.getText().equals("X") && btn8.getText().equals("X") && btn9.getText().equals(""))
			return 9;
		
		else if(btn2.getText().equals("X") && btn3.getText().equals("X") && btn1.getText().equals(""))
			return 1;
		else if(btn5.getText().equals("X") && btn6.getText().equals("X") && btn4.getText().equals(""))
			return 4;
		else if(btn8.getText().equals("X") && btn9.getText().equals("X") && btn7.getText().equals(""))
			return 7;
		
		else if(btn1.getText().equals("X") && btn3.getText().equals("X") && btn2.getText().equals(""))
			return 2;
		else if(btn4.getText().equals("X") && btn6.getText().equals("X") && btn5.getText().equals(""))
			return 5;
		else if(btn7.getText().equals("X") && btn9.getText().equals("X") && btn8.getText().equals(""))
			return 8;

		else if(btn1.getText().equals("X") && btn4.getText().equals("X") && btn7.getText().equals(""))
			return 7;
		else if(btn2.getText().equals("X") && btn5.getText().equals("X") && btn8.getText().equals(""))
			return 8;
		else if(btn3.getText().equals("X") && btn6.getText().equals("X") && btn9.getText().equals(""))
			return 9;
		
		else if(btn4.getText().equals("X") && btn7.getText().equals("X") && btn1.getText().equals(""))
			return 1;
		else if(btn5.getText().equals("X") && btn8.getText().equals("X") && btn2.getText().equals(""))
			return 2;
		else if(btn6.getText().equals("X") && btn9.getText().equals("X") && btn3.getText().equals(""))
			return 3;
		
		else if(btn1.getText().equals("X") && btn7.getText().equals("X") && btn4.getText().equals(""))
			return 4;
		else if(btn2.getText().equals("X") && btn8.getText().equals("X") && btn5.getText().equals(""))
			return 5;
		else if(btn3.getText().equals("X") && btn9.getText().equals("X") && btn6.getText().equals(""))
			return 6;
		
		else if(btn1.getText().equals("X") && btn5.getText().equals("X") && btn9.getText().equals(""))
			return 9;
		else if(btn5.getText().equals("X") && btn9.getText().equals("X") && btn1.getText().equals(""))
			return 1;
		else if(btn1.getText().equals("X") && btn9.getText().equals("X") && btn5.getText().equals(""))
			return 5;
		
		else if(btn3.getText().equals("X") && btn5.getText().equals("X") && btn7.getText().equals(""))
			return 7;
		else if(btn7.getText().equals("X") && btn5.getText().equals("X") && btn3.getText().equals(""))
			return 3;
		else if(btn7.getText().equals("X") && btn3.getText().equals("X") && btn5.getText().equals(""))
			return 5;
		
		else if(btn1.getText().equals("X") && btn5.getText().equals("O") && btn9.getText().equals("X"))
			return 6;
			
		else if(btn3.getText().equals("X") && btn5.getText().equals("O") && btn7.getText().equals("X")) 
			return 4;
		
		else if(btn5.getText().equals(""))
			return 5;
		
		else if(btn1.getText().equals(""))
			return 1;
		else
			return 0;
	}
	
	
	public static boolean doRandomMove(JButton button)	{
		if(button.getText().equals("O") || button.getText().equals("X"))
			return false;
		else	{
			return true;
		}
	}
}

The jar file!

Attached Files


  • 0

#4 Blmaster

Blmaster

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 52 posts

Posted 24 November 2008 - 04:13 PM

Sry for triple posting but i just wanted to refresh this and see if anyone actually likes this? opinions on how to improve are greatly appreciated!
  • 0

#5 GNightOwl

GNightOwl

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 03 December 2008 - 04:17 PM

I'm very excited to view your program, I've been working on a similar project as a part of my app. I'm a new user so can't download the jar yet.
  • 0

#6 GNightOwl

GNightOwl

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 03 December 2008 - 04:21 PM

Wow, very nicely done. You beat me :o
Now I have to go back and improve mine.
  • 0

#7 morefood2001

morefood2001

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1,011 posts

Posted 08 December 2008 - 12:09 PM

Nice code, and +rep :)
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#8 Blmaster

Blmaster

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 52 posts

Posted 10 December 2008 - 02:36 PM

oh thanks i was very impressed to see that the layout came as I expected
  • 0

#9 whitey6993

whitey6993

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 156 posts

Posted 29 December 2008 - 10:31 AM

This is pretty sweet. The AI is a nice touch also.
  • 0

#10 jojorusn

jojorusn

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 12 January 2009 - 09:25 PM

cool
  • 0

#11 ranias86

ranias86

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 17 January 2009 - 02:37 PM

thaaaanks
  • 0

#12 eeeeee

eeeeee

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 24 January 2009 - 10:50 AM

thank you for sharing
  • 0





Also tagged with one or more of these keywords: tic-tac-toe, source, code