# Thread: Tic Tac Toe comp move

1. ## Tic Tac Toe comp move

Hey guys I am making a tic tac toe game and it is 90% finished, but I am not
allowed to use classes.

The problem I have is on the computer move. If the computer hit's a sqaure the
player has already chosen, would it be wise to use a recursive step to pick
another square that is empty?

This is the code for a the [0][0] sqaure on the computer move:

Code:
// function to simulate the computer's move
void computerMove ( char brd[][ 3 ], const char *let, const char *cmp ) {
int choosePos = ( 1 + rand() % 9 );

switch ( choosePos ) {
case 1:
{
if ( brd[ 0 ][ 0 ] == *let ) {
}

brd[ 0 ][ 0 ] = *cmp;
}
break;
The code to exexute this would be placed within the "if statement" that
is checking if the player already exisits there. Or instead of recursion would
a true false loop be advisable?

When I compile and run the code as it is I win since it isnt finished .

2. What you want is the minimax algorithm. Look it up

3. And you'll probably win every time, since there is NO LOGIC to the computer move. Shouldn't the move be based on whether there is a move to block the opponent, if necessary? And if a block is not in order, what square would be best for the computer turn? You need some logic to pick the BEST square for the computer move.

4. Well, I would say that recursion is wrong here. You might get the same number a lot of times and have a stack overflow. It is a possibility, maybe rare, but it exists so its wrong.

Use a while loop:
Code:
int choosePos;
while(1)
choosePos = ( 1 + rand() % 9);
switch(choosePos)
{
case 1:
if ( brd[ 0 ][ 0 ] != *let)
brd[ 0 ][ 0 ] = *cmp;
...
}
EDIT: Of course you can do this simpler without a switch statement. Like
Code:
while(1) {
x = rand() % 3;
y = rand() % 3;
if (brd[x][y] != *let) {
brd[x][y] = *cmp;
break;
}
}
and checking of course BEFORE if the game has finished in order not to get a deadlock...

5. You should use a self organizing map to let teh computer learn to play the correct moves. Obviously it can only make moves that are legal, but since it will never try these if they arent presented as options, you dont have to worry about it chosing illegal moves.

I am assuming this is a homework assignment, so check with the instructor if you can use structs, as a struct under c can also have member functions similar to a class, but its not a class.

6. Thank you guys for the tips and advice. All noted and very much appriciated