Followers 0

# Best way to traverse a 2d array to dertermine the winner in Tic-Tac-Toe

## 18 posts in this topic

I have created a 3x3 matrix for a tic tac toe game that stores the condition of the gameboard . Each cell  stores the value 1 if the particular place of the board is occupied with a circle or 2 if it's occupied with an X. What's the best way to determine the winner as in best way to traverse the matrix and find where there are 3 consecutive symbols of a kind ?

0

##### Share on other sites

Do it in the way that is easiest for you, the reader of the code, to understand.

Although a good idea would be to have +1 for O and -1 for X instead of 1 and 2, in that way you can sum up all 3 rows (in a loop), all 3 columns (in a loop) and both diagonals and if they sum to +3 O has a winning line, -3 means X has a winning line. You can exit the test early if you find a win for either player.

More sophisticated would be to use a bitboard but Alvaro will probably be along in a minute to boggle your mind with that idea ;)

Yeah thanks for the tip man and I wonder who Alvaro is and what he has to say haha !

For something as simple as this,I would go with simple brute force. After all, you only have to check 3 rows, 3 cols and 2 diagonals

Yeah that's what I thought first but I just wanted to know what other more formal methods there are out there.

Edited by AspiringDev
0

##### Share on other sites

I was just typing this, but now it's pointless: (or maybe not )

There aren't that many solutions, and the best way to represent one solution would be as 3x3 1-bit values. 3x3 = 9 bits, which easily fits in a short unsigned int (16-bits).

You can also represent your existing values like this, by using  two short unsigned int - one for O/X stored in the 9 slots, and a mask where 0 means that the slot wasn't filled yet, and 1 means that the slot was filled with the value from the O/X int. As players fill in the slots, you set the bits (using logical or) accordingly, and you can then detect if the game ends by checking if the lower 9 bits in the mask are set. If they are, you just compare the O/X int against a list of solutions (ints).

Reference: http://xkcd.com/832/ :D

Edited by tonemgub
2

##### Share on other sites

More sophisticated would be to use a bitboard but Alvaro will probably be along in a minute to boggle your mind with that idea ;)

Coming through! But not with bitboards. For tic-tac-toe, I posted a much better solution a couple of years ago.

WOW I'm left speechless. I hope I will implement it the right way ! Can't thank you enough !

I was just typing this, but now it's pointless: (or maybe not )

There aren't that many solutions, and the best way to represent one solution would be as 3x3 1-bit values. 3x3 = 9 bits, which easily fits in a short unsigned int (16-bits).

You can also represent your existing values like this, by using  two short unsigned int - one for O/X stored in the 9 slots, and a mask where 0 means that the slot wasn't filled yet, and 1 means that the slot was filled with the value from the O/X int. As players fill in the slots, you set the bits (using logical or) accordingly, and you can then detect if the game ends by checking if the lower 9 bits in the mask are set. If they are, you just compare the O/X int against a list of solutions (ints).

Very helpful explanation my friend. Really I couldn't think that a problem of this kind could have a more sophisticated solution than the normal traversal methods and brute forcing .

Again thanks both of you !

0

##### Share on other sites

A simple brute-force optimization that came to mind when reading the title was:

(

1,2,3,
4,5,6,
7,8,9

)

For each cell, you can perform 3 checks: Horizontal (H), Vertical (V) and Diagonal (D(D1, D2))

But not all checks are needed for each cell, so lets see:

Cell 1: H, V, D1
Cell 2: V
Cell 3: V, D2
Cell 4: H
Cell 5: -
Cell 6: -
Cell 7: H
Cell 8: -
Cell 9: -

In case its not clear:
Cell 2: H is not needed because its covered by Cell1-H and D is simply not possible

Cell 5: H is covered by Cell4-H, Diagonals are covered by Cell1-D1 and Cell3-D2 and V is covered by Cell2-V

So this leaves you with 3x H, 3x V and 2x D checks ~ 8x Checks in total, which is much less then 36x Checks

Ofc the other solutions are much more elegant (referring to the one suggested at #5)

Edit: Oh and ofc, the traversal itself could look like this:

// Horizontal
for (int i = 0; i < 3; i++)
... field[(pos.x + i) % 3, pos.y] ...

// Vertical
for (int i = 0; i < 3; i++)
... field[pos.x, (pos.y + i) % 3] ...

// Diag 1
for (int i = 0; i < 3; i++)
... field[(pos.x + i) % 3, (pos.y + i) % 3] ...

// Diag 2
for (int i = 0; i < 3; i++)
... field[(pos.x - i) % 3, (pos.y + i) % 3] ...

Im not sure about whether C++ % (mod) handles negative numbers mathematically correctly..

Edited by Aphton
1

##### Share on other sites

Im not sure about whether C++ % (mod) handles negative numbers mathematically correctly..

After a four-hour debugging session a year or two ago, the answer to that is: No, it does not.

1

##### Share on other sites

More sophisticated would be to use a bitboard but Alvaro will probably be along in a minute to boggle your mind with that idea ;)

Coming through! But not with bitboards. For tic-tac-toe, I posted a much better solution a couple of years ago.

