This is an old revision of the document!
Tic-Tac-Toe: 2D array
This will be a text based implementation but would be easy to port into a graphic based version. The String player will hold a space, an X, or an O.
- Complete the constructor so the board can be any size, not just 3 by 3. Read the comments for details. Remember that once you make a new array, you still have to initialize each String with a space.
- Complete the
changePlayermethod. If player is “O”, then it should change to an “X” and vice versa. - Complete the
markmethod, that only replaces the grid location with the letter stored inplayerif it currently has a space. call thechangePlayermethod (Don't reduplicate code inside themarkmethod). - complete the
getPlayermethod, so a client class can see who's turn it is - Make the
getGridmethod that returns the 2D grid so a client class can access the board. - Make a method called
movesRemainingthat returns the number of spaces ingrid. Try using a nested enhanced (“for-each”) for loop to count how many spaces are in the grid. - write a main method that makes an instance of the TicTacToe2 class and the calls the
printmethod:
public static void main(String[] args)
Now you can test your code with TicTacToeTexGame.java to see if you can put “X” and “O” in all the squares. Try making sure it does not allow someone to overwrite a square that already has an “X” or a “O” in it.
At this point you have not implemented the winner() method. Without completing the winner() method, it will always say that the game ends with no moves left, an no winner (a “Cat's game).
Next we can work on the TicTacToe2 method winner. Use the WinnerTester class to check your progress with the winner() method of the TicTacToe2 class. You need to check the rows, the columns, and the 2 diagonals. You can simply count how many times the grid contains the player letter in a row or column or diagonal, and if the total matches the size, we have a winner.
Now What?
- Make a game where the user plays against a computer player
- Try using this to make an |Ultimate Tic-Tac-Toe
