Question

I've created a TTT game. However I'm having trouble with the AI taking spots. How do I avoid this from happening so that in the chooseCellRow:Col method it only returns a random spot that has not already been selected by either player?

- (void) chooseCellRow:(NSInteger)row Col:(NSInteger)col
{
    //pick random spot for computer's turn
    row = random()%2;
    col = random()%2;

        if (row == 0 && col == 0) {
            [but00 setTitle:@"X" forState:0];
        }
        else if (row == 0 && col == 1) {
            [but01 setTitle:@"X" forState:0];
        }
        else if (row == 0 && col == 2) {
            [but02 setTitle:@"X" forState:0];
        }

        else if (row == 1 && col == 0) {
            [but10 setTitle:@"X" forState:0];
        }
        else if (row == 1 && col == 1) {
            [but11 setTitle:@"X" forState:0];
        }
        else if (row == 1 && col == 2) {
            [but12 setTitle:@"X" forState:0];
        }

        else if (row == 2 && col == 0) {
            [but20 setTitle:@"X" forState:0];
        }
        else if (row == 2 && col == 1) {
            [but21 setTitle:@"X" forState:0];
        }
        else if (row == 2 && col == 2) {
            [but22 setTitle:@"X" forState:0];
        }
}
Was it helpful?

Solution

Cheating is a moral concept, one which doesn't apply to the computer since it's doing exactly what you've told it to do. However, you could prevent this by simply choosing again if the cell is already occupied, pseudo-code:

row = random() % 3;
col = random() % 3;
while cell[row][col] != empty:  # Add your REAL detection code here.
    row = random() % 3;
    col = random() % 3;

You'll also notice that the above code stops you from cheating as well. Shame on you for only allowing the computer to choose four of the nine possibilities :-)

Applying % 2 to a number will give you 0 or 1, you need to use % 3 to allow for 2 as well.


Based on your comments that you have a cell array which contains the character occupying that cell, the code to continuse until you find a blank cell would be along the lines of:

do {
    row = random() % 3;
    col = random() % 3;
} while (cell[row][col] != ' ');

OTHER TIPS

One easy way would be to keep a list of unused positions and choose from that list. When either player moves, remove the position they choose from the list.

Another, even simpler but less efficient way is to have it choose any position, but try again if the spot it picks is already occupied.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top