As the game only has 8 solutions, storing them as bit flags seems quite reasonable. I like it.

1

##### Share on other sites

While the solutions posted here are really interesting, is it really the best thing to tell a beginner to use low level bit operations to check if someone wins at tic-tac-toe?  I would recommend just iterating through the board, checking each of the possibilities (as already mentioned, 3 horizontal, 3 vertical, and two diagonal).  Once that is working, then you can start to try to optimize the solution (i.e. create separate functions for each type of check, build incremental lists of winning moves, or whatever).

However, all of those are just for learning - I can't believe that a check that is done once for each of the 9 moves in a game is really a candidate for doing abstract optimizations...

2

##### Share on other sites

While the solutions posted here are really interesting, is it really the best thing to tell a beginner to use low level bit operations to check if someone wins at tic-tac-toe?  I would recommend just iterating through the board, checking each of the possibilities (as already mentioned, 3 horizontal, 3 vertical, and two diagonal).  Once that is working, then you can start to try to optimize the solution (i.e. create separate functions for each type of check, build incremental lists of winning moves, or whatever).

However, all of those are just for learning - I can't believe that a check that is done once for each of the 9 moves in a game is really a candidate for doing abstract optimizations...

I have written code for a lot of board games. The first thing I do is come up with a board representation, a move representation, and functions to make moves, undo moves, generate moves and check for end-of-game conditions.

If you are writing a GUI where these things will only be needed once per move in a game, you normally don't have to think about it too hard, and any naive implementation will do.

But if you are writing any type of AI, you are going to have to consider gazillions of moves internally, whether you are using minimax, MCTS or something else. The performance of those basic routines really does matter, and there are clever implementations to be found for pretty much every game I can think of.

Tic-tac-toe is a learning tool, and it's a good opportunity to learn how to think of these clever implementations as well.

EDIT: One more thing: This is not the "For Beginners" forum. The thread I linked to was in "For Beginners", and I was reluctant to describe the fancy bit-manipulation method there. Edited by Álvaro
1

##### Share on other sites

For something as simple as this,I would go with simple brute force. After all, you only have to check 3 rows, 3 cols and 2 diagonals

One simple optimization of that is that, if you're checking after every move, you only need to check the winning patterns that involve the cell just played, which reduces it to checking just 1 row, 1 column, and 0 to 2 diagonals after every move.
1

##### Share on other sites

While the solutions posted here are really interesting, is it really the best thing to tell a beginner to use low level bit operations to check if someone wins at tic-tac-toe?  I would recommend just iterating through the board, checking each of the possibilities (as already mentioned, 3 horizontal, 3 vertical, and two diagonal).  Once that is working, then you can start to try to optimize the solution (i.e. create separate functions for each type of check, build incremental lists of winning moves, or whatever).

However, all of those are just for learning - I can't believe that a check that is done once for each of the 9 moves in a game is really a candidate for doing abstract optimizations...

I have written code for a lot of board games. The first thing I do is come up with a board representation, a move representation, and functions to make moves, undo moves, generate moves and check for end-of-game conditions.

If you are writing a GUI where these things will only be needed once per move in a game, you normally don't have to think about it too hard, and any naive implementation will do.

But if you are writing any type of AI, you are going to have to consider gazillions of moves internally, whether you are using minimax, MCTS or something else. The performance of those basic routines really does matter, and there are clever implementations to be found for pretty much every game I can think of.

Tic-tac-toe is a learning tool, and it's a good opportunity to learn how to think of these clever implementations as well.

EDIT: One more thing: This is not the "For Beginners" forum. The thread I linked to was in "For Beginners", and I was reluctant to describe the fancy bit-manipulation method there.

That is a completely valid point - I was just making an observation based on the nature of the question from the OP.  Like I said, you solutions are really interesting, and they may just be what the OP was asking for.  I just thought for the game at hand it was slightly more than what was required.

1

##### Share on other sites

Well I started the thread to check if there are some more efficient and somewhat complicated methods to approach this particular problem so I can broaden my horizons about efficient problem solving. I'm quite ashamed to say that the truth is I had a hard time understanding most of the posts here but they were good head scratchers for sure despite my lack of knowledge on bitwise operations. I used the usual check with loops and the game works perfectly now so at least I had that. Probably I brought more hassle to you who post all these great methods and explanations and I feel kinda bad that I didn't manage to implement them or even understand them fully but you helped me by showing me interesting things I could never have thought by myself. So...sorry if my question bothered you too much and brought the work on you to explain things but at the same time thank you for being awesome with your  programming magic you showed me !

0

##### Share on other sites

So...sorry if my question bothered you too much and brought the work on you to explain things but at the same time thank you for being awesome with your programming magic you showed me !

Don't worry about it... We enjoy bragging about our programming magic skills... :)

The bitwise operations are basically the same as brute force anyway - the only difference is that they work at the bit-level.

1

##### Share on other sites

Also, even if you don't understand it all right now, it can still be used as a reference later on.

And it might help others who just lurk or happen to google the same problem.

1

## Create an account

Register a new account