HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Tic-Tac-Toe in C++11 - follow-up

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
tacticfollowtoe

Problem

This is based on my first Tic-Tac-Toe game:

Tic-Tac-Toe in C++11

I have come up with different game logic for my game. I would like to know which one is more reliable and effective and how I can improve the whole game.

```
#include
#include
#include
#include
#include
#include

class TicTacToe
{
public:
bool isFull() const;
void draw() const;
void turn(char player);
bool check(char player) const;

private:
bool fill(char player, int position);

static const std::size_t mDim = 3;
std::array grid
{
{
'-', '-', '-',
'-', '-', '-',
'-', '-', '-'
}
};
};

template
struct column : public std::unary_function
{
column(int i)
: colNum(i)
{}

bool operator() (int number)
{
return (number % dim == colNum);
}

int colNum;
};

struct pairCondition
{
int number;
char name;

pairCondition(int number, char name)
: number(number), name(name)
{}

bool operator== (const pairCondition& s) const
{
return name == s.name;
}
};

bool checkCondition(const pairCondition& i, const std::array& a, char player)
{

if (i.number == a[0] || i.number == a[1] || i.number == a[2])
return i.name == player;
else
return i.name != player;

}

bool TicTacToe::fill(char player, int position)
{
if (grid[position] != '-')
return false;
grid[position] = player;
return true;
}

bool TicTacToe::isFull() const
{
return 0 == std::count_if(grid.begin(), grid.end(),
[](const char& i)
{
return i == '-';
});
}

bool TicTacToe::check(char player) const
{
typedef std::function func;

// rows
bool row1 = true, row2 = true, row3 = true;

std::array rows1 = { 0, 1, 2 };
std::array rows2 = { 3, 4, 5 };
std::array rows3 = { 6, 7, 8 };

func rowf1 = std::bind(&checkCondition, std::placeholders::_1, rows1, player);
func rowf2 = std::bind(

Solution

Your check() is still completly hardcoded to have a dimension of 3x3. I think it's even worse, as in more hardcoded, than the previous one.

Your class has a constant mDim. Define your rows, columns and diagonals using that constant. The number of rows and collumns is determined by mDim. Also the length of each row, column and diagonal is determined by 'mDim'.

The same goes for checkCondition(). The 3 is hardcoded but should be governed by mDim.

Try making mDim selectable in the constructor and play a standard 3x3 game of Tic-Tac-Toe and a larger 4x4 game of Tic-Tac-Toe-Tuz to see if you have have removed the hardcoded 3 everywhere.

If you want to go one step further you could remove the hardcoding of the board being a square and the board being 2 dimensional. Ever played 3D Tic-Tac-Toe?

Context

StackExchange Code Review Q#70650, answer score: 5

Revisions (0)

No revisions yet.