Help with printing a tic tac toe board (using a loop to print)

hey im making the smiple game tic tac toe and im tryin to print out the board after each turn. I have a 2d array called char which is a 3 by 3 array and i dont know how i would make a for loop to print out the x's and o's in their right spot and still have the board look like a normal tic tac toe board. When the board is printing the x's and o's are already in the 2d char array board.So basically what i want to happen is after player 1's turn is up wherever he put the x replace the number on the board with an x and keep the rest the same and whenever player 2's turn is up wherever he put the o replace the number on the board with an o and keep the rest the same. Any help would be awesome thanks alot.
Here is the code to the program (i know i use if statements to much its a bad habit of mine)
import java.util.*;
public class Tictactoe
    private char board [] [] = new board [3] [3];
    private int X;
    private int O;
    private Scanner p1choice;
    private Scanner p2choice;
    Scanner input = new Scanner(System.in);
    public Tictactoe()
        p1choice = new Scanner(System.in);
        p2choice = new Scanner(System.in);
        play();
    public void play()
        printoriginalboard();
    public void printoriginalboard()
        System.out.println("    |    |    ");  
        System.out.println("  3 |  2 |  1 ");
        System.out.println("____|____|____");
        System.out.println("    |    |    ");
        System.out.println("  6 |  5 |  4 ");
        System.out.println("    |    |    ");
        System.out.println("____|____|____");
        System.out.println("    |    |    ");
        System.out.println("  9 |  8 |  7 ");
        System.out.println("    |    |    ");
        System.out.println("This is the classic game of tictactoe simply pick a number 1 through 9 to place an x or an o in that area.");
        player1turn();
    public void player1turn()
        System.out.println("Player 1 pick an area to place an X");
        int p1choice= p1choice.nextInt();
        if(p1choice == 1 && p2choice == 1 || p1choice == 1){
            System.out.println("This spot has already been taken");
            else
            board[0][2] = 'x';
        pintboard();
        if(p1choice == 2 && p2choice == 2 || p1choice == 2){
        System.out.println("This spot has already been taken");
        else
            board[1][2] = 'x';
        pintboard();
        if(p1choice == 3 && p2choice == 3 || p1choice == 3){
        System.out.println("This spot has already been taken");
        else
            board[2][2] = 'x';
        pintboard();
        if(p1choice == 4 && p2choice == 4 || p1choice == 4){
        System.out.println("This spot has already been taken");
            board[0][1] = 'x';
        pintboard();
        if(p1choice == 5 && p2choice == 5 || p1choice == 5){
        System.out.println("This spot has already been taken");
        else
            board[1][1] = 'x';
        pintboard();
        if(p1choice == 6 && p2choice == 6 || p1choice == 6){
        System.out.println("This spot has already been taken");
        else
            board[2][1] = 'x';
        pintboard();
        if(p1choice == 7 && p2choice == 7 || p1choice == 7){
        System.out.println("This spot has already been taken");
        else
            board[0][0] = 'x';
        pintboard();
        if(p1choice ==8 && p2choice == 8 || p1choice == 8){
        System.out.println("This spot has already been taken");
        else
            board[1][0] = 'x';
        pintboard();
        if(p1choice == 9 && p2choice == 9 || p1choice == 9){
        System.out.println("This spot has already been taken");
        else
            board[2][0] = 'x';
        pintboard();
    public void p2turn()
        System.out.println("Pick an area to place an O");
        int p2choice = p2choice.nextInt();
        if(p2choice == 1 && p1choice == 1 || p2choice == 1){
        System.out.println("This spot has already been taken");
        else
            board[0][2] = 'o';
        pintboard();
        if(p2choice == 2 && p1choice == 2 || p2choice == 2){
        System.out.println("This spot has already been taken");
        else
            board[1][2] = 'o';
        pintboard();
        if(p2choice == 3 && p1choice == 3 || p2choice == 3){
        System.out.println("This spot has already been taken");
        else
            board[2][2] = 'o';
        pintboard();
        if(p2choice == 4 && p1choice == 4 || p2choice == 4){
        System.out.println("This spot has already been taken");
        else
            board[0][1] = 'o';
        pintboard();
        if(p2choice == 5 && p1choice == 5 || p2choice == 5){
        System.out.println("This spot has already been taken");
        else
            board[1][1] = 'o';
        pintboard();
        if(p2choice == 6 && p1choice == 6 || p2choice == 6){
        System.out.println("This spot has already been taken");
        else
            board[2][1] = 'o';
        pintboard();
        if(p2choice == 7 && p1choice == 7 || p2choice == 7){
        System.out.println("This spot has already been taken");
        else
            board[0][0] = 'o';
        pintboard();
        if(p2choice == 8 && p1choice == 8 || p2choice == 8){
        System.out.println("This spot has already been taken");
        else
            board[1][0] = 'o';
        pintboard();
        if(p2choice == 9 && p1choice == 9 || p2choice == 9){
        System.out.println("This spot has already been taken");
        else
            board[2][0] = 'o';
        pintboard();
    public void pintboard()
    {

Anyway the answer is that you are trying to create an array of char as there is no such thing as a board[3][3].
One of the best tools a programmer can do is learn how to break a big problem into little problems and work on each little problem in isolation, and then when finished combining the solutions together into the final program. You big mistake that I see here is trying to bite off more than you can chew: trying to create a whole functioning interactive program from just one class. Why give yourself a task that would be difficult even for an experienced java programmer? I suggest that you break this down into logical parts and try to solve the smaller problems before worrying about the whole. For instance, if I were doing something like this, I'd create a class called TTTBoard that encapsulated the tic tac toe board and nothing but the board. I'd think of it as an entity. When I wanted the current state of the board, I'd query the board via a method such as getCurrentState. I'd have methods for checking if position is free, for placing an x/o in a spot, for checking for win, etc... Then I'd create a user interface class where I'd give the users a choice and get their responses. I'd probably create a Game class to control it all. While this all seems daunting, you are trying to do essentially the same thing, but all in one huge class. My recommendation: study OOPs and learn to do it the smart way. Good luck.

Similar Messages

  • Help in swing app. tic tac toe

    Trying to make this tic tac toe game. Need a little help. I want the newGameBUT to start the game over, and I would like turnTF to display if a tie occurs. (I tried using *if button.enabled(false) {* but it didn't work. If anyone could help me out, that'd be great. Oh, also, the new game button currently add's 1 to whoever won so far, which is really weird =x. Thanks beforehand.
    import java.awt.*; //import
    import javax.swing.*; //import
    import java.awt.event.*; //import
    import java.awt.Rectangle; //import
    import java.awt.Font; //import
    import javax.swing.BorderFactory; //import
    import javax.swing.border.TitledBorder; //import
    import java.awt.Color; //import
    public class TicTacToeFrame extends JFrame implements ActionListener {
        public TicTacToeFrame() {
            try { //try the following
                jbInit();
            } catch (Exception ex) { // exit on [X]
                ex.printStackTrace(); //exit and print errors
        int xWon = 0; //counting how many times O has won
        int oWon = 0; //counting how many times X has one
        double i = 0; // loop variable to determine turn
        public void actionPerformed(ActionEvent e) {
            String turn = "null"; //current turn
            String notTurn = "null"; //not current turn
            newGameBUT.setEnabled(false); //disable new game button
            if (i % 2 == 0) { // for determining who's turn it is
                turn = "X"; // X's turn when counter is even
                notTurn = "O"; //notTurn used to show who's turn it is in turnTF
            if (i % 2 != 0) { // for determining who's turn it is
                turn = "O"; // O's turn when counter is odd
                notTurn = "X"; //notTurn used to show who's turn it is in turnTF
            turnTF.setText("Currently " + notTurn + "'s turn"); // displays turn
            if (e.getSource() == sqOneBUT) { //disable and print X or O to button
                sqOneBUT.setText(turn); //printing players symbol
                sqOneBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqTwoBUT) { //disable and print X or O to button
                sqTwoBUT.setText(turn); //printing players symbol
                sqTwoBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqThreeBUT) { //disable and print X or O to button
                sqThreeBUT.setText(turn); //printing players symbol
                sqThreeBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFourBUT) { //disable and print X or O to button
                sqFourBUT.setText(turn); //printing players symbol
                sqFourBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFiveBUT) { //disable and print X or O to button
                sqFiveBUT.setText(turn); //printing players symbol
                sqFiveBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSixBUT) { //disable and print X or O to button
                sqSixBUT.setText(turn); //printing players symbol
                sqSixBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSevenBUT) { //disable and print X or O to button
                sqSevenBUT.setText(turn); //printing players symbol
                sqSevenBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqEightBUT) { //disable and print X or O to button
                sqEightBUT.setText(turn); //printing players symbol
                sqEightBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqNineBUT) { //disable and print X or O to button
                sqNineBUT.setText(turn); //printing players symbol
                sqNineBUT.setEnabled(false); //disabling button
            String sqOne = sqOneBUT.getText(); // Strings to read to find winner
            String sqTwo = sqTwoBUT.getText(); // Strings to read to find winner
            String sqThree = sqThreeBUT.getText(); // Strings to read to find winner
            String sqFour = sqFourBUT.getText(); // Strings to read to find winner
            String sqFive = sqFiveBUT.getText(); // Strings to read to find winner
            String sqSix = sqSixBUT.getText(); // Strings to read to find winner
            String sqSeven = sqSevenBUT.getText(); // Strings to read to find winner
            String sqEight = sqEightBUT.getText(); // Strings to read to find winner
            String sqNine = sqNineBUT.getText(); // Strings to read to find winner
             OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O WINS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
             OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
    //horizontal, top, o wins
            if (sqOne == "O") { //checking too see if player O has won
                if (sqFour == "O") {
                    if (sqSeven == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    //vertical, left, o wins
            if (sqOne == "O") { //checking too see if player O has won
                if (sqTwo == "O") {
                    if (sqThree == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // diagonal, top left to bottom right, o wins
            if (sqOne == "O") {
                if (sqFive == "O") { //checking too see if player O has won
                    if (sqNine == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, mid, o wins
            if (sqTwo == "O") { //checking too see if player O has won
                if (sqFive == "O") {
                    if (sqEight == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, bottom, o wins
            if (sqThree == "O") { //checking too see if player O has won
                if (sqSix == "O") {
                    if (sqNine == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // diagonal, top right to bottom left, o wins
            if (sqThree == "O") { //checking too see if player O has won
                if (sqFive == "O") {
                    if (sqSeven == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
             XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
             $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~X WINS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
             XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    //horizontal, top, x wins
            if (sqOne == "X") { //checking too see if player X has won
                if (sqFour == "X") {
                    if (sqSeven == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    //vertical, left, x wins
            if (sqOne == "X") { //checking too see if player X has won
                if (sqTwo == "X") {
                    if (sqThree == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // diagonal, top left to bottom right, x wins
            if (sqOne == "X") { //checking too see if player X has won
                if (sqFive == "X") {
                    if (sqNine == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, mid, x wins
            if (sqTwo == "X") { //checking too see if player X has won
                if (sqFive == "X") {
                    if (sqEight == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, bottom, x wins
            if (sqThree == "X") { //checking too see if player X has won
                if (sqSix == "X") {
                    if (sqNine == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
            // diagonal, top right to bottom left, x wins
            if (sqThree == "X") { //checking too see if player X has won
                if (sqFive == "X") {
                    if (sqSeven == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
            String wins = turnTF.getText(); //Reading who won to print win winTF
            if (wins.equals("X wins!")) { //if X wins
                xWon++; //adding 1 to X's amount of wins
                String xWonString = Integer.toString(xWon); //converting to String
                xWinsTF.setText(xWonString); //displaying # of wins
                newGameBUT.setEnabled(true); //enable new game button
            if (wins.equals("O wins!")) { //if O wins
                oWon++; //adding 1 to O's amount of wins
                String oWonString = Integer.toString(oWon); //converting to String
                oWinsTF.setText(oWonString); //displaying # of wins
                newGameBUT.setEnabled(true); //enable new game button
            if (e.getSource() == newGameBUT) {
            i++; // turn switch
        /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        private void jbInit() throws Exception {
            this.getContentPane().setLayout(null);
            this.getContentPane().setBackground(Color.darkGray);
            sqTwoBUT.setBounds(new Rectangle(2, 116, 115, 115));
            sqTwoBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqFourBUT.setBounds(new Rectangle(118, 1, 115, 115));
            sqFourBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqFiveBUT.setBounds(new Rectangle(118, 116, 115, 115));
            sqFiveBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqSixBUT.setBounds(new Rectangle(118, 232, 115, 115));
            sqSixBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqOneBUT.setBounds(new Rectangle(2, 1, 115, 115));
            sqOneBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqEightBUT.setBounds(new Rectangle(233, 116, 115, 115));
            sqEightBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqNineBUT.setBounds(new Rectangle(233, 232, 115, 115));
            sqNineBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqSevenBUT.setBounds(new Rectangle(233, 1, 115, 115));
            sqSevenBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqOneBUT.addActionListener(this);
            sqTwoBUT.addActionListener(this);
            sqThreeBUT.addActionListener(this);
            sqFourBUT.addActionListener(this);
            sqFiveBUT.addActionListener(this);
            sqSixBUT.addActionListener(this);
            sqSevenBUT.addActionListener(this);
            sqEightBUT.addActionListener(this);
            sqNineBUT.addActionListener(this);
            newGameBUT.addActionListener(this);
            sqThreeBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            turnTF.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            turnTF.setEditable(false);
            turnTF.setText("X goes first");
            turnTF.setHorizontalAlignment(SwingConstants.CENTER);
            turnTF.setBounds(new Rectangle(2, 346, 346, 35));
            oWinsTF.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                              Font.BOLD, 18));
            oWinsTF.setEditable(false);
            oWinsTF.setHorizontalAlignment(SwingConstants.CENTER);
            oWinsTF.setBounds(new Rectangle(256, 419, 79, 59));
            xWinsTF.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                              Font.BOLD, 18));
            xWinsTF.setEditable(false);
            xWinsTF.setHorizontalAlignment(SwingConstants.CENTER);
            xWinsTF.setBounds(new Rectangle(12, 419, 79, 59));
            oWinsLBL.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                               Font.PLAIN, 16));
            oWinsLBL.setForeground(Color.white);
            oWinsLBL.setHorizontalAlignment(SwingConstants.CENTER);
            oWinsLBL.setText("O wins:");
            oWinsLBL.setBounds(new Rectangle(256, 399, 78, 21));
            xWinsLBL.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                               Font.PLAIN, 16));
            xWinsLBL.setForeground(Color.white);
            xWinsLBL.setDisplayedMnemonic('0');
            xWinsLBL.setHorizontalAlignment(SwingConstants.CENTER);
            xWinsLBL.setText("X wins:");
            xWinsLBL.setBounds(new Rectangle(12, 393, 78, 21));
            newGameBUT.setBounds(new Rectangle(101, 455, 146, 23));
            newGameBUT.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                                 Font.BOLD, 14));
            newGameBUT.setText("New Game");
            this.getContentPane().add(sqFourBUT);
            this.getContentPane().add(sqThreeBUT);
            this.getContentPane().add(sqTwoBUT);
            this.getContentPane().add(sqOneBUT);
            this.getContentPane().add(sqFiveBUT);
            this.getContentPane().add(sqSixBUT);
            this.getContentPane().add(sqNineBUT);
            this.getContentPane().add(sqEightBUT);
            this.getContentPane().add(sqSevenBUT);
            this.getContentPane().add(turnTF);
            this.getContentPane().add(xWinsLBL);
            this.getContentPane().add(xWinsTF);
            this.getContentPane().add(oWinsLBL);
            this.getContentPane().add(oWinsTF);
            this.getContentPane().add(newGameBUT);
            sqThreeBUT.setBounds(new Rectangle(2, 232, 115, 115));
        JButton sqTwoBUT = new JButton();
        JButton sqThreeBUT = new JButton();
        JButton sqFourBUT = new JButton();
        JButton sqFiveBUT = new JButton();
        JButton sqSixBUT = new JButton();
        JButton sqOneBUT = new JButton();
        JButton sqEightBUT = new JButton();
        JButton sqNineBUT = new JButton();
        JButton sqSevenBUT = new JButton();
        JTextField turnTF = new JTextField();
        JTextField oWinsTF = new JTextField();
        JTextField xWinsTF = new JTextField();
        JLabel oWinsLBL = new JLabel();
        JLabel xWinsLBL = new JLabel();
        JButton newGameBUT = new JButton();
    }

    This code should be the poster-child for every time we tell someone that repeated code can usually be replaced with collections or method calls.
            if (e.getSource() == sqOneBUT) { //disable and print X or O to button
                sqOneBUT.setText(turn); //printing players symbol
                sqOneBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqTwoBUT) { //disable and print X or O to button
                sqTwoBUT.setText(turn); //printing players symbol
                sqTwoBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqThreeBUT) { //disable and print X or O to button
                sqThreeBUT.setText(turn); //printing players symbol
                sqThreeBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFourBUT) { //disable and print X or O to button
                sqFourBUT.setText(turn); //printing players symbol
                sqFourBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFiveBUT) { //disable and print X or O to button
                sqFiveBUT.setText(turn); //printing players symbol
                sqFiveBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSixBUT) { //disable and print X or O to button
                sqSixBUT.setText(turn); //printing players symbol
                sqSixBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSevenBUT) { //disable and print X or O to button
                sqSevenBUT.setText(turn); //printing players symbol
                sqSevenBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqEightBUT) { //disable and print X or O to button
                sqEightBUT.setText(turn); //printing players symbol
                sqEightBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqNineBUT) { //disable and print X or O to button
                sqNineBUT.setText(turn); //printing players symbol
                sqNineBUT.setEnabled(false); //disabling button
            String sqOne = sqOneBUT.getText(); // Strings to read to find winner
            String sqTwo = sqTwoBUT.getText(); // Strings to read to find winner
            String sqThree = sqThreeBUT.getText(); // Strings to read to find winner
            String sqFour = sqFourBUT.getText(); // Strings to read to find winner
            String sqFive = sqFiveBUT.getText(); // Strings to read to find winner
            String sqSix = sqSixBUT.getText(); // Strings to read to find winner
            String sqSeven = sqSevenBUT.getText(); // Strings to read to find winner
            String sqEight = sqEightBUT.getText(); // Strings to read to find winner
            String sqNine = sqNineBUT.getText(); // Strings to read to find winner

  • Tic Tac Toe game using Graphs

    Does anyone know of an open-source implementation of Tic-Tac-Toe using Graphs? I'm reading through Michael Mann's Data Structures and Other Objects Using Java book and in chapter 14, he briefly mentions the use of directed graphs in implementing a game of Tic Tac Toe. I'm interested in seeing how one would implement something of this sort (and no, it's not a homework assignment).
    If someone would be kind enough as to post a link to a site that offers mini-java applications, along with code that novice developers such as myself can traverse, please do so.
    Thanks in advance.

    As an added though, there's really no need to for each node to keep track of incoming connections, only outgoing ones. What I, personally would do is keep an array of 8 outgoing connections, one for each direction. If no connection was there, then that element in the array would be null. If a connection was there, then that element would be an edge connecting to another node, or the other node itself (depending on whether or not you explicitly implemented 'edges' in your graph).
    That way, you could do something like:
        Node    s         = getOneOfTheEdgeNodes();
        boolean hasWinner = false;    
        try {
            for (int i = 0; i < 8; i ++) {
                if (s.getOutgoing(i).getNode().getOutgoing(i).getNode() != null) {
                    hasWinner = true;
                    break;
        } catch (NullPointerException npx) {
            // No winner.
        if (hasWinner)
            System.out.println(s.getPlayer() + " has won");Yeah, that's a shitty example, but hopefully you get my drift.
    Jason

  • Networked Tic Tac Toe

    I need help with making my Tic Tac Toe game networked. Is there an easy
    way to pass two ints over through a network. Heres my Code so far. I
    already have a working Tic Tac Toe. Just wanted to add Network
    Capability.
    Heres my code:
    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Vector;
    import javax.swing.*;
    * This class functions as the controller for my Tic Tac Toe game.
    * @author Zosden
    * Date Due: 2/22/2008
    * @version 1.0 (22 February 2008)
    * Input: playersFile.txt is a text file to hold players information.
    * String playerXName is a temp String for input of player x's name.
    * String playerOName is a temp String for input of player O's name.
    * Output: playersFile.txt
    public class GameController
        //  Properties   //
        private GameView myView;
        private GameModel myModel;
        private Player myPlayerX;
        private Player myPlayerO;
        private File playersFile;
        private FileReader fileReader;
        private BufferedReader bufReader;
        private FileOutputStream outFileStream;
        private PrintStream p;
        private boolean myPlayerXNewPlayer = true;
        private boolean myPlayerONewPlayer = true;
        private int myPlayerXPosition;
        private int myPlayerOPosition;
        private Vector myPlayerVector = new Vector(10);
        private ServerSocket serverSocket;
        private Socket clientSocket;
        private PrintWriter out;
        private String inputLine;
        private String outputLine;
        private boolean isClient;
        private BufferedReader in;
        private String fromServer;
         * Default controller constructor.
        public GameController(Player aPlayerX, Player aPlayerO, boolean isClient)
            myPlayerX = aPlayerX;
            myPlayerO = aPlayerO;
            this.isClient = isClient;
            this.readPlayers();
            myModel = new GameModel(this);
            myView = new GameView(this);
            if(isClient)
                this.setUpClient();
                this.waitForTurn(-1 , -1);
            else
                this.setUpServer();
        private void waitForTurn(int aRow, int aCol)
            if(isClient)
                if(!(aRow == -1 || aCol == -1))
                    out.println(aRow + " " + aCol + " ");
                    System.out.println("Made Move");
                while(true)
                    try
                        fromServer = in.readLine();
                    catch (IOException e)
                        e.printStackTrace();
                    if(fromServer != null)
                        int row = fromServer.indexOf(" ");
                        int col = fromServer.indexOf(" ");
                        System.out.println(row + " " + col);
                        myModel.move(row, col);
                        break;
            else
                out.println(aRow + " " + aCol + " ");
                while(true)
                    try
                        fromServer = in.readLine();
                    catch (IOException e)
                        e.printStackTrace();
                    int row = fromServer.indexOf(" ");
                    int col = fromServer.indexOf(" ");
                    System.out.println(row + " " + col);
                    myModel.move(row, col);
                    break;
        private void setUpServer()
            serverSocket = null;
            try
                serverSocket = new ServerSocket(4444);
            catch (IOException e)
                System.err.println("Could not listen on port: 4444.");
                System.exit(1);
            clientSocket = null;
            try
                clientSocket = serverSocket.accept();
            catch (IOException e)
                System.err.println("Accept failed.");
                System.exit(1);
            try
                out = new PrintWriter(clientSocket.getOutputStream(), true);
            catch (IOException e)
                e.printStackTrace();
        private void setUpClient()
            try
                clientSocket = new Socket(myPlayerO.getName(), 4444);
                out = new PrintWriter(clientSocket.getOutputStream(), true);   
            catch (UnknownHostException e)
                System.err.println("Don't know about host.");
                System.exit(1);
            catch (IOException e)
                System.err.println("Couldn't get I/O for the connection to.");
                System.exit(1);
         * Tells the model that something has been selected then
         * passes the row and col of the event.
         * pre:  a valid view, model and controller have been designated
         * post: sends aRow and aCol to move in the model class.
         * @param aRow
         * @param aCol
        public void choiceMade(Integer aRow, Integer aCol)
            myModel.move(aRow, aCol);
            this.waitForTurn(aRow, aCol);
        public void changePlayersName()
            this.writePlayers();
            myPlayerVector.clear();
            String playerXName = JOptionPane.showInputDialog(
            "Please enter player X's name.");
            String playerOName = JOptionPane.showInputDialog(
            "Please enter player O's name.");
            this.setPlayerXName(playerXName);
            this.setPlayerOName(playerOName);
            this.readPlayers();
            myView.changeNames();
            myView.setWins();
        public void changeMusic()
            myView.displayDialog();
        public void pauseMusic()
            myModel.pauseMusic();  
        public void startMusic()
            myModel.startMusic();  
        public void quitGame()
            this.writePlayers();
            System.exit(0);
         * Increments the number of wins a certain player has,
         * which is determined by the argument.
         * @param aPlayerType
        public void changeImage(int aRow, int aCol, int aPlayerType)
            myView.setMyImagePieces(aRow, aCol, aPlayerType);
        public void updateScore()
            myView.setWins();
        public void changeMessage(String aString)
            myView.changeMyMessage(aString);
         * This method writes the players name and wins into a text file in
         * order to save that information
         * <pre>
         * pre: The myPlayerX and myPlayerO must be initiated.
         * The text file "playersFile.txt"
         * must exist and be written correctly. If it isn't just
         * delete all info in it and
         * start anew.
         * post: This method will rewrite the entire text file
         * with all the players names.
         * </pre>
        public void writePlayers()
            if(!myPlayerXNewPlayer)
                myPlayerVector.remove(myPlayerXPosition + 1);
                myPlayerVector.insertElementAt(getPlayerXWins(),
                        myPlayerXPosition + 1);
            else
                myPlayerVector.add(getPlayerXName());
                myPlayerVector.add(getPlayerXWins());
            if(!myPlayerONewPlayer)
                myPlayerVector.remove(myPlayerOPosition + 1);
                myPlayerVector.insertElementAt(getPlayerOWins(),
                        myPlayerOPosition + 1);
            else
                myPlayerVector.add(getPlayerOName());
                myPlayerVector.add(getPlayerOWins());
                try
                    outFileStream = new FileOutputStream(playersFile);
                    p = new PrintStream(outFileStream);
                catch (IOException e)
                    e.printStackTrace();
            for(int i = 0; i < myPlayerVector.size(); i++)
                p.println(myPlayerVector.elementAt(i));
            p.close();
         * This method reads the players name and wins in a text file in
         * order to find out their information
         * <pre>
         * pre: The myPlayerX and myPlayerO must be initiated.
         * The text file "playersFile.txt"
         * must exist and be written correctly. If it isn't just
         * delete all info in it and
         * start anew.
         * post: This method will read the entire text file
         * with all the players names.
         * </pre>
        public void readPlayers()
            String tempName = null;
            int tempPosition = 0;
            int tempWins = 0;
            playersFile = new File("playersText.txt");
            try
                fileReader = new FileReader(playersFile);
                bufReader = new BufferedReader(fileReader);
                catch (FileNotFoundException e)
                    e.printStackTrace();
            while(true)
                tempName = null;
                try
                    tempName = bufReader.readLine();
                    if(tempName == null)
                        break;
                    myPlayerVector.insertElementAt(tempName, tempPosition);
                    if(getPlayerXName().equalsIgnoreCase(tempName))
                        myPlayerXPosition = tempPosition;
                    if(getPlayerOName().equalsIgnoreCase(tempName))
                        myPlayerOPosition = tempPosition;
                    tempPosition++;
                    try
                        tempWins = Integer.parseInt(bufReader.readLine());
                    catch(NumberFormatException e)
                        e.printStackTrace();
                    myPlayerVector.insertElementAt(tempWins, tempPosition);
                    tempPosition++;
                catch (IOException e)
                    e.printStackTrace();
                if(getPlayerXName().equalsIgnoreCase(tempName))
                    setPlayerXWins(tempWins);
                    myPlayerXNewPlayer = false;
                if(getPlayerOName().equalsIgnoreCase(tempName))
                    setPlayerOWins(tempWins);
                    myPlayerONewPlayer = false;
        public void incrementWin(int aPlayerType)
            if(aPlayerType == getPlayerOType())
                myPlayerO.incrementWins();
            if(aPlayerType == getPlayerXType())
                myPlayerX.incrementWins();
            updateScore();
        public void changePlayersNames()
            this.writePlayers();
            myPlayerVector.clear();
            String playerXName = JOptionPane.showInputDialog(
            "Please enter player X's name.");
            String playerOName = JOptionPane.showInputDialog(
            "Please enter player O's name.");
            this.setPlayerXName(playerXName);
            this.setPlayerOName(playerOName);
            this.readPlayers();
            myView.changeNames();
            myView.setWins();
        //   Accessor Methods     //
        public int getNumDraws()
            return myModel.getNumberDraws();
        public String getMessages()
            return myModel.getMessages();
        public void setMusic(Integer aSong)
            myModel.setMusic(aSong);
        public String getPlayerXName()
            return myPlayerX.getName();
        public String getPlayerOName()
            return myPlayerO.getName();
        public int getPlayerXWins()
            return myPlayerX.getNumWins();
        public int getPlayerOWins()
            return myPlayerO.getNumWins();
        public int getPlayerXType()
            return myPlayerX.getType();
        public int getPlayerOType()
            return myPlayerO.getType();
        public int getNoPlayerType()
            return myPlayerO.NO_PLAYER;
        private void setPlayerXWins(int aNumWins)
            myPlayerX.setNumWins(aNumWins);
        private void setPlayerOWins(int aNumWins)
            myPlayerO.setNumWins(aNumWins);
        private void setPlayerXName(String aName)
            myPlayerX.setName(aName);
        private void setPlayerOName(String aName)
            myPlayerO.setName(aName);
    }</div>{noformat}
    </div>

    I think I figured it out. I still have some work to do, but that part is easy. Heres the file in case anyone is interested.[TTT.Zip|http://www.mediafire.com/?wii1fn5wqom]
    If anyone knows of a better way to do this same thing please let me know

  • Help with Tic Tac Toe program....

    I am writing a tic tac toe program, and I have already put the 9 boxes onto the screen so that it looks like the Tic Tac Toe board.
    My first box looks something like this:
    Rectangle2D.Double box1 = new Rectangle2D.Double(0, 0, 100, 100);
    g2.draw(box1);
    I want assign a number to the 9 boxes so it looks like this:
    123
    456
    789
    And I want to know how am I suppose to assign a number to a box, so that when the number is pressed it will put an "X" or "O"(depending on whose turn it is).
    P.S. If you already made a Tic Tac Toe progaram can you post it so I will have an idea of what you did. thx.

    I'd hate to post the whole thing, but if you don't have access to it, here it goes:
    * @(#)TicTacToe.java     1.6 01/12/03
    * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
    * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.net.*;
    import java.applet.*;
    * A TicTacToe applet. A very simple, and mostly brain-dead
    * implementation of your favorite game! <p>
    * In this game a position is represented by a white and black
    * bitmask. A bit is set if a position is ocupied. There are
    * 9 squares so there are 1<<9 possible positions for each
    * side. An array of 1<<9 booleans is created, it marks
    * all the winning positions.
    * @version      1.2, 13 Oct 1995
    * @author Arthur van Hoff
    * @modified 04/23/96 Jim Hagen : winning sounds
    * @modified 02/10/98 Mike McCloskey : added destroy()
    public
    class TicTacToe extends Applet implements MouseListener {
         * White's current position. The computer is white.
        int white;
         * Black's current position. The user is black.
        int black;
         * The squares in order of importance...
        final static int moves[] = {4, 0, 2, 6, 8, 1, 3, 5, 7};
         * The winning positions.
        static boolean won[] = new boolean[1 << 9];
        static final int DONE = (1 << 9) - 1;
        static final int OK = 0;
        static final int WIN = 1;
        static final int LOSE = 2;
        static final int STALEMATE = 3;
         * Mark all positions with these bits set as winning.
        static void isWon(int pos) {
         for (int i = 0 ; i < DONE ; i++) {
             if ((i & pos) == pos) {
              won[i] = true;
         * Initialize all winning positions.
        static {
         isWon((1 << 0) | (1 << 1) | (1 << 2));
         isWon((1 << 3) | (1 << 4) | (1 << 5));
         isWon((1 << 6) | (1 << 7) | (1 << 8));
         isWon((1 << 0) | (1 << 3) | (1 << 6));
         isWon((1 << 1) | (1 << 4) | (1 << 7));
         isWon((1 << 2) | (1 << 5) | (1 << 8));
         isWon((1 << 0) | (1 << 4) | (1 << 8));
         isWon((1 << 2) | (1 << 4) | (1 << 6));
         * Compute the best move for white.
         * @return the square to take
        int bestMove(int white, int black) {
         int bestmove = -1;
          loop:
         for (int i = 0 ; i < 9 ; i++) {
             int mw = moves;
         if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) {
              int pw = white | (1 << mw);
              if (won[pw]) {
              // white wins, take it!
              return mw;
              for (int mb = 0 ; mb < 9 ; mb++) {
              if (((pw & (1 << mb)) == 0) && ((black & (1 << mb)) == 0)) {
                   int pb = black | (1 << mb);
                   if (won[pb]) {
                   // black wins, take another
                   continue loop;
              // Neither white nor black can win in one move, this will do.
              if (bestmove == -1) {
              bestmove = mw;
         if (bestmove != -1) {
         return bestmove;
         // No move is totally satisfactory, try the first one that is open
         for (int i = 0 ; i < 9 ; i++) {
         int mw = moves[i];
         if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) {
              return mw;
         // No more moves
         return -1;
    * User move.
    * @return true if legal
    boolean yourMove(int m) {
         if ((m < 0) || (m > 8)) {
         return false;
         if (((black | white) & (1 << m)) != 0) {
         return false;
         black |= 1 << m;
         return true;
    * Computer move.
    * @return true if legal
    boolean myMove() {
         if ((black | white) == DONE) {
         return false;
         int best = bestMove(white, black);
         white |= 1 << best;
         return true;
    * Figure what the status of the game is.
    int status() {
         if (won[white]) {
         return WIN;
         if (won[black]) {
         return LOSE;
         if ((black | white) == DONE) {
         return STALEMATE;
         return OK;
    * Who goes first in the next game?
    boolean first = true;
    * The image for white.
    Image notImage;
    * The image for black.
    Image crossImage;
    * Initialize the applet. Resize and load images.
    public void init() {
         notImage = getImage(getCodeBase(), "images/not.gif");
         crossImage = getImage(getCodeBase(), "images/cross.gif");
         addMouseListener(this);
    public void destroy() {
    removeMouseListener(this);
    * Paint it.
    public void paint(Graphics g) {
         Dimension d = getSize();
         g.setColor(Color.black);
         int xoff = d.width / 3;
         int yoff = d.height / 3;
         g.drawLine(xoff, 0, xoff, d.height);
         g.drawLine(2*xoff, 0, 2*xoff, d.height);
         g.drawLine(0, yoff, d.width, yoff);
         g.drawLine(0, 2*yoff, d.width, 2*yoff);
         int i = 0;
         for (int r = 0 ; r < 3 ; r++) {
         for (int c = 0 ; c < 3 ; c++, i++) {
              if ((white & (1 << i)) != 0) {
              g.drawImage(notImage, c*xoff + 1, r*yoff + 1, this);
              } else if ((black & (1 << i)) != 0) {
              g.drawImage(crossImage, c*xoff + 1, r*yoff + 1, this);
    * The user has clicked in the applet. Figure out where
    * and see if a legal move is possible. If it is a legal
    * move, respond with a legal move (if possible).
    public void mouseReleased(MouseEvent e) {
         int x = e.getX();
         int y = e.getY();
         switch (status()) {
         case WIN:
         case LOSE:
         case STALEMATE:
         play(getCodeBase(), "audio/return.au");
         white = black = 0;
         if (first) {
              white |= 1 << (int)(Math.random() * 9);
         first = !first;
         repaint();
         return;
         // Figure out the row/column
         Dimension d = getSize();
         int c = (x * 3) / d.width;
         int r = (y * 3) / d.height;
         if (yourMove(c + r * 3)) {
         repaint();
         switch (status()) {
         case WIN:
              play(getCodeBase(), "audio/yahoo1.au");
              break;
         case LOSE:
              play(getCodeBase(), "audio/yahoo2.au");
              break;
         case STALEMATE:
              break;
         default:
              if (myMove()) {
              repaint();
              switch (status()) {
              case WIN:
                   play(getCodeBase(), "audio/yahoo1.au");
                   break;
              case LOSE:
                   play(getCodeBase(), "audio/yahoo2.au");
                   break;
              case STALEMATE:
                   break;
              default:
                   play(getCodeBase(), "audio/ding.au");
              } else {
              play(getCodeBase(), "audio/beep.au");
         } else {
         play(getCodeBase(), "audio/beep.au");
    public void mousePressed(MouseEvent e) {
    public void mouseClicked(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public String getAppletInfo() {
         return "TicTacToe by Arthur van Hoff";

  • Tic Tac Toe Java help!

    Hi, I have been trying to create a simple Tic Tac Toe game using Java. I'm currently having problems as to how to create the board using arrays (sorry I don't understand them very well). All I have so far is this,
    public class ticTacToe {
    private int [] [] theBoard = new int [3] [3];
         // *'N' is no winner
         // 'X' is X won
         // 'O' is O won
         // 'C' is a cat's game
         public static char didSomeoneWin(int [] [] currentBoard)
              int winForX = 8000, winForO = 1, checkIfItsAcatsGame = 1, product;
              char winner = 'N';
              for(int column = 0; column < 3; column++) // Check the columns
                   product = currentBoard [0] [column] * currentBoard [1] [column] * currentBoard [2] [column];
                   if(product == winForX) winner = 'X';
                   if(product == winForO) winner = 'O';
              for(int row = 0; row < 3; row++) // Check the rows
                   product = currentBoard [row] [0] * currentBoard [row] [1] * currentBoard [row] [2];
                   if(product == winForX) winner = 'X';
                   if(product == winForO) winner = 'O';
              product = currentBoard [0] [0] * currentBoard [1] [1] * currentBoard [2] [2]; // Check one diagonal
              if(product == winForX) winner = 'X';
              if(product == winForO) winner = 'O';
              product = currentBoard [0] [2] * currentBoard [1] [1] * currentBoard [2] [0]; // Check the other diagonal
              if(product == winForX) winner = 'X';
              if(product == winForO) winner = 'O';
              if(winner == 'N') // If nobody's won, Check for a cat's game
                   for(int row = 0; row < 3; row++)
                        for(int column = 0; column < 3; column++)
                             checkIfItsAcatsGame *=currentBoard [row] [column];
                   if(checkIfItsAcatsGame != 0) winner = 'C'; // any empty space is a zero. So product is zero if there is space left.
              return winner;
         public void markX(int row, int column)
              myBoard [row] [column] = 20;
         public void markO(int row, int column)
              myBoard [row] [column] = 1;
    That is all so far, could someone help me print out the board? And help me out on the arrays? I don't think they are quite right. Thanks in Advance!
    Message was edited by:
    matthews1.7.2.0

    Hi,
    Do you need a GUI ?
    If yes see http://java.sun.com/docs/books/tutorial/uiswing/index.html
    You can also see this : http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html about printing.
    --Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Help Tic Tac Toe beginner

    A Tic Tac Toe board is represented as an array of 9 chars. Write a program that will allow two users to play tic tac toe. The player should ask for moves alternately from players X and O. The program is too dumb to check whether anyone has won or lost and just stops after 9 turns. The program should display the game position as follows after each move.
    The output should be somewhat as follows:
    Choose a spot (1 to 9) for X: 1
    X || ||
    || ||
    || ||
    Basically i have to do this. I was wondering if anyone could lead me in the right direction please?

    class TicTacToe {
        // instance variables
        // constructor(s)
        // method(s)
        public static void main(String[] args) {
            new TicTacToe();
    }There you go. I got you started. Now all you need to do is finish.

  • Finishing tic-tac-toe program

    Hey, so I've completed all the basic steps for playing the actual game, but now I'm working on creating the final booleans for determining if someone won or if it's a stalemate. Here's my entire code, but the boolean methods of interest are located at the bottom. Do I just use the player variable for the if statements? Am I missing anything? Thanks in advance.
    import java.util.*;
    public class Eight3
        public static void main(String[] args)
             Scanner keyboard = new Scanner(System.in);
             System.out.println("Welcome to tic-tac-toe. 'X' goes first.");
             TicTacToe newBoard = new TicTacToe();
             while(true)
             System.out.println("Enter coordinates for your move:");
             String newPlay = keyboard.nextLine();
             newBoard.play(newPlay);
             newBoard.print();
    class TicTacToe
        //will  represent the tic-tac-toe "board"
        private char[][] board;
        private char player;
        public TicTacToe()
             int row, column;
             player = 'X';
             board = new char[3][3];
             for(row = 0; row < board.length; row++)
                 for(column = 0; column < board[row].length; column++)
                     board[row][column] = ' ';
         public boolean play(String s)
              if(s.equals("A1"))
                 if(board[0][0] == ' ')
                     board[0][0] = player;
                else
                     return false;
            else if(s.equals("A2"))
                 if(board[0][1] == ' ')
                     board[0][1] = player;
                else
                    return false;
            else if(s.equals("A3"))
                 if(board[0][2] == ' ')
                     board[0][2] = player;
                else
                    return false;
            else if(s.equals("B1"))
                 if(board[1][0] == ' ')
                    board[1][0] = player;
                else
                    return false;
            else if(s.equals("B2"))
                 if(board[1][1] == ' ')
                    board[1][1] = player;
                else
                        return false;
            else if(s.equals("B3"))
                 if(board[1][2] == ' ')
                    board[1][2] = player;
                else
                    return false;
            else if(s.equals("C1"))
                if(board[2][0] == ' ')
                    board[2][0] = player;
                else
                    return false;
            else if(s.equals("C2"))
                if(board[2][1] == ' ')
                    board[2][1] = player;
                else
                    return false;
            else if(s.equals("C3"))
                     if(board[2][2] == ' ')
                         board[2][2] = player;
                else
                     return false;
            else
                 return false;
            if(player == 'X')
                 player = 'O';
            else
                player = 'X';
            return true;
        public void print()
              System.out.println("      1     2     3  ");
             System.out.println("         |     |     ");
             System.out.println("A     "+board[0][0]+"  |  "+board[0][1]+"  |  "+board[0][2]+" ");
             System.out.println("    - - - - - - - - -");
             System.out.println("B     "+board[1][0]+"  |  "+board[1][1]+"  |  "+board[1][2]+" ");
             System.out.println("    - - - - - - - - -");
             System.out.println("C     "+board[2][0]+"  |  "+board[2][1]+"  |  "+board[2][2]+" ");
             System.out.println("         |     |     ");
         public boolean won()
              if((board[0][0] == player) && (board[0][1] == player) && (board[0][2] == player))
                   return true;
              else if((board[1][0] == player) && (board[1][1] == player) && (board[1][2] == player))
                   return true;
              else if((board[2][0] == player) && (board[1][1] == player) && (board[2][2] == player))
                   return true;
              else if((board[0][0] == player) && (board[1][0] == player) && (board[2][0] == player))
                   return true;
              else if((board[0][1] == player) && (board[1][1] == player) && (board[2][1] == player))
                   return true;
              else if((board[0][2] == player) && (board[1][2] == player) && (board[2][2] == player))
                   return true;
              else if((board[0][0] == player) && (board[1][1] == player) && (board[2][2] == player))
                   return true;
              else if((board[0][2] == player) && (board[1][1] == player) && (board[2][0] == player))
                   return true;
              else
                   return false;
         public boolean stalemate()
              //not sure about this
    }

    Sorry about the ugliness - no it doesn't do what I want it to yet - I would just like some assistance with the public boolean won() method. The game doesn't end when a real life winner is determined. So, if we could just start with that, that'd be great. Thanks.

  • Simple tic tac toe

    heres my code: my question is at the bottom
    import apcslib.*;
    import chn.util.*;
    public class TicTacToe
    public static void main(String[] args)
    //variables and objects
    TicTac one = new TicTac();
    SketchPad paper = new SketchPad(500,500);
    DrawingTool pen = new DrawingTool(paper);
    ConsoleIO console = new ConsoleIO();
    System.out.print("Choose who's turn it is:");
    String choose = console.readToken();
    char variable = choose.charAt(0);
    if(variable == 'O' || variable == 'o')
    System.out.println("1: Top Left Corner");
    System.out.println("2: Top Middle");
    System.out.println("3: Top Right Corner");
    System.out.println("4: Middle Left");
    System.out.println("5: Middle");
    System.out.println("6: Middle Right");
    System.out.println("7: Bottem Left Corner");
    System.out.println("8: Bottom Middle");
    System.out.println("9: Bottom Right Corner");
    System.out.print("Choose where you want to put your mark by picking its number:");
    int choice = console.readInt();
    if(choice == 1)
    one.board(); //draws a tic tac toe board
    one.circle(-120, 65); //draws a circle at that location
    else if(choice == 2);
    one.board();
    one.circle(-50, 65);
    now my question, if i input 1 it draws the circle but it then continues on and draws the second circle to without me telling it to. but if i skip right to drawing the second circle it does and ignores the first one. thanks in advance for any input

       if(choice == 1)
          one.board();   //draws a tic tac
          one.circle(-120, 65);  //draws a
       else if(choice == 2);
           one.board();
           one.circle(-50, 65);
       }   Take the semicolen off of the second condition. It should be " if ( choice == 2 ) { ". Otherwise, the compiler thinks there is nothing to be executed as the result of choice == 2, and the instructions to draw the second circle are a seperate block of code that gets executed regardless of whether the choice is one, two, or fifteen billion.

  • Get blank screen each time? tic tac toe GUI...

    I get a blank screen each time i run this...I'm trying to display a tic tac toe board...the x's and o's are randomly generated...any idea why it's blank each time??
    public class TicTacToe extends JFrame
         private ImageIcon x = new ImageIcon("cross.gif");
         private ImageIcon o = new ImageIcon("not.gif");
         Random random = new Random(2);
         public TicTacToe()
              setLayout(new GridLayout(3,3));
              for(int y = 0; y<= 9; y++)
                Random r = new Random(2);
                   int randint = r.nextInt();
                   if (randint == 0)
                        add(new JLabel(x));
                   if (randint == 2)
                        add(new JLabel(o));
         public static void main(String args[])
              TicTacToe frame = new TicTacToe();
              frame.setTitle("Tic Tac Toe");
              frame.setSize(450,450);
              frame.setLocationRelativeTo(null);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
    }

    Timm017 wrote:
    Interested, what was wrong?He used Random and random.nextInt() incorrectly. Given that nextInt() without arguments can return any int between Integer.MIN_VALUE and Integer.MAX_VALUE with equal probability, the chance of hitting 0 or 2 is fairly low. So, most times (for most Random seeds), his code would never add any buttons to the panel. And, actually, since he used a '2' to seed the Random generator, he always got the same sequence of "random" numbers every time. So, his code would always give the same 9 numbers, and, apparently, those numbers don't include either 0 or 2.
    By the way, rollarace, besides picking the proper nextInt(...) method [you want the one that requires a parameter, as I assume you figured out], you should create the Random object once BEFORE the loop starts, and then just reuse it.
    Also:
    for(int y = 0; y<= 9; y++)should be:
    for(int y = 0; y< 9; y++)Otherwise, once the nextInt(...) part was fixed, he'd add 10 buttons.

  • Help with tic tac toe

    hey all,
    i am having problems creating a tic tac toe program. the program should create a board with NxN spaces, where N is obtained through user input.
    I created a fully working program that does a 3x3 board, checks for diagonal, vertical, horizontal wins and also allows 1 vs computer or 2 players play, but i am struggling with the NxN board.
    here is the code of what i have, can anyone point me in the right direction? all help is appreciated! please keep it simple as possible as i am just learning java!!
    import java.util.Scanner;
    import java.util.Random;
    public class NoughtsCrosses
    static final String PLAYER1 = "X";
    static final String PLAYER2 = "O";
    static final String EMPTY = "�";
    static String[][] board = new String[][];
    static int turn = 0;
    static public void makeBoard(int boardSize)
    for (int x = 0; x < boardSize; x++)
    for (int y = 0; y < boardSize; y++)
    board[x][y] = new String(EMPTY);
    static public void playComputer()
    Scanner scan = new Scanner(System.in);
    Random generator = new Random();
    int move;
    printBoard();
    System.out.println();
    do {
    if(turn%2 == 0)
    System.out.println("Player 1, place your X");
    System.out.print("Make a Move: ");
    move = scan.nextInt();
    else
    System.out.print("Computer, place your O: ");
    move = generator.nextInt(10);
    System.out.println(move);
    getMove(move);
    System.out.println();
    printBoard();
    System.out.println();
    } while(winner().equals(EMPTY) && turn < 9);
    if (winner().equals(EMPTY))
    System.out.println("The Game s a DRAW!");
    else
    System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!");
    static public void playHuman()
    Scanner scan = new Scanner(System.in);
    printBoard();
    System.out.println();
    do {
    if(turn%2 == 0)
    System.out.println("Player 1, place your X");
    else
    System.out.println("Player 2, place your O");
    System.out.print("Make a Move: ");
    int move = scan.nextInt();
    getMove(move);
    System.out.println();
    printBoard();
    System.out.println();
    } while(winner().equals(EMPTY) && turn < 9);
    if (winner().equals(EMPTY))
    System.out.println("The Game s a DRAW!");
    else
    System.out.println("PLAYER " + ((turn - 1) % 2 + 1) + " WINS!!");
    static public void getMove(int move)
    int row = move/3;
    int col = move%3;
    if (board[row][col].equals(EMPTY))
    board[row][col] = (turn % 2 == 0 ? PLAYER1 : PLAYER2);
    turn++;
    else
    System.out.println("OCCUPIED FIELD! TRY AGAIN!");
    static public void printBoard()
    for (int x = 0; x < 3; x++)
    for (int y = 0; y < 3; y++)
    if(y == 0)
    System.out.print(" ");
    System.out.print(board[x][y]);
    if(y < 2)
    System.out.print(" | ");
    System.out.println();
    if(x < 2)
    System.out.println(" ---|---|---");
    static public String winner()
    for (int i = 0; i < board.length; i++)
    /** check horizontally */
    if (board[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)
    Scanner scan = new Scanner(System.in);
    int boardSize;
    System.out.println();
    System.out.println("Welcome to Tic Tac Toe!");
    System.out.println("�����������������������");
    System.out.println("How big should the board be?");
    boardSize = scan.nextInt();
    makeBoard(boardSize);
    int players = 0;
    do{
    System.out.println("How many players?");
    System.out.println("1 (vs. Computer) or 2 (vs. another player)?");
    players = scan.nextInt();
    System.out.println();
    }while(players < 1 || players > 2);
    if (players == 1)
    playComputer();
    else
    playHuman();

    well, i figured out how to do it all, thanks to the TREMENDOUS amount of help here...lol...
    i just have one more (minor problem)...
    i can't get an algorithm working to see if the two diagonals are occupied by x's or o's (see if someone won diagonally)
    to check horizontally & vertically on an NxN board, i use following code:
    int count = 0;
            /** check horizontally  */
            for (int i = 0; i < myBoard.length; i++)
               for (int j = 0; j < myBoard.length-1; j++)
                   if (myBoard[0].equals(myBoard[i][j+1]) && !myBoard[i][0].equals(EMPTY))
    count++;
    if (count >= myBoard.length-1)
    return myBoard[i][0];
    count = 0;
    count = 0;
    /** check vertically */
    for (int i = 0; i < myBoard.length; i++)
    for (int j = 0; j < myBoard.length-1; j++)
    if (myBoard[j][0].equals(myBoard[j+1][i]) && !myBoard[0][i].equals(EMPTY))
    count++;
    if (count >= myBoard.length-1)
    return myBoard[0][i];
    count = 0;
    now i was messing around ALOT and couldn't figure out how to get the diagonals showing! this is what i came up with:
    count =0;
    for (int j = 1; j < myBoard.length; j++)
           if (myBoard[0][0].equals(myBoard[j][j]) && !myBoard[0][0].equals(EMPTY))
                 count++;
                 System.out.println(count);
            if (count >= myBoard.length)
                 return myBoard[0][0];
    count = 0;
    for (int j = myBoard.length-1; j >= 0; j--)
         if (myBoard[0][myBoard.length-1].equals(myBoard[j][j]) && !myBoard[0][myBoard.length-1].equals(EMPTY))
             count++;
             System.out.println(count);
          if (count >= myBoard.length)
              return myBoard[0][myBoard.length-1];
          count = 0;

  • Need help/advice with tic tac toe game

    Hello all. I am working on a tic tac toe game. I was able to program the first 4 moves fine, but ame having trouble with moves 5 and 6 for reasons that are unknown to me. Everything complies fine, its just that the move is displayed int the wrong space (B1) instead of in B2 or B3. Also the move that is supposed to be in A1 disapppears when B2 or B3 is clicked. Also, I need advice as to how to keep the prior moves from being over written.
    At this point I ahve gone over the code on-screen, printed it out, and stared at my drawings... and I'm not having any luck. I'm sure its a small, stupid thing that I'm missing, that anyone else would easily catch. Once again, thx for all your help.
    import java.awt.event.*;
    import java.awt.*;
    import java.applet.*;
    public class game3 extends Applet implements MouseListener{
         String move = "";
         boolean player1 = true;
         String gameBoard[][] = new String [3][3];
    public void spaceA1(Graphics g){ // MOVE IS A1
         if(gameBoard[0][0] == "X")
              g.drawString("X",65,65);
         if(gameBoard[0][0] == "O")
              g.drawString("O",65,65);
    public void spaceA2(Graphics g){ // MOVE IS A2
         if(gameBoard[0][1] == "X")
              g.drawString("X",95,65);
         if(gameBoard[0][1] == "O")
              g.drawString("O",95,65);                         
    public void spaceA3(Graphics g){ // MOVE IS A3               
         if(gameBoard[0][2] == "X")
              g.drawString("X",125,65);
         if(gameBoard[0][2] == "O")
              g.drawString("O",125,65);
    public void spaceB1(Graphics g){ // MOVE IS B1
         if(gameBoard[1][0] == "X")
              g.drawString("X",65,95);
         if(gameBoard[1][0] == "O")
              g.drawString("O",65,95);                    
    public void spaceB2(Graphics g){ // MOVE IS B2
         if(gameBoard[1][1] == "X")
              g.drawString("X",95,95);
         if(gameBoard[1][1] == "O")
              g.drawString("O",95,95);
    public void spaceB3(Graphics g){ // MOVE IS B3
         if(gameBoard[1][2] == "X")
              g.drawString("X",125,95);
         if(gameBoard[1][2] == "O")
              g.drawString("O",125,95);
    public void spaceC1(Graphics g){ // MOVE IS C1
         if(gameBoard[2][0] == "X")
              g.drawString("X",65,125);
         if(gameBoard[2][0] == "O")     
              g.drawString("O",65,125);     
    public void spaceC2(Graphics g){ // MOVE IS C2
         if(gameBoard[2][1] == "X")
              g.drawString("X",95,125);
         if(gameBoard[2][1] == "O")
              g.drawString("O",95,125);
    public void spaceC3(Graphics g){ // MOVE IS C3
         if(gameBoard[2][2] == "X")
              g.drawString("X",125,125);
         if(gameBoard[2][2] == "O")
              g.drawString("O",125,125);
    public void init(){
         addMouseListener(this);
         public void paint(Graphics g){
              g.drawString("    1       2       3", 50,45);
              g.drawString("A",40,70);
              g.drawString("B",40,100);
              g.drawString("C",40,130);
              // first row of boxes
              g.drawRect(50,50,30,30);
              g.drawRect(80,50,30,30);
              g.drawRect(110,50,30,30);
              // second row of boxes
              g.drawRect(50,80,30,30);
              g.drawRect(80,80,30,30);
              g.drawRect(110,80,30,30);
              // third row of boxes
              g.drawRect(50,110,30,30);
              g.drawRect(80,110,30,30);
              g.drawRect(110,110,30,30);
              if(move == "A1"){
                   spaceA2(g);
                   spaceA3(g);
                   spaceB1(g);
                   spaceB2(g);
                   spaceB3(g);
                   spaceC1(g);
                   spaceC2(g);
                   spaceC3(g);
                   if(player1){
                   gameBoard[0][0] = "X";
                   g.drawString("X",65,65);
                   player1 = false;
                   return;
                   else
                   if(!player1){
                   gameBoard[0][0] = "O";
                   g.drawString("O",65,65);
                   player1 = true;
                   return;
              } // end of A1
              else
              if(move == "A2"){
                   spaceA1(g);
                   spaceA3(g);
                   spaceB1(g);
                   spaceB2(g);
                   spaceB3(g);
                   spaceC1(g);
                   spaceC2(g);
                   spaceC3(g);
                   if(player1){
                   gameBoard[0][1] = "X";     
                   g.drawString("X",95,65);
                   player1 = false;
                   return;
                   else
                   if(!player1){
                   gameBoard[0][1] = "O";
                   g.drawString("O",95,65);
                   player1 = true;
                   return;
              } // end of A2
              else
              if(move == "A3"){
                   spaceA1(g);
                   spaceA2(g);
                   spaceB1(g);
                   spaceB2(g);
                   spaceB3(g);
                   spaceC1(g);
                   spaceC2(g);
                   spaceC3(g);
                   if(player1){
                   gameBoard[0][2] = "X";
                   g.drawString("X",125,65);
                   player1 = false;
                   return;
                   else
                   if(!player1){
                   gameBoard[0][2] = "O";
                   g.drawString("O",125,65);
                   player1 = true;
                   return;
              } // end of A3
              else
              if(move == "B1")
                   spaceA1(g);
                   spaceA2(g);
                   spaceA3(g);
                   spaceB2(g);
                   spaceB3(g);
                   spaceC1(g);
                   spaceC2(g);
                   spaceC3(g);
                   if(player1){
                   gameBoard[1][0] = "X";
                   g.drawString("X",65,95);
                   player1 = false;
                   return;
                   else
                   if(!player1){
                   gameBoard[1][0] = "O";
                   g.drawString("O",65,95);
                   player1 = true;
                   return;
              } // end of B1
              else
              if(move == "B2"){
                   spaceA1(g);
                   spaceA2(g);
                   spaceA3(g);
                   spaceB1(g);
                   spaceB3(g);
                   spaceC1(g);
                   spaceC2(g);
                   spaceC3(g);
                   if(player1){
                   gameBoard[1][1] = "X";
                   g.drawString("X",95,95);
                   player1 = false;
                   return;
                   else
                   if(!player1){
                   gameBoard[1][1] = "O";
                   g.drawString("O",95,95);
                   player1 = true;
                   return;
              } // end of B2
              else
              if(move == "B3"){
                   spaceA1(g);
                   spaceA2(g);
                   spaceA3(g);
                   spaceB1(g);
                   spaceB2(g);
                   spaceC1(g);
                   spaceC2(g);
                   spaceC3(g);
                   if(player1){
                   gameBoard[1][2] = "X";
                   g.drawString("X",125,95);
                   player1 = false;
                   return;
                   else
                   if(!player1){
                   gameBoard[1][2] = "O";
                   g.drawString("O",125,95);
                   player1 = true;
                   return;
              }// end of B3
         }// end of graphics
         public void mouseReleased(MouseEvent me){}
         public void mousePressed(MouseEvent me){}
         public void mouseDragged(MouseEvent me){}
         public void mouseEntered(MouseEvent me){}
         public void mouseExited(MouseEvent me){}
         public void mouseClicked(MouseEvent me){
              int x = me.getX();
              int y = me.getY();
              if((x >=51) && (x<= 79) && (y >= 51) && (y <= 79)) //MOVE IS A1
                   move = "A1";
              else
              if((x >=81) && (x<=109) && (y >=51) && (y <= 79))  //MOVE IS A2
                   move = "A2";
              else
              if((x >=111) && (x<=139) && (y >=51) && (y <= 79))  //MOVE IS A3
                   move = "A3";
              else
              if((x >=51) && (x<= 79) && (y >= 81) && (y <= 109))  //MOVE IS B1
                   move = "B1";
              else
              if((x >=81) && (x<=109) && (y >=81) && (y <= 109))  //MOVE IS B2
                   move = "B2";
              else
              if((x >=111) && (x<=139) && (y >=81) && (y <= 109))  //MOVE IS B3
                   move = "B3";
              repaint();
    //<applet code = "game3.class" height =300 width=300> </applet>     

    writing a tic-tac-toe is harder than it sounds.. i wrote one last year in my computer science class.. i have it on my website, if you want to look at code. i wrote it in c++, but the logic is all that matters :)
    btw-last year, i wasnt too good of an OOP programmer, so the program is procedurely written. heres the url:
    http://www.angelfire.com/blues/smb
    also, to tell if a box is already taken, you can just add an if statement:   if ( gameBoard[selX][selY] == null )  //not taken, fill box:many people resort to a boolean matrix of the same idea, but with booleans that store which boxes are taken. i prefer the way above, saves code, memory, and makes it more understandable.
    hope it helps.

  • Need some help with Tic Tac Toe game

    hey. hope u guys can help me out...
    having a problem with my tic tac toe program...
    i have 2 problems.
    1) got the "X" and "O" to appear using a flag(teacher didn't explain)
    using code like this
    if (jb == button[0]){
    if (flag==0)
    button[0].setText("X");
    else
    button[0].setText("O");
    //toggle
    flag = (flag==0)?1:0;
    my problem is how do i get it to stop.(For example button[1] is selected as "X"..how do i stop it from albe to switch to "O")
    2) found this code in javascript online and i want to do what it does in java code
    if(button[0] == " X " && button[1] == " X " && button[2] == " X ")
    alert("You Win!");
    reset();
    how would i do that?
    thanks for the help.

    ok here's my code:
    //TTT.java
    import javax.swing.*;
    import java.awt.*;
    import java .awt.event.*;
    public class TTT extends JFrame
                        implements WindowListener, ActionListener
    private JFrame frFirst;
    private Container cnFirst,cnSecond;
    private     JButton button[]=new JButton[9];
    private JButton btnNewGame,btnExit;
    private FlowLayout southLayout;
    private JPanel southPanel;
    private int flag;
    public TTT()
                   frFirst=new JFrame ("Michael's Tic Tac Toe Game!");
                   cnFirst=frFirst.getContentPane();
                   cnFirst.setLayout (new GridLayout (4,4));
                   cnFirst.setBackground(Color.green);
              for(int i=0;i<button.length;i++)
                        button[i] = new JButton();
                        cnFirst.add(button);
                        flag=0;
              southPanel = new JPanel ();
              btnNewGame = new JButton ("New Game");
              southPanel.add (btnNewGame);
              btnExit = new JButton ("EXIT");
              southPanel.add (btnExit);
              frFirst.add (southPanel,BorderLayout.SOUTH);
              frFirst.setLocation(200, 200);
              frFirst.setSize(400,400);
              frFirst.setResizable(false);
              frFirst.setVisible(true);
              this.frFirst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   // listeners
                   frFirst.addWindowListener(this);
                   button[0].addActionListener(this);
                   button[1].addActionListener(this);
                   button[2].addActionListener(this);
                   button[3].addActionListener(this);
                   button[4].addActionListener(this);
                   button[5].addActionListener(this);
                   button[6].addActionListener(this);
                   button[7].addActionListener(this);
                   button[8].addActionListener(this);
                   btnNewGame.addActionListener (this);
                   btnExit.addActionListener (this);
         //define methods of WindowListener
    public void windowOpened(WindowEvent we)
         public void windowClosing(WindowEvent we)
         System.exit(0);
         public void windowClosed(WindowEvent we)
         public void windowIconified(WindowEvent we)
         public void windowDeiconified(WindowEvent we)
         public void windowActivated(WindowEvent we)
         public void windowDeactivated(WindowEvent we)
    public void actionPerformed(ActionEvent ae)
    //making the X and O to appear on JButtons
         Object obj = ae.getSource();
              if (obj instanceof JButton){
                   JButton jb = (JButton)obj;
                   if (jb == button[0])
                        if (flag==0)
                        button[0].setText("X");
                   else
                        button[0].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[1])
                        if (flag==0)
                        button[1].setText("X");
                   else
                        button[1].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[2])
                        if (flag==0)
                        button[2].setText("X");
                   else
                        button[2].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[3])
                        if (flag==0)
                        button[3].setText("X");
                   else
                        button[3].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[4])
                        if (flag==0)
                        button[4].setText("X");
                   else
                        button[4].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[5])
                        if (flag==0)
                        button[5].setText("X");
                   else
                        button[5].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[6])
                        if (flag==0)
                        button[6].setText("X");
                   else
                        button[6].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[7])
                        if (flag==0)
                        button[7].setText("X");
                   else
                        button[7].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[8])
                        if (flag==0)
                        button[8].setText("X");
                   else
                        button[8].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
    //New Game To Reset
              if (ae.getSource () == btnNewGame)
    /*     String text = JOptionPane.showInputDialog(null,"Do You Want To Start A New Game?","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
    String YES;
    if (text == YES)
         JOptionPane.showMessageDialog(null,"Do You","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
         else{
    add code to reset game
         //Exit Button to Exit
         if (ae.getSource () == btnExit)
              JOptionPane.showMessageDialog(null,"Thanks For Playing!","Michael's Tic Tac Toe Game!",JOptionPane.INFORMATION_MESSAGE);
              this.setVisible(false);
         System.exit(0);
              }     //end of if instanceof
    public static void main(String[]args)
         //instantiate GUI
         new TTT();

  • NEED TIC TAC TOE HELP

    Why do I keep getting the following errors in a very simple, basic TIC TAC TOE program? Any help would be greatly appreciated. Thanks.
    C:\Class\Teresa\TicTacToe017.java:114: 'else' without 'if'
    else if (board[turnRow - 1][turnCol - 1] == 'X'
    ^
    C:\Class\Teresa\TicTacToe017.java:185: 'else' without 'if'
    else // Next player's turn
    ^
    C:\Class\Teresa\TicTacToe017.java:39: cannot resolve symbol
    symbol : method call ()
    location: class TicTacToe017
                        call();
    ^
    C:\Class\Teresa\TicTacToe017.java:145: cannot resolve symbol
    symbol : method writeBoard ()
    location: class TicTacToe017
    writeBoard();
    ^
    C:\Class\Teresa\TicTacToe017.java:165: cannot resolve symbol
    symbol : method writeBoard ()
    location: class TicTacToe017
    writeBoard();
    ^
    C:\Class\Teresa\TicTacToe017.java:181: cannot resolve symbol
    symbol : method writeBoard ()
    location: class TicTacToe017
    writeBoard();
    ^
    6 errors
    Tool completed with exit code 1
    Here is my code so far.
    File name: TicTacToe.java
    A class to play TicTacToe.
    Entries cannot be changed once they are entered.
    Written by: Lew Rakocy
    email address: [email protected]
    Date: 9/2/00
    Changes: 03/13/2003 Made comments like text examples.
    Added code to display board after win and draw.
    public class TicTacToe017
    // Use a 3 X 3 (two-dimensional) array for the game board.
    private static char[][] board = new char[3][3];
    private static char turn;
    private static int row; // Loop controls to
    private static int col; // display the board
    private static int turnRow; // User input to
    private static int turnCol; // select move
    private static boolean entryError;
    private static boolean anotherGame = true;
    private static char repeat; // User input: y or Y to repeat
    private static int entryCount = 0; // Game ends when board is full
    // (when entryCount = 9);
    public static void main(String[] args)
    while(anotherGame)
    newGame();
    while(!winner())
                        //WRITE THE METHOD CALL TO DISPLAY THE "BOARD" HERE
                        call();
                        System.out.println("This is the game board.");
    //WRITE THE METHOD CALL FOR THE "PLAY" OF THE GAME HERE
                        System.out.print("Welcome to Teresa's Tic Tac Toe!");
    System.out.println("Another game? Enter Y or y for yes.");
    repeat = SavitchIn.readLineNonwhiteChar();
    //WRITE THE IF/ELSE STATEMENT TO PLAY ANOTHER GAME HERE
    if ((repeat == 'Y') || (repeat == 'y'))
         System.out.println("Play another game.");
    else
         System.out.println("End of game. Thanks for playing.");
    //WRITE THE HEADER FOR THE writeBoard METHOD HERE
    System.out.println("-----------------");
    System.out.println("|R\\C| 1 | 2 | 3 |");
    System.out.println("-----------------");
    for(row = 0; row < 3; ++row)
    System.out.println("| " + (row + 1)
    + " | " + board[row][0]
    + " | " + board[row][1]
    + " | " + board[row][2]
    + " |");
    System.out.println("-----------------");
    private static void getMove()
    entryError = true; // Will change to false if valid row
    // and column numbers are entered.
    while(entryError)
    System.out.println();
    System.out.println(turn + "'s turn.");
    System.out.println("Where do what your " + turn + " placed?");
    System.out.println(
    "Please enter row number and column number"
    + " separated by a space.");
    System.out.println();
    turnRow = SavitchIn.readInt();
    turnCol = SavitchIn.readInt();
    System.out.println("You have entered row #" + turnRow);
    System.out.println(" and column #" + turnCol);
    // Check for proper range (1, 2, or 3)
                   //WRITE THE IF STATEMENT HERE FOR AN INVALID ENTRY
                   if (board[turnRow - 1][turnCol - 1] > 3)
              System.out.println("Invalid entry: try again.");
    System.out.println(
    "Row & column numbers must be either 1, 2, or 3.");
    // Check to see if it is already occupied
    // Adjust turnRow and turnCol for 0-numbering in array
    else if (board[turnRow - 1][turnCol - 1] == 'X'
    || board[turnRow - 1][turnCol - 1] == 'O')
    System.out.println("That cell is already taken.");
    System.out.println("Please make another selection.");
    else // Valid entry
    entryError = false;
    System.out.println("Thank you for your selection.");
    board[turnRow - 1][turnCol - 1] = turn;
    ++entryCount;
    private static boolean winner()
    // Row checks
    for(row = 0; row < 3; ++row)
    if(board[row][0] == turn)
    if(board[row][1] == turn)
    if(board[row][2] == turn)
    System.out.println();
    System.out.println (turn + " IS THE WINNER!!!");
    writeBoard();
    return true;
    // WRITE A FOR LOOP FOR THE COLUMN CHECKS HERE
    // WRITE A FOR LOOP FOR THE DIAGONAL CHECKS HERE
    if(board[0][2] == turn)
    if(board[1][1] == turn)
    if(board[2][0] == turn)
    System.out.println();
    System.out.println (turn + " IS THE WINNER!!!");
    writeBoard();
    return true;
    // These lines execute only if there is no winner.
    // End game if board is full
    //WRITE THE IF STATEMENT TO CHECK IF THE BOARD IS FULL
              if (entryCount == 9)
    System.out.println();
    System.out.println("Draw: no winner and board is full.");
    writeBoard();
    return true;
    else // Next player's turn
    //WRTITE THE IF/ELSE STATEMENT FOR THE NEXT PLAYER'S TURN
    return false;
    private static void newGame()
    System.out.println();
    System.out.println("New Game: X goes first.");
    turn = 'O'; // Turn will change to X when winner() is called
    // Clear the board
    for(row = 0; row < 3; ++row)
    for(col = 0; col < 3; ++col)
    board[row][col] = ' ';
    entryCount = 0;
    System.out.println();

    the "else without if" means that you have an else statement that wasn't attached to an if statement. In your case, it seems to be because you had multiple statements following an if statement, and you didn't enclose them in a single block.
    The "cannot resolve symbol" means that you referred to something that wasn't defined. Either it's your code, and you forgot to define it, or you were referring to someone else's code, in which case you probably forgot an import statement, or you're using their code incorrectly.

  • Basic Tic Tac Toe programming help please

    I'm trying to make a seperate java class(there is another main that calls this using SWING interface) that makes mark on the board.
    It's supposed to do the following
    Method makeMark returns:
    a null if the cell indicated by row and column has already been marked
    an X if it is X's turn (X gets to go first)
    a Y if it is Y's turn
    Thus makeMark will have to keep of marks made previously and return the appropriate string
    for the requested cell.
    and here is what I got so far, but only getting empty clicks as a respond. Any help will be appreciated. thanks.
    import javax.swing.JButton;
    public class TicTacToeGame {
         public String makeMark(int row, int column){
    String player = "X";
    String [][] Enum = new String [3][3];
              for (row=0; row<=2; row++){
                   for (column=0; column<=2; column++)
                        if (Enum[row][column] == "")
    if (player == "X"){
    Enum[row][column] = "X";
    player = "Y";
    return "X";
    if (player == "Y"){
    Enum[row][column] = "O";
    player = "X";
    return "Y";
    else
    return null;
              return player;
    }

    ok is there a simpler codes that will just flip-flop between X and O? I had it working before but somehow it's not working anymore. Before I had
    public String makeMark(int row, int column){
    player = "X";
    if (player = "X")
    player = "O";
    else if (player = "O")
    player = "X";
    or soemthing like this but it used to work, but I had to revise the code to do more things and it stopped even flip-flopping between X and O.
    Here's main code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * This class is the GUI for TicTacToe. It only handles user clicks on
    * buttons, which represent X's and O's
    * @author Hal Mendoza
    * CSE 21 - Jan 18, 2011, 8:18:22 PM
    * TicTacToe.java
    public class TicTacToe extends JPanel implements ActionListener {
    public final static int NUM_ROWS_COLUMNS = 3;
    private JButton arrayofButtons[][] = new JButton[NUM_ROWS_COLUMNS][NUM_ROWS_COLUMNS];
    TicTacToeGame board = new TicTacToeGame();
    public TicTacToe() {
         BoxLayout ourLayout = new BoxLayout(this, BoxLayout.Y_AXIS);
         setLayout(ourLayout);
         add(buildMainPanel());
    * Builds the panel with buttons
    * @return the panel with buttons
    private JPanel buildMainPanel() {
         JPanel panel = new JPanel();
         GridLayout gridLayout = new GridLayout(0, NUM_ROWS_COLUMNS);
         panel.setLayout(gridLayout);
         for (int row = 0; row < arrayofButtons.length; ++row)
              for (int column = 0; column < arrayofButtons[0].length; ++column) {
                   arrayofButtons[row][column] = new JButton();
                   arrayofButtons[row][column].setPreferredSize(new Dimension(50, 50));
                   arrayofButtons[row][column].addActionListener(this);
                   // Use actionCommand to store x,y location of button
                   arrayofButtons[row][column].setActionCommand(Integer.toString(row) + " " +
                             Integer.toString(column));
                   panel.add(arrayofButtons[row][column]);
         return panel;
    * Called when user clicks buttons with ActionListeners.
    public void actionPerformed(ActionEvent e) {
         JButton button = (JButton) e.getSource();
         String xORo;
         String rowColumn[] = button.getActionCommand().split(" ");
         int row = Integer.parseInt(rowColumn[0]);
         int column = Integer.parseInt(rowColumn[1]);
         xORo = board.makeMark(row, column);
         if (xORo != null)
              button.setText(xORo);
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event dispatch thread.
    private static void createAndShowGUI() {
         // Create and set up the window.
         JFrame frame = new JFrame("Tic Tac Toe");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         // Add contents to the window.
         frame.add(new TicTacToe());
         // Display the window.
         frame.pack();
         frame.setVisible(true);
    public static void main(String[] args) {
         // Schedule a job for the event-dispatching thread:
         // creating and showing this application's GUI.
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                   createAndShowGUI();
    }

Maybe you are looking for

  • Dark screen on Sat Pro A10

    Hi I have a Sat Pro A10. My problem is that my screen is so dark I cannot see the contents (maybe its the backlight?). However when the computer boots I can see the Toshiba logon screen fine. I can also get the picture to appear normal if I shut the

  • APEX_ITEM select_list is not working

    Hi, I am using the below query in my sql select statement . select htmldb_item.HIDDEN(1,ID) HIDDEN, APEX_ITEM.SELECT_LIST(49,DECODE("VERSION",NULL,'-Select-',"VERSION"),decode(get_lov_values(PROD_LEVEL_1),null,'not available',get_lov_values(PROD_LEVE

  • SE80 - Automatic fulfilling of the field

    I would like to know if is possible to use in transaction SE80 in layout, the automatic fulfilling of the field. For exemple: I have a field ID and more 2 fields (name and address). The ID is related with name and address. When I fill the field ID, I

  • Cloud Process template unable to auto syncing in runbook dependancy offering

    Hi, We are using Service Manager 2012 R2 with Rollup4 and Orchestrator 2012 R2 with same rollup. We have integrated cloud process pack for VM provisioning. Some days ago, we have successfully created VM by this setup, but now we are unable to create

  • PO with acc. *** as K and distributed

    Hye I have 2 questions here - 1. Created a PO with account assignment as K - qty is distributed for 5 cost centres with 20 nos each now i have made the GR for 10 nos, but now am not able to track for which cost centre it is consumed is there any repo