TicTacToe:Stage One

On our first stage we need to construct the representation of the TicTacToe Board INSIDE the computer. Computers don't need paper, but they do need memory. Just like we organize our paper by drawing lines, we organize our computer's memory with data structures like Classes, Arrays and ArrayLists.

The Class below uses a 2-D array board. board[0][0] is the top left corner and board[2][2] is the bottom right. If a spot is free to be chosen by X or O, there is a zero there. If X chooses the center spot, then board[1][1] is set to 1. If O chooses the top right spot, then board[0][2]=-1.

You need to finish the three methods that check for a "Cat's Game" (no winner, no spaces availible) or a win from either X or O

For 8 points, use no loops. For 9 points use loops. For 10 points use embedded loops. For 11 points change the logic in the ConsoleTTT so you can play more than one game without restarting the main method.

The TTTBoard API


Class TTTBoard

java.lang.Object
 TTTBoard

public class TTTBoard
extends java.lang.Object

Class TTTBoard is one way to represent a tic tac toe board.

Version:
28 Oct 2007
Author:
Chris Thiel,OFMCap

Constructor Summary
TTTBoard()
          Constructor for objects of class TTTBoard
 
Method Summary
 boolean checkForCatsGame()
          checks for Cats Game by looking for board loctions that have a "0"
 boolean checkForOWin()
          checks for an O win by looking for one of 8 ways that there are 3 -1's in a row.
 boolean checkForXWin()
          checks for an X win by looking for one of 8 ways that there are 3 1's in a row.
 void clear()
          clear sets the board to the starting position
 int get(int row, int col)
          get returns the contents of a board position
 boolean set(int row, int col, int value)
          sets the contents of a board position to either 1 or -1
 java.lang.String showBoard()
          a "String-Graphics" represention of the entire tic tac toe board
 java.lang.String symbol(int row, int col)
          coverts the numerical contents of a board position to a String represention
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 


Class TTTBoard.java

/**
 * Class TTTBoard is one way to represent a tic tac toe board.
 * 
 * @author Chris Thiel,OFMCap
 * @version 28 Oct 2007
 */
public class TTTBoard
{
    /** instance variables - board 
     *
     * 1 = X's 
     * 0 = unchosen
     * -1= O's
     */
    private int [][] board;
    private final int X=1;
    private final int O=-1;

    /**
     * Constructor for objects of class TTTBoard
     */
    public TTTBoard()
    {
        // initialise instance variables
        board = new int[3][3];
        clear();
        
        
    }
    /**
     * clear sets the board to the starting position
     * 
     * */

 
 
    public void clear()
    {
        for (int row=0; row<3; row++) 
          for (int col=0; col<3; col++)
            board[row][col]=0;
    }
    /**
     * get returns the contents of a board position
     *
     * @param  row   the row position 
     * @param  col   the column position
     * @return    a 1 for an X, -1 for O, zero otherwise
     */
    
    
    public int get(int row, int col)
    {
        return board[row][col];
    }
    
     /**
     *  sets the contents of a board position to either 1 or -1
     *
     * @param  row   the row position 
     * @param  col   the column position
     * @param  value the choice (-1 for O, 1 for X)
     * @return  true if the choice was sucessfully made,
     * false if that position has alread been taken
     */
    public boolean set(int row, int col, int value )
    {
        if (board[row][col]==0)
        {
            board[row][col]=value;
            return true;
        } else         
        {
            return false;
        }
    }
    /**
     * checks for Cats Game by looking for 
     * board loctions that have a "0"
     */
    public boolean checkForCatsGame()
    {
        return false;
    }
    /**
     * checks for an X win by looking for 
     * one of 8 ways that there are 3 
     * 1's in a row.  For example:
     * board[0][0]+board[0][1]+board[0][2]==3
     */
    public boolean checkForXWin()
    {
        return false;
    }
    /**
     * checks for an O win by looking for 
     * one of 8 ways that there are 3 
     * -1's in a row.  For example:
     * board[0][0]+board[0][1]+board[0][2]==-3
     **/
    public boolean checkForOWin()
    {
        return false;
    }
    /**
     * a "String-Graphics" represention of the entire
     * tic tac toe board
     * 
     */
    public String showBoard()
    {
        String s;

        s ="";
        for (int row=0;row<3;row++)
        {
           
            for (int col=0;col<3;col++)
            {
              s+=" "+symbol(row,col);
              if (col<2) s+=" |";
            }
            if (row<2) s+="\n---+---+---\n";
        }
        return s;
    }
    /**
     * coverts the numerical contents of a board position
     * to a String represention
     * @param row the row position
     * @param col the colum position
     * @return an "X" "O" or a space
     */
    public String symbol(int row, int col)
    {
        String s=" ";
        if (board[row][col] > 0) return "X";
        if (board[row][col] < 0) return "O";
        return s;
    }
}

User Interface (UI)

For now, we'll make a simple console based UI that uses the scanner class. This one helps you practice counting from 0 to 2 rather than 1 to 3 (a great habit to develop in the wonderful world of Computer Science!). This UI (and this game!) is a bit "retro" so i couldn't resist this "retro" screen shot (green on black text only monitors were the IBM standard for years!)

click on the image for a Quicktime movie demo of the UI

ConsoleTTT.java


import java.util.Scanner;

public class ConsoleTTT
{
	// instance variables 
	public static TTTBoard b;
	private static boolean xTurn;
	private static int r,c,player;
	private static final int X=1;
	private static final int O=-1;
	private static Scanner keyboard;
	private static String message;
	
    private static void init()
    {
    	b=new TTTBoard();
    	xTurn=true;
    	keyboard=new Scanner(System.in);
    }
    private static int getChoice(String message)
    {
        String c;
        int i;
        do 
        {
          System.out.print (message+": ");  
          c=keyboard.nextLine();
          i=Integer.parseInt(c);
        }
        while (i<0 || i>2);
        return i;
    }
           
        
	public static void main(String[] args )
	{
	  init();
		
	  
	  while (!b.checkForCatsGame() && !b.checkForXWin() && !b.checkForOWin())
	  // (I bet you can use De Morgan's Laws to change the above and 
	  //               yet get the same effect here!)
	  {
		System.out.println(b.showBoard());
		if (xTurn) 
		{
		    message="X's turn: ";
		    player=X;
		}
		else 
		{
		    message="O's turn: ";
		    player=O;
		}
		do
		{
		    r=getChoice(message+"Choose row (0..2)");
		    c=getChoice(message+"Choose column (0..2)");
		} while (!b.set(r,c,player)); 
		xTurn=!xTurn; //change who's turn it is
	  }
	  // announce the outcome
	  if (b.checkForXWin()) System.out.println("X WINS");
	  if (b.checkForOWin()) System.out.println("O WINS");
	  if (b.checkForCatsGame()) System.out.println("TIE--CAT'S GAME");
	}
}

Other ideas to change the TTTboard Class

Other ideas to change the ConsoleTTT Class

For the future