Search code examples
c#stringunity-game-enginetic-tac-toe

Replace single character in a String


So, I'm using unity and I have this string that contains the current state of a tic-tac-toe board. It looks like that:

XOX
ONX
OXX

"N" being a neutral space.

The thing is I want to replace one of those "N" with either an "X" or an "O". I tried using :

board[n] = "X";

but i get

"property or indexer cannot be assigned, it is read only"

So I'm trying to figure a way to change one of those "N". Here is my code

if (manager.turn == 1 && !isUsed)
{
    xSprite.enabled = true;
    manager.board[int.Parse(gameObject.name)-1] = 'X';
    manager.GameEndingDraw();
    isUsed = true;
    manager.turn = 2;
}
else if (manager.turn == 2 && !isUsed)
{
    oSprite.enabled = true;
    manager.board[int.Parse(gameObject.name)-1] = 'O';
    manager.GameEndingDraw();
    isUsed = true;
    manager.turn = 1;
}

Solution

  • A Tic-Tac-Toe board is not a string, it is a 3×3 grid of markers such as chars. You should represent it as an array, not a string:

    var board = new char[3, 3];
    for (int i = 0; i < board.GetLength(0); i++)
        for (int j = 0; j < board.GetLength(1); j++)
            board[i, j] = 'N';
    

    Then you can set each marker by its coordinates:

    board[0, 0] = 'X';