SlideShare a Scribd company logo
1 of 26
Download to read offline
import java.util.Scanner;
import java.util.Random;
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
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! Better 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 Do 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 Do 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:  " +
"Your goal is to be the first player to get 3 X's or O's in a " +
"row. (horizontally, diagonally, or vertically) " +
Player1 + ": X " +
Player2 + ": O ";
} else {//About
message = "About:  " +
"Title: Tic-Tac-Toe " +
"Creator: Blmaster " +
"Version: " + VERSION + " ";
}
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..." + " " +
"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-------------------------//
}
Solution
import java.util.Scanner;
import java.util.Random;
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
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! Better 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 Do 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 Do 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:  " +
"Your goal is to be the first player to get 3 X's or O's in a " +
"row. (horizontally, diagonally, or vertically) " +
Player1 + ": X " +
Player2 + ": O ";
} else {//About
message = "About:  " +
"Title: Tic-Tac-Toe " +
"Creator: Blmaster " +
"Version: " + VERSION + " ";
}
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..." + " " +
"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-------------------------//
}

More Related Content

Similar to import java.util.Scanner; import java.util.Random; public clas.pdf

ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfrajkumarm401
 
011 more swings_adv
011 more swings_adv011 more swings_adv
011 more swings_advChaimaa Kabb
 
Java ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdfJava ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdfatulkapoor33
 
I hope the below code is helpful to you, please give me rewards.im.pdf
I hope the below code is helpful to you, please give me rewards.im.pdfI hope the below code is helpful to you, please give me rewards.im.pdf
I hope the below code is helpful to you, please give me rewards.im.pdfapexelectronices01
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfarchanaemporium
 
i need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfi need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfpetercoiffeur18
 
Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfmanjan6
 
Hello, I need some assistance in writing a java program THAT MUST US.pdf
Hello, I need some assistance in writing a java program THAT MUST US.pdfHello, I need some assistance in writing a java program THAT MUST US.pdf
Hello, I need some assistance in writing a java program THAT MUST US.pdfFashionColZone
 
Flash auto play image gallery
Flash auto play image galleryFlash auto play image gallery
Flash auto play image galleryBoy Jeorge
 
Chapter 03 game input
Chapter 03 game inputChapter 03 game input
Chapter 03 game inputboybuon205
 
Swift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfSwift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfJkPoppy
 
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdfbadshetoms
 
Creating a Facebook Clone - Part XVI.pdf
Creating a Facebook Clone - Part XVI.pdfCreating a Facebook Clone - Part XVI.pdf
Creating a Facebook Clone - Part XVI.pdfShaiAlmog1
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfFashionColZone
 
csc 208
csc 208csc 208
csc 208priska
 
10 awt event model
10 awt event model10 awt event model
10 awt event modelBayarkhuu
 
C# Program. Create a Windows application that has the functionality .pdf
C# Program. Create a Windows application that has the functionality .pdfC# Program. Create a Windows application that has the functionality .pdf
C# Program. Create a Windows application that has the functionality .pdffathimalinks
 
1) Write a shortsnippetofcodethatcreates a J Panel objectcalled p1, .pdf
1) Write a shortsnippetofcodethatcreates a J Panel objectcalled p1, .pdf1) Write a shortsnippetofcodethatcreates a J Panel objectcalled p1, .pdf
1) Write a shortsnippetofcodethatcreates a J Panel objectcalled p1, .pdfoptokunal1
 
ANSimport javax.swing.;import java.awt.; import java.awt.ev.pdf
ANSimport javax.swing.;import java.awt.; import java.awt.ev.pdfANSimport javax.swing.;import java.awt.; import java.awt.ev.pdf
ANSimport javax.swing.;import java.awt.; import java.awt.ev.pdfanugrahafancy
 

Similar to import java.util.Scanner; import java.util.Random; public clas.pdf (20)

ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
 
011 more swings_adv
011 more swings_adv011 more swings_adv
011 more swings_adv
 
Java ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdfJava ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdf
 
