Exemple #1
0
        public StepResultDto MakeStep(StepDto newStep)
        {
            var game = _dbContext.Set <Game>()
                       .Where(x => x.Id == newStep.GameId)
                       .Include(x => x.Steps)
                       .First();

            var tickTackToeGame = new TickTackToeGame(game.Steps);

            tickTackToeGame.MakeStep(newStep.Coordinates.X, newStep.Coordinates.Y, game.UserPlayerType);
            var winnerDto = tickTackToeGame.TryGetWinner();
            var step      = new Step()
            {
                GameId = game.Id,
                Player = game.UserPlayerType,
                X      = newStep.Coordinates.X,
                Y      = newStep.Coordinates.Y,
            };

            _dbContext.Add(step);

            CoordinatesDto newStepCoordinates = null;

            if (winnerDto.Winner == null && !winnerDto.IsDraw)
            {
                var botPlayerType = game.UserPlayerType == PlayerType.X ? PlayerType.O : PlayerType.X;

                newStepCoordinates = tickTackToeGame.MakeBotStep(botPlayerType);
                winnerDto          = tickTackToeGame.TryGetWinner();

                var botStep = new Step()
                {
                    GameId = game.Id,
                    Player = botPlayerType,
                    X      = newStepCoordinates.X,
                    Y      = newStepCoordinates.Y,
                };
                _dbContext.Add(botStep);
            }

            game.Winner     = winnerDto.Winner;
            game.IsFinished = winnerDto.Winner != null || winnerDto.IsDraw;


            _dbContext.SaveChanges();

            return(new StepResultDto
            {
                Winner = winnerDto.Winner,
                BotStep = newStepCoordinates,
                IsFinished = game.IsFinished
            });
        }