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 12 of 12

Thread: TicTacToe 2D Array help

  1. #1
    Junior Member
    Join Date
    Jun 2011
    Posts
    29
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default TicTacToe 2D Array help

    I got a new problem. I can't seem to have the validation done on the player. In the game, if I put into the move for the User and the computer already has the move, it'll override it.
    I used if (Usermove == "O"), try again blah bllah blah, but I think my logic is wrong.

    Does anyone have ideas on how to implement validation so that user can't override computer's move? Thanks.

    import java.util.Random;
    import java.util.Scanner;
     
    public class tictactoe {
     
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
     
            char[][] board = new char[3][3];
            char defaultPlayer = 'X';
            int currentMove = -1;
            boolean errorCheck;
     
            fillEmptySpaces(board, ' ');
     
            System.out.println("****************" );
            System.out.println("  Tic-Tac-Toe!" );
            System.out.println("****************");
            printBoard(board);
     
            while (!finalGame(board)) {
              	do {
            		errorCheck = true;
            		System.out.print("Please enter column[Letter] and row[#]: "  +currentMove);
                	String userMove = in.nextLine().toUpperCase();
                	{      	
            	 	if (userMove.equals("A1")){        	 		
            	 		currentMove = 1;
                	}
                	else	if (userMove.equalsIgnoreCase("A2")){
                		currentMove = 4;
                	}
                	else	if (userMove.equalsIgnoreCase("A3")){
                		currentMove = 7;
                	}
                	else	if (userMove.equalsIgnoreCase("B1")){
                		currentMove = 2;
                	}
                	else	if (userMove.equalsIgnoreCase("B2")){
                		currentMove = 5;
                	}
                	else	if (userMove.equalsIgnoreCase( "B3")){
                		currentMove = 8;
                	}
                	else	if (userMove.equalsIgnoreCase( "C1")){
                		currentMove = 3;
                	}
                	else	if (userMove.equalsIgnoreCase("C2")){
                		currentMove = 6;
                	}
                	else if (userMove.equalsIgnoreCase("C3")){
                		currentMove = 9;
                	}      	            	
                	else{
                		errorCheck = false;
                		System.out.println("That move is invalid! Please enter move again.");
                	}
                	}
            	} while(errorCheck == false);
     
            	userMove(defaultPlayer, currentMove, board);
                computerMove(defaultPlayer, currentMove, board);
                printBoard(board);
     
            }
            Results(board);
        }
     
     
        /*********************************************************************
    	 * Method Name:   MOVE_INFO
    	 * Description:   Char map that shows where to put the X's and O's
    	 * 
    	 * Each char represents the the index of the element of 2D array.
    	 * 
    	 * move = 1; [0][1]
    	 * move = 2; [0][2]
    	 * move = 3; [0][3]
    	 * move = 4; [1][1]
    	 * move = 5; [1][2]
    	 * move = 6; [1][3]
    	 * move = 7; [2][1]
    	 * move = 8; [2][2]
    	 * move = 9; [2][3]
    	 * 
    	 *********************************************************************/
        public static final char[][] MOVE_INFO ={{'1', '2', '3'},
        										{ '4', '5', '6'},
        										{ '7', '8', '9'}};
     
     
     
        /*********************************************************************
    	 * Method Name:   fillEmptySpaces
    	 * Parameters:    a, k
    	 * Returns:       NONE
    	 * Description:   It fills all the elements in the array with spaces so
    	 * 				  the program can check if it's anymore moves left.
    	 *********************************************************************/
        public static void fillEmptySpaces(char[][] a, char k) {
            for (int i = 0; i < a.length; i++) {
                for (int j = 0; j < a[i].length; j++) {
                    a[i][j] = k;
                }
            }
        }
    	/*********************************************************************
    	 * Method Name:   userMove
    	 * Parameters:    player(user, 'X')
    	 * 				  move
    	 * 				  board
    	 * Returns:       none
    	 * Description:   Uses the currMove and converts it to move. Each move
    	 * 				  corresponds to the index of an array. See above. 
    	 *********************************************************************/
        public static void userMove(char player, int move, char[][] board) {
        	int row, col;
    		if (!finalGame(board)){
    				row = (move - 1)/ board.length;
           			col = (move - 1) % board[row].length;
    				board[row][col] = 'X';
    		}
      	}
     
        /*********************************************************************
    	 * Method Name:   computerMove
    	 * Parameters:    player(computer, 'O')
    	 * 				  move
    	 * 				  board
    	 * Returns:       none
    	 * Description:   Uses random class to generate a double to pick a random
    	 * 				  place for the O to go. 
    	 *********************************************************************/
        public static void computerMove(char player, int move, char[][] board){
    		int row, col;
    		if (!finalGame(board)){
    			do {				
     
    				Random randomNumbers = new Random();	
    				move = (int)(randomNumbers.nextDouble() *9) +1;
    				row = (move - 1)/ board.length;
           			col = (move - 1) % board[row].length;
     
    			} while ((board[row][col] !=' '));
    			board[row][col] = 'X';
    		}
      	}
    	/*********************************************************************
    	 * Method Name:   printBoard
    	 * Parameters:    board
    	 * Returns:       NONE
    	 * Description:   Prints out the display of the board using nested for 
    	 * 				  loops.
    	 *********************************************************************/
        public static void printBoard(char[][] board) {
        	String VerticalDividers = "   |   |  ";
            String HorizaontalDividers = "------------";
     
        	System.out.println();
            System.out.println(" A" +"   B" +"   C");
     
            for (int i = 0; i < board.length; i++) {
            	int sideLegend= i+1;
            	System.out.println( VerticalDividers + "  " + sideLegend );            
                for (int j = 0; j < board[i].length; j++) {
                    System.out.print(" " + board[i][j] + "  ");
                    if (j < board[i].length - 1) {
                     } 
                    else {
                        System.out.println();
                     }
                }      
               if (i < board.length - 1) {
                    System.out.println(HorizaontalDividers);
                }
            }
            System.out.println();
        }
     
    	/*********************************************************************
    	 * Method Name:   MovesLeft	
    	 * Parameters:    board
    	 * Returns:       true/false
    	 * Description:   Searches the array to find any blank spaces. If there
    	 * 				  then it returns false so the program goes again.
    	 * 				  if it there are spaces, it'll return true so it'll stop 
    	 * 				  the game and searches for winning conditions.
    	 *********************************************************************/
        public static boolean MovesLeft(char[][] board) {
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[i].length; j++) {
                    if (board[i][j] == ' ') {
                        return false;
                    }
                }
            }
            return true;
        	}
    	/*********************************************************************
    	 * Method Name:   finalGame
    	 * Parameters:    board
    	 * Returns:       true or false
    	 * Description:   Uses isWinner to find whether or not the game is truly
    	 * 				  over for X/O.
    	 *********************************************************************/
        public static boolean finalGame(char[][] board) {
            return MovesLeft(board)
                    || checkingWinningCondition('X', board)
                    || checkingWinningCondition('O', board);
        	}
     
     
    	/*********************************************************************
    	 * Method Name:   checkingWinningCondition
    	 * Parameters:    player - player to find condition for
    	 * 				  board
    	 * Returns:       boolean value
    	 * Description:   Goes through all the possible winning conditions
    	 * 					Returns value true if condition is found.
    	 *********************************************************************/
        public static boolean checkingWinningCondition(char player, char[][] board) {
            // Checks Horizontal condition
            for (int row = 0; row < 3; row++) {
                if (board[row][0] == player && board[row][1] == player
                        && board[row][2] == player) {
                    return true;
                }
            }
            // Checks Vertical condition
            for (int col = 0; col < 3; col++) {
                if (board[0][col] == player && board[1][col] == player
                        && board[2][col] == player) {
                    return true;
                }
            }
            // Checks  Diagonals Condition
            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;
            }              
        }
     
        /*********************************************************************
    	 * Method Name:   Results
    	 * Parameters:    player(computer, 'O')
    	 * 				  move
    	 * 				  board
    	 * Returns:       none
    	 * Description:   Uses checkWinningCondition to check for winning condition
    	 * 				  If condition is found, it outputs it into text and ends the 
    	 * 				  input of user move at main. 
    	 *********************************************************************/
        public static void Results(char[][] board) {
            if (checkingWinningCondition('O', board)) {
                System.out.println("O is the winner!");
            	}
            else if (checkingWinningCondition('X', board)) {
                System.out.println("X is the winner!");
            } 
            else {
                System.out.println("The game is CAT!.");
            }
        }
     
     
    }
    Last edited by steel55677; July 4th, 2011 at 05:08 PM. Reason: Updating problem


  2. #2
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: TicTacToe 2D Array help

    Use the equals method not ==. This is asked and answered about 10,000 times a week

  3. The Following User Says Thank You to Junky For This Useful Post:

    steel55677 (July 4th, 2011)

  4. #3
    Junior Member
    Join Date
    Jun 2011
    Posts
    29
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: TicTacToe 2D Array help

    Thank you sir!

  5. #4
    Junior Member
    Join Date
    Jun 2011
    Posts
    29
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: TicTacToe 2D Array help

    Now I got a new problem can't seem to get my logic around it.

  6. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: TicTacToe 2D Array help

    Are you going to post your new problem? Or what happens now?

  7. #6
    Junior Member
    Join Date
    Jun 2011
    Posts
    29
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: TicTacToe 2D Array help

    My apologies, I edited in the original post but I'll say it here as well:

    The new problem is that the 'X' by the user will always override the 'O's by the computer. For example, if I place X at the top left corner [0][0] and then O is placed by the computer at the top right [0][3], I could still place X at that spot which results in 2 X's and 1 O's after my turn. I don't know how to solve this @main method and @MovesLeft or should I make another method and how to implement this into my logic, ugh...

  8. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: TicTacToe 2D Array help

    I could still place X at that spot
    Do you check if the square is occupied before allowing a move there?
    When the computer moves to a square that square should be marked as occupied.

  9. #8
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: TicTacToe 2D Array help

    Quote Originally Posted by steel55677 View Post
    I edited in the original post
    Please don't do that, as it makes the thread meaningless to other members who want to learn from it.

    The new problem is that the 'X' by the user will always override the 'O's by the computer. For example, if I place X at the top left corner [0][0] and then O is placed by the computer at the top right [0][3], I could still place X at that spot which results in 2 X's and 1 O's after my turn. I don't know how to solve this @main method and @MovesLeft or should I make another method and how to implement this into my logic, ugh...
    Why can't you just check to see if the position selected by the user already has an entry or not before accepting the selection? IOW only allow the user to select empty locations.

  10. The Following User Says Thank You to dlorde For This Useful Post:

    steel55677 (July 9th, 2011)

  11. #9
    Junior Member
    Join Date
    Jun 2011
    Posts
    29
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: TicTacToe 2D Array help

    Oh! The previous post was about comparing Reference to a String and I accidently used UserMove=="A1" instead of UserMove.equals("A1").

    and Okay, I tried using another method
     public static boolean Validation(char[][] board) {
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[i].length; j++) {
                    if (board[i][j] == 'O') {
                        return false;
                    }
                }
            }
            return true;
        	}
    so that it searches through the 2d array and finds filled 'O', and if it finds it it'll return false.

    Then i recalled it into my main method

      public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
     
            char[][] board = new char[3][3];
            char defaultPlayer = 'X';
            int currentMove = -1;
            boolean errorCheck;
     
            fillEmptySpaces(board, ' ');
     
            System.out.println("****************" );
            System.out.println("  Tic-Tac-Toe!" );
            System.out.println("****************");
            printBoard(board);
     
            while (!finalGame(board)) {
              	do {
     
            		errorCheck = true;
            		System.out.print("Please enter column[Letter] and row[#]: "  +currentMove);
                	String userMove = in.nextLine().toUpperCase();
                	{      	
            	 	if (userMove.equals("A1")){        	 		
            	 		currentMove = 1;
                	}
                	else	if (userMove.equalsIgnoreCase("A2")){
                		currentMove = 4;
                	}
                	else	if (userMove.equalsIgnoreCase("A3")){
                		currentMove = 7;
                	}
                	else	if (userMove.equalsIgnoreCase("B1")){
                		currentMove = 2;
                	}
                	else	if (userMove.equalsIgnoreCase("B2")){
                		currentMove = 5;
                	}
                	else	if (userMove.equalsIgnoreCase( "B3")){
                		currentMove = 8;
                	}
                	else	if (userMove.equalsIgnoreCase( "C1")){
                		currentMove = 3;
                	}
                	else	if (userMove.equalsIgnoreCase("C2")){
                		currentMove = 6;
                	}
                	else if (userMove.equalsIgnoreCase("C3")){
                		currentMove = 9;
                	}      	 
                	else if (Validation(board) == true){
                		System.out.println("That move is invalid! Please enter move again.");
     
     
                	}
                	else{
                		errorCheck = false;
                		System.out.println("That move is invalid! Please enter move again.");
                	}
                	}
     
            	} while(errorCheck == false);
              	Validation(board);
            	userMove(defaultPlayer, currentMove, board);
                computerMove(defaultPlayer, currentMove, board);
                printBoard(board);
     
            }
            Results(board);
        }

    so that else if (Validation(board) == false){
    System.out.println("That move is invalid! Please enter move again.");, it'll make it invalid. But it doesn't work . still does the same thing.

  12. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: TicTacToe 2D Array help

    Check where you placed this line:
    else if (Validation(board) == false){
    It is in a chain of if/else if statements.

    Shouldn't it be clear of them. Always Test for a legal move after the user enters his move.

  13. The Following User Says Thank You to Norm For This Useful Post:

    steel55677 (July 9th, 2011)

  14. #11
    Junior Member
    Join Date
    Jun 2011
    Posts
    29
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: TicTacToe 2D Array help

    Fixed it . Took about a week haha. but finally. I redone my validation method so that it searches through the entire array, then it finds the map of x's and O's and returns the value that it compares with it before all the if-else chains.
        /*********************************************************************
    	 * Method Name:   Validation
    	 * Paramenters: board, move, existingMove
    	 * Description:   It searches through the array after the user has 
    	 * entered the value and then finds if the position is filled. 
    	 * returns value in the map and puts it in the currentMove.
    	 * 
    	 *********************************************************************/
        public static char Validation(char[][] board,int move, char existingMove) {
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[i].length; j++) {
                    if (board[0][0] == 'X' ||board[0][0] == 'O' ) {                   	                	 
                       	return 1;                               
                  	}
                    else if (board[0][1] == 'X' ||board[0][1] == 'O' ) {                   	                	 
                       	return 2;                               
                  	}
                    else if (board[0][2] == 'X' ||board[0][2] == 'O' ) {                   	                	 
                       	return 3;                               
                  	}
                    else  if (board[1][0] == 'X' ||board[1][0] == 'O' ) {                   	                	 
                       	return 4;                               
                  	}
                    else if (board[1][1] == 'X' ||board[1][1] == 'O' ) {                   	                	 
                       	return 5;                               
                  	}
                    else if (board[1][2] == 'X' ||board[1][2] == 'O' ) {                   	                	 
                       	return 6;                               
                  	}
                    else if (board[2][0] == 'X' ||board[2][0] == 'O' ) {                   	                	 
                       	return 7;                               
                  	}
                    else  if (board[2][1] == 'X' ||board[2][1] == 'O' ) {                   	                	 
                       	return 8;                               
                  	}
                    else  if (board[2][2] == 'X' ||board[2][2] == 'O' ) {                   	                	 
                       	return 9;                               
                  	}
                }
            }     
     
            return existingMove = ' ';
        	}

  15. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: TicTacToe 2D Array help

    * returns value in the map and puts it in the currentMove.
      	return 1;    // This doesn't look like the value from the map
    ..
            return 2;    // ditto
    ..    
     return existingMove = ' ';   // why assign a value to a parameter? it goes away
    The comment and the return statements don't agree.

Similar Threads

  1. Replies: 2
    Last Post: May 13th, 2011, 03:08 AM
  2. [SOLVED] TicTacToe program - Space taken?
    By Actinistia in forum Java Theory & Questions
    Replies: 6
    Last Post: May 2nd, 2011, 11:06 PM
  3. TicTacToe
    By Zerro900 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 27th, 2011, 08:29 AM
  4. Tictactoe problem
    By Nostromo in forum What's Wrong With My Code?
    Replies: 0
    Last Post: March 26th, 2011, 03:38 PM
  5. i neeeed help in tictactoe in java !!
    By yinky in forum What's Wrong With My Code?
    Replies: 0
    Last Post: November 29th, 2009, 11:17 PM