Example #1
0
        public void Play()
        {
            Console.WriteLine("Starting Tic-Tac-Toe game...");
            Console.WriteLine("Choose a position on the board");

            // The scores for each round

            // Hard coded
            MaxPlayer = TicTacToeBoard.Player.O;
            MinPlayer = TicTacToeBoard.Player.X;

            while (!TicTacToeBoard.IsFull())
            {
                var scores = new List <int>();

                string humanMove = Console.ReadLine();
                int    row       = Convert.ToInt32(humanMove.Split(',')[0]);
                int    column    = Convert.ToInt32(humanMove.Split(',')[1]);

                if (!TicTacToeBoard.IsValidCell(row, column) || !TicTacToeBoard.IsCellEmpty(row, column))
                {
                    throw new ArgumentOutOfRangeException("Invalid positions.");
                }

                Console.WriteLine("\n");
                TicTacToeBoard.Board[row, column] = TicTacToeBoard.Player.X;
                TicTacToeBoard.Print();

                Console.WriteLine("\n");
                var availableMoves = TicTacToeBoard.GetAvailablePositions();

                foreach (var currMove in availableMoves)
                {
                    TicTacToeBoard.Board[currMove.Item1, currMove.Item2] = MaxPlayer;

                    int minimaxScore = Minimax(false, 0);
                    scores.Add(minimaxScore);

                    TicTacToeBoard.Board[currMove.Item1, currMove.Item2] = TicTacToeBoard.Player.E;
                }
                Console.WriteLine();

                // User moved (min) -> Its computers move (should be max)
                // For each avaiable move, call minimax
                var index = scores.FindIndex(score => score == scores.Max());

                if (index != -1)
                {
                    var move = availableMoves[index];

                    TicTacToeBoard.Board[move.Item1, move.Item2] = TicTacToeBoard.Player.O;
                    TicTacToeBoard.Print();
                }

                string winner = TicTacToeBoard.HasWinner();

                if (winner == "X")
                {
                    Console.WriteLine("You win!");
                    break;
                }
                else if (winner == "O")
                {
                    Console.WriteLine("Computer wins!");
                    break;
                }
                else if (winner == "-")
                {
                    Console.WriteLine("It is a draw game!");
                    break;
                }
            }
        }