Ejemplo n.º 1
0
        private static string UpdateUi(TicTacToeBoard board)
        {
            board.Display();
            var userInput = Console.ReadLine();

            return(userInput);
        }
Ejemplo n.º 2
0
        public void MainMethod()
        {
            board = new TicTacToeBoard();
            Console.WriteLine("Hello! To play tic tac toe, when it is your turn, enter the index of where you want to play (0-8)");
            Console.Read();

            while (!board.IsFull() && !board.IsWinner(SquareType.X) && !board.IsWinner(SquareType.O))
            {
                DisplayBoardGrid();

                Console.WriteLine("It is {0} turn.", currentTurn);
                int move = promptForInt("Enter your index: ");
                if (board.IsLegalMove(move))
                    board.MakeMove(move, currentTurn);
                else
                {
                    Console.WriteLine("Illegal Move! Press enter!");
                    Console.Read();
                    continue;
                }
                // Swap the turn
                currentTurn = currentTurn == SquareType.X ? SquareType.O : SquareType.X;
            }

            DisplayBoardGrid();

            if (board.IsFull())
                Console.WriteLine("Tie! Board is full!");
            else if (board.IsWinner(SquareType.X))
                AccounceWinner(SquareType.X);
            else if (board.IsWinner(SquareType.O))
                AccounceWinner(SquareType.O);
            else
                Console.WriteLine("Something has gone wrong!");
        }
Ejemplo n.º 3
0
        public Game()
        {
            // initialize a new game board
            theBoard = new TicTacToeBoard();

            // choose the type of players
            this.InitPlayers(this.players);
        }
Ejemplo n.º 4
0
        /// <summary>Command line method used by a human player to select a move.</summary>
        /// <returns>Board index to move to.</returns>
        public static ushort PromptForMove(TicTacToeBoard board, Piece.PieceValue token)
        {
            ushort i = 0;

            do
            {
                Console.Write("Enter the location of your move: ");
                i = Convert.ToUInt16(Console.ReadLine());
            } while (i < 0 || i > 9);

            return(i);
        }
Ejemplo n.º 5
0
        public override ushort Move(TicTacToeBoard currentBoard)
        {
            ushort chosenMove = 0;

            do
            {
                // call the method used to determine the move
                chosenMove = this.moveMethod(currentBoard, this.Token);
            } while (currentBoard.At(chosenMove));

            return(chosenMove);
        }
Ejemplo n.º 6
0
 // Constructs board based on passed board
 public TicTacToeBoard(TicTacToeBoard otherBoard)
 {
     board = new int[3, 3];
     for (int i = 0; i < 3; i++)
     {
         for (int j = 0; j < 3; j++)
         {
             board[i, j] = otherBoard.GetBoard()[i, j];
         }
     }
         
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Plays the game.
        /// </summary>
        public void Play()
        {
            int  move;
            bool over          = false;
            Move currentPlayer = Move.X;
            var  board         = new TicTacToeBoard();

            // Print a greeting.
            Console.WriteLine("xox Play Tic-Tac-Toe! xox" + Newline);

            // Keep going until the game is deemed "over"
            while (!over)
            {
                // Print the board.
                Console.WriteLine(board.ToString());
                Console.WriteLine("Player 1 => X, Player 2 => O");

                // Ask the player to enter a square number
                Console.Write("Enter Square [player " + PrintMove(currentPlayer) + "]: ");
                var playersMove = Console.ReadLine();
                Console.Write(Newline);

                // Process player's move
                if (int.TryParse(playersMove, out move))
                {
                    try
                    {
                        // Attempt to make the move, then change players.
                        board.MakeMove(move, currentPlayer);
                        currentPlayer = FlipCurrentPlayer(currentPlayer);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message + Newline);
                    }
                }
                else
                {
                    // Just in case someone doesn't give us an int.
                    Console.WriteLine("Unable to parse your move, please try again." + Newline);
                }

                //  A little magic here. If the board has a winner set then we're done.
                if (board.Winner != null)
                {
                    this.PrintEndGame(board);
                    over = true;
                }
            }
        }
        /// <summary>
        /// Plays the game.
        /// </summary>
        public void Play()
        {
            int move;
            bool over = false;
            Move currentPlayer = Move.X;
            var board = new TicTacToeBoard();

            // Print a greeting.
            Console.WriteLine("xox Play Tic-Tac-Toe! xox" + Newline);

            // Keep going until the game is deemed "over"
            while (!over)
            {
                // Print the board.
                Console.WriteLine(board.ToString());
                Console.WriteLine("Player 1 => X, Player 2 => O");

                // Ask the player to enter a square number
                Console.Write("Enter Square [player " + PrintMove(currentPlayer) + "]: ");
                var playersMove = Console.ReadLine();
                Console.Write(Newline);

                // Process player's move
                if (int.TryParse(playersMove, out move))
                {
                    try
                    {
                        // Attempt to make the move, then change players.
                        board.MakeMove(move, currentPlayer);
                        currentPlayer = FlipCurrentPlayer(currentPlayer);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message + Newline);
                    }
                }
                else
                {
                    // Just in case someone doesn't give us an int.
                    Console.WriteLine("Unable to parse your move, please try again." + Newline);
                }

                //  A little magic here. If the board has a winner set then we're done.
                if (board.Winner != null)
                {
                    this.PrintEndGame(board);
                    over = true;
                }
            }
        }
