Tic Tac Toe help


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Page 1 of 2 12 LastLast
Results 1 to 15 of 22

Thread: Tic Tac Toe help

Hybrid View

  1. #1
    Join Date
    Jan 2006
    Posts
    9

    Tic Tac Toe help

    Im looking for the simpliest TTT source code, 3x3 matrix...Human vs Human. If anyone have it, please show me the script.

    Any replyes will be really appreciated!

  2. #2
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468

  3. #3
    Join Date
    Jan 2006
    Posts
    9
    "Take a look:

    http://forum.java.sun.com/thread.js...ssageID=3995002"

    Thank You, but it doesnt have 3x3 matrix and i would really appreciate if it had loops...

  4. #4
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290

  5. #5
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Like this you mean ?

    This is a hybrid.
    It acts like an applet in a browser and as an application when started from the command prompt.
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    /**
     * A tictactoe button
     */
    class TTTBtn extends JButton {
      private int btnNo=-1;
      private boolean hit=false;
      private int value=-1;
      public TTTBtn (int btnNo) {
        super();
        this.btnNo=btnNo;
      }
      public void setHit (boolean p1p2) {
        super.setText(p1p2 ? "X" : "O");
        value= p1p2 ? 1 : 4;
      }
      public int getValue() {
        return value;
      }
      public boolean isHit () {
        return value > 0;
      }
      public void reset() {
        setText("");
        value=-1;
      }
      public int getButtonNo () {
        return btnNo;
      }
    }
    /**
     * A tictactoe applet
     */
    public class TicTacToe
        extends JApplet
        implements ActionListener {
    
      JLabel messagesLabel = new JLabel("X goes first");
      JPanel displayPanel = new JPanel(new GridLayout(3, 3));
      private TTTBtn[] bb = new TTTBtn[9];
      private int [][] winLine={
          {0,1,2}, // horizontal
          {3,4,5},
          {6,7,8},
          {0,3,6}, // vertical
          {1,4,7},
          {2,5,8},
          {0,4,8}, // diagonal
          {6,4,2}
      };
      private JButton resetBtn=new JButton("Reset");
      private boolean player1 = true;
    
      public void init() {
        messagesLabel.setOpaque(true);
        messagesLabel.setHorizontalAlignment(SwingConstants.CENTER);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(messagesLabel, BorderLayout.NORTH);
        getContentPane().add(resetBtn, BorderLayout.SOUTH);
        getContentPane().add(displayPanel, BorderLayout.CENTER);
    
        resetBtn.addActionListener(this);
    
        for (int i = 0; i < 9; i++) {
          bb[i] = new TTTBtn(i);
          bb[i].addActionListener(this);
          displayPanel.add(bb[i]);
        }
    
      }
      public int getWinner() {
        for (int i=0; i<winLine.length; i++) {
          int ret = lineWin(winLine[i]);
          if (ret > 0) return ret;
        }
        return -1;
      }
      private int lineWin(int [] pos) {
        int sum=
            bb[pos[0]].getValue()+
            bb[pos[1]].getValue()+
            bb[pos[2]].getValue();
        if (sum==3) return 1;
        if (sum==12) return 2;
        return -1;
      }
      public void actionPerformed(ActionEvent e) {
        if (e.getSource() == resetBtn) {
          resetGame();
        }
        else if (e.getSource()instanceof TTTBtn) {
          TTTBtn btn = (TTTBtn) e.getSource();
          if (!btn.isHit()) {
            if (haveWinner(btn)) {
              enableButtons(false);
            }
          }
        }
      }
    
      private void enableButtons(boolean enabled) {
        for (int i=0; i<bb.length; i++) {
          bb[i].setEnabled(enabled);
        }
      }
    
      private boolean haveWinner(TTTBtn btn) {
        bb[btn.getButtonNo()].setHit(player1);
        int winner = getWinner();
        if (winner > 0) {
          messagesLabel.setBackground(Color.green);
          messagesLabel.setText("Player " + winner + " wins");
          return true;
        }
        else {
          player1 = !player1;
          return false;
        }
      }
    
      private void resetGame() {
        for (int i=0; i<bb.length; i++) {
          bb[i].reset();
        }
        player1=true;
        messagesLabel.setBackground(Color.lightGray);
        messagesLabel.setText("X goes first");
        enableButtons(true);
      }
      /**
       * Test driver main
       */
      public static void main(String[] args) {
        JFrame f=new JFrame("Tic Tac Toe");
        f.getContentPane().setLayout(new GridLayout());
        TicTacToe ttt=new TicTacToe();
        f.getContentPane().add(ttt);
        f.addWindowListener(new WindowAdapter() {
          public void windowClosed(WindowEvent e) {
            System.exit(0);
          }
        });
        ttt.init();
        f.setBounds(100,100,300,270);
        f.setVisible(true);
      }
    }
    eschew obfuscation

  6. #6
    Join Date
    Jan 2006
    Posts
    9
    Quote Originally Posted by sjalle
    This is a hybrid.
    It acts like an applet in a browser and as an application when started from the command prompt.
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    /**
     * A tictactoe button
     */
    class TTTBtn extends JButton {
      private int btnNo=-1;
      private boolean hit=false;
      private int value=-1;
      public TTTBtn (int btnNo) {
        super();
        this.btnNo=btnNo;
      }
      public void setHit (boolean p1p2) {
        super.setText(p1p2 ? "X" : "O");
        value= p1p2 ? 1 : 4;
      }
      public int getValue() {
        return value;
      }
      public boolean isHit () {
        return value > 0;
      }
      public void reset() {
        setText("");
        value=-1;
      }
      public int getButtonNo () {
        return btnNo;
      }
    }
    /**
     * A tictactoe applet
     */
    public class TicTacToe
        extends JApplet
        implements ActionListener {
    
      JLabel messagesLabel = new JLabel("X goes first");
      JPanel displayPanel = new JPanel(new GridLayout(3, 3));
      private TTTBtn[] bb = new TTTBtn[9];
      private int [][] winLine={
          {0,1,2}, // horizontal
          {3,4,5},
          {6,7,8},
          {0,3,6}, // vertical
          {1,4,7},
          {2,5,8},
          {0,4,8}, // diagonal
          {6,4,2}
      };
      private JButton resetBtn=new JButton("Reset");
      private boolean player1 = true;
    
      public void init() {
        messagesLabel.setOpaque(true);
        messagesLabel.setHorizontalAlignment(SwingConstants.CENTER);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(messagesLabel, BorderLayout.NORTH);
        getContentPane().add(resetBtn, BorderLayout.SOUTH);
        getContentPane().add(displayPanel, BorderLayout.CENTER);
    
        resetBtn.addActionListener(this);
    
        for (int i = 0; i < 9; i++) {
          bb[i] = new TTTBtn(i);
          bb[i].addActionListener(this);
          displayPanel.add(bb[i]);
        }
    
      }
      public int getWinner() {
        for (int i=0; i<winLine.length; i++) {
          int ret = lineWin(winLine[i]);
          if (ret > 0) return ret;
        }
        return -1;
      }
      private int lineWin(int [] pos) {
        int sum=
            bb[pos[0]].getValue()+
            bb[pos[1]].getValue()+
            bb[pos[2]].getValue();
        if (sum==3) return 1;
        if (sum==12) return 2;
        return -1;
      }
      public void actionPerformed(ActionEvent e) {
        if (e.getSource() == resetBtn) {
          resetGame();
        }
        else if (e.getSource()instanceof TTTBtn) {
          TTTBtn btn = (TTTBtn) e.getSource();
          if (!btn.isHit()) {
            if (haveWinner(btn)) {
              enableButtons(false);
            }
          }
        }
      }
    
      private void enableButtons(boolean enabled) {
        for (int i=0; i<bb.length; i++) {
          bb[i].setEnabled(enabled);
        }
      }
    
      private boolean haveWinner(TTTBtn btn) {
        bb[btn.getButtonNo()].setHit(player1);
        int winner = getWinner();
        if (winner > 0) {
          messagesLabel.setBackground(Color.green);
          messagesLabel.setText("Player " + winner + " wins");
          return true;
        }
        else {
          player1 = !player1;
          return false;
        }
      }
    
      private void resetGame() {
        for (int i=0; i<bb.length; i++) {
          bb[i].reset();
        }
        player1=true;
        messagesLabel.setBackground(Color.lightGray);
        messagesLabel.setText("X goes first");
        enableButtons(true);
      }
      /**
       * Test driver main
       */
      public static void main(String[] args) {
        JFrame f=new JFrame("Tic Tac Toe");
        f.getContentPane().setLayout(new GridLayout());
        TicTacToe ttt=new TicTacToe();
        f.getContentPane().add(ttt);
        f.addWindowListener(new WindowAdapter() {
          public void windowClosed(WindowEvent e) {
            System.exit(0);
          }
        });
        ttt.init();
        f.setBounds(100,100,300,270);
        f.setVisible(true);
      }
    }
    Thx man, but i want to use simpliest codes like these ones...What you wrote fot me is just to hard ...I'm a begginer...

    import java.awt.*;
    import hsa.Console;

    public class MatrixMulty
    {
    static Console c; // The output console

    public static void main (String[] args)
    {
    c = new Console ();


    //Inputs
    int[] [] m1 = new int [3] [3];
    int[] [] m2 = new int [3] [3];
    int[] [] m3 = new int [3] [3];


    //Inputs Matrix A
    for (int row = 0 ; row < 3 ; row++)
    {
    for (int col = 0 ; col < 3 ; col++)
    {

    c.println ("Please enter your numbers for Matrix A");
    m1 [row] [col] = c.readInt ();

    }
    }
    c.println ("");
    c.println ("");

    //Inputs Matrix B
    for (int row = 0 ; row < 3 ; row++)
    {
    for (int col = 0 ; col < 3 ; col++)
    {

    c.println ("Please enter your numbers for Matrix B");
    m2 [row] [col] = c.readInt ();

    }
    }
    c.println ("");
    c.println ("");

    //Menu
    while (true)
    {
    int choice;
    c.println ("Enter 1 for Adding");
    c.println ("Enter 2 for Subtraction");
    c.println ("Enter 3 for Multiplication");
    c.println ("Enter 4 EXIT");
    choice = c.readInt ();


    //Adding
    if (choice == 1)
    {
    c.println ("Adding");
    for (int a = 0 ; a < 3 ; a++)
    {
    for (int b = 0 ; b < 3 ; b++)
    {
    m3 [a] [b] = m1 [a] [b] + m2 [a] [b];

    }
    }
    c.println (m3 [0] [0] + " " + m3 [0] [1] + " " + m3 [0] [2] + " ");
    c.println (m3 [1] [0] + " " + m3 [1] [1] + " " + m3 [1] [2] + " ");
    c.println (m3 [2] [0] + " " + m3 [2] [1] + " " + m3 [2] [2] + " ");

    c.println ("");
    c.println ("");

    }

    //Subtraction
    else if (choice == 2)
    {
    c.println ("Subtraction");
    for (int a = 0 ; a < 3 ; a++)
    {
    for (int b = 0 ; b < 3 ; b++)
    {
    m3 [a] [b] = m1 [a] [b] - m2 [a] [b];

    }
    }
    c.println (m3 [0] [0] + " " + m3 [0] [1] + " " + m3 [0] [2] + " ");
    c.println (m3 [1] [0] + " " + m3 [1] [1] + " " + m3 [1] [2] + " ");
    c.println (m3 [2] [0] + " " + m3 [2] [1] + " " + m3 [2] [2] + " ");

    c.println ("");
    c.println ("");
    }

    //Multiplication
    else if (choice == 3)
    {
    c.println ("Multiplication");
    for (int a = 0 ; a < 3 ; a++)
    {
    for (int b = 0 ; b < 3 ; b++)
    {
    int sum = 0;
    for (int i = 0 ; i < 3 ; i++)
    {
    sum += m1 [a] [i] * m2 [i] [b];

    }
    m3 [a] [b] = sum;
    }
    }

    c.println (m3 [0] [0] + " " + m3 [0] [1] + " " + m3 [0] [2] + " ");
    c.println (m3 [1] [0] + " " + m3 [1] [1] + " " + m3 [1] [2] + " ");
    c.println (m3 [2] [0] + " " + m3 [2] [1] + " " + m3 [2] [2] + " ");

    c.println ("");
    c.println ("");

    //EXIT
    if (choice == 4)
    {

    System.exit (4);
    }

  7. #7
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Well, if you want to do this without a GUI then I don't think the code will be any simpler (plus the game will suck).
    eschew obfuscation

  8. #8
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    Here's what you want in an application (don't know why you want an application though...)
    Code:
    import javax.swing.JOptionPane;
    
    public class TicTacToe {
        static final String PLAYER1 = "X";
        static final String PLAYER2 = "O";
        static final String EMPTY = "-";
        
        static String[][] board = new String[3][3];
        
        static int turn = 0;
        
        static public void init() {    
            for (int x = 0; x < 3; x++) {
                for (int y = 0; y < 3; y++) {
                    board[x][y] = new String(EMPTY);
                }
            }
        }
        
        static public void getMove(int row, int col) {
            if (board[row][col].equals(EMPTY)) {
                board[row][col] = (turn % 2 == 0 ? PLAYER1 : PLAYER2);
                turn++;
            }
        }
        
        static public void printBoard() {
            for (int x = 0; x < 3; x++) {
                for (int y = 0; y < 3; y++) {
                    System.out.print(board[x][y]);
                }
                System.out.println();
            }
            System.out.println();
        }
        
        static public String winner() {
            for (int i = 0; i < board.length; i++) {
                /** check horizontally */
                if (board[i][0].equals(board[i][1]) &&
                    board[i][0].equals(board[i][2])) {
                    if (!board[i][0].equals(EMPTY)) {
                        return board[i][0];
                    }
                }
                /** check vertically */
                if (board[0][i].equals(board[1][i]) &&
                    board[0][i].equals(board[2][i])) {
                    if (!board[0][i].equals(EMPTY)) {
                        return board[0][i];
                    }
                }
            }
            
            /** check diagonally */
            if (board[0][0].equals(board[1][1]) &&
                board[0][0].equals(board[2][2])) {
                if (!board[0][0].equals(EMPTY)) {
                    return board[0][0];
                }
            }
            if (board[0][2].equals(board[1][1]) &&
                board[0][2].equals(board[2][0])) {
                if (!board[0][2].equals(EMPTY)) {
                    return board[0][2];
                }
            }
            return EMPTY;
        }
        
        static public void main(String[] args) {
            init();
            
            System.out.println("Welcome to Tic-Tac-Toe.");
            
            do {
                int row = Integer.parseInt(JOptionPane.showInputDialog(
                    "Enter the row you wish to move in."));
                int column = Integer.parseInt(JOptionPane.showInputDialog(
                    "Enter the column you wish to move in."));
                getMove(row, column);
                printBoard();
            } while(winner().equals(EMPTY));
            
            System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!");
        }
    }

  9. #9
    Join Date
    Jan 2006
    Posts
    9
    Destin. Thank You man. Thats i really what i was looking for! But some parts i dont get though...
    1)Can you explain briefly each Static Public, what it does ( i get it but i want to make sure )
    2)System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!"); Dont get the calculations inside the brackets)
    3) If its not hard for you, state all methods that you have used

    I would really appreciate your support for a newb like me

  10. #10
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    1. Can you explain briefly each Static Public, what it does
    public makes it so other classes can access the methods
    static is a bit harder to explain, but everything in the wrapper class needs to be static.

    Useful links:
    The Java(tm) Tutorial: Controlling Access to Members of a Class
    Java Glossary: public
    Java Glossary: static

    2.System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!"); Dont get the calculations inside the brackets)
    Yeah, it's ugly. Basically, the turn was just incremented, so we're one over. So we need to subtract 1. Then, % 2 will give us the remainder (0 if player 1 wins, 1 if player 2 wins) then, we need to add 1 so it will be 1 or 2 instead of 0 or 1.

    3. If its not hard for you, state all methods that you have used
    ??
    Last edited by destin; 01-19-2006 at 06:59 PM.

  11. #11
    Join Date
    Jan 2006
    Posts
    9
    Thank you again, but what if the game is a Tie? This script doesn't have a Tie
    I am sorry fot these stupid questions, but i really want to understand the prog..i have a Q if you dont mind answering them..

    1) What "static int turn = 0;" stand for??

  12. #12
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    @Thank you again, but what if the game is a Tie? This script doesn't have a Tie
    So add it.

    @What "static int turn = 0;" stand for??
    It represents whose turn it is (ie. player1 or player2)

    @I am sorry fot these stupid questions, but i really want to understand the prog..i have a Q if you dont mind answering them..
    If you have a question, ask it. That's what this forum is for.

  13. #13
    Join Date
    Jan 2006
    Posts
    9
    How do write a Tie script to this prog?

    Thank You Destin

  14. #14
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    Have you even thought about it yet? It's really not that hard. I've written the whole thing for you so far. At least post what you have tried.

  15. #15
    Join Date
    Jan 2006
    Posts
    9
    May be its something like this, but i think its not right...

    static public String tie ()
    {
    for (int i = 0 ; i < board.length ; i++)
    {
    /** check horizontally */
    if (board [i] [0] != (board [i] [1]) &&
    board [i] [0] != (board [i] [2]))
    {
    if (!board [i] [0] != (EMPTY))
    {
    return board [i] [0];
    }
    }
    /** check vertically */
    if (board [0] [i] != (board [1] [i]) &&
    board [0] [i] != (board [2] [i]))
    {
    if (!board [0] [i] != (EMPTY))
    {
    return board [0] [i];
    }
    }
    }

    /** check diagonally */
    if (board [0] [0] != (board [1] [1]) &&
    board [0] [0] != (board [2] [2]))
    {
    if (!board [0] [0] != (EMPTY))
    {
    return board [0] [0];
    }
    }
    if (board [0] [2] != (board [1] [1]) &&
    board [0] [2] != (board [2] [0]))
    {
    if (!board [0] [2] != (EMPTY))
    {
    return board [0] [2];
    }
    }
    return EMPTY;
    }
    I think they should not be equal in order to get a Tie...Check if im on the right track if not, may be i need a hint...

    Thank You!

Similar Threads

  1. Tic Tac Toe
    By shadow in forum Java
    Replies: 3
    Last Post: 11-14-2005, 11:21 PM
  2. Simple tic tac toe applet
    By Ant_Magma in forum Java
    Replies: 5
    Last Post: 09-26-2005, 04:41 AM
  3. Replies: 1
    Last Post: 08-20-2001, 08:17 AM
  4. Replies: 1
    Last Post: 02-10-2001, 01:20 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center