How do I use a JButton in more than 1 method? - java

So I've been coding my TicTacToe project as a side project for some time now, and have hit another obstacle. I want to use a JButton in more than one method, but I don't know how to go about doing that. Here's my code till now.
`
import java.util.Random ;
import java.util.Scanner ;
import javax.swing.JOptionPane ;
import javax.swing.JFrame ;
import javax.swing.JPanel ;
import java.util.InputMismatchException ;
import java.awt.BorderLayout ;
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.JTextArea ;
import javax.swing.JButton ;
import javax.swing.JRadioButton ;
class TicTacToe
{
public int count = 1 ;
public String letter;
public boolean b1bool = true ;
public boolean b2bool = true ;
public boolean b3bool = true ;
public boolean b4bool = true ;
public boolean b5bool = true ;
public boolean b6bool = true ;
public boolean b7bool = true ;
public boolean b8bool = true ;
public boolean b9bool = true ;
public boolean win = false ;
public void main(String []args)
{
popupintroscreen();
}
public void popupintroscreen()
{
JTextArea introtext = new JTextArea("Welcome to TicTacToe v1.0. This is a Simple Tic Tac Toe app coded by Abhishek Pisharody. Press the button below to play, or view the instructions first, if you prefer. We hope you enjoy playing. Thank you.");
introtext.setEditable(false);
introtext.setLineWrap(true);
JButton startgamebutton = new JButton("Start Game");
startgamebutton.setToolTipText("Start a game of Tic-Tac-Toe");
startgamebutton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent gamestart)
{
JOptionPane.showMessageDialog(null, "Loading.....done!");
tictactoe();
}
});
JButton showinstructions = new JButton("Show Instructions");
showinstructions.setToolTipText("View game instructions. Worth checking out even if you know how to play.");
showinstructions.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent displayinstructionsprompt)
{
JOptionPane.showMessageDialog(null, "Nothing to see here..yet..off you go!");
}
});
JButton highscoresbutton = new JButton("High Scores");
highscoresbutton.setToolTipText("Show high scores for the game");
highscoresbutton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent highscoresbuttonclicked)
{
JOptionPane.showMessageDialog(null,"Not coded yet!");
}
});
JButton quitgamebutton = new JButton("Quit Game");
quitgamebutton.setToolTipText("Quit the game. But why? :(");
quitgamebutton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onquitgamebuttonclick)
{
JOptionPane.showConfirmDialog(null, "Really quit?");
System.exit(0);
}
});
JPanel gamebuttonsholder = new JPanel(new BorderLayout());
gamebuttonsholder.setSize(400,100);
gamebuttonsholder.add(introtext,BorderLayout.PAGE_START);
gamebuttonsholder.add(startgamebutton,BorderLayout.PAGE_END);
gamebuttonsholder.add(showinstructions,BorderLayout.LINE_START);
gamebuttonsholder.add(highscoresbutton,BorderLayout.CENTER);
gamebuttonsholder.add(quitgamebutton,BorderLayout.LINE_END);
JFrame introscreen = new JFrame("Tic Tac Toe");
introscreen.setSize(400,400);
introscreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
introscreen.setLocationRelativeTo(null);
introscreen.add(gamebuttonsholder);
introscreen.setVisible(true);
}
public int tictactoe()
{
final JButton b1 = new JButton("");
b1.setToolTipText("Mark this box");
b1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b1bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b1.setText(letter);
b1bool = false ;
calculatevictory();
processturn();
}}});
final JButton b2 = new JButton("");
b2.setToolTipText("Mark this box");
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b2bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b2.setText(letter);
b2bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b3 = new JButton("");
b3.setToolTipText("Mark this box");
b3.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b3bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b3.setText(letter);
b3bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b4 = new JButton("");
b4.setToolTipText("Mark this box");
b4.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b4bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b4.setText(letter);
b4bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b5 = new JButton("");
b5.setToolTipText("Mark this box");
b5.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b5bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b5.setText(letter);
b5bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b6 = new JButton("");
b6.setToolTipText("Mark this box");
b6.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b6bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b6.setText(letter);
b6bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b7 = new JButton("");
b7.setToolTipText("Mark this box");
b7.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b7bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b7.setText(letter);
b7bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b8 = new JButton("");
b8.setToolTipText("Mark this box");
b8.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b8bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b8.setText(letter);
b8bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b9 = new JButton("");
b9.setToolTipText("Mark this box");
b9.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b9bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b9.setText(letter);
b9bool = false ;
calculatevictory();
processturn();
}}
});
GridLayout gamescreenlayout = new GridLayout(3,3);
JPanel gamescreencontent = new JPanel();
gamescreencontent.setLayout(gamescreenlayout);
gamescreencontent.setSize(400,400);
gamescreencontent.add(b1);
gamescreencontent.add(b2);
gamescreencontent.add(b3);
gamescreencontent.add(b4);
gamescreencontent.add(b5);
gamescreencontent.add(b5);
gamescreencontent.add(b6);
gamescreencontent.add(b7);
gamescreencontent.add(b8);
gamescreencontent.add(b9);
JFrame gamescreen = new JFrame("Tic-Tac-Toe");
gamescreen.setSize(400,400) ;
gamescreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gamescreen.setLocationRelativeTo(null);
gamescreen.add(gamescreencontent);
gamescreen.setVisible(true);
int sexyshit = 1 ;
return sexyshit ;
}
public void calculatevictory(){
if (b1.getText() == b2.getText() && b2.getText() == b3.getText() && b1.getText() != "")
{
win = true ;
}
else if (b4.getText() == b5.getText() && b5.getText() == b6.getText() && b4.getText() != "")
{
win = true ;
}
else if (b7.getText() == b8.getText() && b8.getText() == b9.getText() && b7.getText() != "")
{
win = true ;
}
else if (b1.getText() == b4.getText() && b4.getText() == b7.getText() && b1.getText() != "")
{
win = true ;
}
else if (b2.getText() == b5.getText() && b5.getText() == b8.getText() && b2.getText() != "")
{
win = true ;
}
else if (b3.getText() == b6.getText() && b6.getText() == b9.getText() && b3.getText() != "")
{
win = true ;
}
else if (b1.getText() == b5.getText() && b5.getText() == b9.getText() && b1.getText() != "")
{
win = true ;
}
else if (b3.getText() == b5.getText() && b5.getText() == b7.getText() && b3.getText() != "")
{
win = true ;
}
else
{
win = false ;
}
}
public void processturn()
{
if (win == true)
{
JOptionPane.showMessageDialog(null, letter + "wins!");
}
else if ( count == 9 && win == false)
{
JOptionPane.showMessageDialog(null, "Tie Game");
}
}
}`
When I try to run this, it tells me that the compiler couldn't find symbol b1. Would I have to make the buttons public(if so, how?), or use Inheritance? If it's the latter, please explain in simple terms, because I really haven't begun to learn inheritance yet.
Thank you in advance.