Ejemplo n.º 9
0
        public override ushort Move(TicTacToeBoard currentBoard)
        {
            // computer's algorithm will modify the board so create a copy to work on
            // TicTacToeBoard tempBoard = new TicTacToeBoard(currentBoard);

            // call the method used to determine the move
            ushort chosenMove = this.moveMethod(currentBoard, this.Token);

            while (currentBoard.At(chosenMove))
            {
                chosenMove = this.moveMethod(currentBoard, this.Token);
            }

            return(chosenMove);
        }
Ejemplo n.º 10
0
 private static void GameFinished(GameState result, TicTacToeBoard board)
 {
     if (result == GameState.XWins)
     {
         Console.WriteLine("X you badass!!");
     }
     else if (result == GameState.OWins)
     {
         Console.WriteLine("O is dope!!!");
     }
     else
     {
         Console.WriteLine("This game is rigged!");
     }
 }
Ejemplo n.º 11
0
        public int Minimax(bool isMax, int depth)
        {
            if (TicTacToeBoard.IsGameOver())
            {
                return(TicTacToeBoard.EvaluateWinningScore(depth));
            }

            var Scores = new List <int>();

            var availableMoves = TicTacToeBoard.GetAvailablePositions();

            //Calculate MIN and MAX scores
            if (isMax)
            {
                foreach (var move in availableMoves)
                {
                    // Make a move from the available
                    // user made move, now compo makes
                    TicTacToeBoard.Board[move.Item1, move.Item2] = MaxPlayer;

                    // Add the score of the that board
                    Scores.Add(Minimax(!isMax, depth++));
                    TicTacToeBoard.Board[move.Item1, move.Item2] = TicTacToeBoard.Player.E;
                }

                int maxScore = Scores.Max();

                return(maxScore);
            }
            else
            {
                foreach (var move in availableMoves)
                {
                    // Make a move from the available
                    // user made move, now compo makes
                    TicTacToeBoard.Board[move.Item1, move.Item2] = MinPlayer;
                    // Add the score of the that board
                    Scores.Add(Minimax(!isMax, depth++));

                    TicTacToeBoard.Board[move.Item1, move.Item2] = TicTacToeBoard.Player.E;
                }

                int minScore = Scores.Min();

                return(minScore);
            }
        }
