Results 1 to 17 of 17

Thread: TicTacToe Help

  1. #1
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default TicTacToe Help

    I have everything i need so far..a perfect layout..a menu bar and buttons and a text field at the bottom that i want to display who wins. If anyone here can help me with (when the buttons are clicked an "x or 0" comes up and show the result of who won.

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JOptionPane;
    
    public class TTT extends Frame implements ActionListener
    {
    private Button keys[];
    private Panel keypad;
    private TextField lcd;
    private boolean first;
    private boolean foundKey;
    private boolean clearText;
    
    ////////////MENU//////////////////////////////////////////////////////////
    public TTT()
    {
    MenuBar mnuBar = new MenuBar();
    setMenuBar(mnuBar);
    
    Menu mnuFile = new Menu("File", true);
    mnuBar.add(mnuFile);
    MenuItem mnuFileExit = new MenuItem("Exit");
    mnuFile.add(mnuFileExit);
    
    Menu mnuEdit = new Menu("Edit", true);
    mnuBar.add(mnuEdit);
    MenuItem mnuEditClear = new MenuItem("Clear");
    mnuEdit.add(mnuEditClear);
    
    Menu mnuAbout = new Menu("About", true);
    mnuBar.add(mnuAbout);
    MenuItem mnuAboutTicTacToe = new MenuItem("About TicTacToe");
    mnuAbout.add(mnuAboutTicTacToe);
    
    mnuFileExit.addActionListener(this);
    mnuEditClear.addActionListener(this);
    mnuAboutTicTacToe.addActionListener(this);
    
    mnuFileExit.setActionCommand("Exit");
    mnuEditClear.setActionCommand("Clear");
    mnuAboutTicTacToe.setActionCommand("About");
    
    lcd = new TextField(10);
    lcd.setEditable(false);
    keypad = new Panel();
    keys = new Button [10];
    first = true;
    clearText = true;
    
    for (int i=0; i<=9; i++)
    keys[i] = new Button();
    
    //////////////LAYOUT BORDER////////////////////////////////////////////
    
    setLayout(new BorderLayout());
    keypad.setLayout(new GridLayout(3,3,10,10));
    
    for (int i=1; i<=9; i++)
    keypad.add(keys[i]);
    
    add(lcd, BorderLayout.SOUTH);
    add(keypad, BorderLayout.CENTER);
    
    addWindowListener(
    new WindowAdapter()
    {
    ////////////////EXIT,ABOUT,CLEAR////////////////////////////////////////
    public void windowClosing(WindowEvent e)
    {
    System.exit(0);
    }
    }
    );
    }
    
    public void actionPerformed(ActionEvent e)
    {
    
    String arg = e.getActionCommand();
    if (arg == "Exit")
    System.exit(0);
    
    if (arg == "Clear")
    {
    
    }
    
    
    if (arg == "About")
    {
    String message = "Ryan's TicTacToe \nStructured Programming\nCopyright 2011\nAll rights reserved";
    JOptionPane.showMessageDialog(null,message,
    "About TicTacToe", JOptionPane.INFORMATION_MESSAGE);
    }
    }
    /////////////////TITLE,IMAGE,HEIGHT,WIDTH/////////////////////////////////////////////
    public static void main(String args[])
    
    {
    TTT f = new TTT();
    f.setTitle("TicTacToe Game");
    f.setBounds(200,200,300,300);
    f.setVisible(true);
    
    Image icon = Toolkit.getDefaultToolkit().getImage("Image.gif");
    f.setIconImage(icon);
    
    }
    }

  2. #2
    doWhile is online now Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default

    I suggest you be a lot more specific about your question or problem. Only you know what you need, so help us understand and you will get help much faster. Suggested reading; How To Ask Questions The Smart Way

  3. #3
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    An action basically when i click on a button an x or o appears and if you get three in a row then the result comes up in the bottom of the application as to who won.

  4. #4
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    can anyone help me in the right direction?

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,457
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Ryan10 View Post
    Java Code:
    String arg = e.getActionCommand();
    if (arg == "Exit")
    
    if (arg == "Clear")
    
    if (arg == "About")
    Those are real beginner nonos; you don't compare Strings for equality with the == operator; use the equals( ... ) method instead. Read the API documentation for the String class.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    well my menu works fine thats not what i need help with..but instead just the basic action of when i click a button an x or o shows.

    Thanks

  7. #7
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default

    you need the board in place first, add 9 buttons

    [but1] [but2] [but3]
    [but4] [but5] [but6]
    [but7] [but8] [but9]

    then if the button is clicked, the action command should be:
    Java Code:
    but1Action() {
        if (but1.getText() == null) {
            but1.setText(getSymbol(player));
            evaluateBoard();
        }
    }
    Java Code:
    public String getSymbol(boolean player) {
    String currentPlayer = "";
       if (player) {
            currentPlayer = "X";
       } else {
            currentPlayer = "O";
       }
    return currentPlayer;
    Java Code:
    evaluateBoard() {
        //if there is 3 in a row, set winner, end game
    }
    note: this is a rough idea of a possible solution which you could build on
    Last edited by ozzyman; 03-31-2011 at 05:29 PM. Reason: change if(player==0) to if(player) because in java, boolean are either TRUE or FALSE; not 1 or 0

  8. #8
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    thanks ozzy thats what i need. Appreciate it

  9. #9
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    but i have one question what if i already have "keys" instead of buttons will it work?

  10. #10
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default

    it was a rough idea, i don't know how to use keys. but you don't have to use buttons. you could use text labels, or even set images to buttons or labels; just use anything that will graphically represent the current board.

    it would also be ideal to use an array to read the board from, and write to when the board changes. then you can directly evaluate the values in the board array.

  11. #11
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,457
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Ryan10 View Post
    well my menu works fine thats not what i need help with..but instead just the basic action of when i click a button an x or o shows.

    Thanks
    Good; keep on comparing two Strings for equality with the == operator.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  12. #12
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    but it would probably be easier just to change them to buttons

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,457
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Ryan10 View Post
    but it would probably be easier just to change them to buttons
    Nope, just don't compare Strings for equality the way you do; it is incorrect and in you case just works accidentally.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  14. #14
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    Add buttons like that then?

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

    buttons[i] = new JButton();
    window.add(buttons[i]);
    buttons[i].addActionListener(this);
    }

  15. #15
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default

    you can add the buttons however you like, before hand or dynamically. adding them dynamically means you need to add the button actions dynamically too.

    and take JosAhs advice about the == thing

    Comparing Object references with the == and != Operators
    The two operators that can be used with object references are comparing for equality (==) and inequality (!=). These operators compare two values to see if they refer to the same object. Although this comparison is very fast, it is often not what you want.

    Usually you want to know if the objects have the same value, and not whether two objects are a reference to the same object. For example,

    Java Code:
    if (name == "Mickey Mouse")   // Legal, but ALMOST SURELY WRONG
    This is true only if name is a reference to the same object that "Mickey Mouse" refers to. This will be false if the String in name was read from input or computed (by putting strings together or taking the substring), even though name really does have exactly those characters in it.

    Many classes (eg, String) define the equals() method to compare the values of objects.
    Java: ==, .equals(), compareTo(), and compare()

  16. #16
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    Ok i changed my code around quite a bit but i still need to add somethings that i posted in the second code but im pretty sure im not going to beable to put in 2 "ActionPerformed (event e)" in the same code. Is there another way to add in that second half of the code so i can finish this up and i will look into the "==" problem later im not too concerned about the menu as opposed to it actually working.


    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JOptionPane;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import java.awt.Color;
    
    public class TTT3 extends Frame 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, X, O, SOUTH, b1 = 0;
        private String letter = "";
        private boolean win = false;
        private TextField lcd;
        private Choice colors= new Choice();
    
    ////////////MENU//////////////////////////////////////////////////////////
    public TTT3()
    {
    MenuBar mnuBar = new MenuBar();
    setMenuBar(mnuBar);
    
    Menu mnuFile = new Menu("File", true);
    mnuBar.add(mnuFile);
    MenuItem mnuFileExit = new MenuItem("Exit");
    mnuFile.add(mnuFileExit);
    
    Menu mnuEdit = new Menu("Edit", true);
    mnuBar.add(mnuEdit);
    MenuItem mnuEditClear = new MenuItem("Clear");
    mnuEdit.add(mnuEditClear);
    
    Menu mnuAbout = new Menu("About", true);
    mnuBar.add(mnuAbout);
    MenuItem mnuAboutTicTacToe = new MenuItem("About TicTacToe");
    mnuAbout.add(mnuAboutTicTacToe);
    
    mnuFileExit.addActionListener(this);
    mnuEditClear.addActionListener(this);
    mnuAboutTicTacToe.addActionListener(this);
    
    mnuFileExit.setActionCommand("Exit");
    mnuEditClear.setActionCommand("Clear");
    mnuAboutTicTacToe.setActionCommand("About");
    
    lcd = new TextField(10);
    lcd.setEditable(false);
    add(lcd, BorderLayout.SOUTH);
    
    
    
    //////////////LAYOUT BORDER////////////////////////////////////////////
    
     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);
        }
    
    ////////////////EXIT,ABOUT,CLEAR////////////////////////////////////////
    public void windowClosing(WindowEvent e)
    {
    System.exit(0);
    }
    }
    );
    }
    
    public void actionPerformed(ActionEvent e)
    {
    
    String arg = e.getActionCommand();
    if (arg == "Exit")
    System.exit(0);
    
    if (arg == "Clear")
    {
    
    }
    
    
    if (arg == "About")
    {
    String message = "Ryan's TicTacToe \nStructured Programming\nCopyright 2011\nAll rights reserved";
    JOptionPane.showMessageDialog(null,message,
    "About TicTacToe", JOptionPane.INFORMATION_MESSAGE);
    }
    }
    /////////////////TITLE,IMAGE,HEIGHT,WIDTH/////////////////////////////////////////////
    public static void main(String args[])
    
    {
    TTT f = new TTT();
    f.setTitle("TicTacToe Game");
    f.setBounds(200,200,300,300);
    f.setVisible(true);
    
    Image icon = Toolkit.getDefaultToolkit().getImage("Image.gif");
    f.setIconImage(icon);
    
    }
    }


    Java Code:
    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);
             pressedButton.setBackground(Color.RED);
    
    
    
    
    
    
    
    
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
    
            /*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;
                }
            }

  17. #17
    Ryan10 is offline Senior Member
    Join Date
    Mar 2011
    Posts
    144
    Rep Power
    0

    Default

    I am almost there i think..it comes up fine and all the buttons work but now the menu system doesn't work. No errors came up so what advice can you guys give me to fix this problem.


    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import java.awt.Color;
    
    public class TTT3 extends Frame 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, X, O, SOUTH, b1 = 0;
        private String letter = "";
        private boolean win = false;
        private TextField lcd;
        private boolean first;
        private boolean clearText;
        private Choice colors= new Choice();
    
    ////////////MENU//////////////////////////////////////////////////////////
    public TTT3()
    {
    MenuBar mnuBar = new MenuBar();
    setMenuBar(mnuBar);
    
    Menu mnuFile = new Menu("File", true);
    mnuBar.add(mnuFile);
    MenuItem mnuFileExit = new MenuItem("Exit");
    mnuFile.add(mnuFileExit);
    
    Menu mnuEdit = new Menu("Edit", true);
    mnuBar.add(mnuEdit);
    MenuItem mnuEditClear = new MenuItem("Clear");
    mnuEdit.add(mnuEditClear);
    
    Menu mnuAbout = new Menu("About", true);
    mnuBar.add(mnuAbout);
    MenuItem mnuAboutTicTacToe = new MenuItem("About TicTacToe");
    mnuAbout.add(mnuAboutTicTacToe);
    
    mnuFileExit.addActionListener(this);
    mnuEditClear.addActionListener(this);
    mnuAboutTicTacToe.addActionListener(this);
    
    mnuFileExit.setActionCommand("Exit");
    mnuEditClear.setActionCommand("Clear");
    mnuAboutTicTacToe.setActionCommand("About");
    
    lcd = new TextField(10);
    lcd.setEditable(false);
    add(lcd, BorderLayout.SOUTH);
    first = true;
    clearText = true;
    
    
    
    //////////////LAYOUT BORDER////////////////////////////////////////////
    
     /*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);
              pressedButton.setBackground(Color.RED);
    
    
    
     ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
    
             /*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*/
    
    }
    public static void main(String args[]){
    	TTT3 starter = new TTT3();
    
    
     }
    
    
    }

Similar Threads

  1. Help with TicTacToe
    By jokerboy123 in forum New To Java
    Replies: 1
    Last Post: 01-22-2011, 01:29 AM
  2. TicTacToe game
    By pinotje in forum New To Java
    Replies: 9
    Last Post: 12-23-2010, 05:49 PM
  3. Help with tictactoe
    By ximenaacucr in forum New To Java
    Replies: 3
    Last Post: 09-16-2009, 08:30 PM
  4. TicTacToe
    By Thomas Covington in forum New To Java
    Replies: 1
    Last Post: 04-10-2008, 04:51 AM
  5. TicTacToe
    By Joe3161 in forum New To Java
    Replies: 4
    Last Post: 11-25-2007, 06:47 PM

Posting Permissions

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