Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Tic-Tac-Toe array Win Check

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Exclamation Tic-Tac-Toe array Win Check

    I'm having a hard time figuring out how to check for a win in my tic-tac-toe board. I have to check to see if the winner is X or O or check to see if there is no winner yet (return N) or the board is full and it is a tie (return F). The method in question is named checkForWin. It is the last included method included. I have included the whole program, but the only part that requires some addition is that last method, checkForWin. All else is okay (sufficiently).

    package lab07;
     
    import java.util.*;
     
    public class Lab07 {
     
        /**
         * @param args the command line arguments Do not change main()
         */
        public static void main(String[] args) {
            char[][] board;
            char win;
            char player;
            int size = getBoardSize();
     
            while (size >= 3) {
                board = createEmptyBoard(size);
                player = getStartingPlayer();
                do {
                    getMove(board, player);
                    player = player == 'O' ? 'X' : 'O'; // switch players
                    win = checkForWin(board);
                } while (win == 'N'); // must be F, O or X to leave loop
                if (win == 'F') {
                    System.out.printf("\nThe board is Full: no Winner\n");
                } else {
                    System.out.printf("\nThe winner is %c\n", win);
                }
                displayBoard(board);
                size = getBoardSize();
            } // end play games loop
        } // end main
     
        /**
         * returns 3, 4 or 5 for the size of the play board or -1 to quit This is
         * complete, no changes necessary
         */
        public static int getBoardSize() {
            int retval;
            Scanner keyboard = new Scanner(System.in);
            do {
                System.out.printf("Enter board size 3, 4, 5 or -1 to quit: ");
                retval = keyboard.nextInt();
            } while (retval != 3 && retval != 4 && retval != 5 && retval != -1);
     
            keyboard.nextLine(); // you should know why by now
     
            return retval; // this MUST BE LAST LINE in this method()
        } // getBoardSize
     
        /**
         * randomly selects X or O as the starting player
         *
         */
        public static char getStartingPlayer() {
            char retval = 'X';
            int switchRan;
     
            Random ranGen = new Random();
            switchRan = ranGen.nextInt(2);
            switch (switchRan) {
                case 0:
                    retval = 'O';
                    break;
                case 1:
                    retval = 'X';
                    break;
            }
     
     
            System.out.printf("\n\tNew Game. Starting player is %c\n", retval);
            return retval; // this MUST BE LAST LINE in this method()
        } // end getStartingPlayer
     
        /**
         * gets new memory for a board and fills all cells with a minus sign '-'
         *
         * @param size the board if 3 is 3 x 3, if 4 is 4 x 4 etc.
         */
        public static char[][] createEmptyBoard(int size) {
            char[][] board = new char[size][size];
     
            for (int row = 0; row < board.length; row++) {
                for (int column = 0; column < board[row].length; column++) {
                    board[row][column] = '-';
                }
            }
            return board; // this MUST BE LAST LINE in this method()
        } // end createEmptyBoard
     
        /**
         * 1. displays board and 2. gets row column indexes for next move 3. makes
         * sure the cell has a '-' is a legal move 4. loops till legal 5. puts the
         * player's X or O at that cell
         *
         * @param board the current play board
         * @param the X or O of the current player
         */
        public static void getMove(char[][] board, char player) {
            Scanner keyboard = new Scanner(System.in);
            int row, col;
            System.out.printf("Player %c move\n", player);
            displayBoard(board);
            do {
                System.out.print("Enter row:  >=0 and <=" + (board.length - 1) + "  ");
                row = keyboard.nextInt();
                System.out.print("Enter col:  >=0 and <=" + (board.length - 1) + "  ");
                col = keyboard.nextInt();
            } while (board[row][col] != '-' && (board[row][col] != player));//CHECK THIS ONCE checkForWin IS COMPLETE
            board[row][col] = player;
        } // end getMove
     
        /**
         * displays the current play board to the console
         *
         * @param board the current play board to be displayed
         */
        public static void displayBoard(char[][] board) {
            for (int row = 0; row < board.length; row++) {
                System.out.println();
                for (int column = 0; column < board[row].length; column++) {
                    System.out.printf("%c\t", board[row][column]);
     
                }
            }
            System.out.println();
        } // end displayBoard
     
        /**
         * returns X, O, F or N returns X for X wins O for O wins F for board Full
         * no winner or N for No winner yet
         *
         * @param board, the current play board to be checked
         */
        public static char checkForWin(char[][] board) {
            char retval = 'N';
            int dashCount = board.length * board.length;//set total count of dashes to check for full board vs. open spaces
            int oCount, xCount;
     
     
            /**
             * Check for horizontal wins
             */
            for (int row = 0; row < board.length; row++) {
                oCount = xCount = 0;//Reset X and O counters
                for (int col = 0; col < board[row].length; col++) {
     
                    if (board[row][col] == 'X') {
                        xCount++;
                    } else if (board[row][col] == 'O') {
                        oCount++;
                    } else {
                        dashCount--;
                    }
                    if (xCount == board.length) {
                        retval = 'X';
                    }
                    if (oCount == board.length) {
                        retval = 'O';
                    }
                    if (dashCount == 0) {
                        retval = 'F';
                    }
                }
            }
     
     
     
            return retval; // this MUST BE LAST LINE in this method()
        } // end checkForWin
    }


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Tic-Tac-Toe array Win Check

    Think of how many ways to win.
    3 horizontal wins
    3 vertical wins
    2 diagonal wins

    Does your method check each possibility?

  3. #3
    Junior Member
    Join Date
    Oct 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Tic-Tac-Toe array Win Check

    No, I know it doesn't. That's just as far as i could figure out. I managed to get the horizontal wins. I'm not sure how to use the for-loops to do the others. Should i just reuse that same bit and put it in the for-loop that holds the second? Would that get me the vertical wins?

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Tic-Tac-Toe array Win Check

    Think of how many ways to win.
    3 horizontal wins
    3 vertical wins
    2 diagonal wins
    Well with 8 maximum possible cases, even brute force is fast...

    0 1 2
    3 4 5
    6 7 8

    if ( winOn(0 1 2) ) { //top row wins }
    if ( winOn(3 4 5) ) { //mid row wins }
    if ( winOn(6 7 8) ) { //low row wins }
    if ( winOn(0 3 6) ) { //left col wins }
    if ( winOn(1 4 7) ) { //mid col wins }
    if ( winOn(2 5 8) ) { //right col wins }
    if ( winOn(0 4 8) ) { //top left to bottom right diag wins }
    if ( winOn(2 4 6) ) { //top right to bottom left diag wins }

    There are many different ways to handle this. See which way fits your mind set. Consider possibilities. For example if the game board position 0 has no value, three possible wins are eliminated. Or if position 4 has no value, 4 possible wins need not be checked.

    You mentioned for loops. See what you can come up with.

  5. #5
    Junior Member Icetaller's Avatar
    Join Date
    Oct 2012
    Location
    Athens, Greece
    Posts
    2
    My Mood
    Inspired
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Tic-Tac-Toe array Win Check

    Well, good morning from Greece. I just finished doing a tic tac toe program for myself in my free time. This is what i used to check
    if the current player won the game. Customize it to your needs.
    "The array positions has the moves that player x or o used and moves_played is the moves that player x or o played when you called the method.
    /**code removed by moderator*/
    Last edited by Icetaller; October 28th, 2012 at 06:50 AM. Reason: spoonfeeding

  6. #6
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Tic-Tac-Toe array Win Check

    @ Icetaller
    Hi and welcome. Please read the problem with spoonfeeding.

  7. #7
    Junior Member Icetaller's Avatar
    Join Date
    Oct 2012
    Location
    Athens, Greece
    Posts
    2
    My Mood
    Inspired
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Tic-Tac-Toe array Win Check

    Quote Originally Posted by jps View Post
    @ Icetaller
    Hi and welcome. Please read the problem with spoonfeeding.
    Hey jps. I'm sorry that wasn't my intention. I just learned programming by reading and understanding other people's code. I asked them their thought behind each problem they solved with their code. Then I went on to make another program that came into my mind using the knowledge I acquired from that. Maybe, not all people work that way and they are lazy. It's just I have a different opinion on the "Spoon feeding". But, then again maybe a better way of learning is Socrates' method of extracting the knowledge through the student. I'll try and use the second method if that's how this forum works.

Similar Threads

  1. Need help with tic tac toe game
    By ogpg2006 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: August 2nd, 2012, 07:34 AM
  2. Tic-Tac-Toe Help
    By coke32 in forum Object Oriented Programming
    Replies: 13
    Last Post: March 12th, 2012, 07:59 AM
  3. Tic Tac Toe Program, Can someone help me out????
    By KVM in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 24th, 2012, 08:11 PM
  4. tic tac toe single array code help
    By angelus2402004 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 8th, 2012, 10:17 PM
  5. [SOLVED] Tic Toe java code exists when we enter 0 row and 0 column
    By big_c in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: May 13th, 2009, 07:16 AM

Tags for this Thread