public delegate void AIPlayer(byte[,] gameState, byte currentPiece, out byte row, out byte column);
public static void Main()
byte[,] gameState = new byte[3,3] { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} };
byte row = 0, column = 0;
bool isGameComplete = false;
AIPlayer[] players = new AIPlayer[2]{ null, null };
players[0] = GetNextTurn;
PrintGameBoard(gameState);
if (players[currentPiece-1] != null)
Console.WriteLine("Computer AI making selection for {0}.", GetXO(currentPiece));
players[currentPiece-1](gameState, currentPiece, out row, out column);
Console.WriteLine("Make your selection for {0} or enter 'q' to quit.", GetXO(currentPiece));
response = Console.ReadLine();
Console.WriteLine("That is an invalid entry. Try again.");
if( gameState[row,column] != 0)
if (players[currentPiece-1] != null)
Console.WriteLine("AI error -- invalid selection");
Console.WriteLine("You cannot place your piece there!");
gameState[row,column] = currentPiece;
PrintGameBoard(gameState);
isGameComplete = IsGameComplete(gameState, out winner);
if (winner == 0 && isValidTurn)
Console.WriteLine("It's a draw!");
Console.WriteLine("And the winner is: {0}!", GetXO(winner));
Console.WriteLine("Have a great day!");
public static bool IsGameComplete(byte[,] gameState, out byte winner)
bool hasEmptyCell = false;
for(int i = 0; i <= 2; i++)
for(int j = 0; j <= 2; j++)
for( int i = 0; i <= 2; i++ )
&& gameState[i,0] == gameState[i,1]
&& gameState[i,1] == gameState[i,2])
&& gameState[0, i] == gameState[1, i]
&& gameState[1, i] == gameState[2, i])
if ( gameState[1,1] == gameState[0,0]
&& gameState[1,1] == gameState[2,2])
if ( gameState[1,1] == gameState[0,2]
&& gameState[1,1] == gameState[2,0])
return !hasEmptyCell || winner > 0;
public static void PrintGameBoard(byte[,] gameState)
Console.WriteLine("=========================");
Console.WriteLine("| {0, 3} | {1, 3} | {2, 3} | | 7 | 8 | 9 |", GetXO(gameState[0,0]), GetXO(gameState[0,1]), GetXO(gameState[0,2]));
Console.WriteLine("|-------+-------+-------|");
Console.WriteLine("| {0, 3} | {1, 3} | {2, 3} | | 4 | 5 | 6 |", GetXO(gameState[1,0]), GetXO(gameState[1,1]), GetXO(gameState[1,2]));
Console.WriteLine("|-------+-------+-------|");
Console.WriteLine("| {0, 3} | {1, 3} | {2, 3} | | 1 | 2 | 3 |", GetXO(gameState[2,0]), GetXO(gameState[2,1]), GetXO(gameState[2,2]));
Console.WriteLine("=========================");
public static string GetXO( int value )
public static void GetNextTurn(byte[,] gameState, byte currentPiece, out byte row, out byte column)