Declare your JButton outside the method, in the same place as where you are declaring your int, String, and booleans. In other words, something like
class TicTacToe
{
//...
JButton b1;
//...
public int TicTacToe()
{
b1 = new JButton(); //note that you don't need the ""
}
}
Incidentally, I'd recommend using arrays and looping through them rather than having 9 of everything and having to copy-paste code lots of times.

Related

How to switch between 2 colors in Java Jbuttons after every click

I have been making a color-based Tic Tac Toe game using Java Swing and Java AWT and have more or less finished the project, however there is still one problem that needs to be fixed in order to be a proper Tic Tac Toe game. The colors that are supposed to be used is Orange (X) and blue (O), however for some reason even when checking each turn iteration it refuses to switch colors after every click and at this point I am lost. Any help is appreciated
Board.java:
public class Board extends JPanel {
boolean gameRunning = true;
private final JButton[][] grid = new JButton[3][3];
JFrame board;
JPanel panel;
public Board() {
initBoard();
}
private void makePanel() {
panel = new JPanel();
panel.setBackground(Color.lightGray);
panel.setLayout(new GridLayout(3, 3));
setBoard();
board.add(panel);
}
private void initBoard() {
int BOARD_WIDTH = 800;
int BOARD_HEIGHT = 600;
board = new JFrame();
board.setTitle("JTicTacToe");
board.setSize(BOARD_WIDTH, BOARD_HEIGHT);
board.setResizable(false);
board.setLocationRelativeTo(null);
board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
makePanel();
board.setVisible(true);
}
private void setBoard() {
//Loop through 2D array
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
grid[row][col] = new JButton();
grid[row][col].setOpaque(true);
grid[row][col].setBorderPainted(false);
grid[row][col].addActionListener(new ButtonListener());
panel.add(grid[row][col]);
}
}
validate();
}
protected class ButtonListener implements ActionListener {
Color defaultColor = new Color(238,238,238);
protected void check(int moves) {
//Rows
for (int c = 0; c < 3; c++) {
if (!defaultColor.equals(grid[c][0].getBackground()) && grid[c][0].getBackground() == grid[c][1].getBackground() && grid[c][0].getBackground() == grid[c][2].getBackground()) {
gameRunning = false;
JOptionPane.showMessageDialog(null, "Game Over!");
}
}
//Verticals
for (int c = 0; c < 3; c++) {
if (!defaultColor.equals(grid[0][c].getBackground()) && grid[0][c].getBackground() == grid[1][c].getBackground() && grid[0][c].getBackground() == grid[2][c].getBackground()) {
gameRunning = false;
JOptionPane.showMessageDialog(null, "Game Over!");
}
}
//Check diagonals
if (!defaultColor.equals(grid[0][0].getBackground()) && grid[0][0].getBackground() == grid[1][1].getBackground() && grid[0][0].getBackground() == grid[2][2].getBackground()) {
gameRunning = false;
JOptionPane.showMessageDialog(null, "Game Over!");}
if (!defaultColor.equals(grid[0][2].getBackground()) && grid[0][2].getBackground() == grid[1][1].getBackground() && grid[0][2].getBackground() == grid[2][0].getBackground()) {
gameRunning = false;
JOptionPane.showMessageDialog(null, "Game Over!");
}
//Check draw if game goes to 9 moves
if(moves == 9) {
gameRunning = false;
JOptionPane.showMessageDialog(null, "Draw!");
}
}
#Override
public void actionPerformed(ActionEvent e) {
int turns = 0;
if (e.getSource() == grid[0][0]) {
turns++;
if (turns % 2 == 0) {
grid[0][0].setBackground(Color.orange);
check(turns);
} else {
grid[0][0].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[0][1]) {
turns++;
if (turns % 2 == 0) {
grid[0][1].setBackground(Color.orange);
check(turns);
} else {
grid[0][1].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[0][2]) {
turns++;
if (turns % 2 == 0) {
grid[0][2].setBackground(Color.orange);
check(turns);
} else {
grid[0][2].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[1][0]) {
turns++;
if (turns % 2 == 0) {
grid[1][0].setBackground(Color.orange);
check(turns);
} else {
grid[1][0].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[1][1]) {
turns++;
if (turns % 2 == 0) {
grid[1][1].setBackground(Color.orange);
check(turns);
} else {
grid[1][1].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[1][2]) {
turns++;
if (turns % 2 == 0) {
grid[1][2].setBackground(Color.orange);
check(turns);
} else {
grid[1][2].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[2][0]) {
turns++;
if (turns % 2 == 0) {
grid[2][0].setBackground(Color.orange);
check(turns);
} else {
grid[2][0].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[2][1]) {
turns++;
if (turns % 2 == 0) {
grid[2][1].setBackground(Color.orange);
check(turns);
} else {
grid[2][1].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[2][2]) {
turns++;
if (turns % 2 == 0) {
grid[2][2].setBackground(Color.orange);
check(turns);
} else {
grid[2][2].setBackground(Color.blue);
check(turns);
}
} else {
JOptionPane.showMessageDialog(null, "Invalid");
}
System.out.println(turns);
}
}
}
If you want to make the code prettier:
The variable gameRunning is set but it is never used. You can remove it and the program will still behave the same. Or you can start using it. But just giving it values without using those values is unnecessary work.
The variables at the top should be private (grid is private, but eg board is not)
You can use a loop to shorten the actionPerformed method (note that I added a return;):
#Override
public void actionPerformed(ActionEvent e) {
for (int col = 0; col < 3; col++) {
for (int row = 0; row < 3; row++) {
if (e.getSource() == grid[col][row]) {
turns++;
if (turns % 2 == 0) {
grid[col][row].setBackground(Color.orange);
check(turns);
} else {
grid[col][row].setBackground(Color.blue);
check(turns);
}
System.out.println(turns);
return;
}
}
}
JOptionPane.showMessageDialog(null, "Invalid");
}
You set the variable turns to 0 every time a button is clicked (ie every time actionPerformed is called). You need to make turns global (same as eg grid).

Swing frame doesnt hold or stay after clicking jbutton

I have 2 text areas with a button in between them in a frame in swing and I am using netbeans.
Clicking the button picks up an sql query from textArea1, using getText().
The input is processed (i.e. checked the spellings of the keywords after splitting the query) with SubmitData(). Inside that method, it only uses setText() to set the output to textArea2.
My Problem Is:
The frame just doesn't stay or hold after I press the button.
Here is my code:
void createUI() throws Exception
{
JFrame frame = new JFrame("JDBC All in One");
// Layout of Main Window
Container c = frame.getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
textArea1 = new JTextArea(10, 50);
textArea1.setBounds(10, 10, 30, 30);
btnInsert = new JButton("Submit");
btnInsert.setBounds(10, 10, 10, 10);
btnInsert.addActionListener(this);
textArea2 = new JTextArea(10, 50);
textArea2.setBounds(10, 10, 30, 30);
JPanel pnlInput1 = new JPanel();
JPanel pnlInput2 = new JPanel();
JPanel pnlInput3 = new JPanel();
pnlInput1.add(textArea1);
pnlInput3.add(btnInsert);
pnlInput2.add(textArea2);
frame.add(pnlInput1);
frame.add(pnlInput3);
frame.add(pnlInput2);
frame.setSize(400, 500);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
String cmd = evt.getActionCommand();
if (cmd.equals("Submit")) {
try {
SubmitData();
} catch (Exception e) {}
}
}
public static void SubmitData() throws Exception {
s1 = textArea1.getText();
String[] s2 = s1.split("\\s+");
for (int i = 0; i < s2.length; i++) {
if (s2[i] .equals("elect")|| s2[i] .equals("selct") || s2[i].equals("slect" )|| s2[i].equals("selec")|| s2[i].equals("seect")
{
textArea2.setText("use 'select' instead of " + s2[i]);
System.exit(0);
}
if (s2[i] == "updat" || s2[i] == "updae" || s2[i] == "updte" || s2[i] == "upate") {
textArea2.setText("use 'update' instead of " + s2[i]);
System.exit(0);
}
if (s2[i] == "delet" || s2[i] == "delte" || s2[i] == "elete" || s2[i] == "dlete") {
textArea2.setText("use 'delete' instead of " + s2[i]);
System.exit(0);
}
if (s2[i] == "fro" || s2[i] == "frm" || s2[i] == "fom") {
textArea2.setText("use 'from' instead of " + s2[i]);
System.exit(0);
}
}
}
Edited-i've changed "==" fro string comparision with .equals() but the problem doesnt seem to go away.
System.exit(0);terminates your JVM. Remove it if you want to keep your frame.
Edit for second question :
After your first if, replace your if by else if in order that the others if don't execute when a condition is true.
for (int i = 0; i < s2.length; i++) {
if (s2[i] .equals("elect")|| s2[i] .equals("selct") || s2[i].equals("slect" )|| s2[i].equals("selec")|| s2[i].equals("seect")
{
textArea2.setText("use 'select' instead of " + s2[i]);
}
else if (s2[i] == "updat" || s2[i] == "updae" || s2[i] == "updte" || s2[i] == "upate") {
textArea2.setText("use 'update' instead of " + s2[i]);
}
else if (s2[i] == "delet" || s2[i] == "delte" || s2[i] == "elete" || s2[i] == "dlete") {
textArea2.setText("use 'delete' instead of " + s2[i]);
}
else if (s2[i] == "fro" || s2[i] == "frm" || s2[i] == "fom") {
textArea2.setText("use 'from' instead of " + s2[i]);
}
}

How do I create Logic based AI for my Java Tic Tac Toe Program?

I've almost put the wraps on my program, but I want to add some way for users to play against the computer. For this, I need to create some kind of conditional logic based AI, but can't see which approach to take.
I don't want the computer to take its turn randomly, I want it to actually play like a human player. Would I have to use a deeply nested if statements and multiple moves for each possible turn, or use some kind of for or while loop?
My code reduced to just the WinChecker is here:
public void calculatevictory(){
if (b1.getText() == b2.getText() && b2.getText() == b3.getText() && b1.getText() != "")
{
win = true ;
}
else if (b4.getText() == b5.getText() && b5.getText() == b6.getText() && b4.getText() != "")
{
win = true ;
}
else if (b7.getText() == b8.getText() && b8.getText() == b9.getText() && b7.getText() != "")
{
win = true ;
}
else if (b1.getText() == b4.getText() && b4.getText() == b7.getText() && b1.getText() != "")
{
win = true ;
}
else if (b2.getText() == b5.getText() && b5.getText() == b8.getText() && b2.getText() != "")
{
win = true ;
}
else if (b3.getText() == b6.getText() && b6.getText() == b9.getText() && b3.getText() != "")
{
win = true ;
}
else if (b1.getText() == b5.getText() && b5.getText() == b9.getText() && b1.getText() != "")
{
win = true ;
}
else if (b3.getText() == b5.getText() && b5.getText() == b7.getText() && b3.getText() != "")
{
win = true ;
}
else
{
win = false ;
}
}
My code so far is here:
/* PROGRAM NAME : TIC TAC TOE
* AUTHOR : Jack Robinson
* DATE : 7/17/2014
*/
// Importing necessary classes and directories
import java.util.Random ;
import java.util.Scanner ;
import javax.swing.JOptionPane ;
import javax.swing.JFrame ;
import javax.swing.JPanel ;
import java.util.InputMismatchException ;
import java.awt.BorderLayout ;
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.JTextArea ;
import javax.swing.JButton ;
import javax.swing.JRadioButton ;
import java.awt.Font ;
//Creating class
class TicTacToe
{
//Declaring all instance members
public int count = 1 ;
public String letter;
public boolean b1bool = true ;
public boolean b2bool = true ;
public boolean b3bool = true ;
public boolean b4bool = true ;
public boolean b5bool = true ;
public boolean b6bool = true ;
public boolean b7bool = true ;
public boolean b8bool = true ;
public boolean b9bool = true ;
public boolean win = false ;
public boolean gameinit = true ;
private JButton b1 ;
private JButton b2 ;
private JButton b3 ;
private JButton b4 ;
private JButton b5 ;
private JButton b6 ;
private JButton b7 ;
private JButton b8 ;
private JButton b9 ;
private JFrame gamescreen ;
private JFrame introscreen ;
public Font TToeFont = new Font("Arial",Font.PLAIN,40);
// Main method
public static void main(String []args)
{
// Calls the method which pops up the intro screen ;
TicTacToe runnext = new TicTacToe();
runnext.popupintroscreen();
}
public void popupintroscreen()
{
//Creating introduction text and it's wrapper
JTextArea introtext = new JTextArea("Welcome to TicTacToe v1.0. This is a Simple Tic Tac Toe app coded by Abhishek Pisharody. Press the button below to play, or view the instructions first, if you prefer. We hope you enjoy playing. Thank you.");
introtext.setEditable(false);
introtext.setLineWrap(true);
// ----------------------------------- DECLARING ALL JBUTTONS IN THE INTRO SCREEN AND ADDING ACTION LISTENERS ---------------------------------------------------
JButton startgamebutton = new JButton("Start Game");
startgamebutton.setToolTipText("Start a game of Tic-Tac-Toe");
startgamebutton.setFont(TToeFont);
startgamebutton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent gamestart)
{
if(gameinit == true){
JOptionPane.showMessageDialog(null, "Loading.....done!");
tictactoe();
gameinit = false;
} else {
JOptionPane.showMessageDialog(null, "The game is already running" , "Error" , JOptionPane.ERROR_MESSAGE);
}
}
});
JButton showinstructions = new JButton("Show Instructions");
showinstructions.setToolTipText("View game instructions. Worth checking out even if you know how to play.");
showinstructions.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent displayinstructionsprompt)
{
JOptionPane.showMessageDialog(null, "Nothing to see here..yet..off you go!");
}
});
JButton highscoresbutton = new JButton("High Scores");
highscoresbutton.setToolTipText("Show high scores for the game");
highscoresbutton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent highscoresbuttonclicked)
{
JOptionPane.showMessageDialog(null,"Not coded yet!");
}
});
JButton quitgamebutton = new JButton("Quit Game");
quitgamebutton.setToolTipText("Quit the game. But why? :(");
quitgamebutton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onquitgamebuttonclick)
{
int response = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit the game?" , "Really quit?" , JOptionPane.YES_NO_OPTION );
if(response == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
});
//Creating intro screen content pane and adding buttons to it
JPanel gamebuttonsholder = new JPanel(new BorderLayout());
gamebuttonsholder.setSize(400,100);
gamebuttonsholder.add(introtext,BorderLayout.PAGE_START);
gamebuttonsholder.add(startgamebutton,BorderLayout.PAGE_END);
gamebuttonsholder.add(showinstructions,BorderLayout.LINE_START);
gamebuttonsholder.add(highscoresbutton,BorderLayout.CENTER);
gamebuttonsholder.add(quitgamebutton,BorderLayout.LINE_END);
//Creating the screen itself and setting it visible
introscreen = new JFrame("Tic Tac Toe");
introscreen.setSize(400,400);
introscreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
introscreen.setLocationRelativeTo(null);
introscreen.add(gamebuttonsholder);
introscreen.setVisible(true);
}
// Creating the method which powers the game ;
public int tictactoe()
{
// ----=---------------------- CREATING ALL JBUTTONS ON THE GAME SCREEN AND ADDING ACTION LISTENERS AND REACTIONS -----------------------------------------
b1 = new JButton("");
b1.setToolTipText("Mark this box");
b1.setFont(TToeFont);
b1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b1bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b1.setText(letter);
b1bool = false ;
calculatevictory();
processturn();
}}});
b2 = new JButton("");
b2.setFont(TToeFont);
b2.setToolTipText("Mark this box");
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b2bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b2.setText(letter);
b2bool = false ;
calculatevictory();
processturn();
}}
});
b3 = new JButton("");
b3.setToolTipText("Mark this box");
b3.setFont(TToeFont);
b3.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b3bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b3.setText(letter);
b3bool = false ;
calculatevictory();
processturn();
}}
});
b4 = new JButton("");
b4.setToolTipText("Mark this box");
b4.setFont(TToeFont);
b4.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b4bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b4.setText(letter);
b4bool = false ;
calculatevictory();
processturn();
}}
});
b5 = new JButton("");
b5.setToolTipText("Mark this box");
b5.setFont(TToeFont);
b5.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b5bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b5.setText(letter);
b5bool = false ;
calculatevictory();
processturn();
}}
});
b6 = new JButton("");
b6.setToolTipText("Mark this box");
b6.setFont(TToeFont);
b6.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b6bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b6.setText(letter);
b6bool = false ;
calculatevictory();
processturn();
}}
});
b7 = new JButton("");
b7.setToolTipText("Mark this box");
b7.setFont(TToeFont);
b7.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b7bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b7.setText(letter);
b7bool = false ;
calculatevictory();
processturn();
}}
});
b8 = new JButton("");
b8.setToolTipText("Mark this box");
b8.setFont(TToeFont);
b8.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b8bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b8.setText(letter);
b8bool = false ;
calculatevictory();
processturn();
}}
});
b9 = new JButton("");
b9.setToolTipText("Mark this box");
b9.setFont(TToeFont);
b9.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b9bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b9.setText(letter);
b9bool = false ;
calculatevictory();
processturn();
}}
});
//CREATING GAME SCREEN LAYOUT
GridLayout gamescreenlayout = new GridLayout(3,3);
//CREAING GAME SCREEN CONTENT PANE AND ADDING BUTTONS TO IT
JPanel gamescreencontent = new JPanel();
gamescreencontent.setLayout(gamescreenlayout);
gamescreencontent.setSize(400,400);
gamescreencontent.add(b1);
gamescreencontent.add(b2);
gamescreencontent.add(b3);
gamescreencontent.add(b4);
gamescreencontent.add(b5);
gamescreencontent.add(b5);
gamescreencontent.add(b6);
gamescreencontent.add(b7);
gamescreencontent.add(b8);
gamescreencontent.add(b9);
// CREATING GAME SCREEN AND SETTING IT VISIBLE
gamescreen = new JFrame("Tic-Tac-Toe");
gamescreen.setSize(400,400) ;
gamescreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gamescreen.setLocationRelativeTo(null);
gamescreen.add(gamescreencontent);
gamescreen.setVisible(true);
int gamestuff = 1 ;
return gamestuff ;
}
// This method checks if someone won the game every time you click a button
public void calculatevictory(){
if (b1.getText() == b2.getText() && b2.getText() == b3.getText() && b1.getText() != "")
{
win = true ;
}
else if (b4.getText() == b5.getText() && b5.getText() == b6.getText() && b4.getText() != "")
{
win = true ;
}
else if (b7.getText() == b8.getText() && b8.getText() == b9.getText() && b7.getText() != "")
{
win = true ;
}
else if (b1.getText() == b4.getText() && b4.getText() == b7.getText() && b1.getText() != "")
{
win = true ;
}
else if (b2.getText() == b5.getText() && b5.getText() == b8.getText() && b2.getText() != "")
{
win = true ;
}
else if (b3.getText() == b6.getText() && b6.getText() == b9.getText() && b3.getText() != "")
{
win = true ;
}
else if (b1.getText() == b5.getText() && b5.getText() == b9.getText() && b1.getText() != "")
{
win = true ;
}
else if (b3.getText() == b5.getText() && b5.getText() == b7.getText() && b3.getText() != "")
{
win = true ;
}
else
{
win = false ;
}
}
// This method sends the win message
public void processturn()
{
if (win == true)
{
int restart = JOptionPane.showConfirmDialog(null, letter + " wins! Play again? " ,letter + " Wins!" , JOptionPane.YES_NO_OPTION);
if(restart == JOptionPane.NO_OPTION)
{
gamescreen.dispose();
resetgame();
}
else {
resetgame();
}}
else if ( count == 10 && win == false)
{
JOptionPane.showMessageDialog(null, "Tie Game");
resetgame();
}
}
// This method resets all game variables
public void resetgame()
{
count = 1 ;
b1bool = true ;
b2bool = true ;
b3bool = true ;
b4bool = true ;
b5bool = true ;
b6bool = true ;
b7bool = true ;
b8bool = true ;
b9bool = true ;
win = false ;
gameinit = true ;
b1.setText("");
b2.setText("");
b3.setText("");
b4.setText("");
b5.setText("");
b6.setText("");
b7.setText("");
b8.setText("");
b9.setText("");
}
}
// END OF PROGRAM
Here you go, an entire tic-tac-toe in less than 70 lines of code (in Scala - totally impossible to be this concise in many other languages). First argument to the application is a "true" or "false" to specify human first. Second argument is an integer that will control the depth in which the AI will think (how many moves ahead). Use coordinates to specify your move (starting at 0,0). The App will print the board each move and stop when the game has ended.
It uses a simple brute force lookahead AI, which by the way is very slow for the first couple of moves. You could optimize this either by:
Adding memoization so game trees are not recomputed
Adding a lookup table for opening moves
Just optimize the code, so using mutable data structures and such
code:
import scalaz.syntax.id._
import scala.collection.immutable.IndexedSeq
import scala.util.Try
case class Board(moves: List[(Int, Int)], maxDepth: Int = 4) {
val grid: IndexedSeq[(Int, Int)] = (0 to 2).flatMap(i => (0 to 2).map((_, i)))
def isThree(l: List[(Int, Int)], axis: ((Int, Int)) => Int): Boolean =
l.map(_.swap |> axis).distinct.size == 3 && (l.map(axis).distinct.size == 1 ||
l.map(axis) == l.map(_.swap |> axis) || l.map(axis) == l.map(_.swap |> axis).reverse)
def playerWon(player: List[((Int, Int), Int)]): Boolean =
player.map(_._1).combinations(3).map(_.sortBy(_._1)).exists(p => isThree(p, _._1) || isThree(p, _._2))
def hasWinner: Boolean = {
val (crosses, circles) = moves.zipWithIndex.partition(_._2 % 2 == 0)
playerWon(crosses) || playerWon(circles)
}
def computerMove: Board = Board({
val remainingMoves = grid.filterNot(moves.contains)
var (mvOpt, badMoves, depth) = (Option.empty[(Int, Int)], Set.empty[(Int, Int)], 1)
while (mvOpt.isEmpty && depth <= maxDepth) {
val lookAheadFunc: ((Int, Int)) => Boolean = mv => Board(mv +: moves, maxDepth) |>
List.fill[Board => Board](depth - 1)(_.computerMove).foldLeft[Board => Board](identity)(_ compose _) |>
(_.hasWinner)
if (remainingMoves.size >= depth) mvOpt = if (depth % 2 == 0) {
badMoves ++= remainingMoves.filter(lookAheadFunc)
val okMoves = remainingMoves.filterNot(badMoves)
if (okMoves.size == 1) okMoves.headOption else None
} else remainingMoves.filterNot(badMoves).find(lookAheadFunc)
depth += 1
}
mvOpt.getOrElse(remainingMoves.filterNot(badMoves).headOption.getOrElse(remainingMoves.head))
} +: moves, maxDepth)
def print: Board = {
(0 to 2).reverse.foreach(i => println((moves.reverse.zipWithIndex.map(p =>
if (p._2 % 2 == 0) (p._1, "X") else (p._1, "O")) ++
grid.filterNot(moves.contains).map((_, "B"))).filter(_._1._2 == i).sortBy(_._1._1).map(_._2).mkString))
this
}
def humanAttempt: Try[Board] = Try({
val Array(x, y) = readLine("Your move (of form x,y) $ ").split(",").map(_.toInt)
require(!(x > 2 || x < 0 || y > 2 || y < 0 || moves.contains((x, y))), "Move not valid: " +(x, y))
Board((x, y) +: moves, maxDepth)
})
def humanMove: Board = {
var moveAttempt = humanAttempt
while (moveAttempt.isFailure) {
println("Bad move: " + moveAttempt.failed.get.getMessage)
moveAttempt = humanAttempt
}
moveAttempt.get
}
}
object TicTacToe extends App {
var (board, humanNext) = (Board(Nil, args.drop(1).headOption.map(_.toInt).getOrElse(4)).print, args(0).toBoolean)
while (!board.hasWinner && board.moves.size != 9) {
board = (if (humanNext) board.humanMove else {
println("Computer moving")
board.computerMove
}).print
humanNext = !humanNext
}
}