I hope the below code is helpful to you, please give me rewards.im.pdf
I hope the below code is helpful to you, please give me rewards.im.pdfI hope the below code is helpful to you, please give me rewards.im.pdf
I hope the below code is helpful to you, please give me rewards.im.pdf
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdf
 
i need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfi need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdf
 
Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdf
 
Hello, I need some assistance in writing a java program THAT MUST US.pdf
Hello, I need some assistance in writing a java program THAT MUST US.pdfHello, I need some assistance in writing a java program THAT MUST US.pdf
Hello, I need some assistance in writing a java program THAT MUST US.pdf
 
Flash auto play image gallery
Flash auto play image galleryFlash auto play image gallery
Flash auto play image gallery
 
Chapter 03 game input
Chapter 03 game inputChapter 03 game input
Chapter 03 game input
 
Swift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfSwift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdf
 
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdf
 
Creating a Facebook Clone - Part XVI.pdf
Creating a Facebook Clone - Part XVI.pdfCreating a Facebook Clone - Part XVI.pdf
Creating a Facebook Clone - Part XVI.pdf
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdf
 
Oop lecture9 10
Oop lecture9 10Oop lecture9 10
Oop lecture9 10
 
csc 208
csc 208csc 208
csc 208
 
10 awt event model
10 awt event model10 awt event model
10 awt event model
 
C# Program. Create a Windows application that has the functionality .pdf
C# Program. Create a Windows application that has the functionality .pdfC# Program. Create a Windows application that has the functionality .pdf
C# Program. Create a Windows application that has the functionality .pdf
 
1) Write a shortsnippetofcodethatcreates a J Panel objectcalled p1, .pdf
1) Write a shortsnippetofcodethatcreates a J Panel objectcalled p1, .pdf1) Write a shortsnippetofcodethatcreates a J Panel objectcalled p1, .pdf
1) Write a shortsnippetofcodethatcreates a J Panel objectcalled p1, .pdf
 
ANSimport javax.swing.;import java.awt.; import java.awt.ev.pdf
ANSimport javax.swing.;import java.awt.; import java.awt.ev.pdfANSimport javax.swing.;import java.awt.; import java.awt.ev.pdf
ANSimport javax.swing.;import java.awt.; import java.awt.ev.pdf
 

More from annaipowerelectronic

Structure Hydra has a tubular body, with only one opening the mouth.pdf
Structure Hydra has a tubular body, with only one opening the mouth.pdfStructure Hydra has a tubular body, with only one opening the mouth.pdf
Structure Hydra has a tubular body, with only one opening the mouth.pdfannaipowerelectronic
 
Quality management ensures that an organization, product or service .pdf
Quality management ensures that an organization, product or service .pdfQuality management ensures that an organization, product or service .pdf
Quality management ensures that an organization, product or service .pdfannaipowerelectronic
 
