Exemplo n.º 1
0
        public void Test5x5()
        {
            var estimator = new TicTacToeEstimator(5, 4);

            var state = new TicTacToeState(5, 4);

            state.SetCell(0, 4, Player.Maximizing);
            state.SetCell(1, 3, Player.Maximizing);
            state.SetCell(2, 2, Player.Maximizing);
            state.SetCell(3, 1, Player.Maximizing);

            bool isTerm;
            var  estimate = estimator.GetEstimate(state, out isTerm);

            Assert.IsTrue(isTerm, "it is terminate state");
            Assert.IsTrue(estimate.IsCloseTo(Estimate.MaxInf));
        }
Exemplo n.º 2
0
        public void DoesGameHaveWinner_IsFalse()
        {
            var state = new TicTacToeState
            {
                firstPlayer  = Guid.Empty,
                secondPlayer = Guid.Empty,
                board        = new List <PlayerMark>
                {
                    PlayerMark.Empty, PlayerMark.Empty, PlayerMark.Empty,
                    PlayerMark.X, PlayerMark.O, PlayerMark.X,
                    PlayerMark.Empty, PlayerMark.Empty, PlayerMark.Empty,
                }
            };
            var hasWinner = TicTacToeLogic.IsGameOver(state);

            Assert.False(hasWinner);
        }
Exemplo n.º 3
0
        static void startAlphaBetaDemo()
        {
            System.Console.WriteLine("ALPHA BETA DEMO\n");
            TicTacToeGame  game      = new TicTacToeGame();
            TicTacToeState currState = game.GetInitialState();
            IAdversarialSearch <TicTacToeState, XYLocation> search = AlphaBetaSearch <TicTacToeState, XYLocation, string>
                                                                     .createFor(game);

            while (!(game.IsTerminal(currState)))
            {
                System.Console.WriteLine(game.GetPlayer(currState) + "  playing ... ");
                XYLocation action = search.makeDecision(currState);
                currState = game.GetResult(currState, action);
                System.Console.WriteLine(currState);
            }
            System.Console.WriteLine("ALPHA BETA DEMO done");
        }
Exemplo n.º 4
0
    public void makeMove(int x, int y, int player)
    {
        if (game.board [x, y] == 0 && player == playerTurn && gameStarted && !game.winState)
        {
            TicTacToeState state = new TicTacToeState();
            state.x           = x;
            state.y           = y;
            game.board [x, y] = playerTurn + 1;
            ai.feedMove(state);
            playerTurn++;

            if (playerTurn == game.players.Length)
            {
                playerTurn = 0;
            }

            checkWin(game);
        }
    }
Exemplo n.º 5
0
        public static void DrawState(TicTacToeState state)
        {
            for (int y = 0; y < state.Size; y++)
            {
                if (y == 0)
                {
                    Console.WriteLine(new string('-', state.Size * 2 + 1));
                }

                for (int x = 0; x < state.Size; x++)
                {
                    if (x == 0)
                    {
                        Console.Write("|");
                    }

                    Player?cellState = state.GetCell(x, y);

                    if (cellState == Player.Maximizing)
                    {
                        Console.Write("x");
                    }
                    else if (cellState == Player.Minimizing)
                    {
                        Console.Write("o");
                    }
                    else
                    {
                        Console.Write(" ");
                    }

                    Console.Write("|");
                }

                Console.WriteLine();
                Console.WriteLine(new string('-', state.Size * 2 + 1));
            }

            Console.WriteLine();
        }
Exemplo n.º 6
0
        public static async Task UpdateCurrentGameState(TicTacToeState state, string playFabId, PlayFabApiSettings apiSettings, PlayFabAuthenticationContext authenticationContext)
        {
            var serializedNewGameState = PlayFabSimpleJson.SerializeObject(state);

            var request = new UpdateUserDataRequest()
            {
                PlayFabId = playFabId,
                Data      = new Dictionary <string, string>()
                {
                    { Constants.GAME_CURRENT_STATE_KEY, serializedNewGameState }
                }
            };

            var serverApi = new PlayFabServerInstanceAPI(apiSettings, authenticationContext);

            var result = await serverApi.UpdateUserDataAsync(request);

            if (result.Error != null)
            {
                throw new Exception($"An error occured while creating a new game state: {result.Error.GenerateErrorReport()}");
            }
        }
        public static async Task Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req,
            ILogger log)
        {
            var context = await FunctionContext <PlayFabIdRequest> .Create(req);

            var playFabId = context.FunctionArgument.PlayFabId;

            Settings.TrySetSecretKey(context.ApiSettings);
            Settings.TrySetCloudName(context.ApiSettings);

            var newCurrentGameState = new TicTacToeState()
            {
                Data = new int[9]
            };

            await GameStateUtil.UpdateCurrentGameState(
                newCurrentGameState,
                playFabId,
                context.ApiSettings,
                context.AuthenticationContext);
        }
