problem with console tic tac toe

hi im making tic tac toe and i have ran into a problem. after the space is set i want to put in the code for the computer generating a random number. if the space isnt filled it will set the string to O(the computer). but how do i make it do this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
cout << space1 << "|" << space2 << "|" << space3 << endl;
    cout << "--" << "--" << "-" << endl;
    cout << space4 << "|" << space5 << "|" << space6 << endl;
    cout << "--" << "--" << "-" << endl;
    cout << space7 << "|" << space8 << "|" << space9 << endl;

    while (win == false)
    {
            cout << "Player is X, computer is O" << endl;
            cout << "enter 1,2,3,4,5,6,7,8, or 9: ";
            cin >> choice;

            system("CLS");

            if (choice == "1")
            {
                if(spacefill1 == 0)
                {
                    space1 = "X";
                    spacefill1 = 1;
Last edited on
Do you know how to use random numbers in C++? If not look up srand() and rand() in this website's library reference.
Anyway, what string are you setting to O and where is it? (I'd suggest that you construct the string based on what you randomized.)
yes i know how to use random numbers.(sorry made this post in school so i was rushed) im am trying to say if i hit one then in the if(spacefill1 == 0) (which means the space is empty), after the 2 statements the computer makes a random number. i want to make it so if the number that it picks(1-9) is taken up then it goes to another space and checks it until it finds a empty space.
I used smiley face characters to fill the empty spaces until they were selected by an 'X' or an 'O' : )
Last edited on
Use an array instead of spacex variables. http://www.cplusplus.com/doc/tutorial/arrays/
Don't use system(); http://www.cplusplus.com/forum/articles/11153/

If you use an array, you can iterate over it, index directly using numbers.
Some example :
1
2
3
4
5
6
7
8
9
char grid[3*3];
int choice;
while ( !cin >> choice || choice < 1 || choice > 9 ) {
 /* invalid input, be careful :
  * http://www.cplusplus.com/forum/articles/6046/
  */
}

grid[choice-1] = 'x';

After that you can generate a random number between 0 and 8 inclusive (remember array indexing starts at 0), and if it's occupied already then choose an other one somehow.
Last edited on
Topic archived. No new replies allowed.