Java Tic Tac Toe AI not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My AI code for a computer player is not working as expected. I want it to play a random move, but block an opponent's incoming winning turn. However, it sometimes stops working altogether, and other times plays a specific move even though there is no incoming win combo. My computer AI code is below.
public void compturn()
{
count++ ;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
if (b1.getText() == b2.getText() && b2.getText() != "" && b3.getText() == "")
{
b3.setText(letter);
b3bool = false ;
}
else if (b4.getText() == b5.getText() && b6.getText() == "")
{
b6.setText(letter);
b6bool = false ;
}
else if (b7.getText() == b8.getText() && b9.getText() == "")
{
b9.setText(letter);
b9bool = false ;
}
else if (b1.getText() == b4.getText() && b4.getText() != "" && b7.getText() == "")
{
b7.setText(letter);
b7bool = false ;
}
else if (b2.getText() == b5.getText() && b8.getText() == "")
{
b8.setText(letter);
b8bool = false ;
}
else if (b3.getText() == b6.getText() && b9.getText() == "")
{
b9.setText(letter);
b9bool = false ;
}
else if (b1.getText() == b5.getText() && b5.getText() != "" && b9.getText() == "")
{
b9.setText(letter) ;
b9bool = false ;
}
else if (b3.getText() == b5.getText() && b7.getText() == "")
{
b7.setText(letter);
b7bool = false ;
}
else
{
randomMove();
}
}
public void randomMove()
{
int randomnum = (int)(Math.random() * 10);
if(randomnum == 1 )
{
if(b1.getText().equals("X") || b1.getText().equals("O"))
{
randomMove();
}
else
{
b1.setText(letter);
}
}
if(randomnum == 2 )
{
if(b2.getText().equals("X") || b2.getText().equals("O"))
{
randomMove();
}
else
{
b2.setText(letter);
}
}
if(randomnum == 3 )
{
if(b3.getText().equals("X") || b3.getText().equals("O"))
{
randomMove();
}
else
{
b3.setText(letter);
}
}
if(randomnum == 4 )
{
if(b4.getText().equals("X") || b4.getText().equals("O"))
{
randomMove();
}
else
{
b4.setText(letter);
}
}
if(randomnum == 5 )
{
if(b5.getText().equals("X") || b5.getText().equals("O"))
{
randomMove();
}
else
{
b5.setText(letter);
}
}
if(randomnum == 6 )
{
if(b6.getText().equals("X") || b6.getText().equals("O"))
{
randomMove();
}
else
{
b6.setText(letter);
}
}
if(randomnum == 7 )
{
if(b7.getText().equals("X") || b7.getText().equals("O"))
{
randomMove();
}
else
{
b7.setText(letter);
}
}
if(randomnum == 8 )
{
if(b8.getText().equals("X") || b8.getText().equals("O"))
{
randomMove();
}
else
{
b8.setText(letter);
}
}
if(randomnum == 9 )
{
if(b9.getText().equals("X") || b9.getText().equals("O"))
{
randomMove();
}
else
{
b9.setText(letter);
}
}
}
And my complete code for the main game is here
public int oneplayergame()
{
// ----=---------------------- CREATING ALL JBUTTONS ON THE GAME SCREEN AND ADDING ACTION LISTENERS AND REACTIONS -----------------------------------------
b1 = new JButton("");
b1.setToolTipText("Mark this box");
b1.setFont(TToeFont);
b1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b1bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b1.setText(letter);
b1bool = false ;
calculatevictory();
compturn();
processturn();
}}});
b2 = new JButton("");
b2.setFont(TToeFont);
b2.setToolTipText("Mark this box");
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b2bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b2.setText(letter);
b2bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b3 = new JButton("");
b3.setToolTipText("Mark this box");
b3.setFont(TToeFont);
b3.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b3bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b3.setText(letter);
b3bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b4 = new JButton("");
b4.setToolTipText("Mark this box");
b4.setFont(TToeFont);
b4.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b4bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b4.setText(letter);
b4bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b5 = new JButton("");
b5.setToolTipText("Mark this box");
b5.setFont(TToeFont);
b5.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b5bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b5.setText(letter);
b5bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b6 = new JButton("");
b6.setToolTipText("Mark this box");
b6.setFont(TToeFont);
b6.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b6bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b6.setText(letter);
b6bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b7 = new JButton("");
b7.setToolTipText("Mark this box");
b7.setFont(TToeFont);
b7.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b7bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b7.setText(letter);
b7bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b8 = new JButton("");
b8.setToolTipText("Mark this box");
b8.setFont(TToeFont);
b8.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b8bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b8.setText(letter);
b8bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b9 = new JButton("");
b9.setToolTipText("Mark this box");
b9.setFont(TToeFont);
b9.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b9bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b9.setText(letter);
b9bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
//CREATING GAME SCREEN LAYOUT
//CREAING GAME SCREEN CONTENT PANE AND ADDING BUTTONS TO IT
// This method checks if someone won the game every time you click a button
public void calculatevictory(){
if (b1.getText() == b2.getText() && b2.getText() == b3.getText() && b1.getText() != "")
{
win = true ;
}
else if (b4.getText() == b5.getText() && b5.getText() == b6.getText() && b4.getText() != "")
{
win = true ;
}
else if (b7.getText() == b8.getText() && b8.getText() == b9.getText() && b7.getText() != "")
{
win = true ;
}
else if (b1.getText() == b4.getText() && b4.getText() == b7.getText() && b1.getText() != "")
{
win = true ;
}
else if (b2.getText() == b5.getText() && b5.getText() == b8.getText() && b2.getText() != "")
{
win = true ;
}
else if (b3.getText() == b6.getText() && b6.getText() == b9.getText() && b3.getText() != "")
{
win = true ;
}
else if (b1.getText() == b5.getText() && b5.getText() == b9.getText() && b1.getText() != "")
{
win = true ;
}
else if (b3.getText() == b5.getText() && b5.getText() == b7.getText() && b3.getText() != "")
{
win = true ;
}
else
{
win = false ;
}
}
// This method sends the win message
public void processturn()
}
// This method resets all game variables
public void resetgame()
{
count = 1 ;
b1bool = true ;
b2bool = true ;
b3bool = true ;
b4bool = true ;
b5bool = true ;
b6bool = true ;
b7bool = true ;
b8bool = true ;
b9bool = true ;
win = false ;
gameinit = true ;
b1.setText("");
b2.setText("");
b3.setText("");
b4.setText("");
b5.setText("");
b6.setText("");
b7.setText("");
b8.setText("");
b9.setText("");
}
public void compturn()
{
}
public void randomMove()
{
}
}
Welcome to AI... there are numerous ways you can do this. I'll give you a few tips.
I assume count is used to determine who's turn it is. I'd suggest you rather create an integer 'turn' and then simply do this:
turn = 1 -turn
...where you currently increment count. If it's 0 than it's o's turn, else x's. You can then remove those two long if statements. (You can also use a boolean flag and just not it each time, like so turn = !turn.)
Now the rest... I see you have no arrays. Are you comfortable using them?
If so, rather define, winning sequences. For example:
int[][] win = new int[][]{{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, ...}
Then all you do to determine if you can win, go is to see if you have two of your tokens in spot win[i][0], win[i][1] or win[i][2]. If the third spot it empty, you can win and should move there,
If you can't win, repeat the above process to defend.
If you do not have to defend and you cannot win, move in the centre. If the centre is taken, take a corner, else move random.
This will give you an AI that can still lose sometimes, but will show some intelligence. If you really want to build something unbeatable have a look at the minimax search algorithm.
Good luck!

Adding a main to a pre existing program

I wrote a fairly simple program using a GUI template to learn about adding some form of GUI in java. I completed the program only to discover that it cant be run outside of the IDE without a main method. The program works fine inside Eclipse IDE, but useless otherwise. How do I go about adding a main class so it can be executed as a .jar?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JApplet implements ActionListener {
// Create all labels, textfields and buttons needed (in order)
/**
* This is a tic tac toe game made with the purposes of learning java
*/
private static final long serialVersionUID = 1L;
JButton firstButton;
JButton secondButton;
JButton thirdButton;
JButton fourthButton;
JButton fithButton;
JButton sixthButton;
JButton seventhButton;
JButton eighthButton;
JButton ninthButton;
//this is the position value checker which are later set to x and o
String[] posCheck = { "", "", "", "", "", "", "", "", "" };
// score count JLABELs to display the score inside the game pane.
JLabel scoreP1;
JLabel scoreP2;
// this is used for formatting purposes or something like that, I guess.
JLabel blank;
// score count variables for both players, they both start at 0.
int scoreCount1 = 0, scoreCount2 = 0;
int gamesPlayed = -1;
boolean gameDone = false;
int k;
String prevWinner = "";
// Create any global variables/arrays needed later in the program (final)
Container pane = getContentPane();
//this sets the tile to X or O depending on who's turn it is
String[] symbol = { "O", "X" };
int turnCounter = 0;
int tieChecker = 0;
// Sets up GUI components.
public void init() {
pane.setLayout(new GridLayout(4, 3));
setSize(500, 500);
// Adds jlabel for scores
scoreP1 = new JLabel();
scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
scoreP2 = new JLabel();
scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
blank = new JLabel();
blank.setText(prevWinner);
// these are the JButtons that go in the game panel along with action
// listeners
firstButton = new JButton();
firstButton.addActionListener(this);
secondButton = new JButton();
secondButton.addActionListener(this);
thirdButton = new JButton();
thirdButton.addActionListener(this);
fourthButton = new JButton();
fourthButton.addActionListener(this);
fithButton = new JButton();
fithButton.addActionListener(this);
sixthButton = new JButton();
sixthButton.addActionListener(this);
seventhButton = new JButton();
seventhButton.addActionListener(this);
eighthButton = new JButton();
eighthButton.addActionListener(this);
ninthButton = new JButton();
ninthButton.addActionListener(this);
pane.add(firstButton, 0); // second parameter is the index on pane
pane.add(secondButton, 1);
pane.add(thirdButton, 2);
pane.add(fourthButton, 3);
pane.add(fithButton, 4);
pane.add(sixthButton, 5);
pane.add(seventhButton, 6);
pane.add(eighthButton, 7);
pane.add(ninthButton, 8);
pane.add(scoreP1);
pane.add(blank);
pane.add(scoreP2);
gamesPlayed++;
setContentPane(pane);
} // init method
// checks for mouse clicks here.
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
if (e.getSource() == firstButton)
revealButton(firstButton, 0);
else if (e.getSource() == secondButton)
revealButton(secondButton, 1);
else if (e.getSource() == thirdButton)
revealButton(thirdButton, 2);
else if (e.getSource() == fourthButton)
revealButton(fourthButton, 3);
else if (e.getSource() == fithButton)
revealButton(fithButton, 4);
else if (e.getSource() == sixthButton)
revealButton(sixthButton, 5);
else if (e.getSource() == seventhButton)
revealButton(seventhButton, 6);
else if (e.getSource() == eighthButton)
revealButton(eighthButton, 7);
else if (e.getSource() == ninthButton)
revealButton(ninthButton, 8);
}
} // actionPerformed method
// respond to button pushed
public void revealButton(JButton button, int index) {
// removes the indicated button from pane
pane.remove(button);
// creates a new text field to take the place of the button, makes it
// uneditable and sets background colour
JTextField textField = new JTextField();
textField.setEditable(false);
textField.setBackground(Color.WHITE);
// sets the alignment for the text in the field
textField.setHorizontalAlignment(SwingConstants.CENTER);
// adds the new textfield to the pane at the location of the old button
pane.add(textField, index);
posCheck[index] = symbol[(turnCounter % 2)];
prevWinner = "Player (" + symbol[(turnCounter % 2)]
+ ") is the winner!";
// re-creates pane with new information
setContentPane(pane);
// this sets the text field to either X or O depending who placed last.
textField.setText(symbol[(turnCounter) % 2]);
button.setEnabled(false);
// this is a counter to check if it is a cats game.
tieChecker++;
// check for winner X here
if (((posCheck[0] == "X") && (posCheck[1] == "X") && (posCheck[2] == "X"))
|| ((posCheck[3] == "X") && (posCheck[4] == "X") && (posCheck[5] == "X"))
|| ((posCheck[6] == "X") && (posCheck[7] == "X") && (posCheck[8] == "X"))
|| ((posCheck[0] == "X") && (posCheck[3] == "X") && (posCheck[6] == "X"))
|| ((posCheck[1] == "X") && (posCheck[4] == "X") && (posCheck[7] == "X"))
|| ((posCheck[2] == "X") && (posCheck[5] == "X") && (posCheck[8] == "X"))
|| ((posCheck[0] == "X") && (posCheck[4] == "X") && (posCheck[8] == "X"))
|| ((posCheck[2] == "X") && (posCheck[4] == "X") && (posCheck[6] == "X"))) {
// this part updates the winner score then refreshes the text field
// to reflect the change
scoreCount1++;
scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
blank.setText("Player (X) Is the winner.");
gameDone = true;
turnCounter++;
}
// this checks if O has won the game.
else if (((posCheck[0] == "O") && (posCheck[1] == "O") && (posCheck[2] == "O"))
|| ((posCheck[3] == "O") && (posCheck[4] == "O") && (posCheck[5] == "O"))
|| ((posCheck[6] == "O") && (posCheck[7] == "O") && (posCheck[8] == "O"))
|| ((posCheck[0] == "O") && (posCheck[3] == "O") && (posCheck[6] == "O"))
|| ((posCheck[1] == "O") && (posCheck[4] == "O") && (posCheck[7] == "O"))
|| ((posCheck[2] == "O") && (posCheck[5] == "O") && (posCheck[8] == "O"))
|| ((posCheck[0] == "O") && (posCheck[4] == "O") && (posCheck[8] == "O"))
|| ((posCheck[2] == "O") && (posCheck[4] == "O") && (posCheck[6] == "O"))) {
// this part updates the winner score then refreshes the text field
// to reflect the change
scoreCount2++;
scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
blank.setText("Player (O) Is the winner.");
gameDone = true;
turnCounter++;
}
// this checks if there has been a tie in the game
else if (tieChecker >= 9) {
prevWinner = ("It's a cat's game!");
tieChecker = 0;
gameDone = true;
turnCounter++;
}
// this makes sure the game doesnt end prematurely
else {
gameDone = false;
}
// this if statement is engaged when the game is done and resets the
// board
if (gameDone == true) {
pane.removeAll();
textField.removeAll();
tieChecker = 0;
init();
posCheck[0] = "";
posCheck[1] = "";
posCheck[2] = "";
posCheck[3] = "";
posCheck[4] = "";
posCheck[5] = "";
posCheck[6] = "";
posCheck[7] = "";
posCheck[8] = "";
posCheck[9] = "";
}// end of reset sequence
turnCounter++;
blank.setText("Games Played: " + gamesPlayed);
}
}
If you insist on keeping it as an Applet, make another class and do this:
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
Game g = new Game();
g.init();
frame.getContentPane().add(g);
frame.pack();
frame.setVisible(true);
}
}
You can convert JApplet to JFrame - Change your public init() method to public static void main (String args[]).Then create an instance of JFrame
JFrame frame = new JFrame(); Then add components to it.
or
Add existing applet to JFrame - Adding JApplet into JFrame
So using second method your code would be -
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JApplet implements ActionListener {
// Create all labels, textfields and buttons needed (in order)
/**
* This is a tic tac toe game made with the purposes of learning java
*/
private static final long serialVersionUID = 1L;
JButton firstButton;
JButton secondButton;
JButton thirdButton;
JButton fourthButton;
JButton fithButton;
JButton sixthButton;
JButton seventhButton;
JButton eighthButton;
JButton ninthButton;
//this is the position value checker which are later set to x and o
String[] posCheck = { "", "", "", "", "", "", "", "", "" };
// score count JLABELs to display the score inside the game pane.
JLabel scoreP1;
JLabel scoreP2;
// this is used for formatting purposes or something like that, I guess.
JLabel blank;
// score count variables for both players, they both start at 0.
int scoreCount1 = 0, scoreCount2 = 0;
int gamesPlayed = -1;
boolean gameDone = false;
int k;
String prevWinner = "";
// Create any global variables/arrays needed later in the program (final)
Container pane = getContentPane();
//this sets the tile to X or O depending on who's turn it is
String[] symbol = { "O", "X" };
int turnCounter = 0;
int tieChecker = 0;
// Sets up GUI components.
public void init() {
pane.setLayout(new GridLayout(4, 3));
setSize(500, 500);
// Adds jlabel for scores
scoreP1 = new JLabel();
scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
scoreP2 = new JLabel();
scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
blank = new JLabel();
blank.setText(prevWinner);
// these are the JButtons that go in the game panel along with action
// listeners
firstButton = new JButton();
firstButton.addActionListener(this);
secondButton = new JButton();
secondButton.addActionListener(this);
thirdButton = new JButton();
thirdButton.addActionListener(this);
fourthButton = new JButton();
fourthButton.addActionListener(this);
fithButton = new JButton();
fithButton.addActionListener(this);
sixthButton = new JButton();
sixthButton.addActionListener(this);
seventhButton = new JButton();
seventhButton.addActionListener(this);
eighthButton = new JButton();
eighthButton.addActionListener(this);
ninthButton = new JButton();
ninthButton.addActionListener(this);
pane.add(firstButton, 0); // second parameter is the index on pane
pane.add(secondButton, 1);
pane.add(thirdButton, 2);
pane.add(fourthButton, 3);
pane.add(fithButton, 4);
pane.add(sixthButton, 5);
pane.add(seventhButton, 6);
pane.add(eighthButton, 7);
pane.add(ninthButton, 8);
pane.add(scoreP1);
pane.add(blank);
pane.add(scoreP2);
gamesPlayed++;
setContentPane(pane);
} // init method
// checks for mouse clicks here.
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
if (e.getSource() == firstButton)
revealButton(firstButton, 0);
else if (e.getSource() == secondButton)
revealButton(secondButton, 1);
else if (e.getSource() == thirdButton)
revealButton(thirdButton, 2);
else if (e.getSource() == fourthButton)
revealButton(fourthButton, 3);
else if (e.getSource() == fithButton)
revealButton(fithButton, 4);
else if (e.getSource() == sixthButton)
revealButton(sixthButton, 5);
else if (e.getSource() == seventhButton)
revealButton(seventhButton, 6);
else if (e.getSource() == eighthButton)
revealButton(eighthButton, 7);
else if (e.getSource() == ninthButton)
revealButton(ninthButton, 8);
}
} // actionPerformed method
// respond to button pushed
public void revealButton(JButton button, int index) {
// removes the indicated button from pane
pane.remove(button);
// creates a new text field to take the place of the button, makes it
// uneditable and sets background colour
JTextField textField = new JTextField();
textField.setEditable(false);
textField.setBackground(Color.WHITE);
// sets the alignment for the text in the field
textField.setHorizontalAlignment(SwingConstants.CENTER);
// adds the new textfield to the pane at the location of the old button
pane.add(textField, index);
posCheck[index] = symbol[(turnCounter % 2)];
prevWinner = "Player (" + symbol[(turnCounter % 2)]
+ ") is the winner!";
// re-creates pane with new information
setContentPane(pane);
// this sets the text field to either X or O depending who placed last.
textField.setText(symbol[(turnCounter) % 2]);
button.setEnabled(false);
// this is a counter to check if it is a cats game.
tieChecker++;
// check for winner X here
if (((posCheck[0] == "X") && (posCheck[1] == "X") && (posCheck[2] == "X"))
|| ((posCheck[3] == "X") && (posCheck[4] == "X") && (posCheck[5] == "X"))
|| ((posCheck[6] == "X") && (posCheck[7] == "X") && (posCheck[8] == "X"))
|| ((posCheck[0] == "X") && (posCheck[3] == "X") && (posCheck[6] == "X"))
|| ((posCheck[1] == "X") && (posCheck[4] == "X") && (posCheck[7] == "X"))
|| ((posCheck[2] == "X") && (posCheck[5] == "X") && (posCheck[8] == "X"))
|| ((posCheck[0] == "X") && (posCheck[4] == "X") && (posCheck[8] == "X"))
|| ((posCheck[2] == "X") && (posCheck[4] == "X") && (posCheck[6] == "X"))) {
// this part updates the winner score then refreshes the text field
// to reflect the change
scoreCount1++;
scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
blank.setText("Player (X) Is the winner.");
gameDone = true;
turnCounter++;
}
// this checks if O has won the game.
else if (((posCheck[0] == "O") && (posCheck[1] == "O") && (posCheck[2] == "O"))
|| ((posCheck[3] == "O") && (posCheck[4] == "O") && (posCheck[5] == "O"))
|| ((posCheck[6] == "O") && (posCheck[7] == "O") && (posCheck[8] == "O"))
|| ((posCheck[0] == "O") && (posCheck[3] == "O") && (posCheck[6] == "O"))
|| ((posCheck[1] == "O") && (posCheck[4] == "O") && (posCheck[7] == "O"))
|| ((posCheck[2] == "O") && (posCheck[5] == "O") && (posCheck[8] == "O"))
|| ((posCheck[0] == "O") && (posCheck[4] == "O") && (posCheck[8] == "O"))
|| ((posCheck[2] == "O") && (posCheck[4] == "O") && (posCheck[6] == "O"))) {
// this part updates the winner score then refreshes the text field
// to reflect the change
scoreCount2++;
scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
blank.setText("Player (O) Is the winner.");
gameDone = true;
turnCounter++;
}
// this checks if there has been a tie in the game
else if (tieChecker >= 9) {
prevWinner = ("It's a cat's game!");
tieChecker = 0;
gameDone = true;
turnCounter++;
}
// this makes sure the game doesnt end prematurely
else {
gameDone = false;
}
// this if statement is engaged when the game is done and resets the
// board
if (gameDone == true) {
pane.removeAll();
textField.removeAll();
tieChecker = 0;
init();
posCheck[0] = "";
posCheck[1] = "";
posCheck[2] = "";
posCheck[3] = "";
posCheck[4] = "";
posCheck[5] = "";
posCheck[6] = "";
posCheck[7] = "";
posCheck[8] = "";
posCheck[9] = "";
}// end of reset sequence
turnCounter++;
blank.setText("Games Played: " + gamesPlayed);
}
public static void main(String[] args) {
JFrame baseFrame = new JFrame();
Game gameObject = new Game();
gameObject.init();
baseFrame.setVisible(true);
baseFrame.getContentPane().add(gameObject);
}
}

Categories

Resources