Exemplo n.º 8
0
        public static async Task <TicTacToeState> GetCurrentGameState(string playFabId, PlayFabApiSettings apiSettings, PlayFabAuthenticationContext authenticationContext)
        {
            var request = new GetUserDataRequest()
            {
                PlayFabId = playFabId,
                Keys      = new List <string>()
                {
                    Constants.GAME_CURRENT_STATE_KEY
                }
            };

            var serverApi = new PlayFabServerInstanceAPI(apiSettings, authenticationContext);

            var result = await serverApi.GetUserDataAsync(request);

            if (result.Error != null)
            {
                throw new Exception($"An error occurred while fetching the current game state: Error: {result.Error.GenerateErrorReport()}");
            }

            var resultData = result.Result.Data;

            // Current state found
            if (resultData.Count > 0 && resultData.TryGetValue(Constants.GAME_CURRENT_STATE_KEY, out var currentGameStateRecord))
            {
                return(PlayFabSimpleJson.DeserializeObject <TicTacToeState>(currentGameStateRecord.Value));
            }
            // Current game record does not exist and so must be created
            else
            {
                var newState = new TicTacToeState()
                {
                    Data = new int[9]
                };
                await UpdateCurrentGameState(newState, playFabId, apiSettings, authenticationContext);

                return(newState);
            }
        }
Exemplo n.º 9
0
        public override bool MakeMove(Move move)
        {
            bool succesfulMove = false;

            if (GameBoard.Tiles[(int)move.DestinationTile.TileNum].State == TicTacToeState.Empty)
            {
                GameBoard.Tiles[(int)move.DestinationTile.TileNum].State = _currentPlayer;
                succesfulMove = true;
            }
            else
            {
                succesfulMove = false;
            }
            tilesPlaced += succesfulMove ? 1 : 0;

            /*if (CheckForWin())
             * {
             *  Console.WriteLine("player " + _currentPlayer + " wins.");
             * }
             */
            _currentPlayer = (_currentPlayer == TicTacToeState.O) ? TicTacToeState.X : TicTacToeState.O;
            return(succesfulMove);
        }
Exemplo n.º 10
0
        public static WinCheckResult Check(TicTacToeState state)
        {
            int[,] state2D = ArrayUtil.Make2DArray(state.Data, 3, 3);
            // For all but NONE occupant types, check to see if there is a winner in the game at the moment
            foreach (var occupantType in (OccupantType[])Enum.GetValues(typeof(OccupantType)))
            {
                if (occupantType == OccupantType.NONE)
                {
                    continue;
                }

                if (CheckRowWin(occupantType, state2D) ||
                    CheckColWin(occupantType, state2D) ||
                    CheckDiagWin(occupantType, state2D))
                {
                    return(new WinCheckResult
                    {
                        Winner = (GameWinnerType)occupantType
                    });
                }
            }

            // Check for a draw, otherwise game is not over yet: no winner
            if (CheckDraw(state2D))
            {
                return(new WinCheckResult
                {
                    Winner = GameWinnerType.DRAW
                });
            }

            return(new WinCheckResult
            {
                Winner = GameWinnerType.NONE
            });
        }
Exemplo n.º 11
0
        private static Result ValidateAction(TicTacToeState state, IAction action)
        {
            if (action is TicTacToeMove move)
            {
                if (state.IsTie || state.Winner != null)
                {
                    return(Result.Failed("The game is over"));
                }

                if (move.PlayerId != state.CurrentTurn)
                {
                    return(Result.Failed("It's not your turn"));
                }

                if (state.Board[move.X, move.Y] != 0)
                {
                    return(Result.Failed("Invalid move"));
                }

                return(Result.Success);
            }

            throw new Exception("Invalid action");
        }
