using System; using System.Text; namespace TicTacToeCommandLine { class TicTacToe { enum GameValue { E, X, O}; enum Winner { NONE , X, O}; static Winner checkWinner(GameValue[] table) { //horizontal for (int j=0;j<3;++j) if ( table[3 * j] != GameValue.E && table[3 * j] == table[3 * j + 1] && table[3 * j+ 1] == table[3 * j + 2]) { if (table[3 * j] == GameValue.X) return Winner.X; else return Winner.O; } //vertical for (int i = 0; i < 3; ++i) if (table[i] != GameValue.E && table[i] == table[i + 3] && table[i + 3] == table[i + 6]) { if (table[3 * i] == GameValue.X) return Winner.X; else return Winner.O; } //diagonal if (table[0] != GameValue.E && table[0] == table[4] && table[4] == table[8]) { if (table[0] == GameValue.X) return Winner.X; else return Winner.O; } if (table[2] != GameValue.E && table[2] == table[4] && table[4] == table[6]) { if (table[2] == GameValue.X) return Winner.X; else return Winner.O; } return Winner.NONE; } static void showTable(GameValue[] table) { Console.WriteLine("---------------------"); for (int j = 0; j < 3 ; ++j) { Console.Write("I"); for (int i = 0; i < 3; ++i) { Console.Write("{0} I ", table[i + 3 * j].ToString()); } Console.WriteLine(""); Console.WriteLine("---------------------"); } } static void Main(string[] args) { GameValue[] table = new GameValue[9]; for (int i = 0; i < table.Length; ++i) table[i] = GameValue.E; uint plays = 0; int currentPlayer = 0; Winner state=Winner.NONE; for (; plays < 9; ) { showTable(table); Console.WriteLine("please enter a number (1-9): "); string k = Console.ReadLine(); try { Console.WriteLine("Entered: {0}", k); int index; try { index = Convert.ToInt32(k)-1; } catch (FormatException e) { Console.WriteLine("please enter a number!!!"); continue; } GameValue curr = table[index]; Console.WriteLine("Entered: {0}", index); if (curr != GameValue.E) { Console.WriteLine("This is already taken"); continue; } if (currentPlayer == 0) { table[index] = GameValue.O; } else { table[index] = GameValue.X; } if ((state=checkWinner(table)) != Winner.NONE) { break; } currentPlayer++; if (currentPlayer > 1) currentPlayer = 0; ++plays; } catch (IndexOutOfRangeException e) { Console.WriteLine("Please enter a number between 1 and 9"); } } if (state == Winner.O) { Console.WriteLine("Congratulations player 1"); } else if (state == Winner.X) { Console.WriteLine("Congratulations player 2"); } else { Console.WriteLine("DRAW!!!"); } showTable(table); Console.ReadLine(); } } }