Results 1 to 7 of 7
  1. #1
    zero2008 is offline Member
    Join Date
    Jan 2008
    Posts
    4
    Rep Power
    0

    Red face Tic Tac Toe Ggame Help (Begginer)

    My problem is that I am writing a tic tac toe game and I don't know how to check the 2d array for who has won or if it is a draw.
    I have included two java files which are fully working I just need to create a function to check for the winner or draw.

    TicTacToeTest.java

    PHP Code:
    import java.util.Scanner;
    
    public class TicTacToeTest
    {
    public static void main(String[] args)
    {
    Scanner in = new Scanner(System.in);
    String player = "x";
    TicTacToe game = new TicTacToe();
    boolean done = false;
    while (!done)
    {
    System.out.println(game.toString());
    System.out.println("");
    System.out.print(
    "Row for " + player + " (-1 to exit): ");
    int row = in.nextInt();
    if (row < 0) done = true;
    else
    {
    System.out.print("Column for " + player + ": ");
    int column = in.nextInt();
    game.set(row, column, player);
    if (player.equals("x"))
    player = "o";
    else
    player = "x";
    }
    }
    }
    }
    TicTatToe.java

    PHP Code:
    public class TicTacToe
    {
    /**
    Constructs an empty board.
    */
    public TicTacToe()
    {
    board = new String[ROWS][COLUMNS];
    // Fill with spaces
    for (int i = 0; i < ROWS; i++)
    for (int j = 0; j < COLUMNS; j++)
    board[i][j] = " ";
    }
    
    
    public void set(int i, int j, String player)
    {
    if (board[i][j].equals(" "))
    board[i][j] = player;
    }
    
    /**
    Creates a string representation of the board, such as return the string representation
    */
    public String toString()
    {
    System.out.println("");
    System.out.println("Valid inputs range from 0,0 to 2,2!");
    System.out.println("");
    String r = "";
    String str = "";
    str = str + "-------\n";
    for (int i = 0; i < ROWS; i++)
    {
    
    
    r = "|";
    for (int j = 0; j < COLUMNS; j++)
    str = str + r + board[i][j];
    str = str + "|\n";
    str = str + "-------\n";
    
    
    }
    
    return str;
    }
    
    
    
    private String[][] board;
    private static final int ROWS = 3;
    private static final int COLUMNS = 3;
    
    }
    P.S.
    I have also tried this but it just wont work.

    PHP Code:
    private boolean backDiagonalWinner() {
    char test = board[0][boardSize - 1];
    if (test == EMPTY)
    return false;
    for (int i = 1; i < boardSize; i++)
    if (test != board[i][boardSize - 1 - i])
    return false;
    winner = test;
    return true;
    }
    
    private boolean columnWinner(int col) {
    char test = board[0][col];
    if (test == EMPTY)
    return false;
    for (int i = 1; i < boardSize; i++)
    if (test != board[i][col])
    return false;
    winner = test;
    return true;
    }
    
    private boolean forwardDiagonalWinner() {
    char test = board[0][0];
    if (test == EMPTY)
    return false;
    for (int i = 1; i < boardSize; i++)
    if (test != board[i][i])
    return false;
    winner = test;
    return true;
    }
    
    private boolean rowWinner(int row) {
    char test = board[row][0];
    if (test == EMPTY)
    return false;
    for (int i = 1; i < boardSize; i++)
    if (test != board[row][i])
    return false;
    winner = test;
    return true;
    }
    
    private void setWinner() {
    if (winner != NOWINNER)
    return;
    if (forwardDiagonalWinner() || backDiagonalWinner())
    return;
    for (int i = 0; i < boardSize; i++)
    if (rowWinner(i) || columnWinner(i))
    return;
    if (numberMoves == boardSize*boardSize)
    winner = DRAW;
    }
    Any help would be appreciated. Thanks

  2. #2
    gibsonrocker800's Avatar
    gibsonrocker800 is offline Senior Member
    Join Date
    Nov 2007
    Location
    New York
    Posts
    143
    Rep Power
    0

    Default

    well there are several ways you can do this. one way, the more inefficient way, it to set up arrays for all of the possible wins, and check if the board is equal to any of these ways. This is a mediocre way of doing it. So, the way i would do it is add a method to TicTacToe called public boolean rowsWin() in which it checks if the player won in the rows (horizontally). You just set up a loop that iterates through the array and if the element of the current iteration is equal to "x", add it to an ArrayList of Strings. Then you check to see if the size of the ArrayList is equal to 3, and if so, return true. if not, they obviously didn't win, because the loop only adds an element if that element is "x". Do the same thing for the columns, but changing the structure of the array iteration. Then, make a method for finalWin() and say... if rowsWin and columnsWin() return true, then return true (they won). Now, i'm not going to provide code because i want to see if you can figure this out on your own, but you now have the general logic needed. Good luck!

  3. #3
    zero2008 is offline Member
    Join Date
    Jan 2008
    Posts
    4
    Rep Power
    0

    Default

    As you can see I did try but with no luck so if you can use my code and fix it so it works please help me. I really need it.

  4. #4
    gibsonrocker800's Avatar
    gibsonrocker800 is offline Senior Member
    Join Date
    Nov 2007
    Location
    New York
    Posts
    143
    Rep Power
    0

    Default

    Ok i just finished making the code, and it works great. But, i'm leaving it up to you to make it so that it checks for diagonal wins. (I don't want to just hand you code, i want to get you thinking, to see if you can understand what i did, and put it to use). Let me give you a hint, change the structure of the array iteration (as you can see i did, in the columnsWin(), instead of having board[i][j] i had board[j][i]). Without any further ado, here is your code, with the added methods. I also added to the Tester.

    Java Code:
    import java.util.ArrayList;
    public class TicTacToe
    {
    /**
    Constructs an empty board.
    */
    public TicTacToe()
    {
    board = new String[ROWS][COLUMNS];
    // Fill with spaces
    for (int i = 0; i < ROWS; i++)
    for (int j = 0; j < COLUMNS; j++)
    board[i][j] = " ";
    }
    
    
    public void set(int i, int j, String player)
    {
    if (board[i][j].equals(" "))
    board[i][j] = player;
    }
    
    public boolean gameOver()
    {
    	boolean finalBool = false; //This will be used to get the final decision
    	for(int i = 0; i <= 2; i++)
    		for(int j = 0; j <= 2; j++)
    		{
    			if(board[i][j].equalsIgnoreCase("x") || board[i][j].equalsIgnoreCase("o")) //if the board is full
    				finalBool = true;
    			else
    			{
    				finalBool = false;
    				break;
    			}
    		}
    	return finalBool;
    }
    public boolean rowsWin()
    {
    	ArrayList<String> list = new ArrayList<String>();
    	for(int i = 0; i <= 2; i++)
    	{
    		for(int j = 0; j <= 2; j++)
    			if(board[i][j].equalsIgnoreCase("x"))
    				list.add(board[i][j]);
    	}
    	
    	if(list.size() == 3) //This will return true if 3 x's have been added in the row
    		return true;
    	
    	return false;
    }
    
    public boolean columnsWin()
    {
    	ArrayList<String> list = new ArrayList<String>();
    	for(int i = 0; i <= 2; i++)
    	{
    		for(int j = 0; j <= 2; j++)
    			if(board[j][i].equalsIgnoreCase("x"))
    				list.add(board[j][i]);
    	}
    	
    	if(list.size() == 3)
    		return true;
    	
    	return false;
    }
    
    public boolean finalWin()
    {
    	if(gameOver())
    		if(columnsWin() && rowsWin())
    			return true;
    	return false;
    }
    /**
    Creates a string representation of the board, such as return the string representation
    */
    public String toString()
    {
    System.out.println("");
    System.out.println("Valid inputs range from 0,0 to 2,2!");
    System.out.println("");
    String r = "";
    String str = "";
    str = str + "-------\n";
    for (int i = 0; i < ROWS; i++)
    {
    
    
    r = "|";
    for (int j = 0; j < COLUMNS; j++)
    str = str + r + board[i][j];
    str = str + "|\n";
    str = str + "-------\n";
    
    
    }
    
    return str;
    }
    
    
    
    private String[][] board;
    private static final int ROWS = 3;
    private static final int COLUMNS = 3;
    
    }
    Java Code:
    import java.util.Scanner;
    
    public class TicTacToeTest
    {
    	public static void main(String[] args)
    	{
    		Scanner in = new Scanner(System.in);
    		String player = "x";
    		TicTacToe game = new TicTacToe();
    		boolean done = false;
    		while (!done)
    		{
    			System.out.println(game.toString());
    			System.out.println("");
    			System.out.print(
    					"Row for " + player + " (-1 to exit): ");
    			int row = in.nextInt();
    			if (row < 0) 
    			{
    				System.out.println("Thanks for playing!");
    				System.exit(0); // Do this so that, if they input -1, the program will exit
    				//as opposed to ending the loop, because, as you can see i have a statement after this
    				//loop that will not apply to the user if they enter -1.
    			}
    			else
    			{
    				System.out.print("Column for " + player + ": ");
    				int column = in.nextInt();
    				game.set(row, column, player);
    				if (player.equals("x"))
    					player = "o";
    				else
    					player = "x";
    				if(game.finalWin())
    				{
    					
    					done = true;
    				}
    			}
    		}
    		System.out.println(game.toString());
    		System.out.println("Game over, you win!!!");
    	}
    }

    So there you go, now add and implement a method diagonalWin(), it shouldn't be too hard.

  5. #5
    zero2008 is offline Member
    Join Date
    Jan 2008
    Posts
    4
    Rep Power
    0

    Default

    Thanks for the code how ever it compiles perfect but when I run the code it just goes in circles never stops. Do you know why?

  6. #6
    gibsonrocker800's Avatar
    gibsonrocker800 is offline Senior Member
    Join Date
    Nov 2007
    Location
    New York
    Posts
    143
    Rep Power
    0

    Default

    Hm, i dont know why. It works fine for me. I tested it a bunch of times, and when the user wins, it says "You won!" and exits. I'm really not sure man.

  7. #7
    zero2008 is offline Member
    Join Date
    Jan 2008
    Posts
    4
    Rep Power
    0

    Default

    Can you try this with your code for x: 0 0; 1 0; 2 0; or 2 0; 2 1; 2 2; and tell me what you get cos I get it going in circles.

    Also is the code which you have posted the same as the one you are running.

Posting Permissions

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