Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Java:Tutorial - Tic-Tac-Toe

tic-tac-toe

  • Please log in to reply
60 replies to this topic

#13 The Midnighter

The Midnighter

    CC Newcomer

  • Just Joined
  • PipPip
  • 14 posts

Posted 25 October 2007 - 07:25 AM

I'm having trouble creating a working win function, so I googled it.. and here I am.

I know this thread is meretriciously old, but I really need this help lol.
Here's my current code:

package tictactoe;

import javax.swing.JButton;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TicTacToeForm extends javax.swing.JFrame implements ActionListener
{
    private int[][] winCombinations = new int[][] {
        {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
        {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
        {0, 4, 8}, {2, 4, 6}			 //diagonal wins
    };
    private String turn = "";
    private String config[] = new String[10];
    private boolean win = false;
    private int count = 0;
    
    public TicTacToeForm()
    {
        initComponents();
        jButton1.addActionListener(this);
        jButton2.addActionListener(this);
        jButton3.addActionListener(this);
        jButton4.addActionListener(this);
        jButton5.addActionListener(this);
        jButton6.addActionListener(this);
        jButton7.addActionListener(this);
        jButton8.addActionListener(this);
        jButton9.addActionListener(this);
    }
    
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
    private void initComponents()
    {
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jButton9 = new javax.swing.JButton();

        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("TicTacToe");
        setName("jFrame");
        jButton2.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton2ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 10, 75, 70));

        jButton3.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton3ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 10, 75, 70));

        jButton4.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton4ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, 75, 70));

        jButton5.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton5ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 90, 75, 70));

        jButton6.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton6ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 90, 75, 70));

        jButton1.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton1ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 75, 70));

        jButton7.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton7ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 170, 75, 70));

        jButton8.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton8ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton8, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 170, 75, 70));

        jButton9.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton9ActionPerformed(evt);
            }
        });

        getContentPane().add(jButton9, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 170, 75, 70));

        pack();
    }// </editor-fold>                        
    
    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton9.setText(turn);
        jButton9.setEnabled(false);
        config[9] = turn;
    }                                        
    
    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton8.setText(turn);
        jButton8.setEnabled(false);
        config[8] = turn;
    }                                        
    
    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton7.setText(turn);
        jButton7.setEnabled(false);
        config[7] = turn;
    }                                        
    
    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton6.setText(turn);
        jButton6.setEnabled(false);
        config[6] = turn;
    }                                        
    
    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton5.setText(turn);
        jButton5.setEnabled(false);
        config[5] = turn;
    }                                        
    
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton4.setText(turn);
        jButton4.setEnabled(false);
        config[4] = turn;
    }                                        
    
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton3.setText(turn);
        jButton3.setEnabled(false);
        config[3] = turn;
    }                                        
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton2.setText(turn);
        jButton2.setEnabled(false);
        config[2] = turn;
    }                                        
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
        jButton1.setText(turn);
        jButton1.setEnabled(false);
        config[1] = turn;
    }                                        
    
    public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new TicTacToeForm().setVisible(true);
            }
        });
    }
    
    public boolean checkWinner()
    {
        for(int i=0; i<=7; i++)
        {
            if( config[winCombinations[i][0]].equals(config[winCombinations[i][1]]) &&
                    config[winCombinations[i][1]].equals(config[winCombinations[i][2]]) &&
                    config[winCombinations[i][0]] != "")
            {
                win = true;
            }
        }
        return win;
    }
    
    public void actionPerformed(ActionEvent a)
    {
        count++;
        
        if(count %2 == 0)
        {
            turn = "O";
        }
        else
        {
            turn = "X";
        }
        
    }
    
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    // End of variables declaration                   
}

Right now, my checkWinner(); function doesn't work at all, I tried to adapt a few ideas from this thread, but it didn't help a whole lot.
Any help is appreciated.
  • 0

#14 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 25 October 2007 - 09:41 AM

Well there is 3 things I noticed.
1) You used a crappy IDE to generate your code, use a descent IDE like eclipse and write every line of code yourself and it wont look like fecal matter.

2) Your config array starts at 1 and goes to 9, yet winCombinations[][] only only checks an array from 0 to 8.

3) checkWinner() is never called...
  • 0

#15 phenoma

phenoma

    CC Lurker

  • Just Joined
  • Pip
  • 5 posts

Posted 07 November 2007 - 11:29 AM

Sidewinder | Please use [php], [code=auto:0] and [highlight...] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted.

I know its been a year for the java tutotrial,but I need ur help! can u help me add:
1. A new Game button that starts a new game
2.A running score showing the number of games won by each player(X or O).
in my tic tac toe program?



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;

