+ Reply to Thread
Page 2 of 5 FirstFirst 1234 ... LastLast
Results 11 to 20 of 48

Thread: Java:Tutorial - Tic-Tac-Toe

  1. #11
    Bigbag101 Guest
    Sidewinder | Please use [php], [code] and [quote] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted.

    Still regarding the image instead of text, it still does not appear to be working. If you could be so kind, can you please show me how to setIcon using the code.



    Code:
    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 = 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!");
    			System.exit(0);
    		} else if(count == 9 && win == false){
    			JOptionPane.showMessageDialog(null, "The game was tie!");
    			System.exit(0);
    		}		
    	}
    	
    	public static void main(String[] args){
    		TicTacToeV2 starter = new TicTacToeV2();
    	}
    }
    Sidewinder | Please use [php], [code] and [quote] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted.
    Last edited by John; 06-02-2007 at 08:57 AM.

  2. CODECALL Circuit advertisement

     
  3. #12
    Join Date
    Jul 2006
    Location
    Amherst, New York, United States
    Posts
    6,277
    Blog Entries
    26
    Rep Power
    20
    From the looks of it, you've made no changes to my code. Show me what you did and I will help.

    Have you looked at the Javadocs?

    Java Platform 1.2 Beta 4 API Specification: Class JButton

  4. #13
    Join Date
    Oct 2007
    Posts
    14
    Rep Power
    0

    Hmm...

    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:

    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.

  5. #14
    Join Date
    Jul 2006
    Location
    Amherst, New York, United States
    Posts
    6,277
    Blog Entries
    26
    Rep Power
    20
    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...

  6. #15
    phenoma is offline Newbie
    Join Date
    Nov 2007
    Posts
    5
    Rep Power
    0

    hi

    Sidewinder | Please use [php], [code] 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?


    [highlight="Java"]
    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_CLOS E);
    frame.setVisible(true);
    }
    }[/highlight]

    Sidewinder | Please use [php], [code] and [highlight...] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted.
    Last edited by John; 11-07-2007 at 11:40 AM.

  7. #16
    Join Date
    Jul 2006
    Location
    Amherst, New York, United States
    Posts
    6,277
    Blog Entries
    26
    Rep Power
    20
    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:
    [highlight="Java"]
    public void reset() {
    for(int i = 1; i<=9; i++) {
    buttons[i].setText("");
    buttons[i].setEnabled(true);
    }
    }[/highlight]

    As for keeping track of who won, for my code I would declare two instance variables;
    [highlight="Java"]private int xWins = 0;
    private int oWins = 0;[/highlight]

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

    Hopefully this will give you a nudge in the right direction for what you want to do with your code.
    Last edited by John; 11-07-2007 at 12:00 PM.

  8. #17
    phenoma is offline Newbie
    Join Date
    Nov 2007
    Posts
    5
    Rep Power
    0

    tictactoe

    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!!

  9. #18
    Join Date
    Jul 2006
    Location
    Amherst, New York, United States
    Posts
    6,277
    Blog Entries
    26
    Rep Power
    20
    Code:
    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();
    	}
    }
    Last edited by John; 11-07-2007 at 09:57 PM.

  10. #19
    phenoma is offline Newbie
    Join Date
    Nov 2007
    Posts
    5
    Rep Power
    0
    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....

  11. #20
    Join Date
    Jul 2006
    Location
    Amherst, New York, United States
    Posts
    6,277
    Blog Entries
    26
    Rep Power
    20
    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.

+ Reply to Thread
Page 2 of 5 FirstFirst 1234 ... LastLast

Thread Information

Users Browsing this Thread

There are currently 11 users browsing this thread. (0 members and 11 guests)

Similar Threads

  1. Tutorial: Java Inner Classes
    By Jordan in forum Java Tutorials
    Replies: 1
    Last Post: 02-13-2009, 10:54 PM
  2. Java:Tutorial - A better looking GUI
    By John in forum Java Tutorials
    Replies: 6
    Last Post: 01-12-2009, 03:31 AM
  3. Tutorial: Java Serialization
    By Jordan in forum Java Tutorials
    Replies: 0
    Last Post: 05-07-2008, 02:34 PM
  4. Tutorial: Java Collections
    By Jordan in forum Java Tutorials
    Replies: 0
    Last Post: 05-05-2008, 04:38 PM
  5. Java UML Tutorial
    By gszauer in forum Java Help
    Replies: 4
    Last Post: 01-30-2008, 08:55 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts