Quantcast
Viewing latest article 12
Browse Latest Browse All 35

Answer by user2023861 for Tic Tac Toe in the Console

Why not store moves as a string of 0s and 1s instead of 9 properties? For instance this:

_ X __ X OX O _

could be represented as:

string xmoves = "010010100"string omoves = "000001010"

With this scheme, you can store all of the winning moves (there are only 8) in an array of strings:

string[] winningMoves = {"111000000","000111000", ... }

Then to check if x wins, you have a simple algorithm like this:

static bool IsWin(string moves, string[] winningMoves){    foreach (var item in winningMoves)    {        int count = 0;        for (int i = 0; i < item.Length; i++)        {            if (item[i] == '1'&& moves[i] == '1')            {                count++;                if (count == 3)                    return true;            }        }    }    return false;}

You'll need a function that checks if a move is possible. This is easy:

static bool CanMove(int index, string xmoves, string ymoves){    return xmoves[index] == '0'&& ymoves[index] == '0';}

Finally, to make a move, you need to do a little string concatenation:

static string Move(int index, string moves){    return string.Format("{0}1{1}", moves.Substring(0, index), moves.Substring(index + 1));}

I'd be tempted to store the moves in binary rather than a string so that I can utilize bit-level operations. This would make the code uglier however. For instance, CanMove would look like:

static bool CanMove(int index, int xmoves, int ymoves){    int bit = 1 << index;    return (xmoves & bit) == 0 && (ymoves & bit) == 0;}

Which I find much less intuitive.


Viewing latest article 12
Browse Latest Browse All 35

Trending Articles