Ejemplo n.º 12
0
        public static void Main(string[] args)
        {
            /*1.Make board
             * 2.Play
             * 3.Check for winner
             * 4.Check spaces left (if zero then draw)
             * 5.Play again ...
             * 6.Clear board
             */

            var board = new TicTacToeBoard();
            var game  = new TicTacToeGame(board);

            Console.WriteLine("Please play modafuckkers!! q to quit");

            var userInput = UpdateUi(board);

            while (userInput != "q")
            {
                if (int.TryParse(userInput, out var position))
                {
                    try
                    {
                        var result = game.Play(position);
                        if (result != GameState.Continue)
                        {
                            GameFinished(result, board);

                            board.Clear();
                            Console.WriteLine("Please play modafuckkers!! q to quit");
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"{e.Message}");
                    }
                }
                else
                {
                    Console.WriteLine("Please enter a number from 1 to 9");
                }

                userInput = UpdateUi(board);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Prints the end game.
        /// </summary>
        /// <param name="board">
        /// The board to print.
        /// </param>
        private void PrintEndGame(TicTacToeBoard board)
        {
            switch (board.Winner.Value)
            {
            case Move.X:
            case Move.O:
                Console.WriteLine("Congratulations, we have a winner: " + PrintMove(board.Winner.Value) + "!" + Newline);
                break;

            case Move.Undefined:
                Console.WriteLine("And we have a tie!" + Newline);
                break;
            }

            Console.WriteLine(board.ToString() + Newline);
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
Ejemplo n.º 14
0
        protected static bool ImmediateWin(Piece inPiece, TicTacToeBoard inBoard, ref ushort bestMove)
        {
            for (ushort i = 0; i < inBoard.Length; ++i)
            {
                // create a clone of the current board
                TicTacToeBoard tempBoard = new TicTacToeBoard(inBoard);

                // place a piece on each sqaure in the new board
                tempBoard.Place(inPiece, i);

                // and see if it results in an immediate win
                if (tempBoard.Win(inPiece.Value))
                {
                    bestMove = i;
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 15
0
        protected static bool ImmediateBlock(Piece inPiece, TicTacToeBoard inBoard, ref ushort bestMove)
        {
            Piece p = (inPiece.Value == Piece.PieceValue.X) ? new Piece(Piece.PieceValue.X) : new Piece(Piece.PieceValue.O);

            for (ushort i = 0; i < inBoard.Length; ++i)
            {
                // create a clone of the current board
                TicTacToeBoard tempBoard = new TicTacToeBoard(inBoard);

                tempBoard.Place(p, i);

                if (tempBoard.Win(p.Value))
                {
                    bestMove = i;
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 16
0
        public static ushort MinMaxMove(TicTacToeBoard board, Piece.PieceValue token)
        {
            // computer always plays the center square if it is available
            if (!board.At(4))
            {
                return(4);
            }

            // computer's 2nd move should be a corner if computer went first
            // computer's 1st move should be a corner if the center is taken
            // really not the best strategy
            if ((board.Moves == 1 && board.At(4)) || board.Moves == 2)
            {
                return((TicTacToeBoard.Corners)[Computer.randNum.Next(0, TicTacToeBoard.Corners.Length - 1)]);
            }

            // start with recommended move
            ushort aMove = 4;

            // use MinMax strategy to find the next move
            MoveStrategy strategy = Computer.LookAhead(new Piece(token), new TicTacToeBoard(board), ref aMove);

            return(aMove);
        }
Ejemplo n.º 17
0
 private void CreateGameBoard()
 {
     gameBoard = new TicTacToeBoard();
 }
Ejemplo n.º 18
0
 public void TakeATurn(TicTacToeBoard board)
 {
     board.DisplayBoard();
     bool validMove = false;
     while (!validMove)
     {
         Console.WriteLine("Please make a move (1-9):");
         int move;
         if (Int32.TryParse(Console.ReadLine(), out move))
         {
             if (board.GetMove(move) == 0)
             {
                 board.MakeMove(move, 2);
                 validMove = true;
             }
             else
             {
                 Console.WriteLine("Invalid move. Please try again.");
             }
         }
         else
         {
             Console.WriteLine("Invalid syntax. Please try again.");
         }
     }
 }
Ejemplo n.º 19
0
        public void PlayAGame()
        {
            TicTacToeBot ai = new TicTacToeBot();
            TicTacToeBoard board = new TicTacToeBoard();
            Random rng = new Random();
            bool yourTurn;
            Console.WriteLine("Randomizing who starts...");
            if (rng.Next(2) == 0)
            {
                Console.WriteLine("You start!");
                yourTurn = true;
            }
            else
            {
                Console.WriteLine("AI starts.");
                yourTurn = false;
            }

            int winner = 0;
            bool draw = false;
            while (winner == 0 && !draw)
            {
                if (yourTurn)
                {
                    TakeATurn(board);
                }
                else
                {
                    board.MakeMove(ai.GetBestMove(board), 1);
                }
                yourTurn = !yourTurn;
                winner = board.CheckForWin();
                draw = board.CheckForDraw();
            }
            board.DisplayBoard();
            if (winner == 1)
            {
                Console.WriteLine("AI wins.");
            }
            else if (winner == 2)
            {
                Console.WriteLine("You win!");
            }
            else
            {
                Console.WriteLine("Draw game.");
            }
        }
Ejemplo n.º 20
0
 public double AlphaBeta(TicTacToeBoard oldBoard, double alpha, double beta, int player)
 {
     if (oldBoard.CheckForWin() != 0 || oldBoard.CheckForDraw())
     {
         return Score(oldBoard);
     }
     if (player == 1)
     {
         double val = -10000.0;
         for (int i = 1; i <= 9; i++)
         {
             if (oldBoard.GetMove(i) == 0)
             {
                 TicTacToeBoard newBoard = new TicTacToeBoard(oldBoard);
                 newBoard.MakeMove(i, player);
                 val = Math.Max(val, gamma * AlphaBeta(newBoard, alpha, beta, 2));
                 alpha = Math.Max(alpha, val);
                 if (beta <= alpha) break;
             }
         }
         return alpha;
     }
     else
     {
         double val = 10000.0;
         for (int i = 1; i <= 9; i++)
         {
             if (oldBoard.GetMove(i) == 0)
             {
                 TicTacToeBoard newBoard = new TicTacToeBoard(oldBoard);
                 newBoard.MakeMove(i, player);
                 val = Math.Min(val, gamma * AlphaBeta(newBoard, alpha, beta, 1));
                 beta = Math.Min(val, beta);
                 if (beta <= alpha) break;
             }
         }
         return beta;
     }
 }
Ejemplo n.º 21
0
 public int GetBestMove(TicTacToeBoard board)
 {
     double max = -100000.0;
     int bestMoveSoFar = 0;
     for (int i = 1; i <= 9; i++)
     {
         if (board.GetMove(i) == 0)
         {
             TicTacToeBoard testBoard = new TicTacToeBoard(board);
             testBoard.MakeMove(i, 1);
             double moveScore = AlphaBeta(testBoard, -10000.0, 10000.0, 2);
             if (moveScore > max)
             {
                 max = moveScore;
                 bestMoveSoFar = i;
             }
         }
     }
     return bestMoveSoFar;
 }
Ejemplo n.º 22
0
 public double Score(TicTacToeBoard board)
 {
     int winner = board.CheckForWin();
     if (winner == 1)
     {
         return 10.0;
     }
     else if (winner == 2)
     {
         return -10.0;
     }
     else
     {
         return 0.0;
     }
 }
        /// <summary>
        /// Prints the end game.
        /// </summary>
        /// <param name="board">
        /// The board to print.
        /// </param>
        private void PrintEndGame(TicTacToeBoard board)
        {
            switch(board.Winner.Value) {
                case Move.X:
                case Move.O:
                    Console.WriteLine("Congratulations, we have a winner: " + PrintMove(board.Winner.Value) + "!" + Newline);
                    break;
                case Move.Undefined:
                    Console.WriteLine("And we have a tie!" + Newline);
                    break;
            }

            Console.WriteLine(board.ToString() + Newline);
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
Ejemplo n.º 24
0
 /// <summary>Clone a TicTacToe board from another instance of a board.</summary>
 /// <param name="b">Board to create a deep copy of.</param>
 public TicTacToeBoard(TicTacToeBoard b) : base(b)
 {
 }
Ejemplo n.º 25
0
 /// <summary>Computer picks a board move randomly.</summary>
 /// <returns>Index of board location to move to.</returns>
 public static ushort RandomMove(TicTacToeBoard board, Piece.PieceValue token)
 {
     return(Convert.ToUInt16(Computer.randNum.Next(0, 8)));
 }
Ejemplo n.º 26
0
        protected static MoveStrategy LookAhead(Piece inPiece, TicTacToeBoard inBoard, ref ushort bestMove)
        {
            // unused dummy value to seend the algorithm
            ushort aDummy = 0;
            // temporary strategy
            MoveStrategy aResponse;
            // the strategy to return
            MoveStrategy outValue = (inPiece.Value == Piece.PieceValue.X) ? MoveStrategy.OWin - 1 : MoveStrategy.XWin + 1;

            // first check to see if the game is a draw
            if (inBoard.Full())
            {
                outValue = MoveStrategy.Draw;
            }
            // return any move that results in an immediate win
            else if (Computer.ImmediateWin(inPiece, inBoard, ref bestMove))
            {
                outValue = (inPiece.Value == Piece.PieceValue.X) ? MoveStrategy.XWin : MoveStrategy.OWin;
            }
            // return any move that will result in blocking the other player from an immediate win on his next turn
            else if (Computer.ImmediateBlock(inPiece, inBoard, ref bestMove))
            {
                outValue = (inPiece.Value == Piece.PieceValue.X) ? MoveStrategy.XBlock : MoveStrategy.OBlock;
            }
            // no immediate wins so look for a promising move
            else
            {
                for (ushort i = 0; i < inBoard.Length; ++i)
                {
                    if (!inBoard.At(i))
                    {
                        inBoard.Place(inPiece, i);

                        // swap pieces and go down a move
                        Piece aPiece = (inPiece.Value == Piece.PieceValue.X)  ? new Piece(Piece.PieceValue.O) : new Piece(Piece.PieceValue.X);

                        // call look ahead recursively with a copy of the board each time
                        aResponse = LookAhead(aPiece, new TicTacToeBoard(inBoard), ref aDummy);

                        // determine the best move
                        switch (inPiece.Value)
                        {
                        case Piece.PieceValue.X:
                            if (aResponse > outValue)
                            {
                                outValue = aResponse;
                                bestMove = i;
                            }
                            break;

                        case Piece.PieceValue.O:
                            if (aResponse < outValue)
                            {
                                outValue = aResponse;
                                bestMove = i;
                            }
                            break;

                        default:
                            break;
                        } // end switch
                    }     // end if
                }         // end for loop
            }             // end else

            // return the best move strategy
            return(outValue);
        }
Ejemplo n.º 27
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;
                }
            }
        }
Ejemplo n.º 28
0
 public GameBoard()
 {
     _ticTacToeBoard  = new TicTacToeBoard(3, 3, Symbol.Empty);
     CurrentGameBoard = _ticTacToeBoard.GameBoard;
 }