Exemplo n.º 12
0
 public TicTacToeComputer(TicTacToeState state, short num, BST <GameState> tree)
 {
     playerState = state;
     stateTree   = tree;
     playerNum   = num;
 }
Exemplo n.º 13
0
 public Move GetMove(GameGrid grid)
 {
     var state = new TicTacToeState(PlayerSide, grid);
     return _search.RunMinimax(state, 10).ActionsToState.First();
 }
Exemplo n.º 14
0
        private TicTacToeState CheckForEndgame(TicTacToeState state)
        {
            var rows = Enumerable.Range(0, _size)
                       .Select(i => Enumerable.Range(0, _size).Select(j => state.Board[i, j]).ToList())
                       .ToList();

            var rowVictory = rows.FirstOrDefault(r =>
            {
                var firstValue = r[0];

                return(firstValue != 0 && r.All(v => v == firstValue));
            });

            if (rowVictory != null)
            {
                return(state with {
                    Winner = rowVictory[0]
                });
            }

            var columns = Enumerable.Range(0, _size)
                          .Select(i => Enumerable.Range(0, _size).Select(j => state.Board[j, i]).ToList())
                          .ToList();

            var columnVictory = columns.FirstOrDefault(r =>
            {
                var firstValue = r[0];

                return(firstValue != 0 && r.All(v => v == firstValue));
            });

            if (columnVictory != null)
            {
                return(state with {
                    Winner = columnVictory[0]
                });
            }

            var diagonalVictory = Enumerable.Range(0, _size).Select(i => state.Board[i, i]).All(v => v != 0 && v == state.Board[0, 0]);

            if (diagonalVictory)
            {
                return(state with {
                    Winner = state.Board[0, 0]
                });
            }

            var otherDiagonalVictory = Enumerable.Range(0, _size).Select(i => state.Board[i, _size - i - 1]).All(v => v != 0 && v == state.Board[0, 0]);

            if (otherDiagonalVictory)
            {
                return(state with {
                    Winner = state.Board[0, _size - 1]
                });
            }

            if (state.Board.Cast <int>().All(v => v != 0))
            {
                return(state with {
                    IsTie = true
                });
            }

            return(state);
        }
Exemplo n.º 15
0
 public TicTacToeUser(TicTacToeState state, short num)
 {
     playerState = state;
     playerNum   = num;
 }
Exemplo n.º 16
0
        public void OutputGame(Game currentGame, TicTacToePlayer playerX, TicTacToePlayer playerO, TicTacToeState state, short num)
        {
            BSTNode <GameState> currentNode = stateTree.Find(currentGame.GetStateId());

            Console.WriteLine("Player 1 (" + player1.PlayerState + ") Wins: " + player1Wins);
            Console.WriteLine("Player 2 (" + player2.PlayerState + ") Wins: " + player2Wins);
            Console.WriteLine("Draws: " + draws);
            if (currentNode != stateTree.NullNode)
            {
                GameState currentGameState = currentNode.Value;
                Console.WriteLine("Player " + playerX.PlayerNum + " win probability: " + currentGameState.WinProbability1 + "%");
                Console.WriteLine("Player " + playerO.PlayerNum + " win probability: " + currentGameState.WinProbability2 + "%");
            }
            Console.WriteLine(state + "(Player " + num + ")'s Move");
            Console.Write(currentGame.GameBoard.RenderAsString());
        }
Exemplo n.º 17
0
        public static bool IsGameTie(TicTacToeState state)
        {
            var isTie = IsBoardFull(state) && !DoesGameHaveWinner(state);

            return(isTie);
        }