public class TicTacToe extends JApplet {
// Indicate which player has a turn, initially it is the X player
private char whoseTurn = 'X';

// Create and initialize cells
private Cell[][] cells = new Cell[3][3];

// Create and initialize a status label
private JLabel jlblStatus = new JLabel("X's turn to play");

/** Initialize UI */
public TicTacToe() {
// Panel p to hold cells
JPanel p = new JPanel(new GridLayout(3, 3, 0, 0));
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
p.add(cells[i][j] = new Cell());

// Set line borders on the cells panel and the status label
p.setBorder(new LineBorder(Color.red, 1));
jlblStatus.setBorder(new LineBorder(Color.yellow, 1));

// Place the panel and the label to the applet
add(p, BorderLayout.CENTER);
add(jlblStatus, BorderLayout.SOUTH);
}

/** Determine if the cells are all occupied */
public boolean isFull() {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if (cells[i][j].getToken() == ' ')
return false;

return true;
}

/** Determine if the player with the specified token wins */
public boolean isWon(char token) {
for (int i = 0; i < 3; i++)
if ((cells[i][0].getToken() == token)
&& (cells[i][1].getToken() == token)
&& (cells[i][2].getToken() == token)) {
return true;
}

for (int j = 0; j < 3; j++)
if ((cells[0][j].getToken() == token)
&& (cells[1][j].getToken() == token)
&& (cells[2][j].getToken() == token)) {
return true;
}

if ((cells[0][0].getToken() == token)
&& (cells[1][1].getToken() == token)
&& (cells[2][2].getToken() == token)) {
return true;
}

if ((cells[0][2].getToken() == token)
&& (cells[1][1].getToken() == token)
&& (cells[2][0].getToken() == token)) {
return true;
}

return false;
}

// An inner class for a cell
public class Cell extends JPanel {
// Token used for this cell
private char token = ' ';

public Cell() {
setBorder(new LineBorder(Color.black, 1)); // Set cell's border
addMouseListener(new MouseListener()); // Register listener
}

/** Return token */
public char getToken() {
return token;
}

/** Set a new token */
public void setToken(char c) {
token = c;
repaint();
}

/** Paint the cell */
protected void paintComponent(Graphics g) {
super.paintComponent(g);

if (token == 'X') {
g.drawLine(10, 10, getWidth() - 10, getHeight() - 10);
g.drawLine(getWidth() - 10, 10, 10, getHeight() - 10);
}
else if (token == 'O') {
g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);
}
}

private class MouseListener extends MouseAdapter {
/** Handle mouse click on a cell */
public void mouseClicked(MouseEvent e) {
// If cell is empty and game is not over
if (token == ' ' && whoseTurn != ' ') {
setToken(whoseTurn); // Set token in the cell

// Check game status
if (isWon(whoseTurn)) {
jlblStatus.setText(whoseTurn + " won! The game is over");
whoseTurn = ' '; // Game is over
}
else if (isFull()) {
jlblStatus.setText("Draw! The game is over");
whoseTurn = ' '; // Game is over
}
else {
whoseTurn = (whoseTurn == 'X') ? 'O': 'X'; // Change the turn
jlblStatus.setText(whoseTurn + "'s turn"); // Display whose turn
}
}
}
}
}

/** This main method enables the applet to run as an application */
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("TicTacToe");

// Create an instance of the applet
TicTacToe applet = new TicTacToe();

// Add the applet instance to the frame
frame.add(applet, BorderLayout.CENTER);

// Display the frame
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}


Sidewinder | Please use [php], [code=auto:0] and [highlight...] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted.
  • 0

#16 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 07 November 2007 - 11:58 AM

I don't have time to work with your exact code right now, but to do what you what with my code, this is what you would need to do:

For a "New Game"
1. After the game is over use a JOptionPane - "Do you want to play another game?" - Yes would invoke lets say the reset() method [defined below], and No would end the game.

The reset() method would just need to loop through the 9 buttons and set their text to " " and enable the button. The loop would look like this:

public void reset() {
for(int i = 1; i<=9; i++) {
buttons[i].setText("");
buttons[i].setEnabled(true);
}
}


As for keeping track of who won, for my code I would declare two instance variables;
private int xWins = 0;
private int oWins = 0;


And then in my checkWin() method, I would modify this code:
		if(count % 2 == 0)
letter = "O";
else
letter = "X";
And change it to:
		if(count % 2 == 0) {
letter = "O";
oWins++;
} else {
letter = "X";
xWins++;
}


Hopefully this will give you a nudge in the right direction for what you want to do with your code.
  • 0

#17 phenoma

phenoma

    CC Lurker

  • Just Joined
  • Pip
  • 5 posts

Posted 07 November 2007 - 07:02 PM

sorry but I have tried what you said with your code but it did not work! or may be I'm mistaking...need your help!!
  • 0

