Sign in to follow this  
Voley

c++ code question

Recommended Posts

Voley    122
I got this code and I can't understand what exactly it does. I think, there is a two dimensional array WINNING_ROWS, and the for cycle checks if it suits combinations in the array, but how exaclty is this happening? const int WINNING_ROWS[8][3] = { (0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6) } ; const int TOTAL_ROWS = 8; for (int row = 0; row < TOTAL_ROWS; ++row) { if ((board[WINNING_ROWS[row][0]] != EMPTY) && (board[WINNING_ROWS[row][0]] == board[WINNING_ROWS[row][1]]) && (board[WINNING_ROWS[row][1]] == board[WINNING_ROWS[row][2]])) { return board[WINNING_ROWS[row][0]]; } }

Share this post


Link to post
Share on other sites
CaspianB    309
From what I can tell from what you posted, it's a Tic-Tac-Toe game.

The WINNING_ROWS constant contains an array of the board positions for a winning game.

The Tic-Tac-Toe game is laid out like this:

0|1|2
-----
3|4|5
-----
6|7|8

{(0,1,2), (3,4,5), (6,7,8)} correspond to a horizontal win.
{(0,3,6), (1,4,7), (2,5,8)} correspond to a vertical win.
{(0,4,8), (2,4,6)} correspond to a diagonal win.

The board array likely stores an 'X' or an 'O'. The if structure checks if each one of the sets of positions above has all three values the same.

The odd thing about the code is that, if it finds a winning set, then it returns the position in the board corresponding to the first value in the WINNING_ROWS set. I would think you would want all three positions that create the win, or at least which row in the WINNING_ROWS array is a win.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this