CS 117, Introduction to Computer Science

Project 6: Tic-tac-toe

Overview

Write a program that will allow two users to play tic-tac-toe.

Details

The tic-tac-toe board contains nine squares, as show below with dots.

   .   .   .
   .   .   .
   .   .   .

The program should ask for moves alternately from player X and player O. The players enter their moves by entering the row and column number that they wish. Since the players of this game are probably not C++ programmers, the first row should be numbered 1 and the third row should be numbered 3 (ditto for the columns). After each move, the program should display the updated tic-tac-toe board with X's and O's in the appropriate position. If the move is invalid, or if the spot is already taken, the program should prompt again for the row and column. For example:

   X   .   X
   .   O   .
   .   .   .

The game should end when someone has won by getting three of their letter in a row, column, or diagonal, or there is nowhere else to go (in which case the game is a draw). X should always play first.

You should use a two-dimensional array (matrix) for storing the tic-tac-toe information in memory.
Suggestion: Use a 3 x 3 array of integers, and initialize all values to 0. Record an X with a 1, and an O with a -1. To test if someone has won, use loops to add all rows, columns, and diagonals. If any of them comes out to 3, X wins. If any comes out to -3, O wins.

Sample Run:

Welcome to tic-tac-toe!
X - Enter the row: 1
X - Enter the column: 3

   .   .   X
   .   .   .
   .   .   .

O - Enter the row: 3
O - Enter the column: 3

   .   .   X
   .   .   .
   .   .   O

X - Enter the row: 3
X - Enter the column: 3

That spot is already taken! Try again.

X - Enter the row: 3
X - Enter the column: 1

   .   .   X
   .   .   .
   X   .   O

O - Enter the row: 3
O - Enter the column: 2

   .   .   X
   .   .   .
   X   O   O

X - Enter the row: 2
X - Enter the column: 2

   .   .   X
   .   X   .
   X   .   O

X wins!

Thanks for playing.