public class Deque {private class Node {public int data;public.pdf
public class Deque {private class Node {public int data;public.pdfpublic class Deque {private class Node {public int data;public.pdf
public class Deque {private class Node {public int data;public.pdfannaipowerelectronic
 
Microsoft Excel is a spreadsheet program used to store and retrieve .pdf
Microsoft Excel is a spreadsheet program used to store and retrieve .pdfMicrosoft Excel is a spreadsheet program used to store and retrieve .pdf
Microsoft Excel is a spreadsheet program used to store and retrieve .pdfannaipowerelectronic
 
Mean = xffS = Sqrt((x-x)2fn)intervalMidpoint(x)frequency.pdf
Mean = xffS = Sqrt((x-x)2fn)intervalMidpoint(x)frequency.pdfMean = xffS = Sqrt((x-x)2fn)intervalMidpoint(x)frequency.pdf
Mean = xffS = Sqrt((x-x)2fn)intervalMidpoint(x)frequency.pdfannaipowerelectronic
 
Moles of Be = mass of Bemolar mass of Be= (0.33 g)(9.012 gmol).pdf
Moles of Be = mass of Bemolar mass of Be= (0.33 g)(9.012 gmol).pdfMoles of Be = mass of Bemolar mass of Be= (0.33 g)(9.012 gmol).pdf
Moles of Be = mass of Bemolar mass of Be= (0.33 g)(9.012 gmol).pdfannaipowerelectronic
 
Lyme disease is a bacterial infection which is caused by bacteria ca.pdf
Lyme disease is a bacterial infection which is caused by bacteria ca.pdfLyme disease is a bacterial infection which is caused by bacteria ca.pdf
Lyme disease is a bacterial infection which is caused by bacteria ca.pdfannaipowerelectronic
 
above molecule has 12 signlas. .pdf
                     above molecule has 12 signlas.                   .pdf                     above molecule has 12 signlas.                   .pdf
above molecule has 12 signlas. .pdfannaipowerelectronic
 
Hi,I have added a loop for adding values to list. Highlighted the .pdf
Hi,I have added a loop for adding values to list. Highlighted the .pdfHi,I have added a loop for adding values to list. Highlighted the .pdf
Hi,I have added a loop for adding values to list. Highlighted the .pdfannaipowerelectronic
 
D. ICANNThe Internet Assigned Numbers Authority (IANA) is a depart.pdf
D. ICANNThe Internet Assigned Numbers Authority (IANA) is a depart.pdfD. ICANNThe Internet Assigned Numbers Authority (IANA) is a depart.pdf
D. ICANNThe Internet Assigned Numbers Authority (IANA) is a depart.pdfannaipowerelectronic
 
Cracking of petrolium In petroleum geology and chemistry, cracki.pdf
Cracking of petrolium In petroleum geology and chemistry, cracki.pdfCracking of petrolium In petroleum geology and chemistry, cracki.pdf
Cracking of petrolium In petroleum geology and chemistry, cracki.pdfannaipowerelectronic
 
can you provide any aditional information apart from thisSolutio.pdf
can you provide any aditional information apart from thisSolutio.pdfcan you provide any aditional information apart from thisSolutio.pdf
can you provide any aditional information apart from thisSolutio.pdfannaipowerelectronic
 
AnswerMajority of Americans have faster advancing into above 85 y.pdf
AnswerMajority of Americans have faster advancing into above 85 y.pdfAnswerMajority of Americans have faster advancing into above 85 y.pdf
AnswerMajority of Americans have faster advancing into above 85 y.pdfannaipowerelectronic
 
AnswerA compilation error is generated The method f(int) is und.pdf
AnswerA compilation error is generated The method f(int) is und.pdfAnswerA compilation error is generated The method f(int) is und.pdf
AnswerA compilation error is generated The method f(int) is und.pdfannaipowerelectronic
 
a)   There is a cluster of SNP’s with similar p value in the intron .pdf
a)   There is a cluster of SNP’s with similar p value in the intron .pdfa)   There is a cluster of SNP’s with similar p value in the intron .pdf
a)   There is a cluster of SNP’s with similar p value in the intron .pdfannaipowerelectronic
 
A HRIS, which is otherwise called a human resource information syste.pdf
A HRIS, which is otherwise called a human resource information syste.pdfA HRIS, which is otherwise called a human resource information syste.pdf
A HRIS, which is otherwise called a human resource information syste.pdfannaipowerelectronic
 
4 (110000)^3  =  4 s^2 0.01s = 10^-5 MoleslitSolution.pdf
4  (110000)^3  =  4  s^2  0.01s = 10^-5 MoleslitSolution.pdf4  (110000)^3  =  4  s^2  0.01s = 10^-5 MoleslitSolution.pdf
4 (110000)^3  =  4 s^2 0.01s = 10^-5 MoleslitSolution.pdfannaipowerelectronic
 
1.            It will be absorbed by plant. Or remain in soil that .pdf
 1.            It will be absorbed by plant. Or remain in soil that .pdf 1.            It will be absorbed by plant. Or remain in soil that .pdf
1.            It will be absorbed by plant. Or remain in soil that .pdfannaipowerelectronic
 

More from annaipowerelectronic (20)

Structure Hydra has a tubular body, with only one opening the mouth.pdf
Structure Hydra has a tubular body, with only one opening the mouth.pdfStructure Hydra has a tubular body, with only one opening the mouth.pdf
Structure Hydra has a tubular body, with only one opening the mouth.pdf
 
Quality management ensures that an organization, product or service .pdf
Quality management ensures that an organization, product or service .pdfQuality management ensures that an organization, product or service .pdf
Quality management ensures that an organization, product or service .pdf
 
public class Deque {private class Node {public int data;public.pdf
public class Deque {private class Node {public int data;public.pdfpublic class Deque {private class Node {public int data;public.pdf
public class Deque {private class Node {public int data;public.pdf
 
Microsoft Excel is a spreadsheet program used to store and retrieve .pdf
Microsoft Excel is a spreadsheet program used to store and retrieve .pdfMicrosoft Excel is a spreadsheet program used to store and retrieve .pdf
Microsoft Excel is a spreadsheet program used to store and retrieve .pdf
 
Mean = xffS = Sqrt((x-x)2fn)intervalMidpoint(x)frequency.pdf
Mean = xffS = Sqrt((x-x)2fn)intervalMidpoint(x)frequency.pdfMean = xffS = Sqrt((x-x)2fn)intervalMidpoint(x)frequency.pdf
Mean = xffS = Sqrt((x-x)2fn)intervalMidpoint(x)frequency.pdf
 
Moles of Be = mass of Bemolar mass of Be= (0.33 g)(9.012 gmol).pdf
Moles of Be = mass of Bemolar mass of Be= (0.33 g)(9.012 gmol).pdfMoles of Be = mass of Bemolar mass of Be= (0.33 g)(9.012 gmol).pdf
Moles of Be = mass of Bemolar mass of Be= (0.33 g)(9.012 gmol).pdf
 
Lyme disease is a bacterial infection which is caused by bacteria ca.pdf
Lyme disease is a bacterial infection which is caused by bacteria ca.pdfLyme disease is a bacterial infection which is caused by bacteria ca.pdf
Lyme disease is a bacterial infection which is caused by bacteria ca.pdf
 
above molecule has 12 signlas. .pdf
                     above molecule has 12 signlas.                   .pdf                     above molecule has 12 signlas.                   .pdf
above molecule has 12 signlas. .pdf
 
Hi,I have added a loop for adding values to list. Highlighted the .pdf
Hi,I have added a loop for adding values to list. Highlighted the .pdfHi,I have added a loop for adding values to list. Highlighted the .pdf
Hi,I have added a loop for adding values to list. Highlighted the .pdf
 
D. ICANNThe Internet Assigned Numbers Authority (IANA) is a depart.pdf
D. ICANNThe Internet Assigned Numbers Authority (IANA) is a depart.pdfD. ICANNThe Internet Assigned Numbers Authority (IANA) is a depart.pdf
D. ICANNThe Internet Assigned Numbers Authority (IANA) is a depart.pdf
 
Cracking of petrolium In petroleum geology and chemistry, cracki.pdf
Cracking of petrolium In petroleum geology and chemistry, cracki.pdfCracking of petrolium In petroleum geology and chemistry, cracki.pdf
Cracking of petrolium In petroleum geology and chemistry, cracki.pdf
 
can you provide any aditional information apart from thisSolutio.pdf
can you provide any aditional information apart from thisSolutio.pdfcan you provide any aditional information apart from thisSolutio.pdf
can you provide any aditional information apart from thisSolutio.pdf
 
brasstinSolutionbrasstin.pdf
brasstinSolutionbrasstin.pdfbrasstinSolutionbrasstin.pdf
brasstinSolutionbrasstin.pdf
 
AnswerMajority of Americans have faster advancing into above 85 y.pdf
AnswerMajority of Americans have faster advancing into above 85 y.pdfAnswerMajority of Americans have faster advancing into above 85 y.pdf
AnswerMajority of Americans have faster advancing into above 85 y.pdf
 
AnswerA compilation error is generated The method f(int) is und.pdf
AnswerA compilation error is generated The method f(int) is und.pdfAnswerA compilation error is generated The method f(int) is und.pdf
AnswerA compilation error is generated The method f(int) is und.pdf
 
a)   There is a cluster of SNP’s with similar p value in the intron .pdf
a)   There is a cluster of SNP’s with similar p value in the intron .pdfa)   There is a cluster of SNP’s with similar p value in the intron .pdf
a)   There is a cluster of SNP’s with similar p value in the intron .pdf
 
A HRIS, which is otherwise called a human resource information syste.pdf
A HRIS, which is otherwise called a human resource information syste.pdfA HRIS, which is otherwise called a human resource information syste.pdf
A HRIS, which is otherwise called a human resource information syste.pdf
 
4 (110000)^3  =  4 s^2 0.01s = 10^-5 MoleslitSolution.pdf
4  (110000)^3  =  4  s^2  0.01s = 10^-5 MoleslitSolution.pdf4  (110000)^3  =  4  s^2  0.01s = 10^-5 MoleslitSolution.pdf
4 (110000)^3  =  4 s^2 0.01s = 10^-5 MoleslitSolution.pdf
 
2009.88Solution2009.88.pdf
2009.88Solution2009.88.pdf2009.88Solution2009.88.pdf
2009.88Solution2009.88.pdf
 
1.            It will be absorbed by plant. Or remain in soil that .pdf
 1.            It will be absorbed by plant. Or remain in soil that .pdf 1.            It will be absorbed by plant. Or remain in soil that .pdf
1.            It will be absorbed by plant. Or remain in soil that .pdf
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 

Recently uploaded (20)

OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 

import java.util.Scanner; import java.util.Random; public clas.pdf

