Two
Dimensional Arrays (courtesy of Dr. Huo)
The
following program is the base for the game: tic-tac-toe. Don’t modify the structure
of the main program. Complete three parts as required. Compile and run this
program, and then you can play the game. Have fun!
#include<iostream>
using namespace std;
const int DIM=3;
int main()
{
int row, col;
int blanks=DIM*DIM;
char chessboard[DIM][DIM];
bool putchecker;
int count1=0, count2=0, count3=0,
count4=0;
//initChessBoard
//set all the elements of the ChessBoard to blanks
//Complete this part
//printChessBoard
//print all the elements of the chessBoard with each row in
one line
//Complete this part
char cur='O';
cout<<"Input position(row col)or(-1 -1) to exit; It is the
turn of " <<cur<<endl;
cin>>row>>col;
while(row!=-1 && col!=-1)
{
//complete this part
/* if i and j are not out of bound(that is, i and j are in
the range of 0 and DIM-1)
and
chessboard[i][j] is not occupied(that is, the value of chessboard[i][j] is
blank),
set
chessboard[i][j] to be the value of cur and set putchecker to true. Otherwise,
set putchecker to false.*/
if(!putchecker)
{
cout<<"Invalid move"<<endl;
}
else
{
--blanks;
// print ChessBoard
/* We declare four variables count1, count2, count3, count4
to represent
the occurrence number of x in row number row, column number col,
in the main
diagonal, and in the opposite diagonal. If after calculation, count1,
count2, count3
or count4 equals to DIM cur wins*/
for(int i=0;
i<DIM; ++i)
{
//complete the following
// if the element in position (row, i) is cur, count1 is
increased by 1.
// if the element in position (i, col) is cur, count2 is
increased by 1.
/* if x is in the main diagonal, and the element in
position (i, i) is cur, count3 is increased by 1.*/
/* if x is in the opposite diagonal, and the element in
position (i, DIM-1-I) is cur, count4 is increased by 1.*/
}
if(count1 == 3 || count2 == 3 || count3 == 3 ||
count4 == 3)
{
cout<<
cur << " Wins"<<endl;
return 0;
};
if(blanks==0)
{
cout<<
"Ties"<<endl;
return 0;
}
if(cur=='X')
cur= 'O';
else cur='X';
}
cout<<"Input position(row col) or(-1 -1) to exit; It is
the turn of" <<cur<<endl;
cin>>row>>col;
}
}