Hello, I am making a tictactoe project for my 1st year college and I am wondering how can I use 1d array for tictactoe?

for example) is it like

``````int row1[3] ={0,1,2,}
int row2[3] ={3,4,5}
int row3[3]={6,7,8}
``````

is it like this?

2
Contributors
2
Replies
29
Views
2 Years
Discussion Span
Last Post by invisal

Or you can use a single 1d array for TicTacToe.

``````  int rows[] =
{ 0, 0, 0,
0, 0, 0,
0, 0, 0 }
``````

0 means empty. 1 means player 1, and 2 means player 2.

For example, if a player 2 want to make move on row number 2 and column 1 (row and column must be between 0 to 2), you mark your `rows[2 * 3 + 1] = 2;`. In other word, `rows[row * 3 + col] = player_id;`.

A year ago, I also wrote an article about using only bits to representing the TicTacToe. It might be irrelevant to this question, but I think it is nice to share here for those who interests.

Using Bits for TicTacToe

Using bits to represent a Tic-Tac-Toe board is perfectly fine and is as easy and maintainable as using two dimensional array. Since there are only 8 possibilities for winning condition, you can just check the board against every cases.

``````1 0 0       0 1 0      0 0 1     1 1 1    0 0 0
1 0 0       0 1 0      0 0 1     0 0 0    1 1 1
1 0 0       0 1 0      0 0 1     0 0 0    0 0 0

0 0 0       1 0 0      0 0 1
0 0 0       0 1 0      0 1 0
1 1 1       0 0 1      1 0 0
``````

To keep the clean-ness of the code, try to abstract the implementation of the board away from the your game logic. It is easier to change the board implementation later if you dislike the bitboard representation.

``````class Board
{
private:
uint32_t board;

public:
Board() { board = 0; }

/* Check if there is any of our piece
placed in this (x, y) location */
bool Check(int x, int y) {
return (board & (1 << y * 3 + x)) > 0;
}

/* Make a move in this (x, y) location */
void Move(int x, int y) {
board = board | (1 << y * 3 + x);
}

/* Check if we have won */
bool IsWin()
{
return (board & 292) == 292 || (board & 146) == 146 ||
(board & 73) == 73 || (board & 448) == 448 ||
(board & 56) == 56 || (board & 7) == 7 ||
(board & 273) == 273 || (board & 84) == 84;
}
};
``````

Keep two boards for player 1 and player2.

``````Board player1;
Board player2;
``````

Check if (x, y) location is unoccupied

``````if (!player1.Check(x, y) && !player2.Check(x, y)) {
// unoccupied slot
}
``````

Check if player 1 has won

``````if (player1.isWin()) {
// player 1 has won.
}
``````

Edited by invisal

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.