  • 1. import java.util.Scanner; import java.util.Random; 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},
  • 2. {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);
  • 3. 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));
  • 4. 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;
  • 5. 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
  • 6. // 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 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")) {
  • 7. message = Player1 + " has won"; player1Won++; } else { message = Player2 + " has won"; player2Won++; } } else if(!win && turn>9) message = "Both players have tied! Better 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(); }
  • 8. } //------------------------------------------------------------------------------------------------------------------- ---------------- 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*/}
  • 9. else if(temp.equals("")) showMessage("Invalid Name!"); else if(temp.equals(Player2)) { option = askMessage("Player 1 name matches Player 2's Do 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 Do 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));
  • 10. 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);
  • 11. } /* ------------------------------------- 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: " + "Your goal is to be the first player to get 3 X's or O's in a " + "row. (horizontally, diagonally, or vertically) " + Player1 + ": X " +
  • 12. Player2 + ": O "; } else {//About message = "About: " + "Title: Tic-Tac-Toe " + "Creator: Blmaster " + "Version: " + VERSION + " "; } 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..." + " " + "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");
  • 13. 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-------------------------// } Solution import java.util.Scanner; import java.util.Random;
  • 14. 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,
  • 15. 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);
  • 16. 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
  • 17. 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(); } //-------------------------------------------------------------------------------------------------------------------
  • 18. ---------------- 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("") &&
  • 19. 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 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 {
  • 20. message = Player2 + " has won"; player2Won++; } } else if(!win && turn>9) message = "Both players have tied! Better 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() {
  • 21. 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 Do you want to continue?", "Name
  • 22. 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 Do 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)); } //-------------------------------------------------------------------------------------------------------------------
  • 23. ---------------- 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. |
  • 24. ------------------------------------- */ //-------------------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: " + "Your goal is to be the first player to get 3 X's or O's in a " + "row. (horizontally, diagonally, or vertically) " + Player1 + ": X " + Player2 + ": O "; } else {//About message = "About: " + "Title: Tic-Tac-Toe " +
  • 25. "Creator: Blmaster " + "Version: " + VERSION + " "; } 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..." + " " + "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(); } }
  • 26. } 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-------------------------// }