Exemplo n.º 18
0
    public static List <TicTacToeState> checkWin(TicTacToeGameState state)
    {
        List <TicTacToeState> states = new List <TicTacToeState>();

        for (int player = 0; player < state.players.Length; player++)
        {
            bool win = false;
            for (int x = 0; x < state.board.GetLength(0); x++)
            {
                for (int y = 0; y < state.board.GetLength(1); y++)
                {
                    if (state.board [x, y] != player + 1)
                    {
                        win    = false;
                        states = new List <TicTacToeState>();
                        break;
                    }

                    TicTacToeState s = new TicTacToeState();
                    s.x = x;
                    s.y = y;
                    states.Add(s);
                    win = true;
                }

                if (win)
                {
                    state.winState = true;
                    state.players[player].winner = true;
                    return(states);
                }
            }

            for (int y = 0; y < state.board.GetLength(1); y++)
            {
                for (int x = 0; x < state.board.GetLength(0); x++)
                {
                    if (state.board [x, y] != player + 1)
                    {
                        win    = false;
                        states = new List <TicTacToeState>();
                        break;
                    }

                    TicTacToeState s = new TicTacToeState();
                    s.x = x;
                    s.y = y;
                    states.Add(s);
                    win = true;
                }

                if (win)
                {
                    state.winState = true;
                    state.players[player].winner = true;
                    return(states);
                }
            }

            for (int x = 0; x < state.board.GetLength(0) && x < state.board.GetLength(1); x++)
            {
                if (state.board [x, x] != player + 1)
                {
                    win    = false;
                    states = new List <TicTacToeState>();
                    break;
                }

                TicTacToeState s = new TicTacToeState();
                s.x = x;
                s.y = x;
                states.Add(s);
                win = true;
            }

            if (win)
            {
                state.winState = true;
                state.players[player].winner = true;
                return(states);
            }

            for (int x = state.board.GetLength(0) - 1; x >= 0; x--)
            {
                if (state.board [x, x] != player + 1)
                {
                    win    = false;
                    states = new List <TicTacToeState>();
                    break;
                }

                TicTacToeState s = new TicTacToeState();
                s.x = x;
                s.y = x;
                states.Add(s);
                win = true;
            }

            if (win)
            {
                state.winState = true;
                state.players[player].winner = true;
                return(states);
            }
        }

        return(new List <TicTacToeState>());
    }
Exemplo n.º 19
0
        private static MinimaxMove Minimax(TicTacToeState state, OccupantType player)
        {
            var emptyIndices = EmptyIndices(state);

            var winningResult = WinCheckUtil.Check(state);

            if (winningResult.Winner.Equals(GameWinnerType.PLAYER))
            {
                return(new MinimaxMove {
                    Score = -10
                });
            }
            else if (winningResult.Winner.Equals(GameWinnerType.AI))
            {
                return(new MinimaxMove {
                    Score = 10
                });
            }
            else if (emptyIndices.Count == 0)
            {
                return(new MinimaxMove {
                    Score = 0
                });
            }

            var moves = new List <MinimaxMove>();

            for (int i = 0; i < emptyIndices.Count; i++)
            {
                var move = new MinimaxMove
                {
                    Index = emptyIndices[i]
                };

                state.Data[emptyIndices[i]] = (int)player;

                var result = player.Equals(OccupantType.AI) ?
                             Minimax(state, OccupantType.PLAYER) :
                             Minimax(state, OccupantType.AI);
                move.Score = result.Score;

                state.Data[emptyIndices[i]] = (int)OccupantType.NONE;

                moves.Add(move);
            }

            int bestMove = -1;

            if (player.Equals(OccupantType.AI))
            {
                var bestScore = -10000;
                for (int i = 0; i < moves.Count; i++)
                {
                    if (moves[i].Score > bestScore)
                    {
                        bestScore = moves[i].Score;
                        bestMove  = i;
                    }
                }
            }
            else
            {
                var bestScore = 10000;
                for (int i = 0; i < moves.Count; i++)
                {
                    if (moves[i].Score < bestScore)
                    {
                        bestScore = moves[i].Score;
                        bestMove  = i;
                    }
                }
            }

            return(moves[bestMove]);
        }
Exemplo n.º 20
0
 public LearningPlayer(TicTacToeState state, short num, BST <GameState> tree) : base(state, num, tree)
 {
 }
Exemplo n.º 21
0
 public static WinState Winner(TicTacToeState state) => state.Winner;
Exemplo n.º 22
0
 public static PlayerTag CurrentPlayer(TicTacToeState state) => state.CurrentPlayer;
Exemplo n.º 23
0
        public static bool IsGameOver(TicTacToeState state)
        {
            bool gameOver = DoesGameHaveWinner(state) || IsBoardFull(state);

            return(gameOver);
        }
Exemplo n.º 24
0
 public void setUp()
 {
     game  = new TicTacToeGame();
     state = game.GetInitialState();
 }
Exemplo n.º 25
0
 public void Setup()
 {
     state = new TicTacToeState();
 }
Exemplo n.º 26
0
        public static bool IsBoardFull(TicTacToeState state)
        {
            var isFull = state.board.All(x => x != PlayerMark.Empty);

            return(isFull);
        }