Take Your Turn

The game of Tic-Tac-Toe, also called Noughts and Crosses, provides a fertile field to plow for any budding programmer. It involves a matrix (array), logic, decisions, and all sorts of fun. If you haven’t yet coded your own Tic-Tac-Toe game, I urge you to do so, but that’s not the topic for this month’s Exercise.

No, this month your task is to simulate a game of Tic-Tac-Toe. As an example, here is code that does a crude game simulation:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    char grid[9] = "         ";
    char token;
    int x;

    /* seed the randomizer */
    srand( (unsigned)time(NULL) );

    /* fill the grid */
    for(x=0;x<9;x++)
    {
        token = rand() % 2 ? 'x' : 'o';
        grid[x] = token;
    }

    /* display the grid */
    for(x=0;x<9;x+=3)
    {
        printf(" %c  %c  %c\n",
                grid[x],
                grid[x+1],
                grid[x+2]);
    }

    return(0);
}

Line 7 initializes the grid[] array, which is the game’s 3-by-3 matrix. Spaces represent un-played squares in the game.

The for loop at Line 15 fills the grid with a random 'x' or 'o' character. (The token variable isn’t really needed, but I find the ternary (?:) operator to be confusing, so I don’t like to over-code that statement.)

Finally, the for loop at Line 22 displays the grid[] matrix in a tic-tac-toe style.

Here’s sample output from the program:

 x  x  o
 x  x  x
 o  x  o

Does anything seem wrong with that output? Perhaps you’re a big brother and that’s the type of tic-tac-toe game you would play with your little sister when she didn’t understand the rules. Effectively, player X has allowed player O to play only every other turn. That’s not proper.

When the tokens are randomized, as is done in the sample code, the output can be anything. Theoretically, the board could show all 'x' tokens. That’s unrealistic because, in real life, X and O take turns. X places a token, then O places a token.

In an actual game simulation, token placement is made strategically, but that’s not your task for this month’s Exercise. Nope, your task is to re-code the “fill the grid” portion of the sample program so that the 'x' and 'o' tokens are placed one after the other; X plays first, then O, until the board is filled.

You cannot place a token in a square that already has a token. And you don’t need to worry about playing strategically or stopping the simulation when one player wins: Just fill the grid so that the output is more-or-less evenly split between 'x' and 'o' tokens.

Click here to read my solution, but please try the Exercise on your own before you take a peek at what I’ve done.

Leave a Reply