#18 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 07 November 2007 - 09:49 PM

package general;



import java.awt.*;

import java.awt.event.*;

import javax.swing.*;



public class TicTacToeV2 implements ActionListener {

	/*Instance Variables*/

	private int[][] winCombinations = new int[][] {

			{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins

			{0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins

			{0, 4, 8}, {2, 4, 6}			 //diagonal wins

		};

	private JFrame window = new JFrame("Tic-Tac-Toe");

	private JButton buttons[] = new JButton[9];

	private int count, xWins, oWins = 0;

	private String letter = "";

	private boolean win = false;



	public TicTacToeV2(){

	/*Create Window*/

	window.setSize(300,300);

	window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	window.setLayout(new GridLayout(3,3));

	

	/*Add Buttons To The Window*/

	for(int i=0; i<=8; i++){

		buttons[i] = new JButton();

		window.add(buttons[i]);

		buttons[i].addActionListener(this);

	}

	

	/*Make The Window Visible*/

	window.setVisible(true);

	}

	

	/**

	 When an object is clicked, perform an action.

	 @param a action event object

	 */

	public void actionPerformed(ActionEvent a) {

		count++;

		

		/*Calculate whose turn it is*/

		if(count % 2 == 0)

			letter = "O";

		else

			letter = "X";



		/*Write the letter to the button and deactivate it*/

		 JButton pressedButton = (JButton)a.getSource(); 

		 pressedButton.setText(letter);

		 pressedButton.setEnabled(false);

		

		/*Determine who won*/

		for(int i=0; i<=7; i++){

			if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) && 

				buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) && 

				buttons[winCombinations[i][0]].getText() != ""){

				win = true;

			}

		}

		

		/*Show a dialog when game is over*/

		if(win == true){

			JOptionPane.showMessageDialog(null, letter + " wins the game!");

			playAgainDialog();

		} else if(count == 9 && win == false){

			JOptionPane.showMessageDialog(null, "The game was tie!");

			playAgainDialog();

		}		

	}

	

	public void playAgainDialog() {

		if(letter.equals("X"))  xWins++;

		else                    oWins++;

		

		int response = JOptionPane.showConfirmDialog(null, "Do you want to play again?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

		

		if(response == JOptionPane.YES_OPTION)   reset();

		else                                     System.exit(0);

		

	}

	

	public void reset() {

		for(int i=0; i<=8; i++){

			buttons[i].setText("");

			buttons[i].setEnabled(true);

		}

		win = false;

		count = 0;

	}

	

	public static void main(String[] args){

		TicTacToeV2 starter = new TicTacToeV2();

	}

}

  • 0

#19 phenoma

phenoma

    CC Lurker

  • Just Joined
  • Pip
  • 5 posts

Posted 12 November 2007 - 12:45 PM

appreciate what you are doing for me but working with your program, I can reset it for a new game but still don't know exactly where to modify your program for keeping up with the score, please help...sorry about that....
  • 0

#20 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 12 November 2007 - 06:29 PM

If X wins the game, the variable 'xWins' is incremented. If O wins the game the variable 'oWins' is incremented. Not sure how much more explicit it can be. You can either print it to the console, or add it to the GUI. Adding it to the GUI would probably require a reconstruction of the entire GUI to use multiple panels - one for the game, and another for the score.

P.S. For future questions, there is no need to PM me, I check the forums regularly.
  • 0

#21 TkTech

TkTech

    The Crazy One

  • Retired Mod
  • PipPipPipPipPipPipPip
  • 1144 posts
  • Location:Ottawa, Ontario

Posted 12 November 2007 - 06:45 PM

P.S For future refrence, he thanks you for doing his assignment ;)

Nice code Sidewinder *pulls out a dusty javadoc refrence and begins to read - yes, no swing just AWT...say something about age?*
  • 0
Helpful CODECALL Links: Join Us, Guidelines, FAQ, Post a Tutorial

#22 phenoma

phenoma

    CC Lurker

  • Just Joined
  • Pip
  • 5 posts

Posted 13 November 2007 - 11:56 AM

sorry about that...
  • 0

#23 daremeister

daremeister

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 08 February 2008 - 08:32 AM

Sorry I know this thread is over a year old, but however it has been a big help for me while writing my own java program. I have read through all of the posts, and tried to implement your ideas. However, my instructor requires that our program use two files to get the job done, not just one. Any ideas or pointers in the right direction as to how I could accomplish this? Any help would be appreciated. I included the two files I have tried to do already. Whenever I run it, I recieve no build messages but get some weird exception, (Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException) and am not sure how to fix this. Thanks.

Attached Files


  • 0

#24 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 08 February 2008 - 09:50 AM

A NullPointerException means you have tried to instantiate an object that hasn't been given a value.
  • 0





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