Dec 4, 2013 at 6:58am UTC
#include <iostream>
#include <vector>
using namespace std;
const bool CLEAR_SCREEN = true;
/// @brief Utilizes an escape character sequence to clear the screen
void clearScreen()
{
cout << endl;
if (CLEAR_SCREEN)
{
cout << "\033c";
}
cout << endl;
}
void drawBoard(const vector < char >&board)
{
clearScreen();
for (int i = 0; i < 9; i += 3)
{
cout << " " << board.at(i) << " | " << board.at(i + 1) << " | "
<< board.at(i + 2) << " " << endl;
if (i < 6)
cout << "-----|-----|-----" << endl;
}
cout << endl;
}
void initVector(vector<char> &v)
{
string mapA = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < v.size(); i++)
{
v.at(i) = mapA.at(i);
}
}
int convertPosition(char position)
{
string mapA = "abcdefghijklmnopqrstuvwxyz";
return mapA.find(position);
}
bool validPlacement(const vector <char> &board, int position)
{
if (position > 8 || position < 0 ||
board.at(position) == 'X' || board.at(position) == 'O')
{
return false;
}
else if (position <= 8 || position >= 0)
{
return true;
}
}
bool gameWon(const vector <char> &board)
{
return true;
}
bool boardFull(const vector <char> &board)
{
return true;
}
int getPlay(const vector <char> &board)
{
char play;
cout << "Please choose a position: ";
cin >> play;
cout << endl;
int pos = convertPosition(play);
if (validPlacement(board, pos))
{
return pos;
}
}
const int PLAYER1 = 0;
const int PLAYER2 = 1;
int main()
{
vector <char> board(9);
int curPlay;
int turn = PLAYER1;
initVector(board);
drawBoard(board);
getPlay(board);
return 0;
}
Above is my code for a tic tac toe game with 2 players. I can't seem to get a handle on these problems with these functions:
1) validPlacement: What if both players use the same letter 'o' or 'x'? I need it to make validPlacement false.
2) gameWon: What if the board is only partially filled or there is no row for a winner? I need it to be false.
Dec 4, 2013 at 11:14am UTC
What if both players use the same letter 'o' or 'x'?
It doesn't matter within this function. You just ckeck whether a placement could be done or not. The player doesn't even have the choice what symbol he want. You don't make a placement.
What if the board is only partially filled or there is no row for a winner?
you need to check whether a symbol is set three times in a row horizontally, vertically, or diagonally
validPlacement() has a potential crash. Better check the position before you use it:
1 2 3 4 5 6 7 8 9
bool validPlacement(const vector <char > &board, int position)
{
if (position > 8 || position < 0)
return false ;
else if (board[position] == 'X' || board[position] == 'O' ) // vector has []
return false ;
return true ;
}
Last edited on Dec 4, 2013 at 11:16am UTC
Dec 4, 2013 at 12:52pm UTC
I've noticed another issue when I compiled it. The board is displayed with its positions. I type in one of them (a - I), and then the game ends.
Dec 5, 2013 at 8:48am UTC
you need a loop around drawBoard()
and getPlay()
that goes as long as not gameWon and not boardFull