Question

I am building a tic-tac-toe game and the table is displayed with numbers as place-holders for the characters X and O. I have no idea how to allow a user to select a number, and replace it with an X or O. I understand cin >>, but don't know how to use it in this scenario.

This is a very introductory program, and is for my programming class. I'm not asking for someone to code it for me, but I have no clue where to begin in doing this. If you can help, please keep it as beginner-oriented as possible, otherwise I won't be able to implement it into my program because it will look fishy.

This is my code as of now:

using namespace std;

int board[9] {
    1, 2, 3, 4, 5, 6, 7, 8, 9
};

void displayBoard(void) {
char index;
    cout << endl;
    cout << board[index] << "|" << board[index+1] << "|" << board[index+2] << endl;
    cout << "-----" << endl;
    cout << board[index+3] << "|" << board[index+4] << "|" << board[index+5] << endl;
    cout << "-----" << endl;
    cout << board[index+6] << "|" << board[index+7] << "|" << board[index+8] << endl;
    index = index + 9;
        cin >> board[index];


}

void playerInput(void) {

}
int main (int argc, char *argv[]) {
    displayBoard();


}
Was it helpful?

Solution

A better choice could be to display the board using an array of type char. And you can always convert the characters to integers, or use board's index if you need to use them for calculations(which I doubt you will have to).

 char board[9] {
        '1', '2', '3', '4', '5', '6', '7', '8', '9'
    };

if you need access to those integer values just use the board's index+1.

You can use this:

cin >> movePosition; 

to accept user's input. and when you need to edit the board just use:

   board[movePosition-1] = 'X';

or

   board[movePosition-1] = 'O';

This will now work as the array is of type char.

OTHER TIPS

The ASCII values of 1 through nine is 48 to onward. Use that values in the board. Print using cout<<(char)board[index]; When user enters a position, place X or O character in that index according to the player and display the board again.

int board[9] {
  48, 49..
};

cout<<(char) board[index];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top