# tic tac toe AI

• 12-04-2002
abrege
tic tac toe AI
How would I check if the user gets 3 in a row in a tic tac toe game? I'm stumped :mad:

Here is the code I have:

Code:

```#include <iostream> #include <time.h> #include <windows.h> using namespace std; void draw(char board[3][3]) {         for(int i = 0; i < 3; i ++)         {                 for(int t = 0; t < 3; t ++)                 {                         cout << board[i][t] << ' ';                 }                 cout << endl;         } } void moveEnemey(char board[3][3], char icon[2]) {         srand(time(NULL));         int i, t;         while(1)         {                 i = rand()%3;                 t = rand()%3;                 if(board[i][t] == '_')                 {                         board[i][t] = icon[1];                         break;                 }         } } int main() {         int input;         char icon[2] = { 'X', 'O' };         char board[3][3] =         {                 '_', '_', '_',                 '_', '_', '_',                 '_', '_', '_'         };         while(1)         {                 draw(board);                 cout << "\nMake your move: ";                 cin >> input;                 if(board[0][input - 1] != icon[1])                 {                         board[0][input - 1] = icon[0];                         moveEnemey(board, icon);                 }                 else cout << '\a';                 system("cls");         }         return 0; }```
• 12-04-2002
minesweeper
You want the code to step through and check all 8 possible rows of three in the grid. That's 3 horizontal, 3 vertical and 2 diagonal. As it does so, it needs to check for all 3 places being occupied by whichever piece the user is playing '0' or 'X'. You could either do this 'on the fly' and simply step through each route incrementing a counter and checking if the counter equals 3 at the end or maybe you will find it easier to load each 3 in a row path into a seperate array before checking the arrays. There are no doubt countless more and better ways to do it but these are 2 simple ones that spring to mind.
• 12-04-2002
Hammer
>>srand(time(NULL));
You should only call srand() once in your program, so move it to the start of main().
• 12-04-2002
abrege
Code:

```bool checkUserWin(char board[3][3], char icon[2]) {         int counter = 0, counter2 = 0;         while(counter2 <= 3)         {                 for(int i = 0; i < 3; i ++)                 {                         if(board[counter2][i] == icon[0]) counter ++;                 }                 if(counter == 3) return TRUE;                 counter = 0;                 counter2 ++;         }         return FALSE; }```
This code only accounts for the top row (board[0][i])...any reason why it would do this?
• 12-05-2002
abrege
Thanks, I got alot of of that!