Problem Set 4
Up Problem Set 0 Problem Set 1 Problem Set 2 Problem Set 3 Problem Set 4 Problem Set 5 Problem Set 6 Problem Set 7 Problem Set 8 Problem Set 9 Problem Set 10

 

Objects and Classes: The game of Tic-Tac-Toe

Due 11:59 Monday October 9

Write a program to simulate two players playing the game of Tic-Tac-Toe.  You should define the following two classes with their associated methods:

  1. The class Board (an object template) simulates a Tic-Toe-Toe board, and has the following public methods:
    bulletconstructor Board takes no arguments and returns an empty board (note: if you do this right, this constructor will not have to do anything at all!).
    bulletDisplay displays the board on the Console (see sample output below).
    bulletSetSquare takes three arguments: a character which is either 'O' or 'X', and two integers indicating the square in which to place the O or X, numbered like this:
                (0,0) (0,1) (0,2)
                (1,0) (1,1) (1,2)
                (2,0) (2,1) (2,2)
    bulletGetSquare takes two integers indicating row and column as above, and returns 'O', 'X', or ' ' (the latter is the space character, indicating that no one has played that square yet).
    bulletWinner takes no arguments and returns 'O' if O is a winner, 'X' if X is a winner, and ' ' if neither.
     
  2. The class Player (another object template) simulates a player, and has the following public methods:
    bulletconstructor Player takes a string argument for the name of the player, and either an 'O' or 'X' to indicate that s/he is playing O's or X's, respectively.
    bulletName returns the name of the player (a string).
    bulletMove takes a board object as an argument and modifies the board with the player's move recorded on it (i.e. its return type is void).  This move should be chosen randomly but should not overwrite any previous move!

Your top-level class containing the Main method should create two new Players and one Board, and simulate a game of Tic-Tac-Toe, displaying the board after each move (see below), and stopping when there is a winner.  The program should ask the user for the names of the two players, and at the end declare who the winner is, or "draw" if there is no winner.

Hint: Implement the random behavior by creating a single class variable (i.e. using the static keyword) that is bound to a fresh Random object shared by all Players.

Here is an example of a program in action:

Please type the name of the X player:  John
Please type the name of the O player:  Susan

---
---
O--

---
---
O-X

-O-
---
O-X

-O-
---
OXX

-O-
-O-
OXX

XO-
-O-
OXX

XOO
-O-
OXX

Susan wins!!

Solution.

 

Extra credit (probably extremely hard!):  Define a SmartPlayer class that has the identical interface as Player, except that it uses a winning strategy: that is, if it is allowed to go first, it will either win or draw, but will never lose!