Our assignment was to write a tic-tac-toe program for my programming class.
It is person vs. computer and the computer makes "random" moves, even if computer is going to lose they will choose a random place to put their x or o
it is all correct, now what I have to do is modify the program so the computer plays "smart", and by smart i mean blocking the player from making a 3 of a kind, etc.
so I have no idea how to do that
here is my program now:
#include <iostream>
using namespace std;
void clearBoard(int board[]);
void drawBoard(int board[]);
int getPlayerMove(int player);
int makeRandMove(int player);
bool isMoveValid(int boardp[], int move);
bool isaWin(int board[], int move);
const int board_size = 9;
int main()
{
int board[board_size];
int turn = 0;
int move = 10;
srand(time(0));
clearBoard(board);
while(!isaWin(board, move)){
drawBoard(board);
if(2 == turn)
turn = 1;
else
turn = 2;
do {
if(2 == turn)
move = getPlayerMove(turn);
else
move = makeRandMove(turn);
} while(!isMoveValid(board, move));
board[move] = turn;
}
drawBoard(board);
cout << "Player " << turn << " wins." << endl;
return 0;
}
void clearBoard(int board[])
{
int i;
for(i = 0; i < board_size; ++i) {
board[i] = -i - 1;
}
}
void drawBoard(int board[])
{
int i, j;
for(i = 0; i <= 6; i = i+3) {
for(j = 0; j < 3; ++j) {
if(board[i + j] == 2)
cout << "X";
else if(board[i + j] == 1)
cout << "O";
else
cout << "_";
}
cout << endl;
}
}
int getPlayerMove(int player)
{
int move;
cout << "Player " << player << " enter move: ";
cin >> move;
return move;
}
int makeRandMove(int player)
{
cout << "Computer (player " << player << ") moving." << endl;
return rand() % board_size;
}
bool isMoveValid(int board[], int move)
{
if(board[move] < 0)
return true;
return false;
}
bool isaWin(int board[], int move)
{
if((board[0] == board[1] && board[0] == board[2]) ||
(board[3] == board[4] && board[3] == board[5]) ||
(board[6] == board[7] && board[6] == board[8]) ||
(board[0] == board[3] && board[0] == board[6]) ||
(board[1] == board[4] && board[1] == board[7]) ||
(board[2] == board[5] && board[2] == board[8]) ||
(board[0] == board[4] && board[0] == board[8]) ||
(board[2] == board[4] && board[2] == board[6]))
return true;
return false;
}